File: up.go

package info (click to toggle)
docker-compose 2.32.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,300 kB
  • sloc: makefile: 113; sh: 2
file content (327 lines) | stat: -rw-r--r-- 12,729 bytes parent folder | download
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
/*
   Copyright 2020 Docker Compose CLI authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package compose

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/compose-spec/compose-go/v2/types"
	"github.com/docker/cli/cli/command"
	xprogress "github.com/moby/buildkit/util/progress/progressui"
	"github.com/spf13/cobra"

	"github.com/docker/compose/v2/cmd/formatter"
	"github.com/docker/compose/v2/pkg/api"
	ui "github.com/docker/compose/v2/pkg/progress"
	"github.com/docker/compose/v2/pkg/utils"
)

// composeOptions hold options common to `up` and `run` to run compose project
type composeOptions struct {
	*ProjectOptions
}

type upOptions struct {
	*composeOptions
	Detach                bool
	noStart               bool
	noDeps                bool
	cascadeStop           bool
	cascadeFail           bool
	exitCodeFrom          string
	noColor               bool
	noPrefix              bool
	attachDependencies    bool
	attach                []string
	noAttach              []string
	timestamp             bool
	wait                  bool
	waitTimeout           int
	watch                 bool
	navigationMenu        bool
	navigationMenuChanged bool
}

func (opts upOptions) apply(project *types.Project, services []string) (*types.Project, error) {
	if opts.noDeps {
		var err error
		project, err = project.WithSelectedServices(services, types.IgnoreDependencies)
		if err != nil {
			return nil, err
		}
	}

	if opts.exitCodeFrom != "" {
		_, err := project.GetService(opts.exitCodeFrom)
		if err != nil {
			return nil, err
		}
	}

	return project, nil
}

func (opts *upOptions) validateNavigationMenu(dockerCli command.Cli) {
	if !dockerCli.Out().IsTerminal() {
		opts.navigationMenu = false
		return
	}
	// If --menu flag was not set
	if !opts.navigationMenuChanged {
		if envVar, ok := os.LookupEnv(ComposeMenu); ok {
			opts.navigationMenu = utils.StringToBool(envVar)
			return
		}
		// ...and COMPOSE_MENU env var is not defined we want the default value to be true
		opts.navigationMenu = true
	}
}

func (opts upOptions) OnExit() api.Cascade {
	switch {
	case opts.cascadeStop:
		return api.CascadeStop
	case opts.cascadeFail:
		return api.CascadeFail
	default:
		return api.CascadeIgnore
	}
}

func upCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
	up := upOptions{}
	create := createOptions{}
	build := buildOptions{ProjectOptions: p}
	upCmd := &cobra.Command{
		Use:   "up [OPTIONS] [SERVICE...]",
		Short: "Create and start containers",
		PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
			create.pullChanged = cmd.Flags().Changed("pull")
			create.timeChanged = cmd.Flags().Changed("timeout")
			up.navigationMenuChanged = cmd.Flags().Changed("menu")
			if !cmd.Flags().Changed("remove-orphans") {
				create.removeOrphans = utils.StringToBool(os.Getenv(ComposeRemoveOrphans))
			}
			return validateFlags(&up, &create)
		}),
		RunE: p.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
			create.ignoreOrphans = utils.StringToBool(project.Environment[ComposeIgnoreOrphans])
			if create.ignoreOrphans && create.removeOrphans {
				return fmt.Errorf("cannot combine %s and --remove-orphans", ComposeIgnoreOrphans)
			}
			if len(up.attach) != 0 && up.attachDependencies {
				return errors.New("cannot combine --attach and --attach-dependencies")
			}

			up.validateNavigationMenu(dockerCli)

			if !p.All && len(project.Services) == 0 {
				return fmt.Errorf("no service selected")
			}

			return runUp(ctx, dockerCli, backend, create, up, build, project, services)
		}),
		ValidArgsFunction: completeServiceNames(dockerCli, p),
	}
	flags := upCmd.Flags()
	flags.BoolVarP(&up.Detach, "detach", "d", false, "Detached mode: Run containers in the background")
	flags.BoolVar(&create.Build, "build", false, "Build images before starting containers")
	flags.BoolVarP(&create.AssumeYes, "y", "y", false, `Assume "yes" as answer to all prompts and run non-interactively`)
	flags.BoolVar(&create.noBuild, "no-build", false, "Don't build an image, even if it's policy")
	flags.StringVar(&create.Pull, "pull", "policy", `Pull image before running ("always"|"missing"|"never")`)
	flags.BoolVar(&create.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file")
	flags.StringArrayVar(&create.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.")
	flags.BoolVar(&up.noColor, "no-color", false, "Produce monochrome output")
	flags.BoolVar(&up.noPrefix, "no-log-prefix", false, "Don't print prefix in logs")
	flags.BoolVar(&create.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed")
	flags.BoolVar(&create.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.")
	flags.BoolVar(&up.noStart, "no-start", false, "Don't start the services after creating them")
	flags.BoolVar(&up.cascadeStop, "abort-on-container-exit", false, "Stops all containers if any container was stopped. Incompatible with -d")
	flags.BoolVar(&up.cascadeFail, "abort-on-container-failure", false, "Stops all containers if any container exited with failure. Incompatible with -d")
	flags.StringVar(&up.exitCodeFrom, "exit-code-from", "", "Return the exit code of the selected service container. Implies --abort-on-container-exit")
	flags.IntVarP(&create.timeout, "timeout", "t", 0, "Use this timeout in seconds for container shutdown when attached or when containers are already running")
	flags.BoolVar(&up.timestamp, "timestamps", false, "Show timestamps")
	flags.BoolVar(&up.noDeps, "no-deps", false, "Don't start linked services")
	flags.BoolVar(&create.recreateDeps, "always-recreate-deps", false, "Recreate dependent containers. Incompatible with --no-recreate.")
	flags.BoolVarP(&create.noInherit, "renew-anon-volumes", "V", false, "Recreate anonymous volumes instead of retrieving data from the previous containers")
	flags.BoolVar(&create.quietPull, "quiet-pull", false, "Pull without printing progress information")
	flags.StringArrayVar(&up.attach, "attach", []string{}, "Restrict attaching to the specified services. Incompatible with --attach-dependencies.")
	flags.StringArrayVar(&up.noAttach, "no-attach", []string{}, "Do not attach (stream logs) to the specified services")
	flags.BoolVar(&up.attachDependencies, "attach-dependencies", false, "Automatically attach to log output of dependent services")
	flags.BoolVar(&up.wait, "wait", false, "Wait for services to be running|healthy. Implies detached mode.")
	flags.IntVar(&up.waitTimeout, "wait-timeout", 0, "Maximum duration in seconds to wait for the project to be running|healthy")
	flags.BoolVarP(&up.watch, "watch", "w", false, "Watch source code and rebuild/refresh containers when files are updated.")
	flags.BoolVar(&up.navigationMenu, "menu", false, "Enable interactive shortcuts when running attached. Incompatible with --detach. Can also be enable/disable by setting COMPOSE_MENU environment var.")

	return upCmd
}

//nolint:gocyclo
func validateFlags(up *upOptions, create *createOptions) error {
	if up.exitCodeFrom != "" && !up.cascadeFail {
		up.cascadeStop = true
	}
	if up.cascadeStop && up.cascadeFail {
		return fmt.Errorf("--abort-on-container-failure cannot be combined with --abort-on-container-exit")
	}
	if up.wait {
		if up.attachDependencies || up.cascadeStop || len(up.attach) > 0 {
			return fmt.Errorf("--wait cannot be combined with --abort-on-container-exit, --attach or --attach-dependencies")
		}
		up.Detach = true
	}
	if create.Build && create.noBuild {
		return fmt.Errorf("--build and --no-build are incompatible")
	}
	if up.Detach && (up.attachDependencies || up.cascadeStop || up.cascadeFail || len(up.attach) > 0 || up.watch) {
		return fmt.Errorf("--detach cannot be combined with --abort-on-container-exit, --abort-on-container-failure, --attach, --attach-dependencies or --watch")
	}
	if create.noInherit && create.noRecreate {
		return fmt.Errorf("--no-recreate and --renew-anon-volumes are incompatible")
	}
	if create.forceRecreate && create.noRecreate {
		return fmt.Errorf("--force-recreate and --no-recreate are incompatible")
	}
	if create.recreateDeps && create.noRecreate {
		return fmt.Errorf("--always-recreate-deps and --no-recreate are incompatible")
	}
	if create.noBuild && up.watch {
		return fmt.Errorf("--no-build and --watch are incompatible")
	}
	return nil
}

func runUp(
	ctx context.Context,
	dockerCli command.Cli,
	backend api.Service,
	createOptions createOptions,
	upOptions upOptions,
	buildOptions buildOptions,
	project *types.Project,
	services []string,
) error {
	err := createOptions.Apply(project)
	if err != nil {
		return err
	}

	project, err = upOptions.apply(project, services)
	if err != nil {
		return err
	}

	var build *api.BuildOptions
	if !createOptions.noBuild {
		if createOptions.quietPull {
			buildOptions.Progress = string(xprogress.QuietMode)
		}
		// BuildOptions here is nested inside CreateOptions, so
		// no service list is passed, it will implicitly pick all
		// services being created, which includes any explicitly
		// specified via "services" arg here as well as deps
		bo, err := buildOptions.toAPIBuildOptions(nil)
		if err != nil {
			return err
		}
		build = &bo
	}

	create := api.CreateOptions{
		Build:                build,
		Services:             services,
		RemoveOrphans:        createOptions.removeOrphans,
		IgnoreOrphans:        createOptions.ignoreOrphans,
		Recreate:             createOptions.recreateStrategy(),
		RecreateDependencies: createOptions.dependenciesRecreateStrategy(),
		Inherit:              !createOptions.noInherit,
		Timeout:              createOptions.GetTimeout(),
		QuietPull:            createOptions.quietPull,
		AssumeYes:            createOptions.AssumeYes,
	}

	if upOptions.noStart {
		return backend.Create(ctx, project, create)
	}

	var consumer api.LogConsumer
	var attach []string
	if !upOptions.Detach {
		consumer = formatter.NewLogConsumer(ctx, dockerCli.Out(), dockerCli.Err(), !upOptions.noColor, !upOptions.noPrefix, upOptions.timestamp)

		var attachSet utils.Set[string]
		if len(upOptions.attach) != 0 {
			// services are passed explicitly with --attach, verify they're valid and then use them as-is
			attachSet = utils.NewSet(upOptions.attach...)
			unexpectedSvcs := attachSet.Diff(utils.NewSet(project.ServiceNames()...))
			if len(unexpectedSvcs) != 0 {
				return fmt.Errorf("cannot attach to services not included in up: %s", strings.Join(unexpectedSvcs.Elements(), ", "))
			}
		} else {
			// mark services being launched (and potentially their deps) for attach
			// if they didn't opt-out via Compose YAML
			attachSet = utils.NewSet[string]()
			var dependencyOpt types.DependencyOption = types.IgnoreDependencies
			if upOptions.attachDependencies {
				dependencyOpt = types.IncludeDependencies
			}
			if err := project.ForEachService(services, func(serviceName string, s *types.ServiceConfig) error {
				if s.Attach == nil || *s.Attach {
					attachSet.Add(serviceName)
				}
				return nil
			}, dependencyOpt); err != nil {
				return err
			}
		}
		// filter out any services that have been explicitly marked for ignore with `--no-attach`
		attachSet.RemoveAll(upOptions.noAttach...)
		attach = attachSet.Elements()
	}

	timeout := time.Duration(upOptions.waitTimeout) * time.Second
	return backend.Up(ctx, project, api.UpOptions{
		Create: create,
		Start: api.StartOptions{
			Project:        project,
			Attach:         consumer,
			AttachTo:       attach,
			ExitCodeFrom:   upOptions.exitCodeFrom,
			OnExit:         upOptions.OnExit(),
			Wait:           upOptions.wait,
			WaitTimeout:    timeout,
			Watch:          upOptions.watch,
			Services:       services,
			NavigationMenu: upOptions.navigationMenu && ui.Mode != "plain",
		},
	})
}

func setServiceScale(project *types.Project, name string, replicas int) error {
	service, err := project.GetService(name)
	if err != nil {
		return err
	}
	service.SetScale(replicas)
	project.Services[name] = service
	return nil
}