163 lines
4.7 KiB
Go
Raw Permalink Normal View History

/*
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"
"os/signal"
"slices"
"github.com/compose-spec/compose-go/v2/types"
"github.com/docker/cli/cli"
cmd "github.com/docker/cli/cli/command/container"
"github.com/docker/compose/v2/pkg/api"
"github.com/docker/docker/pkg/stringid"
)
func (s *composeService) RunOneOffContainer(ctx context.Context, project *types.Project, opts api.RunOptions) (int, error) {
containerID, err := s.prepareRun(ctx, project, opts)
if err != nil {
return 0, err
}
// remove cancellable context signal handler so we can forward signals to container without compose to exit
signal.Reset()
sigc := make(chan os.Signal, 128)
signal.Notify(sigc)
go cmd.ForwardAllSignals(ctx, s.apiClient(), containerID, sigc)
defer signal.Stop(sigc)
err = cmd.RunStart(ctx, s.dockerCli, &cmd.StartOptions{
OpenStdin: !opts.Detach && opts.Interactive,
Attach: !opts.Detach,
Containers: []string{containerID},
})
var stErr cli.StatusError
if errors.As(err, &stErr) {
return stErr.StatusCode, nil
}
return 0, err
}
func (s *composeService) prepareRun(ctx context.Context, project *types.Project, opts api.RunOptions) (string, error) {
service, err := project.GetService(opts.Service)
if err != nil {
return "", err
}
applyRunOptions(project, &service, opts)
if err := s.stdin().CheckTty(opts.Interactive, service.Tty); err != nil {
return "", err
}
slug := stringid.GenerateRandomID()
if service.ContainerName == "" {
service.ContainerName = fmt.Sprintf("%[1]s%[4]s%[2]s%[4]srun%[4]s%[3]s", project.Name, service.Name, stringid.TruncateID(slug), api.Separator)
}
one := 1
service.Scale = &one
service.Restart = ""
if service.Deploy != nil {
service.Deploy.RestartPolicy = nil
}
service.CustomLabels = service.CustomLabels.
Add(api.SlugLabel, slug).
Add(api.OneoffLabel, "True")
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
if err := s.ensureImagesExists(ctx, project, opts.Build, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img
return "", err
}
observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
if err != nil {
return "", err
}
if !opts.NoDeps {
if err := s.waitDependencies(ctx, project, service.Name, service.DependsOn, observedState, 0); err != nil {
return "", err
}
}
createOpts := createOptions{
AutoRemove: opts.AutoRemove,
AttachStdin: opts.Interactive,
UseNetworkAliases: opts.UseNetworkAliases,
Labels: mergeLabels(service.Labels, service.CustomLabels),
}
err = newConvergence(project.ServiceNames(), observedState, nil, nil, s).resolveServiceReferences(&service)
if err != nil {
return "", err
}
created, err := s.createContainer(ctx, project, service, service.ContainerName, -1, createOpts)
if err != nil {
return "", err
}
return created.ID, nil
}
func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
service.Tty = opts.Tty
service.StdinOpen = opts.Interactive
service.ContainerName = opts.Name
if len(opts.Command) > 0 {
service.Command = opts.Command
}
fix linting issues with golangci-lint 1.60.2 pkg/watch/watcher_darwin.go:96:16: Error return value of `d.stream.Start` is not checked (errcheck) d.stream.Start() ^ pkg/prompt/prompt.go:97:12: Error return value of `fmt.Fprint` is not checked (errcheck) fmt.Fprint(u.stdout, message) ^ pkg/prompt/prompt.go:99:12: Error return value of `fmt.Scanln` is not checked (errcheck) fmt.Scanln(&answer) ^ cmd/formatter/logs.go:118:15: Error return value of `fmt.Fprintf` is not checked (errcheck) fmt.Fprintf(w, "%s%s%s\n", p.prefix, timestamp, line) ^ cmd/formatter/logs.go:120:15: Error return value of `fmt.Fprintf` is not checked (errcheck) fmt.Fprintf(w, "%s%s\n", p.prefix, line) ^ pkg/progress/json.go:67:15: Error return value of `fmt.Fprintln` is not checked (errcheck) fmt.Fprintln(p.out, string(marshal)) ^ pkg/progress/json.go:87:15: Error return value of `fmt.Fprintln` is not checked (errcheck) fmt.Fprintln(p.out, string(marshal)) ^ pkg/progress/plain.go:47:14: Error return value of `fmt.Fprintln` is not checked (errcheck) fmt.Fprintln(p.out, prefix, e.ID, e.Text, e.StatusText) ^ pkg/progress/tty.go:162:12: Error return value of `fmt.Fprint` is not checked (errcheck) fmt.Fprint(w.out, b.Column(0).ANSI) ^ pkg/progress/tty.go:165:12: Error return value of `fmt.Fprint` is not checked (errcheck) fmt.Fprint(w.out, aec.Hide) ^ pkg/compose/attach.go:53:13: Error return value of `fmt.Fprintf` is not checked (errcheck) fmt.Fprintf(s.stdout(), "Attaching to %s\n", strings.Join(names, ", ")) ^ pkg/compose/compose.go:194:6: emptyStringTest: replace `len(dependencies) > 0` with `dependencies != ""` (gocritic) if len(dependencies) > 0 { ^ pkg/compose/convergence.go:461:2: builtinShadow: shadowing of predeclared identifier: max (gocritic) max := 0 ^ pkg/compose/run.go:127:5: emptyStringTest: replace `len(opts.User) > 0` with `opts.User != ""` (gocritic) if len(opts.User) > 0 { ^ pkg/compose/run.go:139:5: emptyStringTest: replace `len(opts.WorkingDir) > 0` with `opts.WorkingDir != ""` (gocritic) if len(opts.WorkingDir) > 0 { ^ pkg/compose/viz.go:91:8: emptyStringTest: replace `len(portConfig.HostIP) > 0` with `portConfig.HostIP != ""` (gocritic) if len(portConfig.HostIP) > 0 { ^ cmd/compatibility/convert.go:66:6: emptyStringTest: replace `len(arg) > 0` with `arg != ""` (gocritic) if len(arg) > 0 && arg[0] != '-' { ^ pkg/e2e/watch_test.go:208:25: printf: non-constant format string in call to gotest.tools/v3/poll.Continue (govet) return poll.Continue(res.Combined()) ^ pkg/e2e/watch_test.go:290:25: printf: non-constant format string in call to gotest.tools/v3/poll.Continue (govet) return poll.Continue(r.Combined()) ^ Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-11 12:52:55 +02:00
if opts.User != "" {
service.User = opts.User
}
if len(opts.CapAdd) > 0 {
service.CapAdd = append(service.CapAdd, opts.CapAdd...)
service.CapDrop = slices.DeleteFunc(service.CapDrop, func(e string) bool { return slices.Contains(opts.CapAdd, e) })
}
if len(opts.CapDrop) > 0 {
service.CapDrop = append(service.CapDrop, opts.CapDrop...)
service.CapAdd = slices.DeleteFunc(service.CapAdd, func(e string) bool { return slices.Contains(opts.CapDrop, e) })
}
fix linting issues with golangci-lint 1.60.2 pkg/watch/watcher_darwin.go:96:16: Error return value of `d.stream.Start` is not checked (errcheck) d.stream.Start() ^ pkg/prompt/prompt.go:97:12: Error return value of `fmt.Fprint` is not checked (errcheck) fmt.Fprint(u.stdout, message) ^ pkg/prompt/prompt.go:99:12: Error return value of `fmt.Scanln` is not checked (errcheck) fmt.Scanln(&answer) ^ cmd/formatter/logs.go:118:15: Error return value of `fmt.Fprintf` is not checked (errcheck) fmt.Fprintf(w, "%s%s%s\n", p.prefix, timestamp, line) ^ cmd/formatter/logs.go:120:15: Error return value of `fmt.Fprintf` is not checked (errcheck) fmt.Fprintf(w, "%s%s\n", p.prefix, line) ^ pkg/progress/json.go:67:15: Error return value of `fmt.Fprintln` is not checked (errcheck) fmt.Fprintln(p.out, string(marshal)) ^ pkg/progress/json.go:87:15: Error return value of `fmt.Fprintln` is not checked (errcheck) fmt.Fprintln(p.out, string(marshal)) ^ pkg/progress/plain.go:47:14: Error return value of `fmt.Fprintln` is not checked (errcheck) fmt.Fprintln(p.out, prefix, e.ID, e.Text, e.StatusText) ^ pkg/progress/tty.go:162:12: Error return value of `fmt.Fprint` is not checked (errcheck) fmt.Fprint(w.out, b.Column(0).ANSI) ^ pkg/progress/tty.go:165:12: Error return value of `fmt.Fprint` is not checked (errcheck) fmt.Fprint(w.out, aec.Hide) ^ pkg/compose/attach.go:53:13: Error return value of `fmt.Fprintf` is not checked (errcheck) fmt.Fprintf(s.stdout(), "Attaching to %s\n", strings.Join(names, ", ")) ^ pkg/compose/compose.go:194:6: emptyStringTest: replace `len(dependencies) > 0` with `dependencies != ""` (gocritic) if len(dependencies) > 0 { ^ pkg/compose/convergence.go:461:2: builtinShadow: shadowing of predeclared identifier: max (gocritic) max := 0 ^ pkg/compose/run.go:127:5: emptyStringTest: replace `len(opts.User) > 0` with `opts.User != ""` (gocritic) if len(opts.User) > 0 { ^ pkg/compose/run.go:139:5: emptyStringTest: replace `len(opts.WorkingDir) > 0` with `opts.WorkingDir != ""` (gocritic) if len(opts.WorkingDir) > 0 { ^ pkg/compose/viz.go:91:8: emptyStringTest: replace `len(portConfig.HostIP) > 0` with `portConfig.HostIP != ""` (gocritic) if len(portConfig.HostIP) > 0 { ^ cmd/compatibility/convert.go:66:6: emptyStringTest: replace `len(arg) > 0` with `arg != ""` (gocritic) if len(arg) > 0 && arg[0] != '-' { ^ pkg/e2e/watch_test.go:208:25: printf: non-constant format string in call to gotest.tools/v3/poll.Continue (govet) return poll.Continue(res.Combined()) ^ pkg/e2e/watch_test.go:290:25: printf: non-constant format string in call to gotest.tools/v3/poll.Continue (govet) return poll.Continue(r.Combined()) ^ Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-11 12:52:55 +02:00
if opts.WorkingDir != "" {
service.WorkingDir = opts.WorkingDir
}
if opts.Entrypoint != nil {
service.Entrypoint = opts.Entrypoint
if len(opts.Command) == 0 {
service.Command = []string{}
}
}
if len(opts.Environment) > 0 {
cmdEnv := types.NewMappingWithEquals(opts.Environment)
serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) {
v, ok := envResolver(project.Environment)(s)
return v, ok
}).RemoveEmpty()
if service.Environment == nil {
service.Environment = types.MappingWithEquals{}
}
service.Environment.OverrideBy(serviceOverrideEnv)
}
for k, v := range opts.Labels {
service.Labels = service.Labels.Add(k, v)
}
}