Repository navigation
Expand file tree
/
Copy pathnode.go
More file actions
1736 lines (1628 loc) · 60.7 KB
/
Copy pathnode.go
File metadata and controls
1736 lines (1628 loc) · 60.7 KB
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package grpcproc
import (
"cmp"
"context"
"errors"
"fmt"
"log/slog"
"maps"
"math"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/known/emptypb"
grpcprocv1 "github.com/floatdrop/grpcproc/proto/grpcproc/v1"
)
// Resolver turns a node name into an address grpc can dial. Resolve must
// return once ctx is done: that is what bounds a dial by Config.DialTimeout.
type Resolver interface {
Resolve(ctx context.Context, node string) (addr string, err error)
}
// Member is one incarnation of a node, as the cluster knows it.
type Member struct {
Name string
Incarnation uint64
Addr string // where peers dial it: its Config.Advertise
Metadata map[string]string // its Config.Metadata; not to be modified
}
// Registrar publishes a node to the cluster, so that peers resolve it and
// Membership reports it.
type Registrar interface {
// Register returns once self is published, and keeps it published
// until withdraw is called. Start calls Register; Stop calls withdraw
// last, after the node's processes have exited and their Down notices
// have reached its peers. An error must leave self unpublished: Start
// may call Register again.
Register(ctx context.Context, self Member) (withdraw func(context.Context) error, err error)
}
// Membership is the cluster's authoritative view of which nodes are alive.
// Links notice a dead peer by themselves, but only as fast as keepalive
// allows and not at all behind a half-open connection; Membership (an etcd
// lease expiring, say) settles it.
type Membership interface {
// Watch reports members joining and leaving until ctx is done, then
// closes the channel, which Stop waits for.
Watch(ctx context.Context) (<-chan MemberEvent, error)
}
// MemberEvent is a member joining (Up) or leaving the cluster. A leaving
// member with Incarnation 0 means whichever incarnation it was; a joining
// one, an incarnation not known.
type MemberEvent struct {
Member Member
Up bool
}
// lastIncarnation is the default incarnation this program picked last.
var lastIncarnation atomic.Uint64
// nextIncarnation is the current Unix time in nanoseconds, or one more than
// the incarnation picked last, if the clock has not moved past it: two nodes
// of one name started at the same instant must not share an incarnation.
func nextIncarnation() uint64 {
for {
last := lastIncarnation.Load()
inc := max(uint64(time.Now().UnixNano()), last+1)
if lastIncarnation.CompareAndSwap(last, inc) {
return inc
}
}
}
// ResolverFunc adapts a function to Resolver.
type ResolverFunc func(ctx context.Context, node string) (string, error)
func (f ResolverFunc) Resolve(ctx context.Context, node string) (string, error) { return f(ctx, node) }
// StaticResolver is a fixed node -> address map.
type StaticResolver map[string]string
func (s StaticResolver) Resolve(_ context.Context, node string) (string, error) {
if addr, ok := s[node]; ok {
return addr, nil
}
return "", fmt.Errorf("grpcproc: unknown node %q", node)
}
// Config configures a Node. Name, Resolver and Admit are required.
type Config struct {
// Name is the node's logical name; peers address it by this.
Name string
// Advertise is the address peers dial to reach this node's gRPC server.
// It is only informational to the core (NodeInfo, Hello); a Registrar
// publishes it.
Advertise string
// Incarnation distinguishes this start of the node from earlier ones,
// and must grow with each start: a peer that has seen an incarnation of
// the node refuses links from older ones, so that an instance that was
// replaced, and still runs, cannot take the links of its replacement.
// The peer refuses them until Membership reports the newer one gone, or
// it calls Disconnect: a random or hashed Incarnation would be refused
// whenever it came out lower than the last one. Zero picks the current
// Unix time in nanoseconds, which grows as long as the clocks of the
// hosts the node starts on agree to within the time between two starts,
// or one more than the last incarnation picked in this program, if the
// clock has not moved since: a coarse clock, or a testing/synctest
// bubble, whose clock stands still until every goroutine in it waits.
Incarnation uint64
// Resolver maps peer names to addresses.
Resolver Resolver
// Registrar, if set, publishes the node on Start and withdraws it on Stop.
Registrar Registrar
// Names, if set, is the store of the installation's global names, which
// Global targets resolve through and Process.Claim claims in. Start
// watches it before the Registrar; grpcproc/etcd keeps it in etcd.
Names Names
// Metadata describes this start of the node to the cluster: the
// application's version, its zone, whatever placement or a rolling
// deploy decides by. grpcproc reads none of it. It is published with the
// node's Member through the Registrar, so peers find it in their
// Membership (Node.Members), and NodeInfo and the Inspector show it. It
// is fixed for the node's life, so a change is a new start.
Metadata map[string]string
// Membership, if set, is watched from Start: a peer that leaves the
// cluster, or comes back as a newer incarnation, has its links dropped,
// which fires Down{noconnection} for monitors across them and fails
// pending calls. An older incarnation reported up is ignored.
Membership Membership
// DialOptions are used for every outbound connection: credentials,
// keepalive, interceptors. Keepalive is what turns a silent partition
// into a link error; set it here and on the server, whose pings end a
// silent peer's link to this node, which is what declares it down.
DialOptions []grpc.DialOption
// DialOptionsFor, if set, gives more options for the connections to one
// peer, its link's and Dial's. They come after DialOptions, so they
// override them: the credentials of another installation, whose nodes
// present certificates of another CA, say.
DialOptionsFor func(peer string) []grpc.DialOption
// Admit runs for every inbound link before it is accepted, with the
// peer's transport credentials in ctx (grpc/peer) and the identity it
// claims. An error refuses the link: the peer's dial fails with
// PermissionDenied. Otherwise the Policy it returns judges everything the
// peer asks over the link, for as long as the link lasts: messages,
// calls, monitors and links, exits; a nil Policy lets everything through.
//
// It is required, since a peer that is let in may exit any process, and
// claim any node name: AdmitTLS admits a peer whose verified certificate
// names its node, and AdmitAll every peer, for a network where whoever
// reaches the server is trusted.
Admit func(ctx context.Context, peer NodeID) (Policy, error)
// Logger defaults to slog.Default().
Logger *slog.Logger
// Hooks is the observability tap; nil means none.
Hooks Hooks
// CopyLocal clones every locally delivered message, so a sender can keep
// mutating what it sent. Off by default: the pointer is shared.
CopyLocal bool
// DialTimeout bounds a dial: resolving the peer, connecting, and the
// handshake. A send that waits for a dial waits at most this long, as
// long as the Resolver and any interceptors in DialOptions honour their
// ctx. Default 5s.
DialTimeout time.Duration
// DialBackoff is the longest a node waits before dialing a peer again
// once dials to it have failed. Meanwhile everything routed to the peer
// fails at once with ErrNoConnection rather than wait for a dial that
// would likely fail too: sends, calls, exits, replies, Downs; a Monitor
// gets Down{noconnection} at once. The first send after the wait dials
// again, and the others keep failing while it does. The first wait is a
// 32nd of DialBackoff, up to a fifth less for jitter. Each further failure
// doubles it, unless the peer was left alone for longer than DialBackoff,
// and a dial that succeeds starts over. A link that ends within
// DialTimeout of coming up counts as a dial that failed, after the wait
// its dial came after: a path that keeps breaking backs off as one that
// cannot be dialed does. A link the peer opens lets the
// next send dial at once, without starting over, since it shows the peer
// is up but not that this node can reach it. Membership reporting the peer
// up (not as an older incarnation than this node has seen), or
// Disconnect, ends the wait. Default 5s; negative dials again at once.
DialBackoff time.Duration
// MaxQueued bounds the link to each peer: while it holds this many
// envelopes not yet written (LinkInfo.Queued), a message or a call to
// the peer fails at once with a *LinkError whose Err is ErrLinkBusy and
// whose Unsent is set, so sending it again later cannot deliver it
// twice. Each peer has a link of its own, so a peer that cannot keep up
// refuses only what is sent to it. Replies, Downs, monitors and exits
// are queued regardless, and count: the peer waits for a reply or a
// Down, and a refused one would have to cut its link to this node. Zero,
// the default, is no bound: a send never fails for a slow peer, and the
// link holds whatever the peer has not yet taken.
MaxQueued int
// MaxMessageSize is the largest message this node sends a peer, encoded,
// metadata included. Every peer's server must take it, through its
// grpc.MaxRecvMsgSize, or it ends the link the message came on, and with
// it every call and monitor there. A message or a call that encodes
// larger fails at once with ErrTooLarge, and is never sent; a reply that
// large reaches its caller as ErrTooLarge instead. Local sends are not
// limited. Default 4 MiB, gRPC's own limit; at least 64 KiB. To raise it,
// raise grpc.MaxRecvMsgSize on every node's server first.
MaxMessageSize int
// MaxQueuedBytes bounds the link to each peer as MaxQueued does, by the
// bytes of the message bodies it holds (LinkInfo.QueuedBytes, counted as
// Bytes is): a message or a call fails while they come to this much, so
// the last one taken can carry the link past it. Zero, the default, is no
// bound.
MaxQueuedBytes int
}
// Node hosts processes and links to peers. It is a plain value the
// application constructs, registers on its gRPC server, starts and stops.
type Node struct {
cfg Config
id NodeID
log *slog.Logger
hooks Hooks
linkBound bound // Config.MaxQueued and MaxQueuedBytes, for messages and calls
ctx context.Context // parent of every process; cancelled first by Stop
cancel context.CancelFunc
dialWG sync.WaitGroup // finishDial goroutines; Stop waits for them
releases sync.WaitGroup // global names given up by processes that exited; Stop waits for them
nextID atomic.Uint64
nextRef atomic.Uint64
started atomic.Int64 // unix nanos, 0 before Start succeeds
startMu sync.Mutex // one Start at a time
withdraw func(context.Context) error // from Registrar; guarded by mu
// pending is the calls waiting for an answer from a peer. pendingMu
// guards it, and nothing is locked while pendingMu is held: every such
// call takes it twice, and shares it with no one else's state. A call to
// a process of this node is not in it (see callLocal).
pendingMu sync.Mutex
pending map[uint64]*pendingCall
// waiters is who waits on a process of this node from outside any
// process (Wait), by the ref of its watch: a Down to the node's own PID
// answers it. waitersMu is a leaf, like pendingMu.
waitersMu sync.Mutex
waiters map[uint64]chan<- string
// mu guards the fields below, through stopped. A process's lock may be
// taken inside it (spawn does), never the reverse. Deliveries, and sends
// over a live link, only read, so they take it shared.
mu sync.RWMutex
procs map[uint64]*proc
names map[string]*proc
out map[string]*outLink
in map[string]*inLink
dialing map[string]*dialOp
backoff map[string]*redial // peers whose last dial failed
dials map[string]uint64 // per peer, for LinkInfo.Reconnects
newest map[string]uint64 // per peer, the newest incarnation seen (see meet)
epochs map[string]uint64 // per peer, the sessions with it that ended (see supersede)
lastIn map[string]helloNo // per peer, the inbound link that went in last (see serveLink)
hellos atomic.Uint64 // numbers the Hellos of inbound links
members map[string]Member // what Membership reports up, by name (see Members)
watched chan struct{} // closed once the Membership's watch ends; nil before Start
stopping bool // Stop began: no new processes
stopped bool // links closed: no new links
// settling counts, per peer, the changes to its links that were decided
// under mu and are still being carried out: a teardown until the peer is
// declared down, a new inbound link until it is announced. A new inbound
// link waits for none to be under way (settled, on mu), so nothing it
// carries overtakes the old session's Downs, and the peer's inbound link
// events come in order. (A dial is not held up: its link carries nothing
// in.)
settling map[string]int
// announcing counts, per peer, the sessions with it that began (see
// linkUp) and are still being announced: the end of one is announced
// only after it, so a peer's link events come up, down, in that order.
announcing map[string]int
settled *sync.Cond
wg sync.WaitGroup
spawned, exited, deadLetters atomic.Uint64
subs subscribers
}
type pendingCall struct {
node string
// ch has room for the one answer. Whoever answers first removes the call
// from n.pending, under n.pendingMu, so no one else can: takePending,
// nodeDown, Stop.
ch chan callResult
}
// takePending removes and returns the call waiting on ref, or nil: the
// caller that gets it answers it.
func (n *Node) takePending(ref uint64) *pendingCall {
n.pendingMu.Lock()
defer n.pendingMu.Unlock()
pc := n.pending[ref]
delete(n.pending, ref)
return pc
}
type callResult struct {
body proto.Message
err error
}
// outcome is what a caller gets for an answer with status. A full mailbox
// is answered STATUS_NOPROC with ReasonMailboxFull, which no handler can
// send, and which nodes that know no limit read as ErrNoProc.
func outcome(body proto.Message, status grpcprocv1.Status, errText string) callResult {
switch status {
case grpcprocv1.Status_STATUS_OK:
return callResult{body: body}
case grpcprocv1.Status_STATUS_NOPROC:
if errText == ReasonMailboxFull {
return callResult{err: ErrMailboxFull}
}
return callResult{err: ErrNoProc}
case grpcprocv1.Status_STATUS_TYPE:
return callResult{err: ErrType}
default:
return callResult{body: body, err: &RemoteError{Msg: errText}}
}
}
// NewNode validates cfg and returns a node that is not yet started.
func NewNode(cfg Config) (*Node, error) {
if cfg.Name == "" || !validName(cfg.Name) {
return nil, errors.New("grpcproc: Config.Name is required, valid UTF-8 and at most 16 KiB")
}
if cfg.Resolver == nil {
return nil, errors.New("grpcproc: Config.Resolver is required")
}
if cfg.Admit == nil {
return nil, errors.New("grpcproc: Config.Admit is required: AdmitTLS admits peers whose certificates name them, AdmitAll every peer")
}
if !validName(cfg.Advertise) {
return nil, errors.New("grpcproc: Config.Advertise must be valid UTF-8 and at most 16 KiB")
}
if !validMetadata(cfg.Metadata) {
return nil, errors.New("grpcproc: Config.Metadata must be valid UTF-8, each key and value at most 16 KiB")
}
if cfg.MaxMessageSize != 0 && cfg.MaxMessageSize < minMessageSize {
return nil, fmt.Errorf("grpcproc: Config.MaxMessageSize is %d, less than %d", cfg.MaxMessageSize, minMessageSize)
}
if cfg.Incarnation == 0 {
cfg.Incarnation = nextIncarnation()
}
cfg.Metadata = maps.Clone(cfg.Metadata)
cfg.Logger = cmp.Or(cfg.Logger, slog.Default())
cfg.DialTimeout = cmp.Or(cfg.DialTimeout, 5*time.Second)
cfg.DialBackoff = cmp.Or(cfg.DialBackoff, 5*time.Second)
cfg.MaxMessageSize = cmp.Or(cfg.MaxMessageSize, 4<<20)
ctx, cancel := context.WithCancel(context.Background())
n := &Node{
cfg: cfg,
id: NodeID{Name: cfg.Name, Incarnation: cfg.Incarnation},
hooks: cfg.Hooks,
ctx: ctx,
cancel: cancel,
procs: map[uint64]*proc{},
names: map[string]*proc{},
pending: map[uint64]*pendingCall{},
waiters: map[uint64]chan<- string{},
out: map[string]*outLink{},
in: map[string]*inLink{},
dialing: map[string]*dialOp{},
backoff: map[string]*redial{},
dials: map[string]uint64{},
newest: map[string]uint64{},
epochs: map[string]uint64{},
lastIn: map[string]helloNo{},
members: map[string]Member{},
settling: map[string]int{},
announcing: map[string]int{},
}
n.settled = sync.NewCond(&n.mu)
n.linkBound = bound{items: int64(cfg.MaxQueued), bytes: int64(cfg.MaxQueuedBytes)}
n.log = cfg.Logger.With("node", cfg.Name)
return n, nil
}
// Register mounts the grpcproc.v1.Node service on s. Call it before the server
// starts serving.
func (n *Node) Register(s grpc.ServiceRegistrar) {
grpcprocv1.RegisterNodeServer(s, linkServer{n: n})
}
// linkServer is the grpcproc.v1.Node service. It is a type of its own so that
// Node's API does not carry the generated server's methods.
type linkServer struct {
grpcprocv1.UnimplementedNodeServer
n *Node
}
// Link serves one inbound link; see serveLink.
func (s linkServer) Link(stream grpc.BidiStreamingServer[grpcprocv1.Frame, grpcprocv1.Frame]) error {
return s.n.serveLink(stream)
}
// Name is the node's logical name.
func (n *Node) Name() string { return n.id.Name }
// ID is the node's name and incarnation.
func (n *Node) ID() NodeID { return n.id }
// PID is the node's own pseudo-process (ID 0): the sender of messages sent
// from outside any process.
func (n *Node) PID() PID { return PID{Node: n.id.Name, Incarnation: n.id.Incarnation} }
// Start watches Membership and publishes the node with its Registrar, when
// configured. Processes may be spawned before Start and run immediately;
// Start only makes the node known. ctx bounds it. A call after one that
// succeeded does nothing; after one that failed, Start tries again, once
// the Membership's watch of the failed one has ended; concurrent calls
// wait for the one in progress; after Stop began, Start fails with
// ErrNodeStopped.
func (n *Node) Start(ctx context.Context) error {
n.startMu.Lock()
defer n.startMu.Unlock()
if n.started.Load() != 0 {
return nil
}
n.mu.Lock()
stopping, previous := n.stopping, n.watched
n.mu.Unlock()
if stopping {
return ErrNodeStopped
}
if previous != nil {
// A Start that failed with its ctx done left its watch to end on the
// Membership's time: no event of it lands on this one's.
select {
case <-previous:
case <-ctx.Done():
return fmt.Errorf("grpcproc: start: the last watch has not ended: %w", context.Cause(ctx))
}
}
now := time.Now()
// A Start that fails undoes itself: it stops watching and waits for the
// watcher to finish, so that no event from it lands after a retry.
watching, unwatch := context.WithCancel(n.ctx)
watched := make(chan struct{})
failed := func(err error) error {
unwatch()
select {
case <-watched:
case <-ctx.Done():
}
return err
}
if m := n.cfg.Membership; m != nil {
stop := context.AfterFunc(ctx, unlabelled(unwatch)) // ctx bounds the Watch call too
events, err := m.Watch(watching)
if !stop() && err == nil {
err = context.Cause(ctx)
}
if err != nil {
close(watched)
return failed(fmt.Errorf("grpcproc: membership: %w", err))
}
n.mu.Lock()
stopping = n.stopping
if !stopping {
n.watched = watched
}
n.mu.Unlock()
go unlabelled(func() {
defer close(watched)
n.watchMembers(events)
})()
if stopping {
// Stop began while this watched: it would not wait for the watch.
return failed(ErrNodeStopped)
}
} else {
close(watched)
}
if names := n.cfg.Names; names != nil {
stop := context.AfterFunc(ctx, unlabelled(unwatch)) // ctx bounds the Watch call too
err := names.Watch(watching)
if !stop() && err == nil {
err = context.Cause(ctx)
}
if err != nil {
return failed(fmt.Errorf("grpcproc: names: %w", err))
}
}
if r := n.cfg.Registrar; r != nil {
withdraw, err := r.Register(ctx, Member{Name: n.id.Name, Incarnation: n.id.Incarnation, Addr: n.cfg.Advertise, Metadata: maps.Clone(n.cfg.Metadata)})
if err != nil {
return failed(fmt.Errorf("grpcproc: register: %w", err))
}
n.mu.Lock()
stopping := n.stopping
if !stopping {
n.withdraw = withdraw
}
n.mu.Unlock()
if stopping {
// Stop began while this registered: it would not withdraw it.
return failed(errors.Join(ErrNodeStopped, withdraw(ctx)))
}
}
n.started.Store(now.UnixNano())
return nil
}
func (n *Node) watchMembers(events <-chan MemberEvent) {
for ev := range events {
m, up, changed := n.recordMember(ev)
if ev.Member.Name != n.id.Name {
n.memberEvent(ev)
}
if changed {
n.memberChanged(m, up)
}
}
}
// recordMember keeps Members up to date: a member reported up replaces one
// of the same name, unless it is an older incarnation, and one reported down
// goes, if it is the incarnation kept or the event says whichever. A member
// whose name, address or metadata could not be a node's own (NewNode) is
// left out, so that whatever lists Members can send them. It returns the
// member listed or unlisted, if the event changed Members.
func (n *Node) recordMember(ev MemberEvent) (m Member, up, changed bool) {
m = ev.Member
listable := m.Name != "" && validName(m.Name) && validName(m.Addr) && validMetadata(m.Metadata)
if ev.Up && !listable {
n.log.Warn("left a member out: its name, address or metadata is not valid UTF-8, or is over 16 KiB", "peer", wireText(m.Name))
}
n.mu.Lock()
defer n.mu.Unlock()
kept, ok := n.members[m.Name]
switch {
case ev.Up && !listable:
// Not listed, but newer than what is kept: that one is gone.
if ok && (m.Incarnation == 0 || m.Incarnation > kept.Incarnation) {
delete(n.members, m.Name)
return kept, false, true
}
case ev.Up && (!ok || m.Incarnation == 0 || m.Incarnation >= kept.Incarnation):
n.members[m.Name] = m
return m, true, !ok || !sameMember(kept, m) // reported again as it is: no change
case !ev.Up && ok && (m.Incarnation == 0 || m.Incarnation == kept.Incarnation):
delete(n.members, m.Name)
return kept, false, true
}
return Member{}, false, false
}
// sameMember says whether two records of a member say the same.
func sameMember(a, b Member) bool {
return a.Name == b.Name && a.Incarnation == b.Incarnation && a.Addr == b.Addr && maps.Equal(a.Metadata, b.Metadata)
}
// memberChanged announces a change to Members: m listed (up) or unlisted.
func (n *Node) memberChanged(m Member, up bool) {
kind, hook := EventMemberDown, Hooks.OnMemberDown
if up {
kind, hook = EventMemberUp, Hooks.OnMemberUp
}
if n.hooks != nil {
hook(n.hooks, m)
}
n.subs.publish(Event{Kind: kind, Member: m})
}
// Members lists the nodes Config.Membership reports up, this one among them
// once it reports it,
// ordered by name, each as the newest incarnation reported and with the
// Metadata it registered: what placement chooses among, by version or zone
// say. It is this node's view, as current as the Membership's events, and
// empty without a Membership. The Metadata maps are shared: do not modify
// them.
func (n *Node) Members() []Member {
n.mu.RLock()
defer n.mu.RUnlock()
return slices.SortedFunc(maps.Values(n.members), func(a, b Member) int { return cmp.Compare(a.Name, b.Name) })
}
// Member returns the member named name, as Members has it.
func (n *Node) Member(name string) (Member, bool) {
n.mu.RLock()
defer n.mu.RUnlock()
m, ok := n.members[name]
return m, ok
}
// memberEvent drops the links to a peer that left, or that came back as a
// newer incarnation: either way, whatever crossed those links is gone. An
// older incarnation reported up is ignored, as a link from it is refused.
// Once the newest incarnation has left, no incarnation is refused.
func (n *Node) memberEvent(ev MemberEvent) {
peer := NodeID{Name: ev.Member.Name, Incarnation: ev.Member.Incarnation}
n.mu.Lock()
var cause error
restarted := false
switch newest := n.newest[peer.Name]; {
case !ev.Up:
// The links with a peer are with its newest incarnation.
if newest != 0 && (peer.Incarnation == newest || peer.Incarnation == 0) {
delete(n.newest, peer.Name)
cause = errors.New("left the cluster")
}
case peer.Incarnation == 0: // up, as whichever incarnation it is
n.forget(peer.Name)
default:
var stale error
if cause, stale = n.meet(peer); stale != nil {
n.mu.Unlock()
n.log.Warn("ignored an old incarnation reported up", "peer", peer, "err", stale)
return
}
n.forget(peer.Name) // it is back: dial it at once
restarted = cause != nil
}
// The links judged are the links dropped: taken in the same critical
// section, not one that may have replaced them since.
var out *outLink
var in *inLink
if cause != nil {
out, in = n.takeLinks(peer.Name)
}
if restarted {
delete(n.epochs, peer.Name) // a new incarnation counts from 0
}
n.mu.Unlock()
if out != nil || in != nil {
n.linksLost(out, in, cause)
}
}
// Stop asks every process to exit (Receive returns ReasonShutdown), waits for
// them until ctx is done, and for the Membership's watch to end, which it
// does once its ctx is, then closes every link. Watchers of this node's
// processes receive Down{shutdown} while the links are still up: every
// outbound link flushes, and is waited on until its peer ends it, or ctx is
// done. A dial in flight completes within Config.DialTimeout and its link is
// discarded; Stop waits for it too, until ctx is done. If ctx cuts any of
// these waits short, Stop returns its error. The Registrar's withdraw comes
// last, and gets a second of its own if ctx is done by then.
func (n *Node) Stop(ctx context.Context) error {
n.mu.Lock()
if n.stopping {
n.mu.Unlock()
return nil
}
n.stopping = true
n.mu.Unlock()
n.cancel()
done := make(chan struct{})
go unlabelled(func() { n.wg.Wait(); close(done) })()
var err error
select {
case <-done:
case <-ctx.Done():
err = fmt.Errorf("grpcproc: stop: %w", ctx.Err())
}
// The Membership closes its channel once its ctx is done: no member
// hook or event comes once Stop has returned.
n.mu.Lock()
watched := n.watched
n.mu.Unlock()
if watched != nil {
select {
case <-watched:
case <-ctx.Done():
if err == nil {
err = fmt.Errorf("grpcproc: stop: %w", ctx.Err())
}
}
}
n.mu.Lock()
n.stopped = true
outs, ins := n.out, n.in
n.out, n.in = map[string]*outLink{}, map[string]*inLink{}
n.mu.Unlock()
n.settled.Broadcast() // a dial or a link waiting for a peer's links to settle gives up
// Let the Down{shutdown} envelopes reach their peers before the links go:
// every link flushes at once, then each is waited for.
for _, l := range outs {
l.shutdown()
}
flushed := true
for _, l := range outs {
if l.finish(ctx) {
flushed = false
}
}
if !flushed && err == nil {
err = fmt.Errorf("grpcproc: stop: %w", ctx.Err())
}
for _, l := range ins {
l.close()
}
// A link that came up before the node stopped may still be announced
// (OnLinkUp): no hook runs once Stop has returned.
announced := make(chan struct{})
go unlabelled(func() {
n.mu.Lock()
for len(n.announcing) > 0 {
n.settled.Wait()
}
n.mu.Unlock()
close(announced)
})()
select {
case <-announced:
case <-ctx.Done():
if err == nil {
err = fmt.Errorf("grpcproc: stop: %w", ctx.Err())
}
}
// Calls still waiting on a peer will get no answer, and nothing declares
// the peers down any more: fail them. They may have been handled.
n.pendingMu.Lock()
pending := n.pending
n.pending = map[uint64]*pendingCall{}
n.pendingMu.Unlock()
for _, pc := range pending {
pc.ch <- callResult{err: ErrNodeStopped}
}
// So will local calls still open on processes that outlived the wait.
n.mu.RLock()
procs := slices.Collect(maps.Values(n.procs))
n.mu.RUnlock()
for _, p := range procs {
p.failLocalCalls(ErrNodeStopped)
}
// A dial that was in flight when the node stopped completes, and
// finishDial discards its link: wait for it to let go of the node. One
// that installed its link may still be announcing it, so every dial is
// waited for, not only those under way.
dialed := make(chan struct{})
go unlabelled(func() { n.dialWG.Wait(); close(dialed) })()
select {
case <-dialed:
case <-ctx.Done():
if err == nil {
err = fmt.Errorf("grpcproc: stop: %w", ctx.Err())
}
}
// Global names its processes held are given up before the node is
// withdrawn, which, with etcd, would drop them all at once anyway.
released := make(chan struct{})
go unlabelled(func() { n.releases.Wait(); close(released) })()
select {
case <-released:
case <-ctx.Done():
if err == nil {
err = fmt.Errorf("grpcproc: stop: %w", ctx.Err())
}
}
n.mu.Lock()
withdraw := n.withdraw
n.mu.Unlock()
if withdraw != nil {
// Withdrawing is what tells the cluster this node is gone; one peer
// that never ended its stream must not leave it published.
wctx, cancel := context.WithCancel(ctx)
if ctx.Err() != nil {
wctx, cancel = context.WithTimeout(context.WithoutCancel(ctx), time.Second)
}
defer cancel()
if werr := withdraw(wctx); werr != nil {
err = errors.Join(err, fmt.Errorf("grpcproc: withdraw: %w", werr))
}
}
return err
}
// ---------- registry & inspection ----------
// Whereis resolves a name registered on this node.
func (n *Node) Whereis(name string) (PID, bool) {
n.mu.RLock()
defer n.mu.RUnlock()
if p := n.names[name]; p != nil {
return p.pid, true
}
return PID{}, false
}
// Processes snapshots every local process, ordered by PID.
func (n *Node) Processes() []ProcessInfo {
n.mu.RLock()
procs := slices.Collect(maps.Values(n.procs))
n.mu.RUnlock()
slices.SortFunc(procs, func(a, b *proc) int { return cmp.Compare(a.pid.ID, b.pid.ID) }) // PIDs never change
out := make([]ProcessInfo, len(procs))
for i, p := range procs {
out[i] = p.info()
}
return out
}
// Process snapshots one local process.
func (n *Node) Process(pid PID) (ProcessInfo, bool) {
p := n.local(pid)
if p == nil {
return ProcessInfo{}, false
}
return p.info(), true
}
// Inspect asks a local process what it currently believes: the map its
// WithInspect function returns, produced on the process's own goroutine
// between two messages. A process busy in a handler answers when it next
// calls Receive; ctx bounds the wait, and the error then wraps ctx.Err(). A
// process that is gone, or exits before answering (its inspect function
// panicked), is ErrNoProc.
func (n *Node) Inspect(ctx context.Context, pid PID) (map[string]string, error) {
p := n.local(pid)
if p == nil {
return nil, ErrNoProc
}
return p.inspectNow(ctx)
}
// Query asks a local process q, through the function it was spawned with
// WithQuery, and returns its answer, google.protobuf.Empty for none: ErrNoProc
// itself if it does not run here, ErrNoQuery itself if it answers no queries,
// or the function's error as it returned it.
func (n *Node) Query(ctx context.Context, pid PID, q proto.Message) (answer proto.Message, err error) {
p := n.local(pid)
switch {
case p == nil:
return nil, ErrNoProc
case p.query == nil:
return nil, ErrNoQuery
}
defer func() {
if r := recover(); r != nil {
answer, err = nil, fmt.Errorf("grpcproc: query %s panicked: %v", pid, r)
}
}()
answer, err = p.query(ctx, q)
if answer == nil && err == nil {
answer = &emptypb.Empty{}
}
return answer, err
}
// SetLogLevel sets the threshold of a local process's Log() at runtime.
func (n *Node) SetLogLevel(pid PID, level slog.Level) error {
p := n.local(pid)
if p == nil {
return ErrNoProc
}
p.level.Store(int64(level))
p.levelSet.Store(true)
return nil
}
// Info snapshots the node.
func (n *Node) Info() NodeInfo {
n.mu.Lock()
info := NodeInfo{
ID: n.id,
Advertise: n.cfg.Advertise,
Metadata: maps.Clone(n.cfg.Metadata),
Processes: len(n.procs),
Spawned: n.spawned.Load(),
Exited: n.exited.Load(),
DeadLetters: n.deadLetters.Load(),
}
if s := n.started.Load(); s != 0 {
info.StartedAt = time.Unix(0, s)
}
for _, l := range n.out {
li := l.info()
li.Sessions = n.epochs[l.peer.Name]
info.Links = append(info.Links, li)
}
for peer := range n.backoff {
if r := n.backedOff(peer); r != nil {
info.Links = append(info.Links, LinkInfo{
Peer: NodeID{Name: peer}, Outbound: true, State: LinkDown,
Reconnects: n.dials[peer], LastError: r.why, RetryAt: r.at, Sessions: n.epochs[peer],
})
}
}
for _, l := range n.in {
li := l.info()
li.Sessions = n.epochs[l.peer.Name]
info.Links = append(info.Links, li)
}
n.mu.Unlock()
// Outbound links were collected first, so a stable sort by peer keeps
// each peer's outbound link ahead of its inbound one.
slices.SortStableFunc(info.Links, func(a, b LinkInfo) int { return cmp.Compare(a.Peer.Name, b.Peer.Name) })
return info
}
var (
// errDisconnected is why Disconnect dropped a link, or a dial.
errDisconnected = errors.New("disconnected")
// errSessionEnded is why a dial's link was dropped: this node ended its
// session with the peer while it dialed (see finishDial).
errSessionEnded = errors.New("the session it was dialed in ended")
// errUnread is why a session ended when a link from the peer came after
// its next one, and was not read (see serveLink).
errUnread = errors.New("a link from it came after its next one, unread")
)
// Disconnect drops every link with peer, and a dial to it under way, as if
// the network had, and forgets that dials to it failed (Config.DialBackoff)
// and which incarnation of it this node has seen, so that none is refused
// (see Config.Incarnation). Monitors across it fire Down{noconnection} and
// pending calls fail, as do sends waiting for the dial; the next send dials
// again. It reports whether there was a link to drop.
func (n *Node) Disconnect(peer string) bool {
n.mu.Lock()
n.forget(peer)
if d := n.dialing[peer]; d != nil {
d.disconnected = true
}
delete(n.newest, peer)
out, in := n.takeLinks(peer)
n.mu.Unlock()
if out == nil && in == nil {
return false
}
n.linksLost(out, in, errDisconnected)
return true
}
// Peers lists nodes with a live link in either direction.
func (n *Node) Peers() []string {
n.mu.RLock()
defer n.mu.RUnlock()
seen := make(map[string]struct{}, len(n.out)+len(n.in))
for p := range n.out {
seen[p] = struct{}{}
}
for p := range n.in {
seen[p] = struct{}{}
}
return slices.Sorted(maps.Keys(seen))
}
// Dial opens a connection to peer's gRPC server as the node reaches it,
// through Config.Resolver and with Config.DialOptions and DialOptionsFor,
// credentials and all:
// for a service registered there beside grpcproc's own, the peer's Inspector
// say. ctx bounds resolving peer's address. The connection is the caller's
// to close; the node's links do not use it.
func (n *Node) Dial(ctx context.Context, peer string) (*grpc.ClientConn, error) {
addr, err := n.cfg.Resolver.Resolve(ctx, peer)
if err != nil {
return nil, err
}
return grpc.NewClient(addr, n.dialOptions(peer)...)
}
// dialOptions are the options for connections to peer: Config.DialOptions,
// then whatever DialOptionsFor adds, which therefore wins.
func (n *Node) dialOptions(peer string) []grpc.DialOption {
if n.cfg.DialOptionsFor == nil {
return n.cfg.DialOptions
}
return append(slices.Clip(n.cfg.DialOptions), n.cfg.DialOptionsFor(peer)...)
}
// Membership returns Config.Membership, or nil: for a component that follows
// the cluster as the node does, grpcproc/leader say.
func (n *Node) Membership() Membership { return n.cfg.Membership }
func (n *Node) local(pid PID) *proc {
if pid.Node != n.id.Name || pid.Incarnation != n.id.Incarnation {
return nil
}
n.mu.RLock()
defer n.mu.RUnlock()
return n.procs[pid.ID]
}
// lookup resolves a delivery target on this node. A PID from another
// incarnation resolves to nothing.
func (n *Node) lookup(pid PID, name string) *proc {
n.mu.RLock()
defer n.mu.RUnlock()
if name != "" {
return n.names[name]
}
if pid.Incarnation != n.id.Incarnation {