347 lines
13 KiB
Go
Raw Permalink Normal View History

2020-05-14 21:13:07 +02:00
/*
Copyright 2020 Docker Compose CLI authors
2020-05-14 21:13:07 +02:00
2020-06-18 16:13:24 +02:00
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
2020-05-14 21:13:07 +02:00
2020-06-18 16:13:24 +02:00
http://www.apache.org/licenses/LICENSE-2.0
2020-05-14 21:13:07 +02:00
2020-06-18 16:13:24 +02:00
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.
2020-05-14 21:13:07 +02:00
*/
2020-05-14 21:04:38 +02:00
package compose
import (
"context"
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
"errors"
"fmt"
"os"
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
"strings"
"time"
2020-05-14 21:04:38 +02:00
"github.com/compose-spec/compose-go/v2/types"
"github.com/docker/cli/cli/command"
xprogress "github.com/moby/buildkit/util/progress/progressui"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"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"
2020-05-14 21:04:38 +02:00
)
// 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: pass BuildOptions around explicitly & fix multi-platform issues The big change here is to pass around an explicit `*BuildOptions` object as part of Compose operations like `up` & `run` that may or may not do builds. If the options object is `nil`, no builds whatsoever will be attempted. Motivation is to allow for partial rebuilds in the context of an `up` for watch. This was broken and tricky to accomplish because various parts of the Compose APIs mutate the `*Project` for convenience in ways that make it unusable afterwards. (For example, it might set `service.Build = nil` because it's not going to build that service right _then_. But we might still want to build it later!) NOTE: This commit does not actually touch the watch logic. This is all in preparation to make it possible. As part of this, a bunch of code moved around and I eliminated a bunch of partially redundant logic, mostly around multi-platform. Several edge cases have been addressed as part of this: * `DOCKER_DEFAULT_PLATFORM` was _overriding_ explicitly set platforms in some cases, this is no longer true, and it behaves like the Docker CLI now * It was possible for Compose to build an image for one platform and then try to run it for a different platform (and fail) * Errors are no longer returned if a local image exists but for the wrong platform - the correct platform will be fetched/built (if possible). Because there's a LOT of subtlety and tricky logic here, I've also tried to add an excessive amount of explanatory comments. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-30 08:47:09 -04:00
build := buildOptions{ProjectOptions: p}
2020-05-14 21:04:38 +02:00
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 {
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
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),
2020-05-14 21:04:38 +02:00
}
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.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")
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
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.")
flags.BoolVarP(&create.AssumeYes, "yes", "y", false, `Assume "yes" as answer to all prompts and run non-interactively`)
flags.SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName {
// assumeYes was introduced by mistake as `--y`
if name == "y" {
logrus.Warn("--y is deprecated, please use --yes instead")
name = "yes"
}
return pflag.NormalizedName(name)
})
2020-05-14 21:04:38 +02:00
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) {
if up.wait {
return fmt.Errorf("--wait cannot be combined with --abort-on-container-exit, --abort-on-container-failure, --attach, --attach-dependencies or --watch")
} else {
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
}
build: pass BuildOptions around explicitly & fix multi-platform issues The big change here is to pass around an explicit `*BuildOptions` object as part of Compose operations like `up` & `run` that may or may not do builds. If the options object is `nil`, no builds whatsoever will be attempted. Motivation is to allow for partial rebuilds in the context of an `up` for watch. This was broken and tricky to accomplish because various parts of the Compose APIs mutate the `*Project` for convenience in ways that make it unusable afterwards. (For example, it might set `service.Build = nil` because it's not going to build that service right _then_. But we might still want to build it later!) NOTE: This commit does not actually touch the watch logic. This is all in preparation to make it possible. As part of this, a bunch of code moved around and I eliminated a bunch of partially redundant logic, mostly around multi-platform. Several edge cases have been addressed as part of this: * `DOCKER_DEFAULT_PLATFORM` was _overriding_ explicitly set platforms in some cases, this is no longer true, and it behaves like the Docker CLI now * It was possible for Compose to build an image for one platform and then try to run it for a different platform (and fail) * Errors are no longer returned if a local image exists but for the wrong platform - the correct platform will be fetched/built (if possible). Because there's a LOT of subtlety and tricky logic here, I've also tried to add an excessive amount of explanatory comments. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-30 08:47:09 -04:00
func runUp(
ctx context.Context,
dockerCli command.Cli,
build: pass BuildOptions around explicitly & fix multi-platform issues The big change here is to pass around an explicit `*BuildOptions` object as part of Compose operations like `up` & `run` that may or may not do builds. If the options object is `nil`, no builds whatsoever will be attempted. Motivation is to allow for partial rebuilds in the context of an `up` for watch. This was broken and tricky to accomplish because various parts of the Compose APIs mutate the `*Project` for convenience in ways that make it unusable afterwards. (For example, it might set `service.Build = nil` because it's not going to build that service right _then_. But we might still want to build it later!) NOTE: This commit does not actually touch the watch logic. This is all in preparation to make it possible. As part of this, a bunch of code moved around and I eliminated a bunch of partially redundant logic, mostly around multi-platform. Several edge cases have been addressed as part of this: * `DOCKER_DEFAULT_PLATFORM` was _overriding_ explicitly set platforms in some cases, this is no longer true, and it behaves like the Docker CLI now * It was possible for Compose to build an image for one platform and then try to run it for a different platform (and fail) * Errors are no longer returned if a local image exists but for the wrong platform - the correct platform will be fetched/built (if possible). Because there's a LOT of subtlety and tricky logic here, I've also tried to add an excessive amount of explanatory comments. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-30 08:47:09 -04:00
backend api.Service,
createOptions createOptions,
upOptions upOptions,
buildOptions buildOptions,
project *types.Project,
services []string,
) error {
if err := checksForRemoteStack(ctx, dockerCli, project, buildOptions, createOptions.AssumeYes, []string{}); err != nil {
return err
}
err := createOptions.Apply(project)
if err != nil {
return err
}
project, err = upOptions.apply(project, services)
if err != nil {
return err
}
build: pass BuildOptions around explicitly & fix multi-platform issues The big change here is to pass around an explicit `*BuildOptions` object as part of Compose operations like `up` & `run` that may or may not do builds. If the options object is `nil`, no builds whatsoever will be attempted. Motivation is to allow for partial rebuilds in the context of an `up` for watch. This was broken and tricky to accomplish because various parts of the Compose APIs mutate the `*Project` for convenience in ways that make it unusable afterwards. (For example, it might set `service.Build = nil` because it's not going to build that service right _then_. But we might still want to build it later!) NOTE: This commit does not actually touch the watch logic. This is all in preparation to make it possible. As part of this, a bunch of code moved around and I eliminated a bunch of partially redundant logic, mostly around multi-platform. Several edge cases have been addressed as part of this: * `DOCKER_DEFAULT_PLATFORM` was _overriding_ explicitly set platforms in some cases, this is no longer true, and it behaves like the Docker CLI now * It was possible for Compose to build an image for one platform and then try to run it for a different platform (and fail) * Errors are no longer returned if a local image exists but for the wrong platform - the correct platform will be fetched/built (if possible). Because there's a LOT of subtlety and tricky logic here, I've also tried to add an excessive amount of explanatory comments. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-30 08:47:09 -04:00
var build *api.BuildOptions
if !createOptions.noBuild {
if createOptions.quietPull {
buildOptions.Progress = string(xprogress.QuietMode)
build: pass BuildOptions around explicitly & fix multi-platform issues The big change here is to pass around an explicit `*BuildOptions` object as part of Compose operations like `up` & `run` that may or may not do builds. If the options object is `nil`, no builds whatsoever will be attempted. Motivation is to allow for partial rebuilds in the context of an `up` for watch. This was broken and tricky to accomplish because various parts of the Compose APIs mutate the `*Project` for convenience in ways that make it unusable afterwards. (For example, it might set `service.Build = nil` because it's not going to build that service right _then_. But we might still want to build it later!) NOTE: This commit does not actually touch the watch logic. This is all in preparation to make it possible. As part of this, a bunch of code moved around and I eliminated a bunch of partially redundant logic, mostly around multi-platform. Several edge cases have been addressed as part of this: * `DOCKER_DEFAULT_PLATFORM` was _overriding_ explicitly set platforms in some cases, this is no longer true, and it behaves like the Docker CLI now * It was possible for Compose to build an image for one platform and then try to run it for a different platform (and fail) * Errors are no longer returned if a local image exists but for the wrong platform - the correct platform will be fetched/built (if possible). Because there's a LOT of subtlety and tricky logic here, I've also tried to add an excessive amount of explanatory comments. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-30 08:47:09 -04:00
}
// 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
}
bo.Services = services
bo.Deps = !upOptions.noDeps
build: pass BuildOptions around explicitly & fix multi-platform issues The big change here is to pass around an explicit `*BuildOptions` object as part of Compose operations like `up` & `run` that may or may not do builds. If the options object is `nil`, no builds whatsoever will be attempted. Motivation is to allow for partial rebuilds in the context of an `up` for watch. This was broken and tricky to accomplish because various parts of the Compose APIs mutate the `*Project` for convenience in ways that make it unusable afterwards. (For example, it might set `service.Build = nil` because it's not going to build that service right _then_. But we might still want to build it later!) NOTE: This commit does not actually touch the watch logic. This is all in preparation to make it possible. As part of this, a bunch of code moved around and I eliminated a bunch of partially redundant logic, mostly around multi-platform. Several edge cases have been addressed as part of this: * `DOCKER_DEFAULT_PLATFORM` was _overriding_ explicitly set platforms in some cases, this is no longer true, and it behaves like the Docker CLI now * It was possible for Compose to build an image for one platform and then try to run it for a different platform (and fail) * Errors are no longer returned if a local image exists but for the wrong platform - the correct platform will be fetched/built (if possible). Because there's a LOT of subtlety and tricky logic here, I've also tried to add an excessive amount of explanatory comments. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-30 08:47:09 -04:00
build = &bo
}
create := api.CreateOptions{
build: pass BuildOptions around explicitly & fix multi-platform issues The big change here is to pass around an explicit `*BuildOptions` object as part of Compose operations like `up` & `run` that may or may not do builds. If the options object is `nil`, no builds whatsoever will be attempted. Motivation is to allow for partial rebuilds in the context of an `up` for watch. This was broken and tricky to accomplish because various parts of the Compose APIs mutate the `*Project` for convenience in ways that make it unusable afterwards. (For example, it might set `service.Build = nil` because it's not going to build that service right _then_. But we might still want to build it later!) NOTE: This commit does not actually touch the watch logic. This is all in preparation to make it possible. As part of this, a bunch of code moved around and I eliminated a bunch of partially redundant logic, mostly around multi-platform. Several edge cases have been addressed as part of this: * `DOCKER_DEFAULT_PLATFORM` was _overriding_ explicitly set platforms in some cases, this is no longer true, and it behaves like the Docker CLI now * It was possible for Compose to build an image for one platform and then try to run it for a different platform (and fail) * Errors are no longer returned if a local image exists but for the wrong platform - the correct platform will be fetched/built (if possible). Because there's a LOT of subtlety and tricky logic here, I've also tried to add an excessive amount of explanatory comments. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-30 08:47:09 -04:00
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)
}
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
var consumer api.LogConsumer
var attach []string
if !upOptions.Detach {
consumer = formatter.NewLogConsumer(ctx, dockerCli.Out(), dockerCli.Err(), !upOptions.noColor, !upOptions.noPrefix, upOptions.timestamp)
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
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 {
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
if s.Attach == nil || *s.Attach {
attachSet.Add(serviceName)
up: handle various attach use cases better By default, `compose up` attaches to all services (i.e. shows log output from every associated container). If a service is specified, e.g. `compose up foo`, then only `foo`'s logs are tailed. The `--attach-dependencies` flag can also be used, so that if `foo` depended upon `bar`, then `bar`'s logs would also be followed. It's also possible to use `--no-attach` to filter out one or more services explicitly, e.g. `compose up --no-attach=noisy` would launch all services, including `noisy`, and would show log output from every service _except_ `noisy`. Lastly, it's possible to use `up --attach` to explicitly restrict to a subset of services (or their dependencies). How these flags interact with each other is also worth thinking through. There were a few different connected issues here, but the primary issue was that running `compose up foo` was always attaching dependencies regardless of `--attach-dependencies`. The filtering logic here has been updated so that it behaves predictably both when launching all services (`compose up`) or a subset (`compose up foo`) as well as various flag combinations on top of those. Notably, this required making some changes to how it watches containers. The logic here between attaching for logs and monitoring for lifecycle changes is tightly coupled, so some changes were needed to ensure that the full set of services being `up`'d are _watched_ and the subset that should have logs shown are _attached_. (This does mean faking the attach with an event but not actually doing it.) While handling that, I adjusted the context lifetimes here, which improves error handling that gets shown to the user and should help avoid potential leaks by getting rid of a `context.Background()`. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2023-08-17 17:43:13 -04:00
}
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
}