forked from docker/libcompose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
432 lines (350 loc) · 10.1 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
package docker
import (
"fmt"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/nat"
"github.com/docker/libcompose/project"
"github.com/docker/libcompose/utils"
"github.com/fsouza/go-dockerclient"
)
// Service is a project.Service implementations.
type Service struct {
name string
serviceConfig *project.ServiceConfig
context *Context
}
// NewService creates a service
func NewService(name string, serviceConfig *project.ServiceConfig, context *Context) *Service {
return &Service{
name: name,
serviceConfig: serviceConfig,
context: context,
}
}
// Name returns the service name.
func (s *Service) Name() string {
return s.name
}
// Config returns the configuration of the service (project.ServiceConfig).
func (s *Service) Config() *project.ServiceConfig {
return s.serviceConfig
}
// DependentServices returns the dependent services (as an array of ServiceRelationship) of the service.
func (s *Service) DependentServices() []project.ServiceRelationship {
return project.DefaultDependentServices(s.context.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() error {
containers, err := s.collectContainers()
if err != nil {
return err
}
imageName, err := s.ensureImageExists()
if err != nil {
return err
}
if len(containers) != 0 {
return s.eachContainer(func(c *Container) error {
return s.recreateIfNeeded(imageName, c)
})
}
_, err = s.createOne(imageName)
return err
}
func (s *Service) collectContainers() ([]*Container, error) {
client := s.context.ClientFactory.Create(s)
containers, err := GetContainersByFilter(client, SERVICE.Eq(s.name), PROJECT.Eq(s.context.Project.Name))
if err != nil {
return nil, err
}
result := []*Container{}
for _, container := range containers {
name := container.Labels[NAME.Str()]
result = append(result, NewContainer(client, name, s))
}
return result, nil
}
func (s *Service) createOne(imageName string) (*Container, error) {
containers, err := s.constructContainers(imageName, 1)
if err != nil {
return nil, err
}
return containers[0], err
}
func (s *Service) ensureImageExists() (string, error) {
err := s.imageExists()
if err == nil {
return s.imageName(), nil
}
if err != nil && err != docker.ErrNoSuchImage {
return "", err
}
if s.Config().Build != "" {
if s.context.NoBuild {
return "", fmt.Errorf("Service %q needs to be built, but no-build was specified", s.name)
}
return s.imageName(), s.build()
}
return s.imageName(), s.Pull()
}
func (s *Service) imageExists() error {
client := s.context.ClientFactory.Create(s)
_, err := client.InspectImage(s.imageName())
return err
}
func (s *Service) imageName() string {
if s.Config().Image != "" {
return s.Config().Image
}
return fmt.Sprintf("%s_%s", s.context.ProjectName, s.Name())
}
// Build implements Service.Build. If an imageName is specified or if the context has
// no build to work with it will do nothing. Otherwise it will try to build
// the image and returns an error if any.
func (s *Service) Build() error {
if s.Config().Image != "" {
return nil
}
return s.build()
}
func (s *Service) build() error {
if s.context.Builder == nil {
return fmt.Errorf("Cannot build an image without a builder configured")
}
return s.context.Builder.Build(s.imageName(), s.context.Project, s)
}
func (s *Service) constructContainers(imageName string, count int) ([]*Container, error) {
result, err := s.collectContainers()
if err != nil {
return nil, err
}
client := s.context.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 = NewNamer(client, s.context.Project.Name, s.name)
}
defer namer.Close()
for i := len(result); i < count; i++ {
containerName := namer.Next()
c := NewContainer(client, containerName, s)
dockerContainer, err := c.Create(imageName)
if err != nil {
return nil, err
}
logrus.Debugf("Created container %s: %v", dockerContainer.ID, dockerContainer.Names)
result = append(result, NewContainer(client, containerName, s))
}
return result, nil
}
// Up implements Service.Up. It builds the image if needed, creates a container
// and start it.
func (s *Service) Up() error {
containers, err := s.collectContainers()
if err != nil {
return err
}
var imageName = s.imageName()
if len(containers) == 0 || !s.context.NoRecreate {
imageName, err = s.ensureImageExists()
if err != nil {
return err
}
}
return s.up(imageName, true)
}
// 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(qFlag bool) (project.InfoSet, error) {
result := project.InfoSet{}
containers, err := s.collectContainers()
if err != nil {
return nil, err
}
for _, c := range containers {
info, err := c.Info(qFlag)
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() error {
return s.up("", false)
}
func (s *Service) up(imageName string, create bool) error {
containers, err := s.collectContainers()
if err != nil {
return err
}
logrus.Debugf("Found %d existing containers for service %s", len(containers), s.name)
if len(containers) == 0 && create {
c, err := s.createOne(imageName)
if err != nil {
return err
}
containers = []*Container{c}
}
return s.eachContainer(func(c *Container) error {
if create {
if err := s.recreateIfNeeded(imageName, c); err != nil {
return err
}
}
return c.Up(imageName)
})
}
func (s *Service) recreateIfNeeded(imageName string, c *Container) error {
if s.context.NoRecreate {
return nil
}
outOfSync, err := c.OutOfSync(imageName)
if err != nil {
return err
}
logrus.WithFields(logrus.Fields{
"outOfSync": outOfSync,
"ForceRecreate": s.context.ForceRecreate,
"NoRecreate": s.context.NoRecreate}).Debug("Going to decide if recreate is needed")
if s.context.ForceRecreate || outOfSync {
logrus.Infof("Recreating %s", s.name)
if _, err := c.Recreate(imageName); err != nil {
return err
}
}
return nil
}
func (s *Service) eachContainer(action func(*Container) error) error {
containers, err := s.collectContainers()
if err != nil {
return err
}
tasks := utils.InParallel{}
for _, container := range containers {
task := func(container *Container) func() error {
return func() error {
return action(container)
}
}(container)
tasks.Add(task)
}
return tasks.Wait()
}
// Down implements Service.Down. It stops any containers related to the service.
func (s *Service) Down() error {
return s.eachContainer(func(c *Container) error {
return c.Down()
})
}
// Restart implements Service.Restart. It restarts any containers related to the service.
func (s *Service) Restart() error {
return s.eachContainer(func(c *Container) error {
return c.Restart()
})
}
// Kill implements Service.Kill. It kills any containers related to the service.
func (s *Service) Kill() error {
return s.eachContainer(func(c *Container) error {
return c.Kill()
})
}
// Delete implements Service.Delete. It removes any containers related to the service.
func (s *Service) Delete() error {
return s.eachContainer(func(c *Container) error {
return c.Delete()
})
}
// Log implements Service.Log. It returns the docker logs for each container related to the service.
func (s *Service) Log() error {
return s.eachContainer(func(c *Container) error {
return c.Log()
})
}
// 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(scale 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())
}
foundCount := 0
err := s.eachContainer(func(c *Container) error {
foundCount++
if foundCount > scale {
err := c.Down()
if err != nil {
return err
}
return c.Delete()
}
return nil
})
if err != nil {
return err
}
if foundCount != scale {
imageName, err := s.ensureImageExists()
if err != nil {
return err
}
if _, err = s.constructContainers(imageName, scale); err != nil {
return err
}
}
return s.up("", false)
}
// 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() error {
if s.Config().Image == "" {
return nil
}
return pullImage(s.context.ClientFactory.Create(s), s, s.Config().Image)
}
// Pause implements Service.Pause. It puts into pause the container(s) related
// to the service.
func (s *Service) Pause() error {
return s.eachContainer(func(c *Container) error {
return c.Pause()
})
}
// Unpause implements Service.Pause. It brings back from pause the container(s)
// related to the service.
func (s *Service) Unpause() error {
return s.eachContainer(func(c *Container) error {
return c.Unpause()
})
}
// Containers implements Service.Containers. It returns the list of containers
// that are related to the service.
func (s *Service) Containers() ([]project.Container, error) {
result := []project.Container{}
containers, err := s.collectContainers()
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
}