-
Notifications
You must be signed in to change notification settings - Fork 0
/
proc.go
128 lines (106 loc) · 1.96 KB
/
proc.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package proc
import (
"log/slog"
"math/rand"
"os"
"os/exec"
"syscall"
"time"
)
type RestartPolicy int
const (
RestartAlways RestartPolicy = iota
RestartOnFailure
RestartNever
)
type ExecUserType int
const (
UserRestricted ExecUserType = iota
UserPrivileged
)
type Proc struct {
execPath string
args []string
restart RestartPolicy
restartDelay *time.Duration
userType ExecUserType
}
type Option func(p *Proc)
func Args(args ...string) Option {
return func(p *Proc) {
p.args = args
}
}
func Restart(restart RestartPolicy) Option {
return func(p *Proc) {
p.restart = restart
}
}
func RestartDelay(d time.Duration) Option {
return func(p *Proc) {
p.restartDelay = &d
}
}
func RestartRandomDelay() Option {
return func(p *Proc) {
p.restartDelay = nil
}
}
func UserType(userType ExecUserType) Option {
return func(p *Proc) {
p.userType = userType
}
}
func NewProc(execPath string, options ...Option) Proc {
proc := Proc{
execPath: execPath,
}
for _, opt := range options {
opt(&proc)
}
return proc
}
func (p Proc) waitRestartDelay() {
if p.restartDelay == nil {
time.Sleep(time.Duration(rand.Intn(10)) * time.Second)
} else {
time.Sleep(*p.restartDelay)
}
}
func (p Proc) Start() {
L:
for {
cmd := exec.Command(p.execPath, p.args...)
cmd.Dir = "/"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if p.userType == UserPrivileged {
// Do nothing
} else if p.userType == UserRestricted {
cmd.SysProcAttr = &syscall.SysProcAttr{
Credential: &syscall.Credential{
Uid: 1000,
Gid: 1000,
},
}
}
failure := false
if err := cmd.Run(); err != nil {
slog.Error("Command failed", slog.Any("error", err), slog.String("executable", p.execPath))
failure = true
}
switch p.restart {
case RestartAlways:
p.waitRestartDelay()
continue L
case RestartOnFailure:
if failure {
p.waitRestartDelay()
continue L
}
break L
case RestartNever:
break L
}
}
}