forked from docker/libcompose
/
service.go
732 lines (633 loc) · 20.5 KB
/
service.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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
package service
import (
"fmt"
"strings"
"time"
"golang.org/x/net/context"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/docker/libcompose/config"
"github.com/docker/libcompose/docker/auth"
"github.com/docker/libcompose/docker/builder"
composeclient "github.com/docker/libcompose/docker/client"
"github.com/docker/libcompose/docker/container"
"github.com/docker/libcompose/docker/ctx"
"github.com/docker/libcompose/docker/image"
"github.com/docker/libcompose/labels"
"github.com/docker/libcompose/project"
"github.com/docker/libcompose/project/events"
"github.com/docker/libcompose/project/options"
"github.com/docker/libcompose/utils"
"github.com/docker/libcompose/yaml"
)
// Service is a project.Service implementations.
type Service struct {
name string
project *project.Project
serviceConfig *config.ServiceConfig
clientFactory composeclient.Factory
authLookup auth.Lookup
// FIXME(vdemeester) remove this at some point
context *ctx.Context
}
// NewService creates a service
func NewService(name string, serviceConfig *config.ServiceConfig, context *ctx.Context) *Service {
return &Service{
name: name,
project: context.Project,
serviceConfig: serviceConfig,
clientFactory: context.ClientFactory,
authLookup: context.AuthLookup,
context: context,
}
}
// Name returns the service name.
func (s *Service) Name() string {
return s.name
}
// Config returns the configuration of the service (config.ServiceConfig).
func (s *Service) Config() *config.ServiceConfig {
return s.serviceConfig
}
// DependentServices returns the dependent services (as an array of ServiceRelationship) of the service.
func (s *Service) DependentServices() []project.ServiceRelationship {
return DefaultDependentServices(s.project, s)
}
// Create implements Service.Create. It ensures the image exists or build it
// if it can and then create a container.
func (s *Service) Create(ctx context.Context, options options.Create) error {
containers, err := s.collectContainers(ctx)
if err != nil {
return err
}
if err := s.ensureImageExists(ctx, options.NoBuild, options.ForceBuild); err != nil {
return err
}
if len(containers) != 0 {
return s.eachContainer(ctx, containers, func(c *container.Container) error {
_, err := s.recreateIfNeeded(ctx, c, options.NoRecreate, options.ForceRecreate)
return err
})
}
namer, err := s.namer(ctx, 1)
if err != nil {
return err
}
_, err = s.createContainer(ctx, namer, "", nil, false)
return err
}
func (s *Service) namer(ctx context.Context, count int) (Namer, error) {
var namer Namer
var err error
if s.serviceConfig.ContainerName != "" {
if count > 1 {
logrus.Warnf(`The "%s" service is using the custom container name "%s". Docker requires each container to have a unique name. Remove the custom name to scale the service.`, s.name, s.serviceConfig.ContainerName)
}
namer = NewSingleNamer(s.serviceConfig.ContainerName)
} else {
client := s.clientFactory.Create(s)
namer, err = NewNamer(ctx, client, s.project.Name, s.name, false)
if err != nil {
return nil, err
}
}
return namer, nil
}
func (s *Service) collectContainers(ctx context.Context) ([]*container.Container, error) {
client := s.clientFactory.Create(s)
containers, err := container.ListByFilter(ctx, client, labels.SERVICE.Eq(s.name), labels.PROJECT.Eq(s.project.Name))
if err != nil {
return nil, err
}
result := []*container.Container{}
for _, cont := range containers {
c, err := container.New(ctx, client, cont.ID)
if err != nil {
return nil, err
}
result = append(result, c)
}
return result, nil
}
func (s *Service) ensureImageExists(ctx context.Context, noBuild bool, forceBuild bool) error {
if forceBuild {
return s.build(ctx, options.Build{})
}
exists, err := image.Exists(ctx, s.clientFactory.Create(s), s.imageName())
if err != nil {
return err
}
if exists {
return nil
}
if s.Config().Build.Context != "" {
if noBuild {
return fmt.Errorf("Service %q needs to be built, but no-build was specified", s.name)
}
return s.build(ctx, options.Build{})
}
return s.Pull(ctx)
}
func (s *Service) imageName() string {
if s.Config().Image != "" {
return s.Config().Image
}
return fmt.Sprintf("%s_%s", s.project.Name, s.Name())
}
// Build implements Service.Build. It will try to build the image and returns an error if any.
func (s *Service) Build(ctx context.Context, buildOptions options.Build) error {
return s.build(ctx, buildOptions)
}
func (s *Service) build(ctx context.Context, buildOptions options.Build) error {
if s.Config().Build.Context == "" {
return fmt.Errorf("Specified service does not have a build section")
}
builder := &builder.DaemonBuilder{
Client: s.clientFactory.Create(s),
ContextDirectory: s.Config().Build.Context,
Dockerfile: s.Config().Build.Dockerfile,
BuildArgs: s.Config().Build.Args,
AuthConfigs: s.authLookup.All(),
NoCache: buildOptions.NoCache,
ForceRemove: buildOptions.ForceRemove,
Pull: buildOptions.Pull,
LoggerFactory: s.context.LoggerFactory,
}
return builder.Build(ctx, s.imageName())
}
func (s *Service) constructContainers(ctx context.Context, count int) ([]*container.Container, error) {
result, err := s.collectContainers(ctx)
if err != nil {
return nil, err
}
client := s.clientFactory.Create(s)
var namer Namer
if s.serviceConfig.ContainerName != "" {
if count > 1 {
logrus.Warnf(`The "%s" service is using the custom container name "%s". Docker requires each container to have a unique name. Remove the custom name to scale the service.`, s.name, s.serviceConfig.ContainerName)
}
namer = NewSingleNamer(s.serviceConfig.ContainerName)
} else {
namer, err = NewNamer(ctx, client, s.project.Name, s.name, false)
if err != nil {
return nil, err
}
}
for i := len(result); i < count; i++ {
c, err := s.createContainer(ctx, namer, "", nil, false)
if err != nil {
return nil, err
}
// FIXME(vdemeester) use property/method instead
id, _ := c.ID()
logrus.Debugf("Created container %s: %v", id, c.Name())
result = append(result, c)
}
return result, nil
}
// Up implements Service.Up. It builds the image if needed, creates a container
// and start it.
func (s *Service) Up(ctx context.Context, options options.Up) error {
containers, err := s.collectContainers(ctx)
if err != nil {
return err
}
var imageName = s.imageName()
if len(containers) == 0 || !options.NoRecreate {
if err = s.ensureImageExists(ctx, options.NoBuild, options.ForceBuild); err != nil {
return err
}
}
return s.up(ctx, imageName, true, options)
}
// Run implements Service.Run. It runs a one of command within the service container.
// It always create a new container.
func (s *Service) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) {
err := s.ensureImageExists(ctx, false, false)
if err != nil {
return -1, err
}
client := s.clientFactory.Create(s)
namer, err := NewNamer(ctx, client, s.project.Name, s.name, true)
if err != nil {
return -1, err
}
configOverride := &config.ServiceConfig{Command: commandParts, Tty: true, StdinOpen: true}
c, err := s.createContainer(ctx, namer, "", configOverride, true)
if err != nil {
return -1, err
}
if err := s.connectContainerToNetworks(ctx, c, true); err != nil {
return -1, err
}
if options.Detached {
logrus.Infof("%s", c.Name())
return 0, c.Start(ctx)
}
return c.Run(ctx, configOverride)
}
// Info implements Service.Info. It returns an project.InfoSet with the containers
// related to this service (can be multiple if using the scale command).
func (s *Service) Info(ctx context.Context) (project.InfoSet, error) {
result := project.InfoSet{}
containers, err := s.collectContainers(ctx)
if err != nil {
return nil, err
}
for _, c := range containers {
info, err := c.Info(ctx)
if err != nil {
return nil, err
}
result = append(result, info)
}
return result, nil
}
// Start implements Service.Start. It tries to start a container without creating it.
func (s *Service) Start(ctx context.Context) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
if err := s.connectContainerToNetworks(ctx, c, false); err != nil {
return err
}
return c.Start(ctx)
})
}
func (s *Service) up(ctx context.Context, imageName string, create bool, options options.Up) error {
containers, err := s.collectContainers(ctx)
if err != nil {
return err
}
logrus.Debugf("Found %d existing containers for service %s", len(containers), s.name)
if len(containers) == 0 && create {
namer, err := s.namer(ctx, 1)
if err != nil {
return err
}
c, err := s.createContainer(ctx, namer, "", nil, false)
if err != nil {
return err
}
containers = []*container.Container{c}
}
return s.eachContainer(ctx, containers, func(c *container.Container) error {
var err error
if create {
c, err = s.recreateIfNeeded(ctx, c, options.NoRecreate, options.ForceRecreate)
if err != nil {
return err
}
}
if err := s.connectContainerToNetworks(ctx, c, false); err != nil {
return err
}
err = c.Start(ctx)
if err == nil {
s.project.Notify(events.ContainerStarted, s.name, map[string]string{
"name": c.Name(),
})
}
return err
})
}
func (s *Service) connectContainerToNetworks(ctx context.Context, c *container.Container, oneOff bool) error {
connectedNetworks, err := c.Networks()
if err != nil {
return nil
}
if s.serviceConfig.Networks != nil {
for _, network := range s.serviceConfig.Networks.Networks {
existingNetwork, ok := connectedNetworks[network.Name]
if ok {
// FIXME(vdemeester) implement alias checking (to not disconnect/reconnect for nothing)
aliasPresent := false
for _, alias := range existingNetwork.Aliases {
// FIXME(vdemeester) use shortID instead of ID
ID, _ := c.ID()
if alias == ID {
aliasPresent = true
}
}
if aliasPresent {
continue
}
if err := s.NetworkDisconnect(ctx, c, network, oneOff); err != nil {
return err
}
}
if err := s.NetworkConnect(ctx, c, network, oneOff); err != nil {
return err
}
}
}
return nil
}
// NetworkDisconnect disconnects the container from the specified network
func (s *Service) NetworkDisconnect(ctx context.Context, c *container.Container, net *yaml.Network, oneOff bool) error {
containerID, _ := c.ID()
client := s.clientFactory.Create(s)
return client.NetworkDisconnect(ctx, net.RealName, containerID, true)
}
// NetworkConnect connects the container to the specified network
// FIXME(vdemeester) will be refactor with Container refactoring
func (s *Service) NetworkConnect(ctx context.Context, c *container.Container, net *yaml.Network, oneOff bool) error {
containerID, _ := c.ID()
client := s.clientFactory.Create(s)
internalLinks, err := s.getLinks()
if err != nil {
return err
}
links := []string{}
// TODO(vdemeester) handle link to self (?)
for k, v := range internalLinks {
links = append(links, strings.Join([]string{v, k}, ":"))
}
for _, v := range s.serviceConfig.ExternalLinks {
links = append(links, v)
}
aliases := []string{}
if !oneOff {
aliases = []string{s.Name()}
}
aliases = append(aliases, net.Aliases...)
return client.NetworkConnect(ctx, net.RealName, containerID, &network.EndpointSettings{
Aliases: aliases,
Links: links,
IPAddress: net.IPv4Address,
IPAMConfig: &network.EndpointIPAMConfig{
IPv4Address: net.IPv4Address,
IPv6Address: net.IPv6Address,
},
})
}
func (s *Service) recreateIfNeeded(ctx context.Context, c *container.Container, noRecreate, forceRecreate bool) (*container.Container, error) {
if noRecreate {
return c, nil
}
outOfSync, err := s.OutOfSync(ctx, c)
if err != nil {
return c, err
}
logrus.WithFields(logrus.Fields{
"outOfSync": outOfSync,
"ForceRecreate": forceRecreate,
"NoRecreate": noRecreate}).Debug("Going to decide if recreate is needed")
if forceRecreate || outOfSync {
logrus.Infof("Recreating %s", s.name)
newContainer, err := s.recreate(ctx, c)
if err != nil {
return c, err
}
return newContainer, nil
}
return c, err
}
func (s *Service) recreate(ctx context.Context, c *container.Container) (*container.Container, error) {
name := c.Name()
id, _ := c.ID()
newName := fmt.Sprintf("%s_%s", name, id[:12])
logrus.Debugf("Renaming %s => %s", name, newName)
if err := c.Rename(ctx, newName); err != nil {
logrus.Errorf("Failed to rename old container %s", c.Name())
return nil, err
}
namer := NewSingleNamer(name)
newContainer, err := s.createContainer(ctx, namer, id, nil, false)
if err != nil {
return nil, err
}
newID, _ := newContainer.ID()
logrus.Debugf("Created replacement container %s", newID)
if err := c.Remove(ctx, false); err != nil {
logrus.Errorf("Failed to remove old container %s", c.Name())
return nil, err
}
logrus.Debugf("Removed old container %s %s", c.Name(), id)
return newContainer, nil
}
// OutOfSync checks if the container is out of sync with the service definition.
// It looks if the the service hash container label is the same as the computed one.
func (s *Service) OutOfSync(ctx context.Context, c *container.Container) (bool, error) {
if c.ImageConfig() != s.serviceConfig.Image {
logrus.Debugf("Images for %s do not match %s!=%s", c.Name(), c.ImageConfig(), s.serviceConfig.Image)
return true, nil
}
expectedHash := config.GetServiceHash(s.name, s.Config())
if c.Hash() != expectedHash {
logrus.Debugf("Hashes for %s do not match %s!=%s", c.Name(), c.Hash(), expectedHash)
return true, nil
}
image, err := image.InspectImage(ctx, s.clientFactory.Create(s), c.ImageConfig())
if err != nil {
if client.IsErrImageNotFound(err) {
logrus.Debugf("Image %s do not exist, do not know if it's out of sync", c.Image())
return false, nil
}
return false, err
}
logrus.Debugf("Checking existing image name vs id: %s == %s", image.ID, c.Image())
return image.ID != c.Image(), err
}
func (s *Service) collectContainersAndDo(ctx context.Context, action func(*container.Container) error) error {
containers, err := s.collectContainers(ctx)
if err != nil {
return err
}
return s.eachContainer(ctx, containers, action)
}
func (s *Service) eachContainer(ctx context.Context, containers []*container.Container, action func(*container.Container) error) error {
tasks := utils.InParallel{}
for _, cont := range containers {
task := func(cont *container.Container) func() error {
return func() error {
return action(cont)
}
}(cont)
tasks.Add(task)
}
return tasks.Wait()
}
// Stop implements Service.Stop. It stops any containers related to the service.
func (s *Service) Stop(ctx context.Context, timeout int) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
return c.Stop(ctx, timeout)
})
}
// Restart implements Service.Restart. It restarts any containers related to the service.
func (s *Service) Restart(ctx context.Context, timeout int) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
return c.Restart(ctx, timeout)
})
}
// Kill implements Service.Kill. It kills any containers related to the service.
func (s *Service) Kill(ctx context.Context, signal string) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
return c.Kill(ctx, signal)
})
}
// Delete implements Service.Delete. It removes any containers related to the service.
func (s *Service) Delete(ctx context.Context, options options.Delete) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
running, _ := c.IsRunning(ctx)
if !running || options.RemoveRunning {
return c.Remove(ctx, options.RemoveVolume)
}
return nil
})
}
// Log implements Service.Log. It returns the docker logs for each container related to the service.
func (s *Service) Log(ctx context.Context, follow bool) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
containerNumber, err := c.Number()
if err != nil {
return err
}
name := fmt.Sprintf("%s_%d", s.name, containerNumber)
if s.Config().ContainerName != "" {
name = s.Config().ContainerName
}
l := s.context.LoggerFactory.CreateContainerLogger(name)
return c.Log(ctx, l, follow)
})
}
// Scale implements Service.Scale. It creates or removes containers to have the specified number
// of related container to the service to run.
func (s *Service) Scale(ctx context.Context, scale int, timeout int) error {
if s.specificiesHostPort() {
logrus.Warnf("The \"%s\" service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash.", s.Name())
}
containers, err := s.collectContainers(ctx)
if err != nil {
return err
}
if len(containers) > scale {
foundCount := 0
for _, c := range containers {
foundCount++
if foundCount > scale {
if err := c.Stop(ctx, timeout); err != nil {
return err
}
// FIXME(vdemeester) remove volume in scale by default ?
if err := c.Remove(ctx, false); err != nil {
return err
}
}
}
}
if err != nil {
return err
}
if len(containers) < scale {
err := s.ensureImageExists(ctx, false, false)
if err != nil {
return err
}
if _, err = s.constructContainers(ctx, scale); err != nil {
return err
}
}
return s.up(ctx, "", false, options.Up{})
}
// Pull implements Service.Pull. It pulls the image of the service and skip the service that
// would need to be built.
func (s *Service) Pull(ctx context.Context) error {
if s.Config().Image == "" {
return nil
}
return image.PullImage(ctx, s.clientFactory.Create(s), s.name, s.authLookup, s.Config().Image)
}
// Pause implements Service.Pause. It puts into pause the container(s) related
// to the service.
func (s *Service) Pause(ctx context.Context) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
return c.Pause(ctx)
})
}
// Unpause implements Service.Pause. It brings back from pause the container(s)
// related to the service.
func (s *Service) Unpause(ctx context.Context) error {
return s.collectContainersAndDo(ctx, func(c *container.Container) error {
return c.Unpause(ctx)
})
}
// RemoveImage implements Service.RemoveImage. It removes images used for the service
// depending on the specified type.
func (s *Service) RemoveImage(ctx context.Context, imageType options.ImageType) error {
switch imageType {
case "local":
if s.Config().Image != "" {
return nil
}
return image.RemoveImage(ctx, s.clientFactory.Create(s), s.imageName())
case "all":
return image.RemoveImage(ctx, s.clientFactory.Create(s), s.imageName())
default:
// Don't do a thing, should be validated up-front
return nil
}
}
var eventAttributes = []string{"image", "name"}
// Events implements Service.Events. It listen to all real-time events happening
// for the service, and put them into the specified chan.
func (s *Service) Events(ctx context.Context, evts chan events.ContainerEvent) error {
filter := filters.NewArgs()
filter.Add("label", fmt.Sprintf("%s=%s", labels.PROJECT, s.project.Name))
filter.Add("label", fmt.Sprintf("%s=%s", labels.SERVICE, s.name))
client := s.clientFactory.Create(s)
eventq, errq := client.Events(ctx, types.EventsOptions{
Filters: filter,
})
go func() {
for {
select {
case event := <-eventq:
service := event.Actor.Attributes[labels.SERVICE.Str()]
attributes := map[string]string{}
for _, attr := range eventAttributes {
attributes[attr] = event.Actor.Attributes[attr]
}
e := events.ContainerEvent{
Service: service,
Event: event.Action,
Type: event.Type,
ID: event.Actor.ID,
Time: time.Unix(event.Time, 0),
Attributes: attributes,
}
evts <- e
}
}
}()
return <-errq
}
// Containers implements Service.Containers. It returns the list of containers
// that are related to the service.
func (s *Service) Containers(ctx context.Context) ([]project.Container, error) {
result := []project.Container{}
containers, err := s.collectContainers(ctx)
if err != nil {
return nil, err
}
for _, c := range containers {
result = append(result, c)
}
return result, nil
}
func (s *Service) specificiesHostPort() bool {
_, bindings, err := nat.ParsePortSpecs(s.Config().Ports)
if err != nil {
fmt.Println(err)
}
for _, portBindings := range bindings {
for _, portBinding := range portBindings {
if portBinding.HostPort != "" {
return true
}
}
}
return false
}