blob: 4fb2ddb565f0038708c287975f66c5f6c30915ad [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 "fmt"
22 "regexp"
23 "strings"
24
25 "github.com/cenkalti/backoff/v4"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010026)
27
Serge Bazanski216fe7b2021-05-21 18:36:16 +020028// node is a supervision tree node. It represents the state of a Runnable
29// within this tree, its relation to other tree elements, and contains
30// supporting data needed to actually supervise it.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010031type node struct {
Serge Bazanski216fe7b2021-05-21 18:36:16 +020032 // The name of this node. Opaque string. It's used to make up the 'dn'
33 // (distinguished name) of a node within the tree. When starting a runnable
34 // inside a tree, this is where that name gets used.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010035 name string
36 runnable Runnable
37
38 // The supervisor managing this tree.
39 sup *supervisor
Serge Bazanski216fe7b2021-05-21 18:36:16 +020040 // The parent, within the tree, of this node. If this is the root node of
41 // the tree, this is nil.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010042 parent *node
Serge Bazanski216fe7b2021-05-21 18:36:16 +020043 // Children of this tree. This is represented by a map keyed from child
44 // node names, for easy access.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010045 children map[string]*node
Serge Bazanski26d52252022-02-07 15:57:54 +010046 // Reserved nodes that may not be used as child names. This is currently
47 // used by sub-loggers (see SubLogger function), preventing a sub-logger
48 // name from colliding with a node name.
49 reserved map[string]bool
Serge Bazanski216fe7b2021-05-21 18:36:16 +020050 // Supervision groups. Each group is a set of names of children. Sets, and
51 // as such groups, don't overlap between each other. A supervision group
52 // indicates that if any child within that group fails, all others should
53 // be canceled and restarted together.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010054 groups []map[string]bool
55
56 // The current state of the runnable in this node.
57 state nodeState
58
59 // Backoff used to keep runnables from being restarted too fast.
60 bo *backoff.ExponentialBackOff
61
62 // Context passed to the runnable, and its cancel function.
63 ctx context.Context
64 ctxC context.CancelFunc
65}
66
Serge Bazanski216fe7b2021-05-21 18:36:16 +020067// nodeState is the state of a runnable within a node, and in a way the node
68// itself. This follows the state diagram from go/supervision.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010069type nodeState int
70
71const (
Serge Bazanski216fe7b2021-05-21 18:36:16 +020072 // A node that has just been created, and whose runnable has been started
73 // already but hasn't signaled anything yet.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010074 nodeStateNew nodeState = iota
Serge Bazanski216fe7b2021-05-21 18:36:16 +020075 // A node whose runnable has signaled being healthy - this means it's ready
76 // to serve/act.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010077 nodeStateHealthy
78 // A node that has unexpectedly returned or panicked.
79 nodeStateDead
Serge Bazanski216fe7b2021-05-21 18:36:16 +020080 // A node that has declared that its done with its work and should not be
81 // restarted, unless a supervision tree failure requires that.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010082 nodeStateDone
83 // A node that has returned after being requested to cancel.
84 nodeStateCanceled
85)
86
87func (s nodeState) String() string {
88 switch s {
89 case nodeStateNew:
90 return "NODE_STATE_NEW"
91 case nodeStateHealthy:
92 return "NODE_STATE_HEALTHY"
93 case nodeStateDead:
94 return "NODE_STATE_DEAD"
95 case nodeStateDone:
96 return "NODE_STATE_DONE"
97 case nodeStateCanceled:
98 return "NODE_STATE_CANCELED"
99 }
100 return "UNKNOWN"
101}
102
103func (n *node) String() string {
104 return fmt.Sprintf("%s (%s)", n.dn(), n.state.String())
105}
106
107// contextKey is a type used to keep data within context values.
108type contextKey string
109
110var (
111 supervisorKey = contextKey("supervisor")
112 dnKey = contextKey("dn")
113)
114
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200115// fromContext retrieves a tree node from a runnable context. It takes a lock
116// on the tree and returns an unlock function. This unlock function needs to be
117// called once mutations on the tree/supervisor/node are done.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100118func fromContext(ctx context.Context) (*node, func()) {
119 sup, ok := ctx.Value(supervisorKey).(*supervisor)
120 if !ok {
121 panic("supervisor function called from non-runnable context")
122 }
123
124 sup.mu.Lock()
125
126 dnParent, ok := ctx.Value(dnKey).(string)
127 if !ok {
128 sup.mu.Unlock()
129 panic("supervisor function called from non-runnable context")
130 }
131
132 return sup.nodeByDN(dnParent), sup.mu.Unlock
133}
134
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200135// All the following 'internal' supervisor functions must only be called with
136// the supervisor lock taken. Getting a lock via fromContext is enough.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100137
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200138// dn returns the distinguished name of a node. This distinguished name is a
139// period-separated, inverse-DNS-like name. For instance, the runnable 'foo'
140// within the runnable 'bar' will be called 'root.bar.foo'. The root of the
141// tree is always named, and has the dn, 'root'.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100142func (n *node) dn() string {
143 if n.parent != nil {
144 return fmt.Sprintf("%s.%s", n.parent.dn(), n.name)
145 }
146 return n.name
147}
148
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200149// groupSiblings is a helper function to get all runnable group siblings of a
150// given runnable name within this node. All children are always in a group,
151// even if that group is unary.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100152func (n *node) groupSiblings(name string) map[string]bool {
153 for _, m := range n.groups {
154 if _, ok := m[name]; ok {
155 return m
156 }
157 }
158 return nil
159}
160
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200161// newNode creates a new node with a given parent. It does not register it with
162// the parent (as that depends on group placement).
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100163func newNode(name string, runnable Runnable, sup *supervisor, parent *node) *node {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200164 // We use exponential backoff for failed runnables, but at some point we
165 // cap at a given backoff time. To achieve this, we set MaxElapsedTime to
166 // 0, which will cap the backoff at MaxInterval.
Serge Bazanskib9431c92020-08-24 18:16:51 +0200167 bo := backoff.NewExponentialBackOff()
168 bo.MaxElapsedTime = 0
169
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100170 n := &node{
171 name: name,
172 runnable: runnable,
173
Serge Bazanskib9431c92020-08-24 18:16:51 +0200174 bo: bo,
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100175
176 sup: sup,
177 parent: parent,
178 }
179 n.reset()
180 return n
181}
182
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200183// resetNode sets up all the dynamic fields of the node, in preparation of
184// starting a runnable. It clears the node's children, groups and resets its
185// context.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100186func (n *node) reset() {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200187 // Make new context. First, acquire parent context. For the root node
188 // that's Background, otherwise it's the parent's context.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100189 var pCtx context.Context
190 if n.parent == nil {
191 pCtx = context.Background()
192 } else {
193 pCtx = n.parent.ctx
194 }
195 // Mark DN and supervisor in context.
196 ctx := context.WithValue(pCtx, dnKey, n.dn())
197 ctx = context.WithValue(ctx, supervisorKey, n.sup)
198 ctx, ctxC := context.WithCancel(ctx)
199 // Set context
200 n.ctx = ctx
201 n.ctxC = ctxC
202
203 // Clear children and state
204 n.state = nodeStateNew
205 n.children = make(map[string]*node)
Serge Bazanski26d52252022-02-07 15:57:54 +0100206 n.reserved = make(map[string]bool)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100207 n.groups = nil
208
209 // The node is now ready to be scheduled.
210}
211
212// nodeByDN returns a node by given DN from the supervisor.
213func (s *supervisor) nodeByDN(dn string) *node {
214 parts := strings.Split(dn, ".")
215 if parts[0] != "root" {
216 panic("DN does not start with root.")
217 }
218 parts = parts[1:]
219 cur := s.root
220 for {
221 if len(parts) == 0 {
222 return cur
223 }
224
225 next, ok := cur.children[parts[0]]
226 if !ok {
227 panic(fmt.Errorf("could not find %v (%s) in %s", parts, dn, cur))
228 }
229 cur = next
230 parts = parts[1:]
231 }
232}
233
234// reNodeName validates a node name against constraints.
235var reNodeName = regexp.MustCompile(`[a-z90-9_]{1,64}`)
236
237// runGroup schedules a new group of runnables to run on a node.
238func (n *node) runGroup(runnables map[string]Runnable) error {
239 // Check that the parent node is in the right state.
240 if n.state != nodeStateNew {
241 return fmt.Errorf("cannot run new runnable on non-NEW node")
242 }
243
244 // Check the requested runnable names.
245 for name, _ := range runnables {
246 if !reNodeName.MatchString(name) {
247 return fmt.Errorf("runnable name %q is invalid", name)
248 }
249 if _, ok := n.children[name]; ok {
250 return fmt.Errorf("runnable %q already exists", name)
251 }
Serge Bazanski26d52252022-02-07 15:57:54 +0100252 if _, ok := n.reserved[name]; ok {
253 return fmt.Errorf("runnable %q would shadow reserved name (eg. sub-logger)", name)
254 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100255 }
256
257 // Create child nodes.
258 dns := make(map[string]string)
259 group := make(map[string]bool)
260 for name, runnable := range runnables {
261 if g := n.groupSiblings(name); g != nil {
262 return fmt.Errorf("duplicate child name %q", name)
263 }
264 node := newNode(name, runnable, n.sup, n)
265 n.children[name] = node
266
267 dns[name] = node.dn()
268 group[name] = true
269 }
270 // Add group.
271 n.groups = append(n.groups, group)
272
273 // Schedule execution of group members.
274 go func() {
275 for name, _ := range runnables {
276 n.sup.pReq <- &processorRequest{
277 schedule: &processorRequestSchedule{
278 dn: dns[name],
279 },
280 }
281 }
282 }()
283 return nil
284}
285
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200286// signal sequences state changes by signals received from runnables and
287// updates a node's status accordingly.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100288func (n *node) signal(signal SignalType) {
289 switch signal {
290 case SignalHealthy:
291 if n.state != nodeStateNew {
292 panic(fmt.Errorf("node %s signaled healthy", n))
293 }
294 n.state = nodeStateHealthy
295 n.bo.Reset()
296 case SignalDone:
297 if n.state != nodeStateHealthy {
298 panic(fmt.Errorf("node %s signaled done", n))
299 }
300 n.state = nodeStateDone
301 n.bo.Reset()
302 }
303}