-
Notifications
You must be signed in to change notification settings - Fork 494
/
mock_test.go
743 lines (656 loc) · 18.7 KB
/
mock_test.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package peergrouper
import (
"encoding/json"
"fmt"
"math/rand"
"path"
"reflect"
"strconv"
"sync"
"github.com/juju/errors"
"github.com/juju/replicaset/v2"
"github.com/juju/utils/v2/voyeur"
"github.com/juju/worker/v3"
"gopkg.in/tomb.v2"
"github.com/juju/juju/controller"
"github.com/juju/juju/core/instance"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/status"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/state"
coretesting "github.com/juju/juju/testing"
)
// This file holds helper functions for mocking pieces of State and replicaset
// that we don't want to directly depend on in unit tests.
type fakeState struct {
mu sync.Mutex
errors errorPatterns
controllers map[string]*fakeController
controllerInfo voyeur.Value // of *state.ControllerInfo
statuses voyeur.Value // of statuses collection
controllerConfig voyeur.Value // of controller.Config
session *fakeMongoSession
checkMu sync.Mutex
check func(st *fakeState) error
spaces map[string]*fakeSpace
}
var (
_ State = (*fakeState)(nil)
_ ControllerNode = (*fakeController)(nil)
_ MongoSession = (*fakeMongoSession)(nil)
_ Space = (*fakeSpace)(nil)
)
type errorPatterns struct {
patterns []errorPattern
}
type errorPattern struct {
pattern string
errFunc func() error
}
// setErrorFor causes the given error to be returned
// from any mock call that matches the given
// string, which may contain wildcards as
// in path.Match.
//
// The standard form for errors is:
// Type.Function <arg>...
// See individual functions for details.
func (e *errorPatterns) setErrorFor(what string, err error) {
e.setErrorFuncFor(what, func() error {
return err
})
}
// setErrorFuncFor causes the given function
// to be invoked to return the error for the
// given pattern.
func (e *errorPatterns) setErrorFuncFor(what string, errFunc func() error) {
e.patterns = append(e.patterns, errorPattern{
pattern: what,
errFunc: errFunc,
})
}
// errorFor concatenates the call name
// with all the args, space separated,
// and returns any error registered with
// setErrorFor that matches the resulting string.
func (e *errorPatterns) errorFor(name string, args ...interface{}) error {
s := name
for _, arg := range args {
s += " " + fmt.Sprint(arg)
}
f := func() error { return nil }
for _, pattern := range e.patterns {
if ok, _ := path.Match(pattern.pattern, s); ok {
f = pattern.errFunc
break
}
}
err := f()
if err != nil {
logger.Errorf("errorFor %q -> %v", s, err)
}
return err
}
func (e *errorPatterns) resetErrors() {
e.patterns = e.patterns[:0]
}
func NewFakeState() *fakeState {
st := &fakeState{
controllers: make(map[string]*fakeController),
}
st.session = newFakeMongoSession(st, &st.errors)
st.controllerConfig.Set(controller.Config{})
return st
}
func (st *fakeState) getCheck() func(st *fakeState) error {
st.checkMu.Lock()
check := st.check
st.checkMu.Unlock()
return check
}
func (st *fakeState) setCheck(check func(st *fakeState) error) {
st.checkMu.Lock()
st.check = check
st.checkMu.Unlock()
}
func (st *fakeState) checkInvariants() {
check := st.getCheck()
if check == nil {
return
}
if err := check(st); err != nil {
// Force a panic, otherwise we can deadlock
// when called from within the worker.
go panic(err)
select {}
}
}
// checkInvariants checks that all the expected invariants
// in the state hold true. Currently we check that:
// - total number of votes is odd.
// - member voting status implies that controller has vote.
func checkInvariants(st *fakeState) error {
st.mu.Lock()
defer st.mu.Unlock()
members := st.session.members.Get().([]replicaset.Member)
voteCount := 0
for _, m := range members {
votes := 1
if m.Votes != nil {
votes = *m.Votes
}
voteCount += votes
if id, ok := m.Tags[jujuNodeKey]; ok {
if votes > 0 {
m := st.controllers[id]
if m == nil {
return fmt.Errorf("voting member with controller id %q has no associated Controller", id)
}
}
}
}
if voteCount%2 != 1 {
return fmt.Errorf("total vote count is not odd (got %d)", voteCount)
}
return nil
}
type invariantChecker interface {
checkInvariants()
}
// controller is similar to Controller except that
// it bypasses the error mocking machinery.
// It returns nil if there is no controller with the
// given id.
func (st *fakeState) controller(id string) *fakeController {
st.mu.Lock()
defer st.mu.Unlock()
return st.controllers[id]
}
func (st *fakeState) ControllerNode(id string) (ControllerNode, error) {
if err := st.errors.errorFor("State.ControllerNode", id); err != nil {
return nil, err
}
if m := st.controller(id); m != nil {
return m, nil
}
return nil, errors.NotFoundf("controller %s", id)
}
func (st *fakeState) ControllerHost(id string) (ControllerHost, error) {
if err := st.errors.errorFor("State.ControllerHost", id); err != nil {
return nil, err
}
if m := st.controller(id); m != nil {
return m, nil
}
return nil, errors.NotFoundf("controller %s", id)
}
func (st *fakeState) addController(id string, wantsVote bool) *fakeController {
st.mu.Lock()
defer st.mu.Unlock()
logger.Infof("fakeState.addController %q", id)
if st.controllers[id] != nil {
panic(fmt.Errorf("id %q already used", id))
}
doc := controllerDoc{
id: id,
wantsVote: wantsVote,
statusInfo: status.StatusInfo{Status: status.Started},
life: state.Alive,
}
m := &fakeController{
errors: &st.errors,
checker: st,
}
st.controllers[id] = m
m.val.Set(doc)
return m
}
func (st *fakeState) removeController(id string) {
st.mu.Lock()
defer st.mu.Unlock()
if st.controllers[id] == nil {
panic(fmt.Errorf("removing non-existent controller %q", id))
}
delete(st.controllers, id)
}
func (st *fakeState) setControllers(ids ...string) {
st.controllerInfo.Set(&state.ControllerInfo{
ControllerIds: ids,
})
}
func (st *fakeState) ControllerIds() ([]string, error) {
if err := st.errors.errorFor("State.ControllerIds"); err != nil {
return nil, err
}
return deepCopy(st.controllerInfo.Get()).(*state.ControllerInfo).ControllerIds, nil
}
func (st *fakeState) WatchControllerInfo() state.StringsWatcher {
return WatchStrings(&st.controllerInfo)
}
func (st *fakeState) WatchControllerStatusChanges() state.StringsWatcher {
return WatchStrings(&st.statuses)
}
func (st *fakeState) WatchControllerConfig() state.NotifyWatcher {
return WatchValue(&st.controllerConfig)
}
func (st *fakeState) ModelConfig() (*config.Config, error) {
attrs := coretesting.FakeConfig()
cfg, err := config.New(config.NoDefaults, attrs)
return cfg, err
}
func (st *fakeState) ControllerConfig() (controller.Config, error) {
st.mu.Lock()
defer st.mu.Unlock()
if err := st.errors.errorFor("State.ControllerConfig"); err != nil {
return nil, err
}
return deepCopy(st.controllerConfig.Get()).(controller.Config), nil
}
func (st *fakeState) RemoveControllerReference(c ControllerNode) error {
st.mu.Lock()
defer st.mu.Unlock()
controllerInfo := st.controllerInfo.Get().(*state.ControllerInfo)
controllerIds := controllerInfo.ControllerIds
var newControllerIds []string
controllerId := c.Id()
for _, id := range controllerIds {
if id == controllerId {
continue
}
newControllerIds = append(newControllerIds, id)
}
st.setControllers(newControllerIds...)
return nil
}
func (st *fakeState) setHASpace(spaceName string) {
st.mu.Lock()
defer st.mu.Unlock()
// Ensure the configured space always exists in state.
if spaceName != network.AlphaSpaceName {
if st.spaces == nil {
st.spaces = make(map[string]*fakeSpace)
}
st.spaces[spaceName] = &fakeSpace{network.SpaceInfo{ID: spaceName, Name: network.SpaceName(spaceName)}}
}
cfg := st.controllerConfig.Get().(controller.Config)
cfg[controller.JujuHASpace] = spaceName
st.controllerConfig.Set(cfg)
}
func (st *fakeState) Space(name string) (Space, error) {
// Return a representation of the default space whenever requested.
if name == network.AlphaSpaceName {
return &fakeSpace{network.SpaceInfo{}}, nil
}
st.mu.Lock()
defer st.mu.Unlock()
space, ok := st.spaces[name]
if !ok {
return nil, errors.NotFoundf("space %q", name)
}
return space, nil
}
type fakeController struct {
mu sync.Mutex
errors *errorPatterns
val voyeur.Value // of controllerDoc
checker invariantChecker
}
type controllerDoc struct {
id string
wantsVote bool
hasVote bool
instanceId instance.Id
addresses []network.SpaceAddress
statusInfo status.StatusInfo
life state.Life
}
func (m *fakeController) doc() controllerDoc {
return m.val.Get().(controllerDoc)
}
func (m *fakeController) Refresh() error {
m.mu.Lock()
defer m.mu.Unlock()
doc := m.doc()
if err := m.errors.errorFor("Controller.Refresh", doc.id); err != nil {
return err
}
return nil
}
func (m *fakeController) GoString() string {
m.mu.Lock()
defer m.mu.Unlock()
return fmt.Sprintf("&fakeController{%#v}", m.doc())
}
func (m *fakeController) Id() string {
m.mu.Lock()
defer m.mu.Unlock()
return m.doc().id
}
func (m *fakeController) Life() state.Life {
m.mu.Lock()
defer m.mu.Unlock()
return m.doc().life
}
func (m *fakeController) Watch() state.NotifyWatcher {
m.mu.Lock()
defer m.mu.Unlock()
return WatchValue(&m.val)
}
func (m *fakeController) WantsVote() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.doc().wantsVote
}
func (m *fakeController) HasVote() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.doc().hasVote
}
func (m *fakeController) Addresses() network.SpaceAddresses {
m.mu.Lock()
defer m.mu.Unlock()
return m.doc().addresses
}
func (m *fakeController) Status() (status.StatusInfo, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.doc().statusInfo, nil
}
func (m *fakeController) SetStatus(sInfo status.StatusInfo) error {
m.mutate(func(doc *controllerDoc) {
doc.statusInfo = sInfo
})
return nil
}
// mutate atomically changes the controllerDoc of
// the receiver by mutating it with the provided function.
func (m *fakeController) mutate(f func(*controllerDoc)) {
m.mu.Lock()
doc := m.doc()
f(&doc)
m.val.Set(doc)
m.checker.checkInvariants()
m.mu.Unlock()
}
func (m *fakeController) setAddresses(addrs ...network.SpaceAddress) {
m.mutate(func(doc *controllerDoc) {
doc.addresses = addrs
})
}
// SetHasVote implements Controller.SetHasVote.
func (m *fakeController) SetHasVote(hasVote bool) error {
doc := m.doc()
if err := m.errors.errorFor("Controller.SetHasVote", doc.id, hasVote); err != nil {
return err
}
m.mutate(func(doc *controllerDoc) {
doc.hasVote = hasVote
})
return nil
}
func (m *fakeController) setWantsVote(wantsVote bool) {
m.mutate(func(doc *controllerDoc) {
doc.wantsVote = wantsVote
})
}
func (m *fakeController) advanceLifecycle(life state.Life, wantsVote bool) {
m.mutate(func(doc *controllerDoc) {
doc.life = life
doc.wantsVote = wantsVote
})
}
type fakeSpace struct {
network.SpaceInfo
}
func (s *fakeSpace) NetworkSpace() (network.SpaceInfo, error) {
return s.SpaceInfo, nil
}
type fakeMongoSession struct {
// If InstantlyReady is true, replica status of
// all members will be instantly reported as ready.
InstantlyReady bool
errors *errorPatterns
checker invariantChecker
members voyeur.Value // of []replicaset.Member
status voyeur.Value // of *replicaset.Status
}
// newFakeMongoSession returns a mock implementation of mongoSession.
func newFakeMongoSession(checker invariantChecker, errors *errorPatterns) *fakeMongoSession {
s := new(fakeMongoSession)
s.checker = checker
s.errors = errors
return s
}
// CurrentMembers implements mongoSession.CurrentMembers.
func (session *fakeMongoSession) CurrentMembers() ([]replicaset.Member, error) {
if err := session.errors.errorFor("Session.CurrentMembers"); err != nil {
return nil, err
}
return deepCopy(session.members.Get()).([]replicaset.Member), nil
}
// CurrentStatus implements mongoSession.CurrentStatus.
func (session *fakeMongoSession) CurrentStatus() (*replicaset.Status, error) {
if err := session.errors.errorFor("Session.CurrentStatus"); err != nil {
return nil, err
}
return deepCopy(session.status.Get()).(*replicaset.Status), nil
}
func (session *fakeMongoSession) currentPrimary() string {
members := session.members.Get().([]replicaset.Member)
status := session.status.Get().(*replicaset.Status)
for _, statusMember := range status.Members {
if statusMember.State == replicaset.PrimaryState {
for _, member := range members {
if member.Id == statusMember.Id {
return member.Tags["juju-machine-id"]
}
}
}
}
return ""
}
// setStatus sets the status of the current members of the session.
func (session *fakeMongoSession) setStatus(members []replicaset.MemberStatus) {
session.status.Set(deepCopy(&replicaset.Status{
Members: members,
}))
}
// Set implements mongoSession.Set
func (session *fakeMongoSession) Set(members []replicaset.Member) error {
if err := session.errors.errorFor("Session.Set"); err != nil {
logger.Infof("NOT setting replicaset members to \n%s", prettyReplicaSetMembersSlice(members))
return err
}
logger.Infof("setting replicaset members to \n%s", prettyReplicaSetMembersSlice(members))
session.members.Set(deepCopy(members))
if session.InstantlyReady {
statuses := make([]replicaset.MemberStatus, len(members))
for i, m := range members {
statuses[i] = replicaset.MemberStatus{
Id: m.Id,
Address: m.Address,
Healthy: true,
State: replicaset.SecondaryState,
}
if i == 0 {
statuses[i].State = replicaset.PrimaryState
}
}
session.setStatus(statuses)
}
session.checker.checkInvariants()
return nil
}
func (session *fakeMongoSession) StepDownPrimary() error {
if err := session.errors.errorFor("Session.StepDownPrimary"); err != nil {
logger.Debugf("StepDownPrimary error: %v", err)
return err
}
logger.Debugf("StepDownPrimary")
status := session.status.Get().(*replicaset.Status)
members := session.members.Get().([]replicaset.Member)
membersById := make(map[int]replicaset.Member, len(members))
for _, member := range members {
membersById[member.Id] = member
}
// We use a simple algorithm, find the primary, and all the secondaries that don't have 0 priority. And then pick a
// random secondary and swap their states
primaryIndex := -1
secondaryIndexes := []int{}
var info []string
for i, statusMember := range status.Members {
if statusMember.State == replicaset.PrimaryState {
primaryIndex = i
info = append(info, fmt.Sprintf("%d: current primary", statusMember.Id))
} else if statusMember.State == replicaset.SecondaryState {
confMember := membersById[statusMember.Id]
if confMember.Priority == nil || *confMember.Priority > 0 {
secondaryIndexes = append(secondaryIndexes, i)
info = append(info, fmt.Sprintf("%d: eligible secondary", statusMember.Id))
} else {
info = append(info, fmt.Sprintf("%d: ineligible secondary", statusMember.Id))
}
}
}
if primaryIndex == -1 {
return errors.Errorf("no primary to step down, broken config?")
}
if len(secondaryIndexes) < 1 {
return errors.Errorf("no secondaries to switch to")
}
secondaryIndex := secondaryIndexes[rand.Intn(len(secondaryIndexes))]
status.Members[primaryIndex].State = replicaset.SecondaryState
status.Members[secondaryIndex].State = replicaset.PrimaryState
logger.Debugf("StepDownPrimary nominated %d to be the new primary from: %v",
status.Members[secondaryIndex].Id, info)
session.setStatus(status.Members)
return nil
}
func (session *fakeMongoSession) Refresh() {
// If this was a testing.Stub we would track that Refresh was called.
}
// prettyReplicaSetMembersSlice wraps prettyReplicaSetMembers for testing
// purposes only.
func prettyReplicaSetMembersSlice(members []replicaset.Member) string {
vrm := make(map[string]*replicaset.Member, len(members))
for i := range members {
m := members[i]
vrm[strconv.Itoa(m.Id)] = &m
}
return prettyReplicaSetMembers(vrm)
}
// deepCopy makes a deep copy of any type by marshalling
// it as JSON, then unmarshalling it.
func deepCopy(x interface{}) interface{} {
v := reflect.ValueOf(x)
data, err := json.Marshal(x)
if err != nil {
panic(fmt.Errorf("cannot marshal %#v: %v", x, err))
}
newv := reflect.New(v.Type())
if err := json.Unmarshal(data, newv.Interface()); err != nil {
panic(fmt.Errorf("cannot unmarshal %q into %s", data, newv.Type()))
}
// sanity check
newx := newv.Elem().Interface()
if !reflect.DeepEqual(newx, x) {
panic(fmt.Errorf("value not deep-copied correctly"))
}
return newx
}
type notifier struct {
tomb tomb.Tomb
w *voyeur.Watcher
changes chan struct{}
}
func (n *notifier) loop() {
for n.w.Next() {
select {
case n.changes <- struct{}{}:
case <-n.tomb.Dying():
}
}
}
// WatchValue returns a NotifyWatcher that triggers
// when the given value changes. Its Wait and Err methods
// never return a non-nil error.
func WatchValue(val *voyeur.Value) state.NotifyWatcher {
n := ¬ifier{
w: val.Watch(),
changes: make(chan struct{}),
}
n.tomb.Go(func() error {
n.loop()
return nil
})
return n
}
// Changes returns a channel that sends a value when the value changes.
// The value itself can be retrieved by calling the value's Get method.
func (n *notifier) Changes() <-chan struct{} {
return n.changes
}
// Kill stops the notifier but does not wait for it to finish.
func (n *notifier) Kill() {
n.tomb.Kill(nil)
n.w.Close()
}
func (n *notifier) Err() error {
return n.tomb.Err()
}
// Wait waits for the notifier to finish. It always returns nil.
func (n *notifier) Wait() error {
return n.tomb.Wait()
}
func (n *notifier) Stop() error {
return worker.Stop(n)
}
type stringsNotifier struct {
tomb tomb.Tomb
w *voyeur.Watcher
changes chan []string
}
// WatchStrings returns a StringsWatcher that triggers
// when the given value changes. Its Wait and Err methods
// never return a non-nil error.
func WatchStrings(val *voyeur.Value) state.StringsWatcher {
n := &stringsNotifier{
w: val.Watch(),
changes: make(chan []string),
}
n.tomb.Go(func() error {
n.loop()
return nil
})
return n
}
func (n *stringsNotifier) loop() {
for n.w.Next() {
select {
case n.changes <- []string{}:
case <-n.tomb.Dying():
}
}
}
// Changes returns a channel that sends a value when the value changes.
// The value itself can be retrieved by calling the value's Get method.
func (n *stringsNotifier) Changes() <-chan []string {
return n.changes
}
// Kill stops the notifier but does not wait for it to finish.
func (n *stringsNotifier) Kill() {
n.tomb.Kill(nil)
n.w.Close()
}
func (n *stringsNotifier) Err() error {
return n.tomb.Err()
}
// Wait waits for the notifier to finish. It always returns nil.
func (n *stringsNotifier) Wait() error {
return n.tomb.Wait()
}
func (n *stringsNotifier) Stop() error {
return worker.Stop(n)
}