blob: 5fa759e87f0dc75cd8de952533cb2b939e55c977 [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"
24 "time"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010025)
26
Serge Bazanski216fe7b2021-05-21 18:36:16 +020027// The processor maintains runnable goroutines - ie., when requested will start
28// one, and then once it exists it will record the result and act accordingly.
29// It is also responsible for detecting and acting upon supervision subtrees
30// that need to be restarted after death (via a 'GC' process)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010031
Serge Bazanski216fe7b2021-05-21 18:36:16 +020032// processorRequest is a request for the processor. Only one of the fields can
33// be set.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010034type processorRequest struct {
Serge Bazanskiac6b6442020-05-06 19:13:43 +020035 schedule *processorRequestSchedule
36 died *processorRequestDied
37 waitSettled *processorRequestWaitSettled
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010038}
39
40// processorRequestSchedule requests that a given node's runnable be started.
41type processorRequestSchedule struct {
42 dn string
43}
44
Serge Bazanski216fe7b2021-05-21 18:36:16 +020045// processorRequestDied is a signal from a runnable goroutine that the runnable
46// has died.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010047type processorRequestDied struct {
48 dn string
49 err error
50}
51
Serge Bazanskiac6b6442020-05-06 19:13:43 +020052type processorRequestWaitSettled struct {
53 waiter chan struct{}
54}
55
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010056// processor is the main processing loop.
57func (s *supervisor) processor(ctx context.Context) {
58 s.ilogger.Info("supervisor processor started")
59
Serge Bazanskiac6b6442020-05-06 19:13:43 +020060 // Waiters waiting for the GC to be settled.
61 var waiters []chan struct{}
62
Serge Bazanski216fe7b2021-05-21 18:36:16 +020063 // The GC will run every millisecond if needed. Any time the processor
64 // requests a change in the supervision tree (ie a death or a new runnable)
65 // it will mark the state as dirty and run the GC on the next millisecond
66 // cycle.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010067 gc := time.NewTicker(1 * time.Millisecond)
68 defer gc.Stop()
69 clean := true
70
Serge Bazanskiac6b6442020-05-06 19:13:43 +020071 // How long has the GC been clean. This is used to notify 'settled' waiters.
72 cleanCycles := 0
73
74 markDirty := func() {
75 clean = false
76 cleanCycles = 0
77 }
78
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010079 for {
80 select {
81 case <-ctx.Done():
Serge Bazanskic7359672020-10-30 16:38:57 +010082 s.ilogger.Infof("supervisor processor exiting: %v", ctx.Err())
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010083 s.processKill()
84 s.ilogger.Info("supervisor exited")
85 return
86 case <-gc.C:
87 if !clean {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010088 s.processGC()
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010089 }
90 clean = true
Serge Bazanskiac6b6442020-05-06 19:13:43 +020091 cleanCycles += 1
92
Serge Bazanski216fe7b2021-05-21 18:36:16 +020093 // This threshold is somewhat arbitrary. It's a balance between
94 // test speed and test reliability.
Serge Bazanskiac6b6442020-05-06 19:13:43 +020095 if cleanCycles > 50 {
96 for _, w := range waiters {
97 close(w)
98 }
99 waiters = nil
100 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100101 case r := <-s.pReq:
102 switch {
103 case r.schedule != nil:
104 s.processSchedule(r.schedule)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200105 markDirty()
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100106 case r.died != nil:
107 s.processDied(r.died)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200108 markDirty()
109 case r.waitSettled != nil:
110 waiters = append(waiters, r.waitSettled.waiter)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100111 default:
112 panic(fmt.Errorf("unhandled request %+v", r))
113 }
114 }
115 }
116}
117
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200118// processKill cancels all nodes in the supervision tree. This is only called
119// right before exiting the processor, so they do not get automatically
120// restarted.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100121func (s *supervisor) processKill() {
122 s.mu.Lock()
123 defer s.mu.Unlock()
124
125 // Gather all context cancel functions.
126 var cancels []func()
127 queue := []*node{s.root}
128 for {
129 if len(queue) == 0 {
130 break
131 }
132
133 cur := queue[0]
134 queue = queue[1:]
135
136 cancels = append(cancels, cur.ctxC)
137 for _, c := range cur.children {
138 queue = append(queue, c)
139 }
140 }
141
142 // Call all context cancels.
143 for _, c := range cancels {
144 c()
145 }
146}
147
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200148// processSchedule starts a node's runnable in a goroutine and records its
149// output once it's done.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100150func (s *supervisor) processSchedule(r *processorRequestSchedule) {
151 s.mu.Lock()
152 defer s.mu.Unlock()
153
154 n := s.nodeByDN(r.dn)
155 go func() {
Serge Bazanski19bb4122020-05-04 17:57:50 +0200156 if !s.propagatePanic {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100157 defer func() {
158 if rec := recover(); rec != nil {
159 s.pReq <- &processorRequest{
160 died: &processorRequestDied{
161 dn: r.dn,
162 err: fmt.Errorf("panic: %v, stacktrace: %s", rec, string(debug.Stack())),
163 },
164 }
165 }
166 }()
167 }
168
169 res := n.runnable(n.ctx)
170
171 s.pReq <- &processorRequest{
172 died: &processorRequestDied{
173 dn: r.dn,
174 err: res,
175 },
176 }
177 }()
178}
179
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200180// processDied records the result from a runnable goroutine, and updates its
181// node state accordingly. If the result is a death and not an expected exit,
182// related nodes (ie. children and group siblings) are canceled accordingly.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100183func (s *supervisor) processDied(r *processorRequestDied) {
184 s.mu.Lock()
185 defer s.mu.Unlock()
186
187 // Okay, so a Runnable has quit. What now?
188 n := s.nodeByDN(r.dn)
189 ctx := n.ctx
190
191 // Simple case: it was marked as Done and quit with no error.
192 if n.state == nodeStateDone && r.err == nil {
193 // Do nothing. This was supposed to happen. Keep the process as DONE.
194 return
195 }
196
197 // Find innermost error to check if it's a context canceled error.
198 perr := r.err
199 for {
200 if inner := errors.Unwrap(perr); inner != nil {
201 perr = inner
202 continue
203 }
204 break
205 }
206
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200207 // Simple case: the context was canceled and the returned error is the
208 // context error.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100209 if err := ctx.Err(); err != nil && perr == err {
210 // Mark the node as canceled successfully.
211 n.state = nodeStateCanceled
212 return
213 }
214
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200215 // Otherwise, the Runnable should not have died or quit. Handle
216 // accordingly.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100217 err := r.err
218 // A lack of returned error is also an error.
219 if err == nil {
220 err = fmt.Errorf("returned when %s", n.state)
221 } else {
222 err = fmt.Errorf("returned error when %s: %w", n.state, err)
223 }
224
Serge Bazanskic7359672020-10-30 16:38:57 +0100225 s.ilogger.Errorf("Runnable %s died: %v", n.dn(), err)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100226 // Mark as dead.
227 n.state = nodeStateDead
228
229 // Cancel that node's context, just in case something still depends on it.
230 n.ctxC()
231
232 // Cancel all siblings.
233 if n.parent != nil {
234 for name, _ := range n.parent.groupSiblings(n.name) {
235 if name == n.name {
236 continue
237 }
238 sibling := n.parent.children[name]
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200239 // TODO(q3k): does this need to run in a goroutine, ie. can a
240 // context cancel block?
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100241 sibling.ctxC()
242 }
243 }
244}
245
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200246// processGC runs the GC process. It's not really Garbage Collection, as in, it
247// doesn't remove unnecessary tree nodes - but it does find nodes that need to
248// be restarted, find the subset that can and then schedules them for running.
249// As such, it's less of a Garbage Collector and more of a Necromancer.
250// However, GC is a friendlier name.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100251func (s *supervisor) processGC() {
252 s.mu.Lock()
253 defer s.mu.Unlock()
254
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200255 // The 'GC' serves is the main business logic of the supervision tree. It
256 // traverses a locked tree and tries to find subtrees that must be
257 // restarted (because of a DEAD/CANCELED runnable). It then finds which of
258 // these subtrees that should be restarted can be restarted, ie. which ones
259 // are fully recursively DEAD/CANCELED. It also finds the smallest set of
260 // largest subtrees that can be restarted, ie. if there's multiple DEAD
261 // runnables that can be restarted at once, it will do so.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100262
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100263 // Phase one: Find all leaves.
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200264 // This is a simple DFS that finds all the leaves of the tree, ie all nodes
265 // that do not have children nodes.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100266 leaves := make(map[string]bool)
267 queue := []*node{s.root}
268 for {
269 if len(queue) == 0 {
270 break
271 }
272 cur := queue[0]
273 queue = queue[1:]
274
275 for _, c := range cur.children {
276 queue = append([]*node{c}, queue...)
277 }
278
279 if len(cur.children) == 0 {
280 leaves[cur.dn()] = true
281 }
282 }
283
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200284 // Phase two: traverse tree from node to root and make note of all subtrees
285 // that can be restarted.
286 // A subtree is restartable/ready iff every node in that subtree is either
287 // CANCELED, DEAD or DONE. Such a 'ready' subtree can be restarted by the
288 // supervisor if needed.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100289
290 // DNs that we already visited.
291 visited := make(map[string]bool)
292 // DNs whose subtrees are ready to be restarted.
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200293 // These are all subtrees recursively - ie., root.a.a and root.a will both
294 // be marked here.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100295 ready := make(map[string]bool)
296
297 // We build a queue of nodes to visit, starting from the leaves.
298 queue = []*node{}
299 for l, _ := range leaves {
300 queue = append(queue, s.nodeByDN(l))
301 }
302
303 for {
304 if len(queue) == 0 {
305 break
306 }
307
308 cur := queue[0]
309 curDn := cur.dn()
310
311 queue = queue[1:]
312
313 // Do we have a decision about our children?
314 allVisited := true
315 for _, c := range cur.children {
316 if !visited[c.dn()] {
317 allVisited = false
318 break
319 }
320 }
321
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200322 // If no decision about children is available, it means we ended up in
323 // this subtree through some shorter path of a shorter/lower-order
324 // leaf. There is a path to a leaf that's longer than the one that
325 // caused this node to be enqueued. Easy solution: just push back the
326 // current element and retry later.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100327 if !allVisited {
328 // Push back to queue and wait for a decision later.
329 queue = append(queue, cur)
330 continue
331 }
332
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200333 // All children have been visited and we have an idea about whether
334 // they're ready/restartable. All of the node's children must be
335 // restartable in order for this node to be restartable.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100336 childrenReady := true
337 for _, c := range cur.children {
338 if !ready[c.dn()] {
339 childrenReady = false
340 break
341 }
342 }
343
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200344 // In addition to children, the node itself must be restartable (ie.
345 // DONE, DEAD or CANCELED).
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100346 curReady := false
347 switch cur.state {
348 case nodeStateDone:
349 curReady = true
350 case nodeStateCanceled:
351 curReady = true
352 case nodeStateDead:
353 curReady = true
354 }
355
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200356 // Note down that we have an opinion on this node, and note that
357 // opinion down.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100358 visited[curDn] = true
359 ready[curDn] = childrenReady && curReady
360
361 // Now we can also enqueue the parent of this node for processing.
362 if cur.parent != nil && !visited[cur.parent.dn()] {
363 queue = append(queue, cur.parent)
364 }
365 }
366
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200367 // Phase 3: traverse tree from root to find largest subtrees that need to
368 // be restarted and are ready to be restarted.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100369
370 // All DNs that need to be restarted by the GC process.
371 want := make(map[string]bool)
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200372 // All DNs that need to be restarted and can be restarted by the GC process
373 // - a subset of 'want' DNs.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100374 can := make(map[string]bool)
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200375 // The set difference between 'want' and 'can' are all nodes that should be
376 // restarted but can't yet (ie. because a child is still in the process of
377 // being canceled).
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100378
379 // DFS from root.
380 queue = []*node{s.root}
381 for {
382 if len(queue) == 0 {
383 break
384 }
385
386 cur := queue[0]
387 queue = queue[1:]
388
389 // If this node is DEAD or CANCELED it should be restarted.
390 if cur.state == nodeStateDead || cur.state == nodeStateCanceled {
391 want[cur.dn()] = true
392 }
393
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200394 // If it should be restarted and is ready to be restarted...
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100395 if want[cur.dn()] && ready[cur.dn()] {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200396 // And its parent context is valid (ie hasn't been canceled), mark
397 // it as restartable.
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200398 if cur.parent == nil || cur.parent.ctx.Err() == nil {
399 can[cur.dn()] = true
400 continue
401 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100402 }
403
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200404 // Otherwise, traverse further down the tree to see if something else
405 // needs to be done.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100406 for _, c := range cur.children {
407 queue = append(queue, c)
408 }
409 }
410
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100411 // Reinitialize and reschedule all subtrees
412 for dn, _ := range can {
413 n := s.nodeByDN(dn)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200414
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200415 // Only back off when the node unexpectedly died - not when it got
416 // canceled.
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200417 bo := time.Duration(0)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100418 if n.state == nodeStateDead {
419 bo = n.bo.NextBackOff()
420 }
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200421
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200422 // Prepare node for rescheduling - remove its children, reset its state
423 // to new.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100424 n.reset()
Serge Bazanskic7359672020-10-30 16:38:57 +0100425 s.ilogger.Infof("rescheduling supervised node %s with backoff %s", dn, bo.String())
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100426
427 // Reschedule node runnable to run after backoff.
428 go func(n *node, bo time.Duration) {
429 time.Sleep(bo)
430 s.pReq <- &processorRequest{
431 schedule: &processorRequestSchedule{dn: n.dn()},
432 }
433 }(n, bo)
434 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100435}