-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathagent.go
More file actions
1567 lines (1439 loc) · 35.7 KB
/
agent.go
File metadata and controls
1567 lines (1439 loc) · 35.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 main
import (
"bytes"
"encoding/json"
"fmt"
"net"
"os"
"reflect"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
etcd "github.com/coreos/etcd/client"
"golang.org/x/net/context"
"github.com/docker/leadership"
"github.com/docker/libkv"
"github.com/docker/libkv/store"
kvetcd "github.com/docker/libkv/store/etcd"
"github.com/fsouza/go-dockerclient"
lainlet "github.com/laincloud/lainlet/client"
"github.com/projectcalico/libcalico-go/lib/api"
calicoetcd "github.com/projectcalico/libcalico-go/lib/backend/etcd"
calico "github.com/projectcalico/libcalico-go/lib/client"
"github.com/laincloud/networkd/acl"
"github.com/laincloud/networkd/godns"
"github.com/laincloud/networkd/apiserver"
)
const (
LockerStateNone = iota // no lock
LockerStateCreated = iota // create locker
LockerStateLocked = iota // locked && lock by me
LockerStateUnlocked = iota // locked && not lock by me
LockerStateDeleted = iota // delete locker
LockerStateError = iota
)
const (
DOMAINLAIN = "lain"
)
type LockedIp struct {
ip string
modifiedIndex uint64
}
type Agent struct {
ip string
iface string
hostname string
domain string
lockedIps []LockedIp
libnetwork bool
wg sync.WaitGroup
docker *docker.Client
etcd *etcd.Client
calico *calico.Client
libkv store.Store
lainlet *lainlet.Client
vDb *VirtualIpDb
cDb *ContainerDb
stopCh chan struct{}
lainletStopCh chan struct{}
eventCh chan int
// elect
electStopCh chan struct{}
electIsRunning bool
// health
healthStopCh chan struct{}
healthIsRunning bool
// godns
godns *godns.Godns
addr string
//Acl
acl *acl.Acl
aclFlag bool
// swarm
swarmFlag bool
swarmStopCh chan struct{}
swarmIsRunning bool
// tinydns
tinydnsFlag bool
tinydnsStopCh chan struct{}
tinydnsIsRunning bool
// webrouter
webrouterFlag bool
webrouterStopCh chan struct{}
webrouterIsRunning bool
// deployd
deploydFlag bool
deploydStopCh chan struct{}
deploydIsRunning bool
// streamrouter
streamrouterFlag bool
streamrouterStopCh chan struct{}
streamrouterIsRunning bool
// api server
api *apiserver.Server
}
type JSONVirtualIpPortConfig struct {
Src string `json:"src"`
Proto string `json:"proto"`
Dest string `json:"dest"`
}
type JSONVirtualIpConfig struct {
App string `json:"app"`
Proc string `json:"proc"`
Ports []JSONVirtualIpPortConfig `json:"ports"`
ExcludedNodes []string `json:"excluded_nodes"`
}
type JSONLainletContainer struct {
AppName string `json:"app"`
ProcName string `json:"proc"`
NodeName string `json:"nodename"`
NodeIP string `json:"nodeip"`
IP string `json:"ip"`
Port int `json:"port"`
InstanceNo int `json:"instanceNo"`
}
type JSONLainletContainers map[string]JSONLainletContainer
const APIVersion = "1.18"
const EtcdLainVirtualIpKey = "/lain/config/vips"
const EtcdNetworkdVirtualIpKey = "/lain/networkd/vips"
const LainLetVirtualIpKey = "vips"
const EtcdNetworkdLeaderKey = "/lain/networkd/leader"
const EtcdAppNetworkdKey = "/lain/networkd/apps"
const EtcdSwarmKey = "/lain/swarm/docker/swarm/leader"
const EtcdDeploydKey = "/lain/deployd/leader"
// eg: /lain/networkd/containers/webrouter/worker/1 has the vip list for webrouter instance 1
const EtcdNetworkdContainerVips = "/lain/networkd/containers"
func init() {
kvetcd.Register()
}
func (self *Agent) InitFlag(tinydns bool, swarm bool, webrouter bool, deployd bool, acl bool, streamrouter bool) {
self.tinydnsFlag = tinydns
self.swarmFlag = swarm
self.webrouterFlag = webrouter
self.streamrouterFlag = streamrouter
self.deploydFlag = deployd
self.aclFlag = acl
}
func (self *Agent) InitDocker(endpoint string) {
// calico powerstrip need explicit version
client, err := docker.NewVersionedClient(endpoint, APIVersion)
if err != nil {
log.Fatal(err)
}
self.docker = client
// TODO(xutao) check docker daemon status
}
func (self *Agent) InitLibNetwork(flag bool) {
self.libnetwork = flag
}
func (self *Agent) InitEtcd(endpoint string) {
cfg := etcd.Config{
Endpoints: []string{endpoint},
Transport: etcd.DefaultTransport,
// set timeout per request to fail fast when the target endpoint is unavailable
// TODO(xutao) disable HeaderTimeoutPerRequest for etcd proxy
// For watch request, server returns the header immediately to notify Client
// watch start. But if server is behind some kind of proxy, the response
// header may be cached at proxy, and Client cannot rely on this behavior.
//HeaderTimeoutPerRequest: time.Second,
}
c, err := etcd.New(cfg)
if err != nil {
log.Fatal(err)
}
self.etcd = &c
// TODO(xutao) check etcd status
}
func (self *Agent) InitCalico(endpoint string) {
config := api.CalicoAPIConfig{
Spec: api.CalicoAPIConfigSpec{
DatastoreType: api.EtcdV2,
EtcdConfig: calicoetcd.EtcdConfig{
EtcdEndpoints: endpoint,
},
},
}
c, err := calico.New(config)
if err != nil {
log.Fatal(err)
}
self.calico = c
}
func (self *Agent) InitLibkv(endpoint string) {
etcdEndpoint := endpoint
if strings.HasPrefix(endpoint, "http://") {
etcdEndpoint = endpoint[7:]
}
kv, err := libkv.NewStore(
store.ETCD,
[]string{etcdEndpoint},
&store.Config{
ConnectionTimeout: 10 * time.Second,
},
)
if err != nil {
log.Fatal(err)
}
self.libkv = kv
}
func (self *Agent) InitLainlet(endpoint string) error {
client := lainlet.New(endpoint)
retryCounter := 0
for {
_, err := client.Get("/debug", 0)
if err == nil {
// TODO(xutao) check lainlet status
// TODO(xutao) check lainlet version
break
}
log.WithFields(logrus.Fields{
"err": err,
"retryCounter": retryCounter,
}).Error("Fail to connect lainlet")
time.Sleep(30 * time.Second)
retryCounter++
continue
}
self.lainlet = client
return nil
}
func (self *Agent) InitInterface(iface string) {
self.iface = iface
}
func (self *Agent) InitIptables() {
initIptables()
}
func (self *Agent) InitDomain(domain string) {
if domain != "" {
self.domain = domain
log.Info(fmt.Sprintf("Domain %s", domain))
}
}
func (self *Agent) InitHostname(hostname string) {
if hostname != "" {
self.hostname = hostname
return
}
var err error
if hostname, err = os.Hostname(); err != nil {
log.Fatal(err)
}
self.hostname = hostname
log.Info(fmt.Sprintf("Hostname %s", self.hostname))
}
func (self *Agent) InitAddress(ip string) {
if ip == "" {
// default ip: iface's first ip
ifi, err := net.InterfaceByName(self.iface)
if err != nil {
log.Fatal(err)
}
addrs, err := ifi.Addrs()
if err != nil {
log.Fatal(err)
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ip = ipNet.IP.String()
break
}
}
}
}
if ip == "" {
log.Fatal("No net.address")
}
self.ip = ip
log.Info(fmt.Sprintf("HostIP %s", self.ip))
}
func (self *Agent) InitGodns(addr string) {
// TODO(xutao) check host & server
self.godns = godns.New(addr, self.ip, self.libkv, self.lainlet, log)
self.tinydnsStopCh = make(chan struct{})
self.tinydnsIsRunning = false
self.swarmStopCh = make(chan struct{})
self.swarmIsRunning = false
}
func (self *Agent) InitApiServer(addr string) {
self.api = apiserver.New(addr, self.godns)
}
func (self *Agent) InitAcl() {
self.acl = acl.New(log, self.lainlet)
}
func (self *Agent) InitWebrouter() {
self.webrouterStopCh = make(chan struct{})
self.webrouterIsRunning = false
}
func (self *Agent) InitStreamrouter() {
self.streamrouterStopCh = make(chan struct{})
self.streamrouterIsRunning = false
}
func (self *Agent) InitDeployd() {
self.deploydStopCh = make(chan struct{})
self.deploydIsRunning = false
}
func (self *Agent) InitEventChan() {
self.eventCh = make(chan int)
self.stopCh = make(chan struct{})
self.lainletStopCh = make(chan struct{})
self.electStopCh = make(chan struct{})
self.healthStopCh = make(chan struct{})
}
func (self *Agent) ListLainletContainers() (containers JSONLainletContainers, err error) {
url := fmt.Sprintf("/v2/containers?nodename=%s", self.hostname)
data, err := self.lainlet.Get(url, 0)
if err != nil {
return containers, err
}
err = json.Unmarshal(data, &containers)
return containers, err
}
func (self *Agent) FetchNetworkdVirtualIps() {
kapi := etcd.NewKeysAPI(*self.etcd)
resp, err := kapi.Get(context.Background(), EtcdNetworkdVirtualIpKey, &etcd.GetOptions{Recursive: true})
if err != nil {
log.WithFields(logrus.Fields{
"key": EtcdNetworkdVirtualIpKey,
"err": err,
}).Debug("Fail to get etcd key")
return
}
if resp.Node.Dir != true {
log.WithFields(logrus.Fields{
"key": EtcdNetworkdVirtualIpKey,
}).Error("Etcd key is not dir")
}
var ips []LockedIp
prefixKeyLength := len(EtcdNetworkdVirtualIpKey) + 1
for _, node := range resp.Node.Nodes {
vip := node.Key[prefixKeyLength:]
if !strings.HasSuffix(vip, ".lock") {
continue
}
vip = vip[:len(vip)-5]
paresedIp := net.ParseIP(vip)
if paresedIp.To4() == nil {
continue
}
ips = append(ips, LockedIp{ip: vip, modifiedIndex: node.ModifiedIndex})
}
self.lockedIps = ips
}
func (self *Agent) WatchNetworkdVirtualIps() {
ctx := context.Background()
kapi := etcd.NewKeysAPI(*self.etcd)
watcher := kapi.Watcher(EtcdNetworkdVirtualIpKey, &etcd.WatcherOptions{Recursive: true})
for {
resp, err := watcher.Next(ctx)
if err != nil {
log.WithFields(logrus.Fields{
"key": EtcdNetworkdVirtualIpKey,
"err": err,
}).Error("Fail to watch etcd key")
time.Sleep(30 * time.Second)
watcher = kapi.Watcher(EtcdNetworkdVirtualIpKey, &etcd.WatcherOptions{Recursive: true})
continue
}
log.WithFields(logrus.Fields{
"key": resp.Node.Key,
"value": resp.Node.Value,
"action": resp.Action,
}).Debug("Virtual ip lock changed")
// TODO(xutao) get, set, delete, update, create, compareAndSwap, compareAndDelete and expire
// TODO(xutao) check owned ip
if resp.Action != "delete" || resp.Action != "compareAndDelete" {
continue
}
log.Debug("Send virtual ip lock event")
self.eventCh <- 1
}
}
func (self *Agent) WatchLainlet(watchKey string, stopCh <-chan struct{}, callback func(event *lainlet.Response)) {
retryCounter := 0
for {
ctx := context.Background()
ch, err := self.lainlet.Watch(watchKey, ctx)
if err != nil {
log.WithFields(logrus.Fields{
"err": err,
"retryCounter": retryCounter,
}).Error("Fail to Connect Lainlet")
if retryCounter > 3 {
time.Sleep(30 * time.Second)
} else {
time.Sleep(1 * time.Second)
}
retryCounter++
continue
}
retryCounter = 0
breakWatch := false
for {
select {
case event, ok := <-ch:
if !ok {
breakWatch = true
break
}
if event.Id == 0 {
// lainlet error for etcd down
if event.Event == "error" {
log.WithFields(logrus.Fields{
"id": event.Id,
"event": event.Event,
}).Error("Fail to watch lainlet")
time.Sleep(5 * time.Second)
}
continue
}
callback(event)
case <-stopCh:
return
}
if breakWatch {
break
}
}
log.Error("Fail to watch lainlet")
}
}
func (self *Agent) WatchLainletVirtualIps() {
var oldEventData []byte
self.WatchLainlet("/v2/configwatcher?target=vips&heartbeat=5", nil, func(event *lainlet.Response) {
if reflect.DeepEqual(event.Data, oldEventData) {
log.Warn("Ignore old data")
return
}
oldEventData = event.Data
keyPrefixLength := len(LainLetVirtualIpKey) + 1
currentUnixTime := time.Now().Unix()
var vips interface{}
err := json.Unmarshal(event.Data, &vips)
for key, value := range vips.(map[string]interface{}) {
virtualIpKey := key[keyPrefixLength:]
virtualPort := ""
colonCount := strings.Count(virtualIpKey, ":")
if colonCount == 1 {
splitKey := strings.SplitN(virtualIpKey, ":", 2)
virtualIpKey, virtualPort = splitKey[0], splitKey[1]
} else if colonCount > 1 {
log.WithFields(logrus.Fields{
"virtualIpKey": virtualIpKey,
"value": value.(string),
}).Error("Invalid key")
return
}
paresedIp := net.ParseIP(virtualIpKey)
if paresedIp.To4() == nil {
log.WithFields(logrus.Fields{
"virtualIpKey": virtualIpKey,
"value": value.(string),
}).Error("Invalid key")
return
}
log.WithFields(logrus.Fields{
"virtualIpKey": virtualIpKey,
"value": value.(string),
}).Debug("Get virutal ip config from lainlet")
var ipConfig JSONVirtualIpConfig
err = json.Unmarshal([]byte(value.(string)), &ipConfig)
if err != nil {
log.WithFields(logrus.Fields{
"key": fmt.Sprintf("/lain/config/%s", key),
"reason": err,
}).Warn("Cannot parse virtual ip config")
return
}
log.WithFields(logrus.Fields{
"virtualIpKey": virtualIpKey,
"ipConfig": ipConfig,
}).Debug("Get virutal ip json config from lainlet")
if virtualPort != "" {
// TODO(xutao) check ports in config
}
if virtualIpKey == "0.0.0.0" {
// replace 0.0.0.0 as host ip
virtualIpKey = self.ip
}
self.AddVirtualIp(virtualIpKey, virtualPort, ipConfig, currentUnixTime)
}
self.vDb.SetUpdatedUnixTime(currentUnixTime)
log.Debug("Send virtual ip event")
self.eventCh <- 1
})
}
func (self *Agent) WatchProcIps(stopWatchCh <-chan struct{}, app string, proc string) <-chan int {
// TODO(xutao) watch lainlet
kv := self.libkv
key := fmt.Sprintf("%s/%s/%s", EtcdAppNetworkdKey, app, proc)
eventCh := make(chan int)
go func() {
defer close(eventCh)
for {
retryCounter := 0
breakWatch := false
for {
exists, err := kv.Exists(key)
if err != nil {
// TODO(xutao) error processing
log.WithFields(logrus.Fields{
"key": key,
"retryCounter": retryCounter,
}).Error("Cannot get etcd key")
time.Sleep(time.Second * 15)
retryCounter++
continue
}
if !exists {
err = kv.Put(key, []byte(key), &store.WriteOptions{IsDir: true})
if err != nil {
// TODO(xutao) error processing
log.WithFields(logrus.Fields{
"key": key,
"retryCounter": retryCounter,
}).Error("Cannot initialize etcd key")
time.Sleep(time.Second * 15)
retryCounter++
continue
}
}
// everything is ok
break
}
stopCh := make(chan struct{})
events, err := kv.WatchTree(key, stopCh)
if err != nil {
log.WithFields(logrus.Fields{
"key": key,
}).Error("Cannot watch etcd key")
time.Sleep(time.Second * 15)
continue
}
for {
select {
case pairs, ok := <-events:
if !ok {
breakWatch = true
break
}
for _, pair := range pairs {
log.WithFields(logrus.Fields{
"key": pair.Key,
"value": string(pair.Value),
}).Debug("Value changed on key")
}
eventCh <- 1
case <-stopWatchCh:
stopCh <- struct{}{}
close(stopCh)
return
}
if breakWatch {
break
}
}
}
}()
return eventCh
}
// TODO(xutao) move to webrouter app
func (self *Agent) WatchWebrouterIps(stopWatchCh <-chan struct{}) <-chan int {
return self.WatchProcIps(stopWatchCh, "webrouter", "worker")
}
func (self *Agent) ApplyWebrouterIps() {
kv := self.libkv
var servers []string
key := fmt.Sprintf("%s/webrouter/worker", EtcdAppNetworkdKey)
entries, err := kv.List(key)
if err != nil {
log.WithFields(logrus.Fields{
"key": key,
"err": err,
}).Error("Cannot get etcd key")
return
}
for _, pair := range entries {
log.WithFields(logrus.Fields{
"key": pair.Key,
"value": string(pair.Value),
}).Debug("Get tinydns key")
ipKey := pair.Key[len(key)+1:]
splitKey := strings.SplitN(ipKey, ":", 2)
ip, _ := splitKey[0], splitKey[1]
servers = append(servers, ip)
}
if len(servers) < 1 {
return
}
// update webrouter dns A Record
uniqServers := make(map[string]interface{})
for _, server := range servers {
uniqServers[server] = struct{}{}
}
data := make([]string, 0)
for server, _ := range uniqServers {
data = append(data, fmt.Sprintf("+webrouter.lain:%s:300", server))
}
self.AddTinydnsDomain("webrouter.lain", data)
// update main domain as DNS NS
domains := make([]string, 0)
if self.domain != "" {
domains = append(domains, self.domain)
}
if self.domain != DOMAINLAIN {
domains = append(domains, DOMAINLAIN)
}
for _, domain := range domains {
data := make([]string, 0)
for server, _ := range uniqServers {
data = append(data, fmt.Sprintf("+*.%s:%s:300", domain, server))
data = append(data, fmt.Sprintf(".%s:%s:a:300", domain, server))
}
self.AddTinydnsDomain(domain, data)
}
}
func (self *Agent) WatchLeaderIps(stopWatchCh <-chan struct{}, key string) <-chan int {
kv := self.libkv
eventCh := make(chan int)
go func() {
for {
var lastValue []byte
breakWatch := false
retryCounter := 0
for {
exists, err := kv.Exists(key)
if err != nil {
log.WithFields(logrus.Fields{
"key": key,
"retryCounter": retryCounter,
"err": err,
}).Error("Cannot get swarm key")
retryCounter++
time.Sleep(30 * time.Second)
continue
}
if !exists {
log.WithFields(logrus.Fields{
"key": key,
"retryCounter": retryCounter,
}).Debug("No leader key")
retryCounter++
time.Sleep(15 * time.Second)
continue
}
// everything is ok
break
}
stopCh := make(chan struct{})
events, err := kv.Watch(key, stopCh)
if err != nil {
log.WithFields(logrus.Fields{
"key": key,
}).Error("Cannot watch etcd key")
time.Sleep(time.Second * 15)
continue
}
for {
select {
case pair, ok := <-events:
if !ok {
breakWatch = true
break
}
log.WithFields(logrus.Fields{
"key": pair.Key,
"value": string(pair.Value),
"index": pair.LastIndex,
}).Debug("Get leader key")
// swarm filter for updating key every 5s
if !bytes.Equal(lastValue, pair.Value) {
eventCh <- 1
lastValue = pair.Value
}
case <-stopWatchCh:
stopCh <- struct{}{}
close(stopCh)
return
}
if breakWatch {
break
}
}
}
}()
return eventCh
}
func (self *Agent) WatchDeploydIps(stopWatchCh <-chan struct{}) <-chan int {
return self.WatchLeaderIps(stopWatchCh, EtcdDeploydKey)
}
func (self *Agent) ApplyDeploydIps() {
kv := self.libkv
key := EtcdDeploydKey
pair, err := kv.Get(key)
if err != nil {
log.WithFields(logrus.Fields{
"key": key,
"err": err,
}).Error("Cannot get deployd key")
return
}
log.WithFields(logrus.Fields{
"key": pair.Key,
"value": string(pair.Value),
}).Debug("Get deployd key")
value := string(pair.Value)
splitKey := strings.SplitN(value, ":", 2)
ip, _ := splitKey[0], splitKey[1]
ips := []string{ip}
self.godns.AddHost("deployd.lain", ips, "")
}
func (self *Agent) WatchSwarmIps(stopWatchCh <-chan struct{}) <-chan int {
// swarm leader key default ttl: 20
// TODO(xutao) watch lainlet
return self.WatchLeaderIps(stopWatchCh, EtcdSwarmKey)
}
func (self *Agent) ApplySwarmIps() {
kv := self.libkv
key := EtcdSwarmKey
pair, err := kv.Get(key)
if err != nil {
log.WithFields(logrus.Fields{
"key": key,
"err": err,
}).Error("Cannot get swarm key")
return
}
log.WithFields(logrus.Fields{
"key": pair.Key,
"value": string(pair.Value),
}).Debug("Get swarm key")
value := string(pair.Value)
splitKey := strings.SplitN(value, ":", 2)
ip, _ := splitKey[0], splitKey[1]
ips := []string{ip}
self.godns.AddHost("swarm.lain", ips, "")
}
func (self *Agent) RunHealth() {
if self.healthIsRunning {
return
}
log.Info("Run health")
self.healthIsRunning = true
go func() {
self.wg.Add(1)
defer func() {
log.Info("health done")
self.wg.Done()
}()
tickCh := time.NewTicker(time.Second * 30).C
for {
select {
case <-tickCh:
self.FetchNetworkdVirtualIps()
for _, lockedIp := range self.lockedIps {
ip := lockedIp.ip
isAlive := self.IsAliveVirtualIp(ip)
if isAlive {
continue
}
// remove lock
log.WithFields(logrus.Fields{
"ip": ip,
}).Info("Remove dead ip lock")
self.RemoveVirtualIpLock(lockedIp)
}
case <-self.healthStopCh:
return
}
}
}()
}
func (self *Agent) StopHealth() {
log.Debug("Stop health")
if self.healthIsRunning {
self.healthIsRunning = false
self.healthStopCh <- struct{}{}
}
}
func (self *Agent) CreateAppKey(item *VirtualIpItem) {
if item.port == "" {
return
}
value := self.hostname
if self.GetAppKey(item) == value {
return
}
key := fmt.Sprintf("%s/%s/%s/%s:%s", EtcdAppNetworkdKey, item.appName, item.procName, item.ip, item.port)
kapi := etcd.NewKeysAPI(*self.etcd)
// TODO(xutao) retry
_, _ = kapi.Set(
context.Background(),
key,
value,
&etcd.SetOptions{},
)
}
func (self *Agent) GetAppKey(item *VirtualIpItem) string {
key := fmt.Sprintf("%s/%s/%s/%s:%s", EtcdAppNetworkdKey, item.appName, item.procName, item.ip, item.port)
kapi := etcd.NewKeysAPI(*self.etcd)
retryCounter := 0
for {
resp, err := kapi.Get(context.Background(), key, nil)
if err != nil {
if etcdErr, ok := err.(etcd.Error); ok {
switch etcdErr.Code {
case etcd.ErrorCodeKeyNotFound:
return ""
default:
// FIXME(xutao) "client: etcd cluster is unavailable or misconfigured"
log.WithFields(logrus.Fields{
"err": err,
"etcdErrCode": etcdErr.Code,
"key": key,
}).Error("Fail to get key")
}
}
if retryCounter >= 3 {
// FIXME(xutao) "client: etcd cluster is unavailable or misconfigured"
log.WithFields(logrus.Fields{
"err": err,
"key": key,
"retryCounter": retryCounter,
}).Fatal("Fail to get key")
}
time.Sleep(time.Second)
retryCounter++
continue
}
if resp.Node.Dir != false {
log.WithFields(logrus.Fields{
"key": key,
}).Fatal("Etcd key is dir")
}
return resp.Node.Value
}
}
func (self *Agent) DeleteAppKey(item *VirtualIpItem) {
if item.port == "" {
return
}
if self.GetAppKey(item) == "" {
return
}
key := fmt.Sprintf("%s/%s/%s/%s:%s", EtcdAppNetworkdKey, item.appName, item.procName, item.ip, item.port)
kapi := etcd.NewKeysAPI(*self.etcd)
// TODO(xutao) retry
_, _ = kapi.Delete(
context.Background(),
key,
&etcd.DeleteOptions{},
)
}
func (self *Agent) RunElect() {
self.electIsRunning = true
candidate := leadership.NewCandidate(self.libkv,
EtcdNetworkdLeaderKey,
self.hostname,
15*time.Second)
stopCh := make(chan struct{})
go self.WatchElect(stopCh)
go func() {
defer close(stopCh)
for {
breakWatch := false
electedCh, errCh := candidate.RunForElection()
for {
select {
case isElected := <-electedCh:
if isElected {
log.WithFields(logrus.Fields{
"host": self.hostname,
}).Info("Change to leader")
} else {
log.WithFields(logrus.Fields{
"host": self.hostname,
}).Info("Change to follower")
}
case err := <-errCh:
log.Error(err)
breakWatch = true
break
case <-self.electStopCh:
candidate.Resign()
stopCh <- struct{}{}
return
}
if breakWatch {
break
}
}
time.Sleep(30 * time.Second)
}
}()
}
func (self *Agent) WatchElect(stopWatchCh <-chan struct{}) {
// TODO(xutao) watch lainlet
kv := self.libkv
key := EtcdNetworkdLeaderKey
for {
breakWatch := false
retryCounter := 0
for {
exists, err := kv.Exists(key)
if err != nil {
log.WithFields(logrus.Fields{
"key": key,
"retryCounter": retryCounter,
"err": err,
}).Error("Cannot get networkd leader key")
retryCounter++
time.Sleep(30 * time.Second)
continue
}
if !exists {
log.WithFields(logrus.Fields{
"key": key,
"retryCounter": retryCounter,
}).Debug("No networkd leader key")
retryCounter++
time.Sleep(15 * time.Second)