github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/overlord/configstate/configcore/powerbtn.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2017 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package configcore 21 22 import ( 23 "fmt" 24 "os" 25 "path/filepath" 26 27 "github.com/snapcore/snapd/dirs" 28 "github.com/snapcore/snapd/osutil" 29 "github.com/snapcore/snapd/overlord/configstate/config" 30 ) 31 32 func init() { 33 supportedConfigurations["core.system.power-key-action"] = true 34 } 35 36 func powerBtnCfg(opts *fsOnlyContext) string { 37 rootDir := dirs.GlobalRootDir 38 if opts != nil { 39 rootDir = opts.RootDir 40 } 41 return filepath.Join(rootDir, "/etc/systemd/logind.conf.d/00-snap-core.conf") 42 } 43 44 // switchHandlePowerKey changes the behavior when the power key is pressed 45 func switchHandlePowerKey(action string, opts *fsOnlyContext) error { 46 validActions := map[string]bool{ 47 "ignore": true, 48 "poweroff": true, 49 "reboot": true, 50 "halt": true, 51 "kexec": true, 52 "suspend": true, 53 "hibernate": true, 54 "hybrid-sleep": true, 55 "lock": true, 56 } 57 58 cfgDir := filepath.Dir(powerBtnCfg(opts)) 59 if !osutil.IsDirectory(cfgDir) { 60 if err := os.MkdirAll(cfgDir, 0755); err != nil { 61 return err 62 } 63 } 64 if !validActions[action] { 65 return fmt.Errorf("invalid action %q supplied for system.power-key-action option", action) 66 } 67 68 content := fmt.Sprintf(`[Login] 69 HandlePowerKey=%s 70 `, action) 71 return osutil.AtomicWriteFile(powerBtnCfg(opts), []byte(content), 0644, 0) 72 } 73 74 func handlePowerButtonConfiguration(tr config.ConfGetter, opts *fsOnlyContext) error { 75 output, err := coreCfg(tr, "system.power-key-action") 76 if err != nil { 77 return err 78 } 79 if output == "" { 80 if err := os.Remove(powerBtnCfg(opts)); err != nil && !os.IsNotExist(err) { 81 return err 82 } 83 84 } else { 85 if err := switchHandlePowerKey(output, opts); err != nil { 86 return err 87 } 88 } 89 return nil 90 }