-
Notifications
You must be signed in to change notification settings - Fork 5
/
master.go
289 lines (227 loc) · 6.75 KB
/
master.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
package master
import (
"fmt"
"time"
log "github.com/InVisionApp/go-logger"
"github.com/gofrs/uuid"
"github.com/relistan/go-director"
"github.com/InVisionApp/go-logger/shims/logrus"
"github.com/InVisionApp/go-master/backend"
"github.com/InVisionApp/go-master/safe"
)
const (
DefaultHeartbeatFrequency = time.Second * 1
DefaultVersion = "unset"
)
//go:generate counterfeiter -o fakes/fakemaster/fake_master.go . Master
type Master interface {
Start() error
Stop() error
IsMaster() bool
ID() string
Status() (interface{}, error)
}
type master struct {
// the uuid should change each time the master is started up
uuid string
version string
isMaster *safe.SafeBool
info *backend.MasterInfo
heartBeatFreq time.Duration
startHook func()
stopHook func()
heartBeat director.Looper
// all errors occurring on async work is sent back on here
errors chan error
log log.Logger
lock backend.MasterLock
}
type MasterConfig struct {
// Required: Backend that will be used for master election
MasterLock backend.MasterLock
// Optional: How often should a master send heartbeats (default: */1s)
HeartBeatFrequency time.Duration
// Optional: StartHook func is called as soon as a master lock is achieved.
// It is the callback to signal becoming a master
StartHook func()
// Optional: StopHook func is called when the master lock is lost
// It is the callback to signal that it is no longer the master.
// It is not called when the master is stopped manually
StopHook func()
// Optional: Error channel to receive go-master related error messages
Err chan error
// Optional: Logger for go-master to use (default: new logrus shim will be created)
Logger log.Logger
// Optional: If set, workers will NOT perform any work if the master's
// version differs from their own version. (default: "unset")
Version string
}
func New(cfg *MasterConfig) Master {
setDefaults(cfg)
return &master{
uuid: generateUUID().String(), // pick a unique ID for the master
version: cfg.Version,
isMaster: safe.NewBool(),
heartBeatFreq: cfg.HeartBeatFrequency,
lock: cfg.MasterLock,
startHook: cfg.StartHook,
stopHook: cfg.StopHook,
heartBeat: director.NewImmediateTimedLooper(director.FOREVER, cfg.HeartBeatFrequency, nil),
//TODO: implement error proxy
//TODO: check for a nil err chan
errors: cfg.Err,
log: cfg.Logger,
}
}
func setDefaults(cfg *MasterConfig) {
if cfg.Logger == nil {
cfg.Logger = logrus.New(nil)
}
if cfg.Version == "" {
cfg.Version = DefaultVersion
}
if cfg.HeartBeatFrequency.String() == "0s" {
cfg.HeartBeatFrequency = DefaultHeartbeatFrequency
}
}
func (m *master) ID() string {
return m.uuid
}
// validate that all necessary configuration/components are there
func (m *master) validate() error {
if m.lock == nil {
return fmt.Errorf("MasterLock backend must be defined")
}
return nil
}
func (m *master) Start() error {
// can not start if already a master
if m.isMaster.Val() {
return fmt.Errorf("already master since %v", m.info.StartedAt)
}
if err := m.validate(); err != nil {
return fmt.Errorf("invalid master setup: %v", err)
}
// kick off the heartbeat loop
go m.runHeartBeat()
return nil
}
func (m *master) runHeartBeat() {
m.heartBeat.Loop(func() error {
if !m.isMaster.Val() {
// attempt to become the master
if m.becomeMaster() {
// became the master
if m.startHook != nil {
// run the start hook in a routine so it doesn't block
go m.startHook()
}
}
// continue
return nil
}
// I am the master!
// run the heartbeat
if err := m.lock.WriteHeartbeat(m.info); err != nil {
m.sendError(fmt.Errorf("failed to write heartbeat: %v", err))
// if heartbeat fails or master lock lost, stop the tasks
m.cleanupMaster()
//continue
return nil
}
m.log.Debugf("wrote heartbeat: %v", m.info.LastHeartbeat)
//continue
return nil
})
}
func (m *master) becomeMaster() bool {
mi := &backend.MasterInfo{
MasterID: m.uuid,
Version: m.version,
}
if err := m.lock.Lock(mi); err != nil {
// The heartbeat tries to become master every second. Logging an error here
// (at error level) is a constant stream.
m.log.Debugf("failed to acquire lock while becoming master: %v", err)
return false
}
m.isMaster.SetTrue()
m.info = mi
return true
}
// Call on this to do cleanup after a master lock is lost.
func (m *master) cleanupMaster() {
// this is done first so that anything
// reading this will get an accurate value
m.isMaster.SetFalse()
m.info = &backend.MasterInfo{}
if m.stopHook != nil {
// run hook in routine to avoid blocking
go m.stopHook()
}
}
func (m *master) Stop() error {
if !m.isMaster.Val() {
m.log.Debug("not currently the master, so nothing to stop")
// this is not an error because the master is stopped
// it just becomes a no-op
return nil
}
// stop the heartbeat
//TODO: if the heartbeat is not running, this will be a leak
m.heartBeat.Quit()
// attempt a release on the backend
// this is a best effort. The heartbeat loop has been stopped,
// so the lock will be lost eventually either way
if err := m.lock.UnLock(m.uuid); err != nil {
m.sendError(fmt.Errorf("failed to release lock on master backend: %v", err))
}
// at this point, as far as this node is concerned, it is
// no longer the master. The only risk is that the heartbeat
// did not quit properly
// TODO: how can we determine that the heartbeat quit correctly?
// this is only done once unlock is successful
m.isMaster.SetFalse()
m.info = &backend.MasterInfo{}
return nil
}
func (m *master) IsMaster() bool {
return m.isMaster.Val()
}
func (m *master) Status() (interface{}, error) {
status := map[string]interface{}{
"is_master": m.isMaster.Val(),
}
// currently there is nothing to make status error
// eventually we could have something like error rate
return status, nil
}
func (m *master) sendError(err error) {
//if an err chan exists, send the error, otherwise log it
if m.errors != nil {
// do this in a routine in case no one is reading this channel
// a routine leak is better than a lock up serving stale data
// alternatively there could be an intermediate proxy that reads
// this channel and queues up errors to be read. Then it becomes
// a memory concern instead
go func() {
//TODO: implement deadline for send error routine
m.errors <- err
}()
} else {
m.log.Error(err)
}
}
// a random uuid to use as a namespace
var nsUUID = uuid.Must(uuid.FromString("34b13033-50e7-4083-97f5-d389cf3a1c0e"))
// generate a UUID by iterating over the strategies, without throwing an error
func generateUUID() uuid.UUID {
id, err := uuid.NewV1()
if err != nil {
id, err = uuid.NewV4()
if err != nil {
return uuid.NewV5(nsUUID, time.Now().String())
}
}
return id
}