Debian Codegraph @

api/v0/detector/zoo/detect_test.go

raw symbols SCIP
1 package zoo_test
2
3 import (
4 "fmt"
5 "sync"
6 "testing"
7 "time"
8
9 "github.com/gogo/protobuf/proto"
10 log "github.com/golang/glog"
11 "github.com/mesos/mesos-go/api/v0/detector"
12 mock_zkdetector "github.com/mesos/mesos-go/api/v0/detector/zoo/mock"
13 mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
14 util "github.com/mesos/mesos-go/api/v0/mesosutil"
15 "github.com/samuel/go-zookeeper/zk"
16 "github.com/stretchr/testify/assert"
17
18 . "github.com/mesos/mesos-go/api/v0/detector/zoo"
19 )
20
21 const (
22 zkurl = "zk://127.0.0.1:2181/mesos"
23 zkurl_bad = "zk://127.0.0.1:2181"
24 test_zk_path = "/test"
25 )
26
27 func newTestMasterInfo(id int) []byte {
28 miPb := util.NewMasterInfo(fmt.Sprintf("master(%d)@localhost:5050", id), 123456789, 400)
29 data, err := proto.Marshal(miPb)
30 if err != nil {
31 panic(err)
32 }
33 return data
34 }
35
36 func TestMasterDetectorChildrenChanged(t *testing.T) {
37 var (
38 path = test_zk_path
39 snapDetected = make(chan struct{})
40
41 bf = func(client ZKInterface, done <-chan struct{}) (ZKInterface, error) {
42 if client == nil {
43 log.V(1).Infoln("bootstrapping detector")
44 defer log.V(1).Infoln("bootstrapping detector ..finished")
45
46 mocked, _, errs := mock_zkdetector.NewClient(test_zk_path, "info_0", "info_5", "info_10")
47 client = mocked
48
49 mocked.On("Data", fmt.Sprintf("%s/info_0", path)).Return(newTestMasterInfo(0), nil)
50
51 // wait for the first child snapshot to be processed before signaling end-of-watch
52 // (which is signalled by closing errs).
53 go func() {
54 defer close(errs)
55 select {
56 case <-snapDetected:
57 case <-done:
58 t.Errorf("detector died before child snapshot")
59 }
60 }()
61 }
62 return client, nil
63 }
64 called = 0
65 lostMaster = make(chan struct{})
66 md, err = NewMasterDetector(zkurl, MinCyclePeriod(10*time.Millisecond), Bootstrap(bf))
67 )
68 defer md.Cancel()
69 assert.NoError(t, err)
70
71 const expectedLeader = "master(0)@localhost:5050"
72 err = md.Detect(detector.OnMasterChanged(func(master *mesos.MasterInfo) {
73 //expect 2 calls in sequence: the first setting a master
74 //and the second clearing it
75 switch called++; called {
76 case 1:
77 defer close(snapDetected)
78 assert.NotNil(t, master)
79 assert.Equal(t, expectedLeader, master.GetId())
80 case 2:
81 md.Cancel()
82 defer close(lostMaster)
83 assert.Nil(t, master)
84 default:
85 t.Errorf("unexpected notification call attempt %d", called)
86 }
87 }))
88 assert.NoError(t, err)
89
90 fatalOn(t, 10*time.Second, lostMaster, "Waited too long for lost master")
91
92 select {
93 case <-md.Done():
94 assert.Equal(t, 2, called, "expected 2 detection callbacks instead of %d", called)
95 case <-time.After(time.Second * 10):
96 panic("Waited too long for detector shutdown...")
97 }
98 }
99
100 // single connector instance, it's internal connection to zk is flappy
101 func TestMasterDetectorFlappyConnectionState(t *testing.T) {
102 const ITERATIONS = 3
103 var (
104 path = test_zk_path
105
106 bf = func(client ZKInterface, _ <-chan struct{}) (ZKInterface, error) {
107 if client == nil {
108 log.V(1).Infoln("bootstrapping detector")
109 defer log.V(1).Infoln("bootstrapping detector ..finished")
110
111 children := []string{"info_0", "info_5", "info_10"}
112 mocked, snaps, errs := mock_zkdetector.NewClient(test_zk_path, children...)
113 client = mocked
114
115 mocked.On("Data", fmt.Sprintf("%s/info_0", path)).Return(newTestMasterInfo(0), nil)
116
117 // the first snapshot will be sent immediately and the detector will be awaiting en event.
118 // cycle through some connected/disconnected events but maintain the same snapshot
119 go func() {
120 defer close(errs)
121 for attempt := 0; attempt < ITERATIONS; attempt++ {
122 // send an error, should cause the detector to re-issue a watch
123 errs <- zk.ErrSessionExpired
124 // the detection loop issues another watch, so send it a snapshot..
125 // send another snapshot
126 snaps <- children
127 }
128 }()
129 }
130 return client, nil
131 }
132 called = 0
133 lostMaster = make(chan struct{})
134 wg sync.WaitGroup
135 md, err = NewMasterDetector(zkurl, MinCyclePeriod(10*time.Millisecond), Bootstrap(bf))
136 )
137 defer md.Cancel()
138 assert.NoError(t, err)
139
140 wg.Add(1 + ITERATIONS) // +1 for the initial snapshot that's sent for the first watch
141
142 const EXPECTED_CALLS = (ITERATIONS * 2) + 2 // +1 for initial snapshot, +1 for final lost-leader (close(errs))
143 err = md.Detect(detector.OnMasterChanged(func(master *mesos.MasterInfo) {
144 called++
145 log.V(3).Infof("detector invoked: called %d", called)
146 switch {
147 case called < EXPECTED_CALLS:
148 if master != nil {
149 wg.Done()
150 assert.Equal(t, master.GetId(), "master(0)@localhost:5050")
151 }
152 case called == EXPECTED_CALLS:
153 md.Cancel()
154 defer close(lostMaster)
155 assert.Nil(t, master)
156 default:
157 t.Errorf("unexpected notification call attempt %d", called)
158 }
159 }))
160 assert.NoError(t, err)
161
162 fatalAfter(t, 10*time.Second, wg.Wait, "Waited too long for new-master alerts")
163 fatalOn(t, 3*time.Second, lostMaster, "Waited too long for lost master")
164
165 select {
166 case <-md.Done():
167 assert.Equal(t, EXPECTED_CALLS, called, "expected %d detection callbacks instead of %d", EXPECTED_CALLS, called)
168 case <-time.After(time.Second * 10):
169 panic("Waited too long for detector shutdown...")
170 }
171 }
172
173 func TestMasterDetector_multipleLeadershipChanges(t *testing.T) {
174 var (
175 leadershipChanges = [][]string{
176 {"info_014", "info_010", "info_005"},
177 {"info_005", "info_004", "info_022"},
178 {}, // indicates no master
179 {"info_017", "info_099", "info_200"},
180 }
181
182 ITERATIONS = len(leadershipChanges)
183 // +1 for initial snapshot, +1 for final lost-leader (close(errs))
184 EXPECTED_CALLS = (ITERATIONS + 2)
185 path = test_zk_path
186
187 bf = func(client ZKInterface, _ <-chan struct{}) (ZKInterface, error) {
188 if client == nil {
189 log.V(1).Infoln("bootstrapping detector")
190 defer log.V(1).Infoln("bootstrapping detector ..finished")
191
192 children := []string{"info_0", "info_5", "info_10"}
193 mocked, snaps, errs := mock_zkdetector.NewClient(test_zk_path, children...)
194 client = mocked
195
196 mocked.On("Data", fmt.Sprintf("%s/info_0", path)).Return(newTestMasterInfo(0), nil)
197 mocked.On("Data", fmt.Sprintf("%s/info_005", path)).Return(newTestMasterInfo(5), nil)
198 mocked.On("Data", fmt.Sprintf("%s/info_004", path)).Return(newTestMasterInfo(4), nil)
199 mocked.On("Data", fmt.Sprintf("%s/info_017", path)).Return(newTestMasterInfo(17), nil)
200
201 // the first snapshot will be sent immediately and the detector will be awaiting en event.
202 // cycle through some connected/disconnected events but maintain the same snapshot
203 go func() {
204 defer close(errs)
205 for attempt := 0; attempt < ITERATIONS; attempt++ {
206 snaps <- leadershipChanges[attempt]
207 }
208 }()
209 }
210 return client, nil
211 }
212
213 called = 0
214 lostMaster = make(chan struct{})
215 expectedLeaders = []int{0, 5, 4, 17}
216 leaderIdx = 0
217 wg sync.WaitGroup
218 md, err = NewMasterDetector(zkurl, MinCyclePeriod(10*time.Millisecond), Bootstrap(bf))
219 )
220 defer md.Cancel()
221 assert.NoError(t, err)
222
223 wg.Add(ITERATIONS) // +1 for the initial snapshot that's sent for the first watch, -1 because set 3 is empty
224 err = md.Detect(detector.OnMasterChanged(func(master *mesos.MasterInfo) {
225 called++
226 log.V(3).Infof("detector invoked: called %d", called)
227 switch {
228 case called < EXPECTED_CALLS:
229 if master != nil {
230 expectedLeader := fmt.Sprintf("master(%d)@localhost:5050", expectedLeaders[leaderIdx])
231 assert.Equal(t, expectedLeader, master.GetId())
232 leaderIdx++
233 wg.Done()
234 }
235 case called == EXPECTED_CALLS:
236 md.Cancel()
237 defer close(lostMaster)
238 assert.Nil(t, master)
239 default:
240 t.Errorf("unexpected notification call attempt %d", called)
241 }
242 }))
243 assert.NoError(t, err)
244
245 fatalAfter(t, 10*time.Second, wg.Wait, "Waited too long for new-master alerts")
246 fatalOn(t, 3*time.Second, lostMaster, "Waited too long for lost master")
247
248 select {
249 case <-md.Done():
250 assert.Equal(t, EXPECTED_CALLS, called, "expected %d detection callbacks instead of %d", EXPECTED_CALLS, called)
251 case <-time.After(time.Second * 10):
252 panic("Waited too long for detector shutdown...")
253 }
254 }
255
256 func afterFunc(f func()) <-chan struct{} {
257 ch := make(chan struct{})
258 go func() {
259 defer close(ch)
260 f()
261 }()
262 return ch
263 }
264
265 func fatalAfter(t *testing.T, d time.Duration, f func(), msg string, args ...interface{}) {
266 fatalOn(t, d, afterFunc(f), msg, args...)
267 }
268
269 func fatalOn(t *testing.T, d time.Duration, ch <-chan struct{}, msg string, args ...interface{}) {
270 select {
271 case <-ch:
272 return
273 case <-time.After(d):
274 // check for a tie
275 select {
276 case <-ch:
277 return
278 default:
279 t.Fatalf(msg, args...)
280 }
281 }
282 }
283
284 /* TODO(jdef) refactor this to work with the new ZKInterface
285 func TestNotifyAllMasters(t *testing.T) {
286 c, err := newClient(test_zk_hosts, test_zk_path)
287 assert.NoError(t, err)
288
289 childEvents := make(chan zk.Event, 5)
290 connector := NewMockConnector()
291
292 c.setFactory(asFactory(func() (Connector, <-chan zk.Event, error) {
293 sessionEvents := make(chan zk.Event, 1)
294 sessionEvents <- zk.Event{
295 Type: zk.EventSession,
296 State: zk.StateConnected,
297 }
298 return connector, sessionEvents, nil
299 }))
300
301 md, err := NewMasterDetector(zkurl)
302 defer md.Cancel()
303
304 assert.NoError(t, err)
305
306 c.errorHandler = ErrorHandler(func(c *Client, e error) {
307 t.Errorf("unexpected error: %v", e)
308 })
309 md.Client = c
310
311 listener := &allMastersListener{}
312
313 //-- expect primer
314 var primer sync.WaitGroup
315 ignoreArgs := func(f func()) func(mock.Arguments) {
316 primer.Add(1)
317 return func(_ mock.Arguments) {
318 f()
319 }
320 }
321 connector.On("Children", test_zk_path).Return([]string{}, &zk.Stat{}, nil).Run(ignoreArgs(primer.Done)).Once()
322 listener.On("UpdatedMasters", []*mesos.MasterInfo{}).Return().Run(ignoreArgs(primer.Done)).Once()
323 connector.On("ChildrenW", test_zk_path).Return([]string{test_zk_path}, &zk.Stat{}, (<-chan zk.Event)(childEvents), nil).Run(ignoreArgs(primer.Done)).Once()
324 md.Detect(listener)
325 fatalAfter(t, 3*time.Second, primer.Wait, "timed out waiting for detection primer")
326
327 listener.AssertExpectations(t)
328 connector.AssertExpectations(t)
329
330 //-- test membership changes
331 type expectedGets struct {
332 info []byte
333 err error
334 }
335 tt := []struct {
336 zkEntry []string
337 gets []expectedGets
338 leaderIdx int
339 }{
340 {[]string{"info_004"}, []expectedGets{{newTestMasterInfo(1), nil}}, 0},
341 {[]string{"info_007", "info_005", "info_006"}, []expectedGets{{newTestMasterInfo(2), nil}, {newTestMasterInfo(3), nil}, {newTestMasterInfo(4), nil}}, 1},
342 {nil, nil, -1},
343 }
344 for j, tc := range tt {
345 // expectations
346 var tcwait sync.WaitGroup
347 ignoreArgs = func(f func()) func(mock.Arguments) {
348 tcwait.Add(1)
349 return func(_ mock.Arguments) {
350 f()
351 }
352 }
353
354 expectedInfos := []*mesos.MasterInfo{}
355 for i, zke := range tc.zkEntry {
356 connector.On("Get", fmt.Sprintf("%s/%s", test_zk_path, zke)).Return(tc.gets[i].info, &zk.Stat{}, tc.gets[i].err).Run(ignoreArgs(tcwait.Done)).Once()
357 masterInfo := &mesos.MasterInfo{}
358 err = proto.Unmarshal(tc.gets[i].info, masterInfo)
359 if err != nil {
360 t.Fatalf("failed to unmarshall MasterInfo data: %v", err)
361 }
362 expectedInfos = append(expectedInfos, masterInfo)
363 }
364 if len(tc.zkEntry) > 0 {
365 connector.On("Get", fmt.Sprintf("%s/%s", test_zk_path, tc.zkEntry[tc.leaderIdx])).Return(
366 tc.gets[tc.leaderIdx].info, &zk.Stat{}, tc.gets[tc.leaderIdx].err).Run(ignoreArgs(tcwait.Done)).Once()
367 }
368 connector.On("Children", test_zk_path).Return(tc.zkEntry, &zk.Stat{}, nil).Run(ignoreArgs(tcwait.Done)).Once()
369 listener.On("OnMasterChanged", mock.AnythingOfType("*mesosproto.MasterInfo")).Return().Run(ignoreArgs(tcwait.Done)).Once()
370 listener.On("UpdatedMasters", expectedInfos).Return().Run(ignoreArgs(tcwait.Done)).Once()
371 connector.On("ChildrenW", test_zk_path).Return([]string{test_zk_path}, &zk.Stat{}, (<-chan zk.Event)(childEvents), nil).Run(ignoreArgs(tcwait.Done)).Once()
372
373 // fire the event that triggers the test case
374 childEvents <- zk.Event{
375 Type: zk.EventNodeChildrenChanged,
376 Path: test_zk_path,
377 }
378
379 // allow plenty of time for all the async processing to happen
380 fatalAfter(t, 5*time.Second, tcwait.Wait, "timed out waiting for all-masters test case %d", j+1)
381 listener.AssertExpectations(t)
382 connector.AssertExpectations(t)
383 }
384
385 connector.On("Close").Return(nil)
386 }
387 */