server.garden privileged automation agent (mirror of https://git.sequentialread.com/forest/rootsystem)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

117 lines
2.5 KiB

package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
errors "git.sequentialread.com/forest/pkg-errors"
)
type AnsibleTaskResult struct {
Name string
Success bool
Skipped bool
Mode string
Role string
Changed bool
}
func main() {
arguments := os.Args[1:]
process := exec.Command("ansible-playbook", arguments...)
stdoutPipe, err := process.StdoutPipe()
if err != nil {
fmt.Fprint(os.Stderr, "can't connect stdout pipe to ansible-playbook process")
os.Exit(1)
}
stderrPipe, err := process.StderrPipe()
if err != nil {
fmt.Fprint(os.Stderr, "can't connect stderr pipe to ansible-playbook process")
os.Exit(1)
}
err = process.Start()
if err != nil {
err = errors.Wrapf(err, "can't ShellExec(ansible-playbook %s), process.Start() returned", strings.Join(arguments, " "))
os.Exit(1)
}
stdoutScanner := bufio.NewScanner(stdoutPipe)
stdoutScanner.Split(bufio.ScanLines)
stderrScanner := bufio.NewScanner(stderrPipe)
stderrScanner.Split(bufio.ScanLines)
_ = os.Remove("ansible.log")
_ = os.Remove("ansible-log.json")
ansibleTaskResults := []AnsibleTaskResult{}
writeLogLine := func(text string) error {
file, err := os.OpenFile("ansible.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer file.Close()
if _, err = file.WriteString(fmt.Sprintln(text)); err != nil {
return err
}
return nil
}
writeTaskResult := func(taskResult AnsibleTaskResult) error {
ansibleTaskResults = append(ansibleTaskResults, taskResult)
file, err := os.OpenFile("ansible-log.json", os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer file.Close()
jsonBytes, err := json.MarshalIndent(ansibleTaskResults, "", " ")
if err != nil {
return err
}
_, err = file.Write(jsonBytes)
if err != nil {
return err
}
return nil
}
go (func() {
for stdoutScanner.Scan() {
line := stdoutScanner.Text()
var taskResult AnsibleTaskResult
err := json.Unmarshal([]byte(line), &taskResult)
if err == nil && taskResult.Name != "" {
err = writeTaskResult(taskResult)
} else {
err = writeLogLine(line)
}
if err != nil {
panic(err)
}
}
})()
go (func() {
for stderrScanner.Scan() {
err := writeLogLine(stderrScanner.Text())
if err != nil {
panic(err)
}
}
})()
err = process.Wait()
if err != nil {
err = errors.Wrapf(err, "can't ShellExec(ansible-playbook %s), process.Wait() returned", strings.Join(arguments, " "))
}
os.Exit(process.ProcessState.ExitCode())
}