forked from wormhole-foundation/wormhole
-
Notifications
You must be signed in to change notification settings - Fork 1
/
supervisor_node.go
272 lines (235 loc) · 7.86 KB
/
supervisor_node.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
package supervisor
import (
"context"
"fmt"
"regexp"
"strings"
"github.com/cenkalti/backoff/v4"
"go.uber.org/zap"
)
// node is a supervision tree node. It represents the state of a Runnable within this tree, its relation to other tree
// elements, and contains supporting data needed to actually supervise it.
type node struct {
// The name of this node. Opaque string. It's used to make up the 'dn' (distinguished name) of a node within
// the tree. When starting a runnable inside a tree, this is where that name gets used.
name string
runnable Runnable
// The supervisor managing this tree.
sup *supervisor
// The parent, within the tree, of this node. If this is the root node of the tree, this is nil.
parent *node
// Children of this tree. This is represented by a map keyed from child node names, for easy access.
children map[string]*node
// Supervision groups. Each group is a set of names of children. Sets, and as such groups, don't overlap between
// each other. A supervision group indicates that if any child within that group fails, all others should be
// canceled and restarted together.
groups []map[string]bool
// The current state of the runnable in this node.
state nodeState
// Backoff used to keep runnables from being restarted too fast.
bo *backoff.ExponentialBackOff
// Context passed to the runnable, and its cancel function.
ctx context.Context
ctxC context.CancelFunc
}
// nodeState is the state of a runnable within a node, and in a way the node itself.
// This follows the state diagram from go/supervision.
type nodeState int
const (
// A node that has just been created, and whose runnable has been started already but hasn't signaled anything yet.
nodeStateNew nodeState = iota
// A node whose runnable has signaled being healthy - this means it's ready to serve/act.
nodeStateHealthy
// A node that has unexpectedly returned or panicked.
nodeStateDead
// A node that has declared that its done with its work and should not be restarted, unless a supervision tree
// failure requires that.
nodeStateDone
// A node that has returned after being requested to cancel.
nodeStateCanceled
)
func (s nodeState) String() string {
switch s {
case nodeStateNew:
return "NODE_STATE_NEW"
case nodeStateHealthy:
return "NODE_STATE_HEALTHY"
case nodeStateDead:
return "NODE_STATE_DEAD"
case nodeStateDone:
return "NODE_STATE_DONE"
case nodeStateCanceled:
return "NODE_STATE_CANCELED"
}
return "UNKNOWN"
}
func (n *node) String() string {
return fmt.Sprintf("%s (%s)", n.dn(), n.state.String())
}
// contextKey is a type used to keep data within context values.
type contextKey string
var (
supervisorKey = contextKey("supervisor")
dnKey = contextKey("dn")
)
// fromContext retrieves a tree node from a runnable context. It takes a lock on the tree and returns an unlock
// function. This unlock function needs to be called once mutations on the tree/supervisor/node are done.
func fromContext(ctx context.Context) (*node, func()) {
sup, ok := ctx.Value(supervisorKey).(*supervisor)
if !ok {
panic("supervisor function called from non-runnable context")
}
sup.mu.Lock()
dnParent, ok := ctx.Value(dnKey).(string)
if !ok {
sup.mu.Unlock()
panic("supervisor function called from non-runnable context")
}
return sup.nodeByDN(dnParent), sup.mu.Unlock
}
// All the following 'internal' supervisor functions must only be called with the supervisor lock taken. Getting a lock
// via fromContext is enough.
// dn returns the distinguished name of a node. This distinguished name is a period-separated, inverse-DNS-like name.
// For instance, the runnable 'foo' within the runnable 'bar' will be called 'root.bar.foo'. The root of the tree is
// always named, and has the dn, 'root'.
func (n *node) dn() string {
if n.parent != nil {
return fmt.Sprintf("%s.%s", n.parent.dn(), n.name)
}
return n.name
}
// groupSiblings is a helper function to get all runnable group siblings of a given runnable name within this node.
// All children are always in a group, even if that group is unary.
func (n *node) groupSiblings(name string) map[string]bool {
for _, m := range n.groups {
if _, ok := m[name]; ok {
return m
}
}
return nil
}
// newNode creates a new node with a given parent. It does not register it with the parent (as that depends on group
// placement).
func newNode(name string, runnable Runnable, sup *supervisor, parent *node) *node {
// We use exponential backoff for failed runnables, but at some point we cap at a given backoff time.
// To achieve this, we set MaxElapsedTime to 0, which will cap the backoff at MaxInterval.
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = 0
n := &node{
name: name,
runnable: runnable,
bo: bo,
sup: sup,
parent: parent,
}
n.reset()
return n
}
// resetNode sets up all the dynamic fields of the node, in preparation of starting a runnable. It clears the node's
// children, groups and resets its context.
func (n *node) reset() {
// Make new context. First, acquire parent context. For the root node that's Background, otherwise it's the
// parent's context.
var pCtx context.Context
if n.parent == nil {
pCtx = context.Background()
} else {
pCtx = n.parent.ctx
}
// Mark DN and supervisor in context.
ctx := context.WithValue(pCtx, dnKey, n.dn())
ctx = context.WithValue(ctx, supervisorKey, n.sup)
ctx, ctxC := context.WithCancel(ctx)
// Set context
n.ctx = ctx
n.ctxC = ctxC
// Clear children and state
n.state = nodeStateNew
n.children = make(map[string]*node)
n.groups = nil
// The node is now ready to be scheduled.
}
// nodeByDN returns a node by given DN from the supervisor.
func (s *supervisor) nodeByDN(dn string) *node {
parts := strings.Split(dn, ".")
if parts[0] != "root" {
panic("DN does not start with root.")
}
parts = parts[1:]
cur := s.root
for {
if len(parts) == 0 {
return cur
}
next, ok := cur.children[parts[0]]
if !ok {
panic(fmt.Errorf("could not find %v (%s) in %s", parts, dn, cur))
}
cur = next
parts = parts[1:]
}
}
// reNodeName validates a node name against constraints.
var reNodeName = regexp.MustCompile(`[a-z90-9_]{1,64}`)
// runGroup schedules a new group of runnables to run on a node.
func (n *node) runGroup(runnables map[string]Runnable) error {
// Check that the parent node is in the right state.
if n.state != nodeStateNew {
return fmt.Errorf("cannot run new runnable on non-NEW node")
}
// Check the requested runnable names.
for name, _ := range runnables {
if !reNodeName.MatchString(name) {
return fmt.Errorf("runnable name %q is invalid", name)
}
if _, ok := n.children[name]; ok {
return fmt.Errorf("runnable %q already exists", name)
}
}
// Create child nodes.
dns := make(map[string]string)
group := make(map[string]bool)
for name, runnable := range runnables {
if g := n.groupSiblings(name); g != nil {
return fmt.Errorf("duplicate child name %q", name)
}
node := newNode(name, runnable, n.sup, n)
n.children[name] = node
dns[name] = node.dn()
group[name] = true
}
// Add group.
n.groups = append(n.groups, group)
// Schedule execution of group members.
go func() {
for name, _ := range runnables {
n.sup.pReq <- &processorRequest{
schedule: &processorRequestSchedule{
dn: dns[name],
},
}
}
}()
return nil
}
// signal sequences state changes by signals received from runnables and updates a node's status accordingly.
func (n *node) signal(signal SignalType) {
switch signal {
case SignalHealthy:
if n.state != nodeStateNew {
panic(fmt.Errorf("node %s signaled healthy", n))
}
n.state = nodeStateHealthy
n.bo.Reset()
case SignalDone:
if n.state != nodeStateHealthy {
panic(fmt.Errorf("node %s signaled done", n))
}
n.state = nodeStateDone
n.bo.Reset()
}
}
// getLogger creates a new logger for a given supervisor node, to be used by its runnable.
func (n *node) getLogger() *zap.Logger {
return n.sup.logger.Named(n.dn())
}