Skip to content

Commit 4a88643

Browse files
gitforbitamelhusic
authored andcommitted
MEDIUM: watcher: fix race condition & plumbing stop for test
1 parent f8963ae commit 4a88643

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

consul/watcher.go

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,9 @@ type Watcher struct {
6060
certCAPool *x509.CertPool
6161
leaf *certLeaf
6262

63-
update chan struct{}
64-
log Logger
63+
update chan struct{}
64+
shutdownCh chan struct{}
65+
log Logger
6566
}
6667

6768
// New builds a new watcher
@@ -70,10 +71,11 @@ func New(service string, consul *api.Client, log Logger) *Watcher {
7071
service: service,
7172
consul: consul,
7273

73-
C: make(chan Config),
74-
upstreams: make(map[string]*upstream),
75-
update: make(chan struct{}, 1),
76-
log: log,
74+
C: make(chan Config),
75+
upstreams: make(map[string]*upstream),
76+
update: make(chan struct{}, 1),
77+
shutdownCh: make(chan struct{}),
78+
log: log,
7779
}
7880
}
7981

@@ -182,9 +184,11 @@ func (w *Watcher) startUpstream(up api.Upstream) {
182184
go func() {
183185
index := uint64(0)
184186
for {
187+
w.lock.Lock()
185188
if u.done {
186189
return
187190
}
191+
w.lock.Unlock()
188192
nodes, meta, err := w.consul.Health().Connect(up.DestinationName, "", true, &api.QueryOptions{
189193
Datacenter: up.Datacenter,
190194
WaitTime: 10 * time.Minute,
@@ -255,6 +259,9 @@ func (w *Watcher) watchLeaf() {
255259
w.ready.Done()
256260
first = false
257261
}
262+
if w.isStopped() {
263+
return
264+
}
258265
}
259266
}
260267

@@ -285,6 +292,9 @@ func (w *Watcher) watchService(service string, handler func(first bool, srv *api
285292
}
286293

287294
first = false
295+
if w.isStopped() {
296+
return
297+
}
288298
}
289299
}
290300

@@ -329,6 +339,9 @@ func (w *Watcher) watchCA() {
329339
w.ready.Done()
330340
first = false
331341
}
342+
if w.isStopped() {
343+
return
344+
}
332345
}
333346
}
334347

@@ -416,3 +429,16 @@ func (w *Watcher) notifyChanged() {
416429
default:
417430
}
418431
}
432+
433+
func (w *Watcher) Stop() {
434+
close(w.shutdownCh)
435+
}
436+
437+
func (w *Watcher) isStopped() bool {
438+
select {
439+
case <-w.shutdownCh:
440+
return true
441+
default:
442+
return false
443+
}
444+
}

utils_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ func startConnectService(t *testing.T, sd *lib.Shutdown, client *api.Client, reg
7070
errs <- err
7171
}
7272
}()
73+
watcher.Stop()
7374

7475
sourceHap := haproxy.New(client, watcher.C, haproxy.Options{
7576
EnableIntentions: true,

0 commit comments

Comments
 (0)