Fix a race in pkg/discovery/memory

Fix #22964

Signed-off-by: Akihiro Suda <suda.akihiro@lab.ntt.co.jp>
This commit is contained in:
Akihiro Suda 2016-05-25 02:52:35 +00:00
parent 29dbcbad87
commit 1f8fbbc0d8

View file

@ -1,16 +1,18 @@
package memory
import (
"sync"
"time"
"github.com/docker/docker/pkg/discovery"
)
// Discovery implements a descovery backend that keeps
// Discovery implements a discovery backend that keeps
// data in memory.
type Discovery struct {
heartbeat time.Duration
values []string
mu sync.Mutex
}
func init() {
@ -41,21 +43,27 @@ func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-c
// Send the initial entries if available.
var currentEntries discovery.Entries
var err error
s.mu.Lock()
if len(s.values) > 0 {
var err error
currentEntries, err = discovery.CreateEntries(s.values)
if err != nil {
errCh <- err
} else {
ch <- currentEntries
}
}
s.mu.Unlock()
if err != nil {
errCh <- err
} else if currentEntries != nil {
ch <- currentEntries
}
// Periodically send updates.
for {
select {
case <-ticker.C:
s.mu.Lock()
newEntries, err := discovery.CreateEntries(s.values)
s.mu.Unlock()
if err != nil {
errCh <- err
continue
@ -78,6 +86,8 @@ func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-c
// Register adds a new address to the discovery.
func (s *Discovery) Register(addr string) error {
s.mu.Lock()
s.values = append(s.values, addr)
s.mu.Unlock()
return nil
}