-
Notifications
You must be signed in to change notification settings - Fork 148
/
cmd_linux.go
58 lines (50 loc) · 1.41 KB
/
cmd_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
//go:build linux
// +build linux
package process
import (
"context"
"fmt"
"math"
"os"
"os/exec"
"path/filepath"
"syscall"
)
func getCmd(ctx context.Context, path string, env []string, uid, gid int, arg ...string) (*exec.Cmd, error) {
var cmd *exec.Cmd
if ctx == nil {
cmd = exec.Command(path, arg...)
} else {
cmd = exec.CommandContext(ctx, path, arg...)
}
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, env...)
cmd.Dir = filepath.Dir(path)
if isInt32(uid) && isInt32(gid) {
cmd.SysProcAttr = &syscall.SysProcAttr{
// on shutdown all sub-processes are sent SIGTERM, in the case that the Agent dies or is -9 killed
// then also kill the children (only supported on linux)
Pdeathsig: syscall.SIGKILL,
Credential: &syscall.Credential{
Uid: uint32(uid),
Gid: uint32(gid),
NoSetGroups: true,
},
}
} else {
return nil, fmt.Errorf("invalid uid: '%d' or gid: '%d'", uid, gid)
}
return cmd, nil
}
func isInt32(val int) bool {
return val >= 0 && val <= math.MaxInt32
}
func killCmd(proc *os.Process) error {
return proc.Kill()
}
func terminateCmd(proc *os.Process) error {
return proc.Signal(syscall.SIGTERM)
}