-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.go
1145 lines (960 loc) · 23.6 KB
/
agent.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
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 fleet
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand"
"net"
"net/http"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/KarpelesLab/jwt"
"github.com/KarpelesLab/rchan"
"github.com/KarpelesLab/ringbuf"
bolt "go.etcd.io/bbolt"
)
type GetFileFunc func(*Agent, string) ([]byte, error)
type Agent struct {
socket net.Listener
id string
name string
division string
hostname string // only the hostname side
IP string // ip as seen from outside
cache string // location of cache
inCfg *tls.Config
outCfg *tls.Config
ca *x509.CertPool
announceIdx uint64
peers map[string]*Peer
peersMutex sync.RWMutex
peersCount uint32
port int // random
services map[string]chan net.Conn
svcMutex sync.RWMutex
transport http.RoundTripper
status int // 0=waiting 1=ready
statusLock sync.RWMutex
statusCond *sync.Cond
// log
logbuf *ringbuf.Writer
// DB
db *bolt.DB
dbWatch map[string][]DbWatchCallback
dbWatchLock sync.RWMutex
// Meta-info
meta map[string]any
metaLk sync.RWMutex
// getfile callback
GetFile GetFileFunc
// seed: use a pointer for atomic seed details update
seed *seedData
// locking
globalLocks map[string]*globalLock
globalLocksLk sync.RWMutex
// cert cache
pubCert *crtCache
intCert *crtCache
// settings
settings map[string]any
settingsUpdated time.Time
}
// New will just initialize a basic agent without any settings
func New(opts ...AgentOption) *Agent {
a := spawn()
for _, o := range opts {
o.apply(a)
}
a.start()
return a
}
// return a new agent using the provided GetFile method
func WithGetFile(f GetFileFunc, opts ...AgentOption) *Agent {
return New(append([]AgentOption{f}, opts...)...)
}
func spawn() *Agent {
local := "local"
if host, err := os.Hostname(); err == nil && host != "" {
local = host
}
a := &Agent{
id: local,
name: local,
port: 61337,
peers: make(map[string]*Peer),
services: make(map[string]chan net.Conn),
dbWatch: make(map[string][]DbWatchCallback),
globalLocks: make(map[string]*globalLock),
}
a.pubCert = &crtCache{a: a, k: "public_key"}
a.intCert = &crtCache{a: a, k: "internal_key"}
a.statusCond = sync.NewCond(a.statusLock.RLocker())
runtime.SetFinalizer(a, closeAgentect)
return a
}
func (a *Agent) start() {
// perform various start actions
a.initLog()
a.initPath()
a.initDb()
a.initSeed()
a.directoryThread()
a.channelSet()
// only setSelf() after everything has been started so we know Self() returns a ready instance
setSelf(a)
}
func closeAgentect(a *Agent) {
a.Close()
}
func (a *Agent) Close() {
a.shutdownDb()
a.shutdownLog()
}
func (a *Agent) GetStatus() int {
a.statusLock.RLock()
defer a.statusLock.RUnlock()
return a.status
}
func (a *Agent) setStatus(s int) {
a.statusLock.Lock()
defer a.statusLock.Unlock()
a.status = s
a.statusCond.Broadcast()
}
// WaitReady will lock until the agent is ready for operation (connected to other peers)
func (a *Agent) WaitReady() {
a.statusLock.RLock()
defer a.statusLock.RUnlock()
for {
if a.status == 1 {
return
}
a.statusCond.Wait()
}
}
func (a *Agent) doInit(token *jwt.Token) (err error) {
if token != nil {
// update info based on jwt data
if id := token.Payload().GetString("id"); id != "" {
a.id = id
}
if name := token.Payload().GetString("nam"); name != "" {
a.name = name
}
if div := token.Payload().GetString("loc"); div != "" {
a.division = div
}
if iss := token.Payload().GetString("iss"); iss != "" {
a.hostname = iss
}
}
// load CA
a.ca, _ = a.GetCA()
// create tls.Config objects
a.inCfg = new(tls.Config)
a.outCfg = new(tls.Config)
// set certificates
a.inCfg.GetCertificate = a.intCert.GetCertificate
a.outCfg.GetClientCertificate = a.intCert.GetClientCertificate
a.inCfg.RootCAs = a.ca
a.outCfg.RootCAs = a.ca
a.inCfg.NextProtos = []string{"fssh", "fbin", "p2p"}
// configure client auth
a.inCfg.ClientAuth = tls.RequireAndVerifyClientCert
a.inCfg.ClientCAs = a.ca
if a.socket == nil {
sock, err := net.ListenTCP("tcp", &net.TCPAddr{Port: a.port})
if err != nil {
log.Printf("[agent] failed to listen: %s", err)
return err
}
// update a.port (will be the same value if it wasn't 0)
a.port = sock.Addr().(*net.TCPAddr).Port
a.socket = tls.NewListener(sock, a.inCfg)
log.Printf("[agent] Listening on :%d", a.port)
}
// create a transport object for http queries
a.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: a.DialContext,
DialTLS: a.Dial,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
go a.listenLoop()
go a.eventLoop()
return
}
func (a *Agent) Id() string {
return a.id
}
func (a *Agent) Name() (string, string) {
return a.name, a.hostname
}
func (a *Agent) BroadcastRpc(ctx context.Context, endpoint string, data any) error {
// send request
pkt := &PacketRpc{
SourceId: a.id,
Endpoint: endpoint,
Data: data,
}
peers := a.GetPeers()
if len(peers) == 0 {
return nil
}
for _, p := range peers {
if p.id == a.id {
// do not send to self
continue
}
// do in gorouting in case connection lags or fails and triggers call to unregister that deadlocks because we hold a lock
pkt2 := &PacketRpc{}
*pkt2 = *pkt
pkt2.TargetId = p.id
go p.Send(ctx, pkt2)
}
return nil
}
func (a *Agent) BroadcastPacket(ctx context.Context, pc uint16, data []byte) error {
peers := a.GetPeers()
if len(peers) == 0 {
return nil // nothing to do
}
var wg sync.WaitGroup
for _, p := range peers {
wg.Add(1)
go func(p *Peer) {
defer wg.Done()
p.WritePacket(ctx, pc, data)
}(p)
}
wg.Wait()
return nil
}
func (a *Agent) broadcastDbRecord(ctx context.Context, bucket, key, val []byte, v DbStamp) error {
pkt := &PacketDbRecord{
SourceId: a.id,
Stamp: v,
Bucket: bucket,
Key: key,
Val: val,
}
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()
if len(a.peers) == 0 {
return nil
}
for _, p := range a.peers {
if p.id == a.id {
// do not send to self
continue
}
// do in gorouting in case connection lags or fails and triggers call to unregister that deadlocks because we hold a lock
pkt2 := &PacketDbRecord{}
*pkt2 = *pkt
pkt2.TargetId = p.id
go p.Send(ctx, pkt2)
}
return nil
}
type rpcChoiceStruct struct {
routines uint32
peer *Peer
}
func (a *Agent) AnyRpc(ctx context.Context, division string, endpoint string, data any) error {
// send request
pkt := &PacketRpc{
SourceId: a.id,
Endpoint: endpoint,
Data: data,
}
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()
if len(a.peers) == 0 {
return errors.New("no peer available")
}
var choices []rpcChoiceStruct
for _, p := range a.peers {
if p.id == a.id {
// do not send to self
continue
}
if division != "" && p.division != division {
continue
}
choices = append(choices, rpcChoiceStruct{routines: p.numG, peer: p})
}
sort.SliceStable(choices, func(i, j int) bool { return choices[i].routines < choices[j].routines })
for _, i := range choices {
// do in gorouting in case connection lags or fails and triggers call to unregister that deadlocks because we hold a lock
pkt.TargetId = i.peer.id
atomic.AddUint32(&i.peer.numG, 1) // increment value to avoid sending bursts to the same node
go i.peer.Send(ctx, pkt)
return nil
}
return errors.New("no peer available")
}
func (a *Agent) DivisionRpc(ctx context.Context, division int, endpoint string, data any) error {
divMatch := a.division
if division > 0 {
// only keep the N first parts of divison. Eg if N=2 and "divMatch" is "a/b/c", divMatch should become "a/b/"
pos := 0
for i := 0; i < division; i += 1 {
Xpos := strings.IndexByte(divMatch[pos+1:], '/')
if Xpos == -1 {
// do exact match
pos = -1
break
}
pos += Xpos + 1
}
if pos > 0 {
divMatch = divMatch[:pos+1]
}
} else if division < 0 {
// only remove N last parts of division. If N=-1, "a/b/c" becomes "a/b/"
pos := len(divMatch)
for i := 0; i < 0-division; i += 1 {
if pos <= 1 {
// out of match, just go wildcard
pos = -1
break
}
Xpos := strings.LastIndexByte(divMatch[:pos-1], '/')
if Xpos == -1 {
// wildcard
pos = -1
break
}
pos = Xpos
}
if pos > 0 {
divMatch = divMatch[:pos]
} else {
// wildcard match
divMatch = ""
}
}
return a.DivisionPrefixRpc(ctx, divMatch, endpoint, data)
}
func (a *Agent) DivisionPrefixRpc(ctx context.Context, divMatch string, endpoint string, data any) error {
// send request
pkt := &PacketRpc{
SourceId: a.id,
Endpoint: endpoint,
Data: data,
}
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()
if len(a.peers) == 0 {
return nil
}
for _, p := range a.peers {
if p.id == a.id {
// do not send to self
continue
}
if !strings.HasPrefix(p.division, divMatch) {
continue
}
// do in gorouting in case connection lags or fails and triggers call to unregister that deadlocks because we hold a lock
pkt2 := &PacketRpc{}
*pkt2 = *pkt
pkt2.TargetId = p.id
go p.Send(ctx, pkt2)
}
return nil
}
func (a *Agent) AllRPC(ctx context.Context, endpoint string, data any) ([]any, error) {
// call method on ALL hosts and collect responses
// put a timeout on context just in case
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// build response pipe
id, res := rchan.New()
defer id.Release()
// prepare request
pkt := &PacketRpc{
SourceId: a.id,
R: id,
Endpoint: endpoint,
Data: data,
}
// send request
n, err := a.broadcastRpcPacket(ctx, pkt)
if err != nil {
return nil, err
}
if n == 0 {
// no error, no nothing
return nil, nil
}
// collect responses
var final []any
for {
select {
case vany := <-res:
v, ok := vany.(*PacketRpcResponse)
if !ok {
continue
}
if v.HasError {
final = append(final, errors.New(v.Error))
} else {
final = append(final, v.Data)
}
if len(final) == n {
return final, nil
}
case <-ctx.Done():
return final, ctx.Err()
}
}
}
func (a *Agent) AllRpcRequest(ctx context.Context, endpoint string, data []byte) ([]any, error) {
// call method on ALL hosts and collect responses
if len(endpoint) > 65535 {
return nil, errors.New("RPC endpoint name length too long")
}
// put a timeout on context just in case
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// build response pipe
id, res := rchan.New()
defer id.Release()
buf := make([]byte, 14)
binary.BigEndian.PutUint64(buf[:8], uint64(id))
binary.BigEndian.PutUint32(buf[8:12], 0) // flags
binary.BigEndian.PutUint16(buf[12:14], uint16(len(endpoint)))
buf = append(append(buf, endpoint...), data...)
// send request
n := 0
for _, p := range a.GetPeers() {
if p.id == a.id {
continue
}
n += 1
go func(p *Peer) {
err := p.WritePacket(ctx, PacketRpcBinReq, buf)
if err != nil {
id.Send(ctx, err)
}
}(p)
}
// collect responses
var final []any
for {
select {
case v := <-res:
final = append(final, v)
if len(final) == n {
return final, nil
}
case <-ctx.Done():
return final, ctx.Err()
}
}
}
func (a *Agent) broadcastRpcPacket(ctx context.Context, pkt *PacketRpc) (n int, err error) {
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()
if len(a.peers) == 0 {
return
}
for _, p := range a.peers {
if p.id == a.id {
// do not send to self
continue
}
n += 1
// do in gorouting in case connection lags or fails and triggers call to unregister that deadlocks because we hold a lock
pkt2 := &PacketRpc{}
*pkt2 = *pkt
pkt2.TargetId = p.id
go p.Send(ctx, pkt2)
}
return
}
func (a *Agent) BroadcastRpcBin(ctx context.Context, endpoint string, pkt []byte) (n int, err error) {
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()
if len(a.peers) == 0 {
return
}
var wg sync.WaitGroup
for _, p := range a.peers {
if p.id == a.id {
// do not send to self
continue
}
n += 1
wg.Add(1)
// do in gorouting in case connection lags or fails and triggers call to unregister that deadlocks because we hold a lock
go func() {
defer wg.Done()
p.ssh.SendRequest("rpc/"+endpoint, false, pkt)
}()
}
// wait for all sends to end to make sure pkt can be re-used
wg.Wait()
return
}
func (a *Agent) RpcRequest(ctx context.Context, id string, endpoint string, data []byte) ([]byte, error) {
if len(endpoint) > 65535 {
return nil, errors.New("RPC endpoint name length too long")
}
// send data to given peer
p := a.GetPeer(id)
if p == nil {
return nil, errors.New("failed to find peer")
}
resId, res := rchan.New()
defer resId.Release()
buf := make([]byte, 14)
binary.BigEndian.PutUint64(buf[:8], uint64(resId))
binary.BigEndian.PutUint32(buf[8:12], 0) // flags
binary.BigEndian.PutUint16(buf[12:14], uint16(len(endpoint)))
buf = append(append(buf, endpoint...), data...)
err := p.WritePacket(ctx, PacketRpcBinReq, buf)
if err != nil {
return nil, err
}
final := <-res
switch v := final.(type) {
case error:
return nil, v
case []byte:
return v, nil
default:
return nil, fmt.Errorf("unsupported response type %T", final)
}
}
// RpcSend sends a request but expects no response, failure will only reported if the request failed to be
// sent, and failure on the other side will not be reported
func (a *Agent) RpcSend(ctx context.Context, id string, endpoint string, data []byte) error {
p := a.GetPeer(id)
if p == nil {
return errors.New("failed to find peer")
}
_, _, err := p.ssh.SendRequest("rpc/"+endpoint, false, data)
if err != nil {
log.Printf("[fleet] failed sending RPC packet to peer %s: %s", p.name, err)
}
return err
}
func (a *Agent) RPC(ctx context.Context, id string, endpoint string, data any) (any, error) {
p := a.GetPeer(id)
if p == nil {
return nil, errors.New("failed to find peer")
}
resId, res := rchan.New()
defer resId.Release()
// send request
pkt := &PacketRpc{
TargetId: id,
SourceId: a.id,
R: resId,
Endpoint: endpoint,
Data: data,
}
p.Send(ctx, pkt)
// get response
select {
case rany := <-res:
r, ok := rany.(*PacketRpcResponse)
if !ok {
return nil, errors.New("invalid response type")
}
if r == nil {
return nil, errors.New("failed to wait for response")
}
err := error(nil)
if r.HasError {
err = errors.New(r.Error)
}
return r.Data, err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (a *Agent) handleRpcBin(peer *Peer, buf []byte) error {
if len(buf) < 14 {
return errors.New("packet too small")
}
// buf format:
// <reqId>:uint64
// <flags>:uint32
// <endpointNameLen>:uint16
// <endpointName>:string
// <data>
id := binary.BigEndian.Uint64(buf[:8])
flags := binary.BigEndian.Uint32(buf[8:12])
pfx := buf[:12]
ln := binary.BigEndian.Uint16(buf[12:14])
if len(buf) < 14+int(ln) {
return errors.New("packet too small 2")
}
endpoint := string(buf[14 : int(ln)+14])
buf = buf[int(ln)+14:]
go func() {
data, err := CallRpcEndpoint(endpoint, buf)
if id == 0 {
// do not send any response
return
}
dataB, ok := data.([]byte)
if !ok {
err = errors.New("RPC method did not return []byte")
}
if err != nil {
// report error
flags |= 0x10000 // ="error"
dataB = []byte(err.Error())
}
res := append(pfx, dataB...)
binary.BigEndian.PutUint32(res[:4], flags) // update flags if needed
// return result by sending packet
peer.WritePacket(context.Background(), PacketRpcBinRes, res)
}()
return nil
}
func (a *Agent) handleRpcBinResponse(peer *Peer, buf []byte) error {
if len(buf) < 12 {
return errors.New("invalid buffer length for response")
}
id := rchan.Id(binary.BigEndian.Uint64(buf[:8]))
c := id.C()
if c == nil {
return nil
}
flags := binary.BigEndian.Uint32(buf[8:12])
buf = buf[12:]
val := any(buf)
if flags&0x10000 == 0x10000 {
// error
val = errors.New(string(buf))
}
go func() {
t := time.NewTimer(time.Second)
defer t.Stop()
select {
case c <- val:
case <-t.C:
// timeout
}
}()
return nil
}
func (a *Agent) handleRpc(pkt *PacketRpc) error {
res := PacketRpcResponse{
SourceId: a.id,
TargetId: pkt.SourceId,
R: pkt.R,
}
ctx := context.Background()
if pkt.R == 0 {
// no return
CallRpcEndpoint(pkt.Endpoint, pkt.Data)
return nil
}
func() {
var err error
res.Data, err = CallRpcEndpoint(pkt.Endpoint, pkt.Data)
if err != nil {
res.Error = err.Error()
res.HasError = true
}
}()
return a.SendTo(ctx, res.TargetId, res)
}
func (a *Agent) handleRpcResponse(pkt *PacketRpcResponse) error {
c := pkt.R.C()
if c == nil {
return nil
}
t := time.NewTimer(time.Second)
defer t.Stop()
select {
case c <- pkt:
// OK
return nil
case <-t.C:
// timeout
return nil
}
}
func (a *Agent) dialPeer(host string, port int, name string, id string, alt []string) {
if id == a.id {
// avoid connect to self
return
}
if port == 0 {
port = a.port
}
// random delay before connect
time.Sleep(time.Duration(rand.Intn(1500)+200) * time.Millisecond)
// check if already connected
if a.IsConnected(id) {
return
}
cfg := a.outCfg.Clone()
cfg.ServerName = id
cfg.NextProtos = []string{"fssh", "fbin"}
// handle alt IPs and try these first
if len(alt) > 0 {
// typically alt ips are in the CIDR format, we want to re-format these as host:port
c, err := tlsDialAll(context.Background(), 5*time.Second, formatAltAddrs(host, alt, port), cfg)
if err == nil {
// success!
go a.newConn(c, false)
return
}
log.Printf("[fleet] Alt connection failed, will attempt regular connection: %s", err)
}
c, err := tls.Dial("tcp", host+":"+strconv.FormatInt(int64(port), 10), cfg)
if err != nil {
log.Printf("[fleet] failed to connect to peer %s(%s): %s", name, id, err)
return
}
go a.newConn(c, false)
}
func (a *Agent) IsConnected(id string) bool {
if id == a.id {
// we are "connected" to self
return true
}
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()
_, ok := a.peers[id]
return ok
}
func (a *Agent) listenLoop() {
for {
conn, err := a.socket.Accept()
if err != nil {
log.Printf("[fleet] failed to accept connections: %s", err)
return
}
go a.newConn(conn, true)
}
}
func (a *Agent) eventLoop() {
announce := time.NewTicker(30 * time.Second)
for range announce.C {
a.doAnnounce()
}
}
func (a *Agent) doAnnounce() {
peers := a.GetPeers()
if len(peers) == 0 {
return
}
x := atomic.AddUint64(&a.announceIdx, 1)
pkt := &PacketAnnounce{
Id: a.id,
Now: time.Now(),
Idx: x,
AZ: a.division,
NumG: uint32(runtime.NumGoroutine()),
Meta: a.copyMeta(),
}
//log.Printf("[agent] broadcasting announce %+v to %d peers", pkt, len(peers))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var wg sync.WaitGroup
for _, p := range peers {
// do in gorouting in case connection lags or fails and triggers call to unregister that deadlocks because we hold a lock
wg.Add(1)
go func(p *Peer) {
defer wg.Done()
err := p.Send(ctx, pkt)
if err != nil {
log.Printf("[agent] failed to send announce to %s: %s", p.id, err)
}
}(p)
}
wg.Wait()
}
func (a *Agent) DumpInfo(w io.Writer) {
fmt.Fprintf(w, "Fleet Agent Information\n")
fmt.Fprintf(w, "=======================\n\n")
fmt.Fprintf(w, "Local name: %s\n", a.name)
fmt.Fprintf(w, "Division: %s\n", a.division)
fmt.Fprintf(w, "Local ID: %s\n", a.id)
fmt.Fprintf(w, "Seed ID: %s (seed stamp: %s)\n", a.SeedId(), a.seed.ts)
if tk := tpmKeyObject; tk != nil {
// we have a tpm key
fmt.Fprintf(w, "TPM key: YES\n")
}
fmt.Fprintf(w, "\n")
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()
t := make(sortablePeers, 0, len(a.peers))
for _, p := range a.peers {
t = append(t, p)
}
// sort
sort.Sort(t)
for _, p := range t {
fmt.Fprintf(w, "Peer: %s (%s)\n", p.name, p.id)
fmt.Fprintf(w, "Division: %s\n", p.division)
fmt.Fprintf(w, "Endpoint: %s\n", p.RemoteAddr())
fmt.Fprintf(w, "Connected:%s (%s ago)\n", p.cnx, time.Since(p.cnx))
fmt.Fprintf(w, "Protocol: %s\n", p.protocol)
fmt.Fprintf(w, "Last Ann: %s\n", time.Since(p.annTime))
fmt.Fprintf(w, "Latency: %s\n", p.Ping)
fmt.Fprintf(w, "Offset: %s\n", p.timeOfft)
fmt.Fprintf(w, "Routines: %d\n", p.numG)
fmt.Fprintf(w, "\n")
}
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "DB keys:\n")
for _, bk := range []string{"fleet", "global", "app"} {
var l []string
if c, err := a.NewDbCursor([]byte(bk)); err == nil {
defer c.Close()
k, _ := c.First()
for {
if k == nil {
break
}
l = append(l, string(k))
k, _ = c.Next()
}
}
fmt.Fprintf(w, "%s: %v\n", bk, l)
}
}
func (a *Agent) GetPeer(id string) *Peer {
a.peersMutex.RLock()
defer a.peersMutex.RUnlock()