...
1 package containers
2
3 import (
4 "context"
5 "fmt"
6 "os/exec"
7 "strings"
8 "time"
9
10 syscall "golang.org/x/sys/unix"
11
12 "edge-infra.dev/pkg/sds/devices/logger"
13 )
14
15 const (
16
17
18 timeout = time.Minute * 10
19 )
20
21 type ExecFn func(ctx context.Context, ctrName, rootPath, scriptPath string, envVars map[string]string)
22
23
24 func NewExecFn(ctx context.Context, ctrName, rootPath, scriptPath string, envVars map[string]string) {
25 log := logger.FromContext(ctx)
26 logArgs := []any{"path", scriptPath, "container", ctrName}
27 log.Debug("triggering script execution in container", logArgs...)
28 go func() {
29 ctx, cancelFn := context.WithTimeout(ctx, timeout)
30 defer cancelFn()
31 executeCommand(ctx, []string{scriptPath}, []string{}, rootPath, envVars)
32 }()
33 }
34
35
36
37 func executeCommand(ctx context.Context, cmd, args []string, rootPath string, envVars map[string]string) {
38 log := logger.FromContext(ctx)
39 commands := strings.Join(cmd, " ")
40 execCmd := exec.CommandContext(ctx, commands, args...)
41 execCmd.Dir = "/"
42 execCmd.SysProcAttr = &syscall.SysProcAttr{Chroot: rootPath}
43 for k, v := range envVars {
44 execCmd.Env = append(execCmd.Env, fmt.Sprintf("%s=%s", k, v))
45 }
46 output, err := execCmd.CombinedOutput()
47 log.Debug("running command from device rule", "error", err, "output", string(output))
48 }
49
View as plain text