supervise.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
package main import ( "container/ring" "encoding/json" "errors" "fmt" "io" "log" "log/syslog" "net/http" "net/url" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "syscall" "time" ) // remoteSyslogError throttles printing error messages about remote // syslog. Since a remote syslog writer is created for stdout and stderr of each // supervised process, error messages during early boot spam the serial console // without limiting. When the value is 0, a log message can be printed. A // background goroutine resets the value to 0 once a second. var remoteSyslogError uint32 func init() { go func() { for range time.Tick(1 * time.Second) { atomic.StoreUint32(&remoteSyslogError, 0) } }() } type remoteSyslogWriter struct { raddr, tag string lines *lineRingBuffer syslogMu sync.Mutex syslog io.Writer } func (w *remoteSyslogWriter) establish() { for { sl, err := syslog.Dial("udp", w.raddr, syslog.LOG_INFO, w.tag) if err != nil { if atomic.SwapUint32(&remoteSyslogError, 1) == 0 { log.Printf("remote syslog: %v", err) } time.Sleep(1 * time.Second) continue } w.syslogMu.Lock() defer w.syslogMu.Unlock() // replay buffer in case any messages were sent before the connection // could be established (before the network is ready) for _, line := range w.lines.Lines() { sl.Write([]byte(line + "\n")) } // send all future writes to syslog w.syslog = sl return } } func (w *remoteSyslogWriter) Lines() []string { return w.lines.Lines() } func (w *remoteSyslogWriter) Stream() (<-chan string, func()) { return w.lines.Stream() } func (w *remoteSyslogWriter) Write(b []byte) (int, error) { w.lines.Write(b) w.syslogMu.Lock() defer w.syslogMu.Unlock() if w.syslog == nil { return len(b), nil } for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") { w.syslog.Write([]byte(line + "\n")) } return len(b), nil } type lineRingBuffer struct { sync.RWMutex remainder string r *ring.Ring streams map[chan string]struct{} } func newLineRingBuffer(size int) *lineRingBuffer { return &lineRingBuffer{ r: ring.New(size), streams: make(map[chan string]struct{}), } } func (lrb *lineRingBuffer) Write(b []byte) (int, error) { lrb.Lock() defer lrb.Unlock() text := lrb.remainder + string(b) for { idx := strings.Index(text, "\n") if idx == -1 { break } line := text[:idx] lrb.r.Value = line for stream := range lrb.streams { select { case stream <- line: default: // If receiver channel is blocking, skip. This means streams // will miss log lines if they are full. } } lrb.r = lrb.r.Next() text = text[idx+1:] } lrb.remainder = text return len(b), nil } func (lrb *lineRingBuffer) Lines() []string { lrb.RLock() defer lrb.RUnlock() lines := make([]string, 0, lrb.r.Len()) lrb.r.Do(func(x interface{}) { if x != nil { lines = append(lines, x.(string)) } }) return lines } // Stream generates a new channel which will stream any logged lines, including everything currently // in the ring buffer. Deregister the stream by calling the close function. func (lrb *lineRingBuffer) Stream() (<-chan string, func()) { lrb.Lock() defer lrb.Unlock() // Need a chan that has at least len(ring) entries in it, otherwise populating it with existing // contents of the ring will block forever. stream := make(chan string, 101) lrb.r.Do(func(x interface{}) { if x != nil { stream <- x.(string) } }) lrb.streams[stream] = struct{}{} return stream, func() { lrb.Lock() defer lrb.Unlock() delete(lrb.streams, stream) close(stream) } } type lineswriter interface { io.Writer Lines() []string Stream() (<-chan string, func()) } type supervisionMode int const ( superviseLoop supervisionMode = iota superviseOnce superviseDone ) type service struct { // config (never updated) ModuleInfo string // state stopped bool stoppedMu sync.RWMutex cmd *exec.Cmd cmdMu sync.Mutex Stdout lineswriter Stderr lineswriter started time.Time startedMu sync.RWMutex process *os.Process processMu sync.RWMutex diversionMu sync.Mutex diversion string supervisionMu sync.Mutex supervision supervisionMode waitForClock bool state *processState } func (s *service) setDiversion(d string) { s.diversionMu.Lock() defer s.diversionMu.Unlock() s.diversion = d } func (s *service) Diverted() string { s.diversionMu.Lock() defer s.diversionMu.Unlock() return s.diversion } func (s *service) Path() string { if d := s.Diverted(); d != "" { return d } return s.Cmd().Path } func (s *service) Cmd() *exec.Cmd { s.cmdMu.Lock() defer s.cmdMu.Unlock() return s.cmd } func (s *service) setCmd(cmd *exec.Cmd) { s.cmdMu.Lock() defer s.cmdMu.Unlock() s.cmd = cmd } func (s *service) Name() string { return s.Cmd().Args[0] } func (s *service) supervisionMode() supervisionMode { s.supervisionMu.Lock() defer s.supervisionMu.Unlock() return s.supervision } func (s *service) setSupervisionMode(mode supervisionMode) { s.supervisionMu.Lock() defer s.supervisionMu.Unlock() s.supervision = mode } func (s *service) Stopped() bool { s.stoppedMu.RLock() defer s.stoppedMu.RUnlock() return s.stopped } func (s *service) setStopped(val bool) { s.stoppedMu.Lock() defer s.stoppedMu.Unlock() s.stopped = val } func (s *service) Started() time.Time { s.startedMu.RLock() defer s.startedMu.RUnlock() return s.started } func (s *service) setStarted(t time.Time) { s.startedMu.Lock() defer s.startedMu.Unlock() s.started = t } func (s *service) Process() *os.Process { s.processMu.RLock() defer s.processMu.RUnlock() return s.process } func (s *service) Signal(signal syscall.Signal) error { s.processMu.RLock() defer s.processMu.RUnlock() if s.process != nil { // Use syscall.Kill instead of s.process.Signal since we want // to the send the signal to all process of the group (-pid) err := syscall.Kill(-s.process.Pid, signal) if errno, ok := err.(syscall.Errno); ok { if errno == syscall.ESRCH { return nil // no such process, nothing to signal } } return err } return nil // no process, nothing to signal } func (s *service) setProcess(p *os.Process) { s.processMu.Lock() defer s.processMu.Unlock() s.process = p } func (s *service) MarshalJSON() ([]byte, error) { pid := 0 if proc := s.Process(); proc != nil { pid = proc.Pid } return json.Marshal(&struct { Stopped bool StartTime time.Time Pid int Path string Args []string Diverted string }{ Stopped: s.Stopped(), StartTime: s.Started(), Pid: pid, Path: s.Cmd().Path, Args: s.Cmd().Args, Diverted: s.Diverted(), }) } func rssOfPid(pid int) int64 { statm, err := os.ReadFile(fmt.Sprintf("/proc/%d/statm", pid)) if err != nil { return 0 } parts := strings.Split(strings.TrimSpace(string(statm)), " ") if len(parts) < 2 { return 0 } rss, err := strconv.ParseInt(parts[1], 0, 64) if err != nil { return 0 } return rss * 4096 } func (s *service) RSS() int64 { if p := s.Process(); p != nil { return rssOfPid(s.Process().Pid) } return 0 } var syslogRaddr string func initRemoteSyslog() { b, err := os.ReadFile("/perm/remote_syslog/target") if err != nil { if !os.IsNotExist(err) { log.Print(err) } return } raddr := strings.TrimSpace(string(b)) log.Printf("sending process stdout/stderr to remote syslog %s", raddr) syslogRaddr = raddr } func newLogWriter(tag string) lineswriter { lb := newLineRingBuffer(100) if syslogRaddr == "" { return lb } wr := &remoteSyslogWriter{ raddr: syslogRaddr, tag: tag, lines: lb, } go wr.establish() return wr } func isDontSupervise(err error) bool { ee, ok := err.(*exec.ExitError) if !ok { return false } ws, ok := ee.Sys().(syscall.WaitStatus) if !ok { return false } return ws.ExitStatus() == 125 } func supervise(s *service) { if modInfo, err := readModuleInfo(s.Path()); err == nil { s.ModuleInfo = modInfo } else { log.Printf("cannot read module info from %s: %v", s.Cmd().Path, err) } attempt := 0 // Wait for clock to be updated via ntp for services // that need correct time. This can be enabled // by adding a settings file named waitforclock.txt under // waitforclock/<package> directory. if strings.HasPrefix(s.Cmd().Path, "/user/") && s.waitForClock { log.Print("gore: waiting for clock to be synced") WaitForClock() } for { if s.Stopped() { time.Sleep(1 * time.Second) continue } cmd := &exec.Cmd{ Path: s.Cmd().Path, Args: s.Cmd().Args, Env: s.Cmd().Env, Stdout: s.Stdout, Stderr: s.Stderr, SysProcAttr: &syscall.SysProcAttr{ // create a new process group for each service to make it easier to terminate all its // processes with a single signal. Setpgid: true, }, } if d := s.Diverted(); d != "" { cmd.Path = d args := make([]string, len(cmd.Args)) copy(args, cmd.Args) args[0] = d cmd.Args = args } if cmd.Env == nil { cmd.Env = os.Environ() // for older gokr-packer versions } if attempt == 0 { cmd.Env = append(cmd.Env, "GOKRAZY_FIRST_START=1") } // Designate a subdirectory under /perm/home as $HOME. // This mirrors what gore system daemons and // ported daemons would do, so setting $HOME // increases the chance that third-party daemons // just work. base := filepath.Base(s.Cmd().Path) homeDir := "gore/" + base cmd.Env = append(cmd.Env, "HOME="+homeDir) if err := os.MkdirAll(homeDir, 0700); err != nil { if errors.Is(err, syscall.EROFS) { log.Printf("gore: cannot create $HOME directory without writeable gore/ dir") } else { log.Fatalf("gore: creating $HOME: %s", err) } } else { // Process execution fails when cmd.Dir points to // a non-existant directory. cmd.Dir = homeDir } log.Printf("gore: attempt %d, starting %q", attempt, cmd.Args) s.setStarted(time.Now()) attempt++ pid := -1 if err := cmd.Start(); err != nil { if d := s.Diverted(); os.IsNotExist(err) && d != "" { log.Printf("gore: removing no longer existing diversion %q", d) s.setDiversion("") } log.Println("gore: " + err.Error()) } else { pid = cmd.Process.Pid } s.state.Set(Running) s.setProcess(cmd.Process) err := cmd.Wait() if err != nil { if isDontSupervise(err) { log.Println("gore: process should not be supervised, stopping") s.setStopped(true) } log.Println("gore: " + err.Error()) } else { log.Printf("gore: exited successfully, stopping") s.setStopped(true) } if s.supervisionMode() == superviseOnce { s.setSupervisionMode(superviseDone) if !s.Stopped() { log.Println("gore: running process only once, stopping") s.setStopped(true) } } for { if pid <= 0 { // Sanity check pid value. // Sending 0 for pid in Wait4 has special meaning, which we don't want. break } // Wait4 return the pid of a process that exited, // or -1 if there are no processes to be waited on (or error). wpid, _ := syscall.Wait4(-pid, nil, 0, nil) if wpid == -1 { break } } s.state.Set(Stopped) time.Sleep(1 * time.Second) } } var services struct { sync.Mutex S []*service } // signalSupervisedServices sends a given signal to all non-stopped processes. // It returns the corresponding processState to allow waiting for a given state. func signalSupervisedServices(signal syscall.Signal) []*processState { services.Lock() defer services.Unlock() states := make([]*processState, 0, len(services.S)) for _, s := range services.S { // s.Stopped() only checks the "stopped" flag of the service (if it shouldn't restart). // We check the actual state as well to be sure to re-send a signal if we are already // in the "Stopping" state. if s.Stopped() && s.state.Get() == Stopped { continue } // NOTE: Stopping can be inaccurate if the process exited after the check above. // In that case, `state.Set(Stopping)` will be ignored - see `processState.Set()`. s.state.Set(Stopping) s.setStopped(true) s.Signal(signal) states = append(states, s.state) } return states } // killSupervisedServices is called before rebooting when upgrading, allowing // processes to terminate in an orderly fashion. func killSupervisedServices(signalDelay time.Duration) { log.Println("sending sigterm to all services") termStates := signalSupervisedServices(syscall.SIGTERM) termDone := make(chan struct{}) go func() { for _, s := range termStates { s.WaitTill(Stopped) } close(termDone) }() select { case <-termDone: log.Println("all services shut down") return case <-time.After(signalDelay): } log.Println("some services did not stop, send sigkill") killStates := signalSupervisedServices(syscall.SIGKILL) killDone := make(chan struct{}) go func() { for _, s := range killStates { s.WaitTill(Stopped) } close(killDone) }() select { case <-killDone: log.Println("all services shut down") return case <-time.After(signalDelay): } log.Println("some services did not stop after sigkill") } func findSvc(path string) *service { services.Lock() defer services.Unlock() for _, s := range services.S { if s.Cmd().Path == path { return s } } return nil } func restart(s *service, signal syscall.Signal) error { if s.Stopped() { s.setStopped(false) // start process in next supervise iteration return nil } return s.Signal(signal) // kill to restart } func stop(s *service, signal syscall.Signal) error { if s.Stopped() { return nil // nothing to do } s.setStopped(true) return s.Signal(signal) } func stopstartHandler(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "expected a POST request", http.StatusBadRequest) return } cookieToken := xsrfTokenFromCookies(r.Cookies()) if cookieToken == 0 { http.Error(w, "XSRF cookie missing", http.StatusBadRequest) return } i, err := strconv.ParseInt(r.FormValue("xsrftoken"), 0, 32) if err != nil { http.Error(w, fmt.Sprintf("parsing XSRF token form value: %v", err), http.StatusBadRequest) return } if formToken := int32(i); cookieToken != formToken { http.Error(w, "XSRF token mismatch", http.StatusForbidden) return } signal := syscall.SIGTERM if r.FormValue("signal") == "kill" { signal = syscall.SIGKILL } path := r.FormValue("path") s := findSvc(path) if s == nil { http.Error(w, "no such service", http.StatusNotFound) return } if r.URL.Path == "/restart" { if r.FormValue("supervise") == "once" { s.setSupervisionMode(superviseOnce) } else { s.setSupervisionMode(superviseLoop) } err = restart(s, signal) } else { err = stop(s, signal) } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // StatusSeeOther will result in a GET request for the // redirect location u, _ := url.Parse("/status") u.RawQuery = url.Values{ "path": []string{path}, }.Encode() http.Redirect(w, r, u.String(), http.StatusSeeOther) } func superviseServices(svc []*service) { services.Lock() services.S = svc defer services.Unlock() for _, s := range services.S { fmt.Println(s) go supervise(s) } http.HandleFunc("POST /stop", stopstartHandler) http.HandleFunc("POST /restart", stopstartHandler) } func WaitForClock() { epochPlus1Year := time.Unix(60*60*24*365, 0) for { if time.Now().After(epochPlus1Year) { return } // Sleeps for 1 real second, regardless of wall-clock time. // See https://github.com/golang/proposal/blob/master/design/12914-monotonic.md time.Sleep(1 * time.Second) } }