1 // MsgSyncReq: run commands on the remote host
3 // Copyright (C) 2021 Simon Ruderich
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
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.
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/>.
26 "ruderich.org/simon/safcm"
27 "ruderich.org/simon/safcm/cmd/safcm-remote/run"
30 func (s *Sync) syncCommands() error {
31 // Run triggered commands first
32 for _, path := range s.triggers {
33 for _, x := range s.req.Files[path].TriggerCommands {
34 err := s.syncCommand(x, path)
40 // Regular commands afterwards so they can react on triggers if
42 for _, x := range s.req.Commands {
43 err := s.syncCommand(x, "")
51 func (s *Sync) syncCommand(command string, trigger string) error {
52 s.resp.CommandChanges = append(s.resp.CommandChanges,
60 change := &s.resp.CommandChanges[len(s.resp.CommandChanges)-1]
62 cmd := exec.Command("/bin/sh", "-c", command)
63 cmd.Env = safcmEnviroment(s.req.Groups)
64 // Cannot use cmd.CombinedOutputCmd() because we need another log
65 // level (here the command is the actual change and not a side effect)
66 // and different error handling.
67 s.log.Verbosef("commands: running %s", run.QuoteForDebug(cmd))
68 out, err := s.cmd.Runner.CombinedOutput(cmd)
70 s.log.Debug2f("commands: command output:\n%s", out)
72 change.Output = string(out)
74 change.Error = err.Error()
75 return fmt.Errorf("%q failed: %v", command, err)
81 func safcmEnviroment(groups []string) []string {
83 // Provide additional environment variables so commands can check
86 fmt.Sprintf("SAFCM_GROUPS=%s", strings.Join(groups, " ")))
87 for _, x := range groups {
88 env = append(env, fmt.Sprintf("SAFCM_GROUP_%s=%s", x, x))