blob: ea8a4d0e46749891077454d5f6d3bb6580f5b4b4 [file] [log] [blame]
Serge Bazanski9c09c4e2020-03-24 13:58:01 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package supervisor
18
19import (
20 "context"
21 "errors"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010022 "fmt"
23 "runtime/debug"
Serge Bazanskiec19b602022-03-09 20:41:31 +010024 "sort"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010025 "time"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010026)
27
Serge Bazanski216fe7b2021-05-21 18:36:16 +020028// The processor maintains runnable goroutines - ie., when requested will start
29// one, and then once it exists it will record the result and act accordingly.
30// It is also responsible for detecting and acting upon supervision subtrees
31// that need to be restarted after death (via a 'GC' process)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010032
Serge Bazanski216fe7b2021-05-21 18:36:16 +020033// processorRequest is a request for the processor. Only one of the fields can
34// be set.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010035type processorRequest struct {
Serge Bazanskiac6b6442020-05-06 19:13:43 +020036 schedule *processorRequestSchedule
37 died *processorRequestDied
38 waitSettled *processorRequestWaitSettled
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010039}
40
41// processorRequestSchedule requests that a given node's runnable be started.
42type processorRequestSchedule struct {
43 dn string
44}
45
Serge Bazanski216fe7b2021-05-21 18:36:16 +020046// processorRequestDied is a signal from a runnable goroutine that the runnable
47// has died.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010048type processorRequestDied struct {
49 dn string
50 err error
51}
52
Serge Bazanskiac6b6442020-05-06 19:13:43 +020053type processorRequestWaitSettled struct {
54 waiter chan struct{}
55}
56
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010057// processor is the main processing loop.
58func (s *supervisor) processor(ctx context.Context) {
59 s.ilogger.Info("supervisor processor started")
60
Serge Bazanskiac6b6442020-05-06 19:13:43 +020061 // Waiters waiting for the GC to be settled.
62 var waiters []chan struct{}
63
Serge Bazanski216fe7b2021-05-21 18:36:16 +020064 // The GC will run every millisecond if needed. Any time the processor
65 // requests a change in the supervision tree (ie a death or a new runnable)
66 // it will mark the state as dirty and run the GC on the next millisecond
67 // cycle.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010068 gc := time.NewTicker(1 * time.Millisecond)
69 defer gc.Stop()
70 clean := true
71
Serge Bazanskiac6b6442020-05-06 19:13:43 +020072 // How long has the GC been clean. This is used to notify 'settled' waiters.
73 cleanCycles := 0
74
75 markDirty := func() {
76 clean = false
77 cleanCycles = 0
78 }
79
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010080 for {
81 select {
82 case <-ctx.Done():
Serge Bazanskic7359672020-10-30 16:38:57 +010083 s.ilogger.Infof("supervisor processor exiting: %v", ctx.Err())
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010084 s.processKill()
Serge Bazanskiec19b602022-03-09 20:41:31 +010085 s.ilogger.Info("supervisor exited, starting liquidator to clean up remaining runnables...")
86 go s.liquidator()
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010087 return
88 case <-gc.C:
89 if !clean {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010090 s.processGC()
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010091 }
92 clean = true
Serge Bazanskiac6b6442020-05-06 19:13:43 +020093 cleanCycles += 1
94
Serge Bazanski216fe7b2021-05-21 18:36:16 +020095 // This threshold is somewhat arbitrary. It's a balance between
96 // test speed and test reliability.
Serge Bazanskiac6b6442020-05-06 19:13:43 +020097 if cleanCycles > 50 {
98 for _, w := range waiters {
99 close(w)
100 }
101 waiters = nil
102 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100103 case r := <-s.pReq:
104 switch {
105 case r.schedule != nil:
106 s.processSchedule(r.schedule)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200107 markDirty()
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100108 case r.died != nil:
109 s.processDied(r.died)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200110 markDirty()
111 case r.waitSettled != nil:
112 waiters = append(waiters, r.waitSettled.waiter)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100113 default:
114 panic(fmt.Errorf("unhandled request %+v", r))
115 }
116 }
117 }
118}
119
Serge Bazanskiec19b602022-03-09 20:41:31 +0100120// The liquidator is a context-free goroutine which the supervisor starts after
121// its context has been canceled. Its job is to take over listening on the
122// processing channels that the supervisor processor would usually listen on,
123// and implement the minimum amount of logic required to mark existing runnables
124// as DEAD.
125//
126// It exits when all runnables have exited one way or another, and the
127// supervision tree is well and truly dead. This will also be reflected by
128// liveRunnables returning an empty list.
129func (s *supervisor) liquidator() {
130 for {
131 select {
132 case r := <-s.pReq:
133 switch {
134 case r.schedule != nil:
135 s.ilogger.Infof("liquidator: refusing to schedule %s", r.schedule.dn)
136 s.mu.Lock()
137 n := s.nodeByDN(r.schedule.dn)
138 n.state = nodeStateDead
139 s.mu.Unlock()
140 case r.died != nil:
141 s.ilogger.Infof("liquidator: %s exited", r.died.dn)
142 s.mu.Lock()
143 n := s.nodeByDN(r.died.dn)
144 n.state = nodeStateDead
145 s.mu.Unlock()
146 }
147 }
148 live := s.liveRunnables()
149 if len(live) == 0 {
150 s.ilogger.Infof("liquidator: complete, all runnables dead or done")
151 return
152 }
153 }
154}
155
156// liveRunnables returns a list of runnable DNs that aren't DONE/DEAD. This is
157// used by the liquidator to figure out when its job is done, and by the
158// TestHarness to know when to unblock the test cleanup function.
159func (s *supervisor) liveRunnables() []string {
160 s.mu.RLock()
161 defer s.mu.RUnlock()
162
163 // DFS through supervision tree, making not of live (non-DONE/DEAD runnables).
164 var live []string
165 seen := make(map[string]bool)
166 q := []*node{s.root}
167 for {
168 if len(q) == 0 {
169 break
170 }
171
172 // Pop from DFS queue.
173 el := q[0]
174 q = q[1:]
175
176 // Skip already visited runnables (this shouldn't happen because the supervision
177 // tree is, well, a tree - but better stay safe than get stuck in a loop).
178 eldn := el.dn()
179 if seen[eldn] {
180 continue
181 }
182 seen[eldn] = true
183
184 if el.state != nodeStateDead && el.state != nodeStateDone {
185 live = append(live, eldn)
186 }
187
188 // Recurse.
189 for _, child := range el.children {
190 q = append(q, child)
191 }
192 }
193
194 sort.Strings(live)
195 return live
196}
197
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200198// processKill cancels all nodes in the supervision tree. This is only called
199// right before exiting the processor, so they do not get automatically
200// restarted.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100201func (s *supervisor) processKill() {
202 s.mu.Lock()
203 defer s.mu.Unlock()
204
205 // Gather all context cancel functions.
206 var cancels []func()
207 queue := []*node{s.root}
208 for {
209 if len(queue) == 0 {
210 break
211 }
212
213 cur := queue[0]
214 queue = queue[1:]
215
216 cancels = append(cancels, cur.ctxC)
217 for _, c := range cur.children {
218 queue = append(queue, c)
219 }
220 }
221
222 // Call all context cancels.
223 for _, c := range cancels {
224 c()
225 }
226}
227
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200228// processSchedule starts a node's runnable in a goroutine and records its
229// output once it's done.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100230func (s *supervisor) processSchedule(r *processorRequestSchedule) {
231 s.mu.Lock()
232 defer s.mu.Unlock()
233
234 n := s.nodeByDN(r.dn)
235 go func() {
Serge Bazanski19bb4122020-05-04 17:57:50 +0200236 if !s.propagatePanic {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100237 defer func() {
238 if rec := recover(); rec != nil {
239 s.pReq <- &processorRequest{
240 died: &processorRequestDied{
241 dn: r.dn,
242 err: fmt.Errorf("panic: %v, stacktrace: %s", rec, string(debug.Stack())),
243 },
244 }
245 }
246 }()
247 }
248
249 res := n.runnable(n.ctx)
250
251 s.pReq <- &processorRequest{
252 died: &processorRequestDied{
253 dn: r.dn,
254 err: res,
255 },
256 }
257 }()
258}
259
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200260// processDied records the result from a runnable goroutine, and updates its
261// node state accordingly. If the result is a death and not an expected exit,
262// related nodes (ie. children and group siblings) are canceled accordingly.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100263func (s *supervisor) processDied(r *processorRequestDied) {
264 s.mu.Lock()
265 defer s.mu.Unlock()
266
267 // Okay, so a Runnable has quit. What now?
268 n := s.nodeByDN(r.dn)
269 ctx := n.ctx
270
271 // Simple case: it was marked as Done and quit with no error.
272 if n.state == nodeStateDone && r.err == nil {
273 // Do nothing. This was supposed to happen. Keep the process as DONE.
274 return
275 }
276
277 // Find innermost error to check if it's a context canceled error.
278 perr := r.err
279 for {
280 if inner := errors.Unwrap(perr); inner != nil {
281 perr = inner
282 continue
283 }
284 break
285 }
286
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200287 // Simple case: the context was canceled and the returned error is the
288 // context error.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100289 if err := ctx.Err(); err != nil && perr == err {
290 // Mark the node as canceled successfully.
291 n.state = nodeStateCanceled
292 return
293 }
294
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200295 // Otherwise, the Runnable should not have died or quit. Handle
296 // accordingly.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100297 err := r.err
298 // A lack of returned error is also an error.
299 if err == nil {
300 err = fmt.Errorf("returned when %s", n.state)
301 } else {
302 err = fmt.Errorf("returned error when %s: %w", n.state, err)
303 }
304
Serge Bazanskic7359672020-10-30 16:38:57 +0100305 s.ilogger.Errorf("Runnable %s died: %v", n.dn(), err)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100306 // Mark as dead.
307 n.state = nodeStateDead
308
309 // Cancel that node's context, just in case something still depends on it.
310 n.ctxC()
311
312 // Cancel all siblings.
313 if n.parent != nil {
314 for name, _ := range n.parent.groupSiblings(n.name) {
315 if name == n.name {
316 continue
317 }
318 sibling := n.parent.children[name]
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200319 // TODO(q3k): does this need to run in a goroutine, ie. can a
320 // context cancel block?
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100321 sibling.ctxC()
322 }
323 }
324}
325
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200326// processGC runs the GC process. It's not really Garbage Collection, as in, it
327// doesn't remove unnecessary tree nodes - but it does find nodes that need to
328// be restarted, find the subset that can and then schedules them for running.
329// As such, it's less of a Garbage Collector and more of a Necromancer.
330// However, GC is a friendlier name.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100331func (s *supervisor) processGC() {
332 s.mu.Lock()
333 defer s.mu.Unlock()
334
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200335 // The 'GC' serves is the main business logic of the supervision tree. It
336 // traverses a locked tree and tries to find subtrees that must be
337 // restarted (because of a DEAD/CANCELED runnable). It then finds which of
338 // these subtrees that should be restarted can be restarted, ie. which ones
339 // are fully recursively DEAD/CANCELED. It also finds the smallest set of
340 // largest subtrees that can be restarted, ie. if there's multiple DEAD
341 // runnables that can be restarted at once, it will do so.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100342
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100343 // Phase one: Find all leaves.
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200344 // This is a simple DFS that finds all the leaves of the tree, ie all nodes
345 // that do not have children nodes.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100346 leaves := make(map[string]bool)
347 queue := []*node{s.root}
348 for {
349 if len(queue) == 0 {
350 break
351 }
352 cur := queue[0]
353 queue = queue[1:]
354
355 for _, c := range cur.children {
356 queue = append([]*node{c}, queue...)
357 }
358
359 if len(cur.children) == 0 {
360 leaves[cur.dn()] = true
361 }
362 }
363
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200364 // Phase two: traverse tree from node to root and make note of all subtrees
365 // that can be restarted.
366 // A subtree is restartable/ready iff every node in that subtree is either
367 // CANCELED, DEAD or DONE. Such a 'ready' subtree can be restarted by the
368 // supervisor if needed.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100369
370 // DNs that we already visited.
371 visited := make(map[string]bool)
372 // DNs whose subtrees are ready to be restarted.
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200373 // These are all subtrees recursively - ie., root.a.a and root.a will both
374 // be marked here.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100375 ready := make(map[string]bool)
376
377 // We build a queue of nodes to visit, starting from the leaves.
378 queue = []*node{}
379 for l, _ := range leaves {
380 queue = append(queue, s.nodeByDN(l))
381 }
382
383 for {
384 if len(queue) == 0 {
385 break
386 }
387
388 cur := queue[0]
389 curDn := cur.dn()
390
391 queue = queue[1:]
392
393 // Do we have a decision about our children?
394 allVisited := true
395 for _, c := range cur.children {
396 if !visited[c.dn()] {
397 allVisited = false
398 break
399 }
400 }
401
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200402 // If no decision about children is available, it means we ended up in
403 // this subtree through some shorter path of a shorter/lower-order
404 // leaf. There is a path to a leaf that's longer than the one that
405 // caused this node to be enqueued. Easy solution: just push back the
406 // current element and retry later.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100407 if !allVisited {
408 // Push back to queue and wait for a decision later.
409 queue = append(queue, cur)
410 continue
411 }
412
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200413 // All children have been visited and we have an idea about whether
414 // they're ready/restartable. All of the node's children must be
415 // restartable in order for this node to be restartable.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100416 childrenReady := true
Serge Bazanskiba7bf7d2021-10-29 16:59:00 +0200417 var childrenNotReady []string
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100418 for _, c := range cur.children {
419 if !ready[c.dn()] {
Serge Bazanskiba7bf7d2021-10-29 16:59:00 +0200420 childrenNotReady = append(childrenNotReady, c.dn())
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100421 childrenReady = false
422 break
423 }
424 }
425
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200426 // In addition to children, the node itself must be restartable (ie.
427 // DONE, DEAD or CANCELED).
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100428 curReady := false
429 switch cur.state {
430 case nodeStateDone:
431 curReady = true
432 case nodeStateCanceled:
433 curReady = true
434 case nodeStateDead:
435 curReady = true
436 }
437
Serge Bazanskiba7bf7d2021-10-29 16:59:00 +0200438 if cur.state == nodeStateDead && !childrenReady {
439 s.ilogger.Warningf("Not restarting %s: children not ready to be restarted: %v", curDn, childrenNotReady)
440 }
441
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200442 // Note down that we have an opinion on this node, and note that
443 // opinion down.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100444 visited[curDn] = true
445 ready[curDn] = childrenReady && curReady
446
447 // Now we can also enqueue the parent of this node for processing.
448 if cur.parent != nil && !visited[cur.parent.dn()] {
449 queue = append(queue, cur.parent)
450 }
451 }
452
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200453 // Phase 3: traverse tree from root to find largest subtrees that need to
454 // be restarted and are ready to be restarted.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100455
456 // All DNs that need to be restarted by the GC process.
457 want := make(map[string]bool)
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200458 // All DNs that need to be restarted and can be restarted by the GC process
459 // - a subset of 'want' DNs.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100460 can := make(map[string]bool)
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200461 // The set difference between 'want' and 'can' are all nodes that should be
462 // restarted but can't yet (ie. because a child is still in the process of
463 // being canceled).
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100464
465 // DFS from root.
466 queue = []*node{s.root}
467 for {
468 if len(queue) == 0 {
469 break
470 }
471
472 cur := queue[0]
473 queue = queue[1:]
474
475 // If this node is DEAD or CANCELED it should be restarted.
476 if cur.state == nodeStateDead || cur.state == nodeStateCanceled {
477 want[cur.dn()] = true
478 }
479
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200480 // If it should be restarted and is ready to be restarted...
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100481 if want[cur.dn()] && ready[cur.dn()] {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200482 // And its parent context is valid (ie hasn't been canceled), mark
483 // it as restartable.
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200484 if cur.parent == nil || cur.parent.ctx.Err() == nil {
485 can[cur.dn()] = true
486 continue
487 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100488 }
489
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200490 // Otherwise, traverse further down the tree to see if something else
491 // needs to be done.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100492 for _, c := range cur.children {
493 queue = append(queue, c)
494 }
495 }
496
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100497 // Reinitialize and reschedule all subtrees
498 for dn, _ := range can {
499 n := s.nodeByDN(dn)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200500
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200501 // Only back off when the node unexpectedly died - not when it got
502 // canceled.
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200503 bo := time.Duration(0)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100504 if n.state == nodeStateDead {
505 bo = n.bo.NextBackOff()
506 }
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200507
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200508 // Prepare node for rescheduling - remove its children, reset its state
509 // to new.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100510 n.reset()
Serge Bazanskic7359672020-10-30 16:38:57 +0100511 s.ilogger.Infof("rescheduling supervised node %s with backoff %s", dn, bo.String())
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100512
513 // Reschedule node runnable to run after backoff.
514 go func(n *node, bo time.Duration) {
515 time.Sleep(bo)
516 s.pReq <- &processorRequest{
517 schedule: &processorRequestSchedule{dn: n.dn()},
518 }
519 }(n, bo)
520 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100521}