/
consul_discovery.go
106 lines (85 loc) · 2.3 KB
/
consul_discovery.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
package consul
import (
"fmt"
"net"
"strconv"
"time"
consulapi "github.com/hashicorp/consul/api"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
hv1 "google.golang.org/grpc/health/grpc_health_v1"
)
type Discovery struct {
svcName string
host string
port int
consul *consulapi.Client
hs *health.Server
}
func (d *Discovery) getIdent() string {
if d.host == "" || d.host == "localhost" || d.host == "127.0.0.1" {
return fmt.Sprintf("%d", d.port)
}
return fmt.Sprintf("%s:%d", d.host, d.port)
}
// TODO: Deactivate a consul API here, not a cfg.
func New(serviceName, addr string, cfg *consulapi.Config, srv *grpc.Server) (*Discovery, error) {
client, err := consulapi.NewClient(cfg)
if err != nil {
return nil, err
}
// Extract host:port from the given address.
// TODO: Maybe better to do this outside?
host, sPort, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
nPort, err := strconv.Atoi(sPort)
if err != nil {
return nil, err
}
d := &Discovery{
svcName: serviceName,
host: host,
port: nPort,
consul: client,
hs: health.NewServer(),
}
d.hs.SetServingStatus("", hv1.HealthCheckResponse_SERVING)
hv1.RegisterHealthServer(srv, d.hs)
return d, nil
}
func (d *Discovery) Start() error {
def := &consulapi.AgentServiceRegistration{
Name: d.svcName,
ID: d.getIdent(),
// How other nodes should call the service.
Address: d.host,
Port: d.port,
Check: &consulapi.AgentServiceCheck{
GRPC: fmt.Sprintf("%s:%d", d.host, d.port),
// How long to wait between checks.
Interval: (3 * time.Second).String(),
// How long to wait for a response before giving up.
Timeout: (1 * time.Second).String(),
// How long to wait after a service becomes critical (i.e. starts
// returning error, unhealthy responses, or timing out) before
// removing it from service discovery. Might actually take longer
// than this because of Consul implementation.
DeregisterCriticalServiceAfter: (10 * time.Second).String(),
},
}
// TODO: Send this in a loop while running, in case Consul dies.
err := d.consul.Agent().ServiceRegister(def)
if err != nil {
return err
}
return nil
}
func (d *Discovery) Stop() error {
err := d.consul.Agent().ServiceDeregister(d.getIdent())
if err != nil {
return err
}
return nil
}