/
discovery.go
189 lines (166 loc) · 4.33 KB
/
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
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
package etcd
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/coreos/etcd/client"
"golang.org/x/net/context"
)
// RegistryClient is the interface for service
// discovery based on etcd.
type RegistryClient interface {
// Register given service
// to etcd instance
Register() error
// Unregister the service
// from etcd.
Unregister() error
// ServiceByName
// return the base addresses
// for service instances.
ServicesByName(name string) ([]string, error)
}
// RegistryConfig is configuration structure
// for connectiong to etcd instance
// and identify the service.
type RegistryConfig struct {
// EtcdEndpoints that service
// registry client connects to.
EtcdEndpoints []string
// ServiceName is the
// the name of
// service in application.
ServiceName string
// InstanceName is the identification
// for service instance.
InstanceName string
// BaseURL is the url
// that the service is
// acessible on.
BaseURL string
etcdKey string
keepAliveTicker *time.Ticker
cancel context.CancelFunc
}
// ReigistryClient structure implements the
// basic functionality for service registration
// in etcd.
// After the Reguster method is called, the client
// periodically refreshes the record about the
// service.
type ReigistryClient struct {
RegistryConfig
EtcdKApi client.KeysAPI
}
// New creates the EtcdRegistryClient
// with service paramters defined by config.
func New(config RegistryConfig) (*ReigistryClient, error) {
cfg := client.Config{
Endpoints: config.EtcdEndpoints,
Transport: client.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
}
c, err := client.New(cfg)
if err != nil {
return nil, err
}
etcdClient := &ReigistryClient{
config,
client.NewKeysAPI(c),
}
return etcdClient, nil
}
// Register register service
// to configured etcd instance.
// Once the Register is called, the client
// also periodically
// calls the refresh goroutine.
func (e *ReigistryClient) Register() error {
e.etcdKey = buildKey(e.ServiceName, e.InstanceName)
value := registerDTO{
e.BaseURL,
}
val, _ := json.Marshal(value)
e.keepAliveTicker = time.NewTicker(KeepAlivePeriod)
ctx, c := context.WithCancel(context.TODO())
e.cancel = c
insertFunc := func() error {
_, err := e.EtcdKApi.Set(context.Background(), e.etcdKey, string(val), &client.SetOptions{
TTL: TTL,
})
return err
}
refreshTTLFunc := func() error {
_, err := e.EtcdKApi.Set(context.Background(), e.etcdKey, string(val), &client.SetOptions{
TTL: TTL,
Refresh: true,
})
return err
}
err := insertFunc()
if err != nil {
return err
}
// Exec the keep alive goroutine
go func() {
for {
select {
case <-e.keepAliveTicker.C:
refreshTTLFunc()
log.Printf("Keep alive routine for %s", e.ServiceName)
case <-ctx.Done():
log.Printf("Shutdown keep alive routine for %s", e.ServiceName)
return
}
}
}()
fmt.Println("Register2Etcd")
return nil
}
// Unregister removes the service instance from
// etcd. Once the Unregister method is called,
// the periodicall refresh goroutine is cancelled.
func (e *ReigistryClient) Unregister() error {
e.cancel()
e.keepAliveTicker.Stop()
_, err := e.EtcdKApi.Delete(context.Background(), e.etcdKey, nil)
fmt.Println("Unregister2Etcd")
return err
}
// ServicesByName query the
// etcd instance for service nodes for service
// by given name.
func (e *ReigistryClient) ServicesByName(name string) ([]string, error) {
response, err := e.EtcdKApi.Get(context.Background(), fmt.Sprintf("/%s", name), nil)
var ipList []string
ipList = make([]string, 0)
if err == nil {
for _, node := range response.Node.Nodes {
val := ®isterDTO{}
json.Unmarshal([]byte(node.Value), val)
ipList = append(ipList, val.BaseURL)
}
}
return ipList, err
}
type registerDTO struct {
BaseURL string
}
func buildKey(servicetype, instanceName string) string {
return fmt.Sprintf("%s/%s", servicetype, instanceName)
}
// GetServicesByName get service by name
func GetServicesByName(name string) ([]string, error) {
response, err := KeysAPI.Get(context.Background(), fmt.Sprintf("/%s", name), nil)
var ipList []string
ipList = make([]string, 0)
if err == nil {
for _, node := range response.Node.Nodes {
val := ®isterDTO{}
json.Unmarshal([]byte(node.Value), val)
ipList = append(ipList, val.BaseURL)
}
}
return ipList, err
}