restic-scheduler/shell.go

75 lines
1.5 KiB
Go
Raw Normal View History

2022-02-23 00:39:01 +00:00
package main
import (
"fmt"
"log"
"os"
"os/exec"
"strings"
)
var (
loggerFlags = log.LstdFlags | log.Lmsgprefix
loggers = map[string]*log.Logger{}
)
func GetLogger(name string) *log.Logger {
if logger, ok := loggers[name]; ok {
return logger
}
logger := log.New(os.Stderr, name+":", loggerFlags)
loggers[name] = logger
return logger
}
func GetChildLogger(parent *log.Logger, name string) *log.Logger {
childName := fmt.Sprintf("%s%s", parent.Prefix(), name)
return GetLogger(childName)
}
type CapturedLogWriter struct {
Lines []string
2022-02-23 00:39:01 +00:00
logger *log.Logger
}
func NewCapturedLogWriter(logger *log.Logger) *CapturedLogWriter {
return &CapturedLogWriter{Lines: []string{}, logger: logger}
2022-02-23 00:39:01 +00:00
}
func (w *CapturedLogWriter) Write(content []byte) (n int, err error) {
2022-02-23 00:55:41 +00:00
message := string(content)
2022-02-23 00:39:01 +00:00
for _, line := range strings.Split(message, "\n") {
w.Lines = append(w.Lines, line)
2022-02-23 00:39:01 +00:00
w.logger.Printf(" %s", line)
}
2022-02-23 00:55:41 +00:00
return len(content), nil
2022-02-23 00:39:01 +00:00
}
func RunShell(script string, cwd string, env map[string]string, logger *log.Logger) error {
2022-02-23 00:55:41 +00:00
cmd := exec.Command("sh", "-c", strings.TrimSpace(script)) // nolint:gosec
2022-02-23 00:39:01 +00:00
// Make both stderr and stdout go to logger
cmd.Stdout = NewCapturedLogWriter(logger)
2022-02-23 00:39:01 +00:00
cmd.Stderr = cmd.Stdout
// Set working directory
cmd.Dir = cwd
// Convert env to list if values provided
if len(env) > 0 {
envList := os.Environ()
2022-02-23 22:13:00 +00:00
envList = append(envList, EnvMapToList(env)...)
2022-02-23 00:39:01 +00:00
cmd.Env = envList
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("shell execution failed: %w", err)
}
return nil
}