-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
93 lines (78 loc) · 1.89 KB
/
memory.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
package memory // import "github.com/docker/docker/pkg/discovery/memory"
import (
"sync"
"time"
"github.com/docker/docker/pkg/discovery"
)
// Discovery implements a discovery backend that keeps
// data in memory.
type Discovery struct {
heartbeat time.Duration
values []string
mu sync.Mutex
}
func init() {
Init()
}
// Init registers the memory backend on demand.
func Init() {
discovery.Register("memory", &Discovery{})
}
// Initialize sets the heartbeat for the memory backend.
func (s *Discovery) Initialize(_ string, heartbeat time.Duration, _ time.Duration, _ map[string]string) error {
s.heartbeat = heartbeat
s.values = make([]string, 0)
return nil
}
// Watch sends periodic discovery updates to a channel.
func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) {
ch := make(chan discovery.Entries)
errCh := make(chan error)
ticker := time.NewTicker(s.heartbeat)
go func() {
defer close(errCh)
defer close(ch)
// Send the initial entries if available.
var currentEntries discovery.Entries
var err error
s.mu.Lock()
if len(s.values) > 0 {
currentEntries, err = discovery.CreateEntries(s.values)
}
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
}
// Check if the file has really changed.
if !newEntries.Equals(currentEntries) {
ch <- newEntries
}
currentEntries = newEntries
case <-stopCh:
ticker.Stop()
return
}
}
}()
return ch, errCh
}
// 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
}