Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(#2116) Support disown in exec watcher #2117

Merged
merged 1 commit into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ clone_folder: c:\gopath\src\github.com\choria-io\go-choria

environment:
GOPATH: c:\gopath
GOVERSION: "1.20"
GOVERSION: "1.21.0"
MCOLLECTIVE_CERTNAME: rip.mcollective
RUBY_VERSION: 24
CGO_ENABLED: 0

init:
- git config --global core.autocrlf input

stack: go 1.18
stack: go 1.21

install:
# Install the specific Go version.
Expand Down
27 changes: 24 additions & 3 deletions aagent/watchers/execwatcher/exec.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) 2019-2022, R.I. Pienaar and the Choria Project contributors
// Copyright (c) 2019-2024, R.I. Pienaar and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0

Expand Down Expand Up @@ -49,6 +49,7 @@
OutputAsData bool `mapstructure:"parse_as_data"`
SuppressSuccessAnnounce bool `mapstructure:"suppress_success_announce"`
GatherInitialState bool `mapstructure:"gather_initial_state"`
Disown bool `mapstructure:"disown"`
Timeout time.Duration
}

Expand Down Expand Up @@ -240,103 +241,123 @@
return s
}

func (w *Watcher) watch(ctx context.Context) (state State, err error) {
if !w.ShouldWatch() {
return Skipped, nil
}

if w.properties.Governor != "" {
fin, err := w.EnterGovernor(ctx, w.properties.Governor, w.properties.GovernorTimeout)
if err != nil {
w.Errorf("Cannot enter Governor %s: %s", w.properties.Governor, err)
return Error, err
}
defer fin()
}

start := time.Now()
defer func() {
w.mu.Lock()
w.previousRunTime = time.Since(start)
w.mu.Unlock()
}()

w.Infof("Running %s", w.properties.Command)

timeoutCtx, cancel := context.WithTimeout(ctx, w.properties.Timeout)
defer cancel()

parsedCommand, err := w.ProcessTemplate(w.properties.Command)
if err != nil {
return Error, fmt.Errorf("could not process command template: %s", err)
}

splitcmd, err := shlex.Split(parsedCommand)
if err != nil {
w.Errorf("Exec watcher %s failed: %s", w.properties.Command, err)
return Error, err
}

if len(splitcmd) == 0 {
w.Errorf("Invalid command %q", w.properties.Command)
return Error, err
}

var args []string
if len(splitcmd) > 1 {
args = splitcmd[1:]
}

df, err := w.DataCopyFile()
if err != nil {
w.Errorf("Could not get a copy of the data into a temporary file, skipping execution: %s", err)
return Error, err
}
defer os.Remove(df)

ff, err := w.FactsFile()
if err != nil {
w.Errorf("Could not expose machine facts, skipping execution: %s", err)
return Error, err
}
defer os.Remove(ff)

cmd := exec.CommandContext(timeoutCtx, splitcmd[0], args...)
var cmd *exec.Cmd
if w.properties.Disown {
cmd = exec.Command(splitcmd[0], args...)
} else {
cmd = exec.CommandContext(timeoutCtx, splitcmd[0], args...)
}
cmd.Dir = w.machine.Directory()

cmd.Env = append(cmd.Env, fmt.Sprintf("MACHINE_WATCHER_NAME=%s", w.name))
cmd.Env = append(cmd.Env, fmt.Sprintf("MACHINE_NAME=%s", w.machine.Name()))
cmd.Env = append(cmd.Env, fmt.Sprintf("PATH=%s%s%s", os.Getenv("PATH"), string(os.PathListSeparator), w.machine.Directory()))
cmd.Env = append(cmd.Env, fmt.Sprintf("WATCHER_DATA=%s", df))
cmd.Env = append(cmd.Env, fmt.Sprintf("WATCHER_FACTS=%s", ff))

for _, e := range w.properties.Environment {
es, err := w.ProcessTemplate(e)
if err != nil {
return Error, fmt.Errorf("could not process environment template: %s", err)
}
cmd.Env = append(cmd.Env, es)
}

output, err := cmd.CombinedOutput()
var output []byte

if w.properties.Disown {
w.Infof("Running command disowned from parent")
err = disown(cmd)
if err != nil {
return Error, fmt.Errorf("could not disown process: %w", err)
}
err = cmd.Start()
if err == nil {
go func() { cmd.Wait() }()
}
} else {
output, err = cmd.CombinedOutput()
}

if err != nil {
w.Errorf("Exec watcher %s failed: %s", w.properties.Command, err)
return Error, err
}

w.Debugf("Output from %s: %s", w.properties.Command, output)

if w.properties.OutputAsData {
err = w.setOutputAsData(output)
if err != nil {
w.Errorf("Could not save output data: %s", err)
return Error, err
}
}

return Success, nil
}

Check notice on line 360 in aagent/watchers/execwatcher/exec.go

View check run for this annotation

codefactor.io / CodeFactor

aagent/watchers/execwatcher/exec.go#L244-L360

Complex Method
func (w *Watcher) setOutputAsData(output []byte) error {
dat := map[string]string{}
err := json.Unmarshal(output, &dat)
Expand Down
21 changes: 21 additions & 0 deletions aagent/watchers/execwatcher/exec_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) 2024, R.I. Pienaar and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0

//go:build !windows

package execwatcher

import (
"os/exec"
"syscall"
)

func disown(cmd *exec.Cmd) error {
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Pgid: 0,
}

return nil
}
14 changes: 14 additions & 0 deletions aagent/watchers/execwatcher/exec_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) 2024, R.I. Pienaar and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0

package execwatcher

import (
"fmt"
"os/exec"
)

func disown(cmd *exec.Cmd) error {
return fmt.Errorf("disown is not supported on windows")
}
Loading