This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto_checkin.go
81 lines (70 loc) · 2.01 KB
/
auto_checkin.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
package consul_checkin
import (
consul_api "github.com/hashicorp/consul/api"
. "github.com/thekondor/consul-checkin/watchdog"
"time"
)
type AutoCheckinService struct {
config *Config
consulAgent *consul_api.Agent
connectionWatchdog ConnectionWatchdog
services []Service
}
// TODO: check for already existing services with duplicate IDs
func (self *AutoCheckinService) Add(service Service) {
self.services = append(self.services, service)
}
func (self *AutoCheckinService) Start() {
self.connectionWatchdog = self.watchConsul()
self.registerServices()
}
func (self *AutoCheckinService) Stop() {
self.deregisterServices()
self.connectionWatchdog.Stop()
}
func (self AutoCheckinService) watchConsul() ConnectionWatchdog {
watchdog, _ := WatchConnection(
CheckHealthOverLeaderPing(self.config.Consul.Client),
&WatchOptions{
PingInterval: 3 * time.Second,
On: ConnectionEvents{
ConnectionRecovered: self.registerServices,
ConnectionFailed: func(uint, error) RetryDecision {
return TryAgain
},
ConnectionLost: func(error) RetryDecision {
return TryAgain
},
},
},
)
return watchdog
}
func (self AutoCheckinService) registerServices() {
for _, svc := range self.services {
self.register(svc.ConsulService)
}
}
func (self AutoCheckinService) deregisterServices() {
for _, svc := range self.services {
self.deregister(svc.ConsulService.ID)
}
}
func (self AutoCheckinService) register(consulService *consul_api.AgentServiceRegistration) {
err := self.consulAgent.ServiceRegister(consulService)
if nil != err {
self.config.On.ServiceRegisterFailed(consulService.ID, err)
}
}
func (self AutoCheckinService) deregister(consulServiceId string) {
err := self.consulAgent.ServiceDeregister(consulServiceId)
if nil != err {
self.config.On.ServiceDeregisterFailed(consulServiceId, err)
}
}
func CheckinAutomatically(config *Config) *AutoCheckinService {
return &AutoCheckinService{
config: config,
consulAgent: config.Consul.Client.Agent(),
}
}