This repository has been archived by the owner on Apr 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 99
/
memberlist.go
299 lines (247 loc) · 7.4 KB
/
memberlist.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
/*
Copyright 2018-2022 Mailgun Technologies Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gubernator
import (
"bufio"
"bytes"
"context"
"encoding/gob"
"encoding/json"
"io"
"net"
"runtime"
"strconv"
ml "github.com/hashicorp/memberlist"
"github.com/mailgun/holster/v4/clock"
"github.com/mailgun/holster/v4/retry"
"github.com/mailgun/holster/v4/setter"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type MemberListPool struct {
log FieldLogger
memberList *ml.Memberlist
conf MemberListPoolConfig
events *memberListEventHandler
}
type MemberListPoolConfig struct {
// (Required) This is the peer information that will be advertised to other members
Advertise PeerInfo
// (Required) This is the address:port the member list protocol listen for other members on
MemberListAddress string
// (Required) This is the address:port the member list will advertise to other members it finds
AdvertiseAddress string
// (Required) A list of nodes this member list instance can contact to find other members.
KnownNodes []string
// (Required) A callback function which is called when the member list changes
OnUpdate UpdateFunc
// (Optional) The name of the node this member list identifies itself as.
NodeName string
// (Optional) An interface through which logging will occur (Usually *logrus.Entry)
Logger FieldLogger
}
func NewMemberListPool(ctx context.Context, conf MemberListPoolConfig) (*MemberListPool, error) {
setter.SetDefault(conf.Logger, logrus.WithField("category", "gubernator"))
m := &MemberListPool{
log: conf.Logger,
conf: conf,
}
host, port, err := splitAddress(conf.MemberListAddress)
if err != nil {
return nil, errors.Wrap(err, "MemberListAddress=`%s` is invalid;")
}
// Member list requires the address to be an ip address
if ip := net.ParseIP(host); ip == nil {
addrs, err := net.LookupHost(host)
if err != nil {
return nil, errors.Wrapf(err, "while preforming host lookup for '%s'", host)
}
if len(addrs) == 0 {
return nil, errors.Wrapf(err, "net.LookupHost() returned no addresses for '%s'", host)
}
host = addrs[0]
}
// Configure member list event handler
m.events = newMemberListEventHandler(m.log, conf)
// Configure member list
config := ml.DefaultWANConfig()
config.Events = m.events
config.AdvertiseAddr = host
config.AdvertisePort = port
if conf.NodeName != "" {
config.Name = conf.NodeName
}
config.LogOutput = newLogWriter(m.log)
// Create and set member list
memberList, err := ml.Create(config)
if err != nil {
return nil, err
}
m.memberList = memberList
// Prep metadata
gob.Register(memberListMetadata{})
// Join member list pool
err = m.joinPool(ctx, conf)
if err != nil {
return nil, errors.Wrap(err, "while attempting to join the member-list pool")
}
return m, nil
}
func (m *MemberListPool) joinPool(ctx context.Context, conf MemberListPoolConfig) error {
// Get local node and set metadata
node := m.memberList.LocalNode()
b, err := json.Marshal(&conf.Advertise)
if err != nil {
return errors.Wrap(err, "error marshalling PeerInfo as JSON")
}
node.Meta = b
err = retry.Until(ctx, retry.Interval(clock.Millisecond*300), func(ctx context.Context, i int) error {
// Join member list
_, err = m.memberList.Join(conf.KnownNodes)
if err != nil {
return errors.Wrap(err, "while joining member-list")
}
return nil
})
if err != nil {
return errors.Wrap(err, "timed out attempting to join member list")
}
// Add the local node to the event handler's peer list
m.events.addPeer(node)
return nil
}
func (m *MemberListPool) Close() {
err := m.memberList.Leave(clock.Second)
if err != nil {
m.log.Warn(errors.Wrap(err, "while leaving member-list"))
}
}
type memberListEventHandler struct {
peers map[string]PeerInfo
log FieldLogger
conf MemberListPoolConfig
}
func newMemberListEventHandler(log FieldLogger, conf MemberListPoolConfig) *memberListEventHandler {
handler := memberListEventHandler{
conf: conf,
log: log,
}
handler.peers = make(map[string]PeerInfo)
return &handler
}
func (e *memberListEventHandler) addPeer(node *ml.Node) {
ip := getIP(node.Address())
peer, err := unmarshallPeer(node.Meta, ip)
if err != nil {
e.log.WithError(err).Warnf("while adding to peers")
} else {
e.peers[ip] = peer
e.callOnUpdate()
}
}
func (e *memberListEventHandler) NotifyJoin(node *ml.Node) {
ip := getIP(node.Address())
peer, err := unmarshallPeer(node.Meta, ip)
if err != nil {
// This is called during member list initialization due to the fact that the local node
// has no metadata yet
e.log.WithError(err).Warn("while deserialize member-list peer")
return
}
peer.IsOwner = false
e.peers[ip] = peer
e.callOnUpdate()
}
func (e *memberListEventHandler) NotifyLeave(node *ml.Node) {
ip := getIP(node.Address())
// Remove PeerInfo
delete(e.peers, ip)
e.callOnUpdate()
}
func (e *memberListEventHandler) NotifyUpdate(node *ml.Node) {
ip := getIP(node.Address())
peer, err := unmarshallPeer(node.Meta, ip)
if err != nil {
e.log.WithError(err).Warn("while unmarshalling peer info")
}
peer.IsOwner = false
e.peers[ip] = peer
e.callOnUpdate()
}
func (e *memberListEventHandler) callOnUpdate() {
var peers []PeerInfo
for _, p := range e.peers {
if p.GRPCAddress == e.conf.Advertise.GRPCAddress {
p.IsOwner = true
}
peers = append(peers, p)
}
e.conf.OnUpdate(peers)
}
func getIP(address string) string {
addr, _, _ := net.SplitHostPort(address)
return addr
}
func makeAddress(ip string, port int) string {
return net.JoinHostPort(ip, strconv.Itoa(port))
}
// Deprecated
type memberListMetadata struct {
DataCenter string
AdvertiseAddress string
GubernatorPort int
}
func unmarshallPeer(b []byte, ip string) (PeerInfo, error) {
var peer PeerInfo
if err := json.Unmarshal(b, &peer); err != nil {
var metadata memberListMetadata
decoder := gob.NewDecoder(bytes.NewBuffer(b))
if err := decoder.Decode(&peer); err != nil {
return peer, errors.Wrap(err, "error decoding peer")
}
// Handle deprecated GubernatorPort
if metadata.AdvertiseAddress == "" {
metadata.AdvertiseAddress = makeAddress(ip, metadata.GubernatorPort)
}
return PeerInfo{GRPCAddress: metadata.AdvertiseAddress, DataCenter: metadata.DataCenter}, nil
}
return peer, nil
}
func newLogWriter(log FieldLogger) *io.PipeWriter {
reader, writer := io.Pipe()
go func() {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
log.Info(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Errorf("Error while reading from Writer: %s", err)
}
reader.Close()
}()
runtime.SetFinalizer(writer, func(w *io.PipeWriter) {
writer.Close()
})
return writer
}
func splitAddress(addr string) (string, int, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return host, 0, errors.New(" expected format is `address:port`")
}
intPort, err := strconv.Atoi(port)
if err != nil {
return host, intPort, errors.Wrap(err, "port must be a number")
}
return host, intPort, nil
}