This repository was archived by the owner on Jan 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
214 lines (184 loc) · 5.04 KB
/
main.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Dinit is a mini init replacement useful for use inside Docker containers.
package main
import (
"flag"
"fmt"
"math"
"os"
"os/exec"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
"time"
)
var (
Version = "0.6.2" // Remove and just use git hash when building it?
timeout time.Duration
maxproc float64
start, stop string
primary, sock bool
version bool
procs = NewProcs()
prim = NewPrimary()
test = &Test{} // only for testing
lg = &Log{}
)
const testPid = 123
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: dinit (version %s) [OPTION...] -r CMD [OPTION..] [-r CMD [OPTION...]]...\n", Version)
fmt.Fprintln(os.Stderr, "Start CMDs by passing the environment.")
fmt.Fprintln(os.Stderr, "Distribute SIGHUP, SIGTERM and SIGINT to the processes.")
flag.PrintDefaults()
}
// -r CMD [OPTION...]
commands, flags := Args(os.Args)
os.Args = flags
flag.DurationVar(&timeout, "timeout", envDuration("$DINIT_TIMEOUT", 10*time.Second), "time in seconds between SIGTERM and SIGKILL (DINIT_TIMEOUT)")
flag.Float64Var(&maxproc, "maxproc", 0.0, "set GOMAXPROCS to runtime.NumCPU() * maxproc, when GOMAXPROCS already set use that")
flag.Float64Var(&maxproc, "core-fraction", 0.0, "set GOMAXPROCS to runtime.NumCPU() * core-fraction, when GOMAXPROCS already set use that")
flag.StringVar(&start, "start", envString("$DINIT_START", ""), "command to run during startup, non-zero exit status aborts dinit (DINIT_START)")
flag.StringVar(&stop, "stop", envString("$DINIT_STOP", ""), "command to run during teardown (DINIT_STOP)")
flag.BoolVar(&sock, "submit", false, "write -r CMD... to the unix socket "+socketName)
flag.BoolVar(&primary, "primary", false, "all processes are primary")
if len(commands) == 0 {
flag.Usage()
return
}
flag.Parse()
prim.SetAll(primary)
if !sock {
// If sending something over the socket, don't open it.
go socket(socketName)
defer os.Remove(socketName)
}
if maxproc > 0.0 {
if v := os.Getenv("GOMAXPROCS"); v != "" {
lg.Printf("GOMAXPROCS already set, using that value: %s", v)
} else {
numcpu := strconv.Itoa(int(math.Ceil(float64(runtime.NumCPU()) * maxproc)))
lg.Printf("using %s as GOMAXPROCS", numcpu)
os.Setenv("GOMAXPROCS", numcpu)
}
}
if start != "" {
startcmd := command(start)
if err := startcmd.Run(); err != nil {
lg.Fatalf("start command failed: %s", err)
}
}
if stop != "" {
stopcmd := command(stop)
defer stopcmd.Run()
}
if sock {
err := write(socketName, commands)
if err != nil {
lg.Fatalf("failed to write to unix socket: %s", err)
}
return
}
if os.Getpid() == 1 {
go reap()
}
run(commands, false)
wait(sock)
}
// run runs the commands as given on the command line. If noprimary is
// true none of the processes will be considered primary.
func run(commands []*exec.Cmd, fromsocket bool) {
for i, _ := range commands {
// Need to copy here, because otherwise the closure below will access
// to wrong command, when we run in a loop.
c := commands[i]
if err := c.Start(); err != nil {
lg.Printf("process failed to start: %v", err)
if !fromsocket {
procs.Cleanup(syscall.SIGINT)
return
}
continue
}
if i == len(commands)-1 && !fromsocket {
prim.Set(c.Process.Pid)
}
pid := c.Process.Pid
if test.Test() {
pid = testPid
}
lg.Printf("pid %d started: %v", pid, c.Args)
procs.Insert(c)
go func() {
err := c.Wait()
pid := c.Process.Pid
if test.Test() {
pid = testPid
}
switch err {
default:
_, ok := err.(*os.SyscallError)
if !ok {
lg.Printf("pid %d finished: %v with error: %v", pid, c.Args, err)
break
}
fallthrough
case nil:
lg.Printf("pid %d finished: %v", pid, c.Args)
}
procs.Remove(c)
if prim.All() || prim.Primary(c.Process.Pid) {
if prim.All() {
lg.Printf("all processes considered primary, signalling other processes")
} else {
lg.Printf("pid %d was primary, signalling other processes", pid)
}
procs.Cleanup(syscall.SIGINT)
}
}()
}
return
}
// wait waits for commands to finish.
func wait(sock bool) {
defer func() { lg.Printf("all processes exited, goodbye!") }()
if !sock {
defer os.Remove(socketName)
}
ints := make(chan os.Signal)
signal.Notify(ints, syscall.SIGINT, syscall.SIGTERM)
other := make(chan os.Signal)
signal.Notify(other, syscall.SIGHUP)
tick := time.Tick(100 * time.Millisecond) // 0.1 sec
for {
select {
case <-tick:
if procs.Len() == 0 {
return
}
case sig := <-other:
procs.Signal(sig)
case sig := <-ints:
procs.Cleanup(sig)
}
}
}
// command parses arg and returns an *exec.Cmd that is ready to be run.
// This is currently only used for the start and stop commands.
func command(arg string) *exec.Cmd {
args, err := ReadArgs(strings.NewReader(arg))
if err != nil {
lg.Fatalf("invalid command %q", arg)
}
if len(args) == 0 {
lg.Fatalf("invalid empty command")
}
for i, a := range args {
args[i] = os.ExpandEnv(a)
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd
}