-
Notifications
You must be signed in to change notification settings - Fork 712
/
registry.go
339 lines (284 loc) · 8.1 KB
/
registry.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
package docker
import (
"sync"
"time"
log "github.com/Sirupsen/logrus"
docker_client "github.com/fsouza/go-dockerclient"
"github.com/weaveworks/scope/probe/controls"
)
// Consts exported for testing.
const (
CreateEvent = "create"
DestroyEvent = "destroy"
StartEvent = "start"
DieEvent = "die"
PauseEvent = "pause"
UnpauseEvent = "unpause"
endpoint = "unix:///var/run/docker.sock"
)
// Vars exported for testing.
var (
NewDockerClientStub = newDockerClient
NewContainerStub = NewContainer
)
// Registry keeps track of running docker containers and their images
type Registry interface {
Stop()
LockedPIDLookup(f func(func(int) Container))
WalkContainers(f func(Container))
WalkImages(f func(*docker_client.APIImages))
WatchContainerUpdates(ContainerUpdateWatcher)
GetContainer(string) (Container, bool)
}
// ContainerUpdateWatcher is the type of functions that get called when containers are updated.
type ContainerUpdateWatcher func(c Container)
type registry struct {
sync.RWMutex
quit chan chan struct{}
interval time.Duration
client Client
pipes controls.PipeClient
watchers []ContainerUpdateWatcher
containers map[string]Container
containersByPID map[int]Container
images map[string]*docker_client.APIImages
}
// Client interface for mocking.
type Client interface {
ListContainers(docker_client.ListContainersOptions) ([]docker_client.APIContainers, error)
InspectContainer(string) (*docker_client.Container, error)
ListImages(docker_client.ListImagesOptions) ([]docker_client.APIImages, error)
AddEventListener(chan<- *docker_client.APIEvents) error
RemoveEventListener(chan *docker_client.APIEvents) error
StopContainer(string, uint) error
StartContainer(string, *docker_client.HostConfig) error
RestartContainer(string, uint) error
PauseContainer(string) error
UnpauseContainer(string) error
AttachToContainerNonBlocking(docker_client.AttachToContainerOptions) (docker_client.CloseWaiter, error)
CreateExec(docker_client.CreateExecOptions) (*docker_client.Exec, error)
StartExecNonBlocking(string, docker_client.StartExecOptions) (docker_client.CloseWaiter, error)
}
func newDockerClient(endpoint string) (Client, error) {
return docker_client.NewClient(endpoint)
}
// NewRegistry returns a usable Registry. Don't forget to Stop it.
func NewRegistry(interval time.Duration, pipes controls.PipeClient) (Registry, error) {
client, err := NewDockerClientStub(endpoint)
if err != nil {
return nil, err
}
r := ®istry{
containers: map[string]Container{},
containersByPID: map[int]Container{},
images: map[string]*docker_client.APIImages{},
client: client,
pipes: pipes,
interval: interval,
quit: make(chan chan struct{}),
}
r.registerControls()
go r.loop()
return r, nil
}
// Stop stops the Docker registry's event subscriber.
func (r *registry) Stop() {
r.deregisterControls()
ch := make(chan struct{})
r.quit <- ch
<-ch
}
// WatchContainerUpdates registers a callback to be called
// whenever a container is updated.
func (r *registry) WatchContainerUpdates(f ContainerUpdateWatcher) {
r.Lock()
defer r.Unlock()
r.watchers = append(r.watchers, f)
}
func (r *registry) loop() {
for {
// NB listenForEvents blocks.
// Returning false means we should exit.
if !r.listenForEvents() {
return
}
// Sleep here so we don't hammer the
// logs if docker is down
time.Sleep(r.interval)
}
}
func (r *registry) listenForEvents() bool {
// First we empty the store lists.
// This ensure any containers that went away inbetween calls to
// listenForEvents don't hang around.
r.reset()
// Next, start listening for events. We do this before fetching
// the list of containers so we don't miss containers created
// after listing but before listening for events.
events := make(chan *docker_client.APIEvents)
if err := r.client.AddEventListener(events); err != nil {
log.Errorf("docker registry: %s", err)
return true
}
defer func() {
if err := r.client.RemoveEventListener(events); err != nil {
log.Errorf("docker registry: %s", err)
}
}()
if err := r.updateContainers(); err != nil {
log.Errorf("docker registry: %s", err)
return true
}
if err := r.updateImages(); err != nil {
log.Errorf("docker registry: %s", err)
return true
}
otherUpdates := time.Tick(r.interval)
for {
select {
case event, ok := <-events:
if !ok {
log.Errorf("docker registry: event listener unexpectedly disconnected")
return true
}
r.handleEvent(event)
case <-otherUpdates:
if err := r.updateImages(); err != nil {
log.Errorf("docker registry: %s", err)
return true
}
case ch := <-r.quit:
r.Lock()
defer r.Unlock()
for _, c := range r.containers {
c.StopGatheringStats()
}
close(ch)
return false
}
}
}
func (r *registry) reset() {
r.Lock()
defer r.Unlock()
for _, c := range r.containers {
c.StopGatheringStats()
}
r.containers = map[string]Container{}
r.containersByPID = map[int]Container{}
r.images = map[string]*docker_client.APIImages{}
}
func (r *registry) updateContainers() error {
apiContainers, err := r.client.ListContainers(docker_client.ListContainersOptions{All: true})
if err != nil {
return err
}
for _, apiContainer := range apiContainers {
r.updateContainerState(apiContainer.ID)
}
return nil
}
func (r *registry) updateImages() error {
images, err := r.client.ListImages(docker_client.ListImagesOptions{})
if err != nil {
return err
}
r.Lock()
defer r.Unlock()
for i := range images {
image := &images[i]
r.images[image.ID] = image
}
return nil
}
func (r *registry) handleEvent(event *docker_client.APIEvents) {
switch event.Status {
case CreateEvent, StartEvent, DieEvent, DestroyEvent, PauseEvent, UnpauseEvent:
r.updateContainerState(event.ID)
}
}
func (r *registry) updateContainerState(containerID string) {
r.Lock()
defer r.Unlock()
dockerContainer, err := r.client.InspectContainer(containerID)
if err != nil {
// Don't spam the logs if the container was short lived
if _, ok := err.(*docker_client.NoSuchContainer); !ok {
log.Errorf("Error processing event for container %s: %v", containerID, err)
return
}
// Container doesn't exist anymore, so lets stop and remove it
container, ok := r.containers[containerID]
if !ok {
return
}
delete(r.containers, containerID)
delete(r.containersByPID, container.PID())
container.StopGatheringStats()
return
}
// Container exists, ensure we have it
c, ok := r.containers[containerID]
if !ok {
c = NewContainerStub(dockerContainer)
r.containers[containerID] = c
} else {
// potentially remove existing pid mapping.
delete(r.containersByPID, c.PID())
c.UpdateState(dockerContainer)
}
// Update PID index
if c.PID() > 1 {
r.containersByPID[c.PID()] = c
}
// Trigger anyone watching for updates
for _, f := range r.watchers {
f(c)
}
// And finally, ensure we gather stats for it
if dockerContainer.State.Running {
if err := c.StartGatheringStats(); err != nil {
log.Errorf("Error gather stats for container: %s", containerID)
return
}
} else {
c.StopGatheringStats()
}
}
// LockedPIDLookup runs f under a read lock, and gives f a function for
// use doing pid->container lookups.
func (r *registry) LockedPIDLookup(f func(func(int) Container)) {
r.RLock()
defer r.RUnlock()
lookup := func(pid int) Container {
return r.containersByPID[pid]
}
f(lookup)
}
// WalkContainers runs f on every running containers the registry knows of.
func (r *registry) WalkContainers(f func(Container)) {
r.RLock()
defer r.RUnlock()
for _, container := range r.containers {
f(container)
}
}
func (r *registry) GetContainer(id string) (Container, bool) {
r.RLock()
defer r.RUnlock()
c, ok := r.containers[id]
return c, ok
}
// WalkImages runs f on every image of running containers the registry
// knows of. f may be run on the same image more than once.
func (r *registry) WalkImages(f func(*docker_client.APIImages)) {
r.RLock()
defer r.RUnlock()
// Loop over containers so we only emit images for running containers.
for _, container := range r.containers {
image, ok := r.images[container.Image()]
if ok {
f(image)
}
}
}