-
Notifications
You must be signed in to change notification settings - Fork 51
/
monitor.go
637 lines (524 loc) · 18.4 KB
/
monitor.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
package dockermonitor
import (
"context"
"errors"
"fmt"
"io"
"os"
"runtime"
"strconv"
"time"
"go.uber.org/zap"
"github.com/dchest/siphash"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"go.aporeto.io/trireme-lib/collector"
"go.aporeto.io/trireme-lib/common"
"go.aporeto.io/trireme-lib/monitor/constants"
"go.aporeto.io/trireme-lib/policy"
tevents "go.aporeto.io/trireme-lib/common"
"go.aporeto.io/trireme-lib/monitor/config"
"go.aporeto.io/trireme-lib/monitor/extractors"
"go.aporeto.io/trireme-lib/monitor/registerer"
"go.aporeto.io/trireme-lib/utils/cgnetcls"
"go.aporeto.io/trireme-lib/utils/portspec"
dockerClient "github.com/docker/docker/client"
)
// DockerMonitor implements the connection to Docker and monitoring based on docker events.
type DockerMonitor struct {
dockerClient dockerClient.CommonAPIClient
socketType string
socketAddress string
metadataExtractor extractors.DockerMetadataExtractor
handlers map[Event]func(ctx context.Context, event *events.Message) error
eventnotifications []chan *events.Message
stopprocessor []chan bool
numberOfQueues int
stoplistener chan bool
config *config.ProcessorConfig
netcls cgnetcls.Cgroupnetcls
killContainerOnPolicyError bool
syncAtStart bool
}
// New returns a new docker monitor.
func New() *DockerMonitor {
return &DockerMonitor{}
}
// SetupConfig provides a configuration to implmentations. Every implementation
// can have its own config type.
func (d *DockerMonitor) SetupConfig(registerer registerer.Registerer, cfg interface{}) (err error) {
defaultConfig := DefaultConfig()
if cfg == nil {
cfg = defaultConfig
}
dockerConfig, ok := cfg.(*Config)
if !ok {
return fmt.Errorf("Invalid configuration specified")
}
// Setup defaults
dockerConfig = SetupDefaultConfig(dockerConfig)
d.socketType = dockerConfig.SocketType
d.socketAddress = dockerConfig.SocketAddress
d.metadataExtractor = dockerConfig.EventMetadataExtractor
d.syncAtStart = dockerConfig.SyncAtStart
d.killContainerOnPolicyError = dockerConfig.KillContainerOnPolicyError
d.handlers = make(map[Event]func(ctx context.Context, event *events.Message) error)
d.stoplistener = make(chan bool)
d.netcls = cgnetcls.NewDockerCgroupNetController()
d.numberOfQueues = runtime.NumCPU() * 8
d.eventnotifications = make([]chan *events.Message, d.numberOfQueues)
d.stopprocessor = make([]chan bool, d.numberOfQueues)
for i := 0; i < d.numberOfQueues; i++ {
d.eventnotifications[i] = make(chan *events.Message, 1000)
d.stopprocessor[i] = make(chan bool)
}
// Add handlers for the events that we know how to process
d.addHandler(EventCreate, d.handleCreateEvent)
d.addHandler(EventStart, d.handleStartEvent)
d.addHandler(EventDie, d.handleDieEvent)
d.addHandler(EventDestroy, d.handleDestroyEvent)
d.addHandler(EventPause, d.handlePauseEvent)
d.addHandler(EventUnpause, d.handleUnpauseEvent)
return nil
}
// SetupHandlers sets up handlers for monitors to invoke for various events such as
// processing unit events and synchronization events. This will be called before Start()
// by the consumer of the monitor
func (d *DockerMonitor) SetupHandlers(c *config.ProcessorConfig) {
d.config = c
}
// Run will start the DockerPolicy Enforcement.
// It applies a policy to each Container already Up and Running.
// It listens to all ContainerEvents
func (d *DockerMonitor) Run(ctx context.Context) error {
if err := d.config.IsComplete(); err != nil {
return fmt.Errorf("docker: %s", err)
}
err := d.waitForDockerDaemon(ctx)
if err != nil {
zap.L().Error("Docker daemon is not running - skipping container processing", zap.Error(err))
return nil
}
if d.syncAtStart && d.config.Policy != nil {
options := types.ContainerListOptions{All: true}
containers, err := d.dockerClient.ContainerList(ctx, options)
if err != nil {
return fmt.Errorf("unable to get container list: %s", err)
}
// Starting the eventListener and wait to hear on channel for it to be ready.
// Need to start before the resync process so that we don't loose any events.
// They will be buffered. We don't want to start the listener before
// getting the list from docker though, to avoid duplicates.
listenerReady := make(chan struct{})
go d.eventListener(ctx, listenerReady)
<-listenerReady
zap.L().Debug("Syncing all existing containers")
// Syncing all Existing containers depending on MonitorSetting
if err := d.resyncContainers(ctx, containers); err != nil {
zap.L().Error("Unable to sync existing containers", zap.Error(err))
}
} else {
// Starting the eventListener and wait to hear on channel for it to be ready.
// We are not doing resync. We just start the listener.
listenerReady := make(chan struct{})
go d.eventListener(ctx, listenerReady)
<-listenerReady
}
// Start processing the events
go d.eventProcessors(ctx)
return nil
}
// addHandler adds a callback handler for the given docker event.
// Interesting event names include 'start' and 'die'. For more on events see
// https://docs.docker.com/engine/reference/api/docker_remote_api/
// under the section 'Docker Events'.
func (d *DockerMonitor) addHandler(event Event, handler EventHandler) {
d.handlers[event] = handler
}
// sendRequestToQueue sends a request to a channel based on a hash function
func (d *DockerMonitor) sendRequestToQueue(r *events.Message) {
key0 := uint64(256203161)
key1 := uint64(982451653)
h := siphash.Hash(key0, key1, []byte(r.ID))
d.eventnotifications[int(h%uint64(d.numberOfQueues))] <- r
}
// eventProcessor processes docker events. We are processing multiple
// queues in parallel so that we can activate containers as fast
// as possible.
func (d *DockerMonitor) eventProcessors(ctx context.Context) {
for i := 0; i < d.numberOfQueues; i++ {
go func(i int) {
for {
select {
case event := <-d.eventnotifications[i]:
if f, ok := d.handlers[Event(event.Action)]; ok {
if err := f(ctx, event); err != nil {
zap.L().Error("Unable to handle docker event",
zap.String("action", event.Action),
zap.Error(err),
)
}
continue
}
case <-ctx.Done():
return
}
}
}(i)
}
}
// eventListener listens to Docker events from the daemon and passes to
// to the processor through a buffered channel. This minimizes the chances
// that we will miss events because the processor is delayed
func (d *DockerMonitor) eventListener(ctx context.Context, listenerReady chan struct{}) {
f := filters.NewArgs()
f.Add("type", "container")
options := types.EventsOptions{
Filters: f,
}
messages, errs := d.dockerClient.Events(context.Background(), options)
// Once the buffered event channel was returned by Docker we return the ready status.
listenerReady <- struct{}{}
for {
select {
case message := <-messages:
zap.L().Debug("Got message from docker client",
zap.String("action", message.Action),
zap.String("ID", message.ID),
)
d.sendRequestToQueue(&message)
case err := <-errs:
if err != nil && err != io.EOF {
zap.L().Warn("Received docker event error",
zap.Error(err),
)
}
case <-ctx.Done():
return
}
}
}
// Resync resyncs all the existing containers on the Host, using the
// same process as when a container is initially spawn up
func (d *DockerMonitor) Resync(ctx context.Context) error {
if !d.syncAtStart || d.config.Policy == nil {
zap.L().Debug("No synchronization of containers performed")
return nil
}
zap.L().Debug("Syncing all existing containers")
options := types.ContainerListOptions{All: true}
containers, err := d.dockerClient.ContainerList(ctx, options)
if err != nil {
return fmt.Errorf("unable to get container list: %s", err)
}
return d.resyncContainers(ctx, containers)
}
func (d *DockerMonitor) resyncContainers(ctx context.Context, containers []types.Container) error {
// now resync the old containers
for _, c := range containers {
container, err := d.dockerClient.ContainerInspect(ctx, c.ID)
if err != nil {
continue
}
puID, _ := puIDFromDockerID(container.ID)
runtime, err := d.extractMetadata(&container)
if err != nil {
continue
}
event := common.EventStop
if container.State.Running {
if !container.State.Paused {
event = common.EventStart
} else {
event = common.EventPause
}
}
if container.HostConfig.NetworkMode == constants.DockerHostMode {
options := hostModeOptions(&container)
options.PolicyExtensions = runtime.Options().PolicyExtensions
runtime.SetOptions(*options)
runtime.SetPUType(common.LinuxProcessPU)
}
if err := d.config.Policy.HandlePUEvent(ctx, puID, event, runtime); err != nil {
zap.L().Error("Unable to sync existing Container",
zap.String("dockerID", c.ID),
zap.Error(err),
)
}
}
return nil
}
// setupHostMode sets up the net_cls cgroup for the host mode
func (d *DockerMonitor) setupHostMode(puID string, runtimeInfo *policy.PURuntime, dockerInfo *types.ContainerJSON) (err error) {
if err = d.netcls.Creategroup(puID); err != nil {
return err
}
// Clean the cgroup on exit, if we have failed t activate.
defer func() {
if err != nil {
if derr := d.netcls.DeleteCgroup(puID); derr != nil {
zap.L().Warn("Failed to clean cgroup",
zap.String("puID", puID),
zap.Error(derr),
zap.Error(err),
)
}
}
}()
markval := runtimeInfo.Options().CgroupMark
if markval == "" {
return errors.New("mark value not found")
}
mark, _ := strconv.ParseUint(markval, 10, 32)
if err := d.netcls.AssignMark(puID, mark); err != nil {
return err
}
if err := d.netcls.AddProcess(puID, dockerInfo.State.Pid); err != nil {
return err
}
return nil
}
func (d *DockerMonitor) retrieveDockerInfo(ctx context.Context, event *events.Message) (*types.ContainerJSON, error) {
info, err := d.dockerClient.ContainerInspect(ctx, event.ID)
if err != nil {
// If we see errors, we will kill the container for security reasons if DockerMonitor was configured to do so.
if d.killContainerOnPolicyError {
timeout := 0 * time.Second
if err1 := d.dockerClient.ContainerStop(ctx, event.ID, &timeout); err1 != nil {
zap.L().Warn("Unable to stop illegal container",
zap.String("dockerID", event.ID),
zap.Error(err1),
)
}
d.config.Collector.CollectContainerEvent(&collector.ContainerRecord{
ContextID: event.ID,
IPAddress: nil,
Tags: nil,
Event: collector.ContainerFailed,
})
return nil, fmt.Errorf("unable to read container information: container %s killed: %s", event.ID, err)
}
return nil, fmt.Errorf("unable to read container information: container %s kept alive per policy: %s", event.ID, err)
}
return &info, nil
}
// ExtractMetadata generates the RuntimeInfo based on Docker primitive
func (d *DockerMonitor) extractMetadata(dockerInfo *types.ContainerJSON) (*policy.PURuntime, error) {
if dockerInfo == nil {
return nil, errors.New("docker info is empty")
}
if d.metadataExtractor != nil {
return d.metadataExtractor(dockerInfo)
}
return extractors.DefaultMetadataExtractor(dockerInfo)
}
// handleCreateEvent generates a create event type. We extract the metadata
// and start the policy resolution at the create event. No need to wait
// for the start event.
func (d *DockerMonitor) handleCreateEvent(ctx context.Context, event *events.Message) error {
puID, err := puIDFromDockerID(event.ID)
if err != nil {
return err
}
container, err := d.retrieveDockerInfo(ctx, event)
if err != nil {
return err
}
runtime, err := d.extractMetadata(container)
if err != nil {
return err
}
// If it is a host container, we need to activate it as a Linux process. We will
// override the options that the metadata extractor provided. We will maintain
// any policy extensions in the object.
if container.HostConfig.NetworkMode == constants.DockerHostMode {
options := hostModeOptions(container)
options.PolicyExtensions = runtime.Options().PolicyExtensions
runtime.SetOptions(*options)
runtime.SetPUType(common.LinuxProcessPU)
}
return d.config.Policy.HandlePUEvent(ctx, puID, tevents.EventCreate, runtime)
}
// handleStartEvent will notify the policy engine immediately about the event in order
// to start the implementation of the functions. At this point we know the process ID
// that is needed for the remote enforcers.
func (d *DockerMonitor) handleStartEvent(ctx context.Context, event *events.Message) error {
container, err := d.retrieveDockerInfo(ctx, event)
if err != nil {
return err
}
if !container.State.Running {
return nil
}
puID, err := puIDFromDockerID(container.ID)
if err != nil {
return err
}
runtime, err := d.extractMetadata(container)
if err != nil {
return err
}
// If it is a host container, we need to activate it as a Linux process. We will
// override the options that the metadata extractor provided.
if container.HostConfig.NetworkMode == constants.DockerHostMode {
options := hostModeOptions(container)
options.PolicyExtensions = runtime.Options().PolicyExtensions
runtime.SetOptions(*options)
runtime.SetPUType(common.LinuxProcessPU)
}
if err = d.config.Policy.HandlePUEvent(ctx, puID, tevents.EventStart, runtime); err != nil {
if d.killContainerOnPolicyError {
timeout := 0 * time.Second
if err1 := d.dockerClient.ContainerStop(ctx, event.ID, &timeout); err1 != nil {
zap.L().Warn("Unable to stop illegal container",
zap.String("dockerID", event.ID),
zap.Error(err1),
)
}
d.config.Collector.CollectContainerEvent(&collector.ContainerRecord{
ContextID: event.ID,
IPAddress: nil,
Tags: nil,
Event: collector.ContainerFailed,
})
return fmt.Errorf("unable to start container because of policy: container %s killed: %s", event.ID, err)
}
return fmt.Errorf("unable to set policy: container %s kept alive per policy: %s", puID, err)
}
if container.HostConfig.NetworkMode == constants.DockerHostMode {
if err = d.setupHostMode(puID, runtime, container); err != nil {
return fmt.Errorf("unable to setup host mode for container %s: %s", puID, err)
}
}
return nil
}
//handleDie event is called when a container dies. It generates a "Stop" event.
func (d *DockerMonitor) handleDieEvent(ctx context.Context, event *events.Message) error {
puID, err := puIDFromDockerID(event.ID)
if err != nil {
return err
}
return d.config.Policy.HandlePUEvent(ctx, puID, tevents.EventStop, policy.NewPURuntimeWithDefaults())
}
// handleDestroyEvent handles destroy events from Docker. It generated a "Destroy event"
func (d *DockerMonitor) handleDestroyEvent(ctx context.Context, event *events.Message) error {
puID, err := puIDFromDockerID(event.ID)
if err != nil {
return err
}
err = d.config.Policy.HandlePUEvent(ctx, puID, tevents.EventDestroy, policy.NewPURuntimeWithDefaults())
if err != nil {
zap.L().Error("Failed to handle delete event",
zap.Error(err),
)
}
if err := d.netcls.DeleteCgroup(puID); err != nil {
zap.L().Warn("Failed to clean netcls group",
zap.String("puID", puID),
zap.Error(err),
)
}
return nil
}
// handlePauseEvent generates a create event type.
func (d *DockerMonitor) handlePauseEvent(ctx context.Context, event *events.Message) error {
zap.L().Info("UnPause Event for nativeID", zap.String("ID", event.ID))
puID, err := puIDFromDockerID(event.ID)
if err != nil {
return err
}
return d.config.Policy.HandlePUEvent(ctx, puID, tevents.EventPause, policy.NewPURuntimeWithDefaults())
}
// handleCreateEvent generates a create event type.
func (d *DockerMonitor) handleUnpauseEvent(ctx context.Context, event *events.Message) error {
puID, err := puIDFromDockerID(event.ID)
if err != nil {
return err
}
return d.config.Policy.HandlePUEvent(ctx, puID, tevents.EventUnpause, policy.NewPURuntimeWithDefaults())
}
func puIDFromDockerID(dockerID string) (string, error) {
if dockerID == "" {
return "", errors.New("unable to generate context id: empty docker id")
}
if len(dockerID) < 12 {
return "", fmt.Errorf("unable to generate context id: dockerid smaller than 12 characters: %s", dockerID)
}
return dockerID[:12], nil
}
func initDockerClient(socketType string, socketAddress string) (*dockerClient.Client, error) {
var socket string
switch socketType {
case "tcp":
socket = "https://" + socketAddress
case "unix":
// Sanity check that this path exists
if _, oserr := os.Stat(socketAddress); os.IsNotExist(oserr) {
return nil, oserr
}
socket = "unix://" + socketAddress
default:
return nil, fmt.Errorf("bad socket type: %s", socketType)
}
defaultHeaders := map[string]string{"User-Agent": "engine-api-dockerClient-1.0"}
dc, err := dockerClient.NewClient(socket, DockerClientVersion, nil, defaultHeaders)
if err != nil {
return nil, fmt.Errorf("unable to create docker client: %s", err)
}
return dc, nil
}
func (d *DockerMonitor) setupDockerDaemon() (err error) {
if d.dockerClient == nil {
// Initialize client
if d.dockerClient, err = initDockerClient(d.socketType, d.socketAddress); err != nil {
return err
}
}
ctx, cancel := context.WithTimeout(context.Background(), dockerPingTimeout)
defer cancel()
_, err = d.dockerClient.Ping(ctx)
return err
}
// waitForDockerDaemon is a blocking call which will try to bring up docker, if not return err
// with timeout
func (d *DockerMonitor) waitForDockerDaemon(ctx context.Context) (err error) {
done := make(chan bool)
go func() {
for errg := d.setupDockerDaemon(); errg != nil; {
zap.L().Debug("Unable to init docker client. Retrying...", zap.Error(errg))
<-time.After(dockerRetryTimer)
continue
}
done <- true
}()
select {
case <-ctx.Done():
return nil
case <-time.After(dockerInitializationWait):
return fmt.Errorf("Unable to connect to docker daemon")
case <-done:
}
return nil
}
// hostModeOptions creates the default options for a host-mode container. The
// container must be activated as a Linux Process.
func hostModeOptions(dockerInfo *types.ContainerJSON) *policy.OptionsType {
options := policy.OptionsType{
CgroupName: strconv.Itoa(dockerInfo.State.Pid),
CgroupMark: strconv.FormatUint(cgnetcls.MarkVal(), 10),
}
for p := range dockerInfo.Config.ExposedPorts {
if p.Proto() == "tcp" {
s, err := portspec.NewPortSpecFromString(p.Port(), nil)
if err != nil {
continue
}
options.Services = append(options.Services, common.Service{
Protocol: uint8(6),
Ports: s,
})
}
}
return &options
}