repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/hook.go
pkg/compose/hook.go
/* 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" "fmt" "io" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) func (s composeService) runHook(ctx context.Context, ctr container.Summary, service types.ServiceConfig, hook types.ServiceHook, listener api.ContainerEventListener) error { wOut := utils.GetWriter(func(line string) { listener(api.ContainerEvent{ Type: api.HookEventLog, Source: getContainerNameWithoutProject(ctr) + " ->", ID: ctr.ID, Service: service.Name, Line: line, }) }) defer wOut.Close() //nolint:errcheck detached := listener == nil exec, err := s.apiClient().ContainerExecCreate(ctx, ctr.ID, container.ExecOptions{ User: hook.User, Privileged: hook.Privileged, Env: ToMobyEnv(hook.Environment), WorkingDir: hook.WorkingDir, Cmd: hook.Command, AttachStdout: !detached, AttachStderr: !detached, }) if err != nil { return err } if detached { return s.runWaitExec(ctx, exec.ID, service, listener) } height, width := s.stdout().GetTtySize() consoleSize := &[2]uint{height, width} attach, err := s.apiClient().ContainerExecAttach(ctx, exec.ID, container.ExecAttachOptions{ Tty: service.Tty, ConsoleSize: consoleSize, }) if err != nil { return err } defer attach.Close() if service.Tty { _, err = io.Copy(wOut, attach.Reader) } else { _, err = stdcopy.StdCopy(wOut, wOut, attach.Reader) } if err != nil { return err } inspected, err := s.apiClient().ContainerExecInspect(ctx, exec.ID) if err != nil { return err } if inspected.ExitCode != 0 { return fmt.Errorf("%s hook exited with status %d", service.Name, inspected.ExitCode) } return nil } func (s composeService) runWaitExec(ctx context.Context, execID string, service types.ServiceConfig, listener api.ContainerEventListener) error { err := s.apiClient().ContainerExecStart(ctx, execID, container.ExecStartOptions{ Detach: listener == nil, Tty: service.Tty, }) if err != nil { return nil } // We miss a ContainerExecWait API tick := time.NewTicker(100 * time.Millisecond) for { select { case <-ctx.Done(): return nil case <-tick.C: inspect, err := s.apiClient().ContainerExecInspect(ctx, execID) if err != nil { return nil } if !inspect.Running { if inspect.ExitCode != 0 { return fmt.Errorf("%s hook exited with status %d", service.Name, inspect.ExitCode) } return nil } } } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/exec.go
pkg/compose/exec.go
/* 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" "strings" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command/container" containerType "github.com/docker/docker/api/types/container" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Exec(ctx context.Context, projectName string, options api.RunOptions) (int, error) { projectName = strings.ToLower(projectName) target, err := s.getExecTarget(ctx, projectName, options) if err != nil { return 0, err } exec := container.NewExecOptions() exec.Interactive = options.Interactive exec.TTY = options.Tty exec.Detach = options.Detach exec.User = options.User exec.Privileged = options.Privileged exec.Workdir = options.WorkingDir exec.Command = options.Command for _, v := range options.Environment { err := exec.Env.Set(v) if err != nil { return 0, err } } err = container.RunExec(ctx, s.dockerCli, target.ID, exec) var sterr cli.StatusError if errors.As(err, &sterr) { return sterr.StatusCode, err } return 0, err } func (s *composeService) getExecTarget(ctx context.Context, projectName string, opts api.RunOptions) (containerType.Summary, error) { return s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, opts.Service, opts.Index) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/loader.go
pkg/compose/loader.go
/* 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" "os" "strings" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/loader" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/remote" "github.com/docker/compose/v5/pkg/utils" ) // LoadProject implements api.Compose.LoadProject // It loads and validates a Compose project from configuration files. func (s *composeService) LoadProject(ctx context.Context, options api.ProjectLoadOptions) (*types.Project, error) { // Setup remote loaders (Git, OCI) remoteLoaders := s.createRemoteLoaders(options) projectOptions, err := s.buildProjectOptions(options, remoteLoaders) if err != nil { return nil, err } // Register all user-provided listeners (e.g., for metrics collection) for _, listener := range options.LoadListeners { if listener != nil { projectOptions.WithListeners(listener) } } if options.Compatibility || utils.StringToBool(projectOptions.Environment[api.ComposeCompatibility]) { api.Separator = "_" } project, err := projectOptions.LoadProject(ctx) if err != nil { return nil, err } // Post-processing: service selection, environment resolution, etc. project, err = s.postProcessProject(project, options) if err != nil { return nil, err } return project, nil } // createRemoteLoaders creates Git and OCI remote loaders if not in offline mode func (s *composeService) createRemoteLoaders(options api.ProjectLoadOptions) []loader.ResourceLoader { if options.Offline { return nil } git := remote.NewGitRemoteLoader(s.dockerCli, options.Offline) oci := remote.NewOCIRemoteLoader(s.dockerCli, options.Offline, options.OCI) return []loader.ResourceLoader{git, oci} } // buildProjectOptions constructs compose-go ProjectOptions from API options func (s *composeService) buildProjectOptions(options api.ProjectLoadOptions, remoteLoaders []loader.ResourceLoader) (*cli.ProjectOptions, error) { opts := []cli.ProjectOptionsFn{ cli.WithWorkingDirectory(options.WorkingDir), cli.WithOsEnv, } // Add PWD if not present if _, present := os.LookupEnv("PWD"); !present { if pwd, err := os.Getwd(); err == nil { opts = append(opts, cli.WithEnv([]string{"PWD=" + pwd})) } } // Add remote loaders for _, r := range remoteLoaders { opts = append(opts, cli.WithResourceLoader(r)) } opts = append(opts, // Load PWD/.env if present and no explicit --env-file has been set cli.WithEnvFiles(options.EnvFiles...), // read dot env file to populate project environment cli.WithDotEnv, // get compose file path set by COMPOSE_FILE cli.WithConfigFileEnv, // if none was selected, get default compose.yaml file from current dir or parent folder cli.WithDefaultConfigPath, // .. and then, a project directory != PWD maybe has been set so let's load .env file cli.WithEnvFiles(options.EnvFiles...), //nolint:gocritic // intentionally applying cli.WithEnvFiles twice. cli.WithDotEnv, //nolint:gocritic // intentionally applying cli.WithDotEnv twice. // eventually COMPOSE_PROFILES should have been set cli.WithDefaultProfiles(options.Profiles...), cli.WithName(options.ProjectName), ) return cli.NewProjectOptions(options.ConfigPaths, append(options.ProjectOptionsFns, opts...)...) } // postProcessProject applies post-loading transformations to the project func (s *composeService) postProcessProject(project *types.Project, options api.ProjectLoadOptions) (*types.Project, error) { if project.Name == "" { return nil, errors.New("project name can't be empty. Use ProjectName option to set a valid name") } project, err := project.WithServicesEnabled(options.Services...) if err != nil { return nil, err } // Add custom labels for name, s := range project.Services { s.CustomLabels = map[string]string{ api.ProjectLabel: project.Name, api.ServiceLabel: name, api.VersionLabel: api.ComposeVersion, api.WorkingDirLabel: project.WorkingDir, api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","), api.OneoffLabel: "False", } if len(options.EnvFiles) != 0 { s.CustomLabels[api.EnvironmentFileLabel] = strings.Join(options.EnvFiles, ",") } project.Services[name] = s } project, err = project.WithSelectedServices(options.Services) if err != nil { return nil, err } // Remove unnecessary resources if not All if !options.All { project = project.WithoutUnnecessaryResources() } return project, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/stop.go
pkg/compose/stop.go
/* 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" "slices" "strings" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Stop(ctx context.Context, projectName string, options api.StopOptions) error { return Run(ctx, func(ctx context.Context) error { return s.stop(ctx, strings.ToLower(projectName), options, nil) }, "stop", s.events) } func (s *composeService) stop(ctx context.Context, projectName string, options api.StopOptions, event api.ContainerEventListener) error { containers, err := s.getContainers(ctx, projectName, oneOffExclude, true) if err != nil { return err } project := options.Project if project == nil { project, err = s.getProjectWithResources(ctx, containers, projectName) if err != nil { return err } } if len(options.Services) == 0 { options.Services = project.ServiceNames() } return InReverseDependencyOrder(ctx, project, func(c context.Context, service string) error { if !slices.Contains(options.Services, service) { return nil } serv := project.Services[service] return s.stopContainers(ctx, &serv, containers.filter(isService(service)).filter(isNotOneOff), options.Timeout, event) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/watch_test.go
pkg/compose/watch_test.go
/* 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" "fmt" "os" "testing" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/streams" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/jonboulle/clockwork" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" "github.com/docker/compose/v5/internal/sync" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/mocks" "github.com/docker/compose/v5/pkg/watch" ) type testWatcher struct { events chan watch.FileEvent errors chan error } func (t testWatcher) Start() error { return nil } func (t testWatcher) Close() error { return nil } func (t testWatcher) Events() chan watch.FileEvent { return t.events } func (t testWatcher) Errors() chan error { return t.errors } type stdLogger struct{} func (s stdLogger) Log(containerName, message string) { fmt.Printf("%s: %s\n", containerName, message) } func (s stdLogger) Err(containerName, message string) { fmt.Fprintf(os.Stderr, "%s: %s\n", containerName, message) } func (s stdLogger) Status(containerName, msg string) { fmt.Printf("%s: %s\n", containerName, msg) } func TestWatch_Sync(t *testing.T) { mockCtrl := gomock.NewController(t) cli := mocks.NewMockCli(mockCtrl) cli.EXPECT().Err().Return(streams.NewOut(os.Stderr)).AnyTimes() apiClient := mocks.NewMockAPIClient(mockCtrl) apiClient.EXPECT().ContainerList(gomock.Any(), gomock.Any()).Return([]container.Summary{ testContainer("test", "123", false), }, nil).AnyTimes() // we expect the image to be pruned apiClient.EXPECT().ImageList(gomock.Any(), image.ListOptions{ Filters: filters.NewArgs( filters.Arg("dangling", "true"), filters.Arg("label", api.ProjectLabel+"=myProjectName"), ), }).Return([]image.Summary{ {ID: "123"}, {ID: "456"}, }, nil).Times(1) apiClient.EXPECT().ImageRemove(gomock.Any(), "123", image.RemoveOptions{}).Times(1) apiClient.EXPECT().ImageRemove(gomock.Any(), "456", image.RemoveOptions{}).Times(1) // cli.EXPECT().Client().Return(apiClient).AnyTimes() ctx, cancelFunc := context.WithCancel(context.Background()) t.Cleanup(cancelFunc) proj := types.Project{ Name: "myProjectName", Services: types.Services{ "test": { Name: "test", }, }, } watcher := testWatcher{ events: make(chan watch.FileEvent), errors: make(chan error), } syncer := newFakeSyncer() clock := clockwork.NewFakeClock() go func() { service := composeService{ dockerCli: cli, clock: clock, } rules, err := getWatchRules(&types.DevelopConfig{ Watch: []types.Trigger{ { Path: "/sync", Action: "sync", Target: "/work", Ignore: []string{"ignore"}, }, { Path: "/rebuild", Action: "rebuild", }, }, }, types.ServiceConfig{Name: "test"}) assert.NilError(t, err) err = service.watchEvents(ctx, &proj, api.WatchOptions{ Build: &api.BuildOptions{}, LogTo: stdLogger{}, Prune: true, }, watcher, syncer, rules) assert.NilError(t, err) }() watcher.Events() <- watch.NewFileEvent("/sync/changed") watcher.Events() <- watch.NewFileEvent("/sync/changed/sub") err := clock.BlockUntilContext(ctx, 3) assert.NilError(t, err) clock.Advance(watch.QuietPeriod) select { case actual := <-syncer.synced: require.ElementsMatch(t, []*sync.PathMapping{ {HostPath: "/sync/changed", ContainerPath: "/work/changed"}, {HostPath: "/sync/changed/sub", ContainerPath: "/work/changed/sub"}, }, actual) case <-time.After(100 * time.Millisecond): t.Error("timeout") } watcher.Events() <- watch.NewFileEvent("/rebuild") watcher.Events() <- watch.NewFileEvent("/sync/changed") err = clock.BlockUntilContext(ctx, 4) assert.NilError(t, err) clock.Advance(watch.QuietPeriod) select { case batch := <-syncer.synced: t.Fatalf("received unexpected events: %v", batch) case <-time.After(100 * time.Millisecond): // expected } // TODO: there's not a great way to assert that the rebuild attempt happened } type fakeSyncer struct { synced chan []*sync.PathMapping } func newFakeSyncer() *fakeSyncer { return &fakeSyncer{ synced: make(chan []*sync.PathMapping), } } func (f *fakeSyncer) Sync(ctx context.Context, service string, paths []*sync.PathMapping) error { f.synced <- paths return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/commit.go
pkg/compose/commit.go
/* 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" "fmt" "strings" "github.com/docker/docker/api/types/container" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Commit(ctx context.Context, projectName string, options api.CommitOptions) error { return Run(ctx, func(ctx context.Context) error { return s.commit(ctx, projectName, options) }, "commit", s.events) } func (s *composeService) commit(ctx context.Context, projectName string, options api.CommitOptions) error { projectName = strings.ToLower(projectName) ctr, err := s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, options.Service, options.Index) if err != nil { return err } name := getCanonicalContainerName(ctr) s.events.On(api.Resource{ ID: name, Status: api.Working, Text: api.StatusCommitting, }) if s.dryRun { s.events.On(api.Resource{ ID: name, Status: api.Done, Text: api.StatusCommitted, }) return nil } response, err := s.apiClient().ContainerCommit(ctx, ctr.ID, container.CommitOptions{ Reference: options.Reference, Comment: options.Comment, Author: options.Author, Changes: options.Changes.GetSlice(), Pause: options.Pause, }) if err != nil { return err } s.events.On(api.Resource{ ID: name, Text: fmt.Sprintf("Committed as %s", response.ID), Status: api.Done, }) return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/create.go
pkg/compose/create.go
/* 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 ( "bytes" "context" "encoding/json" "errors" "fmt" "os" "path/filepath" "slices" "strconv" "strings" "github.com/compose-spec/compose-go/v2/paths" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" "github.com/docker/docker/api/types/blkiodev" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/versions" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/go-connections/nat" "github.com/sirupsen/logrus" cdi "tags.cncf.io/container-device-interface/pkg/parser" "github.com/docker/compose/v5/pkg/api" ) type createOptions struct { AutoRemove bool AttachStdin bool UseNetworkAliases bool Labels types.Labels } type createConfigs struct { Container *container.Config Host *container.HostConfig Network *network.NetworkingConfig Links []string } func (s *composeService) Create(ctx context.Context, project *types.Project, createOpts api.CreateOptions) error { return Run(ctx, func(ctx context.Context) error { return s.create(ctx, project, createOpts) }, "create", s.events) } func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error { if len(options.Services) == 0 { options.Services = project.ServiceNames() } err := project.CheckContainerNameUnicity() if err != nil { return err } err = s.ensureImagesExists(ctx, project, options.Build, options.QuietPull) if err != nil { return err } err = s.ensureModels(ctx, project, options.QuietPull) if err != nil { return err } prepareNetworks(project) networks, err := s.ensureNetworks(ctx, project) if err != nil { return err } volumes, err := s.ensureProjectVolumes(ctx, project) if err != nil { return err } var observedState Containers observedState, err = s.getContainers(ctx, project.Name, oneOffInclude, true) if err != nil { return err } orphans := observedState.filter(isOrphaned(project)) if len(orphans) > 0 && !options.IgnoreOrphans { if options.RemoveOrphans { err := s.removeContainers(ctx, orphans, nil, nil, false) if err != nil { return err } } else { logrus.Warnf("Found orphan containers (%s) for this project. If "+ "you removed or renamed this service in your compose "+ "file, you can run this command with the "+ "--remove-orphans flag to clean it up.", orphans.names()) } } // Temporary implementation of use_api_socket until we get actual support inside docker engine project, err = s.useAPISocket(project) if err != nil { return err } return newConvergence(options.Services, observedState, networks, volumes, s).apply(ctx, project, options) } func prepareNetworks(project *types.Project) { for k, nw := range project.Networks { nw.CustomLabels = nw.CustomLabels. Add(api.NetworkLabel, k). Add(api.ProjectLabel, project.Name). Add(api.VersionLabel, api.ComposeVersion) project.Networks[k] = nw } } func (s *composeService) ensureNetworks(ctx context.Context, project *types.Project) (map[string]string, error) { networks := map[string]string{} for name, nw := range project.Networks { id, err := s.ensureNetwork(ctx, project, name, &nw) if err != nil { return nil, err } networks[name] = id project.Networks[name] = nw } return networks, nil } func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) (map[string]string, error) { ids := map[string]string{} for k, volume := range project.Volumes { volume.CustomLabels = volume.CustomLabels.Add(api.VolumeLabel, k) volume.CustomLabels = volume.CustomLabels.Add(api.ProjectLabel, project.Name) volume.CustomLabels = volume.CustomLabels.Add(api.VersionLabel, api.ComposeVersion) id, err := s.ensureVolume(ctx, k, volume, project) if err != nil { return nil, err } ids[k] = id } return ids, nil } //nolint:gocyclo func (s *composeService) getCreateConfigs(ctx context.Context, p *types.Project, service types.ServiceConfig, number int, inherit *container.Summary, opts createOptions, ) (createConfigs, error) { labels, err := s.prepareLabels(opts.Labels, service, number) if err != nil { return createConfigs{}, err } var runCmd, entrypoint []string if service.Command != nil { runCmd = service.Command } if service.Entrypoint != nil { entrypoint = service.Entrypoint } var ( tty = service.Tty stdinOpen = service.StdinOpen ) proxyConfig := types.MappingWithEquals(s.configFile().ParseProxyConfig(s.apiClient().DaemonHost(), nil)) env := proxyConfig.OverrideBy(service.Environment) var mainNwName string var mainNw *types.ServiceNetworkConfig if len(service.Networks) > 0 { mainNwName = service.NetworksByPriority()[0] mainNw = service.Networks[mainNwName] } macAddress, err := s.prepareContainerMACAddress(ctx, service, mainNw, mainNwName) if err != nil { return createConfigs{}, err } healthcheck, err := s.ToMobyHealthCheck(ctx, service.HealthCheck) if err != nil { return createConfigs{}, err } exposed, err := buildContainerPorts(service) if err != nil { return createConfigs{}, err } containerConfig := container.Config{ Hostname: service.Hostname, Domainname: service.DomainName, User: service.User, ExposedPorts: exposed, Tty: tty, OpenStdin: stdinOpen, StdinOnce: opts.AttachStdin && stdinOpen, AttachStdin: opts.AttachStdin, AttachStderr: true, AttachStdout: true, Cmd: runCmd, Image: api.GetImageNameOrDefault(service, p.Name), WorkingDir: service.WorkingDir, Entrypoint: entrypoint, NetworkDisabled: service.NetworkMode == "disabled", MacAddress: macAddress, // Field is deprecated since API v1.44, but kept for compatibility with older API versions. Labels: labels, StopSignal: service.StopSignal, Env: ToMobyEnv(env), Healthcheck: healthcheck, StopTimeout: ToSeconds(service.StopGracePeriod), } // VOLUMES/MOUNTS/FILESYSTEMS tmpfs := map[string]string{} for _, t := range service.Tmpfs { if arr := strings.SplitN(t, ":", 2); len(arr) > 1 { tmpfs[arr[0]] = arr[1] } else { tmpfs[arr[0]] = "" } } binds, mounts, err := s.buildContainerVolumes(ctx, *p, service, inherit) if err != nil { return createConfigs{}, err } // NETWORKING links, err := s.getLinks(ctx, p.Name, service, number) if err != nil { return createConfigs{}, err } apiVersion, err := s.RuntimeVersion(ctx) if err != nil { return createConfigs{}, err } networkMode, networkingConfig, err := defaultNetworkSettings(p, service, number, links, opts.UseNetworkAliases, apiVersion) if err != nil { return createConfigs{}, err } portBindings := buildContainerPortBindingOptions(service) // MISC resources := getDeployResources(service) var logConfig container.LogConfig if service.Logging != nil { logConfig = container.LogConfig{ Type: service.Logging.Driver, Config: service.Logging.Options, } } securityOpts, unconfined, err := parseSecurityOpts(p, service.SecurityOpt) if err != nil { return createConfigs{}, err } hostConfig := container.HostConfig{ AutoRemove: opts.AutoRemove, Annotations: service.Annotations, Binds: binds, Mounts: mounts, CapAdd: service.CapAdd, CapDrop: service.CapDrop, NetworkMode: networkMode, Init: service.Init, IpcMode: container.IpcMode(service.Ipc), CgroupnsMode: container.CgroupnsMode(service.Cgroup), ReadonlyRootfs: service.ReadOnly, RestartPolicy: getRestartPolicy(service), ShmSize: int64(service.ShmSize), Sysctls: service.Sysctls, PortBindings: portBindings, Resources: resources, VolumeDriver: service.VolumeDriver, VolumesFrom: service.VolumesFrom, DNS: service.DNS, DNSSearch: service.DNSSearch, DNSOptions: service.DNSOpts, ExtraHosts: service.ExtraHosts.AsList(":"), SecurityOpt: securityOpts, StorageOpt: service.StorageOpt, UsernsMode: container.UsernsMode(service.UserNSMode), UTSMode: container.UTSMode(service.Uts), Privileged: service.Privileged, PidMode: container.PidMode(service.Pid), Tmpfs: tmpfs, Isolation: container.Isolation(service.Isolation), Runtime: service.Runtime, LogConfig: logConfig, GroupAdd: service.GroupAdd, Links: links, OomScoreAdj: int(service.OomScoreAdj), } if unconfined { hostConfig.MaskedPaths = []string{} hostConfig.ReadonlyPaths = []string{} } cfgs := createConfigs{ Container: &containerConfig, Host: &hostConfig, Network: networkingConfig, Links: links, } return cfgs, nil } // prepareContainerMACAddress handles the service-level mac_address field and the newer mac_address field added to service // network config. This newer field is only compatible with the Engine API v1.44 (and onwards), and this API version // also deprecates the container-wide mac_address field. Thus, this method will validate service config and mutate the // passed mainNw to provide backward-compatibility whenever possible. // // It returns the container-wide MAC address, but this value will be kept empty for newer API versions. func (s *composeService) prepareContainerMACAddress(ctx context.Context, service types.ServiceConfig, mainNw *types.ServiceNetworkConfig, nwName string) (string, error) { version, err := s.RuntimeVersion(ctx) if err != nil { return "", err } // Engine API 1.44 added support for endpoint-specific MAC address and now returns a warning when a MAC address is // set in container.Config. Thus, we have to jump through a number of hoops: // // 1. Top-level mac_address and main endpoint's MAC address should be the same ; // 2. If supported by the API, top-level mac_address should be migrated to the main endpoint and container.Config // should be kept empty ; // 3. Otherwise, the endpoint mac_address should be set in container.Config and no other endpoint-specific // mac_address can be specified. If that's the case, use top-level mac_address ; // // After that, if an endpoint mac_address is set, it's either user-defined or migrated by the code below, so // there's no need to check for API version in defaultNetworkSettings. macAddress := service.MacAddress if macAddress != "" && mainNw != nil && mainNw.MacAddress != "" && mainNw.MacAddress != macAddress { return "", fmt.Errorf("the service-level mac_address should have the same value as network %s", nwName) } if versions.GreaterThanOrEqualTo(version, "1.44") { if mainNw != nil && mainNw.MacAddress == "" { mainNw.MacAddress = macAddress } macAddress = "" } else if len(service.Networks) > 0 { var withMacAddress []string for nwName, nw := range service.Networks { if nw != nil && nw.MacAddress != "" { withMacAddress = append(withMacAddress, nwName) } } if len(withMacAddress) > 1 { return "", fmt.Errorf("a MAC address is specified for multiple networks (%s), but this feature requires Docker Engine v25 or later", strings.Join(withMacAddress, ", ")) } if mainNw != nil && mainNw.MacAddress != "" { macAddress = mainNw.MacAddress } } return macAddress, nil } func getAliases(project *types.Project, service types.ServiceConfig, serviceIndex int, cfg *types.ServiceNetworkConfig, useNetworkAliases bool) []string { aliases := []string{getContainerName(project.Name, service, serviceIndex)} if useNetworkAliases { aliases = append(aliases, service.Name) if cfg != nil { aliases = append(aliases, cfg.Aliases...) } } return aliases } func createEndpointSettings(p *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, links []string, useNetworkAliases bool) *network.EndpointSettings { const ifname = "com.docker.network.endpoint.ifname" config := service.Networks[networkKey] var ipam *network.EndpointIPAMConfig var ( ipv4Address string ipv6Address string macAddress string driverOpts types.Options gwPriority int ) if config != nil { ipv4Address = config.Ipv4Address ipv6Address = config.Ipv6Address ipam = &network.EndpointIPAMConfig{ IPv4Address: ipv4Address, IPv6Address: ipv6Address, LinkLocalIPs: config.LinkLocalIPs, } macAddress = config.MacAddress driverOpts = config.DriverOpts if config.InterfaceName != "" { if driverOpts == nil { driverOpts = map[string]string{} } if name, ok := driverOpts[ifname]; ok && name != config.InterfaceName { logrus.Warnf("ignoring services.%s.networks.%s.interface_name as %s driver_opts is already declared", service.Name, networkKey, ifname) } driverOpts[ifname] = config.InterfaceName } gwPriority = config.GatewayPriority } return &network.EndpointSettings{ Aliases: getAliases(p, service, serviceIndex, config, useNetworkAliases), Links: links, IPAddress: ipv4Address, IPv6Gateway: ipv6Address, IPAMConfig: ipam, MacAddress: macAddress, DriverOpts: driverOpts, GwPriority: gwPriority, } } // copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath // TODO find so way to share this code with docker/cli func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, bool, error) { var ( unconfined bool parsed []string ) for _, opt := range securityOpts { if opt == "systempaths=unconfined" { unconfined = true continue } con := strings.SplitN(opt, "=", 2) if len(con) == 1 && con[0] != "no-new-privileges" { if strings.Contains(opt, ":") { con = strings.SplitN(opt, ":", 2) } else { return securityOpts, false, fmt.Errorf("invalid security-opt: %q", opt) } } if con[0] == "seccomp" && con[1] != "unconfined" && con[1] != "builtin" { f, err := os.ReadFile(p.RelativePath(con[1])) if err != nil { return securityOpts, false, fmt.Errorf("opening seccomp profile (%s) failed: %w", con[1], err) } b := bytes.NewBuffer(nil) if err := json.Compact(b, f); err != nil { return securityOpts, false, fmt.Errorf("compacting json for seccomp profile (%s) failed: %w", con[1], err) } parsed = append(parsed, fmt.Sprintf("seccomp=%s", b.Bytes())) } else { parsed = append(parsed, opt) } } return parsed, unconfined, nil } func (s *composeService) prepareLabels(labels types.Labels, service types.ServiceConfig, number int) (map[string]string, error) { hash, err := ServiceHash(service) if err != nil { return nil, err } labels[api.ConfigHashLabel] = hash if number > 0 { // One-off containers are not indexed labels[api.ContainerNumberLabel] = strconv.Itoa(number) } var dependencies []string for s, d := range service.DependsOn { dependencies = append(dependencies, fmt.Sprintf("%s:%s:%t", s, d.Condition, d.Restart)) } labels[api.DependenciesLabel] = strings.Join(dependencies, ",") return labels, nil } // defaultNetworkSettings determines the container.NetworkMode and corresponding network.NetworkingConfig (nil if not applicable). func defaultNetworkSettings(project *types.Project, service types.ServiceConfig, serviceIndex int, links []string, useNetworkAliases bool, version string, ) (container.NetworkMode, *network.NetworkingConfig, error) { if service.NetworkMode != "" { return container.NetworkMode(service.NetworkMode), nil, nil } if len(project.Networks) == 0 { return "none", nil, nil } var primaryNetworkKey string if len(service.Networks) > 0 { primaryNetworkKey = service.NetworksByPriority()[0] } else { primaryNetworkKey = "default" } primaryNetworkMobyNetworkName := project.Networks[primaryNetworkKey].Name primaryNetworkEndpoint := createEndpointSettings(project, service, serviceIndex, primaryNetworkKey, links, useNetworkAliases) endpointsConfig := map[string]*network.EndpointSettings{} // Starting from API version 1.44, the Engine will take several EndpointsConfigs // so we can pass all the extra networks we want the container to be connected to // in the network configuration instead of connecting the container to each extra // network individually after creation. if versions.GreaterThanOrEqualTo(version, "1.44") { if len(service.Networks) > 1 { serviceNetworks := service.NetworksByPriority() for _, networkKey := range serviceNetworks[1:] { mobyNetworkName := project.Networks[networkKey].Name epSettings := createEndpointSettings(project, service, serviceIndex, networkKey, links, useNetworkAliases) endpointsConfig[mobyNetworkName] = epSettings } } if primaryNetworkEndpoint.MacAddress == "" { primaryNetworkEndpoint.MacAddress = service.MacAddress } } if versions.LessThan(version, "1.49") { for _, config := range service.Networks { if config != nil && config.InterfaceName != "" { return "", nil, fmt.Errorf("interface_name requires Docker Engine v28.1 or later") } } } endpointsConfig[primaryNetworkMobyNetworkName] = primaryNetworkEndpoint networkConfig := &network.NetworkingConfig{ EndpointsConfig: endpointsConfig, } // From the Engine API docs: // > Supported standard values are: bridge, host, none, and container:<name|id>. // > Any other value is taken as a custom network's name to which this container should connect to. return container.NetworkMode(primaryNetworkMobyNetworkName), networkConfig, nil } func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy { var restart container.RestartPolicy if service.Restart != "" { split := strings.Split(service.Restart, ":") var attempts int if len(split) > 1 { attempts, _ = strconv.Atoi(split[1]) } restart = container.RestartPolicy{ Name: mapRestartPolicyCondition(split[0]), MaximumRetryCount: attempts, } } if service.Deploy != nil && service.Deploy.RestartPolicy != nil { policy := *service.Deploy.RestartPolicy var attempts int if policy.MaxAttempts != nil { attempts = int(*policy.MaxAttempts) } restart = container.RestartPolicy{ Name: mapRestartPolicyCondition(policy.Condition), MaximumRetryCount: attempts, } } return restart } func mapRestartPolicyCondition(condition string) container.RestartPolicyMode { // map definitions of deploy.restart_policy to engine definitions switch condition { case "none", "no": return container.RestartPolicyDisabled case "on-failure": return container.RestartPolicyOnFailure case "unless-stopped": return container.RestartPolicyUnlessStopped case "any", "always": return container.RestartPolicyAlways default: return container.RestartPolicyMode(condition) } } func getDeployResources(s types.ServiceConfig) container.Resources { var swappiness *int64 if s.MemSwappiness != 0 { val := int64(s.MemSwappiness) swappiness = &val } resources := container.Resources{ CgroupParent: s.CgroupParent, Memory: int64(s.MemLimit), MemorySwap: int64(s.MemSwapLimit), MemorySwappiness: swappiness, MemoryReservation: int64(s.MemReservation), OomKillDisable: &s.OomKillDisable, CPUCount: s.CPUCount, CPUPeriod: s.CPUPeriod, CPUQuota: s.CPUQuota, CPURealtimePeriod: s.CPURTPeriod, CPURealtimeRuntime: s.CPURTRuntime, CPUShares: s.CPUShares, NanoCPUs: int64(s.CPUS * 1e9), CPUPercent: int64(s.CPUPercent * 100), CpusetCpus: s.CPUSet, DeviceCgroupRules: s.DeviceCgroupRules, } if s.PidsLimit != 0 { resources.PidsLimit = &s.PidsLimit } setBlkio(s.BlkioConfig, &resources) if s.Deploy != nil { setLimits(s.Deploy.Resources.Limits, &resources) setReservations(s.Deploy.Resources.Reservations, &resources) } var cdiDeviceNames []string for _, device := range s.Devices { if device.Source == device.Target && cdi.IsQualifiedName(device.Source) { cdiDeviceNames = append(cdiDeviceNames, device.Source) continue } resources.Devices = append(resources.Devices, container.DeviceMapping{ PathOnHost: device.Source, PathInContainer: device.Target, CgroupPermissions: device.Permissions, }) } if len(cdiDeviceNames) > 0 { resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{ Driver: "cdi", DeviceIDs: cdiDeviceNames, }) } for _, gpus := range s.Gpus { resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{ Driver: gpus.Driver, Count: int(gpus.Count), DeviceIDs: gpus.IDs, Capabilities: [][]string{append(gpus.Capabilities, "gpu")}, Options: gpus.Options, }) } ulimits := toUlimits(s.Ulimits) resources.Ulimits = ulimits return resources } func toUlimits(m map[string]*types.UlimitsConfig) []*container.Ulimit { var ulimits []*container.Ulimit for name, u := range m { soft := u.Single if u.Soft != 0 { soft = u.Soft } hard := u.Single if u.Hard != 0 { hard = u.Hard } ulimits = append(ulimits, &container.Ulimit{ Name: name, Hard: int64(hard), Soft: int64(soft), }) } return ulimits } func setReservations(reservations *types.Resource, resources *container.Resources) { if reservations == nil { return } // Cpu reservation is a swarm option and PIDs is only a limit // So we only need to map memory reservation and devices if reservations.MemoryBytes != 0 { resources.MemoryReservation = int64(reservations.MemoryBytes) } for _, device := range reservations.Devices { resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{ Capabilities: [][]string{device.Capabilities}, Count: int(device.Count), DeviceIDs: device.IDs, Driver: device.Driver, Options: device.Options, }) } } func setLimits(limits *types.Resource, resources *container.Resources) { if limits == nil { return } if limits.MemoryBytes != 0 { resources.Memory = int64(limits.MemoryBytes) } if limits.NanoCPUs != 0 { resources.NanoCPUs = int64(limits.NanoCPUs * 1e9) } if limits.Pids > 0 { resources.PidsLimit = &limits.Pids } } func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) { if blkio == nil { return } resources.BlkioWeight = blkio.Weight for _, b := range blkio.WeightDevice { resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{ Path: b.Path, Weight: b.Weight, }) } for _, b := range blkio.DeviceReadBps { resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{ Path: b.Path, Rate: uint64(b.Rate), }) } for _, b := range blkio.DeviceReadIOps { resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{ Path: b.Path, Rate: uint64(b.Rate), }) } for _, b := range blkio.DeviceWriteBps { resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{ Path: b.Path, Rate: uint64(b.Rate), }) } for _, b := range blkio.DeviceWriteIOps { resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{ Path: b.Path, Rate: uint64(b.Rate), }) } } func buildContainerPorts(s types.ServiceConfig) (nat.PortSet, error) { ports := nat.PortSet{} for _, s := range s.Expose { proto, port := nat.SplitProtoPort(s) start, end, err := nat.ParsePortRange(port) if err != nil { return nil, err } for i := start; i <= end; i++ { p := nat.Port(fmt.Sprintf("%d/%s", i, proto)) ports[p] = struct{}{} } } for _, p := range s.Ports { p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol)) ports[p] = struct{}{} } return ports, nil } func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap { bindings := nat.PortMap{} for _, port := range s.Ports { p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol)) binding := nat.PortBinding{ HostIP: port.HostIP, HostPort: port.Published, } bindings[p] = append(bindings[p], binding) } return bindings } func getDependentServiceFromMode(mode string) string { if strings.HasPrefix( mode, types.NetworkModeServicePrefix, ) { return mode[len(types.NetworkModeServicePrefix):] } return "" } func (s *composeService) buildContainerVolumes( ctx context.Context, p types.Project, service types.ServiceConfig, inherit *container.Summary, ) ([]string, []mount.Mount, error) { var mounts []mount.Mount var binds []string mountOptions, err := s.buildContainerMountOptions(ctx, p, service, inherit) if err != nil { return nil, nil, err } for _, m := range mountOptions { switch m.Type { case mount.TypeBind: // `Mount` is preferred but does not offer option to created host path if missing // so `Bind` API is used here with raw volume string // see https://github.com/moby/moby/issues/43483 v := findVolumeByTarget(service.Volumes, m.Target) if v != nil { if v.Type != types.VolumeTypeBind { v.Source = m.Source } if !bindRequiresMountAPI(v.Bind) { source := m.Source if vol := findVolumeByName(p.Volumes, m.Source); vol != nil { source = m.Source } binds = append(binds, toBindString(source, v)) continue } } case mount.TypeVolume: v := findVolumeByTarget(service.Volumes, m.Target) vol := findVolumeByName(p.Volumes, m.Source) if v != nil && vol != nil { // Prefer the bind API if no advanced option is used, to preserve backward compatibility if !volumeRequiresMountAPI(v.Volume) { binds = append(binds, toBindString(vol.Name, v)) continue } } case mount.TypeImage: version, err := s.RuntimeVersion(ctx) if err != nil { return nil, nil, err } if versions.LessThan(version, "1.48") { return nil, nil, fmt.Errorf("volume with type=image require Docker Engine v28 or later") } } mounts = append(mounts, m) } return binds, mounts, nil } func toBindString(name string, v *types.ServiceVolumeConfig) string { access := "rw" if v.ReadOnly { access = "ro" } options := []string{access} if v.Bind != nil && v.Bind.SELinux != "" { options = append(options, v.Bind.SELinux) } if v.Bind != nil && v.Bind.Propagation != "" { options = append(options, v.Bind.Propagation) } if v.Volume != nil && v.Volume.NoCopy { options = append(options, "nocopy") } return fmt.Sprintf("%s:%s:%s", name, v.Target, strings.Join(options, ",")) } func findVolumeByName(volumes types.Volumes, name string) *types.VolumeConfig { for _, vol := range volumes { if vol.Name == name { return &vol } } return nil } func findVolumeByTarget(volumes []types.ServiceVolumeConfig, target string) *types.ServiceVolumeConfig { for _, v := range volumes { if v.Target == target { return &v } } return nil } // bindRequiresMountAPI check if Bind declaration can be implemented by the plain old Bind API or uses any of the advanced // options which require use of Mount API func bindRequiresMountAPI(bind *types.ServiceVolumeBind) bool { switch { case bind == nil: return false case !bool(bind.CreateHostPath): return true case bind.Propagation != "": return true case bind.Recursive != "": return true default: return false } } // volumeRequiresMountAPI check if Volume declaration can be implemented by the plain old Bind API or uses any of the advanced // options which require use of Mount API func volumeRequiresMountAPI(vol *types.ServiceVolumeVolume) bool { switch { case vol == nil: return false case len(vol.Labels) > 0: return true case vol.Subpath != "": return true case vol.NoCopy: return true default: return false } } func (s *composeService) buildContainerMountOptions(ctx context.Context, p types.Project, service types.ServiceConfig, inherit *container.Summary) ([]mount.Mount, error) { mounts := map[string]mount.Mount{} if inherit != nil { for _, m := range inherit.Mounts { if m.Type == "tmpfs" { continue } src := m.Source if m.Type == "volume" { src = m.Name } img, err := s.apiClient().ImageInspect(ctx, api.GetImageNameOrDefault(service, p.Name)) if err != nil { return nil, err } if img.Config != nil { if _, ok := img.Config.Volumes[m.Destination]; ok { // inherit previous container's anonymous volume mounts[m.Destination] = mount.Mount{ Type: m.Type, Source: src, Target: m.Destination, ReadOnly: !m.RW, } } } volumes := []types.ServiceVolumeConfig{} for _, v := range service.Volumes { if v.Target != m.Destination || v.Source != "" { volumes = append(volumes, v) continue } // inherit previous container's anonymous volume mounts[m.Destination] = mount.Mount{ Type: m.Type, Source: src, Target: m.Destination, ReadOnly: !m.RW, } } service.Volumes = volumes } } mounts, err := fillBindMounts(p, service, mounts) if err != nil { return nil, err } values := make([]mount.Mount, 0, len(mounts)) for _, v := range mounts { values = append(values, v) } return values, nil } func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) { for _, v := range s.Volumes { bindMount, err := buildMount(p, v) if err != nil { return nil, err } m[bindMount.Target] = bindMount } secrets, err := buildContainerSecretMounts(p, s) if err != nil { return nil, err } for _, s := range secrets { if _, found := m[s.Target]; found { continue } m[s.Target] = s } configs, err := buildContainerConfigMounts(p, s) if err != nil { return nil, err } for _, c := range configs { if _, found := m[c.Target]; found { continue } m[c.Target] = c } return m, nil } func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) { mounts := map[string]mount.Mount{} configsBaseDir := "/" for _, config := range s.Configs { target := config.Target if config.Target == "" { target = configsBaseDir + config.Source } else if !isAbsTarget(config.Target) { target = configsBaseDir + config.Target } definedConfig := p.Configs[config.Source] if definedConfig.External { return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name) } if definedConfig.Driver != "" { return nil, errors.New("Docker Compose does not support configs.*.driver") //nolint:staticcheck } if definedConfig.TemplateDriver != "" { return nil, errors.New("Docker Compose does not support configs.*.template_driver") //nolint:staticcheck } if definedConfig.Environment != "" || definedConfig.Content != "" { continue } if config.UID != "" || config.GID != "" || config.Mode != nil { logrus.Warn("config `uid`, `gid` and `mode` are not supported, they will be ignored") } bindMount, err := buildMount(p, types.ServiceVolumeConfig{ Type: types.VolumeTypeBind, Source: definedConfig.File, Target: target, ReadOnly: true, }) if err != nil { return nil, err } mounts[target] = bindMount } values := make([]mount.Mount, 0, len(mounts)) for _, v := range mounts { values = append(values, v) } return values, nil } func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) { mounts := map[string]mount.Mount{} secretsDir := "/run/secrets/" for _, secret := range s.Secrets { target := secret.Target if secret.Target == "" { target = secretsDir + secret.Source } else if !isAbsTarget(secret.Target) { target = secretsDir + secret.Target } definedSecret := p.Secrets[secret.Source] if definedSecret.External { return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name) } if definedSecret.Driver != "" {
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
true
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/envresolver.go
pkg/compose/envresolver.go
/* 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 ( "runtime" "strings" ) // isCaseInsensitiveEnvVars is true on platforms where environment variable names are treated case-insensitively. var isCaseInsensitiveEnvVars = (runtime.GOOS == "windows") // envResolver returns resolver for environment variables suitable for the current platform. // Expected to be used with `MappingWithEquals.Resolve`. // Updates in `environment` may not be reflected. func envResolver(environment map[string]string) func(string) (string, bool) { return envResolverWithCase(environment, isCaseInsensitiveEnvVars) } // envResolverWithCase returns resolver for environment variables with the specified case-sensitive condition. // Expected to be used with `MappingWithEquals.Resolve`. // Updates in `environment` may not be reflected. func envResolverWithCase(environment map[string]string, caseInsensitive bool) func(string) (string, bool) { if environment == nil { return func(s string) (string, bool) { return "", false } } if !caseInsensitive { return func(s string) (string, bool) { v, ok := environment[s] return v, ok } } // variable names must be treated case-insensitively. // Resolves in this way: // * Return the value if its name matches with the passed name case-sensitively. // * Otherwise, return the value if its lower-cased name matches lower-cased passed name. // * The value is indefinite if multiple variable matches. loweredEnvironment := make(map[string]string, len(environment)) for k, v := range environment { loweredEnvironment[strings.ToLower(k)] = v } return func(s string) (string, bool) { v, ok := environment[s] if ok { return v, ok } v, ok = loweredEnvironment[strings.ToLower(s)] return v, ok } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/stop_test.go
pkg/compose/stop_test.go
/* 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" "strings" "testing" "time" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/volume" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" compose "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) func TestStopTimeout(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) ctx := context.Background() api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(false)).Return( []container.Summary{ testContainer("service1", "123", false), testContainer("service1", "456", false), testContainer("service2", "789", false), }, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{}, nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return([]network.Summary{}, nil) timeout := 2 * time.Second stopConfig := container.StopOptions{Timeout: utils.DurationSecondToInt(&timeout)} api.EXPECT().ContainerStop(gomock.Any(), "123", stopConfig).Return(nil) api.EXPECT().ContainerStop(gomock.Any(), "456", stopConfig).Return(nil) api.EXPECT().ContainerStop(gomock.Any(), "789", stopConfig).Return(nil) err = tested.Stop(ctx, strings.ToLower(testProject), compose.StopOptions{ Timeout: &timeout, }) assert.NilError(t, err) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/ls.go
pkg/compose/ls.go
/* 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" "fmt" "slices" "sort" "strings" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/sirupsen/logrus" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) List(ctx context.Context, opts api.ListOptions) ([]api.Stack, error) { list, err := s.apiClient().ContainerList(ctx, container.ListOptions{ Filters: filters.NewArgs(hasProjectLabelFilter(), hasConfigHashLabel()), All: opts.All, }) if err != nil { return nil, err } return containersToStacks(list) } func containersToStacks(containers []container.Summary) ([]api.Stack, error) { containersByLabel, keys, err := groupContainerByLabel(containers, api.ProjectLabel) if err != nil { return nil, err } var projects []api.Stack for _, project := range keys { configFiles, err := combinedConfigFiles(containersByLabel[project]) if err != nil { logrus.Warn(err.Error()) configFiles = "N/A" } projects = append(projects, api.Stack{ ID: project, Name: project, Status: combinedStatus(containerToState(containersByLabel[project])), ConfigFiles: configFiles, }) } return projects, nil } func combinedConfigFiles(containers []container.Summary) (string, error) { configFiles := []string{} for _, c := range containers { files, ok := c.Labels[api.ConfigFilesLabel] if !ok { return "", fmt.Errorf("no label %q set on container %q of compose project", api.ConfigFilesLabel, c.ID) } for f := range strings.SplitSeq(files, ",") { if !slices.Contains(configFiles, f) { configFiles = append(configFiles, f) } } } return strings.Join(configFiles, ","), nil } func containerToState(containers []container.Summary) []string { statuses := []string{} for _, c := range containers { statuses = append(statuses, c.State) } return statuses } func combinedStatus(statuses []string) string { nbByStatus := map[string]int{} keys := []string{} for _, status := range statuses { nb, ok := nbByStatus[status] if !ok { nb = 0 keys = append(keys, status) } nbByStatus[status] = nb + 1 } sort.Strings(keys) result := "" for _, status := range keys { nb := nbByStatus[status] if result != "" { result += ", " } result += fmt.Sprintf("%s(%d)", status, nb) } return result } func groupContainerByLabel(containers []container.Summary, labelName string) (map[string][]container.Summary, []string, error) { containersByLabel := map[string][]container.Summary{} keys := []string{} for _, c := range containers { label, ok := c.Labels[labelName] if !ok { return nil, nil, fmt.Errorf("no label %q set on container %q of compose project", labelName, c.ID) } labelContainers, ok := containersByLabel[label] if !ok { labelContainers = []container.Summary{} keys = append(keys, label) } labelContainers = append(labelContainers, c) containersByLabel[label] = labelContainers } sort.Strings(keys) return containersByLabel, keys, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/progress.go
pkg/compose/progress.go
/* 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" "fmt" "github.com/docker/compose/v5/pkg/api" ) type progressFunc func(context.Context) error func Run(ctx context.Context, pf progressFunc, operation string, bus api.EventProcessor) error { bus.Start(ctx, operation) err := pf(ctx) bus.Done(operation, err != nil) return err } // errorEvent creates a new Error Resource with message func errorEvent(id string, msg string) api.Resource { return api.Resource{ ID: id, Status: api.Error, Text: api.StatusError, Details: msg, } } // errorEventf creates a new Error Resource with format message func errorEventf(id string, msg string, args ...any) api.Resource { return errorEvent(id, fmt.Sprintf(msg, args...)) } // creatingEvent creates a new Create in progress Resource func creatingEvent(id string) api.Resource { return newEvent(id, api.Working, api.StatusCreating) } // startingEvent creates a new Starting in progress Resource func startingEvent(id string) api.Resource { return newEvent(id, api.Working, api.StatusStarting) } // startedEvent creates a new Started in progress Resource func startedEvent(id string) api.Resource { return newEvent(id, api.Done, api.StatusStarted) } // waiting creates a new waiting event func waiting(id string) api.Resource { return newEvent(id, api.Working, api.StatusWaiting) } // healthy creates a new healthy event func healthy(id string) api.Resource { return newEvent(id, api.Done, api.StatusHealthy) } // exited creates a new exited event func exited(id string) api.Resource { return newEvent(id, api.Done, api.StatusExited) } // restartingEvent creates a new Restarting in progress Resource func restartingEvent(id string) api.Resource { return newEvent(id, api.Working, api.StatusRestarting) } // runningEvent creates a new Running in progress Resource func runningEvent(id string) api.Resource { return newEvent(id, api.Done, api.StatusRunning) } // createdEvent creates a new Created (done) Resource func createdEvent(id string) api.Resource { return newEvent(id, api.Done, api.StatusCreated) } // stoppingEvent creates a new Stopping in progress Resource func stoppingEvent(id string) api.Resource { return newEvent(id, api.Working, api.StatusStopping) } // stoppedEvent creates a new Stopping in progress Resource func stoppedEvent(id string) api.Resource { return newEvent(id, api.Done, api.StatusStopped) } // killingEvent creates a new Killing in progress Resource func killingEvent(id string) api.Resource { return newEvent(id, api.Working, api.StatusKilling) } // killedEvent creates a new Killed in progress Resource func killedEvent(id string) api.Resource { return newEvent(id, api.Done, api.StatusKilled) } // removingEvent creates a new Removing in progress Resource func removingEvent(id string) api.Resource { return newEvent(id, api.Working, api.StatusRemoving) } // removedEvent creates a new removed (done) Resource func removedEvent(id string) api.Resource { return newEvent(id, api.Done, api.StatusRemoved) } // buildingEvent creates a new Building in progress Resource func buildingEvent(id string) api.Resource { return newEvent("Image "+id, api.Working, api.StatusBuilding) } // builtEvent creates a new built (done) Resource func builtEvent(id string) api.Resource { return newEvent("Image "+id, api.Done, api.StatusBuilt) } // pullingEvent creates a new pulling (in progress) Resource func pullingEvent(id string) api.Resource { return newEvent("Image "+id, api.Working, api.StatusPulling) } // pulledEvent creates a new pulled (done) Resource func pulledEvent(id string) api.Resource { return newEvent("Image "+id, api.Done, api.StatusPulled) } // skippedEvent creates a new Skipped Resource func skippedEvent(id string, reason string) api.Resource { return api.Resource{ ID: id, Status: api.Warning, Text: "Skipped: " + reason, } } // newEvent new event func newEvent(id string, status api.EventStatus, text string, reason ...string) api.Resource { r := api.Resource{ ID: id, Status: status, Text: text, } if len(reason) > 0 { r.Details = reason[0] } return r } type ignore struct{} func (q *ignore) Start(_ context.Context, _ string) { } func (q *ignore) Done(_ string, _ bool) { } func (q *ignore) On(_ ...api.Resource) { }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/build_classic.go
pkg/compose/build_classic.go
/* 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" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command/image/build" buildtypes "github.com/docker/docker/api/types/build" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/progress" "github.com/docker/docker/pkg/streamformatter" "github.com/moby/go-archive" "github.com/sirupsen/logrus" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) doBuildClassic(ctx context.Context, project *types.Project, serviceToBuild types.Services, options api.BuildOptions) (map[string]string, error) { imageIDs := map[string]string{} // Not using bake, additional_context: service:xx is implemented by building images in dependency order project, err := project.WithServicesTransform(func(serviceName string, service types.ServiceConfig) (types.ServiceConfig, error) { if service.Build != nil { for _, c := range service.Build.AdditionalContexts { if t, found := strings.CutPrefix(c, types.ServicePrefix); found { if service.DependsOn == nil { service.DependsOn = map[string]types.ServiceDependency{} } service.DependsOn[t] = types.ServiceDependency{ Condition: "build", // non-canonical, but will force dependency graph ordering } } } } return service, nil }) if err != nil { return imageIDs, err } // we use a pre-allocated []string to collect build digest by service index while running concurrent goroutines builtDigests := make([]string, len(project.Services)) names := project.ServiceNames() getServiceIndex := func(name string) int { for idx, n := range names { if n == name { return idx } } return -1 } err = InDependencyOrder(ctx, project, func(ctx context.Context, name string) error { trace.SpanFromContext(ctx).SetAttributes(attribute.String("builder", "classic")) service, ok := serviceToBuild[name] if !ok { return nil } image := api.GetImageNameOrDefault(service, project.Name) s.events.On(buildingEvent(image)) id, err := s.doBuildImage(ctx, project, service, options) if err != nil { return err } s.events.On(builtEvent(image)) builtDigests[getServiceIndex(name)] = id if options.Push { return s.push(ctx, project, api.PushOptions{}) } return nil }, func(traversal *graphTraversal) { traversal.maxConcurrency = s.maxConcurrency }) if err != nil { return nil, err } for i, imageDigest := range builtDigests { if imageDigest != "" { service := project.Services[names[i]] imageRef := api.GetImageNameOrDefault(service, project.Name) imageIDs[imageRef] = imageDigest } } return imageIDs, err } //nolint:gocyclo func (s *composeService) doBuildImage(ctx context.Context, project *types.Project, service types.ServiceConfig, options api.BuildOptions) (string, error) { var ( buildCtx io.ReadCloser dockerfileCtx io.ReadCloser contextDir string relDockerfile string ) if len(service.Build.Platforms) > 1 { return "", fmt.Errorf("the classic builder doesn't support multi-arch build, set DOCKER_BUILDKIT=1 to use BuildKit") } if service.Build.Privileged { return "", fmt.Errorf("the classic builder doesn't support privileged mode, set DOCKER_BUILDKIT=1 to use BuildKit") } if len(service.Build.AdditionalContexts) > 0 { return "", fmt.Errorf("the classic builder doesn't support additional contexts, set DOCKER_BUILDKIT=1 to use BuildKit") } if len(service.Build.SSH) > 0 { return "", fmt.Errorf("the classic builder doesn't support SSH keys, set DOCKER_BUILDKIT=1 to use BuildKit") } if len(service.Build.Secrets) > 0 { return "", fmt.Errorf("the classic builder doesn't support secrets, set DOCKER_BUILDKIT=1 to use BuildKit") } if service.Build.Labels == nil { service.Build.Labels = make(map[string]string) } service.Build.Labels[api.ImageBuilderLabel] = "classic" dockerfileName := dockerFilePath(service.Build.Context, service.Build.Dockerfile) specifiedContext := service.Build.Context progBuff := s.stdout() buildBuff := s.stdout() contextType, err := build.DetectContextType(specifiedContext) if err != nil { return "", err } switch contextType { case build.ContextTypeStdin: return "", fmt.Errorf("building from STDIN is not supported") case build.ContextTypeLocal: contextDir, relDockerfile, err = build.GetContextFromLocalDir(specifiedContext, dockerfileName) if err != nil { return "", fmt.Errorf("unable to prepare context: %w", err) } if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) { // Dockerfile is outside build-context; read the Dockerfile and pass it as dockerfileCtx dockerfileCtx, err = os.Open(dockerfileName) if err != nil { return "", fmt.Errorf("unable to open Dockerfile: %w", err) } defer dockerfileCtx.Close() //nolint:errcheck } case build.ContextTypeGit: var tempDir string tempDir, relDockerfile, err = build.GetContextFromGitURL(specifiedContext, dockerfileName) if err != nil { return "", fmt.Errorf("unable to prepare context: %w", err) } defer func() { _ = os.RemoveAll(tempDir) }() contextDir = tempDir case build.ContextTypeRemote: buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, dockerfileName) if err != nil { return "", fmt.Errorf("unable to prepare context: %w", err) } default: return "", fmt.Errorf("unable to prepare context: path %q not found", specifiedContext) } // read from a directory into tar archive if buildCtx == nil { excludes, err := build.ReadDockerignore(contextDir) if err != nil { return "", err } if err := build.ValidateContextDirectory(contextDir, excludes); err != nil { return "", fmt.Errorf("checking context: %w", err) } // And canonicalize dockerfile name to a platform-independent one relDockerfile = filepath.ToSlash(relDockerfile) excludes = build.TrimBuildFilesFromExcludes(excludes, relDockerfile, false) buildCtx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{ ExcludePatterns: excludes, ChownOpts: &archive.ChownOpts{UID: 0, GID: 0}, }) if err != nil { return "", err } } // replace Dockerfile if it was added from stdin or a file outside the build-context, and there is archive context if dockerfileCtx != nil && buildCtx != nil { buildCtx, relDockerfile, err = build.AddDockerfileToBuildContext(dockerfileCtx, buildCtx) if err != nil { return "", err } } buildCtx, err = build.Compress(buildCtx) if err != nil { return "", err } // Setup an upload progress bar progressOutput := streamformatter.NewProgressOutput(progBuff) body := progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon") configFile := s.configFile() creds, err := configFile.GetAllCredentials() if err != nil { return "", err } authConfigs := make(map[string]registry.AuthConfig, len(creds)) for k, authConfig := range creds { authConfigs[k] = registry.AuthConfig{ Username: authConfig.Username, Password: authConfig.Password, ServerAddress: authConfig.ServerAddress, // TODO(thaJeztah): Are these expected to be included? See https://github.com/docker/cli/pull/6516#discussion_r2387586472 Auth: authConfig.Auth, IdentityToken: authConfig.IdentityToken, RegistryToken: authConfig.RegistryToken, } } buildOpts := imageBuildOptions(s.getProxyConfig(), project, service, options) imageName := api.GetImageNameOrDefault(service, project.Name) buildOpts.Tags = append(buildOpts.Tags, imageName) buildOpts.Dockerfile = relDockerfile buildOpts.AuthConfigs = authConfigs buildOpts.Memory = options.Memory ctx, cancel := context.WithCancel(ctx) defer cancel() s.events.On(buildingEvent(imageName)) response, err := s.apiClient().ImageBuild(ctx, body, buildOpts) if err != nil { return "", err } defer response.Body.Close() //nolint:errcheck imageID := "" aux := func(msg jsonmessage.JSONMessage) { var result buildtypes.Result if err := json.Unmarshal(*msg.Aux, &result); err != nil { logrus.Errorf("Failed to parse aux message: %s", err) } else { imageID = result.ID } } err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, progBuff.FD(), true, aux) if err != nil { var jerr *jsonmessage.JSONError if errors.As(err, &jerr) { // If no error code is set, default to 1 if jerr.Code == 0 { jerr.Code = 1 } return "", cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code} } return "", err } s.events.On(builtEvent(imageName)) return imageID, nil } func imageBuildOptions(proxyConfigs map[string]string, project *types.Project, service types.ServiceConfig, options api.BuildOptions) buildtypes.ImageBuildOptions { config := service.Build return buildtypes.ImageBuildOptions{ Version: buildtypes.BuilderV1, Tags: config.Tags, NoCache: config.NoCache, Remove: true, PullParent: config.Pull, BuildArgs: resolveAndMergeBuildArgs(proxyConfigs, project, service, options), Labels: config.Labels, NetworkMode: config.Network, ExtraHosts: config.ExtraHosts.AsList(":"), Target: config.Target, Isolation: container.Isolation(config.Isolation), } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/container.go
pkg/compose/container.go
/* 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 ( "io" moby "github.com/docker/docker/api/types" ) var _ io.ReadCloser = ContainerStdout{} // ContainerStdout implement ReadCloser for moby.HijackedResponse type ContainerStdout struct { moby.HijackedResponse } // Read implement io.ReadCloser func (l ContainerStdout) Read(p []byte) (n int, err error) { return l.Reader.Read(p) } // Close implement io.ReadCloser func (l ContainerStdout) Close() error { l.HijackedResponse.Close() return nil } var _ io.WriteCloser = ContainerStdin{} // ContainerStdin implement WriteCloser for moby.HijackedResponse type ContainerStdin struct { moby.HijackedResponse } // Write implement io.WriteCloser func (c ContainerStdin) Write(p []byte) (n int, err error) { return c.Conn.Write(p) } // Close implement io.WriteCloser func (c ContainerStdin) Close() error { return c.CloseWrite() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/ps_test.go
pkg/compose/ps_test.go
/* 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" "strings" "testing" containerType "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" compose "github.com/docker/compose/v5/pkg/api" ) func TestPs(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) ctx := context.Background() args := filters.NewArgs(projectFilter(strings.ToLower(testProject)), hasConfigHashLabel()) args.Add("label", "com.docker.compose.oneoff=False") listOpts := containerType.ListOptions{Filters: args, All: false} c1, inspect1 := containerDetails("service1", "123", containerType.StateRunning, containerType.Healthy, 0) c2, inspect2 := containerDetails("service1", "456", containerType.StateRunning, "", 0) c2.Ports = []containerType.Port{{PublicPort: 80, PrivatePort: 90, IP: "localhost"}} c3, inspect3 := containerDetails("service2", "789", containerType.StateExited, "", 130) api.EXPECT().ContainerList(ctx, listOpts).Return([]containerType.Summary{c1, c2, c3}, nil) api.EXPECT().ContainerInspect(anyCancellableContext(), "123").Return(inspect1, nil) api.EXPECT().ContainerInspect(anyCancellableContext(), "456").Return(inspect2, nil) api.EXPECT().ContainerInspect(anyCancellableContext(), "789").Return(inspect3, nil) containers, err := tested.Ps(ctx, strings.ToLower(testProject), compose.PsOptions{}) expected := []compose.ContainerSummary{ { ID: "123", Name: "123", Names: []string{"/123"}, Image: "foo", Project: strings.ToLower(testProject), Service: "service1", State: containerType.StateRunning, Health: containerType.Healthy, Publishers: []compose.PortPublisher{}, Labels: map[string]string{ compose.ProjectLabel: strings.ToLower(testProject), compose.ConfigFilesLabel: "/src/pkg/compose/testdata/compose.yaml", compose.WorkingDirLabel: "/src/pkg/compose/testdata", compose.ServiceLabel: "service1", }, }, { ID: "456", Name: "456", Names: []string{"/456"}, Image: "foo", Project: strings.ToLower(testProject), Service: "service1", State: containerType.StateRunning, Health: "", Publishers: []compose.PortPublisher{{URL: "localhost", TargetPort: 90, PublishedPort: 80}}, Labels: map[string]string{ compose.ProjectLabel: strings.ToLower(testProject), compose.ConfigFilesLabel: "/src/pkg/compose/testdata/compose.yaml", compose.WorkingDirLabel: "/src/pkg/compose/testdata", compose.ServiceLabel: "service1", }, }, { ID: "789", Name: "789", Names: []string{"/789"}, Image: "foo", Project: strings.ToLower(testProject), Service: "service2", State: containerType.StateExited, Health: "", ExitCode: 130, Publishers: []compose.PortPublisher{}, Labels: map[string]string{ compose.ProjectLabel: strings.ToLower(testProject), compose.ConfigFilesLabel: "/src/pkg/compose/testdata/compose.yaml", compose.WorkingDirLabel: "/src/pkg/compose/testdata", compose.ServiceLabel: "service2", }, }, } assert.NilError(t, err) assert.DeepEqual(t, containers, expected) } func containerDetails(service string, id string, status containerType.ContainerState, health containerType.HealthStatus, exitCode int) (containerType.Summary, containerType.InspectResponse) { ctr := containerType.Summary{ ID: id, Names: []string{"/" + id}, Image: "foo", Labels: containerLabels(service, false), State: status, } inspect := containerType.InspectResponse{ ContainerJSONBase: &containerType.ContainerJSONBase{ State: &containerType.State{ Status: status, Health: &containerType.Health{Status: health}, ExitCode: exitCode, }, }, } return ctr, inspect }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/kill.go
pkg/compose/kill.go
/* 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" "strings" "github.com/docker/docker/api/types/container" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Kill(ctx context.Context, projectName string, options api.KillOptions) error { return Run(ctx, func(ctx context.Context) error { return s.kill(ctx, strings.ToLower(projectName), options) }, "kill", s.events) } func (s *composeService) kill(ctx context.Context, projectName string, options api.KillOptions) error { services := options.Services var containers Containers containers, err := s.getContainers(ctx, projectName, oneOffInclude, options.All, services...) if err != nil { return err } project := options.Project if project == nil { project, err = s.getProjectWithResources(ctx, containers, projectName) if err != nil { return err } } if !options.RemoveOrphans { containers = containers.filter(isService(project.ServiceNames()...)) } if len(containers) == 0 { return api.ErrNoResources } eg, ctx := errgroup.WithContext(ctx) containers.forEach(func(ctr container.Summary) { eg.Go(func() error { eventName := getContainerProgressName(ctr) s.events.On(killingEvent(eventName)) err := s.apiClient().ContainerKill(ctx, ctr.ID, options.Signal) if err != nil { s.events.On(errorEvent(eventName, "Error while Killing")) return err } s.events.On(killedEvent(eventName)) return nil }) }) return eg.Wait() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/down_test.go
pkg/compose/down_test.go
/* 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" "fmt" "os" "strings" "testing" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" "github.com/docker/cli/cli/streams" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/volume" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" compose "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/mocks" ) func TestDown(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(false)).Return( []container.Summary{ testContainer("service1", "123", false), testContainer("service2", "456", false), testContainer("service2", "789", false), testContainer("service_orphan", "321", true), }, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{}, nil) // network names are not guaranteed to be unique, ensure Compose handles // cleanup properly if duplicates are inadvertently created api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return([]network.Summary{ {ID: "abc123", Name: "myProject_default", Labels: map[string]string{compose.NetworkLabel: "default"}}, {ID: "def456", Name: "myProject_default", Labels: map[string]string{compose.NetworkLabel: "default"}}, }, nil) stopOptions := container.StopOptions{} api.EXPECT().ContainerStop(gomock.Any(), "123", stopOptions).Return(nil) api.EXPECT().ContainerStop(gomock.Any(), "456", stopOptions).Return(nil) api.EXPECT().ContainerStop(gomock.Any(), "789", stopOptions).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "123", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "456", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "789", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{ Filters: filters.NewArgs( projectFilter(strings.ToLower(testProject)), networkFilter("default")), }).Return([]network.Summary{ {ID: "abc123", Name: "myProject_default"}, {ID: "def456", Name: "myProject_default"}, }, nil) api.EXPECT().NetworkInspect(gomock.Any(), "abc123", gomock.Any()).Return(network.Inspect{ID: "abc123"}, nil) api.EXPECT().NetworkInspect(gomock.Any(), "def456", gomock.Any()).Return(network.Inspect{ID: "def456"}, nil) api.EXPECT().NetworkRemove(gomock.Any(), "abc123").Return(nil) api.EXPECT().NetworkRemove(gomock.Any(), "def456").Return(nil) err = tested.Down(context.Background(), strings.ToLower(testProject), compose.DownOptions{}) assert.NilError(t, err) } func TestDownWithGivenServices(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(false)).Return( []container.Summary{ testContainer("service1", "123", false), testContainer("service2", "456", false), testContainer("service2", "789", false), testContainer("service_orphan", "321", true), }, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{}, nil) // network names are not guaranteed to be unique, ensure Compose handles // cleanup properly if duplicates are inadvertently created api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return([]network.Summary{ {ID: "abc123", Name: "myProject_default", Labels: map[string]string{compose.NetworkLabel: "default"}}, {ID: "def456", Name: "myProject_default", Labels: map[string]string{compose.NetworkLabel: "default"}}, }, nil) stopOptions := container.StopOptions{} api.EXPECT().ContainerStop(gomock.Any(), "123", stopOptions).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "123", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{ Filters: filters.NewArgs( projectFilter(strings.ToLower(testProject)), networkFilter("default")), }).Return([]network.Summary{ {ID: "abc123", Name: "myProject_default"}, }, nil) api.EXPECT().NetworkInspect(gomock.Any(), "abc123", gomock.Any()).Return(network.Inspect{ID: "abc123"}, nil) api.EXPECT().NetworkRemove(gomock.Any(), "abc123").Return(nil) err = tested.Down(context.Background(), strings.ToLower(testProject), compose.DownOptions{ Services: []string{"service1", "not-running-service"}, }) assert.NilError(t, err) } func TestDownWithSpecifiedServiceButTheServicesAreNotRunning(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(false)).Return( []container.Summary{ testContainer("service1", "123", false), testContainer("service2", "456", false), testContainer("service2", "789", false), testContainer("service_orphan", "321", true), }, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{}, nil) // network names are not guaranteed to be unique, ensure Compose handles // cleanup properly if duplicates are inadvertently created api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return([]network.Summary{ {ID: "abc123", Name: "myProject_default", Labels: map[string]string{compose.NetworkLabel: "default"}}, {ID: "def456", Name: "myProject_default", Labels: map[string]string{compose.NetworkLabel: "default"}}, }, nil) err = tested.Down(context.Background(), strings.ToLower(testProject), compose.DownOptions{ Services: []string{"not-running-service1", "not-running-service2"}, }) assert.NilError(t, err) } func TestDownRemoveOrphans(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(true)).Return( []container.Summary{ testContainer("service1", "123", false), testContainer("service2", "789", false), testContainer("service_orphan", "321", true), }, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{}, nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return([]network.Summary{ { Name: "myProject_default", Labels: map[string]string{compose.NetworkLabel: "default"}, }, }, nil) stopOptions := container.StopOptions{} api.EXPECT().ContainerStop(gomock.Any(), "123", stopOptions).Return(nil) api.EXPECT().ContainerStop(gomock.Any(), "789", stopOptions).Return(nil) api.EXPECT().ContainerStop(gomock.Any(), "321", stopOptions).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "123", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "789", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "321", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{ Filters: filters.NewArgs( networkFilter("default"), projectFilter(strings.ToLower(testProject)), ), }).Return([]network.Summary{{ID: "abc123", Name: "myProject_default"}}, nil) api.EXPECT().NetworkInspect(gomock.Any(), "abc123", gomock.Any()).Return(network.Inspect{ID: "abc123"}, nil) api.EXPECT().NetworkRemove(gomock.Any(), "abc123").Return(nil) err = tested.Down(context.Background(), strings.ToLower(testProject), compose.DownOptions{RemoveOrphans: true}) assert.NilError(t, err) } func TestDownRemoveVolumes(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(false)).Return( []container.Summary{testContainer("service1", "123", false)}, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{ Volumes: []*volume.Volume{{Name: "myProject_volume"}}, }, nil) api.EXPECT().VolumeInspect(gomock.Any(), "myProject_volume"). Return(volume.Volume{}, nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return(nil, nil) api.EXPECT().ContainerStop(gomock.Any(), "123", container.StopOptions{}).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "123", container.RemoveOptions{Force: true, RemoveVolumes: true}).Return(nil) api.EXPECT().VolumeRemove(gomock.Any(), "myProject_volume", true).Return(nil) err = tested.Down(context.Background(), strings.ToLower(testProject), compose.DownOptions{Volumes: true}) assert.NilError(t, err) } func TestDownRemoveImages(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() opts := compose.DownOptions{ Project: &types.Project{ Name: strings.ToLower(testProject), Services: types.Services{ "local-anonymous": {Name: "local-anonymous"}, "local-named": {Name: "local-named", Image: "local-named-image"}, "remote": {Name: "remote", Image: "remote-image"}, "remote-tagged": {Name: "remote-tagged", Image: "registry.example.com/remote-image-tagged:v1.0"}, "no-images-anonymous": {Name: "no-images-anonymous"}, "no-images-named": {Name: "no-images-named", Image: "missing-named-image"}, }, }, } api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(false)). Return([]container.Summary{ testContainer("service1", "123", false), }, nil). AnyTimes() api.EXPECT().ImageList(gomock.Any(), image.ListOptions{ Filters: filters.NewArgs( projectFilter(strings.ToLower(testProject)), filters.Arg("dangling", "false"), ), }).Return([]image.Summary{ { Labels: types.Labels{compose.ServiceLabel: "local-anonymous"}, RepoTags: []string{"testproject-local-anonymous:latest"}, }, { Labels: types.Labels{compose.ServiceLabel: "local-named"}, RepoTags: []string{"local-named-image:latest"}, }, }, nil).AnyTimes() imagesToBeInspected := map[string]bool{ "testproject-local-anonymous": true, "local-named-image": true, "remote-image": true, "testproject-no-images-anonymous": false, "missing-named-image": false, } for img, exists := range imagesToBeInspected { var resp image.InspectResponse var err error if exists { resp.RepoTags = []string{img} } else { err = errdefs.ErrNotFound.WithMessage(fmt.Sprintf("test specified that image %q should not exist", img)) } api.EXPECT().ImageInspect(gomock.Any(), img). Return(resp, err). AnyTimes() } api.EXPECT().ImageInspect(gomock.Any(), "registry.example.com/remote-image-tagged:v1.0"). Return(image.InspectResponse{RepoTags: []string{"registry.example.com/remote-image-tagged:v1.0"}}, nil). AnyTimes() localImagesToBeRemoved := []string{ "testproject-local-anonymous:latest", "local-named-image:latest", } for _, img := range localImagesToBeRemoved { // test calls down --rmi=local then down --rmi=all, so local images // get "removed" 2x, while other images are only 1x api.EXPECT().ImageRemove(gomock.Any(), img, image.RemoveOptions{}). Return(nil, nil). Times(2) } t.Log("-> docker compose down --rmi=local") opts.Images = "local" err = tested.Down(context.Background(), strings.ToLower(testProject), opts) assert.NilError(t, err) otherImagesToBeRemoved := []string{ "remote-image:latest", "registry.example.com/remote-image-tagged:v1.0", } for _, img := range otherImagesToBeRemoved { api.EXPECT().ImageRemove(gomock.Any(), img, image.RemoveOptions{}). Return(nil, nil). Times(1) } t.Log("-> docker compose down --rmi=all") opts.Images = "all" err = tested.Down(context.Background(), strings.ToLower(testProject), opts) assert.NilError(t, err) } func TestDownRemoveImages_NoLabel(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) ctr := testContainer("service1", "123", false) api.EXPECT().ContainerList(gomock.Any(), projectFilterListOpt(false)).Return( []container.Summary{ctr}, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{ Volumes: []*volume.Volume{{Name: "myProject_volume"}}, }, nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return(nil, nil) // ImageList returns no images for the project since they were unlabeled // (created by an older version of Compose) api.EXPECT().ImageList(gomock.Any(), image.ListOptions{ Filters: filters.NewArgs( projectFilter(strings.ToLower(testProject)), filters.Arg("dangling", "false"), ), }).Return(nil, nil) api.EXPECT().ImageInspect(gomock.Any(), "testproject-service1"). Return(image.InspectResponse{}, nil) api.EXPECT().ContainerStop(gomock.Any(), "123", container.StopOptions{}).Return(nil) api.EXPECT().ContainerRemove(gomock.Any(), "123", container.RemoveOptions{Force: true}).Return(nil) api.EXPECT().ImageRemove(gomock.Any(), "testproject-service1:latest", image.RemoveOptions{}).Return(nil, nil) err = tested.Down(context.Background(), strings.ToLower(testProject), compose.DownOptions{Images: "local"}) assert.NilError(t, err) } func prepareMocks(mockCtrl *gomock.Controller) (*mocks.MockAPIClient, *mocks.MockCli) { api := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) cli.EXPECT().Client().Return(api).AnyTimes() cli.EXPECT().Err().Return(streams.NewOut(os.Stderr)).AnyTimes() cli.EXPECT().Out().Return(streams.NewOut(os.Stdout)).AnyTimes() return api, cli }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/kill_test.go
pkg/compose/kill_test.go
/* 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" "fmt" "path/filepath" "strings" "testing" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/volume" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" compose "github.com/docker/compose/v5/pkg/api" ) const testProject = "testProject" func TestKillAll(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) name := strings.ToLower(testProject) ctx := context.Background() api.EXPECT().ContainerList(ctx, container.ListOptions{ Filters: filters.NewArgs(projectFilter(name), hasConfigHashLabel()), }).Return( []container.Summary{testContainer("service1", "123", false), testContainer("service1", "456", false), testContainer("service2", "789", false)}, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{}, nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return([]network.Summary{ {ID: "abc123", Name: "testProject_default"}, }, nil) api.EXPECT().ContainerKill(anyCancellableContext(), "123", "").Return(nil) api.EXPECT().ContainerKill(anyCancellableContext(), "456", "").Return(nil) api.EXPECT().ContainerKill(anyCancellableContext(), "789", "").Return(nil) err = tested.Kill(ctx, name, compose.KillOptions{}) assert.NilError(t, err) } func TestKillSignal(t *testing.T) { const serviceName = "service1" mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) name := strings.ToLower(testProject) listOptions := container.ListOptions{ Filters: filters.NewArgs(projectFilter(name), serviceFilter(serviceName), hasConfigHashLabel()), } ctx := context.Background() api.EXPECT().ContainerList(ctx, listOptions).Return([]container.Summary{testContainer(serviceName, "123", false)}, nil) api.EXPECT().VolumeList( gomock.Any(), volume.ListOptions{ Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject))), }). Return(volume.ListResponse{}, nil) api.EXPECT().NetworkList(gomock.Any(), network.ListOptions{Filters: filters.NewArgs(projectFilter(strings.ToLower(testProject)))}). Return([]network.Summary{ {ID: "abc123", Name: "testProject_default"}, }, nil) api.EXPECT().ContainerKill(anyCancellableContext(), "123", "SIGTERM").Return(nil) err = tested.Kill(ctx, name, compose.KillOptions{Services: []string{serviceName}, Signal: "SIGTERM"}) assert.NilError(t, err) } func testContainer(service string, id string, oneOff bool) container.Summary { // canonical docker names in the API start with a leading slash, some // parts of Compose code will attempt to strip this off, so make sure // it's consistently present name := "/" + strings.TrimPrefix(id, "/") return container.Summary{ ID: id, Names: []string{name}, Labels: containerLabels(service, oneOff), State: container.StateExited, } } func containerLabels(service string, oneOff bool) map[string]string { workingdir := "/src/pkg/compose/testdata" composefile := filepath.Join(workingdir, "compose.yaml") labels := map[string]string{ compose.ServiceLabel: service, compose.ConfigFilesLabel: composefile, compose.WorkingDirLabel: workingdir, compose.ProjectLabel: strings.ToLower(testProject), } if oneOff { labels[compose.OneoffLabel] = "True" } return labels } func anyCancellableContext() gomock.Matcher { ctxWithCancel, cancel := context.WithCancel(context.Background()) cancel() return gomock.AssignableToTypeOf(ctxWithCancel) } func projectFilterListOpt(withOneOff bool) container.ListOptions { filter := filters.NewArgs( projectFilter(strings.ToLower(testProject)), hasConfigHashLabel(), ) if !withOneOff { filter.Add("label", fmt.Sprintf("%s=False", compose.OneoffLabel)) } return container.ListOptions{ Filters: filter, All: true, } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/wait.go
pkg/compose/wait.go
/* 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" "fmt" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Wait(ctx context.Context, projectName string, options api.WaitOptions) (int64, error) { containers, err := s.getContainers(ctx, projectName, oneOffInclude, false, options.Services...) if err != nil { return 0, err } if len(containers) == 0 { return 0, fmt.Errorf("no containers for project %q", projectName) } eg, waitCtx := errgroup.WithContext(ctx) var statusCode int64 for _, ctr := range containers { eg.Go(func() error { var err error resultC, errC := s.apiClient().ContainerWait(waitCtx, ctr.ID, "") select { case result := <-resultC: _, _ = fmt.Fprintf(s.stdout(), "container %q exited with status code %d\n", ctr.ID, result.StatusCode) statusCode = result.StatusCode case err = <-errC: } return err }) } err = eg.Wait() if err != nil { return 42, err // Ignore abort flag in case of error in wait } if options.DownProjectOnContainerExit { return statusCode, s.Down(ctx, projectName, api.DownOptions{ RemoveOrphans: true, }) } return statusCode, err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/down.go
pkg/compose/down.go
/* 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" "fmt" "strings" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" containerType "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" imageapi "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/network" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) type downOp func() error func (s *composeService) Down(ctx context.Context, projectName string, options api.DownOptions) error { return Run(ctx, func(ctx context.Context) error { return s.down(ctx, strings.ToLower(projectName), options) }, "down", s.events) } func (s *composeService) down(ctx context.Context, projectName string, options api.DownOptions) error { //nolint:gocyclo resourceToRemove := false include := oneOffExclude if options.RemoveOrphans { include = oneOffInclude } containers, err := s.getContainers(ctx, projectName, include, true) if err != nil { return err } project := options.Project if project == nil { project, err = s.getProjectWithResources(ctx, containers, projectName) if err != nil { return err } } // Check requested services exists in model services, err := checkSelectedServices(options, project) if err != nil { return err } if len(options.Services) > 0 && len(services) == 0 { logrus.Infof("Any of the services %v not running in project %q", options.Services, projectName) return nil } options.Services = services if len(containers) > 0 { resourceToRemove = true } err = InReverseDependencyOrder(ctx, project, func(c context.Context, service string) error { serv := project.Services[service] if serv.Provider != nil { return s.runPlugin(ctx, project, serv, "down") } serviceContainers := containers.filter(isService(service)) err := s.removeContainers(ctx, serviceContainers, &serv, options.Timeout, options.Volumes) return err }, WithRootNodesAndDown(options.Services)) if err != nil { return err } orphans := containers.filter(isOrphaned(project)) if options.RemoveOrphans && len(orphans) > 0 { err := s.removeContainers(ctx, orphans, nil, options.Timeout, false) if err != nil { return err } } ops := s.ensureNetworksDown(ctx, project) if options.Images != "" { imgOps, err := s.ensureImagesDown(ctx, project, options) if err != nil { return err } ops = append(ops, imgOps...) } if options.Volumes { ops = append(ops, s.ensureVolumesDown(ctx, project)...) } if !resourceToRemove && len(ops) == 0 { logrus.Warnf("Warning: No resource found to remove for project %q.", projectName) } eg, ctx := errgroup.WithContext(ctx) for _, op := range ops { eg.Go(op) } return eg.Wait() } func checkSelectedServices(options api.DownOptions, project *types.Project) ([]string, error) { var services []string for _, service := range options.Services { _, err := project.GetService(service) if err != nil { if options.Project != nil { // ran with an explicit compose.yaml file, so we should not ignore return nil, err } // ran without an explicit compose.yaml file, so can't distinguish typo vs container already removed } else { services = append(services, service) } } return services, nil } func (s *composeService) ensureVolumesDown(ctx context.Context, project *types.Project) []downOp { var ops []downOp for _, vol := range project.Volumes { if vol.External { continue } volumeName := vol.Name ops = append(ops, func() error { return s.removeVolume(ctx, volumeName) }) } return ops } func (s *composeService) ensureImagesDown(ctx context.Context, project *types.Project, options api.DownOptions) ([]downOp, error) { imagePruner := NewImagePruner(s.apiClient(), project) pruneOpts := ImagePruneOptions{ Mode: ImagePruneMode(options.Images), RemoveOrphans: options.RemoveOrphans, } images, err := imagePruner.ImagesToPrune(ctx, pruneOpts) if err != nil { return nil, err } var ops []downOp for i := range images { img := images[i] ops = append(ops, func() error { return s.removeImage(ctx, img) }) } return ops, nil } func (s *composeService) ensureNetworksDown(ctx context.Context, project *types.Project) []downOp { var ops []downOp for key, n := range project.Networks { if n.External { continue } // loop capture variable for op closure networkKey := key idOrName := n.Name ops = append(ops, func() error { return s.removeNetwork(ctx, networkKey, project.Name, idOrName) }) } return ops } func (s *composeService) removeNetwork(ctx context.Context, composeNetworkName string, projectName string, name string) error { networks, err := s.apiClient().NetworkList(ctx, network.ListOptions{ Filters: filters.NewArgs( projectFilter(projectName), networkFilter(composeNetworkName)), }) if err != nil { return fmt.Errorf("failed to list networks: %w", err) } if len(networks) == 0 { return nil } eventName := fmt.Sprintf("Network %s", name) s.events.On(removingEvent(eventName)) var found int for _, net := range networks { if net.Name != name { continue } nw, err := s.apiClient().NetworkInspect(ctx, net.ID, network.InspectOptions{}) if errdefs.IsNotFound(err) { s.events.On(newEvent(eventName, api.Warning, "No resource found to remove")) return nil } if err != nil { return err } if len(nw.Containers) > 0 { s.events.On(newEvent(eventName, api.Warning, "Resource is still in use")) found++ continue } if err := s.apiClient().NetworkRemove(ctx, net.ID); err != nil { if errdefs.IsNotFound(err) { continue } s.events.On(errorEvent(eventName, err.Error())) return fmt.Errorf("failed to remove network %s: %w", name, err) } s.events.On(removedEvent(eventName)) found++ } if found == 0 { // in practice, it's extremely unlikely for this to ever occur, as it'd // mean the network was present when we queried at the start of this // method but was then deleted by something else in the interim s.events.On(newEvent(eventName, api.Warning, "No resource found to remove")) return nil } return nil } func (s *composeService) removeImage(ctx context.Context, image string) error { id := fmt.Sprintf("Image %s", image) s.events.On(newEvent(id, api.Working, "Removing")) _, err := s.apiClient().ImageRemove(ctx, image, imageapi.RemoveOptions{}) if err == nil { s.events.On(newEvent(id, api.Done, "Removed")) return nil } if errdefs.IsConflict(err) { s.events.On(newEvent(id, api.Warning, "Resource is still in use")) return nil } if errdefs.IsNotFound(err) { s.events.On(newEvent(id, api.Done, "Warning: No resource found to remove")) return nil } return err } func (s *composeService) removeVolume(ctx context.Context, id string) error { resource := fmt.Sprintf("Volume %s", id) _, err := s.apiClient().VolumeInspect(ctx, id) if errdefs.IsNotFound(err) { // Already gone return nil } s.events.On(newEvent(resource, api.Working, "Removing")) err = s.apiClient().VolumeRemove(ctx, id, true) if err == nil { s.events.On(newEvent(resource, api.Done, "Removed")) return nil } if errdefs.IsConflict(err) { s.events.On(newEvent(resource, api.Warning, "Resource is still in use")) return nil } if errdefs.IsNotFound(err) { s.events.On(newEvent(resource, api.Done, "Warning: No resource found to remove")) return nil } return err } func (s *composeService) stopContainer(ctx context.Context, service *types.ServiceConfig, ctr containerType.Summary, timeout *time.Duration, listener api.ContainerEventListener) error { eventName := getContainerProgressName(ctr) s.events.On(stoppingEvent(eventName)) if service != nil { for _, hook := range service.PreStop { err := s.runHook(ctx, ctr, *service, hook, listener) if err != nil { // Ignore errors indicating that some containers were already stopped or removed. if errdefs.IsNotFound(err) || errdefs.IsConflict(err) { return nil } return err } } } timeoutInSecond := utils.DurationSecondToInt(timeout) err := s.apiClient().ContainerStop(ctx, ctr.ID, containerType.StopOptions{Timeout: timeoutInSecond}) if err != nil { s.events.On(errorEvent(eventName, "Error while Stopping")) return err } s.events.On(stoppedEvent(eventName)) return nil } func (s *composeService) stopContainers(ctx context.Context, serv *types.ServiceConfig, containers []containerType.Summary, timeout *time.Duration, listener api.ContainerEventListener) error { eg, ctx := errgroup.WithContext(ctx) for _, ctr := range containers { eg.Go(func() error { return s.stopContainer(ctx, serv, ctr, timeout, listener) }) } return eg.Wait() } func (s *composeService) removeContainers(ctx context.Context, containers []containerType.Summary, service *types.ServiceConfig, timeout *time.Duration, volumes bool) error { eg, ctx := errgroup.WithContext(ctx) for _, ctr := range containers { eg.Go(func() error { return s.stopAndRemoveContainer(ctx, ctr, service, timeout, volumes) }) } return eg.Wait() } func (s *composeService) stopAndRemoveContainer(ctx context.Context, ctr containerType.Summary, service *types.ServiceConfig, timeout *time.Duration, volumes bool) error { eventName := getContainerProgressName(ctr) err := s.stopContainer(ctx, service, ctr, timeout, nil) if errdefs.IsNotFound(err) { s.events.On(removedEvent(eventName)) return nil } if err != nil { return err } s.events.On(removingEvent(eventName)) err = s.apiClient().ContainerRemove(ctx, ctr.ID, containerType.RemoveOptions{ Force: true, RemoveVolumes: volumes, }) if err != nil && !errdefs.IsNotFound(err) && !errdefs.IsConflict(err) { s.events.On(errorEvent(eventName, "Error while Removing")) return err } s.events.On(removedEvent(eventName)) return nil } func (s *composeService) getProjectWithResources(ctx context.Context, containers Containers, projectName string) (*types.Project, error) { containers = containers.filter(isNotOneOff) p, err := s.projectFromName(containers, projectName) if err != nil && !api.IsNotFoundError(err) { return nil, err } project, err := p.WithServicesTransform(func(name string, service types.ServiceConfig) (types.ServiceConfig, error) { for k := range service.DependsOn { if dependency, ok := service.DependsOn[k]; ok { dependency.Required = false service.DependsOn[k] = dependency } } return service, nil }) if err != nil { return nil, err } volumes, err := s.actualVolumes(ctx, projectName) if err != nil { return nil, err } project.Volumes = volumes networks, err := s.actualNetworks(ctx, projectName) if err != nil { return nil, err } project.Networks = networks return project, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/create_test.go
pkg/compose/create_test.go
/* 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" "os" "path/filepath" "sort" "testing" composeloader "github.com/compose-spec/compose-go/v2/loader" composetypes "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/image" mountTypes "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" "gotest.tools/v3/assert/cmp" "github.com/docker/compose/v5/pkg/api" ) func TestBuildBindMount(t *testing.T) { project := composetypes.Project{} volume := composetypes.ServiceVolumeConfig{ Type: composetypes.VolumeTypeBind, Source: "", Target: "/data", } mount, err := buildMount(project, volume) assert.NilError(t, err) assert.Assert(t, filepath.IsAbs(mount.Source)) _, err = os.Stat(mount.Source) assert.NilError(t, err) assert.Equal(t, mount.Type, mountTypes.TypeBind) } func TestBuildNamedPipeMount(t *testing.T) { project := composetypes.Project{} volume := composetypes.ServiceVolumeConfig{ Type: composetypes.VolumeTypeNamedPipe, Source: "\\\\.\\pipe\\docker_engine_windows", Target: "\\\\.\\pipe\\docker_engine", } mount, err := buildMount(project, volume) assert.NilError(t, err) assert.Equal(t, mount.Type, mountTypes.TypeNamedPipe) } func TestBuildVolumeMount(t *testing.T) { project := composetypes.Project{ Name: "myProject", Volumes: composetypes.Volumes(map[string]composetypes.VolumeConfig{ "myVolume": { Name: "myProject_myVolume", }, }), } volume := composetypes.ServiceVolumeConfig{ Type: composetypes.VolumeTypeVolume, Source: "myVolume", Target: "/data", } mount, err := buildMount(project, volume) assert.NilError(t, err) assert.Equal(t, mount.Source, "myProject_myVolume") assert.Equal(t, mount.Type, mountTypes.TypeVolume) } func TestServiceImageName(t *testing.T) { assert.Equal(t, api.GetImageNameOrDefault(composetypes.ServiceConfig{Image: "myImage"}, "myProject"), "myImage") assert.Equal(t, api.GetImageNameOrDefault(composetypes.ServiceConfig{Name: "aService"}, "myProject"), "myProject-aService") } func TestPrepareNetworkLabels(t *testing.T) { project := composetypes.Project{ Name: "myProject", Networks: composetypes.Networks(map[string]composetypes.NetworkConfig{"skynet": {}}), } prepareNetworks(&project) assert.DeepEqual(t, project.Networks["skynet"].CustomLabels, composetypes.Labels(map[string]string{ "com.docker.compose.network": "skynet", "com.docker.compose.project": "myProject", "com.docker.compose.version": api.ComposeVersion, })) } func TestBuildContainerMountOptions(t *testing.T) { project := composetypes.Project{ Name: "myProject", Services: composetypes.Services{ "myService": { Name: "myService", Volumes: []composetypes.ServiceVolumeConfig{ { Type: composetypes.VolumeTypeVolume, Target: "/var/myvolume1", }, { Type: composetypes.VolumeTypeVolume, Target: "/var/myvolume2", }, { Type: composetypes.VolumeTypeVolume, Source: "myVolume3", Target: "/var/myvolume3", Volume: &composetypes.ServiceVolumeVolume{ Subpath: "etc", }, }, { Type: composetypes.VolumeTypeNamedPipe, Source: "\\\\.\\pipe\\docker_engine_windows", Target: "\\\\.\\pipe\\docker_engine", }, }, }, }, Volumes: composetypes.Volumes(map[string]composetypes.VolumeConfig{ "myVolume1": { Name: "myProject_myVolume1", }, "myVolume2": { Name: "myProject_myVolume2", }, }), } inherit := &container.Summary{ Mounts: []container.MountPoint{ { Type: composetypes.VolumeTypeVolume, Destination: "/var/myvolume1", }, { Type: composetypes.VolumeTypeVolume, Destination: "/var/myvolume2", }, }, } mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mock, cli := prepareMocks(mockCtrl) s := composeService{ dockerCli: cli, } mock.EXPECT().ImageInspect(gomock.Any(), "myProject-myService").AnyTimes().Return(image.InspectResponse{}, nil) mounts, err := s.buildContainerMountOptions(context.TODO(), project, project.Services["myService"], inherit) sort.Slice(mounts, func(i, j int) bool { return mounts[i].Target < mounts[j].Target }) assert.NilError(t, err) assert.Assert(t, len(mounts) == 4) assert.Equal(t, mounts[0].Target, "/var/myvolume1") assert.Equal(t, mounts[1].Target, "/var/myvolume2") assert.Equal(t, mounts[2].Target, "/var/myvolume3") assert.Equal(t, mounts[2].VolumeOptions.Subpath, "etc") assert.Equal(t, mounts[3].Target, "\\\\.\\pipe\\docker_engine") mounts, err = s.buildContainerMountOptions(context.TODO(), project, project.Services["myService"], inherit) sort.Slice(mounts, func(i, j int) bool { return mounts[i].Target < mounts[j].Target }) assert.NilError(t, err) assert.Assert(t, len(mounts) == 4) assert.Equal(t, mounts[0].Target, "/var/myvolume1") assert.Equal(t, mounts[1].Target, "/var/myvolume2") assert.Equal(t, mounts[2].Target, "/var/myvolume3") assert.Equal(t, mounts[2].VolumeOptions.Subpath, "etc") assert.Equal(t, mounts[3].Target, "\\\\.\\pipe\\docker_engine") } func TestDefaultNetworkSettings(t *testing.T) { t.Run("returns the network with the highest priority when service has multiple networks", func(t *testing.T) { service := composetypes.ServiceConfig{ Name: "myService", Networks: map[string]*composetypes.ServiceNetworkConfig{ "myNetwork1": { Priority: 10, }, "myNetwork2": { Priority: 1000, }, }, } project := composetypes.Project{ Name: "myProject", Services: composetypes.Services{ "myService": service, }, Networks: composetypes.Networks(map[string]composetypes.NetworkConfig{ "myNetwork1": { Name: "myProject_myNetwork1", }, "myNetwork2": { Name: "myProject_myNetwork2", }, }), } networkMode, networkConfig, err := defaultNetworkSettings(&project, service, 1, nil, true, "1.43") assert.NilError(t, err) assert.Equal(t, string(networkMode), "myProject_myNetwork2") assert.Check(t, cmp.Len(networkConfig.EndpointsConfig, 1)) assert.Check(t, cmp.Contains(networkConfig.EndpointsConfig, "myProject_myNetwork2")) }) t.Run("returns default network when service has no networks", func(t *testing.T) { service := composetypes.ServiceConfig{ Name: "myService", } project := composetypes.Project{ Name: "myProject", Services: composetypes.Services{ "myService": service, }, Networks: composetypes.Networks(map[string]composetypes.NetworkConfig{ "myNetwork1": { Name: "myProject_myNetwork1", }, "myNetwork2": { Name: "myProject_myNetwork2", }, "default": { Name: "myProject_default", }, }), } networkMode, networkConfig, err := defaultNetworkSettings(&project, service, 1, nil, true, "1.43") assert.NilError(t, err) assert.Equal(t, string(networkMode), "myProject_default") assert.Check(t, cmp.Len(networkConfig.EndpointsConfig, 1)) assert.Check(t, cmp.Contains(networkConfig.EndpointsConfig, "myProject_default")) }) t.Run("returns none if project has no networks", func(t *testing.T) { service := composetypes.ServiceConfig{ Name: "myService", } project := composetypes.Project{ Name: "myProject", Services: composetypes.Services{ "myService": service, }, } networkMode, networkConfig, err := defaultNetworkSettings(&project, service, 1, nil, true, "1.43") assert.NilError(t, err) assert.Equal(t, string(networkMode), "none") assert.Check(t, cmp.Nil(networkConfig)) }) t.Run("returns defined network mode if explicitly set", func(t *testing.T) { service := composetypes.ServiceConfig{ Name: "myService", NetworkMode: "host", } project := composetypes.Project{ Name: "myProject", Services: composetypes.Services{"myService": service}, Networks: composetypes.Networks(map[string]composetypes.NetworkConfig{ "default": { Name: "myProject_default", }, }), } networkMode, networkConfig, err := defaultNetworkSettings(&project, service, 1, nil, true, "1.43") assert.NilError(t, err) assert.Equal(t, string(networkMode), "host") assert.Check(t, cmp.Nil(networkConfig)) }) } func TestCreateEndpointSettings(t *testing.T) { eps := createEndpointSettings(&composetypes.Project{ Name: "projName", }, composetypes.ServiceConfig{ Name: "serviceName", ContainerName: "containerName", Networks: map[string]*composetypes.ServiceNetworkConfig{ "netName": { Priority: 100, Aliases: []string{"alias1", "alias2"}, Ipv4Address: "10.16.17.18", Ipv6Address: "fdb4:7a7f:373a:3f0c::42", LinkLocalIPs: []string{"169.254.10.20"}, MacAddress: "10:00:00:00:01", DriverOpts: composetypes.Options{ "driverOpt1": "optval1", "driverOpt2": "optval2", }, }, }, }, 0, "netName", []string{"link1", "link2"}, true) assert.Check(t, cmp.DeepEqual(eps, &network.EndpointSettings{ IPAMConfig: &network.EndpointIPAMConfig{ IPv4Address: "10.16.17.18", IPv6Address: "fdb4:7a7f:373a:3f0c::42", LinkLocalIPs: []string{"169.254.10.20"}, }, Links: []string{"link1", "link2"}, Aliases: []string{"containerName", "serviceName", "alias1", "alias2"}, MacAddress: "10:00:00:00:01", DriverOpts: map[string]string{ "driverOpt1": "optval1", "driverOpt2": "optval2", }, // FIXME(robmry) - IPAddress and IPv6Gateway are "operational data" fields... // - The IPv6 address here is the container's address, not the gateway. // - Both fields will be cleared by the daemon, but they could be removed from // the request. IPAddress: "10.16.17.18", IPv6Gateway: "fdb4:7a7f:373a:3f0c::42", })) } func Test_buildContainerVolumes(t *testing.T) { pwd, err := os.Getwd() assert.NilError(t, err) tests := []struct { name string yaml string binds []string mounts []mountTypes.Mount }{ { name: "bind mount local path", yaml: ` services: test: volumes: - ./data:/data `, binds: []string{filepath.Join(pwd, "data") + ":/data:rw"}, mounts: nil, }, { name: "bind mount, not create host path", yaml: ` services: test: volumes: - type: bind source: ./data target: /data bind: create_host_path: false `, binds: nil, mounts: []mountTypes.Mount{ { Type: "bind", Source: filepath.Join(pwd, "data"), Target: "/data", BindOptions: &mountTypes.BindOptions{CreateMountpoint: false}, }, }, }, { name: "mount volume", yaml: ` services: test: volumes: - data:/data volumes: data: name: my_volume `, binds: []string{"my_volume:/data:rw"}, mounts: nil, }, { name: "mount volume, readonly", yaml: ` services: test: volumes: - data:/data:ro volumes: data: name: my_volume `, binds: []string{"my_volume:/data:ro"}, mounts: nil, }, { name: "mount volume subpath", yaml: ` services: test: volumes: - type: volume source: data target: /data volume: subpath: test/ volumes: data: name: my_volume `, binds: nil, mounts: []mountTypes.Mount{ { Type: "volume", Source: "my_volume", Target: "/data", VolumeOptions: &mountTypes.VolumeOptions{Subpath: "test/"}, }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p, err := composeloader.LoadWithContext(context.TODO(), composetypes.ConfigDetails{ ConfigFiles: []composetypes.ConfigFile{ { Filename: "test", Content: []byte(tt.yaml), }, }, }, func(options *composeloader.Options) { options.SkipValidation = true options.SkipConsistencyCheck = true }) assert.NilError(t, err) s := &composeService{} binds, mounts, err := s.buildContainerVolumes(context.TODO(), *p, p.Services["test"], nil) assert.NilError(t, err) assert.DeepEqual(t, tt.binds, binds) assert.DeepEqual(t, tt.mounts, mounts) }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/hash.go
pkg/compose/hash.go
/* 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 ( "encoding/json" "github.com/compose-spec/compose-go/v2/types" "github.com/opencontainers/go-digest" ) // ServiceHash computes the configuration hash for a service. func ServiceHash(o types.ServiceConfig) (string, error) { // remove the Build config when generating the service hash o.Build = nil o.PullPolicy = "" o.Scale = nil if o.Deploy != nil { o.Deploy.Replicas = nil } o.DependsOn = nil o.Profiles = nil bytes, err := json.Marshal(o) if err != nil { return "", err } return digest.SHA256.FromBytes(bytes).Encoded(), nil } // NetworkHash computes the configuration hash for a network. func NetworkHash(o *types.NetworkConfig) (string, error) { bytes, err := json.Marshal(o) if err != nil { return "", err } return digest.SHA256.FromBytes(bytes).Encoded(), nil } // VolumeHash computes the configuration hash for a volume. func VolumeHash(o types.VolumeConfig) (string, error) { if o.Driver == "" { // (TODO: jhrotko) This probably should be fixed in compose-go o.Driver = "local" } bytes, err := json.Marshal(o) if err != nil { return "", err } return digest.SHA256.FromBytes(bytes).Encoded(), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/convert.go
pkg/compose/convert.go
/* 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" "time" compose "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/versions" ) // ToMobyEnv convert into []string func ToMobyEnv(environment compose.MappingWithEquals) []string { var env []string for k, v := range environment { if v == nil { env = append(env, k) } else { env = append(env, fmt.Sprintf("%s=%s", k, *v)) } } return env } // ToMobyHealthCheck convert into container.HealthConfig func (s *composeService) ToMobyHealthCheck(ctx context.Context, check *compose.HealthCheckConfig) (*container.HealthConfig, error) { if check == nil { return nil, nil } var ( interval time.Duration timeout time.Duration period time.Duration retries int ) if check.Interval != nil { interval = time.Duration(*check.Interval) } if check.Timeout != nil { timeout = time.Duration(*check.Timeout) } if check.StartPeriod != nil { period = time.Duration(*check.StartPeriod) } if check.Retries != nil { retries = int(*check.Retries) } test := check.Test if check.Disable { test = []string{"NONE"} } var startInterval time.Duration if check.StartInterval != nil { version, err := s.RuntimeVersion(ctx) if err != nil { return nil, err } if versions.LessThan(version, "1.44") { return nil, errors.New("can't set healthcheck.start_interval as feature require Docker Engine v25 or later") } else { startInterval = time.Duration(*check.StartInterval) } if check.StartPeriod == nil { // see https://github.com/moby/moby/issues/48874 return nil, errors.New("healthcheck.start_interval requires healthcheck.start_period to be set") } } return &container.HealthConfig{ Test: test, Interval: interval, Timeout: timeout, StartPeriod: period, StartInterval: startInterval, Retries: retries, }, nil } // ToSeconds convert into seconds func ToSeconds(d *compose.Duration) *int { if d == nil { return nil } s := int(time.Duration(*d).Seconds()) return &s }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/build_bake.go
pkg/compose/build_bake.go
/* 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 ( "bufio" "bytes" "context" "crypto/sha1" "encoding/json" "errors" "fmt" "io" "io/fs" "os" "os/exec" "path/filepath" "slices" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/console" "github.com/containerd/errdefs" "github.com/docker/cli/cli-plugins/manager" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command/image/build" "github.com/docker/cli/cli/streams" "github.com/docker/docker/api/types/versions" "github.com/google/uuid" "github.com/moby/buildkit/client" gitutil "github.com/moby/buildkit/frontend/dockerfile/dfgitutil" "github.com/moby/buildkit/util/progress/progressui" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func buildWithBake(dockerCli command.Cli) (bool, error) { enabled, err := dockerCli.BuildKitEnabled() if err != nil { return false, err } if !enabled { return false, nil } _, err = manager.GetPlugin("buildx", dockerCli, &cobra.Command{}) if err != nil { if errdefs.IsNotFound(err) { logrus.Warnf("Docker Compose requires buildx plugin to be installed") return false, nil } return false, err } return true, err } // We _could_ use bake.* types from github.com/docker/buildx but long term plan is to remove buildx as a dependency type bakeConfig struct { Groups map[string]bakeGroup `json:"group"` Targets map[string]bakeTarget `json:"target"` } type bakeGroup struct { Targets []string `json:"targets"` } type bakeTarget struct { Context string `json:"context,omitempty"` Contexts map[string]string `json:"contexts,omitempty"` Dockerfile string `json:"dockerfile,omitempty"` DockerfileInline string `json:"dockerfile-inline,omitempty"` Args map[string]string `json:"args,omitempty"` Labels map[string]string `json:"labels,omitempty"` Tags []string `json:"tags,omitempty"` CacheFrom []string `json:"cache-from,omitempty"` CacheTo []string `json:"cache-to,omitempty"` Target string `json:"target,omitempty"` Secrets []string `json:"secret,omitempty"` SSH []string `json:"ssh,omitempty"` Platforms []string `json:"platforms,omitempty"` Pull bool `json:"pull,omitempty"` NoCache bool `json:"no-cache,omitempty"` NetworkMode string `json:"network,omitempty"` NoCacheFilter []string `json:"no-cache-filter,omitempty"` ShmSize types.UnitBytes `json:"shm-size,omitempty"` Ulimits []string `json:"ulimits,omitempty"` Call string `json:"call,omitempty"` Entitlements []string `json:"entitlements,omitempty"` ExtraHosts map[string]string `json:"extra-hosts,omitempty"` Outputs []string `json:"output,omitempty"` Attest []string `json:"attest,omitempty"` } type bakeMetadata map[string]buildStatus type buildStatus struct { Digest string `json:"containerimage.digest"` Image string `json:"image.name"` } func (s *composeService) doBuildBake(ctx context.Context, project *types.Project, serviceToBeBuild types.Services, options api.BuildOptions) (map[string]string, error) { //nolint:gocyclo eg := errgroup.Group{} ch := make(chan *client.SolveStatus) displayMode := progressui.DisplayMode(options.Progress) if p, ok := os.LookupEnv("BUILDKIT_PROGRESS"); ok && displayMode == progressui.AutoMode { displayMode = progressui.DisplayMode(p) } out := options.Out if out == nil { out = s.stdout() } display, err := progressui.NewDisplay(makeConsole(out), displayMode) if err != nil { return nil, err } eg.Go(func() error { _, err := display.UpdateFrom(ctx, ch) return err }) cfg := bakeConfig{ Groups: map[string]bakeGroup{}, Targets: map[string]bakeTarget{}, } var ( group bakeGroup privileged bool read []string expectedImages = make(map[string]string, len(serviceToBeBuild)) // service name -> expected image targets = make(map[string]string, len(serviceToBeBuild)) // service name -> build target ) // produce a unique ID for service used as bake target for serviceName := range project.Services { t := strings.ReplaceAll(serviceName, ".", "_") for { if _, ok := targets[serviceName]; !ok { targets[serviceName] = t break } t += "_" } } var secretsEnv []string for serviceName, service := range project.Services { if service.Build == nil { continue } buildConfig := *service.Build labels := getImageBuildLabels(project, service) args := resolveAndMergeBuildArgs(s.getProxyConfig(), project, service, options).ToMapping() for k, v := range args { args[k] = strings.ReplaceAll(v, "${", "$${") } entitlements := buildConfig.Entitlements if slices.Contains(buildConfig.Entitlements, "security.insecure") { privileged = true } if buildConfig.Privileged { entitlements = append(entitlements, "security.insecure") privileged = true } var outputs []string var call string push := options.Push && service.Image != "" switch { case options.Check: call = "lint" case len(service.Build.Platforms) > 1: outputs = []string{fmt.Sprintf("type=image,push=%t", push)} default: if push { outputs = []string{"type=registry"} } else { outputs = []string{"type=docker"} } } read = append(read, buildConfig.Context) for _, path := range buildConfig.AdditionalContexts { _, _, err := gitutil.ParseGitRef(path) if !strings.Contains(path, "://") && err != nil { read = append(read, path) } } image := api.GetImageNameOrDefault(service, project.Name) s.events.On(buildingEvent(image)) expectedImages[serviceName] = image pull := service.Build.Pull || options.Pull noCache := service.Build.NoCache || options.NoCache target := targets[serviceName] secrets, env := toBakeSecrets(project, buildConfig.Secrets) secretsEnv = append(secretsEnv, env...) cfg.Targets[target] = bakeTarget{ Context: buildConfig.Context, Contexts: additionalContexts(buildConfig.AdditionalContexts, targets), Dockerfile: dockerFilePath(buildConfig.Context, buildConfig.Dockerfile), DockerfileInline: strings.ReplaceAll(buildConfig.DockerfileInline, "${", "$${"), Args: args, Labels: labels, Tags: append(buildConfig.Tags, image), CacheFrom: buildConfig.CacheFrom, CacheTo: buildConfig.CacheTo, NetworkMode: buildConfig.Network, NoCacheFilter: buildConfig.NoCacheFilter, Platforms: buildConfig.Platforms, Target: buildConfig.Target, Secrets: secrets, SSH: toBakeSSH(append(buildConfig.SSH, options.SSHs...)), Pull: pull, NoCache: noCache, ShmSize: buildConfig.ShmSize, Ulimits: toBakeUlimits(buildConfig.Ulimits), Entitlements: entitlements, ExtraHosts: toBakeExtraHosts(buildConfig.ExtraHosts), Outputs: outputs, Call: call, Attest: toBakeAttest(buildConfig), } } // create a bake group with targets for services to build for serviceName, service := range serviceToBeBuild { if service.Build == nil { continue } group.Targets = append(group.Targets, targets[serviceName]) } cfg.Groups["default"] = group b, err := json.MarshalIndent(cfg, "", " ") if err != nil { return nil, err } if options.Print { _, err = fmt.Fprintln(s.stdout(), string(b)) return nil, err } logrus.Debugf("bake build config:\n%s", string(b)) tmpdir := os.TempDir() var metadataFile string for { // we don't use os.CreateTemp here as we need a temporary file name, but don't want it actually created // as bake relies on atomicwriter and this creates conflict during rename metadataFile = filepath.Join(tmpdir, fmt.Sprintf("compose-build-metadataFile-%s.json", uuid.New().String())) if _, err = os.Stat(metadataFile); err != nil { if os.IsNotExist(err) { break } var pathError *fs.PathError if errors.As(err, &pathError) { return nil, fmt.Errorf("can't access os.tempDir %s: %w", tmpdir, pathError.Err) } } } defer func() { _ = os.Remove(metadataFile) }() buildx, err := s.getBuildxPlugin() if err != nil { return nil, err } args := []string{"bake", "--file", "-", "--progress", "rawjson", "--metadata-file", metadataFile} // FIXME we should prompt user about this, but this is a breaking change in UX for _, path := range read { args = append(args, "--allow", "fs.read="+path) } if privileged { args = append(args, "--allow", "security.insecure") } if options.SBOM != "" { args = append(args, "--sbom="+options.SBOM) } if options.Provenance != "" { args = append(args, "--provenance="+options.Provenance) } if options.Builder != "" { args = append(args, "--builder", options.Builder) } if options.Quiet { args = append(args, "--progress=quiet") } logrus.Debugf("Executing bake with args: %v", args) if s.dryRun { return s.dryRunBake(cfg), nil } cmd := exec.CommandContext(ctx, buildx.Path, args...) err = s.prepareShellOut(ctx, types.NewMapping(os.Environ()), cmd) if err != nil { return nil, err } endpoint, cleanup, err := s.propagateDockerEndpoint() if err != nil { return nil, err } cmd.Env = append(cmd.Env, endpoint...) cmd.Env = append(cmd.Env, secretsEnv...) defer cleanup() cmd.Stdout = s.stdout() cmd.Stdin = bytes.NewBuffer(b) pipe, err := cmd.StderrPipe() if err != nil { return nil, err } var errMessage []string reader := bufio.NewReader(pipe) err = cmd.Start() if err != nil { return nil, err } eg.Go(cmd.Wait) for { line, readErr := reader.ReadString('\n') if readErr != nil { if readErr == io.EOF { break } if errors.Is(readErr, os.ErrClosed) { logrus.Debugf("bake stopped") break } return nil, fmt.Errorf("failed to execute bake: %w", readErr) } decoder := json.NewDecoder(strings.NewReader(line)) var status client.SolveStatus err := decoder.Decode(&status) if err != nil { if strings.HasPrefix(line, "ERROR: ") { errMessage = append(errMessage, line[7:]) } else { errMessage = append(errMessage, line) } continue } ch <- &status } close(ch) // stop build progress UI err = eg.Wait() if err != nil { if len(errMessage) > 0 { return nil, errors.New(strings.Join(errMessage, "\n")) } return nil, fmt.Errorf("failed to execute bake: %w", err) } b, err = os.ReadFile(metadataFile) if err != nil { return nil, err } var md bakeMetadata err = json.Unmarshal(b, &md) if err != nil { return nil, err } results := map[string]string{} for name := range serviceToBeBuild { image := expectedImages[name] target := targets[name] built, ok := md[target] if !ok { return nil, fmt.Errorf("build result not found in Bake metadata for service %s", name) } results[image] = built.Digest s.events.On(builtEvent(image)) } return results, nil } func (s *composeService) getBuildxPlugin() (*manager.Plugin, error) { buildx, err := manager.GetPlugin("buildx", s.dockerCli, &cobra.Command{}) if err != nil { return nil, err } if buildx.Err != nil { return nil, buildx.Err } if buildx.Version == "" { return nil, fmt.Errorf("failed to get version of buildx") } if versions.LessThan(buildx.Version[1:], "0.17.0") { return nil, fmt.Errorf("compose build requires buildx 0.17 or later") } return buildx, nil } // makeConsole wraps the provided writer to match [containerd.File] interface if it is of type *streams.Out. // buildkit's NewDisplay doesn't actually require a [io.Reader], it only uses the [containerd.Console] type to // benefits from ANSI capabilities, but only does writes. func makeConsole(out io.Writer) io.Writer { if s, ok := out.(*streams.Out); ok { return &_console{s} } return out } var _ console.File = &_console{} type _console struct { *streams.Out } func (c _console) Read(p []byte) (n int, err error) { return 0, errors.New("not implemented") } func (c _console) Close() error { return nil } func (c _console) Fd() uintptr { return c.FD() } func (c _console) Name() string { return "compose" } func toBakeExtraHosts(hosts types.HostsList) map[string]string { m := make(map[string]string) for k, v := range hosts { m[k] = strings.Join(v, ",") } return m } func additionalContexts(contexts types.Mapping, targets map[string]string) map[string]string { ac := map[string]string{} for k, v := range contexts { if target, found := strings.CutPrefix(v, types.ServicePrefix); found { v = "target:" + targets[target] } ac[k] = v } return ac } func toBakeUlimits(ulimits map[string]*types.UlimitsConfig) []string { s := []string{} for u, l := range ulimits { if l.Single > 0 { s = append(s, fmt.Sprintf("%s=%d", u, l.Single)) } else { s = append(s, fmt.Sprintf("%s=%d:%d", u, l.Soft, l.Hard)) } } return s } func toBakeSSH(ssh types.SSHConfig) []string { var s []string for _, key := range ssh { s = append(s, fmt.Sprintf("%s=%s", key.ID, key.Path)) } return s } func toBakeSecrets(project *types.Project, secrets []types.ServiceSecretConfig) ([]string, []string) { var s []string var env []string for _, ref := range secrets { def := project.Secrets[ref.Source] target := ref.Target if target == "" { target = ref.Source } switch { case def.Environment != "": env = append(env, fmt.Sprintf("%s=%s", def.Environment, project.Environment[def.Environment])) s = append(s, fmt.Sprintf("id=%s,type=env,env=%s", target, def.Environment)) case def.File != "": s = append(s, fmt.Sprintf("id=%s,type=file,src=%s", target, def.File)) } } return s, env } func toBakeAttest(buildConfig types.BuildConfig) []string { var attests []string // Handle per-service provenance configuration (only from build config, not global options) if buildConfig.Provenance != "" { if buildConfig.Provenance == "true" { attests = append(attests, "type=provenance") } else if buildConfig.Provenance != "false" { attests = append(attests, fmt.Sprintf("type=provenance,%s", buildConfig.Provenance)) } } // Handle per-service SBOM configuration (only from build config, not global options) if buildConfig.SBOM != "" { if buildConfig.SBOM == "true" { attests = append(attests, "type=sbom") } else if buildConfig.SBOM != "false" { attests = append(attests, fmt.Sprintf("type=sbom,%s", buildConfig.SBOM)) } } return attests } func dockerFilePath(ctxName string, dockerfile string) string { if dockerfile == "" { return "" } if contextType, _ := build.DetectContextType(ctxName); contextType == build.ContextTypeGit { return dockerfile } if !filepath.IsAbs(dockerfile) { dockerfile = filepath.Join(ctxName, dockerfile) } dir := filepath.Dir(dockerfile) symlinks, err := filepath.EvalSymlinks(dir) if err == nil { return filepath.Join(symlinks, filepath.Base(dockerfile)) } return dockerfile } func (s composeService) dryRunBake(cfg bakeConfig) map[string]string { bakeResponse := map[string]string{} for name, target := range cfg.Targets { dryRunUUID := fmt.Sprintf("dryRun-%x", sha1.Sum([]byte(name))) s.displayDryRunBuildEvent(name, dryRunUUID, target.Tags[0]) bakeResponse[name] = dryRunUUID } for name := range bakeResponse { s.events.On(builtEvent(name)) } return bakeResponse } func (s composeService) displayDryRunBuildEvent(name, dryRunUUID, tag string) { s.events.On(api.Resource{ ID: name + " ==>", Status: api.Done, Text: fmt.Sprintf("==> writing image %s", dryRunUUID), }) s.events.On(api.Resource{ ID: name + " ==> ==>", Status: api.Done, Text: fmt.Sprintf(`naming to %s`, tag), }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/attach.go
pkg/compose/attach.go
/* 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" "io" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/streams" containerType "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/stdcopy" "github.com/moby/term" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) func (s *composeService) attach(ctx context.Context, project *types.Project, listener api.ContainerEventListener, selectedServices []string) (Containers, error) { containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true, selectedServices...) if err != nil { return nil, err } if len(containers) == 0 { return containers, nil } containers.sorted() // This enforces predictable colors assignment var names []string for _, c := range containers { names = append(names, getContainerNameWithoutProject(c)) } _, _ = fmt.Fprintf(s.stdout(), "Attaching to %s\n", strings.Join(names, ", ")) for _, ctr := range containers { err := s.attachContainer(ctx, ctr, listener) if err != nil { return nil, err } } return containers, err } func (s *composeService) attachContainer(ctx context.Context, container containerType.Summary, listener api.ContainerEventListener) error { service := container.Labels[api.ServiceLabel] name := getContainerNameWithoutProject(container) return s.doAttachContainer(ctx, service, container.ID, name, listener) } func (s *composeService) doAttachContainer(ctx context.Context, service, id, name string, listener api.ContainerEventListener) error { inspect, err := s.apiClient().ContainerInspect(ctx, id) if err != nil { return err } wOut := utils.GetWriter(func(line string) { listener(api.ContainerEvent{ Type: api.ContainerEventLog, Source: name, ID: id, Service: service, Line: line, }) }) wErr := utils.GetWriter(func(line string) { listener(api.ContainerEvent{ Type: api.ContainerEventErr, Source: name, ID: id, Service: service, Line: line, }) }) _, _, err = s.attachContainerStreams(ctx, id, inspect.Config.Tty, nil, wOut, wErr) return err } func (s *composeService) attachContainerStreams(ctx context.Context, container string, tty bool, stdin io.ReadCloser, stdout, stderr io.WriteCloser) (func(), chan bool, error) { detached := make(chan bool) restore := func() { /* noop */ } if stdin != nil { in := streams.NewIn(stdin) if in.IsTerminal() { state, err := term.SetRawTerminal(in.FD()) if err != nil { return restore, detached, err } restore = func() { term.RestoreTerminal(in.FD(), state) //nolint:errcheck } } } streamIn, streamOut, err := s.getContainerStreams(ctx, container) if err != nil { return restore, detached, err } go func() { <-ctx.Done() if stdin != nil { stdin.Close() //nolint:errcheck } }() if streamIn != nil && stdin != nil { go func() { _, err := io.Copy(streamIn, stdin) var escapeErr term.EscapeError if errors.As(err, &escapeErr) { close(detached) } }() } if stdout != nil { go func() { defer stdout.Close() //nolint:errcheck defer stderr.Close() //nolint:errcheck defer streamOut.Close() //nolint:errcheck if tty { io.Copy(stdout, streamOut) //nolint:errcheck } else { stdcopy.StdCopy(stdout, stderr, streamOut) //nolint:errcheck } }() } return restore, detached, nil } func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.WriteCloser, io.ReadCloser, error) { var stdout io.ReadCloser var stdin io.WriteCloser cnx, err := s.apiClient().ContainerAttach(ctx, container, containerType.AttachOptions{ Stream: true, Stdin: true, Stdout: true, Stderr: true, Logs: false, DetachKeys: s.configFile().DetachKeys, }) if err == nil { stdout = ContainerStdout{HijackedResponse: cnx} stdin = ContainerStdin{HijackedResponse: cnx} return stdin, stdout, nil } // Fallback to logs API logs, err := s.apiClient().ContainerLogs(ctx, container, containerType.LogsOptions{ ShowStdout: true, ShowStderr: true, Follow: true, }) if err != nil { return nil, nil, err } return stdin, logs, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/build.go
pkg/compose/build.go
/* 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" "fmt" "strings" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/platforms" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/sirupsen/logrus" "github.com/docker/compose/v5/internal/tracing" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error { err := options.Apply(project) if err != nil { return err } return Run(ctx, func(ctx context.Context) error { return tracing.SpanWrapFunc("project/build", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error { builtImages, err := s.build(ctx, project, options, nil) if err == nil && len(builtImages) == 0 { logrus.Warn("No services to build") } return err })(ctx) }, "build", s.events) } func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions, localImages map[string]api.ImageSummary) (map[string]string, error) { imageIDs := map[string]string{} serviceToBuild := types.Services{} var policy types.DependencyOption = types.IgnoreDependencies if options.Deps { policy = types.IncludeDependencies } if len(options.Services) == 0 { options.Services = project.ServiceNames() } // also include services used as additional_contexts with service: prefix options.Services = addBuildDependencies(options.Services, project) // Some build dependencies we just introduced may not be enabled var err error project, err = project.WithServicesEnabled(options.Services...) if err != nil { return nil, err } project, err = project.WithSelectedServices(options.Services) if err != nil { return nil, err } err = project.ForEachService(options.Services, func(serviceName string, service *types.ServiceConfig) error { if service.Build == nil { return nil } image := api.GetImageNameOrDefault(*service, project.Name) _, localImagePresent := localImages[image] if localImagePresent && service.PullPolicy != types.PullPolicyBuild { return nil } serviceToBuild[serviceName] = *service return nil }, policy) if err != nil { return imageIDs, err } if len(serviceToBuild) == 0 { return imageIDs, nil } bake, err := buildWithBake(s.dockerCli) if err != nil { return nil, err } if bake { return s.doBuildBake(ctx, project, serviceToBuild, options) } return s.doBuildClassic(ctx, project, serviceToBuild, options) } func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, buildOpts *api.BuildOptions, quietPull bool) error { for name, service := range project.Services { if service.Provider == nil && service.Image == "" && service.Build == nil { return fmt.Errorf("invalid service %q. Must specify either image or build", name) } } images, err := s.getLocalImagesDigests(ctx, project) if err != nil { return err } err = tracing.SpanWrapFunc("project/pull", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error { return s.pullRequiredImages(ctx, project, images, quietPull) }, )(ctx) if err != nil { return err } if buildOpts != nil { err = tracing.SpanWrapFunc("project/build", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error { builtImages, err := s.build(ctx, project, *buildOpts, images) if err != nil { return err } for name, digest := range builtImages { images[name] = api.ImageSummary{ Repository: name, ID: digest, LastTagTime: time.Now(), } } return nil }, )(ctx) if err != nil { return err } } // set digest as com.docker.compose.image label so we can detect outdated containers for name, service := range project.Services { image := api.GetImageNameOrDefault(service, project.Name) img, ok := images[image] if ok { service.CustomLabels.Add(api.ImageDigestLabel, img.ID) } project.Services[name] = service } return nil } func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]api.ImageSummary, error) { imageNames := utils.Set[string]{} for _, s := range project.Services { imageNames.Add(api.GetImageNameOrDefault(s, project.Name)) for _, volume := range s.Volumes { if volume.Type == types.VolumeTypeImage { imageNames.Add(volume.Source) } } } imgs, err := s.getImageSummaries(ctx, imageNames.Elements()) if err != nil { return nil, err } for i, service := range project.Services { imgName := api.GetImageNameOrDefault(service, project.Name) img, ok := imgs[imgName] if !ok { continue } if service.Platform != "" { platform, err := platforms.Parse(service.Platform) if err != nil { return nil, err } inspect, err := s.apiClient().ImageInspect(ctx, img.ID) if err != nil { return nil, err } actual := specs.Platform{ Architecture: inspect.Architecture, OS: inspect.Os, Variant: inspect.Variant, } if !platforms.NewMatcher(platform).Match(actual) { logrus.Debugf("local image %s doesn't match expected platform %s", service.Image, service.Platform) // there is a local image, but it's for the wrong platform, so // pretend it doesn't exist so that we can pull/build an image // for the correct platform instead delete(imgs, imgName) } } project.Services[i].CustomLabels.Add(api.ImageDigestLabel, img.ID) } return imgs, nil } // resolveAndMergeBuildArgs returns the final set of build arguments to use for the service image build. // // First, args directly defined via `build.args` in YAML are considered. // Then, any explicitly passed args in opts (e.g. via `--build-arg` on the CLI) are merged, overwriting any // keys that already exist. // Next, any keys without a value are resolved using the project environment. // // Finally, standard proxy variables based on the Docker client configuration are added, but will not overwrite // any values if already present. func resolveAndMergeBuildArgs(proxyConfig map[string]string, project *types.Project, service types.ServiceConfig, opts api.BuildOptions) types.MappingWithEquals { result := make(types.MappingWithEquals). OverrideBy(service.Build.Args). OverrideBy(opts.Args). Resolve(envResolver(project.Environment)) // proxy arguments do NOT override and should NOT have env resolution applied, // so they're handled last for k, v := range proxyConfig { if _, ok := result[k]; !ok { v := v result[k] = &v } } return result } func getImageBuildLabels(project *types.Project, service types.ServiceConfig) types.Labels { ret := make(types.Labels) if service.Build != nil { for k, v := range service.Build.Labels { ret.Add(k, v) } } ret.Add(api.VersionLabel, api.ComposeVersion) ret.Add(api.ProjectLabel, project.Name) ret.Add(api.ServiceLabel, service.Name) return ret } func addBuildDependencies(services []string, project *types.Project) []string { servicesWithDependencies := utils.NewSet(services...) for _, service := range services { s, ok := project.Services[service] if !ok { s = project.DisabledServices[service] } b := s.Build if b != nil { for _, target := range b.AdditionalContexts { if s, found := strings.CutPrefix(target, types.ServicePrefix); found { servicesWithDependencies.Add(s) } } } } if len(servicesWithDependencies) > len(services) { return addBuildDependencies(servicesWithDependencies.Elements(), project) } return servicesWithDependencies.Elements() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/model.go
pkg/compose/model.go
/* 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 ( "bufio" "context" "encoding/json" "fmt" "os/exec" "slices" "strconv" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" "github.com/docker/cli/cli-plugins/manager" "github.com/docker/docker/api/types/versions" "github.com/spf13/cobra" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) ensureModels(ctx context.Context, project *types.Project, quietPull bool) error { if len(project.Models) == 0 { return nil } mdlAPI, err := s.newModelAPI(project) if err != nil { return err } defer mdlAPI.Close() availableModels, err := mdlAPI.ListModels(ctx) eg, ctx := errgroup.WithContext(ctx) eg.Go(func() error { return mdlAPI.SetModelVariables(ctx, project) }) for name, config := range project.Models { if config.Name == "" { config.Name = name } eg.Go(func() error { if !slices.Contains(availableModels, config.Model) { err = mdlAPI.PullModel(ctx, config, quietPull, s.events) if err != nil { return err } } return mdlAPI.ConfigureModel(ctx, config, s.events) }) } return eg.Wait() } type modelAPI struct { path string env []string prepare func(ctx context.Context, cmd *exec.Cmd) error cleanup func() version string } func (s *composeService) newModelAPI(project *types.Project) (*modelAPI, error) { dockerModel, err := manager.GetPlugin("model", s.dockerCli, &cobra.Command{}) if err != nil { if errdefs.IsNotFound(err) { return nil, fmt.Errorf("'models' support requires Docker Model plugin") } return nil, err } if dockerModel.Err != nil { return nil, fmt.Errorf("failed to load Docker Model plugin: %w", dockerModel.Err) } endpoint, cleanup, err := s.propagateDockerEndpoint() if err != nil { return nil, err } return &modelAPI{ path: dockerModel.Path, version: dockerModel.Version, prepare: func(ctx context.Context, cmd *exec.Cmd) error { return s.prepareShellOut(ctx, project.Environment, cmd) }, cleanup: cleanup, env: append(project.Environment.Values(), endpoint...), }, nil } func (m *modelAPI) Close() { m.cleanup() } func (m *modelAPI) PullModel(ctx context.Context, model types.ModelConfig, quietPull bool, events api.EventProcessor) error { events.On(api.Resource{ ID: model.Name, Status: api.Working, Text: api.StatusPulling, }) cmd := exec.CommandContext(ctx, m.path, "pull", model.Model) err := m.prepare(ctx, cmd) if err != nil { return err } stream, err := cmd.StdoutPipe() if err != nil { return err } err = cmd.Start() if err != nil { return err } scanner := bufio.NewScanner(stream) for scanner.Scan() { msg := scanner.Text() if msg == "" { continue } if !quietPull { events.On(api.Resource{ ID: model.Name, Status: api.Working, Text: api.StatusPulling, }) } } err = cmd.Wait() if err != nil { events.On(errorEvent(model.Name, err.Error())) } events.On(api.Resource{ ID: model.Name, Status: api.Working, Text: api.StatusPulled, }) return err } func (m *modelAPI) ConfigureModel(ctx context.Context, config types.ModelConfig, events api.EventProcessor) error { events.On(api.Resource{ ID: config.Name, Status: api.Working, Text: api.StatusConfiguring, }) // configure [--context-size=<n>] MODEL [-- <runtime-flags...>] args := []string{"configure"} if config.ContextSize > 0 { args = append(args, "--context-size", strconv.Itoa(config.ContextSize)) } args = append(args, config.Model) // Only append RuntimeFlags if docker model CLI version is >= v1.0.6 if len(config.RuntimeFlags) != 0 && m.supportsRuntimeFlags() { args = append(args, "--") args = append(args, config.RuntimeFlags...) } cmd := exec.CommandContext(ctx, m.path, args...) err := m.prepare(ctx, cmd) if err != nil { return err } err = cmd.Run() if err != nil { events.On(errorEvent(config.Name, err.Error())) return err } events.On(api.Resource{ ID: config.Name, Status: api.Done, Text: api.StatusConfigured, }) return nil } func (m *modelAPI) SetModelVariables(ctx context.Context, project *types.Project) error { cmd := exec.CommandContext(ctx, m.path, "status", "--json") err := m.prepare(ctx, cmd) if err != nil { return err } statusOut, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf("error checking docker-model status: %w", err) } type Status struct { Endpoint string `json:"endpoint"` } var status Status err = json.Unmarshal(statusOut, &status) if err != nil { return err } for _, service := range project.Services { for ref, modelConfig := range service.Models { model := project.Models[ref] varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_") var variable string if modelConfig != nil && modelConfig.ModelVariable != "" { variable = modelConfig.ModelVariable } else { variable = varPrefix + "_MODEL" } service.Environment[variable] = &model.Model if modelConfig != nil && modelConfig.EndpointVariable != "" { variable = modelConfig.EndpointVariable } else { variable = varPrefix + "_URL" } service.Environment[variable] = &status.Endpoint } } return nil } type Model struct { Id string `json:"id"` Tags []string `json:"tags"` Created int `json:"created"` Config struct { Format string `json:"format"` Quantization string `json:"quantization"` Parameters string `json:"parameters"` Architecture string `json:"architecture"` Size string `json:"size"` } `json:"config"` } func (m *modelAPI) ListModels(ctx context.Context) ([]string, error) { cmd := exec.CommandContext(ctx, m.path, "ls", "--json") err := m.prepare(ctx, cmd) if err != nil { return nil, err } output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("error checking available models: %w", err) } type AvailableModel struct { Id string `json:"id"` Tags []string `json:"tags"` Created int `json:"created"` } models := []AvailableModel{} err = json.Unmarshal(output, &models) if err != nil { return nil, fmt.Errorf("error unmarshalling available models: %w", err) } var availableModels []string for _, model := range models { availableModels = append(availableModels, model.Tags...) } return availableModels, nil } // supportsRuntimeFlags checks if the docker model version supports runtime flags // Runtime flags are supported in version >= v1.0.6 func (m *modelAPI) supportsRuntimeFlags() bool { // If version is not cached, don't append runtime flags to be safe if m.version == "" { return false } // Strip 'v' prefix if present (e.g., "v1.0.6" -> "1.0.6") versionStr := strings.TrimPrefix(m.version, "v") return !versions.LessThan(versionStr, "1.0.6") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/restart.go
pkg/compose/restart.go
/* 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" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) func (s *composeService) Restart(ctx context.Context, projectName string, options api.RestartOptions) error { return Run(ctx, func(ctx context.Context) error { return s.restart(ctx, strings.ToLower(projectName), options) }, "restart", s.events) } func (s *composeService) restart(ctx context.Context, projectName string, options api.RestartOptions) error { //nolint:gocyclo containers, err := s.getContainers(ctx, projectName, oneOffExclude, true) if err != nil { return err } project := options.Project if project == nil { project, err = s.getProjectWithResources(ctx, containers, projectName) if err != nil { return err } } if options.NoDeps { project, err = project.WithSelectedServices(options.Services, types.IgnoreDependencies) if err != nil { return err } } // ignore depends_on relations which are not impacted by restarting service or not required project, err = project.WithServicesTransform(func(_ string, s types.ServiceConfig) (types.ServiceConfig, error) { for name, r := range s.DependsOn { if !r.Restart { delete(s.DependsOn, name) } } return s, nil }) if err != nil { return err } if len(options.Services) != 0 { project, err = project.WithSelectedServices(options.Services, types.IncludeDependents) if err != nil { return err } } return InDependencyOrder(ctx, project, func(c context.Context, service string) error { config := project.Services[service] err = s.waitDependencies(ctx, project, service, config.DependsOn, containers, 0) if err != nil { return err } eg, ctx := errgroup.WithContext(ctx) for _, ctr := range containers.filter(isService(service)) { eg.Go(func() error { def := project.Services[service] for _, hook := range def.PreStop { err = s.runHook(ctx, ctr, def, hook, nil) if err != nil { return err } } eventName := getContainerProgressName(ctr) s.events.On(restartingEvent(eventName)) timeout := utils.DurationSecondToInt(options.Timeout) err = s.apiClient().ContainerRestart(ctx, ctr.ID, container.StopOptions{Timeout: timeout}) if err != nil { return err } s.events.On(startedEvent(eventName)) for _, hook := range def.PostStart { err = s.runHook(ctx, ctr, def, hook, nil) if err != nil { return err } } return nil }) } return eg.Wait() }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/port.go
pkg/compose/port.go
/* 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" "fmt" "strings" "github.com/docker/docker/api/types/container" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Port(ctx context.Context, projectName string, service string, port uint16, options api.PortOptions) (string, int, error) { projectName = strings.ToLower(projectName) ctr, err := s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, service, options.Index) if err != nil { return "", 0, err } for _, p := range ctr.Ports { if p.PrivatePort == port && p.Type == options.Protocol { return p.IP, int(p.PublicPort), nil } } return "", 0, portNotFoundError(options.Protocol, port, ctr) } func portNotFoundError(protocol string, port uint16, ctr container.Summary) error { formatPort := func(protocol string, port uint16) string { return fmt.Sprintf("%d/%s", port, protocol) } var containerPorts []string for _, p := range ctr.Ports { containerPorts = append(containerPorts, formatPort(p.Type, p.PublicPort)) } name := strings.TrimPrefix(ctr.Names[0], "/") return fmt.Errorf("no port %s for container %s: %s", formatPort(protocol, port), name, strings.Join(containerPorts, ", ")) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/publish.go
pkg/compose/publish.go
/* 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 ( "bytes" "context" "crypto/sha256" "encoding/json" "errors" "fmt" "io" "os" "strings" "github.com/DefangLabs/secret-detector/pkg/scanner" "github.com/DefangLabs/secret-detector/pkg/secrets" "github.com/compose-spec/compose-go/v2/loader" "github.com/compose-spec/compose-go/v2/types" "github.com/distribution/reference" "github.com/opencontainers/go-digest" "github.com/opencontainers/image-spec/specs-go" v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/sirupsen/logrus" "github.com/docker/compose/v5/internal/oci" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose/transform" ) func (s *composeService) Publish(ctx context.Context, project *types.Project, repository string, options api.PublishOptions) error { return Run(ctx, func(ctx context.Context) error { return s.publish(ctx, project, repository, options) }, "publish", s.events) } //nolint:gocyclo func (s *composeService) publish(ctx context.Context, project *types.Project, repository string, options api.PublishOptions) error { project, err := project.WithProfiles([]string{"*"}) if err != nil { return err } accept, err := s.preChecks(project, options) if err != nil { return err } if !accept { return nil } err = s.Push(ctx, project, api.PushOptions{IgnoreFailures: true, ImageMandatory: true}) if err != nil { return err } layers, err := s.createLayers(ctx, project, options) if err != nil { return err } s.events.On(api.Resource{ ID: repository, Text: "publishing", Status: api.Working, }) if logrus.IsLevelEnabled(logrus.DebugLevel) { logrus.Debug("publishing layers") for _, layer := range layers { indent, _ := json.MarshalIndent(layer, "", " ") fmt.Println(string(indent)) } } if !s.dryRun { named, err := reference.ParseDockerRef(repository) if err != nil { return err } var insecureRegistries []string if options.InsecureRegistry { insecureRegistries = append(insecureRegistries, reference.Domain(named)) } resolver := oci.NewResolver(s.configFile(), insecureRegistries...) descriptor, err := oci.PushManifest(ctx, resolver, named, layers, options.OCIVersion) if err != nil { s.events.On(api.Resource{ ID: repository, Text: "publishing", Status: api.Error, }) return err } if options.Application { manifests := []v1.Descriptor{} for _, service := range project.Services { ref, err := reference.ParseDockerRef(service.Image) if err != nil { return err } manifest, err := oci.Copy(ctx, resolver, ref, named) if err != nil { return err } manifests = append(manifests, manifest) } descriptor.Data = nil index, err := json.Marshal(v1.Index{ Versioned: specs.Versioned{SchemaVersion: 2}, MediaType: v1.MediaTypeImageIndex, Manifests: manifests, Subject: &descriptor, Annotations: map[string]string{ "com.docker.compose.version": api.ComposeVersion, }, }) if err != nil { return err } imagesDescriptor := v1.Descriptor{ MediaType: v1.MediaTypeImageIndex, ArtifactType: oci.ComposeProjectArtifactType, Digest: digest.FromString(string(index)), Size: int64(len(index)), Annotations: map[string]string{ "com.docker.compose.version": api.ComposeVersion, }, Data: index, } err = oci.Push(ctx, resolver, reference.TrimNamed(named), imagesDescriptor) if err != nil { return err } } } s.events.On(api.Resource{ ID: repository, Text: "published", Status: api.Done, }) return nil } func (s *composeService) createLayers(ctx context.Context, project *types.Project, options api.PublishOptions) ([]v1.Descriptor, error) { var layers []v1.Descriptor extFiles := map[string]string{} envFiles := map[string]string{} for _, file := range project.ComposeFiles { data, err := processFile(ctx, file, project, extFiles, envFiles) if err != nil { return nil, err } layerDescriptor := oci.DescriptorForComposeFile(file, data) layers = append(layers, layerDescriptor) } extLayers, err := processExtends(ctx, project, extFiles) if err != nil { return nil, err } layers = append(layers, extLayers...) if options.WithEnvironment { layers = append(layers, envFileLayers(envFiles)...) } if options.ResolveImageDigests { yaml, err := s.generateImageDigestsOverride(ctx, project) if err != nil { return nil, err } layerDescriptor := oci.DescriptorForComposeFile("image-digests.yaml", yaml) layers = append(layers, layerDescriptor) } return layers, nil } func processExtends(ctx context.Context, project *types.Project, extFiles map[string]string) ([]v1.Descriptor, error) { var layers []v1.Descriptor moreExtFiles := map[string]string{} for xf, hash := range extFiles { data, err := processFile(ctx, xf, project, moreExtFiles, nil) if err != nil { return nil, err } layerDescriptor := oci.DescriptorForComposeFile(hash, data) layerDescriptor.Annotations["com.docker.compose.extends"] = "true" layers = append(layers, layerDescriptor) } for f, hash := range moreExtFiles { if _, ok := extFiles[f]; ok { delete(moreExtFiles, f) } extFiles[f] = hash } if len(moreExtFiles) > 0 { extLayers, err := processExtends(ctx, project, moreExtFiles) if err != nil { return nil, err } layers = append(layers, extLayers...) } return layers, nil } func processFile(ctx context.Context, file string, project *types.Project, extFiles map[string]string, envFiles map[string]string) ([]byte, error) { f, err := os.ReadFile(file) if err != nil { return nil, err } base, err := loader.LoadWithContext(ctx, types.ConfigDetails{ WorkingDir: project.WorkingDir, Environment: project.Environment, ConfigFiles: []types.ConfigFile{ { Filename: file, Content: f, }, }, }, func(options *loader.Options) { options.SkipValidation = true options.SkipExtends = true options.SkipConsistencyCheck = true options.ResolvePaths = true options.SkipInclude = true options.Profiles = project.Profiles }) if err != nil { return nil, err } for name, service := range base.Services { for i, envFile := range service.EnvFiles { hash := fmt.Sprintf("%x.env", sha256.Sum256([]byte(envFile.Path))) envFiles[envFile.Path] = hash f, err = transform.ReplaceEnvFile(f, name, i, hash) if err != nil { return nil, err } } if service.Extends == nil { continue } xf := service.Extends.File if xf == "" { continue } if _, err = os.Stat(service.Extends.File); os.IsNotExist(err) { // No local file, while we loaded the project successfully: This is actually a remote resource continue } hash := fmt.Sprintf("%x.yaml", sha256.Sum256([]byte(xf))) extFiles[xf] = hash f, err = transform.ReplaceExtendsFile(f, name, hash) if err != nil { return nil, err } } return f, nil } func (s *composeService) generateImageDigestsOverride(ctx context.Context, project *types.Project) ([]byte, error) { project, err := project.WithImagesResolved(ImageDigestResolver(ctx, s.configFile(), s.apiClient())) if err != nil { return nil, err } override := types.Project{ Services: types.Services{}, } for name, service := range project.Services { override.Services[name] = types.ServiceConfig{ Image: service.Image, } } return override.MarshalYAML() } func (s *composeService) preChecks(project *types.Project, options api.PublishOptions) (bool, error) { if ok, err := s.checkOnlyBuildSection(project); !ok || err != nil { return false, err } bindMounts := s.checkForBindMount(project) if len(bindMounts) > 0 { b := strings.Builder{} b.WriteString("you are about to publish bind mounts declaration within your OCI artifact.\n" + "only the bind mount declarations will be added to the OCI artifact (not content)\n" + "please double check that you are not mounting potential user's sensitive directories or data\n") for key, val := range bindMounts { b.WriteString(key) for _, v := range val { b.WriteString(v.String()) b.WriteRune('\n') } } b.WriteString("Are you ok to publish these bind mount declarations?") confirm, err := s.prompt(b.String(), false) if err != nil || !confirm { return false, err } } detectedSecrets, err := s.checkForSensitiveData(project) if err != nil { return false, err } if len(detectedSecrets) > 0 { b := strings.Builder{} b.WriteString("you are about to publish sensitive data within your OCI artifact.\n" + "please double check that you are not leaking sensitive data\n") for _, val := range detectedSecrets { b.WriteString(val.Type) b.WriteRune('\n') b.WriteString(fmt.Sprintf("%q: %s\n", val.Key, val.Value)) } b.WriteString("Are you ok to publish these sensitive data?") confirm, err := s.prompt(b.String(), false) if err != nil || !confirm { return false, err } } err = s.checkEnvironmentVariables(project, options) if err != nil { return false, err } return true, nil } func (s *composeService) checkEnvironmentVariables(project *types.Project, options api.PublishOptions) error { errorList := map[string][]string{} for _, service := range project.Services { if len(service.EnvFiles) > 0 { errorList[service.Name] = append(errorList[service.Name], fmt.Sprintf("service %q has env_file declared.", service.Name)) } } if !options.WithEnvironment && len(errorList) > 0 { errorMsgSuffix := "To avoid leaking sensitive data, you must either explicitly allow the sending of environment variables by using the --with-env flag,\n" + "or remove sensitive data from your Compose configuration" var errorMsg strings.Builder for _, errors := range errorList { for _, err := range errors { errorMsg.WriteString(fmt.Sprintf("%s\n", err)) } } return fmt.Errorf("%s%s", errorMsg.String(), errorMsgSuffix) } return nil } func envFileLayers(files map[string]string) []v1.Descriptor { var layers []v1.Descriptor for file, hash := range files { f, err := os.ReadFile(file) if err != nil { // if we can't read the file, skip to the next one continue } layerDescriptor := oci.DescriptorForEnvFile(hash, f) layers = append(layers, layerDescriptor) } return layers } func (s *composeService) checkOnlyBuildSection(project *types.Project) (bool, error) { errorList := []string{} for _, service := range project.Services { if service.Image == "" && service.Build != nil { errorList = append(errorList, service.Name) } } if len(errorList) > 0 { var errMsg strings.Builder errMsg.WriteString("your Compose stack cannot be published as it only contains a build section for service(s):\n") for _, serviceInError := range errorList { errMsg.WriteString(fmt.Sprintf("- %q\n", serviceInError)) } return false, errors.New(errMsg.String()) } return true, nil } func (s *composeService) checkForBindMount(project *types.Project) map[string][]types.ServiceVolumeConfig { allFindings := map[string][]types.ServiceVolumeConfig{} for serviceName, config := range project.Services { bindMounts := []types.ServiceVolumeConfig{} for _, volume := range config.Volumes { if volume.Type == types.VolumeTypeBind { bindMounts = append(bindMounts, volume) } } if len(bindMounts) > 0 { allFindings[serviceName] = bindMounts } } return allFindings } func (s *composeService) checkForSensitiveData(project *types.Project) ([]secrets.DetectedSecret, error) { var allFindings []secrets.DetectedSecret scan := scanner.NewDefaultScanner() // Check all compose files for _, file := range project.ComposeFiles { in, err := composeFileAsByteReader(file, project) if err != nil { return nil, err } findings, err := scan.ScanReader(in) if err != nil { return nil, fmt.Errorf("failed to scan compose file %s: %w", file, err) } allFindings = append(allFindings, findings...) } for _, service := range project.Services { // Check env files for _, envFile := range service.EnvFiles { findings, err := scan.ScanFile(envFile.Path) if err != nil { return nil, fmt.Errorf("failed to scan env file %s: %w", envFile.Path, err) } allFindings = append(allFindings, findings...) } } // Check configs defined by files for _, config := range project.Configs { if config.File != "" { findings, err := scan.ScanFile(config.File) if err != nil { return nil, fmt.Errorf("failed to scan config file %s: %w", config.File, err) } allFindings = append(allFindings, findings...) } } // Check secrets defined by files for _, secret := range project.Secrets { if secret.File != "" { findings, err := scan.ScanFile(secret.File) if err != nil { return nil, fmt.Errorf("failed to scan secret file %s: %w", secret.File, err) } allFindings = append(allFindings, findings...) } } return allFindings, nil } func composeFileAsByteReader(filePath string, project *types.Project) (io.Reader, error) { composeFile, err := os.ReadFile(filePath) if err != nil { return nil, fmt.Errorf("failed to open compose file %s: %w", filePath, err) } base, err := loader.LoadWithContext(context.TODO(), types.ConfigDetails{ WorkingDir: project.WorkingDir, Environment: project.Environment, ConfigFiles: []types.ConfigFile{ { Filename: filePath, Content: composeFile, }, }, }, func(options *loader.Options) { options.SkipValidation = true options.SkipExtends = true options.SkipConsistencyCheck = true options.ResolvePaths = true options.SkipInterpolation = true options.SkipResolveEnvironment = true }) if err != nil { return nil, err } in, err := base.MarshalYAML() if err != nil { return nil, err } return bytes.NewBuffer(in), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/printer.go
pkg/compose/printer.go
/* 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 ( "fmt" "github.com/docker/compose/v5/pkg/api" ) // logPrinter watch application containers and collect their logs type logPrinter interface { HandleEvent(event api.ContainerEvent) } type printer struct { consumer api.LogConsumer } // newLogPrinter builds a LogPrinter passing containers logs to LogConsumer func newLogPrinter(consumer api.LogConsumer) logPrinter { printer := printer{ consumer: consumer, } return &printer } func (p *printer) HandleEvent(event api.ContainerEvent) { switch event.Type { case api.ContainerEventExited: if event.Restarting { p.consumer.Status(event.Source, fmt.Sprintf("exited with code %d (restarting)", event.ExitCode)) } else { p.consumer.Status(event.Source, fmt.Sprintf("exited with code %d", event.ExitCode)) } case api.ContainerEventRecreated: p.consumer.Status(event.Container.Labels[api.ContainerReplaceLabel], "has been recreated") case api.ContainerEventLog, api.HookEventLog: p.consumer.Log(event.Source, event.Line) case api.ContainerEventErr: p.consumer.Err(event.Source, event.Line) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/images.go
pkg/compose/images.go
/* 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" "fmt" "slices" "strings" "sync" "time" "github.com/containerd/errdefs" "github.com/containerd/platforms" "github.com/distribution/reference" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/client" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Images(ctx context.Context, projectName string, options api.ImagesOptions) (map[string]api.ImageSummary, error) { projectName = strings.ToLower(projectName) allContainers, err := s.apiClient().ContainerList(ctx, container.ListOptions{ All: true, Filters: filters.NewArgs(projectFilter(projectName)), }) if err != nil { return nil, err } var containers []container.Summary if len(options.Services) > 0 { // filter service containers for _, c := range allContainers { if slices.Contains(options.Services, c.Labels[api.ServiceLabel]) { containers = append(containers, c) } } } else { containers = allContainers } version, err := s.RuntimeVersion(ctx) if err != nil { return nil, err } withPlatform := versions.GreaterThanOrEqualTo(version, "1.49") summary := map[string]api.ImageSummary{} var mux sync.Mutex eg, ctx := errgroup.WithContext(ctx) for _, c := range containers { eg.Go(func() error { image, err := s.apiClient().ImageInspect(ctx, c.Image) if err != nil { return err } id := image.ID // platform-specific image ID can't be combined with image tag, see https://github.com/moby/moby/issues/49995 if withPlatform && c.ImageManifestDescriptor != nil && c.ImageManifestDescriptor.Platform != nil { image, err = s.apiClient().ImageInspect(ctx, c.Image, client.ImageInspectWithPlatform(c.ImageManifestDescriptor.Platform)) if err != nil { return err } } var repository, tag string ref, err := reference.ParseDockerRef(c.Image) if err == nil { // ParseDockerRef will reject a local image ID repository = reference.FamiliarName(ref) if tagged, ok := ref.(reference.Tagged); ok { tag = tagged.Tag() } } var created *time.Time if image.Created != "" { t, err := time.Parse(time.RFC3339Nano, image.Created) if err != nil { return err } created = &t } mux.Lock() defer mux.Unlock() summary[getCanonicalContainerName(c)] = api.ImageSummary{ ID: id, Repository: repository, Tag: tag, Platform: platforms.Platform{ Architecture: image.Architecture, OS: image.Os, OSVersion: image.OsVersion, Variant: image.Variant, }, Size: image.Size, Created: created, LastTagTime: image.Metadata.LastTagTime, } return nil }) } err = eg.Wait() return summary, err } func (s *composeService) getImageSummaries(ctx context.Context, repoTags []string) (map[string]api.ImageSummary, error) { summary := map[string]api.ImageSummary{} l := sync.Mutex{} eg, ctx := errgroup.WithContext(ctx) for _, repoTag := range repoTags { eg.Go(func() error { inspect, err := s.apiClient().ImageInspect(ctx, repoTag) if err != nil { if errdefs.IsNotFound(err) { return nil } return fmt.Errorf("unable to get image '%s': %w", repoTag, err) } tag := "" repository := "" ref, err := reference.ParseDockerRef(repoTag) if err == nil { // ParseDockerRef will reject a local image ID repository = reference.FamiliarName(ref) if tagged, ok := ref.(reference.Tagged); ok { tag = tagged.Tag() } } l.Lock() summary[repoTag] = api.ImageSummary{ ID: inspect.ID, Repository: repository, Tag: tag, Size: inspect.Size, LastTagTime: inspect.Metadata.LastTagTime, } l.Unlock() return nil }) } return summary, eg.Wait() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/convergence_test.go
pkg/compose/convergence_test.go
/* 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" "fmt" "strings" "testing" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/config/configfile" moby "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/network" "github.com/docker/go-connections/nat" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/mocks" ) func TestContainerName(t *testing.T) { s := types.ServiceConfig{ Name: "testservicename", ContainerName: "testcontainername", Scale: intPtr(1), Deploy: &types.DeployConfig{}, } ret, err := getScale(s) assert.NilError(t, err) assert.Equal(t, ret, *s.Scale) s.Scale = intPtr(0) ret, err = getScale(s) assert.NilError(t, err) assert.Equal(t, ret, *s.Scale) s.Scale = intPtr(2) _, err = getScale(s) assert.Error(t, err, fmt.Sprintf(doubledContainerNameWarning, s.Name, s.ContainerName)) } func intPtr(i int) *int { return &i } func TestServiceLinks(t *testing.T) { const dbContainerName = "/" + testProject + "-db-1" const webContainerName = "/" + testProject + "-web-1" s := types.ServiceConfig{ Name: "web", Scale: intPtr(1), } containerListOptions := container.ListOptions{ Filters: filters.NewArgs( projectFilter(testProject), serviceFilter("db"), oneOffFilter(false), hasConfigHashLabel(), ), All: true, } t.Run("service links default", func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() s.Links = []string{"db"} c := testContainer("db", dbContainerName, false) apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil) links, err := tested.(*composeService).getLinks(context.Background(), testProject, s, 1) assert.NilError(t, err) assert.Equal(t, len(links), 3) assert.Equal(t, links[0], "testProject-db-1:db") assert.Equal(t, links[1], "testProject-db-1:db-1") assert.Equal(t, links[2], "testProject-db-1:testProject-db-1") }) t.Run("service links", func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() s.Links = []string{"db:db"} c := testContainer("db", dbContainerName, false) apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil) links, err := tested.(*composeService).getLinks(context.Background(), testProject, s, 1) assert.NilError(t, err) assert.Equal(t, len(links), 3) assert.Equal(t, links[0], "testProject-db-1:db") assert.Equal(t, links[1], "testProject-db-1:db-1") assert.Equal(t, links[2], "testProject-db-1:testProject-db-1") }) t.Run("service links name", func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() s.Links = []string{"db:dbname"} c := testContainer("db", dbContainerName, false) apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil) links, err := tested.(*composeService).getLinks(context.Background(), testProject, s, 1) assert.NilError(t, err) assert.Equal(t, len(links), 3) assert.Equal(t, links[0], "testProject-db-1:dbname") assert.Equal(t, links[1], "testProject-db-1:db-1") assert.Equal(t, links[2], "testProject-db-1:testProject-db-1") }) t.Run("service links external links", func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() s.Links = []string{"db:dbname"} s.ExternalLinks = []string{"db1:db2"} c := testContainer("db", dbContainerName, false) apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil) links, err := tested.(*composeService).getLinks(context.Background(), testProject, s, 1) assert.NilError(t, err) assert.Equal(t, len(links), 4) assert.Equal(t, links[0], "testProject-db-1:dbname") assert.Equal(t, links[1], "testProject-db-1:db-1") assert.Equal(t, links[2], "testProject-db-1:testProject-db-1") // ExternalLink assert.Equal(t, links[3], "db1:db2") }) t.Run("service links itself oneoff", func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() s.Links = []string{} s.ExternalLinks = []string{} s.Labels = s.Labels.Add(api.OneoffLabel, "True") c := testContainer("web", webContainerName, true) containerListOptionsOneOff := container.ListOptions{ Filters: filters.NewArgs( projectFilter(testProject), serviceFilter("web"), oneOffFilter(false), hasConfigHashLabel(), ), All: true, } apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptionsOneOff).Return([]container.Summary{c}, nil) links, err := tested.(*composeService).getLinks(context.Background(), testProject, s, 1) assert.NilError(t, err) assert.Equal(t, len(links), 3) assert.Equal(t, links[0], "testProject-web-1:web") assert.Equal(t, links[1], "testProject-web-1:web-1") assert.Equal(t, links[2], "testProject-web-1:testProject-web-1") }) } func TestWaitDependencies(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() t.Run("should skip dependencies with scale 0", func(t *testing.T) { dbService := types.ServiceConfig{Name: "db", Scale: intPtr(0)} redisService := types.ServiceConfig{Name: "redis", Scale: intPtr(0)} project := types.Project{Name: strings.ToLower(testProject), Services: types.Services{ "db": dbService, "redis": redisService, }} dependencies := types.DependsOnConfig{ "db": {Condition: ServiceConditionRunningOrHealthy}, "redis": {Condition: ServiceConditionRunningOrHealthy}, } assert.NilError(t, tested.(*composeService).waitDependencies(context.Background(), &project, "", dependencies, nil, 0)) }) t.Run("should skip dependencies with condition service_started", func(t *testing.T) { dbService := types.ServiceConfig{Name: "db", Scale: intPtr(1)} redisService := types.ServiceConfig{Name: "redis", Scale: intPtr(1)} project := types.Project{Name: strings.ToLower(testProject), Services: types.Services{ "db": dbService, "redis": redisService, }} dependencies := types.DependsOnConfig{ "db": {Condition: types.ServiceConditionStarted, Required: true}, "redis": {Condition: types.ServiceConditionStarted, Required: true}, } assert.NilError(t, tested.(*composeService).waitDependencies(context.Background(), &project, "", dependencies, nil, 0)) }) } func TestCreateMobyContainer(t *testing.T) { t.Run("connects container networks one by one if API <1.44", func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() cli.EXPECT().ConfigFile().Return(&configfile.ConfigFile{}).AnyTimes() apiClient.EXPECT().DaemonHost().Return("").AnyTimes() apiClient.EXPECT().ImageInspect(gomock.Any(), gomock.Any()).Return(image.InspectResponse{}, nil).AnyTimes() // force `RuntimeVersion` to fetch again runtimeVersion = runtimeVersionCache{} apiClient.EXPECT().ServerVersion(gomock.Any()).Return(moby.Version{ APIVersion: "1.43", }, nil).AnyTimes() service := types.ServiceConfig{ Name: "test", Networks: map[string]*types.ServiceNetworkConfig{ "a": { Priority: 10, }, "b": { Priority: 100, }, }, } project := types.Project{ Name: "bork", Services: types.Services{ "test": service, }, Networks: types.Networks{ "a": types.NetworkConfig{ Name: "a-moby-name", }, "b": types.NetworkConfig{ Name: "b-moby-name", }, }, } var falseBool bool apiClient.EXPECT().ContainerCreate(gomock.Any(), gomock.Any(), gomock.Eq( &container.HostConfig{ PortBindings: nat.PortMap{}, ExtraHosts: []string{}, Tmpfs: map[string]string{}, Resources: container.Resources{ OomKillDisable: &falseBool, }, NetworkMode: "b-moby-name", }), gomock.Eq( &network.NetworkingConfig{ EndpointsConfig: map[string]*network.EndpointSettings{ "b-moby-name": { IPAMConfig: &network.EndpointIPAMConfig{}, Aliases: []string{"bork-test-0"}, }, }, }), gomock.Any(), gomock.Any()).Times(1).Return( container.CreateResponse{ ID: "an-id", }, nil) apiClient.EXPECT().ContainerInspect(gomock.Any(), gomock.Eq("an-id")).Times(1).Return( container.InspectResponse{ ContainerJSONBase: &container.ContainerJSONBase{ ID: "an-id", Name: "a-name", }, Config: &container.Config{}, NetworkSettings: &container.NetworkSettings{}, }, nil) apiClient.EXPECT().NetworkConnect(gomock.Any(), "a-moby-name", "an-id", gomock.Eq( &network.EndpointSettings{ IPAMConfig: &network.EndpointIPAMConfig{}, Aliases: []string{"bork-test-0"}, })) _, err = tested.(*composeService).createMobyContainer(context.Background(), &project, service, "test", 0, nil, createOptions{ Labels: make(types.Labels), }) assert.NilError(t, err) }) t.Run("includes all container networks in ContainerCreate call if API >=1.44", func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() apiClient := mocks.NewMockAPIClient(mockCtrl) cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) cli.EXPECT().Client().Return(apiClient).AnyTimes() cli.EXPECT().ConfigFile().Return(&configfile.ConfigFile{}).AnyTimes() apiClient.EXPECT().DaemonHost().Return("").AnyTimes() apiClient.EXPECT().ImageInspect(gomock.Any(), gomock.Any()).Return(image.InspectResponse{}, nil).AnyTimes() // force `RuntimeVersion` to fetch fresh version runtimeVersion = runtimeVersionCache{} apiClient.EXPECT().ServerVersion(gomock.Any()).Return(moby.Version{ APIVersion: "1.44", }, nil).AnyTimes() service := types.ServiceConfig{ Name: "test", Networks: map[string]*types.ServiceNetworkConfig{ "a": { Priority: 10, }, "b": { Priority: 100, }, }, } project := types.Project{ Name: "bork", Services: types.Services{ "test": service, }, Networks: types.Networks{ "a": types.NetworkConfig{ Name: "a-moby-name", }, "b": types.NetworkConfig{ Name: "b-moby-name", }, }, } var falseBool bool apiClient.EXPECT().ContainerCreate(gomock.Any(), gomock.Any(), gomock.Eq( &container.HostConfig{ PortBindings: nat.PortMap{}, ExtraHosts: []string{}, Tmpfs: map[string]string{}, Resources: container.Resources{ OomKillDisable: &falseBool, }, NetworkMode: "b-moby-name", }), gomock.Eq( &network.NetworkingConfig{ EndpointsConfig: map[string]*network.EndpointSettings{ "a-moby-name": { IPAMConfig: &network.EndpointIPAMConfig{}, Aliases: []string{"bork-test-0"}, }, "b-moby-name": { IPAMConfig: &network.EndpointIPAMConfig{}, Aliases: []string{"bork-test-0"}, }, }, }), gomock.Any(), gomock.Any()).Times(1).Return( container.CreateResponse{ ID: "an-id", }, nil) apiClient.EXPECT().ContainerInspect(gomock.Any(), gomock.Eq("an-id")).Times(1).Return( container.InspectResponse{ ContainerJSONBase: &container.ContainerJSONBase{ ID: "an-id", Name: "a-name", }, Config: &container.Config{}, NetworkSettings: &container.NetworkSettings{}, }, nil) _, err = tested.(*composeService).createMobyContainer(context.Background(), &project, service, "test", 0, nil, createOptions{ Labels: make(types.Labels), }) assert.NilError(t, err) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/ls_test.go
pkg/compose/ls_test.go
/* 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 ( "fmt" "testing" "github.com/docker/docker/api/types/container" "gotest.tools/v3/assert" "github.com/docker/compose/v5/pkg/api" ) func TestContainersToStacks(t *testing.T) { containers := []container.Summary{ { ID: "service1", State: "running", Labels: map[string]string{api.ProjectLabel: "project1", api.ConfigFilesLabel: "/home/docker-compose.yaml"}, }, { ID: "service2", State: "running", Labels: map[string]string{api.ProjectLabel: "project1", api.ConfigFilesLabel: "/home/docker-compose.yaml"}, }, { ID: "service3", State: "running", Labels: map[string]string{api.ProjectLabel: "project2", api.ConfigFilesLabel: "/home/project2-docker-compose.yaml"}, }, } stacks, err := containersToStacks(containers) assert.NilError(t, err) assert.DeepEqual(t, stacks, []api.Stack{ { ID: "project1", Name: "project1", Status: "running(2)", ConfigFiles: "/home/docker-compose.yaml", }, { ID: "project2", Name: "project2", Status: "running(1)", ConfigFiles: "/home/project2-docker-compose.yaml", }, }) } func TestStacksMixedStatus(t *testing.T) { assert.Equal(t, combinedStatus([]string{"running"}), "running(1)") assert.Equal(t, combinedStatus([]string{"running", "running", "running"}), "running(3)") assert.Equal(t, combinedStatus([]string{"running", "exited", "running"}), "exited(1), running(2)") } func TestCombinedConfigFiles(t *testing.T) { containersByLabel := map[string][]container.Summary{ "project1": { { ID: "service1", State: "running", Labels: map[string]string{api.ProjectLabel: "project1", api.ConfigFilesLabel: "/home/docker-compose.yaml"}, }, { ID: "service2", State: "running", Labels: map[string]string{api.ProjectLabel: "project1", api.ConfigFilesLabel: "/home/docker-compose.yaml"}, }, }, "project2": { { ID: "service3", State: "running", Labels: map[string]string{api.ProjectLabel: "project2", api.ConfigFilesLabel: "/home/project2-docker-compose.yaml"}, }, }, "project3": { { ID: "service4", State: "running", Labels: map[string]string{api.ProjectLabel: "project3"}, }, }, } testData := map[string]struct { ConfigFiles string Error error }{ "project1": {ConfigFiles: "/home/docker-compose.yaml", Error: nil}, "project2": {ConfigFiles: "/home/project2-docker-compose.yaml", Error: nil}, "project3": {ConfigFiles: "", Error: fmt.Errorf("no label %q set on container %q of compose project", api.ConfigFilesLabel, "service4")}, } for project, containers := range containersByLabel { configFiles, err := combinedConfigFiles(containers) expected := testData[project] if expected.Error != nil { assert.Error(t, err, expected.Error.Error()) } else { assert.Equal(t, err, expected.Error) } assert.Equal(t, configFiles, expected.ConfigFiles) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/plugins.go
pkg/compose/plugins.go
/* 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 ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "strings" "sync" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" "github.com/docker/cli/cli-plugins/manager" "github.com/docker/cli/cli/config" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" ) type JsonMessage struct { Type string `json:"type"` Message string `json:"message"` } const ( ErrorType = "error" InfoType = "info" SetEnvType = "setenv" DebugType = "debug" providerMetadataDirectory = "compose/providers" ) var mux sync.Mutex func (s *composeService) runPlugin(ctx context.Context, project *types.Project, service types.ServiceConfig, command string) error { provider := *service.Provider plugin, err := s.getPluginBinaryPath(provider.Type) if err != nil { return err } cmd, err := s.setupPluginCommand(ctx, project, service, plugin, command) if err != nil { return err } variables, err := s.executePlugin(cmd, command, service) if err != nil { return err } mux.Lock() defer mux.Unlock() for name, s := range project.Services { if _, ok := s.DependsOn[service.Name]; ok { prefix := strings.ToUpper(service.Name) + "_" for key, val := range variables { s.Environment[prefix+key] = &val } project.Services[name] = s } } return nil } func (s *composeService) executePlugin(cmd *exec.Cmd, command string, service types.ServiceConfig) (types.Mapping, error) { var action string switch command { case "up": s.events.On(creatingEvent(service.Name)) action = "create" case "down": s.events.On(removingEvent(service.Name)) action = "remove" default: return nil, fmt.Errorf("unsupported plugin command: %s", command) } stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } err = cmd.Start() if err != nil { return nil, err } decoder := json.NewDecoder(stdout) defer func() { _ = stdout.Close() }() variables := types.Mapping{} for { var msg JsonMessage err = decoder.Decode(&msg) if errors.Is(err, io.EOF) { break } if err != nil { return nil, err } switch msg.Type { case ErrorType: s.events.On(newEvent(service.Name, api.Error, msg.Message)) return nil, errors.New(msg.Message) case InfoType: s.events.On(newEvent(service.Name, api.Working, msg.Message)) case SetEnvType: key, val, found := strings.Cut(msg.Message, "=") if !found { return nil, fmt.Errorf("invalid response from plugin: %s", msg.Message) } variables[key] = val case DebugType: logrus.Debugf("%s: %s", service.Name, msg.Message) default: return nil, fmt.Errorf("invalid response from plugin: %s", msg.Type) } } err = cmd.Wait() if err != nil { s.events.On(errorEvent(service.Name, err.Error())) return nil, fmt.Errorf("failed to %s service provider: %s", action, err.Error()) } switch command { case "up": s.events.On(createdEvent(service.Name)) case "down": s.events.On(removedEvent(service.Name)) } return variables, nil } func (s *composeService) getPluginBinaryPath(provider string) (path string, err error) { if provider == "compose" { return "", errors.New("'compose' is not a valid provider type") } plugin, err := manager.GetPlugin(provider, s.dockerCli, &cobra.Command{}) if err == nil { path = plugin.Path } if errdefs.IsNotFound(err) { path, err = exec.LookPath(executable(provider)) } return path, err } func (s *composeService) setupPluginCommand(ctx context.Context, project *types.Project, service types.ServiceConfig, path, command string) (*exec.Cmd, error) { cmdOptionsMetadata := s.getPluginMetadata(path, service.Provider.Type, project) var currentCommandMetadata CommandMetadata switch command { case "up": currentCommandMetadata = cmdOptionsMetadata.Up case "down": currentCommandMetadata = cmdOptionsMetadata.Down } provider := *service.Provider commandMetadataIsEmpty := cmdOptionsMetadata.IsEmpty() if err := currentCommandMetadata.CheckRequiredParameters(provider); !commandMetadataIsEmpty && err != nil { return nil, err } args := []string{"compose", fmt.Sprintf("--project-name=%s", project.Name), command} for k, v := range provider.Options { for _, value := range v { if _, ok := currentCommandMetadata.GetParameter(k); commandMetadataIsEmpty || ok { args = append(args, fmt.Sprintf("--%s=%s", k, value)) } } } args = append(args, service.Name) cmd := exec.CommandContext(ctx, path, args...) err := s.prepareShellOut(ctx, project.Environment, cmd) if err != nil { return nil, err } return cmd, nil } func (s *composeService) getPluginMetadata(path, command string, project *types.Project) ProviderMetadata { cmd := exec.Command(path, "compose", "metadata") err := s.prepareShellOut(context.Background(), project.Environment, cmd) if err != nil { logrus.Debugf("failed to prepare plugin metadata command: %v", err) return ProviderMetadata{} } stdout := &bytes.Buffer{} cmd.Stdout = stdout if err := cmd.Run(); err != nil { logrus.Debugf("failed to start plugin metadata command: %v", err) return ProviderMetadata{} } var metadata ProviderMetadata if err := json.Unmarshal(stdout.Bytes(), &metadata); err != nil { output, _ := io.ReadAll(stdout) logrus.Debugf("failed to decode plugin metadata: %v - %s", err, output) return ProviderMetadata{} } // Save metadata into docker home directory to be used by Docker LSP tool // Just log the error as it's not a critical error for the main flow metadataDir := filepath.Join(config.Dir(), providerMetadataDirectory) if err := os.MkdirAll(metadataDir, 0o700); err == nil { metadataFilePath := filepath.Join(metadataDir, command+".json") if err := os.WriteFile(metadataFilePath, stdout.Bytes(), 0o600); err != nil { logrus.Debugf("failed to save plugin metadata: %v", err) } } else { logrus.Debugf("failed to create plugin metadata directory: %v", err) } return metadata } type ProviderMetadata struct { Description string `json:"description"` Up CommandMetadata `json:"up"` Down CommandMetadata `json:"down"` } func (p ProviderMetadata) IsEmpty() bool { return p.Description == "" && p.Up.Parameters == nil && p.Down.Parameters == nil } type CommandMetadata struct { Parameters []ParameterMetadata `json:"parameters"` } type ParameterMetadata struct { Name string `json:"name"` Description string `json:"description"` Required bool `json:"required"` Type string `json:"type"` Default string `json:"default,omitempty"` } func (c CommandMetadata) GetParameter(paramName string) (ParameterMetadata, bool) { for _, p := range c.Parameters { if p.Name == paramName { return p, true } } return ParameterMetadata{}, false } func (c CommandMetadata) CheckRequiredParameters(provider types.ServiceProviderConfig) error { for _, p := range c.Parameters { if p.Required { if _, ok := provider.Options[p.Name]; !ok { return fmt.Errorf("required parameter %q is missing from provider %q definition", p.Name, provider.Type) } } } return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/apiSocket.go
pkg/compose/apiSocket.go
/* 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 ( "bytes" "errors" "fmt" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/config/configfile" ) // --use-api-socket is not actually supported by the Docker Engine // but is a client-side hack (see https://github.com/docker/cli/blob/master/cli/command/container/create.go#L246) // we replicate here by transforming the project model func (s *composeService) useAPISocket(project *types.Project) (*types.Project, error) { useAPISocket := false for _, service := range project.Services { if service.UseAPISocket { useAPISocket = true break } } if !useAPISocket { return project, nil } if s.getContextInfo().ServerOSType() == "windows" { return nil, errors.New("use_api_socket can't be used with a Windows Docker Engine") } creds, err := s.configFile().GetAllCredentials() if err != nil { return nil, fmt.Errorf("resolving credentials failed: %w", err) } newConfig := &configfile.ConfigFile{ AuthConfigs: creds, } var configBuf bytes.Buffer if err := newConfig.SaveToWriter(&configBuf); err != nil { return nil, fmt.Errorf("saving creds for API socket: %w", err) } project.Configs["#apisocket"] = types.ConfigObjConfig{ Content: configBuf.String(), } for name, service := range project.Services { if !service.UseAPISocket { continue } service.Volumes = append(service.Volumes, types.ServiceVolumeConfig{ Type: types.VolumeTypeBind, Source: "/var/run/docker.sock", Target: "/var/run/docker.sock", }) _, envvarPresent := service.Environment["DOCKER_CONFIG"] // If the DOCKER_CONFIG env var is already present, we assume the client knows // what they're doing and don't inject the creds. if !envvarPresent { // Set our special little location for the config file. path := "/run/secrets/docker" service.Environment["DOCKER_CONFIG"] = &path } service.Configs = append(service.Configs, types.ServiceConfigObjConfig{ Source: "#apisocket", Target: "/run/secrets/docker/config.json", }) project.Services[name] = service } return project, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/hash_test.go
pkg/compose/hash_test.go
/* 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 ( "testing" "github.com/compose-spec/compose-go/v2/types" "gotest.tools/v3/assert" ) func TestServiceHash(t *testing.T) { hash1, err := ServiceHash(serviceConfig(1)) assert.NilError(t, err) hash2, err := ServiceHash(serviceConfig(2)) assert.NilError(t, err) assert.Equal(t, hash1, hash2) } func serviceConfig(replicas int) types.ServiceConfig { return types.ServiceConfig{ Scale: &replicas, Deploy: &types.DeployConfig{ Replicas: &replicas, }, Name: "foo", Image: "bar", } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/top.go
pkg/compose/top.go
/* 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" "strings" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Top(ctx context.Context, projectName string, services []string) ([]api.ContainerProcSummary, error) { projectName = strings.ToLower(projectName) var containers Containers containers, err := s.getContainers(ctx, projectName, oneOffInclude, false) if err != nil { return nil, err } if len(services) > 0 { containers = containers.filter(isService(services...)) } summary := make([]api.ContainerProcSummary, len(containers)) eg, ctx := errgroup.WithContext(ctx) for i, ctr := range containers { eg.Go(func() error { topContent, err := s.apiClient().ContainerTop(ctx, ctr.ID, []string{}) if err != nil { return err } name := getCanonicalContainerName(ctr) s := api.ContainerProcSummary{ ID: ctr.ID, Name: name, Processes: topContent.Processes, Titles: topContent.Titles, Service: name, } if service, exists := ctr.Labels[api.ServiceLabel]; exists { s.Service = service } if replica, exists := ctr.Labels[api.ContainerNumberLabel]; exists { s.Replica = replica } summary[i] = s return nil }) } return summary, eg.Wait() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/watch.go
pkg/compose/watch.go
/* 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" "io" "io/fs" "os" "path" "path/filepath" "slices" "strconv" "strings" gsync "sync" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/compose-spec/compose-go/v2/utils" ccli "github.com/docker/cli/cli/command/container" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/go-viper/mapstructure/v2" "github.com/moby/buildkit/util/progress/progressui" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" pathutil "github.com/docker/compose/v5/internal/paths" "github.com/docker/compose/v5/internal/sync" "github.com/docker/compose/v5/internal/tracing" "github.com/docker/compose/v5/pkg/api" cutils "github.com/docker/compose/v5/pkg/utils" "github.com/docker/compose/v5/pkg/watch" ) type WatchFunc func(ctx context.Context, project *types.Project, options api.WatchOptions) (func() error, error) type Watcher struct { project *types.Project options api.WatchOptions watchFn WatchFunc stopFn func() errCh chan error } func NewWatcher(project *types.Project, options api.UpOptions, w WatchFunc, consumer api.LogConsumer) (*Watcher, error) { for i := range project.Services { service := project.Services[i] if service.Develop != nil && service.Develop.Watch != nil { build := options.Create.Build return &Watcher{ project: project, options: api.WatchOptions{ LogTo: consumer, Build: build, }, watchFn: w, errCh: make(chan error), }, nil } } // none of the services is eligible to watch return nil, fmt.Errorf("none of the selected services is configured for watch, see https://docs.docker.com/compose/how-tos/file-watch/") } // ensure state changes are atomic var mx gsync.Mutex func (w *Watcher) Start(ctx context.Context) error { mx.Lock() defer mx.Unlock() ctx, cancelFunc := context.WithCancel(ctx) w.stopFn = cancelFunc wait, err := w.watchFn(ctx, w.project, w.options) if err != nil { go func() { w.errCh <- err }() return err } go func() { w.errCh <- wait() }() return nil } func (w *Watcher) Stop() error { mx.Lock() defer mx.Unlock() if w.stopFn == nil { return nil } w.stopFn() w.stopFn = nil err := <-w.errCh return err } // getSyncImplementation returns an appropriate sync implementation for the // project. // // Currently, an implementation that batches files and transfers them using // the Moby `Untar` API. func (s *composeService) getSyncImplementation(project *types.Project) (sync.Syncer, error) { var useTar bool if useTarEnv, ok := os.LookupEnv("COMPOSE_EXPERIMENTAL_WATCH_TAR"); ok { useTar, _ = strconv.ParseBool(useTarEnv) } else { useTar = true } if !useTar { return nil, errors.New("no available sync implementation") } return sync.NewTar(project.Name, tarDockerClient{s: s}), nil } func (s *composeService) Watch(ctx context.Context, project *types.Project, options api.WatchOptions) error { wait, err := s.watch(ctx, project, options) if err != nil { return err } return wait() } type watchRule struct { types.Trigger include watch.PathMatcher ignore watch.PathMatcher service string } func (r watchRule) Matches(event watch.FileEvent) *sync.PathMapping { hostPath := string(event) if !pathutil.IsChild(r.Path, hostPath) { return nil } included, err := r.include.Matches(hostPath) if err != nil { logrus.Warnf("error include matching %q: %v", hostPath, err) return nil } if !included { logrus.Debugf("%s is not matching include pattern", hostPath) return nil } isIgnored, err := r.ignore.Matches(hostPath) if err != nil { logrus.Warnf("error ignore matching %q: %v", hostPath, err) return nil } if isIgnored { logrus.Debugf("%s is matching ignore pattern", hostPath) return nil } var containerPath string if r.Target != "" { rel, err := filepath.Rel(r.Path, hostPath) if err != nil { logrus.Warnf("error making %s relative to %s: %v", hostPath, r.Path, err) return nil } // always use Unix-style paths for inside the container containerPath = path.Join(r.Target, filepath.ToSlash(rel)) } return &sync.PathMapping{ HostPath: hostPath, ContainerPath: containerPath, } } func (s *composeService) watch(ctx context.Context, project *types.Project, options api.WatchOptions) (func() error, error) { //nolint: gocyclo var err error if project, err = project.WithSelectedServices(options.Services); err != nil { return nil, err } syncer, err := s.getSyncImplementation(project) if err != nil { return nil, err } eg, ctx := errgroup.WithContext(ctx) var ( rules []watchRule paths []string ) for serviceName, service := range project.Services { config, err := loadDevelopmentConfig(service, project) if err != nil { return nil, err } if service.Develop != nil { config = service.Develop } if config == nil { continue } for _, trigger := range config.Watch { if trigger.Action == types.WatchActionRebuild { if service.Build == nil { return nil, fmt.Errorf("can't watch service %q with action %s without a build context", service.Name, types.WatchActionRebuild) } if options.Build == nil { return nil, fmt.Errorf("--no-build is incompatible with watch action %s in service %s", types.WatchActionRebuild, service.Name) } // set the service to always be built - watch triggers `Up()` when it receives a rebuild event service.PullPolicy = types.PullPolicyBuild project.Services[serviceName] = service } } for _, trigger := range config.Watch { if isSync(trigger) && checkIfPathAlreadyBindMounted(trigger.Path, service.Volumes) { logrus.Warnf("path '%s' also declared by a bind mount volume, this path won't be monitored!\n", trigger.Path) continue } else { shouldInitialSync := trigger.InitialSync // Check legacy extension attribute for backward compatibility if !shouldInitialSync { var legacyInitialSync bool success, err := trigger.Extensions.Get("x-initialSync", &legacyInitialSync) if err == nil && success && legacyInitialSync { shouldInitialSync = true logrus.Warnf("x-initialSync is DEPRECATED, please use the official `initial_sync` attribute\n") } } if shouldInitialSync && isSync(trigger) { // Need to check initial files are in container that are meant to be synced from watch action err := s.initialSync(ctx, project, service, trigger, syncer) if err != nil { return nil, err } } } paths = append(paths, trigger.Path) } serviceWatchRules, err := getWatchRules(config, service) if err != nil { return nil, err } rules = append(rules, serviceWatchRules...) } if len(paths) == 0 { return nil, fmt.Errorf("none of the selected services is configured for watch, consider setting a 'develop' section") } watcher, err := watch.NewWatcher(paths) if err != nil { return nil, err } err = watcher.Start() if err != nil { return nil, err } eg.Go(func() error { return s.watchEvents(ctx, project, options, watcher, syncer, rules) }) options.LogTo.Log(api.WatchLogger, "Watch enabled") return func() error { err := eg.Wait() if werr := watcher.Close(); werr != nil { logrus.Debugf("Error closing Watcher: %v", werr) } return err }, nil } func getWatchRules(config *types.DevelopConfig, service types.ServiceConfig) ([]watchRule, error) { var rules []watchRule dockerIgnores, err := watch.LoadDockerIgnore(service.Build) if err != nil { return nil, err } // add a hardcoded set of ignores on top of what came from .dockerignore // some of this should likely be configurable (e.g. there could be cases // where you want `.git` to be synced) but this is suitable for now dotGitIgnore, err := watch.NewDockerPatternMatcher("/", []string{".git/"}) if err != nil { return nil, err } for _, trigger := range config.Watch { ignore, err := watch.NewDockerPatternMatcher(trigger.Path, trigger.Ignore) if err != nil { return nil, err } var include watch.PathMatcher if len(trigger.Include) == 0 { include = watch.AnyMatcher{} } else { include, err = watch.NewDockerPatternMatcher(trigger.Path, trigger.Include) if err != nil { return nil, err } } rules = append(rules, watchRule{ Trigger: trigger, include: include, ignore: watch.NewCompositeMatcher( dockerIgnores, watch.EphemeralPathMatcher(), dotGitIgnore, ignore, ), service: service.Name, }) } return rules, nil } func isSync(trigger types.Trigger) bool { return trigger.Action == types.WatchActionSync || trigger.Action == types.WatchActionSyncRestart } func (s *composeService) watchEvents(ctx context.Context, project *types.Project, options api.WatchOptions, watcher watch.Notify, syncer sync.Syncer, rules []watchRule) error { ctx, cancel := context.WithCancel(ctx) defer cancel() // debounce and group filesystem events so that we capture IDE saving many files as one "batch" event batchEvents := watch.BatchDebounceEvents(ctx, s.clock, watcher.Events()) for { select { case <-ctx.Done(): options.LogTo.Log(api.WatchLogger, "Watch disabled") return nil case err, open := <-watcher.Errors(): if err != nil { options.LogTo.Err(api.WatchLogger, "Watch disabled with errors: "+err.Error()) } if open { continue } return err case batch := <-batchEvents: start := time.Now() logrus.Debugf("batch start: count[%d]", len(batch)) err := s.handleWatchBatch(ctx, project, options, batch, rules, syncer) if err != nil { logrus.Warnf("Error handling changed files: %v", err) } logrus.Debugf("batch complete: duration[%s] count[%d]", time.Since(start), len(batch)) } } } func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (*types.DevelopConfig, error) { var config types.DevelopConfig y, ok := service.Extensions["x-develop"] if !ok { return nil, nil } logrus.Warnf("x-develop is DEPRECATED, please use the official `develop` attribute") err := mapstructure.Decode(y, &config) if err != nil { return nil, err } baseDir, err := filepath.EvalSymlinks(project.WorkingDir) if err != nil { return nil, fmt.Errorf("resolving symlink for %q: %w", project.WorkingDir, err) } for i, trigger := range config.Watch { if !filepath.IsAbs(trigger.Path) { trigger.Path = filepath.Join(baseDir, trigger.Path) } if p, err := filepath.EvalSymlinks(trigger.Path); err == nil { // this might fail because the path doesn't exist, etc. trigger.Path = p } trigger.Path = filepath.Clean(trigger.Path) if trigger.Path == "" { return nil, errors.New("watch rules MUST define a path") } if trigger.Action == types.WatchActionRebuild && service.Build == nil { return nil, fmt.Errorf("service %s doesn't have a build section, can't apply %s on watch", types.WatchActionRebuild, service.Name) } if trigger.Action == types.WatchActionSyncExec && len(trigger.Exec.Command) == 0 { return nil, fmt.Errorf("can't watch with action %q on service %s without a command", types.WatchActionSyncExec, service.Name) } config.Watch[i] = trigger } return &config, nil } func checkIfPathAlreadyBindMounted(watchPath string, volumes []types.ServiceVolumeConfig) bool { for _, volume := range volumes { if volume.Bind != nil { relPath, err := filepath.Rel(volume.Source, watchPath) if err == nil && !strings.HasPrefix(relPath, "..") { return true } } } return false } type tarDockerClient struct { s *composeService } func (t tarDockerClient) ContainersForService(ctx context.Context, projectName string, serviceName string) ([]container.Summary, error) { containers, err := t.s.getContainers(ctx, projectName, oneOffExclude, true, serviceName) if err != nil { return nil, err } return containers, nil } func (t tarDockerClient) Exec(ctx context.Context, containerID string, cmd []string, in io.Reader) error { execCfg := container.ExecOptions{ Cmd: cmd, AttachStdout: false, AttachStderr: true, AttachStdin: in != nil, Tty: false, } execCreateResp, err := t.s.apiClient().ContainerExecCreate(ctx, containerID, execCfg) if err != nil { return err } startCheck := container.ExecStartOptions{Tty: false, Detach: false} conn, err := t.s.apiClient().ContainerExecAttach(ctx, execCreateResp.ID, startCheck) if err != nil { return err } defer conn.Close() var eg errgroup.Group if in != nil { eg.Go(func() error { defer func() { _ = conn.CloseWrite() }() _, err := io.Copy(conn.Conn, in) return err }) } eg.Go(func() error { _, err := io.Copy(t.s.stdout(), conn.Reader) return err }) err = t.s.apiClient().ContainerExecStart(ctx, execCreateResp.ID, startCheck) if err != nil { return err } // although the errgroup is not tied directly to the context, the operations // in it are reading/writing to the connection, which is tied to the context, // so they won't block indefinitely if err := eg.Wait(); err != nil { return err } execResult, err := t.s.apiClient().ContainerExecInspect(ctx, execCreateResp.ID) if err != nil { return err } if execResult.Running { return errors.New("process still running") } if execResult.ExitCode != 0 { return fmt.Errorf("exit code %d", execResult.ExitCode) } return nil } func (t tarDockerClient) Untar(ctx context.Context, id string, archive io.ReadCloser) error { return t.s.apiClient().CopyToContainer(ctx, id, "/", archive, container.CopyToContainerOptions{ CopyUIDGID: true, }) } //nolint:gocyclo func (s *composeService) handleWatchBatch(ctx context.Context, project *types.Project, options api.WatchOptions, batch []watch.FileEvent, rules []watchRule, syncer sync.Syncer) error { var ( restart = map[string]bool{} syncfiles = map[string][]*sync.PathMapping{} exec = map[string][]int{} rebuild = map[string]bool{} ) for _, event := range batch { for i, rule := range rules { mapping := rule.Matches(event) if mapping == nil { continue } switch rule.Action { case types.WatchActionRebuild: rebuild[rule.service] = true case types.WatchActionSync: syncfiles[rule.service] = append(syncfiles[rule.service], mapping) case types.WatchActionRestart: restart[rule.service] = true case types.WatchActionSyncRestart: syncfiles[rule.service] = append(syncfiles[rule.service], mapping) restart[rule.service] = true case types.WatchActionSyncExec: syncfiles[rule.service] = append(syncfiles[rule.service], mapping) // We want to run exec hooks only once after syncfiles if multiple file events match // as we can't compare ServiceHook to sort and compact a slice, collect rule indexes exec[rule.service] = append(exec[rule.service], i) } } } logrus.Debugf("watch actions: rebuild %d sync %d restart %d", len(rebuild), len(syncfiles), len(restart)) if len(rebuild) > 0 { err := s.rebuild(ctx, project, utils.MapKeys(rebuild), options) if err != nil { return err } } for serviceName, pathMappings := range syncfiles { writeWatchSyncMessage(options.LogTo, serviceName, pathMappings) err := syncer.Sync(ctx, serviceName, pathMappings) if err != nil { return err } } if len(restart) > 0 { services := utils.MapKeys(restart) err := s.restart(ctx, project.Name, api.RestartOptions{ Services: services, Project: project, NoDeps: false, }) if err != nil { return err } options.LogTo.Log( api.WatchLogger, fmt.Sprintf("service(s) %q restarted", services)) } eg, ctx := errgroup.WithContext(ctx) for service, rulesToExec := range exec { slices.Sort(rulesToExec) for _, i := range slices.Compact(rulesToExec) { err := s.exec(ctx, project, service, rules[i].Exec, eg) if err != nil { return err } } } return eg.Wait() } func (s *composeService) exec(ctx context.Context, project *types.Project, serviceName string, x types.ServiceHook, eg *errgroup.Group) error { containers, err := s.getContainers(ctx, project.Name, oneOffExclude, false, serviceName) if err != nil { return err } for _, c := range containers { eg.Go(func() error { exec := ccli.NewExecOptions() exec.User = x.User exec.Privileged = x.Privileged exec.Command = x.Command exec.Workdir = x.WorkingDir exec.DetachKeys = s.configFile().DetachKeys for _, v := range x.Environment.ToMapping().Values() { err := exec.Env.Set(v) if err != nil { return err } } return ccli.RunExec(ctx, s.dockerCli, c.ID, exec) }) } return nil } func (s *composeService) rebuild(ctx context.Context, project *types.Project, services []string, options api.WatchOptions) error { options.LogTo.Log(api.WatchLogger, fmt.Sprintf("Rebuilding service(s) %q after changes were detected...", services)) // restrict the build to ONLY this service, not any of its dependencies options.Build.Services = services options.Build.Progress = string(progressui.PlainMode) options.Build.Out = cutils.GetWriter(func(line string) { options.LogTo.Log(api.WatchLogger, line) }) var ( imageNameToIdMap map[string]string err error ) err = tracing.SpanWrapFunc("project/build", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error { imageNameToIdMap, err = s.build(ctx, project, *options.Build, nil) return err })(ctx) if err != nil { options.LogTo.Log(api.WatchLogger, fmt.Sprintf("Build failed. Error: %v", err)) return err } if options.Prune { s.pruneDanglingImagesOnRebuild(ctx, project.Name, imageNameToIdMap) } options.LogTo.Log(api.WatchLogger, fmt.Sprintf("service(s) %q successfully built", services)) err = s.create(ctx, project, api.CreateOptions{ Services: services, Inherit: true, Recreate: api.RecreateForce, }) if err != nil { options.LogTo.Log(api.WatchLogger, fmt.Sprintf("Failed to recreate services after update. Error: %v", err)) return err } p, err := project.WithSelectedServices(services, types.IncludeDependents) if err != nil { return err } err = s.start(ctx, project.Name, api.StartOptions{ Project: p, Services: services, AttachTo: services, }, nil) if err != nil { options.LogTo.Log(api.WatchLogger, fmt.Sprintf("Application failed to start after update. Error: %v", err)) } return nil } // writeWatchSyncMessage prints out a message about the sync for the changed paths. func writeWatchSyncMessage(log api.LogConsumer, serviceName string, pathMappings []*sync.PathMapping) { if logrus.IsLevelEnabled(logrus.DebugLevel) { hostPathsToSync := make([]string, len(pathMappings)) for i := range pathMappings { hostPathsToSync[i] = pathMappings[i].HostPath } log.Log( api.WatchLogger, fmt.Sprintf( "Syncing service %q after changes were detected: %s", serviceName, strings.Join(hostPathsToSync, ", "), ), ) } else { log.Log( api.WatchLogger, fmt.Sprintf("Syncing service %q after %d changes were detected", serviceName, len(pathMappings)), ) } } func (s *composeService) pruneDanglingImagesOnRebuild(ctx context.Context, projectName string, imageNameToIdMap map[string]string) { images, err := s.apiClient().ImageList(ctx, image.ListOptions{ Filters: filters.NewArgs( filters.Arg("dangling", "true"), filters.Arg("label", api.ProjectLabel+"="+projectName), ), }) if err != nil { logrus.Debugf("Failed to list images: %v", err) return } for _, img := range images { if _, ok := imageNameToIdMap[img.ID]; !ok { _, err := s.apiClient().ImageRemove(ctx, img.ID, image.RemoveOptions{}) if err != nil { logrus.Debugf("Failed to remove image %s: %v", img.ID, err) } } } } // Walks develop.watch.path and checks which files should be copied inside the container // ignores develop.watch.ignore, Dockerfile, compose files, bind mounted paths and .git func (s *composeService) initialSync(ctx context.Context, project *types.Project, service types.ServiceConfig, trigger types.Trigger, syncer sync.Syncer) error { dockerIgnores, err := watch.LoadDockerIgnore(service.Build) if err != nil { return err } dotGitIgnore, err := watch.NewDockerPatternMatcher("/", []string{".git/"}) if err != nil { return err } triggerIgnore, err := watch.NewDockerPatternMatcher(trigger.Path, trigger.Ignore) if err != nil { return err } // FIXME .dockerignore ignoreInitialSync := watch.NewCompositeMatcher( dockerIgnores, watch.EphemeralPathMatcher(), dotGitIgnore, triggerIgnore) pathsToCopy, err := s.initialSyncFiles(ctx, project, service, trigger, ignoreInitialSync) if err != nil { return err } return syncer.Sync(ctx, service.Name, pathsToCopy) } // Syncs files from develop.watch.path if thy have been modified after the image has been created // //nolint:gocyclo func (s *composeService) initialSyncFiles(ctx context.Context, project *types.Project, service types.ServiceConfig, trigger types.Trigger, ignore watch.PathMatcher) ([]*sync.PathMapping, error) { fi, err := os.Stat(trigger.Path) if err != nil { return nil, err } timeImageCreated, err := s.imageCreatedTime(ctx, project, service.Name) if err != nil { return nil, err } var pathsToCopy []*sync.PathMapping switch mode := fi.Mode(); { case mode.IsDir(): // process directory err = filepath.WalkDir(trigger.Path, func(path string, d fs.DirEntry, err error) error { if err != nil { // handle possible path err, just in case... return err } if trigger.Path == path { // walk starts at the root directory return nil } if shouldIgnore(filepath.Base(path), ignore) || checkIfPathAlreadyBindMounted(path, service.Volumes) { // By definition sync ignores bind mounted paths if d.IsDir() { // skip folder return fs.SkipDir } return nil // skip file } info, err := d.Info() if err != nil { return err } if !d.IsDir() { if info.ModTime().Before(timeImageCreated) { // skip file if it was modified before image creation return nil } rel, err := filepath.Rel(trigger.Path, path) if err != nil { return err } // only copy files (and not full directories) pathsToCopy = append(pathsToCopy, &sync.PathMapping{ HostPath: path, ContainerPath: filepath.Join(trigger.Target, rel), }) } return nil }) case mode.IsRegular(): // process file if fi.ModTime().After(timeImageCreated) && !shouldIgnore(filepath.Base(trigger.Path), ignore) && !checkIfPathAlreadyBindMounted(trigger.Path, service.Volumes) { pathsToCopy = append(pathsToCopy, &sync.PathMapping{ HostPath: trigger.Path, ContainerPath: trigger.Target, }) } } return pathsToCopy, err } func shouldIgnore(name string, ignore watch.PathMatcher) bool { shouldIgnore, _ := ignore.Matches(name) // ignore files that match any ignore pattern return shouldIgnore } // gets the image creation time for a service func (s *composeService) imageCreatedTime(ctx context.Context, project *types.Project, serviceName string) (time.Time, error) { containers, err := s.apiClient().ContainerList(ctx, container.ListOptions{ All: true, Filters: filters.NewArgs( filters.Arg("label", fmt.Sprintf("%s=%s", api.ProjectLabel, project.Name)), filters.Arg("label", fmt.Sprintf("%s=%s", api.ServiceLabel, serviceName))), }) if err != nil { return time.Now(), err } if len(containers) == 0 { return time.Now(), fmt.Errorf("could not get created time for service's image") } img, err := s.apiClient().ImageInspect(ctx, containers[0].ImageID) if err != nil { return time.Now(), err } // Need to get the oldest one? timeCreated, err := time.Parse(time.RFC3339Nano, img.Created) if err != nil { return time.Now(), err } return timeCreated, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/secrets.go
pkg/compose/secrets.go
/* 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 ( "archive/tar" "bytes" "context" "fmt" "strconv" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" ) type mountType string const ( secretMount mountType = "secret" configMount mountType = "config" ) func (s *composeService) injectSecrets(ctx context.Context, project *types.Project, service types.ServiceConfig, id string) error { return s.injectFileReferences(ctx, project, service, id, secretMount) } func (s *composeService) injectConfigs(ctx context.Context, project *types.Project, service types.ServiceConfig, id string) error { return s.injectFileReferences(ctx, project, service, id, configMount) } func (s *composeService) injectFileReferences(ctx context.Context, project *types.Project, service types.ServiceConfig, id string, mountType mountType) error { mounts, sources := s.getFilesAndMap(project, service, mountType) for _, mount := range mounts { content, err := s.resolveFileContent(project, sources[mount.Source], mountType) if err != nil { return err } if content == "" { continue } if service.ReadOnly { return fmt.Errorf("cannot create %s %q in read-only service %s: `file` is the sole supported option", mountType, sources[mount.Source].Name, service.Name) } s.setDefaultTarget(&mount, mountType) if err := s.copyFileToContainer(ctx, id, content, mount); err != nil { return err } } return nil } func (s *composeService) getFilesAndMap(project *types.Project, service types.ServiceConfig, mountType mountType) ([]types.FileReferenceConfig, map[string]types.FileObjectConfig) { var files []types.FileReferenceConfig var fileMap map[string]types.FileObjectConfig switch mountType { case secretMount: files = make([]types.FileReferenceConfig, len(service.Secrets)) for i, config := range service.Secrets { files[i] = types.FileReferenceConfig(config) } fileMap = make(map[string]types.FileObjectConfig) for k, v := range project.Secrets { fileMap[k] = types.FileObjectConfig(v) } case configMount: files = make([]types.FileReferenceConfig, len(service.Configs)) for i, config := range service.Configs { files[i] = types.FileReferenceConfig(config) } fileMap = make(map[string]types.FileObjectConfig) for k, v := range project.Configs { fileMap[k] = types.FileObjectConfig(v) } } return files, fileMap } func (s *composeService) resolveFileContent(project *types.Project, source types.FileObjectConfig, mountType mountType) (string, error) { if source.Content != "" { // inlined, or already resolved by include return source.Content, nil } if source.Environment != "" { env, ok := project.Environment[source.Environment] if !ok { return "", fmt.Errorf("environment variable %q required by %s %q is not set", source.Environment, mountType, source.Name) } return env, nil } return "", nil } func (s *composeService) setDefaultTarget(file *types.FileReferenceConfig, mountType mountType) { if file.Target == "" { if mountType == secretMount { file.Target = "/run/secrets/" + file.Source } else { file.Target = "/" + file.Source } } else if mountType == secretMount && !isAbsTarget(file.Target) { file.Target = "/run/secrets/" + file.Target } } func (s *composeService) copyFileToContainer(ctx context.Context, id, content string, file types.FileReferenceConfig) error { b, err := createTar(content, file) if err != nil { return err } return s.apiClient().CopyToContainer(ctx, id, "/", &b, container.CopyToContainerOptions{ CopyUIDGID: file.UID != "" || file.GID != "", }) } func createTar(env string, config types.FileReferenceConfig) (bytes.Buffer, error) { value := []byte(env) b := bytes.Buffer{} tarWriter := tar.NewWriter(&b) mode := types.FileMode(0o444) if config.Mode != nil { mode = *config.Mode } var uid, gid int if config.UID != "" { v, err := strconv.Atoi(config.UID) if err != nil { return b, err } uid = v } if config.GID != "" { v, err := strconv.Atoi(config.GID) if err != nil { return b, err } gid = v } header := &tar.Header{ Name: config.Target, Size: int64(len(value)), Mode: int64(mode), ModTime: time.Now(), Uid: uid, Gid: gid, } err := tarWriter.WriteHeader(header) if err != nil { return bytes.Buffer{}, err } _, err = tarWriter.Write(value) if err != nil { return bytes.Buffer{}, err } err = tarWriter.Close() return b, err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/volumes_test.go
pkg/compose/volumes_test.go
/* 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" "testing" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/volume" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" "github.com/docker/compose/v5/pkg/api" ) func TestVolumes(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockApi, mockCli := prepareMocks(mockCtrl) tested := composeService{ dockerCli: mockCli, } // Create test volumes vol1 := &volume.Volume{Name: testProject + "_vol1"} vol2 := &volume.Volume{Name: testProject + "_vol2"} vol3 := &volume.Volume{Name: testProject + "_vol3"} // Create test containers with volume mounts c1 := container.Summary{ Labels: map[string]string{api.ServiceLabel: "service1"}, Mounts: []container.MountPoint{ {Name: testProject + "_vol1"}, {Name: testProject + "_vol2"}, }, } c2 := container.Summary{ Labels: map[string]string{api.ServiceLabel: "service2"}, Mounts: []container.MountPoint{ {Name: testProject + "_vol3"}, }, } ctx := context.Background() args := filters.NewArgs(projectFilter(testProject)) listOpts := container.ListOptions{Filters: args} volumeListArgs := filters.NewArgs(projectFilter(testProject)) volumeListOpts := volume.ListOptions{Filters: volumeListArgs} volumeReturn := volume.ListResponse{ Volumes: []*volume.Volume{vol1, vol2, vol3}, } containerReturn := []container.Summary{c1, c2} // Mock API calls mockApi.EXPECT().ContainerList(ctx, listOpts).Times(2).Return(containerReturn, nil) mockApi.EXPECT().VolumeList(ctx, volumeListOpts).Times(2).Return(volumeReturn, nil) // Test without service filter - should return all project volumes volumeOptions := api.VolumesOptions{} volumes, err := tested.Volumes(ctx, testProject, volumeOptions) expected := []api.VolumesSummary{vol1, vol2, vol3} assert.NilError(t, err) assert.DeepEqual(t, volumes, expected) // Test with service filter - should only return volumes used by service1 volumeOptions = api.VolumesOptions{Services: []string{"service1"}} volumes, err = tested.Volumes(ctx, testProject, volumeOptions) expected = []api.VolumesSummary{vol1, vol2} assert.NilError(t, err) assert.DeepEqual(t, volumes, expected) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/desktop.go
pkg/compose/desktop.go
/* Copyright 2024 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" "strings" ) // engineLabelDesktopAddress is used to detect that Compose is running with a // Docker Desktop context. When this label is present, the value is an endpoint // address for an in-memory socket (AF_UNIX or named pipe). const engineLabelDesktopAddress = "com.docker.desktop.address" func (s *composeService) isDesktopIntegrationActive(ctx context.Context) (bool, error) { info, err := s.apiClient().Info(ctx) if err != nil { return false, err } for _, l := range info.Labels { k, _, ok := strings.Cut(l, "=") if ok && k == engineLabelDesktopAddress { return true, nil } } return false, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/logs_test.go
pkg/compose/logs_test.go
/* Copyright 2022 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" "io" "strings" "sync" "testing" "github.com/compose-spec/compose-go/v2/types" containerType "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/pkg/stdcopy" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" compose "github.com/docker/compose/v5/pkg/api" ) func TestComposeService_Logs_Demux(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) require.NoError(t, err) name := strings.ToLower(testProject) ctx := context.Background() api.EXPECT().ContainerList(ctx, containerType.ListOptions{ All: true, Filters: filters.NewArgs(oneOffFilter(false), projectFilter(name), hasConfigHashLabel()), }).Return( []containerType.Summary{ testContainer("service", "c", false), }, nil, ) api.EXPECT(). ContainerInspect(anyCancellableContext(), "c"). Return(containerType.InspectResponse{ ContainerJSONBase: &containerType.ContainerJSONBase{ID: "c"}, Config: &containerType.Config{Tty: false}, }, nil) c1Reader, c1Writer := io.Pipe() t.Cleanup(func() { _ = c1Reader.Close() _ = c1Writer.Close() }) c1Stdout := stdcopy.NewStdWriter(c1Writer, stdcopy.Stdout) c1Stderr := stdcopy.NewStdWriter(c1Writer, stdcopy.Stderr) go func() { _, err := c1Stdout.Write([]byte("hello stdout\n")) assert.NoError(t, err, "Writing to fake stdout") _, err = c1Stderr.Write([]byte("hello stderr\n")) assert.NoError(t, err, "Writing to fake stderr") _ = c1Writer.Close() }() api.EXPECT().ContainerLogs(anyCancellableContext(), "c", gomock.Any()). Return(c1Reader, nil) opts := compose.LogOptions{ Project: &types.Project{ Services: types.Services{ "service": {Name: "service"}, }, }, } consumer := &testLogConsumer{} err = tested.Logs(ctx, name, consumer, opts) require.NoError(t, err) require.Equal( t, []string{"hello stdout", "hello stderr"}, consumer.LogsForContainer("c"), ) } // TestComposeService_Logs_ServiceFiltering ensures that we do not include // logs from out-of-scope services based on the Compose file vs actual state. // // NOTE(milas): This test exists because each method is currently duplicating // a lot of the project/service filtering logic. We should consider moving it // to an earlier point in the loading process, at which point this test could // safely be removed. func TestComposeService_Logs_ServiceFiltering(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) require.NoError(t, err) name := strings.ToLower(testProject) ctx := context.Background() api.EXPECT().ContainerList(ctx, containerType.ListOptions{ All: true, Filters: filters.NewArgs(oneOffFilter(false), projectFilter(name), hasConfigHashLabel()), }).Return( []containerType.Summary{ testContainer("serviceA", "c1", false), testContainer("serviceA", "c2", false), // serviceB will be filtered out by the project definition to // ensure we ignore "orphan" containers testContainer("serviceB", "c3", false), testContainer("serviceC", "c4", false), }, nil, ) for _, id := range []string{"c1", "c2", "c4"} { api.EXPECT(). ContainerInspect(anyCancellableContext(), id). Return( containerType.InspectResponse{ ContainerJSONBase: &containerType.ContainerJSONBase{ID: id}, Config: &containerType.Config{Tty: true}, }, nil, ) api.EXPECT().ContainerLogs(anyCancellableContext(), id, gomock.Any()). Return(io.NopCloser(strings.NewReader("hello "+id+"\n")), nil). Times(1) } // this simulates passing `--filename` with a Compose file that does NOT // reference `serviceB` even though it has running services for this proj proj := &types.Project{ Services: types.Services{ "serviceA": {Name: "serviceA"}, "serviceC": {Name: "serviceC"}, }, } consumer := &testLogConsumer{} opts := compose.LogOptions{ Project: proj, } err = tested.Logs(ctx, name, consumer, opts) require.NoError(t, err) require.Equal(t, []string{"hello c1"}, consumer.LogsForContainer("c1")) require.Equal(t, []string{"hello c2"}, consumer.LogsForContainer("c2")) require.Empty(t, consumer.LogsForContainer("c3")) require.Equal(t, []string{"hello c4"}, consumer.LogsForContainer("c4")) } type testLogConsumer struct { mu sync.Mutex // logs is keyed by container ID; values are log lines logs map[string][]string } func (l *testLogConsumer) Log(containerName, message string) { l.mu.Lock() defer l.mu.Unlock() if l.logs == nil { l.logs = make(map[string][]string) } l.logs[containerName] = append(l.logs[containerName], message) } func (l *testLogConsumer) Err(containerName, message string) { l.Log(containerName, message) } func (l *testLogConsumer) Status(containerName, msg string) {} func (l *testLogConsumer) LogsForContainer(containerName string) []string { l.mu.Lock() defer l.mu.Unlock() return l.logs[containerName] }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/ps.go
pkg/compose/ps.go
/* 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" "sort" "strings" "github.com/docker/docker/api/types/container" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Ps(ctx context.Context, projectName string, options api.PsOptions) ([]api.ContainerSummary, error) { projectName = strings.ToLower(projectName) oneOff := oneOffExclude if options.All { oneOff = oneOffInclude } containers, err := s.getContainers(ctx, projectName, oneOff, options.All, options.Services...) if err != nil { return nil, err } if len(options.Services) != 0 { containers = containers.filter(isService(options.Services...)) } summary := make([]api.ContainerSummary, len(containers)) eg, ctx := errgroup.WithContext(ctx) for i, ctr := range containers { eg.Go(func() error { publishers := make([]api.PortPublisher, len(ctr.Ports)) sort.Slice(ctr.Ports, func(i, j int) bool { return ctr.Ports[i].PrivatePort < ctr.Ports[j].PrivatePort }) for i, p := range ctr.Ports { publishers[i] = api.PortPublisher{ URL: p.IP, TargetPort: int(p.PrivatePort), PublishedPort: int(p.PublicPort), Protocol: p.Type, } } inspect, err := s.apiClient().ContainerInspect(ctx, ctr.ID) if err != nil { return err } var ( health container.HealthStatus exitCode int ) if inspect.State != nil { switch inspect.State.Status { case container.StateRunning: if inspect.State.Health != nil { health = inspect.State.Health.Status } case container.StateExited, container.StateDead: exitCode = inspect.State.ExitCode } } var ( local int mounts []string ) for _, m := range ctr.Mounts { name := m.Name if name == "" { name = m.Source } if m.Driver == "local" { local++ } mounts = append(mounts, name) } var networks []string if ctr.NetworkSettings != nil { for k := range ctr.NetworkSettings.Networks { networks = append(networks, k) } } summary[i] = api.ContainerSummary{ ID: ctr.ID, Name: getCanonicalContainerName(ctr), Names: ctr.Names, Image: ctr.Image, Project: ctr.Labels[api.ProjectLabel], Service: ctr.Labels[api.ServiceLabel], Command: ctr.Command, State: ctr.State, Status: ctr.Status, Created: ctr.Created, Labels: ctr.Labels, SizeRw: ctr.SizeRw, SizeRootFs: ctr.SizeRootFs, Mounts: mounts, LocalVolumes: local, Networks: networks, Health: health, ExitCode: exitCode, Publishers: publishers, } return nil }) } return summary, eg.Wait() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/containers.go
pkg/compose/containers.go
/* 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" "fmt" "slices" "sort" "strconv" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/compose/v5/pkg/api" ) // Containers is a set of moby Container type Containers []container.Summary type oneOff int const ( oneOffInclude = oneOff(iota) oneOffExclude oneOffOnly ) func (s *composeService) getContainers(ctx context.Context, project string, oneOff oneOff, all bool, selectedServices ...string) (Containers, error) { var containers Containers f := getDefaultFilters(project, oneOff, selectedServices...) containers, err := s.apiClient().ContainerList(ctx, container.ListOptions{ Filters: filters.NewArgs(f...), All: all, }) if err != nil { return nil, err } if len(selectedServices) > 1 { containers = containers.filter(isService(selectedServices...)) } return containers, nil } func getDefaultFilters(projectName string, oneOff oneOff, selectedServices ...string) []filters.KeyValuePair { f := []filters.KeyValuePair{projectFilter(projectName)} if len(selectedServices) == 1 { f = append(f, serviceFilter(selectedServices[0])) } f = append(f, hasConfigHashLabel()) switch oneOff { case oneOffOnly: f = append(f, oneOffFilter(true)) case oneOffExclude: f = append(f, oneOffFilter(false)) case oneOffInclude: } return f } func (s *composeService) getSpecifiedContainer(ctx context.Context, projectName string, oneOff oneOff, all bool, serviceName string, containerIndex int) (container.Summary, error) { defaultFilters := getDefaultFilters(projectName, oneOff, serviceName) if containerIndex > 0 { defaultFilters = append(defaultFilters, containerNumberFilter(containerIndex)) } containers, err := s.apiClient().ContainerList(ctx, container.ListOptions{ Filters: filters.NewArgs( defaultFilters..., ), All: all, }) if err != nil { return container.Summary{}, err } if len(containers) < 1 { if containerIndex > 0 { return container.Summary{}, fmt.Errorf("service %q is not running container #%d", serviceName, containerIndex) } return container.Summary{}, fmt.Errorf("service %q is not running", serviceName) } // Sort by container number first, then put one-off containers at the end sort.Slice(containers, func(i, j int) bool { numberLabelX, _ := strconv.Atoi(containers[i].Labels[api.ContainerNumberLabel]) numberLabelY, _ := strconv.Atoi(containers[j].Labels[api.ContainerNumberLabel]) IsOneOffLabelTrueX := containers[i].Labels[api.OneoffLabel] == "True" IsOneOffLabelTrueY := containers[j].Labels[api.OneoffLabel] == "True" if IsOneOffLabelTrueX || IsOneOffLabelTrueY { return !IsOneOffLabelTrueX && IsOneOffLabelTrueY } return numberLabelX < numberLabelY }) return containers[0], nil } // containerPredicate define a predicate we want container to satisfy for filtering operations type containerPredicate func(c container.Summary) bool func matches(c container.Summary, predicates ...containerPredicate) bool { for _, predicate := range predicates { if !predicate(c) { return false } } return true } func isService(services ...string) containerPredicate { return func(c container.Summary) bool { service := c.Labels[api.ServiceLabel] return slices.Contains(services, service) } } // isOrphaned is a predicate to select containers without a matching service definition in compose project func isOrphaned(project *types.Project) containerPredicate { services := append(project.ServiceNames(), project.DisabledServiceNames()...) return func(c container.Summary) bool { // One-off container v, ok := c.Labels[api.OneoffLabel] if ok && v == "True" { return c.State == container.StateExited || c.State == container.StateDead } // Service that is not defined in the compose model service := c.Labels[api.ServiceLabel] return !slices.Contains(services, service) } } func isNotOneOff(c container.Summary) bool { v, ok := c.Labels[api.OneoffLabel] return !ok || v == "False" } // filter return Containers with elements to match predicate func (containers Containers) filter(predicates ...containerPredicate) Containers { var filtered Containers for _, c := range containers { if matches(c, predicates...) { filtered = append(filtered, c) } } return filtered } func (containers Containers) names() []string { var names []string for _, c := range containers { names = append(names, getCanonicalContainerName(c)) } return names } func (containers Containers) forEach(fn func(container.Summary)) { for _, c := range containers { fn(c) } } func (containers Containers) sorted() Containers { sort.Slice(containers, func(i, j int) bool { return getCanonicalContainerName(containers[i]) < getCanonicalContainerName(containers[j]) }) return containers }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/compose.go
pkg/compose/compose.go
/* 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" "io" "strconv" "strings" "sync" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/buildx/store/storeutil" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/config/configfile" "github.com/docker/cli/cli/flags" "github.com/docker/cli/cli/streams" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" "github.com/jonboulle/clockwork" "github.com/sirupsen/logrus" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/dryrun" ) type Option func(service *composeService) error // NewComposeService creates a Compose service using Docker CLI. // This is the standard constructor that requires command.Cli for full functionality. // // Example usage: // // dockerCli, _ := command.NewDockerCli() // service := NewComposeService(dockerCli) // // For advanced configuration with custom overrides, use ServiceOption functions: // // service := NewComposeService(dockerCli, // WithPrompt(prompt.NewPrompt(cli.In(), cli.Out()).Confirm), // WithOutputStream(customOut), // WithErrorStream(customErr), // WithInputStream(customIn)) // // Or set all streams at once: // // service := NewComposeService(dockerCli, // WithStreams(customOut, customErr, customIn)) func NewComposeService(dockerCli command.Cli, options ...Option) (api.Compose, error) { s := &composeService{ dockerCli: dockerCli, clock: clockwork.NewRealClock(), maxConcurrency: -1, dryRun: false, } for _, option := range options { if err := option(s); err != nil { return nil, err } } if s.prompt == nil { s.prompt = func(message string, defaultValue bool) (bool, error) { fmt.Println(message) logrus.Warning("Compose is running without a 'prompt' component to interact with user") return defaultValue, nil } } if s.events == nil { s.events = &ignore{} } // If custom streams were provided, wrap the Docker CLI to use them if s.outStream != nil || s.errStream != nil || s.inStream != nil { s.dockerCli = s.wrapDockerCliWithStreams(dockerCli) } return s, nil } // WithStreams sets custom I/O streams for output and interaction func WithStreams(out, err io.Writer, in io.Reader) Option { return func(s *composeService) error { s.outStream = out s.errStream = err s.inStream = in return nil } } // WithOutputStream sets a custom output stream func WithOutputStream(out io.Writer) Option { return func(s *composeService) error { s.outStream = out return nil } } // WithErrorStream sets a custom error stream func WithErrorStream(err io.Writer) Option { return func(s *composeService) error { s.errStream = err return nil } } // WithInputStream sets a custom input stream func WithInputStream(in io.Reader) Option { return func(s *composeService) error { s.inStream = in return nil } } // WithContextInfo sets custom Docker context information func WithContextInfo(info api.ContextInfo) Option { return func(s *composeService) error { s.contextInfo = info return nil } } // WithProxyConfig sets custom HTTP proxy configuration for builds func WithProxyConfig(config map[string]string) Option { return func(s *composeService) error { s.proxyConfig = config return nil } } // WithPrompt configure a UI component for Compose service to interact with user and confirm actions func WithPrompt(prompt Prompt) Option { return func(s *composeService) error { s.prompt = prompt return nil } } // WithMaxConcurrency defines upper limit for concurrent operations against engine API func WithMaxConcurrency(maxConcurrency int) Option { return func(s *composeService) error { s.maxConcurrency = maxConcurrency return nil } } // WithDryRun configure Compose to run without actually applying changes func WithDryRun(s *composeService) error { s.dryRun = true cli, err := command.NewDockerCli() if err != nil { return err } options := flags.NewClientOptions() options.Context = s.dockerCli.CurrentContext() err = cli.Initialize(options, command.WithInitializeClient(func(cli *command.DockerCli) (client.APIClient, error) { return dryrun.NewDryRunClient(s.apiClient(), s.dockerCli) })) if err != nil { return err } s.dockerCli = cli return nil } type Prompt func(message string, defaultValue bool) (bool, error) // AlwaysOkPrompt returns a Prompt implementation that always returns true without user interaction. func AlwaysOkPrompt() Prompt { return func(message string, defaultValue bool) (bool, error) { return true, nil } } // WithEventProcessor configure component to get notified on Compose operation and progress events. // Typically used to configure a progress UI func WithEventProcessor(bus api.EventProcessor) Option { return func(s *composeService) error { s.events = bus return nil } } type composeService struct { dockerCli command.Cli // prompt is used to interact with user and confirm actions prompt Prompt // eventBus collects tasks execution events events api.EventProcessor // Optional overrides for specific components (for SDK users) outStream io.Writer errStream io.Writer inStream io.Reader contextInfo api.ContextInfo proxyConfig map[string]string clock clockwork.Clock maxConcurrency int dryRun bool } // Close releases any connections/resources held by the underlying clients. // // In practice, this service has the same lifetime as the process, so everything // will get cleaned up at about the same time regardless even if not invoked. func (s *composeService) Close() error { var errs []error if s.dockerCli != nil { errs = append(errs, s.apiClient().Close()) } return errors.Join(errs...) } func (s *composeService) apiClient() client.APIClient { return s.dockerCli.Client() } func (s *composeService) configFile() *configfile.ConfigFile { return s.dockerCli.ConfigFile() } // getContextInfo returns the context info - either custom override or dockerCli adapter func (s *composeService) getContextInfo() api.ContextInfo { if s.contextInfo != nil { return s.contextInfo } return &dockerCliContextInfo{cli: s.dockerCli} } // getProxyConfig returns the proxy config - either custom override or environment-based func (s *composeService) getProxyConfig() map[string]string { if s.proxyConfig != nil { return s.proxyConfig } return storeutil.GetProxyConfig(s.dockerCli) } func (s *composeService) stdout() *streams.Out { return s.dockerCli.Out() } func (s *composeService) stdin() *streams.In { return s.dockerCli.In() } func (s *composeService) stderr() *streams.Out { return s.dockerCli.Err() } // readCloserAdapter adapts io.Reader to io.ReadCloser type readCloserAdapter struct { r io.Reader } func (r *readCloserAdapter) Read(p []byte) (int, error) { return r.r.Read(p) } func (r *readCloserAdapter) Close() error { return nil } // wrapDockerCliWithStreams wraps the Docker CLI to intercept and override stream methods func (s *composeService) wrapDockerCliWithStreams(baseCli command.Cli) command.Cli { wrapper := &streamOverrideWrapper{ Cli: baseCli, } // Wrap custom streams in Docker CLI's stream types if s.outStream != nil { wrapper.outStream = streams.NewOut(s.outStream) } if s.errStream != nil { wrapper.errStream = streams.NewOut(s.errStream) } if s.inStream != nil { wrapper.inStream = streams.NewIn(&readCloserAdapter{r: s.inStream}) } return wrapper } // streamOverrideWrapper wraps command.Cli to override streams with custom implementations type streamOverrideWrapper struct { command.Cli outStream *streams.Out errStream *streams.Out inStream *streams.In } func (w *streamOverrideWrapper) Out() *streams.Out { if w.outStream != nil { return w.outStream } return w.Cli.Out() } func (w *streamOverrideWrapper) Err() *streams.Out { if w.errStream != nil { return w.errStream } return w.Cli.Err() } func (w *streamOverrideWrapper) In() *streams.In { if w.inStream != nil { return w.inStream } return w.Cli.In() } func getCanonicalContainerName(c container.Summary) string { if len(c.Names) == 0 { // corner case, sometime happens on removal. return short ID as a safeguard value return c.ID[:12] } // Names return container canonical name /foo + link aliases /linked_by/foo for _, name := range c.Names { if strings.LastIndex(name, "/") == 0 { return name[1:] } } return strings.TrimPrefix(c.Names[0], "/") } func getContainerNameWithoutProject(c container.Summary) string { project := c.Labels[api.ProjectLabel] defaultName := getDefaultContainerName(project, c.Labels[api.ServiceLabel], c.Labels[api.ContainerNumberLabel]) name := getCanonicalContainerName(c) if name != defaultName { // service declares a custom container_name return name } return name[len(project)+1:] } // projectFromName builds a types.Project based on actual resources with compose labels set func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) { project := &types.Project{ Name: projectName, Services: types.Services{}, } if len(containers) == 0 { return project, fmt.Errorf("no container found for project %q: %w", projectName, api.ErrNotFound) } set := types.Services{} for _, c := range containers { serviceLabel, ok := c.Labels[api.ServiceLabel] if !ok { serviceLabel = getCanonicalContainerName(c) } service, ok := set[serviceLabel] if !ok { service = types.ServiceConfig{ Name: serviceLabel, Image: c.Image, Labels: c.Labels, } } service.Scale = increment(service.Scale) set[serviceLabel] = service } for name, service := range set { dependencies := service.Labels[api.DependenciesLabel] if dependencies != "" { service.DependsOn = types.DependsOnConfig{} for dc := range strings.SplitSeq(dependencies, ",") { dcArr := strings.Split(dc, ":") condition := ServiceConditionRunningOrHealthy // Let's restart the dependency by default if we don't have the info stored in the label restart := true required := true dependency := dcArr[0] // backward compatibility if len(dcArr) > 1 { condition = dcArr[1] if len(dcArr) > 2 { restart, _ = strconv.ParseBool(dcArr[2]) } } service.DependsOn[dependency] = types.ServiceDependency{Condition: condition, Restart: restart, Required: required} } set[name] = service } } project.Services = set SERVICES: for _, qs := range services { for _, es := range project.Services { if es.Name == qs { continue SERVICES } } return project, fmt.Errorf("no such service: %q: %w", qs, api.ErrNotFound) } project, err := project.WithSelectedServices(services) if err != nil { return project, err } return project, nil } func increment(scale *int) *int { i := 1 if scale != nil { i = *scale + 1 } return &i } func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) { opts := volume.ListOptions{ Filters: filters.NewArgs(projectFilter(projectName)), } volumes, err := s.apiClient().VolumeList(ctx, opts) if err != nil { return nil, err } actual := types.Volumes{} for _, vol := range volumes.Volumes { actual[vol.Labels[api.VolumeLabel]] = types.VolumeConfig{ Name: vol.Name, Driver: vol.Driver, Labels: vol.Labels, } } return actual, nil } func (s *composeService) actualNetworks(ctx context.Context, projectName string) (types.Networks, error) { networks, err := s.apiClient().NetworkList(ctx, network.ListOptions{ Filters: filters.NewArgs(projectFilter(projectName)), }) if err != nil { return nil, err } actual := types.Networks{} for _, net := range networks { actual[net.Labels[api.NetworkLabel]] = types.NetworkConfig{ Name: net.Name, Driver: net.Driver, Labels: net.Labels, } } return actual, nil } var swarmEnabled = struct { once sync.Once val bool err error }{} func (s *composeService) isSwarmEnabled(ctx context.Context) (bool, error) { swarmEnabled.once.Do(func() { info, err := s.apiClient().Info(ctx) if err != nil { swarmEnabled.err = err } switch info.Swarm.LocalNodeState { case swarm.LocalNodeStateInactive, swarm.LocalNodeStateLocked: swarmEnabled.val = false default: swarmEnabled.val = true } }) return swarmEnabled.val, swarmEnabled.err } type runtimeVersionCache struct { once sync.Once val string err error } var runtimeVersion runtimeVersionCache func (s *composeService) RuntimeVersion(ctx context.Context) (string, error) { runtimeVersion.once.Do(func() { version, err := s.apiClient().ServerVersion(ctx) if err != nil { runtimeVersion.err = err } runtimeVersion.val = version.APIVersion }) return runtimeVersion.val, runtimeVersion.err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/publish_test.go
pkg/compose/publish_test.go
/* 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" "slices" "testing" "github.com/compose-spec/compose-go/v2/loader" "github.com/compose-spec/compose-go/v2/types" "github.com/google/go-cmp/cmp" v1 "github.com/opencontainers/image-spec/specs-go/v1" "gotest.tools/v3/assert" "github.com/docker/compose/v5/internal" "github.com/docker/compose/v5/pkg/api" ) func Test_createLayers(t *testing.T) { project, err := loader.LoadWithContext(context.TODO(), types.ConfigDetails{ WorkingDir: "testdata/publish/", Environment: types.Mapping{}, ConfigFiles: []types.ConfigFile{ { Filename: "testdata/publish/compose.yaml", }, }, }) assert.NilError(t, err) project.ComposeFiles = []string{"testdata/publish/compose.yaml"} service := &composeService{} layers, err := service.createLayers(context.TODO(), project, api.PublishOptions{ WithEnvironment: true, }) assert.NilError(t, err) published := string(layers[0].Data) assert.Equal(t, published, `name: test services: test: extends: file: f8f9ede3d201ec37d5a5e3a77bbadab79af26035e53135e19571f50d541d390c.yaml service: foo string: image: test env_file: 5efca9cdbac9f5394c6c2e2094b1b42661f988f57fcab165a0bf72b205451af3.env list: image: test env_file: - 5efca9cdbac9f5394c6c2e2094b1b42661f988f57fcab165a0bf72b205451af3.env mapping: image: test env_file: - path: 5efca9cdbac9f5394c6c2e2094b1b42661f988f57fcab165a0bf72b205451af3.env `) expectedLayers := []v1.Descriptor{ { MediaType: "application/vnd.docker.compose.file+yaml", Annotations: map[string]string{ "com.docker.compose.file": "compose.yaml", "com.docker.compose.version": internal.Version, }, }, { MediaType: "application/vnd.docker.compose.file+yaml", Annotations: map[string]string{ "com.docker.compose.extends": "true", "com.docker.compose.file": "f8f9ede3d201ec37d5a5e3a77bbadab79af26035e53135e19571f50d541d390c", "com.docker.compose.version": internal.Version, }, }, { MediaType: "application/vnd.docker.compose.envfile", Annotations: map[string]string{ "com.docker.compose.envfile": "5efca9cdbac9f5394c6c2e2094b1b42661f988f57fcab165a0bf72b205451af3", "com.docker.compose.version": internal.Version, }, }, } assert.DeepEqual(t, expectedLayers, layers, cmp.FilterPath(func(path cmp.Path) bool { return !slices.Contains([]string{".Data", ".Digest", ".Size"}, path.String()) }, cmp.Ignore())) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/scale.go
pkg/compose/scale.go
/* 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" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/compose/v5/internal/tracing" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Scale(ctx context.Context, project *types.Project, options api.ScaleOptions) error { return Run(ctx, tracing.SpanWrapFunc("project/scale", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error { err := s.create(ctx, project, api.CreateOptions{Services: options.Services}) if err != nil { return err } return s.start(ctx, project.Name, api.StartOptions{Project: project, Services: options.Services}, nil) }), "scale", s.events) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/logs.go
pkg/compose/logs.go
/* 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" "io" "github.com/containerd/errdefs" "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/stdcopy" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) func (s *composeService) Logs( ctx context.Context, projectName string, consumer api.LogConsumer, options api.LogOptions, ) error { var containers Containers var err error if options.Index > 0 { ctr, err := s.getSpecifiedContainer(ctx, projectName, oneOffExclude, true, options.Services[0], options.Index) if err != nil { return err } containers = append(containers, ctr) } else { containers, err = s.getContainers(ctx, projectName, oneOffExclude, true, options.Services...) if err != nil { return err } } if options.Project != nil && len(options.Services) == 0 { // we run with an explicit compose.yaml, so only consider services defined in this file options.Services = options.Project.ServiceNames() containers = containers.filter(isService(options.Services...)) } eg, ctx := errgroup.WithContext(ctx) for _, ctr := range containers { eg.Go(func() error { err := s.logContainer(ctx, consumer, ctr, options) if errdefs.IsNotImplemented(err) { logrus.Warnf("Can't retrieve logs for %q: %s", getCanonicalContainerName(ctr), err.Error()) return nil } return err }) } if options.Follow { printer := newLogPrinter(consumer) monitor := newMonitor(s.apiClient(), projectName) if len(options.Services) > 0 { monitor.withServices(options.Services) } else if options.Project != nil { monitor.withServices(options.Project.ServiceNames()) } monitor.withListener(printer.HandleEvent) monitor.withListener(func(event api.ContainerEvent) { if event.Type == api.ContainerEventStarted { eg.Go(func() error { ctr, err := s.apiClient().ContainerInspect(ctx, event.ID) if err != nil { return err } err = s.doLogContainer(ctx, consumer, event.Source, ctr, api.LogOptions{ Follow: options.Follow, Since: ctr.State.StartedAt, Until: options.Until, Tail: options.Tail, Timestamps: options.Timestamps, }) if errdefs.IsNotImplemented(err) { // ignore return nil } return err }) } }) eg.Go(func() error { // pass ctx so monitor will immediately stop on SIGINT return monitor.Start(ctx) }) } return eg.Wait() } func (s *composeService) logContainer(ctx context.Context, consumer api.LogConsumer, c container.Summary, options api.LogOptions) error { ctr, err := s.apiClient().ContainerInspect(ctx, c.ID) if err != nil { return err } name := getContainerNameWithoutProject(c) return s.doLogContainer(ctx, consumer, name, ctr, options) } func (s *composeService) doLogContainer(ctx context.Context, consumer api.LogConsumer, name string, ctr container.InspectResponse, options api.LogOptions) error { r, err := s.apiClient().ContainerLogs(ctx, ctr.ID, container.LogsOptions{ ShowStdout: true, ShowStderr: true, Follow: options.Follow, Since: options.Since, Until: options.Until, Tail: options.Tail, Timestamps: options.Timestamps, }) if err != nil { return err } defer r.Close() //nolint:errcheck w := utils.GetWriter(func(line string) { consumer.Log(name, line) }) if ctr.Config.Tty { _, err = io.Copy(w, r) } else { _, err = stdcopy.StdCopy(w, w, r) } return err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/export.go
pkg/compose/export.go
/* 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" "fmt" "io" "strings" "github.com/docker/cli/cli/command" "github.com/moby/sys/atomicwriter" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Export(ctx context.Context, projectName string, options api.ExportOptions) error { return Run(ctx, func(ctx context.Context) error { return s.export(ctx, projectName, options) }, "export", s.events) } func (s *composeService) export(ctx context.Context, projectName string, options api.ExportOptions) error { projectName = strings.ToLower(projectName) container, err := s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, options.Service, options.Index) if err != nil { return err } if options.Output == "" { if s.stdout().IsTerminal() { return fmt.Errorf("output option is required when exporting to terminal") } } else if err := command.ValidateOutputPath(options.Output); err != nil { return fmt.Errorf("failed to export container: %w", err) } name := getCanonicalContainerName(container) s.events.On(api.Resource{ ID: name, Text: api.StatusExporting, Status: api.Working, }) responseBody, err := s.apiClient().ContainerExport(ctx, container.ID) if err != nil { return err } defer func() { if err := responseBody.Close(); err != nil { s.events.On(errorEventf(name, "Failed to close response body: %s", err.Error())) } }() if !s.dryRun { if options.Output == "" { _, err := io.Copy(s.stdout(), responseBody) return err } else { writer, err := atomicwriter.New(options.Output, 0o600) if err != nil { return err } defer func() { _ = writer.Close() }() _, err = io.Copy(writer, responseBody) return err } } s.events.On(api.Resource{ ID: name, Text: api.StatusExported, Status: api.Done, }) return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/run.go
pkg/compose/run.go
/* 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/docker/pkg/stringid" "github.com/docker/compose/v5/pkg/api" ) 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 from exiting 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}, DetachKeys: s.configFile().DetachKeys, }) 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) { // Temporary implementation of use_api_socket until we get actual support inside docker engine project, err := s.useAPISocket(project) if err != nil { return "", err } err = Run(ctx, func(ctx context.Context) error { return s.startDependencies(ctx, project, opts) }, "run", s.events) if err != nil { return "", err } 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") // Only ensure image exists for the target service, dependencies were already handled by startDependencies buildOpts := prepareBuildOptions(opts) if err := s.ensureImagesExists(ctx, project, buildOpts, 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 } err = s.ensureModels(ctx, project, opts.QuietPull) if err != nil { return "", err } created, err := s.createContainer(ctx, project, service, service.ContainerName, -1, createOpts) if err != nil { return "", err } ctr, err := s.apiClient().ContainerInspect(ctx, created.ID) if err != nil { return "", err } err = s.injectSecrets(ctx, project, service, ctr.ID) if err != nil { return created.ID, err } err = s.injectConfigs(ctx, project, service, ctr.ID) return created.ID, err } func prepareBuildOptions(opts api.RunOptions) *api.BuildOptions { if opts.Build == nil { return nil } // Create a copy of build options and restrict to only the target service buildOptsCopy := *opts.Build buildOptsCopy.Services = []string{opts.Service} return &buildOptsCopy } 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 } 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) }) } 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) } } func (s *composeService) startDependencies(ctx context.Context, project *types.Project, options api.RunOptions) error { project = project.WithServicesDisabled(options.Service) err := s.Create(ctx, project, api.CreateOptions{ Build: options.Build, IgnoreOrphans: options.IgnoreOrphans, RemoveOrphans: options.RemoveOrphans, QuietPull: options.QuietPull, }) if err != nil { return err } if len(project.Services) > 0 { return s.Start(ctx, project.Name, api.StartOptions{ Project: project, }) } return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/volumes.go
pkg/compose/volumes.go
/* 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" "slices" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/volume" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Volumes(ctx context.Context, project string, options api.VolumesOptions) ([]api.VolumesSummary, error) { allContainers, err := s.apiClient().ContainerList(ctx, container.ListOptions{ Filters: filters.NewArgs(projectFilter(project)), }) if err != nil { return nil, err } var containers []container.Summary if len(options.Services) > 0 { // filter service containers for _, c := range allContainers { if slices.Contains(options.Services, c.Labels[api.ServiceLabel]) { containers = append(containers, c) } } } else { containers = allContainers } volumesResponse, err := s.apiClient().VolumeList(ctx, volume.ListOptions{ Filters: filters.NewArgs(projectFilter(project)), }) if err != nil { return nil, err } projectVolumes := volumesResponse.Volumes if len(options.Services) == 0 { return projectVolumes, nil } var volumes []api.VolumesSummary // create a name lookup of volumes used by containers serviceVolumes := make(map[string]bool) for _, container := range containers { for _, mount := range container.Mounts { serviceVolumes[mount.Name] = true } } // append if volumes in this project are in serviceVolumes for _, v := range projectVolumes { if serviceVolumes[v.Name] { volumes = append(volumes, v) } } return volumes, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/cp.go
pkg/compose/cp.go
/* 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" "io" "os" "path/filepath" "strings" "github.com/docker/cli/cli/command" "github.com/docker/docker/api/types/container" "github.com/moby/go-archive" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) type copyDirection int const ( fromService copyDirection = 1 << iota toService acrossServices = fromService | toService ) func (s *composeService) Copy(ctx context.Context, projectName string, options api.CopyOptions) error { return Run(ctx, func(ctx context.Context) error { return s.copy(ctx, projectName, options) }, "copy", s.events) } func (s *composeService) copy(ctx context.Context, projectName string, options api.CopyOptions) error { projectName = strings.ToLower(projectName) srcService, srcPath := splitCpArg(options.Source) destService, dstPath := splitCpArg(options.Destination) var direction copyDirection var serviceName string var copyFunc func(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error if srcService != "" { direction |= fromService serviceName = srcService copyFunc = s.copyFromContainer } if destService != "" { direction |= toService serviceName = destService copyFunc = s.copyToContainer } if direction == acrossServices { return errors.New("copying between services is not supported") } if direction == 0 { return errors.New("unknown copy direction") } containers, err := s.listContainersTargetedForCopy(ctx, projectName, options, direction, serviceName) if err != nil { return err } g := errgroup.Group{} for _, cont := range containers { ctr := cont g.Go(func() error { name := getCanonicalContainerName(ctr) var msg string if direction == fromService { msg = fmt.Sprintf("%s:%s to %s", name, srcPath, dstPath) } else { msg = fmt.Sprintf("%s to %s:%s", srcPath, name, dstPath) } s.events.On(api.Resource{ ID: name, Text: api.StatusCopying, Details: msg, Status: api.Working, }) if err := copyFunc(ctx, ctr.ID, srcPath, dstPath, options); err != nil { return err } s.events.On(api.Resource{ ID: name, Text: api.StatusCopied, Details: msg, Status: api.Done, }) return nil }) } return g.Wait() } func (s *composeService) listContainersTargetedForCopy(ctx context.Context, projectName string, options api.CopyOptions, direction copyDirection, serviceName string) (Containers, error) { var containers Containers var err error switch { case options.Index > 0: ctr, err := s.getSpecifiedContainer(ctx, projectName, oneOffExclude, true, serviceName, options.Index) if err != nil { return nil, err } return append(containers, ctr), nil default: withOneOff := oneOffExclude if options.All { withOneOff = oneOffInclude } containers, err = s.getContainers(ctx, projectName, withOneOff, true, serviceName) if err != nil { return nil, err } if len(containers) < 1 { return nil, fmt.Errorf("no container found for service %q", serviceName) } if direction == fromService { return containers[:1], err } return containers, err } } func (s *composeService) copyToContainer(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error { var err error if srcPath != "-" { // Get an absolute source path. srcPath, err = resolveLocalPath(srcPath) if err != nil { return err } } // Prepare destination copy info by stat-ing the container path. dstInfo := archive.CopyInfo{Path: dstPath} dstStat, err := s.apiClient().ContainerStatPath(ctx, containerID, dstPath) // If the destination is a symbolic link, we should evaluate it. if err == nil && dstStat.Mode&os.ModeSymlink != 0 { linkTarget := dstStat.LinkTarget if !isAbs(linkTarget) { // Join with the parent directory. dstParent, _ := archive.SplitPathDirEntry(dstPath) linkTarget = filepath.Join(dstParent, linkTarget) } dstInfo.Path = linkTarget dstStat, err = s.apiClient().ContainerStatPath(ctx, containerID, linkTarget) } // Validate the destination path if err := command.ValidateOutputPathFileMode(dstStat.Mode); err != nil { return fmt.Errorf(`destination "%s:%s" must be a directory or a regular file: %w`, containerID, dstPath, err) } // Ignore any error and assume that the parent directory of the destination // path exists, in which case the copy may still succeed. If there is any // type of conflict (e.g., non-directory overwriting an existing directory // or vice versa) the extraction will fail. If the destination simply did // not exist, but the parent directory does, the extraction will still // succeed. if err == nil { dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir() } var ( content io.Reader resolvedDstPath string ) if srcPath == "-" { content = s.stdin() resolvedDstPath = dstInfo.Path if !dstInfo.IsDir { return fmt.Errorf("destination \"%s:%s\" must be a directory", containerID, dstPath) } } else { // Prepare source copy info. srcInfo, err := archive.CopyInfoSourcePath(srcPath, opts.FollowLink) if err != nil { return err } srcArchive, err := archive.TarResource(srcInfo) if err != nil { return err } defer srcArchive.Close() //nolint:errcheck // With the stat info about the local source as well as the // destination, we have enough information to know whether we need to // alter the archive that we upload so that when the server extracts // it to the specified directory in the container we get the desired // copy behavior. // See comments in the implementation of `archive.PrepareArchiveCopy` // for exactly what goes into deciding how and whether the source // archive needs to be altered for the correct copy behavior when it is // extracted. This function also infers from the source and destination // info which directory to extract to, which may be the parent of the // destination that the user specified. // Don't create the archive if running in Dry Run mode if !s.dryRun { dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo) if err != nil { return err } defer preparedArchive.Close() //nolint:errcheck resolvedDstPath = dstDir content = preparedArchive } } options := container.CopyToContainerOptions{ AllowOverwriteDirWithFile: false, CopyUIDGID: opts.CopyUIDGID, } return s.apiClient().CopyToContainer(ctx, containerID, resolvedDstPath, content, options) } func (s *composeService) copyFromContainer(ctx context.Context, containerID, srcPath, dstPath string, opts api.CopyOptions) error { var err error if dstPath != "-" { // Get an absolute destination path. dstPath, err = resolveLocalPath(dstPath) if err != nil { return err } } if err := command.ValidateOutputPath(dstPath); err != nil { return err } // if client requests to follow symbol link, then must decide target file to be copied var rebaseName string if opts.FollowLink { srcStat, err := s.apiClient().ContainerStatPath(ctx, containerID, srcPath) // If the destination is a symbolic link, we should follow it. if err == nil && srcStat.Mode&os.ModeSymlink != 0 { linkTarget := srcStat.LinkTarget if !isAbs(linkTarget) { // Join with the parent directory. srcParent, _ := archive.SplitPathDirEntry(srcPath) linkTarget = filepath.Join(srcParent, linkTarget) } linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget) srcPath = linkTarget } } content, stat, err := s.apiClient().CopyFromContainer(ctx, containerID, srcPath) if err != nil { return err } defer content.Close() //nolint:errcheck if dstPath == "-" { _, err = io.Copy(s.stdout(), content) return err } srcInfo := archive.CopyInfo{ Path: srcPath, Exists: true, IsDir: stat.Mode.IsDir(), RebaseName: rebaseName, } preArchive := content if srcInfo.RebaseName != "" { _, srcBase := archive.SplitPathDirEntry(srcInfo.Path) preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName) } return archive.CopyTo(preArchive, srcInfo, dstPath) } // IsAbs is a platform-agnostic wrapper for filepath.IsAbs. // // On Windows, golang filepath.IsAbs does not consider a path \windows\system32 // as absolute as it doesn't start with a drive-letter/colon combination. However, // in docker we need to verify things such as WORKDIR /windows/system32 in // a Dockerfile (which gets translated to \windows\system32 when being processed // by the daemon). This SHOULD be treated as absolute from a docker processing // perspective. func isAbs(path string) bool { return filepath.IsAbs(path) || strings.HasPrefix(path, string(os.PathSeparator)) } func splitCpArg(arg string) (ctr, path string) { if isAbs(arg) { // Explicit local absolute path, e.g., `C:\foo` or `/foo`. return "", arg } parts := strings.SplitN(arg, ":", 2) if len(parts) == 1 || strings.HasPrefix(parts[0], ".") { // Either there's no `:` in the arg // OR it's an explicit local relative path like `./file:name.txt`. return "", arg } return parts[0], parts[1] } func resolveLocalPath(localPath string) (absPath string, err error) { if absPath, err = filepath.Abs(localPath); err != nil { return absPath, err } return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/docker_cli_providers.go
pkg/compose/docker_cli_providers.go
/* 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 ( "github.com/docker/cli/cli/command" ) // dockerCliContextInfo implements api.ContextInfo using Docker CLI type dockerCliContextInfo struct { cli command.Cli } func (c *dockerCliContextInfo) CurrentContext() string { return c.cli.CurrentContext() } func (c *dockerCliContextInfo) ServerOSType() string { return c.cli.ServerInfo().OSType } func (c *dockerCliContextInfo) BuildKitEnabled() (bool, error) { return c.cli.BuildKitEnabled() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/viz.go
pkg/compose/viz.go
/* Copyright 2023 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" "strconv" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/compose/v5/pkg/api" ) // maps a service with the services it depends on type vizGraph map[*types.ServiceConfig][]*types.ServiceConfig func (s *composeService) Viz(_ context.Context, project *types.Project, opts api.VizOptions) (string, error) { graph := make(vizGraph) for _, service := range project.Services { graph[&service] = make([]*types.ServiceConfig, 0, len(service.DependsOn)) for dependencyName := range service.DependsOn { // no error should be returned since dependencyName should exist dependency, _ := project.GetService(dependencyName) graph[&service] = append(graph[&service], &dependency) } } // build graphviz graph var graphBuilder strings.Builder // graph name graphBuilder.WriteString("digraph ") writeQuoted(&graphBuilder, project.Name) graphBuilder.WriteString(" {\n") // graph layout // dot is the perfect layout for this use case since graph is directed and hierarchical graphBuilder.WriteString(opts.Indentation + "layout=dot;\n") addNodes(&graphBuilder, graph, project.Name, &opts) graphBuilder.WriteByte('\n') addEdges(&graphBuilder, graph, &opts) graphBuilder.WriteString("}\n") return graphBuilder.String(), nil } // addNodes adds the corresponding graphviz representation of all the nodes in the given graph to the graphBuilder // returns the same graphBuilder func addNodes(graphBuilder *strings.Builder, graph vizGraph, projectName string, opts *api.VizOptions) *strings.Builder { for serviceNode := range graph { // write: // "service name" [style="filled" label<<font point-size="15">service name</font> graphBuilder.WriteString(opts.Indentation) writeQuoted(graphBuilder, serviceNode.Name) graphBuilder.WriteString(" [style=\"filled\" label=<<font point-size=\"15\">") graphBuilder.WriteString(serviceNode.Name) graphBuilder.WriteString("</font>") if opts.IncludeNetworks && len(serviceNode.Networks) > 0 { graphBuilder.WriteString("<font point-size=\"10\">") graphBuilder.WriteString("<br/><br/><b>Networks:</b>") for _, networkName := range serviceNode.NetworksByPriority() { graphBuilder.WriteString("<br/>") graphBuilder.WriteString(networkName) } graphBuilder.WriteString("</font>") } if opts.IncludePorts && len(serviceNode.Ports) > 0 { graphBuilder.WriteString("<font point-size=\"10\">") graphBuilder.WriteString("<br/><br/><b>Ports:</b>") for _, portConfig := range serviceNode.Ports { graphBuilder.WriteString("<br/>") if portConfig.HostIP != "" { graphBuilder.WriteString(portConfig.HostIP) graphBuilder.WriteByte(':') } graphBuilder.WriteString(portConfig.Published) graphBuilder.WriteByte(':') graphBuilder.WriteString(strconv.Itoa(int(portConfig.Target))) graphBuilder.WriteString(" (") graphBuilder.WriteString(portConfig.Protocol) graphBuilder.WriteString(", ") graphBuilder.WriteString(portConfig.Mode) graphBuilder.WriteString(")") } graphBuilder.WriteString("</font>") } if opts.IncludeImageName { graphBuilder.WriteString("<font point-size=\"10\">") graphBuilder.WriteString("<br/><br/><b>Image:</b><br/>") graphBuilder.WriteString(api.GetImageNameOrDefault(*serviceNode, projectName)) graphBuilder.WriteString("</font>") } graphBuilder.WriteString(">];\n") } return graphBuilder } // addEdges adds the corresponding graphviz representation of all edges in the given graph to the graphBuilder // returns the same graphBuilder func addEdges(graphBuilder *strings.Builder, graph vizGraph, opts *api.VizOptions) *strings.Builder { for parent, children := range graph { for _, child := range children { graphBuilder.WriteString(opts.Indentation) writeQuoted(graphBuilder, parent.Name) graphBuilder.WriteString(" -> ") writeQuoted(graphBuilder, child.Name) graphBuilder.WriteString(";\n") } } return graphBuilder } // writeQuoted writes "str" to builder func writeQuoted(builder *strings.Builder, str string) { builder.WriteByte('"') builder.WriteString(str) builder.WriteByte('"') }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/pull.go
pkg/compose/pull.go
/* 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" "encoding/base64" "encoding/json" "errors" "fmt" "io" "strings" "sync" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/distribution/reference" "github.com/docker/buildx/driver" "github.com/docker/cli/cli/config/configfile" "github.com/docker/docker/api/types/image" "github.com/docker/docker/client" "github.com/docker/docker/pkg/jsonmessage" "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/internal/registry" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Pull(ctx context.Context, project *types.Project, options api.PullOptions) error { return Run(ctx, func(ctx context.Context) error { return s.pull(ctx, project, options) }, "pull", s.events) } func (s *composeService) pull(ctx context.Context, project *types.Project, opts api.PullOptions) error { //nolint:gocyclo images, err := s.getLocalImagesDigests(ctx, project) if err != nil { return err } eg, ctx := errgroup.WithContext(ctx) eg.SetLimit(s.maxConcurrency) var ( mustBuild []string pullErrors = make([]error, len(project.Services)) imagesBeingPulled = map[string]string{} ) i := 0 for name, service := range project.Services { if service.Image == "" { s.events.On(api.Resource{ ID: name, Status: api.Done, Text: "Skipped", Details: "No image to be pulled", }) continue } switch service.PullPolicy { case types.PullPolicyNever, types.PullPolicyBuild: s.events.On(api.Resource{ ID: "Image " + service.Image, Status: api.Done, Text: "Skipped", }) continue case types.PullPolicyMissing, types.PullPolicyIfNotPresent: if imageAlreadyPresent(service.Image, images) { s.events.On(api.Resource{ ID: "Image " + service.Image, Status: api.Done, Text: "Skipped", Details: "Image is already present locally", }) continue } } if service.Build != nil && opts.IgnoreBuildable { s.events.On(api.Resource{ ID: "Image " + service.Image, Status: api.Done, Text: "Skipped", Details: "Image can be built", }) continue } if _, ok := imagesBeingPulled[service.Image]; ok { continue } imagesBeingPulled[service.Image] = service.Name idx := i eg.Go(func() error { _, err := s.pullServiceImage(ctx, service, opts.Quiet, project.Environment["DOCKER_DEFAULT_PLATFORM"]) if err != nil { pullErrors[idx] = err if service.Build != nil { mustBuild = append(mustBuild, service.Name) } if !opts.IgnoreFailures && service.Build == nil { if s.dryRun { s.events.On(errorEventf("Image "+service.Image, "error pulling image: %s", service.Image)) } // fail fast if image can't be pulled nor built return err } } return nil }) i++ } err = eg.Wait() if len(mustBuild) > 0 { logrus.Warnf("WARNING: Some service image(s) must be built from source by running:\n docker compose build %s", strings.Join(mustBuild, " ")) } if err != nil { return err } if opts.IgnoreFailures { return nil } return errors.Join(pullErrors...) } func imageAlreadyPresent(serviceImage string, localImages map[string]api.ImageSummary) bool { normalizedImage, err := reference.ParseDockerRef(serviceImage) if err != nil { return false } switch refType := normalizedImage.(type) { case reference.NamedTagged: _, ok := localImages[serviceImage] return ok && refType.Tag() != "latest" default: _, ok := localImages[serviceImage] return ok } } func getUnwrappedErrorMessage(err error) string { derr := errors.Unwrap(err) if derr != nil { return getUnwrappedErrorMessage(derr) } return err.Error() } func (s *composeService) pullServiceImage(ctx context.Context, service types.ServiceConfig, quietPull bool, defaultPlatform string) (string, error) { resource := "Image " + service.Image s.events.On(pullingEvent(service.Image)) ref, err := reference.ParseNormalizedNamed(service.Image) if err != nil { return "", err } encodedAuth, err := encodedAuth(ref, s.configFile()) if err != nil { return "", err } platform := service.Platform if platform == "" { platform = defaultPlatform } stream, err := s.apiClient().ImagePull(ctx, service.Image, image.PullOptions{ RegistryAuth: encodedAuth, Platform: platform, }) if ctx.Err() != nil { s.events.On(api.Resource{ ID: resource, Status: api.Warning, Text: "Interrupted", }) return "", nil } // check if has error and the service has a build section // then the status should be warning instead of error if err != nil && service.Build != nil { s.events.On(api.Resource{ ID: resource, Status: api.Warning, Text: getUnwrappedErrorMessage(err), }) return "", err } if err != nil { s.events.On(errorEvent(resource, getUnwrappedErrorMessage(err))) return "", err } dec := json.NewDecoder(stream) for { var jm jsonmessage.JSONMessage if err := dec.Decode(&jm); err != nil { if errors.Is(err, io.EOF) { break } return "", err } if jm.Error != nil { return "", errors.New(jm.Error.Message) } if !quietPull { toPullProgressEvent(resource, jm, s.events) } } s.events.On(pulledEvent(service.Image)) inspected, err := s.apiClient().ImageInspect(ctx, service.Image) if err != nil { return "", err } return inspected.ID, nil } // ImageDigestResolver creates a func able to resolve image digest from a docker ref, func ImageDigestResolver(ctx context.Context, file *configfile.ConfigFile, apiClient client.APIClient) func(named reference.Named) (digest.Digest, error) { return func(named reference.Named) (digest.Digest, error) { auth, err := encodedAuth(named, file) if err != nil { return "", err } inspect, err := apiClient.DistributionInspect(ctx, named.String(), auth) if err != nil { return "", fmt.Errorf("failed to resolve digest for %s: %w", named.String(), err) } return inspect.Descriptor.Digest, nil } } func encodedAuth(ref reference.Named, configFile driver.Auth) (string, error) { authConfig, err := configFile.GetAuthConfig(registry.GetAuthConfigKey(reference.Domain(ref))) if err != nil { return "", err } buf, err := json.Marshal(authConfig) if err != nil { return "", err } return base64.URLEncoding.EncodeToString(buf), nil } func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]api.ImageSummary, quietPull bool) error { needPull := map[string]types.ServiceConfig{} for name, service := range project.Services { pull, err := mustPull(service, images) if err != nil { return err } if pull { needPull[name] = service } for i, vol := range service.Volumes { if vol.Type == types.VolumeTypeImage { if _, ok := images[vol.Source]; !ok { // Hack: create a fake ServiceConfig so we pull missing volume image n := fmt.Sprintf("%s:volume %d", name, i) needPull[n] = types.ServiceConfig{ Name: n, Image: vol.Source, } } } } } if len(needPull) == 0 { return nil } eg, ctx := errgroup.WithContext(ctx) eg.SetLimit(s.maxConcurrency) pulledImages := map[string]api.ImageSummary{} var mutex sync.Mutex for name, service := range needPull { eg.Go(func() error { id, err := s.pullServiceImage(ctx, service, quietPull, project.Environment["DOCKER_DEFAULT_PLATFORM"]) mutex.Lock() defer mutex.Unlock() pulledImages[name] = api.ImageSummary{ ID: id, Repository: service.Image, LastTagTime: time.Now(), } if err != nil && isServiceImageToBuild(service, project.Services) { // image can be built, so we can ignore pull failure return nil } return err }) } err := eg.Wait() for i, service := range needPull { if pulledImages[i].ID != "" { images[service.Image] = pulledImages[i] } } return err } func mustPull(service types.ServiceConfig, images map[string]api.ImageSummary) (bool, error) { if service.Provider != nil { return false, nil } if service.Image == "" { return false, nil } policy, duration, err := service.GetPullPolicy() if err != nil { return false, err } switch policy { case types.PullPolicyAlways: // force pull return true, nil case types.PullPolicyNever, types.PullPolicyBuild: return false, nil case types.PullPolicyRefresh: img, ok := images[service.Image] if !ok { return true, nil } return time.Now().After(img.LastTagTime.Add(duration)), nil default: // Pull if missing _, ok := images[service.Image] return !ok, nil } } func isServiceImageToBuild(service types.ServiceConfig, services types.Services) bool { if service.Build != nil { return true } if service.Image == "" { // N.B. this should be impossible as service must have either `build` or `image` (or both) return false } // look through the other services to see if another has a build definition for the same // image name for _, svc := range services { if svc.Image == service.Image && svc.Build != nil { return true } } return false } const ( PreparingPhase = "Preparing" WaitingPhase = "waiting" PullingFsPhase = "Pulling fs layer" DownloadingPhase = "Downloading" DownloadCompletePhase = "Download complete" ExtractingPhase = "Extracting" VerifyingChecksumPhase = "Verifying Checksum" AlreadyExistsPhase = "Already exists" PullCompletePhase = "Pull complete" ) func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, events api.EventProcessor) { if jm.ID == "" || jm.Progress == nil { return } var ( progress string total int64 percent int current int64 status = api.Working ) progress = jm.Progress.String() switch jm.Status { case PreparingPhase, WaitingPhase, PullingFsPhase: percent = 0 case DownloadingPhase, ExtractingPhase, VerifyingChecksumPhase: if jm.Progress != nil { current = jm.Progress.Current total = jm.Progress.Total if jm.Progress.Total > 0 { percent = int(jm.Progress.Current * 100 / jm.Progress.Total) if percent > 100 { percent = 100 } } } case DownloadCompletePhase, AlreadyExistsPhase, PullCompletePhase: status = api.Done percent = 100 } if strings.Contains(jm.Status, "Image is up to date") || strings.Contains(jm.Status, "Downloaded newer image") { status = api.Done percent = 100 } if jm.Error != nil { status = api.Error progress = jm.Error.Message } events.On(api.Resource{ ID: jm.ID, ParentID: parent, Current: current, Total: total, Percent: percent, Status: status, Text: jm.Status, Details: progress, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/convergence.go
pkg/compose/convergence.go
/* 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" "maps" "slices" "sort" "strconv" "strings" "sync" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/platforms" "github.com/docker/docker/api/types/container" mmount "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/versions" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/sirupsen/logrus" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/internal/tracing" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) const ( doubledContainerNameWarning = "WARNING: The %q service is using the custom container name %q. " + "Docker requires each container to have a unique name. " + "Remove the custom name to scale the service" ) // convergence manages service's container lifecycle. // Based on initially observed state, it reconciles the existing container with desired state, which might include // re-creating container, adding or removing replicas, or starting stopped containers. // Cross services dependencies are managed by creating services in expected order and updating `service:xx` reference // when a service has converged, so dependent ones can be managed with resolved containers references. type convergence struct { compose *composeService services map[string]Containers networks map[string]string volumes map[string]string stateMutex sync.Mutex } func (c *convergence) getObservedState(serviceName string) Containers { c.stateMutex.Lock() defer c.stateMutex.Unlock() return c.services[serviceName] } func (c *convergence) setObservedState(serviceName string, containers Containers) { c.stateMutex.Lock() defer c.stateMutex.Unlock() c.services[serviceName] = containers } func newConvergence(services []string, state Containers, networks map[string]string, volumes map[string]string, s *composeService) *convergence { observedState := map[string]Containers{} for _, s := range services { observedState[s] = Containers{} } for _, c := range state.filter(isNotOneOff) { service := c.Labels[api.ServiceLabel] observedState[service] = append(observedState[service], c) } return &convergence{ compose: s, services: observedState, networks: networks, volumes: volumes, } } func (c *convergence) apply(ctx context.Context, project *types.Project, options api.CreateOptions) error { return InDependencyOrder(ctx, project, func(ctx context.Context, name string) error { service, err := project.GetService(name) if err != nil { return err } return tracing.SpanWrapFunc("service/apply", tracing.ServiceOptions(service), func(ctx context.Context) error { strategy := options.RecreateDependencies if slices.Contains(options.Services, name) { strategy = options.Recreate } return c.ensureService(ctx, project, service, strategy, options.Inherit, options.Timeout) })(ctx) }) } func (c *convergence) ensureService(ctx context.Context, project *types.Project, service types.ServiceConfig, recreate string, inherit bool, timeout *time.Duration) error { //nolint:gocyclo if service.Provider != nil { return c.compose.runPlugin(ctx, project, service, "up") } expected, err := getScale(service) if err != nil { return err } containers := c.getObservedState(service.Name) actual := len(containers) updated := make(Containers, expected) eg, ctx := errgroup.WithContext(ctx) err = c.resolveServiceReferences(&service) if err != nil { return err } sort.Slice(containers, func(i, j int) bool { // select obsolete containers first, so they get removed as we scale down if obsolete, _ := c.mustRecreate(service, containers[i], recreate); obsolete { // i is obsolete, so must be first in the list return true } if obsolete, _ := c.mustRecreate(service, containers[j], recreate); obsolete { // j is obsolete, so must be first in the list return false } // For up-to-date containers, sort by container number to preserve low-values in container numbers ni, erri := strconv.Atoi(containers[i].Labels[api.ContainerNumberLabel]) nj, errj := strconv.Atoi(containers[j].Labels[api.ContainerNumberLabel]) if erri == nil && errj == nil { return ni > nj } // If we don't get a container number (?) just sort by creation date return containers[i].Created < containers[j].Created }) slices.Reverse(containers) for i, ctr := range containers { if i >= expected { // Scale Down // As we sorted containers, obsolete ones and/or highest number will be removed ctr := ctr traceOpts := append(tracing.ServiceOptions(service), tracing.ContainerOptions(ctr)...) eg.Go(tracing.SpanWrapFuncForErrGroup(ctx, "service/scale/down", traceOpts, func(ctx context.Context) error { return c.compose.stopAndRemoveContainer(ctx, ctr, &service, timeout, false) })) continue } mustRecreate, err := c.mustRecreate(service, ctr, recreate) if err != nil { return err } if mustRecreate { err := c.stopDependentContainers(ctx, project, service) if err != nil { return err } i, ctr := i, ctr eg.Go(tracing.SpanWrapFuncForErrGroup(ctx, "container/recreate", tracing.ContainerOptions(ctr), func(ctx context.Context) error { recreated, err := c.compose.recreateContainer(ctx, project, service, ctr, inherit, timeout) updated[i] = recreated return err })) continue } // Enforce non-diverged containers are running name := getContainerProgressName(ctr) switch ctr.State { case container.StateRunning: c.compose.events.On(runningEvent(name)) case container.StateCreated: case container.StateRestarting: case container.StateExited: default: ctr := ctr eg.Go(tracing.EventWrapFuncForErrGroup(ctx, "service/start", tracing.ContainerOptions(ctr), func(ctx context.Context) error { return c.compose.startContainer(ctx, ctr) })) } updated[i] = ctr } next := nextContainerNumber(containers) for i := 0; i < expected-actual; i++ { // Scale UP number := next + i name := getContainerName(project.Name, service, number) eventOpts := tracing.SpanOptions{trace.WithAttributes(attribute.String("container.name", name))} eg.Go(tracing.EventWrapFuncForErrGroup(ctx, "service/scale/up", eventOpts, func(ctx context.Context) error { opts := createOptions{ AutoRemove: false, AttachStdin: false, UseNetworkAliases: true, Labels: mergeLabels(service.Labels, service.CustomLabels), } ctr, err := c.compose.createContainer(ctx, project, service, name, number, opts) updated[actual+i] = ctr return err })) continue } err = eg.Wait() c.setObservedState(service.Name, updated) return err } func (c *convergence) stopDependentContainers(ctx context.Context, project *types.Project, service types.ServiceConfig) error { // Stop dependent containers, so they will be restarted after service is re-created dependents := project.GetDependentsForService(service, func(dependency types.ServiceDependency) bool { return dependency.Restart }) if len(dependents) == 0 { return nil } err := c.compose.stop(ctx, project.Name, api.StopOptions{ Services: dependents, Project: project, }, nil) if err != nil { return err } for _, name := range dependents { dependentStates := c.getObservedState(name) for i, dependent := range dependentStates { dependent.State = container.StateExited dependentStates[i] = dependent } c.setObservedState(name, dependentStates) } return nil } func getScale(config types.ServiceConfig) (int, error) { scale := config.GetScale() if scale > 1 && config.ContainerName != "" { return 0, fmt.Errorf(doubledContainerNameWarning, config.Name, config.ContainerName) } return scale, nil } // resolveServiceReferences replaces reference to another service with reference to an actual container func (c *convergence) resolveServiceReferences(service *types.ServiceConfig) error { err := c.resolveVolumeFrom(service) if err != nil { return err } err = c.resolveSharedNamespaces(service) if err != nil { return err } return nil } func (c *convergence) resolveVolumeFrom(service *types.ServiceConfig) error { for i, vol := range service.VolumesFrom { spec := strings.Split(vol, ":") if len(spec) == 0 { continue } if spec[0] == "container" { service.VolumesFrom[i] = spec[1] continue } name := spec[0] dependencies := c.getObservedState(name) if len(dependencies) == 0 { return fmt.Errorf("cannot share volume with service %s: container missing", name) } service.VolumesFrom[i] = dependencies.sorted()[0].ID } return nil } func (c *convergence) resolveSharedNamespaces(service *types.ServiceConfig) error { str := service.NetworkMode if name := getDependentServiceFromMode(str); name != "" { dependencies := c.getObservedState(name) if len(dependencies) == 0 { return fmt.Errorf("cannot share network namespace with service %s: container missing", name) } service.NetworkMode = types.ContainerPrefix + dependencies.sorted()[0].ID } str = service.Ipc if name := getDependentServiceFromMode(str); name != "" { dependencies := c.getObservedState(name) if len(dependencies) == 0 { return fmt.Errorf("cannot share IPC namespace with service %s: container missing", name) } service.Ipc = types.ContainerPrefix + dependencies.sorted()[0].ID } str = service.Pid if name := getDependentServiceFromMode(str); name != "" { dependencies := c.getObservedState(name) if len(dependencies) == 0 { return fmt.Errorf("cannot share PID namespace with service %s: container missing", name) } service.Pid = types.ContainerPrefix + dependencies.sorted()[0].ID } return nil } func (c *convergence) mustRecreate(expected types.ServiceConfig, actual container.Summary, policy string) (bool, error) { if policy == api.RecreateNever { return false, nil } if policy == api.RecreateForce { return true, nil } configHash, err := ServiceHash(expected) if err != nil { return false, err } configChanged := actual.Labels[api.ConfigHashLabel] != configHash imageUpdated := actual.Labels[api.ImageDigestLabel] != expected.CustomLabels[api.ImageDigestLabel] if configChanged || imageUpdated { return true, nil } if c.networks != nil && actual.State == "running" { if checkExpectedNetworks(expected, actual, c.networks) { return true, nil } } if c.volumes != nil { if checkExpectedVolumes(expected, actual, c.volumes) { return true, nil } } return false, nil } func checkExpectedNetworks(expected types.ServiceConfig, actual container.Summary, networks map[string]string) bool { // check the networks container is connected to are the expected ones for net := range expected.Networks { id := networks[net] if id == "swarm" { // corner-case : swarm overlay network isn't visible until a container is attached continue } found := false for _, settings := range actual.NetworkSettings.Networks { if settings.NetworkID == id { found = true break } } if !found { // config is up-to-date but container is not connected to network return true } } return false } func checkExpectedVolumes(expected types.ServiceConfig, actual container.Summary, volumes map[string]string) bool { // check container's volume mounts and search for the expected ones for _, vol := range expected.Volumes { if vol.Type != string(mmount.TypeVolume) { continue } if vol.Source == "" { continue } id := volumes[vol.Source] found := false for _, mount := range actual.Mounts { if mount.Type != mmount.TypeVolume { continue } if mount.Name == id { found = true break } } if !found { // config is up-to-date but container doesn't have volume mounted return true } } return false } func getContainerName(projectName string, service types.ServiceConfig, number int) string { name := getDefaultContainerName(projectName, service.Name, strconv.Itoa(number)) if service.ContainerName != "" { name = service.ContainerName } return name } func getDefaultContainerName(projectName, serviceName, index string) string { return strings.Join([]string{projectName, serviceName, index}, api.Separator) } func getContainerProgressName(ctr container.Summary) string { return "Container " + getCanonicalContainerName(ctr) } func containerEvents(containers Containers, eventFunc func(string) api.Resource) []api.Resource { events := []api.Resource{} for _, ctr := range containers { events = append(events, eventFunc(getContainerProgressName(ctr))) } return events } func containerReasonEvents(containers Containers, eventFunc func(string, string) api.Resource, reason string) []api.Resource { events := []api.Resource{} for _, ctr := range containers { events = append(events, eventFunc(getContainerProgressName(ctr), reason)) } return events } // ServiceConditionRunningOrHealthy is a service condition on status running or healthy const ServiceConditionRunningOrHealthy = "running_or_healthy" //nolint:gocyclo func (s *composeService) waitDependencies(ctx context.Context, project *types.Project, dependant string, dependencies types.DependsOnConfig, containers Containers, timeout time.Duration) error { if timeout > 0 { withTimeout, cancelFunc := context.WithTimeout(ctx, timeout) defer cancelFunc() ctx = withTimeout } eg, ctx := errgroup.WithContext(ctx) for dep, config := range dependencies { if shouldWait, err := shouldWaitForDependency(dep, config, project); err != nil { return err } else if !shouldWait { continue } waitingFor := containers.filter(isService(dep), isNotOneOff) s.events.On(containerEvents(waitingFor, waiting)...) if len(waitingFor) == 0 { if config.Required { return fmt.Errorf("%s is missing dependency %s", dependant, dep) } logrus.Warnf("%s is missing dependency %s", dependant, dep) continue } eg.Go(func() error { ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() for { select { case <-ticker.C: case <-ctx.Done(): return nil } switch config.Condition { case ServiceConditionRunningOrHealthy: isHealthy, err := s.isServiceHealthy(ctx, waitingFor, true) if err != nil { if !config.Required { s.events.On(containerReasonEvents(waitingFor, skippedEvent, fmt.Sprintf("optional dependency %q is not running or is unhealthy", dep))...) logrus.Warnf("optional dependency %q is not running or is unhealthy: %s", dep, err.Error()) return nil } return err } if isHealthy { s.events.On(containerEvents(waitingFor, healthy)...) return nil } case types.ServiceConditionHealthy: isHealthy, err := s.isServiceHealthy(ctx, waitingFor, false) if err != nil { if !config.Required { s.events.On(containerReasonEvents(waitingFor, skippedEvent, fmt.Sprintf("optional dependency %q failed to start", dep))...) logrus.Warnf("optional dependency %q failed to start: %s", dep, err.Error()) return nil } s.events.On(containerEvents(waitingFor, func(s string) api.Resource { return errorEventf(s, "dependency %s failed to start", dep) })...) return fmt.Errorf("dependency failed to start: %w", err) } if isHealthy { s.events.On(containerEvents(waitingFor, healthy)...) return nil } case types.ServiceConditionCompletedSuccessfully: isExited, code, err := s.isServiceCompleted(ctx, waitingFor) if err != nil { return err } if isExited { if code == 0 { s.events.On(containerEvents(waitingFor, exited)...) return nil } messageSuffix := fmt.Sprintf("%q didn't complete successfully: exit %d", dep, code) if !config.Required { // optional -> mark as skipped & don't propagate error s.events.On(containerReasonEvents(waitingFor, skippedEvent, fmt.Sprintf("optional dependency %s", messageSuffix))...) logrus.Warnf("optional dependency %s", messageSuffix) return nil } msg := fmt.Sprintf("service %s", messageSuffix) s.events.On(containerEvents(waitingFor, func(s string) api.Resource { return errorEventf(s, "service %s", messageSuffix) })...) return errors.New(msg) } default: logrus.Warnf("unsupported depends_on condition: %s", config.Condition) return nil } } }) } err := eg.Wait() if errors.Is(err, context.DeadlineExceeded) { return fmt.Errorf("timeout waiting for dependencies") } return err } func shouldWaitForDependency(serviceName string, dependencyConfig types.ServiceDependency, project *types.Project) (bool, error) { if dependencyConfig.Condition == types.ServiceConditionStarted { // already managed by InDependencyOrder return false, nil } if service, err := project.GetService(serviceName); err != nil { for _, ds := range project.DisabledServices { if ds.Name == serviceName { // don't wait for disabled service (--no-deps) return false, nil } } return false, err } else if service.GetScale() == 0 { // don't wait for the dependency which configured to have 0 containers running return false, nil } else if service.Provider != nil { // don't wait for provider services return false, nil } return true, nil } func nextContainerNumber(containers []container.Summary) int { maxNumber := 0 for _, c := range containers { s, ok := c.Labels[api.ContainerNumberLabel] if !ok { logrus.Warnf("container %s is missing %s label", c.ID, api.ContainerNumberLabel) } n, err := strconv.Atoi(s) if err != nil { logrus.Warnf("container %s has invalid %s label: %s", c.ID, api.ContainerNumberLabel, s) continue } if n > maxNumber { maxNumber = n } } return maxNumber + 1 } func (s *composeService) createContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, name string, number int, opts createOptions, ) (ctr container.Summary, err error) { eventName := "Container " + name s.events.On(creatingEvent(eventName)) ctr, err = s.createMobyContainer(ctx, project, service, name, number, nil, opts) if err != nil { if ctx.Err() == nil { s.events.On(api.Resource{ ID: eventName, Status: api.Error, Text: err.Error(), }) } return ctr, err } s.events.On(createdEvent(eventName)) return ctr, nil } func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, replaced container.Summary, inherit bool, timeout *time.Duration, ) (created container.Summary, err error) { eventName := getContainerProgressName(replaced) s.events.On(newEvent(eventName, api.Working, "Recreate")) defer func() { if err != nil && ctx.Err() == nil { s.events.On(api.Resource{ ID: eventName, Status: api.Error, Text: err.Error(), }) } }() number, err := strconv.Atoi(replaced.Labels[api.ContainerNumberLabel]) if err != nil { return created, err } var inherited *container.Summary if inherit { inherited = &replaced } replacedContainerName := service.ContainerName if replacedContainerName == "" { replacedContainerName = service.Name + api.Separator + strconv.Itoa(number) } name := getContainerName(project.Name, service, number) tmpName := fmt.Sprintf("%s_%s", replaced.ID[:12], name) opts := createOptions{ AutoRemove: false, AttachStdin: false, UseNetworkAliases: true, Labels: mergeLabels(service.Labels, service.CustomLabels).Add(api.ContainerReplaceLabel, replacedContainerName), } created, err = s.createMobyContainer(ctx, project, service, tmpName, number, inherited, opts) if err != nil { return created, err } timeoutInSecond := utils.DurationSecondToInt(timeout) err = s.apiClient().ContainerStop(ctx, replaced.ID, container.StopOptions{Timeout: timeoutInSecond}) if err != nil { return created, err } err = s.apiClient().ContainerRemove(ctx, replaced.ID, container.RemoveOptions{}) if err != nil { return created, err } err = s.apiClient().ContainerRename(ctx, tmpName, name) if err != nil { return created, err } s.events.On(newEvent(eventName, api.Done, "Recreated")) return created, err } // force sequential calls to ContainerStart to prevent race condition in engine assigning ports from ranges var startMx sync.Mutex func (s *composeService) startContainer(ctx context.Context, ctr container.Summary) error { s.events.On(newEvent(getContainerProgressName(ctr), api.Working, "Restart")) startMx.Lock() defer startMx.Unlock() err := s.apiClient().ContainerStart(ctx, ctr.ID, container.StartOptions{}) if err != nil { return err } s.events.On(newEvent(getContainerProgressName(ctr), api.Done, "Restarted")) return nil } func (s *composeService) createMobyContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, name string, number int, inherit *container.Summary, opts createOptions, ) (container.Summary, error) { var created container.Summary cfgs, err := s.getCreateConfigs(ctx, project, service, number, inherit, opts) if err != nil { return created, err } platform := service.Platform if platform == "" { platform = project.Environment["DOCKER_DEFAULT_PLATFORM"] } var plat *specs.Platform if platform != "" { var p specs.Platform p, err = platforms.Parse(platform) if err != nil { return created, err } plat = &p } response, err := s.apiClient().ContainerCreate(ctx, cfgs.Container, cfgs.Host, cfgs.Network, plat, name) if err != nil { return created, err } for _, warning := range response.Warnings { s.events.On(api.Resource{ ID: service.Name, Status: api.Warning, Text: warning, }) } inspectedContainer, err := s.apiClient().ContainerInspect(ctx, response.ID) if err != nil { return created, err } created = container.Summary{ ID: inspectedContainer.ID, Labels: inspectedContainer.Config.Labels, Names: []string{inspectedContainer.Name}, NetworkSettings: &container.NetworkSettingsSummary{ Networks: inspectedContainer.NetworkSettings.Networks, }, } apiVersion, err := s.RuntimeVersion(ctx) if err != nil { return created, err } // Starting API version 1.44, the ContainerCreate API call takes multiple networks // so we include all the configurations there and can skip the one-by-one calls here if versions.LessThan(apiVersion, "1.44") { // the highest-priority network is the primary and is included in the ContainerCreate API // call via container.NetworkMode & network.NetworkingConfig // any remaining networks are connected one-by-one here after creation (but before start) serviceNetworks := service.NetworksByPriority() for _, networkKey := range serviceNetworks { mobyNetworkName := project.Networks[networkKey].Name if string(cfgs.Host.NetworkMode) == mobyNetworkName { // primary network already configured as part of ContainerCreate continue } epSettings := createEndpointSettings(project, service, number, networkKey, cfgs.Links, opts.UseNetworkAliases) if err := s.apiClient().NetworkConnect(ctx, mobyNetworkName, created.ID, epSettings); err != nil { return created, err } } } return created, nil } // getLinks mimics V1 compose/service.py::Service::_get_links() func (s *composeService) getLinks(ctx context.Context, projectName string, service types.ServiceConfig, number int) ([]string, error) { var links []string format := func(k, v string) string { return fmt.Sprintf("%s:%s", k, v) } getServiceContainers := func(serviceName string) (Containers, error) { return s.getContainers(ctx, projectName, oneOffExclude, true, serviceName) } for _, rawLink := range service.Links { linkSplit := strings.Split(rawLink, ":") linkServiceName := linkSplit[0] linkName := linkServiceName if len(linkSplit) == 2 { linkName = linkSplit[1] // linkName if informed like in: "serviceName:linkName" } cnts, err := getServiceContainers(linkServiceName) if err != nil { return nil, err } for _, c := range cnts { containerName := getCanonicalContainerName(c) links = append(links, format(containerName, linkName), format(containerName, linkServiceName+api.Separator+strconv.Itoa(number)), format(containerName, strings.Join([]string{projectName, linkServiceName, strconv.Itoa(number)}, api.Separator)), ) } } if service.Labels[api.OneoffLabel] == "True" { cnts, err := getServiceContainers(service.Name) if err != nil { return nil, err } for _, c := range cnts { containerName := getCanonicalContainerName(c) links = append(links, format(containerName, service.Name), format(containerName, strings.TrimPrefix(containerName, projectName+api.Separator)), format(containerName, containerName), ) } } for _, rawExtLink := range service.ExternalLinks { extLinkSplit := strings.Split(rawExtLink, ":") externalLink := extLinkSplit[0] linkName := externalLink if len(extLinkSplit) == 2 { linkName = extLinkSplit[1] } links = append(links, format(externalLink, linkName)) } return links, nil } func (s *composeService) isServiceHealthy(ctx context.Context, containers Containers, fallbackRunning bool) (bool, error) { for _, c := range containers { ctr, err := s.apiClient().ContainerInspect(ctx, c.ID) if err != nil { return false, err } name := ctr.Name[1:] if ctr.State.Status == container.StateExited { return false, fmt.Errorf("container %s exited (%d)", name, ctr.State.ExitCode) } if ctr.Config.Healthcheck == nil && fallbackRunning { // Container does not define a health check, but we can fall back to "running" state return ctr.State != nil && ctr.State.Status == container.StateRunning, nil } if ctr.State == nil || ctr.State.Health == nil { return false, fmt.Errorf("container %s has no healthcheck configured", name) } switch ctr.State.Health.Status { case container.Healthy: // Continue by checking the next container. case container.Unhealthy: return false, fmt.Errorf("container %s is unhealthy", name) case container.Starting: return false, nil default: return false, fmt.Errorf("container %s had unexpected health status %q", name, ctr.State.Health.Status) } } return true, nil } func (s *composeService) isServiceCompleted(ctx context.Context, containers Containers) (bool, int, error) { for _, c := range containers { ctr, err := s.apiClient().ContainerInspect(ctx, c.ID) if err != nil { return false, 0, err } if ctr.State != nil && ctr.State.Status == container.StateExited { return true, ctr.State.ExitCode, nil } } return false, 0, nil } func (s *composeService) startService(ctx context.Context, project *types.Project, service types.ServiceConfig, containers Containers, listener api.ContainerEventListener, timeout time.Duration, ) error { if service.Deploy != nil && service.Deploy.Replicas != nil && *service.Deploy.Replicas == 0 { return nil } err := s.waitDependencies(ctx, project, service.Name, service.DependsOn, containers, timeout) if err != nil { return err } if len(containers) == 0 { if service.GetScale() == 0 { return nil } return fmt.Errorf("service %q has no container to start", service.Name) } for _, ctr := range containers.filter(isService(service.Name)) { if ctr.State == container.StateRunning { continue } err = s.injectSecrets(ctx, project, service, ctr.ID) if err != nil { return err } err = s.injectConfigs(ctx, project, service, ctr.ID) if err != nil { return err } eventName := getContainerProgressName(ctr) s.events.On(startingEvent(eventName)) err = s.apiClient().ContainerStart(ctx, ctr.ID, container.StartOptions{}) if err != nil { return err } for _, hook := range service.PostStart { err = s.runHook(ctx, ctr, service, hook, listener) if err != nil { return err } } s.events.On(startedEvent(eventName)) } return nil } func mergeLabels(ls ...types.Labels) types.Labels { merged := types.Labels{} for _, l := range ls { maps.Copy(merged, l) } return merged }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/events.go
pkg/compose/events.go
/* 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" "slices" "strings" "time" "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/filters" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Events(ctx context.Context, projectName string, options api.EventsOptions) error { projectName = strings.ToLower(projectName) evts, errors := s.apiClient().Events(ctx, events.ListOptions{ Filters: filters.NewArgs(projectFilter(projectName)), Since: options.Since, Until: options.Until, }) for { select { case event := <-evts: // TODO: support other event types if event.Type != "container" { continue } oneOff := event.Actor.Attributes[api.OneoffLabel] if oneOff == "True" { // ignore continue } service := event.Actor.Attributes[api.ServiceLabel] if len(options.Services) > 0 && !slices.Contains(options.Services, service) { continue } attributes := map[string]string{} for k, v := range event.Actor.Attributes { if strings.HasPrefix(k, "com.docker.compose.") { continue } attributes[k] = v } timestamp := time.Unix(event.Time, 0) if event.TimeNano != 0 { timestamp = time.Unix(0, event.TimeNano) } err := options.Consumer(api.Event{ Timestamp: timestamp, Service: service, Container: event.Actor.ID, Status: string(event.Action), Attributes: attributes, }) if err != nil { return err } case err := <-errors: return err } } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/generate.go
pkg/compose/generate.go
/* Copyright 2023 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" "fmt" "maps" "slices" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Generate(ctx context.Context, options api.GenerateOptions) (*types.Project, error) { filtersListNames := filters.NewArgs() filtersListIDs := filters.NewArgs() for _, containerName := range options.Containers { filtersListNames.Add("name", containerName) filtersListIDs.Add("id", containerName) } containers, err := s.apiClient().ContainerList(ctx, container.ListOptions{ Filters: filtersListNames, All: true, }) if err != nil { return nil, err } containersByIds, err := s.apiClient().ContainerList(ctx, container.ListOptions{ Filters: filtersListIDs, All: true, }) if err != nil { return nil, err } for _, ctr := range containersByIds { if !slices.ContainsFunc(containers, func(summary container.Summary) bool { return summary.ID == ctr.ID }) { containers = append(containers, ctr) } } if len(containers) == 0 { return nil, fmt.Errorf("no container(s) found with the following name(s): %s", strings.Join(options.Containers, ",")) } return s.createProjectFromContainers(containers, options.ProjectName) } func (s *composeService) createProjectFromContainers(containers []container.Summary, projectName string) (*types.Project, error) { project := &types.Project{} services := types.Services{} networks := types.Networks{} volumes := types.Volumes{} secrets := types.Secrets{} if projectName != "" { project.Name = projectName } for _, c := range containers { // if the container is from a previous Compose application, use the existing service name serviceLabel, ok := c.Labels[api.ServiceLabel] if !ok { serviceLabel = getCanonicalContainerName(c) } service, ok := services[serviceLabel] if !ok { service = types.ServiceConfig{ Name: serviceLabel, Image: c.Image, Labels: c.Labels, } } service.Scale = increment(service.Scale) inspect, err := s.apiClient().ContainerInspect(context.Background(), c.ID) if err != nil { services[serviceLabel] = service continue } s.extractComposeConfiguration(&service, inspect, volumes, secrets, networks) service.Labels = cleanDockerPreviousLabels(service.Labels) services[serviceLabel] = service } project.Services = services project.Networks = networks project.Volumes = volumes project.Secrets = secrets return project, nil } func (s *composeService) extractComposeConfiguration(service *types.ServiceConfig, inspect container.InspectResponse, volumes types.Volumes, secrets types.Secrets, networks types.Networks) { service.Environment = types.NewMappingWithEquals(inspect.Config.Env) if inspect.Config.Healthcheck != nil { healthConfig := inspect.Config.Healthcheck service.HealthCheck = s.toComposeHealthCheck(healthConfig) } if len(inspect.Mounts) > 0 { detectedVolumes, volumeConfigs, detectedSecrets, secretsConfigs := s.toComposeVolumes(inspect.Mounts) service.Volumes = append(service.Volumes, volumeConfigs...) service.Secrets = append(service.Secrets, secretsConfigs...) maps.Copy(volumes, detectedVolumes) maps.Copy(secrets, detectedSecrets) } if len(inspect.NetworkSettings.Networks) > 0 { detectedNetworks, networkConfigs := s.toComposeNetwork(inspect.NetworkSettings.Networks) service.Networks = networkConfigs maps.Copy(networks, detectedNetworks) } if len(inspect.HostConfig.PortBindings) > 0 { for key, portBindings := range inspect.HostConfig.PortBindings { for _, portBinding := range portBindings { service.Ports = append(service.Ports, types.ServicePortConfig{ Target: uint32(key.Int()), Published: portBinding.HostPort, Protocol: key.Proto(), HostIP: portBinding.HostIP, }) } } } } func (s *composeService) toComposeHealthCheck(healthConfig *container.HealthConfig) *types.HealthCheckConfig { var healthCheck types.HealthCheckConfig healthCheck.Test = healthConfig.Test if healthConfig.Timeout != 0 { timeout := types.Duration(healthConfig.Timeout) healthCheck.Timeout = &timeout } if healthConfig.Interval != 0 { interval := types.Duration(healthConfig.Interval) healthCheck.Interval = &interval } if healthConfig.StartPeriod != 0 { startPeriod := types.Duration(healthConfig.StartPeriod) healthCheck.StartPeriod = &startPeriod } if healthConfig.StartInterval != 0 { startInterval := types.Duration(healthConfig.StartInterval) healthCheck.StartInterval = &startInterval } if healthConfig.Retries != 0 { retries := uint64(healthConfig.Retries) healthCheck.Retries = &retries } return &healthCheck } func (s *composeService) toComposeVolumes(volumes []container.MountPoint) (map[string]types.VolumeConfig, []types.ServiceVolumeConfig, map[string]types.SecretConfig, []types.ServiceSecretConfig, ) { volumeConfigs := make(map[string]types.VolumeConfig) secretConfigs := make(map[string]types.SecretConfig) var serviceVolumeConfigs []types.ServiceVolumeConfig var serviceSecretConfigs []types.ServiceSecretConfig for _, volume := range volumes { serviceVC := types.ServiceVolumeConfig{ Type: string(volume.Type), Source: volume.Source, Target: volume.Destination, ReadOnly: !volume.RW, } switch volume.Type { case mount.TypeVolume: serviceVC.Source = volume.Name vol := types.VolumeConfig{} if volume.Driver != "local" { vol.Driver = volume.Driver vol.Name = volume.Name } volumeConfigs[volume.Name] = vol serviceVolumeConfigs = append(serviceVolumeConfigs, serviceVC) case mount.TypeBind: if strings.HasPrefix(volume.Destination, "/run/secrets") { destination := strings.Split(volume.Destination, "/") secret := types.SecretConfig{ Name: destination[len(destination)-1], File: strings.TrimPrefix(volume.Source, "/host_mnt"), } secretConfigs[secret.Name] = secret serviceSecretConfigs = append(serviceSecretConfigs, types.ServiceSecretConfig{ Source: secret.Name, Target: volume.Destination, }) } else { serviceVolumeConfigs = append(serviceVolumeConfigs, serviceVC) } } } return volumeConfigs, serviceVolumeConfigs, secretConfigs, serviceSecretConfigs } func (s *composeService) toComposeNetwork(networks map[string]*network.EndpointSettings) (map[string]types.NetworkConfig, map[string]*types.ServiceNetworkConfig) { networkConfigs := make(map[string]types.NetworkConfig) serviceNetworkConfigs := make(map[string]*types.ServiceNetworkConfig) for name, net := range networks { inspect, err := s.apiClient().NetworkInspect(context.Background(), name, network.InspectOptions{}) if err != nil { networkConfigs[name] = types.NetworkConfig{} } else { networkConfigs[name] = types.NetworkConfig{ Internal: inspect.Internal, } } serviceNetworkConfigs[name] = &types.ServiceNetworkConfig{ Aliases: net.Aliases, } } return networkConfigs, serviceNetworkConfigs } func cleanDockerPreviousLabels(labels types.Labels) types.Labels { cleanedLabels := types.Labels{} for key, value := range labels { if !strings.HasPrefix(key, "com.docker.compose.") && !strings.HasPrefix(key, "desktop.docker.io") { cleanedLabels[key] = value } } return cleanedLabels }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/viz_test.go
pkg/compose/viz_test.go
/* 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" "strconv" "testing" "github.com/compose-spec/compose-go/v2/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" compose "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/mocks" ) func TestViz(t *testing.T) { project := types.Project{ Name: "viz-test", WorkingDir: "/home", Services: types.Services{ "service1": { Name: "service1", Image: "image-for-service1", Ports: []types.ServicePortConfig{ { Published: "80", Target: 80, Protocol: "tcp", }, { Published: "53", Target: 533, Protocol: "udp", }, }, Networks: map[string]*types.ServiceNetworkConfig{ "internal": nil, }, }, "service2": { Name: "service2", Image: "image-for-service2", Ports: []types.ServicePortConfig{}, }, "service3": { Name: "service3", Image: "some-image", DependsOn: map[string]types.ServiceDependency{ "service2": {}, "service1": {}, }, }, "service4": { Name: "service4", Image: "another-image", DependsOn: map[string]types.ServiceDependency{ "service3": {}, }, Ports: []types.ServicePortConfig{ { Published: "8080", Target: 80, }, }, Networks: map[string]*types.ServiceNetworkConfig{ "external": nil, }, }, "With host IP": { Name: "With host IP", Image: "user/image-name", DependsOn: map[string]types.ServiceDependency{ "service1": {}, }, Ports: []types.ServicePortConfig{ { Published: "8888", Target: 8080, HostIP: "127.0.0.1", }, }, }, }, Networks: types.Networks{ "internal": types.NetworkConfig{}, "external": types.NetworkConfig{}, "not-used": types.NetworkConfig{}, }, Volumes: nil, Secrets: nil, Configs: nil, Extensions: nil, ComposeFiles: nil, Environment: nil, DisabledServices: nil, Profiles: nil, } mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() cli := mocks.NewMockCli(mockCtrl) tested, err := NewComposeService(cli) require.NoError(t, err) ctx := context.Background() t.Run("viz (no ports, networks or image)", func(t *testing.T) { graphStr, err := tested.Viz(ctx, &project, compose.VizOptions{ Indentation: " ", IncludePorts: false, IncludeImageName: false, IncludeNetworks: false, }) require.NoError(t, err, "viz command failed") // check indentation assert.Contains(t, graphStr, "\n ", graphStr) assert.NotContains(t, graphStr, "\n ", graphStr) // check digraph name assert.Contains(t, graphStr, "digraph \""+project.Name+"\"", graphStr) // check nodes for _, service := range project.Services { assert.Contains(t, graphStr, "\""+service.Name+"\" [style=\"filled\"", graphStr) } // check node attributes assert.NotContains(t, graphStr, "Networks", graphStr) assert.NotContains(t, graphStr, "Image", graphStr) assert.NotContains(t, graphStr, "Ports", graphStr) // check edges that SHOULD exist in the generated graph allowedEdges := make(map[string][]string) for name, service := range project.Services { allowed := make([]string, 0, len(service.DependsOn)) for depName := range service.DependsOn { allowed = append(allowed, depName) } allowedEdges[name] = allowed } for serviceName, dependencies := range allowedEdges { for _, dependencyName := range dependencies { assert.Contains(t, graphStr, "\""+serviceName+"\" -> \""+dependencyName+"\"", graphStr) } } // check edges that SHOULD NOT exist in the generated graph forbiddenEdges := make(map[string][]string) for name, service := range project.Services { forbiddenEdges[name] = make([]string, 0, len(project.ServiceNames())-len(service.DependsOn)) for _, serviceName := range project.ServiceNames() { _, edgeExists := service.DependsOn[serviceName] if !edgeExists { forbiddenEdges[name] = append(forbiddenEdges[name], serviceName) } } } for serviceName, forbiddenDeps := range forbiddenEdges { for _, forbiddenDep := range forbiddenDeps { assert.NotContains(t, graphStr, "\""+serviceName+"\" -> \""+forbiddenDep+"\"") } } }) t.Run("viz (with ports, networks and image)", func(t *testing.T) { graphStr, err := tested.Viz(ctx, &project, compose.VizOptions{ Indentation: "\t", IncludePorts: true, IncludeImageName: true, IncludeNetworks: true, }) require.NoError(t, err, "viz command failed") // check indentation assert.Contains(t, graphStr, "\n\t", graphStr) assert.NotContains(t, graphStr, "\n\t\t", graphStr) // check digraph name assert.Contains(t, graphStr, "digraph \""+project.Name+"\"", graphStr) // check nodes for _, service := range project.Services { assert.Contains(t, graphStr, "\""+service.Name+"\" [style=\"filled\"", graphStr) } // check node attributes assert.Contains(t, graphStr, "Networks", graphStr) assert.Contains(t, graphStr, ">internal<", graphStr) assert.Contains(t, graphStr, ">external<", graphStr) assert.Contains(t, graphStr, "Image", graphStr) for _, service := range project.Services { assert.Contains(t, graphStr, ">"+service.Image+"<", graphStr) } assert.Contains(t, graphStr, "Ports", graphStr) for _, service := range project.Services { for _, portConfig := range service.Ports { assert.NotContains(t, graphStr, ">"+portConfig.Published+":"+strconv.Itoa(int(portConfig.Target))+"<", graphStr) } } }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/dependencies_test.go
pkg/compose/dependencies_test.go
/* 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" "fmt" "sort" "sync" "testing" "github.com/compose-spec/compose-go/v2/types" testify "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "github.com/docker/compose/v5/pkg/utils" ) func createTestProject() *types.Project { return &types.Project{ Services: types.Services{ "test1": { Name: "test1", DependsOn: map[string]types.ServiceDependency{ "test2": {}, }, }, "test2": { Name: "test2", DependsOn: map[string]types.ServiceDependency{ "test3": {}, }, }, "test3": { Name: "test3", }, }, } } func TestTraversalWithMultipleParents(t *testing.T) { dependent := types.ServiceConfig{ Name: "dependent", DependsOn: make(types.DependsOnConfig), } project := types.Project{ Services: types.Services{"dependent": dependent}, } for i := 1; i <= 100; i++ { name := fmt.Sprintf("svc_%d", i) dependent.DependsOn[name] = types.ServiceDependency{} svc := types.ServiceConfig{Name: name} project.Services[name] = svc } ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) svc := make(chan string, 10) seen := make(map[string]int) done := make(chan struct{}) go func() { for service := range svc { seen[service]++ } done <- struct{}{} }() err := InDependencyOrder(ctx, &project, func(ctx context.Context, service string) error { svc <- service return nil }) require.NoError(t, err, "Error during iteration") close(svc) <-done testify.Len(t, seen, 101) for svc, count := range seen { assert.Equal(t, 1, count, "Service: %s", svc) } } func TestInDependencyUpCommandOrder(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) var order []string err := InDependencyOrder(ctx, createTestProject(), func(ctx context.Context, service string) error { order = append(order, service) return nil }) require.NoError(t, err, "Error during iteration") require.Equal(t, []string{"test3", "test2", "test1"}, order) } func TestInDependencyReverseDownCommandOrder(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) var order []string err := InReverseDependencyOrder(ctx, createTestProject(), func(ctx context.Context, service string) error { order = append(order, service) return nil }) require.NoError(t, err, "Error during iteration") require.Equal(t, []string{"test1", "test2", "test3"}, order) } func TestBuildGraph(t *testing.T) { testCases := []struct { desc string services types.Services expectedVertices map[string]*Vertex }{ { desc: "builds graph with single service", services: types.Services{ "test": { Name: "test", DependsOn: types.DependsOnConfig{}, }, }, expectedVertices: map[string]*Vertex{ "test": { Key: "test", Service: "test", Status: ServiceStopped, Children: map[string]*Vertex{}, Parents: map[string]*Vertex{}, }, }, }, { desc: "builds graph with two separate services", services: types.Services{ "test": { Name: "test", DependsOn: types.DependsOnConfig{}, }, "another": { Name: "another", DependsOn: types.DependsOnConfig{}, }, }, expectedVertices: map[string]*Vertex{ "test": { Key: "test", Service: "test", Status: ServiceStopped, Children: map[string]*Vertex{}, Parents: map[string]*Vertex{}, }, "another": { Key: "another", Service: "another", Status: ServiceStopped, Children: map[string]*Vertex{}, Parents: map[string]*Vertex{}, }, }, }, { desc: "builds graph with a service and a dependency", services: types.Services{ "test": { Name: "test", DependsOn: types.DependsOnConfig{ "another": types.ServiceDependency{}, }, }, "another": { Name: "another", DependsOn: types.DependsOnConfig{}, }, }, expectedVertices: map[string]*Vertex{ "test": { Key: "test", Service: "test", Status: ServiceStopped, Children: map[string]*Vertex{ "another": {}, }, Parents: map[string]*Vertex{}, }, "another": { Key: "another", Service: "another", Status: ServiceStopped, Children: map[string]*Vertex{}, Parents: map[string]*Vertex{ "test": {}, }, }, }, }, { desc: "builds graph with multiple dependency levels", services: types.Services{ "test": { Name: "test", DependsOn: types.DependsOnConfig{ "another": types.ServiceDependency{}, }, }, "another": { Name: "another", DependsOn: types.DependsOnConfig{ "another_dep": types.ServiceDependency{}, }, }, "another_dep": { Name: "another_dep", DependsOn: types.DependsOnConfig{}, }, }, expectedVertices: map[string]*Vertex{ "test": { Key: "test", Service: "test", Status: ServiceStopped, Children: map[string]*Vertex{ "another": {}, }, Parents: map[string]*Vertex{}, }, "another": { Key: "another", Service: "another", Status: ServiceStopped, Children: map[string]*Vertex{ "another_dep": {}, }, Parents: map[string]*Vertex{ "test": {}, }, }, "another_dep": { Key: "another_dep", Service: "another_dep", Status: ServiceStopped, Children: map[string]*Vertex{}, Parents: map[string]*Vertex{ "another": {}, }, }, }, }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { project := types.Project{ Services: tC.services, } graph, err := NewGraph(&project, ServiceStopped) assert.NilError(t, err, fmt.Sprintf("failed to build graph for: %s", tC.desc)) for k, vertex := range graph.Vertices { expected, ok := tC.expectedVertices[k] assert.Equal(t, true, ok) assert.Equal(t, true, isVertexEqual(*expected, *vertex)) } }) } } func TestBuildGraphDependsOn(t *testing.T) { testCases := []struct { desc string services types.Services expectedVertices map[string]*Vertex }{ { desc: "service depends on init container which is already removed", services: types.Services{ "test": { Name: "test", DependsOn: types.DependsOnConfig{ "test-removed-init-container": types.ServiceDependency{ Condition: "service_completed_successfully", Restart: false, Extensions: types.Extensions(nil), Required: false, }, }, }, }, expectedVertices: map[string]*Vertex{ "test": { Key: "test", Service: "test", Status: ServiceStopped, Children: map[string]*Vertex{}, Parents: map[string]*Vertex{}, }, }, }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { project := types.Project{ Services: tC.services, } graph, err := NewGraph(&project, ServiceStopped) assert.NilError(t, err, fmt.Sprintf("failed to build graph for: %s", tC.desc)) for k, vertex := range graph.Vertices { expected, ok := tC.expectedVertices[k] assert.Equal(t, true, ok) assert.Equal(t, true, isVertexEqual(*expected, *vertex)) } }) } } func isVertexEqual(a, b Vertex) bool { childrenEquality := true for c := range a.Children { if _, ok := b.Children[c]; !ok { childrenEquality = false } } parentEquality := true for p := range a.Parents { if _, ok := b.Parents[p]; !ok { parentEquality = false } } return a.Key == b.Key && a.Service == b.Service && childrenEquality && parentEquality } func TestWith_RootNodesAndUp(t *testing.T) { graph := &Graph{ lock: sync.RWMutex{}, Vertices: map[string]*Vertex{}, } /** graph topology: A B / \ / \ G C E \ / D | F */ graph.AddVertex("A", "A", 0) graph.AddVertex("B", "B", 0) graph.AddVertex("C", "C", 0) graph.AddVertex("D", "D", 0) graph.AddVertex("E", "E", 0) graph.AddVertex("F", "F", 0) graph.AddVertex("G", "G", 0) _ = graph.AddEdge("C", "A") _ = graph.AddEdge("C", "B") _ = graph.AddEdge("E", "B") _ = graph.AddEdge("D", "C") _ = graph.AddEdge("D", "E") _ = graph.AddEdge("F", "D") _ = graph.AddEdge("G", "A") tests := []struct { name string nodes []string want []string }{ { name: "whole graph", nodes: []string{"A", "B"}, want: []string{"A", "B", "C", "D", "E", "F", "G"}, }, { name: "only leaves", nodes: []string{"F", "G"}, want: []string{"F", "G"}, }, { name: "simple dependent", nodes: []string{"D"}, want: []string{"D", "F"}, }, { name: "diamond dependents", nodes: []string{"B"}, want: []string{"B", "C", "D", "E", "F"}, }, { name: "partial graph", nodes: []string{"A"}, want: []string{"A", "C", "D", "F", "G"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mx := sync.Mutex{} expected := utils.Set[string]{} expected.AddAll("C", "G", "D", "F") var visited []string gt := downDirectionTraversal(func(ctx context.Context, s string) error { mx.Lock() defer mx.Unlock() visited = append(visited, s) return nil }) WithRootNodesAndDown(tt.nodes)(gt) err := gt.visit(context.TODO(), graph) assert.NilError(t, err) sort.Strings(visited) assert.DeepEqual(t, tt.want, visited) }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/plugins_windows.go
pkg/compose/plugins_windows.go
//go:build windows /* 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 func executable(s string) string { return s + ".exe" }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/dependencies.go
pkg/compose/dependencies.go
/* 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" "fmt" "slices" "strings" "sync" "github.com/compose-spec/compose-go/v2/types" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) // ServiceStatus indicates the status of a service type ServiceStatus int // Services status flags const ( ServiceStopped ServiceStatus = iota ServiceStarted ) type graphTraversal struct { mu sync.Mutex seen map[string]struct{} ignored map[string]struct{} extremityNodesFn func(*Graph) []*Vertex // leaves or roots adjacentNodesFn func(*Vertex) []*Vertex // getParents or getChildren filterAdjacentByStatusFn func(*Graph, string, ServiceStatus) []*Vertex // filterChildren or filterParents targetServiceStatus ServiceStatus adjacentServiceStatusToSkip ServiceStatus visitorFn func(context.Context, string) error maxConcurrency int } func upDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal { return &graphTraversal{ extremityNodesFn: leaves, adjacentNodesFn: getParents, filterAdjacentByStatusFn: filterChildren, adjacentServiceStatusToSkip: ServiceStopped, targetServiceStatus: ServiceStarted, visitorFn: visitorFn, } } func downDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal { return &graphTraversal{ extremityNodesFn: roots, adjacentNodesFn: getChildren, filterAdjacentByStatusFn: filterParents, adjacentServiceStatusToSkip: ServiceStarted, targetServiceStatus: ServiceStopped, visitorFn: visitorFn, } } // InDependencyOrder applies the function to the services of the project taking in account the dependency order func InDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error, options ...func(*graphTraversal)) error { graph, err := NewGraph(project, ServiceStopped) if err != nil { return err } t := upDirectionTraversal(fn) for _, option := range options { option(t) } return t.visit(ctx, graph) } // InReverseDependencyOrder applies the function to the services of the project in reverse order of dependencies func InReverseDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error, options ...func(*graphTraversal)) error { graph, err := NewGraph(project, ServiceStarted) if err != nil { return err } t := downDirectionTraversal(fn) for _, option := range options { option(t) } return t.visit(ctx, graph) } func WithRootNodesAndDown(nodes []string) func(*graphTraversal) { return func(t *graphTraversal) { if len(nodes) == 0 { return } originalFn := t.extremityNodesFn t.extremityNodesFn = func(graph *Graph) []*Vertex { var want []string for _, node := range nodes { vertex := graph.Vertices[node] want = append(want, vertex.Service) for _, v := range getAncestors(vertex) { want = append(want, v.Service) } } t.ignored = map[string]struct{}{} for k := range graph.Vertices { if !slices.Contains(want, k) { t.ignored[k] = struct{}{} } } return originalFn(graph) } } } func (t *graphTraversal) visit(ctx context.Context, g *Graph) error { expect := len(g.Vertices) if expect == 0 { return nil } eg, ctx := errgroup.WithContext(ctx) if t.maxConcurrency > 0 { eg.SetLimit(t.maxConcurrency + 1) } nodeCh := make(chan *Vertex, expect) defer close(nodeCh) // nodeCh need to allow n=expect writers while reader goroutine could have returner after ctx.Done eg.Go(func() error { for { select { case <-ctx.Done(): return nil case node := <-nodeCh: expect-- if expect == 0 { return nil } t.run(ctx, g, eg, t.adjacentNodesFn(node), nodeCh) } } }) nodes := t.extremityNodesFn(g) t.run(ctx, g, eg, nodes, nodeCh) return eg.Wait() } // Note: this could be `graph.walk` or whatever func (t *graphTraversal) run(ctx context.Context, graph *Graph, eg *errgroup.Group, nodes []*Vertex, nodeCh chan *Vertex) { for _, node := range nodes { // Don't start this service yet if all of its children have // not been started yet. if len(t.filterAdjacentByStatusFn(graph, node.Key, t.adjacentServiceStatusToSkip)) != 0 { continue } if !t.consume(node.Key) { // another worker already visited this node continue } eg.Go(func() error { var err error if _, ignore := t.ignored[node.Service]; !ignore { err = t.visitorFn(ctx, node.Service) } if err == nil { graph.UpdateStatus(node.Key, t.targetServiceStatus) } nodeCh <- node return err }) } } func (t *graphTraversal) consume(nodeKey string) bool { t.mu.Lock() defer t.mu.Unlock() if t.seen == nil { t.seen = make(map[string]struct{}) } if _, ok := t.seen[nodeKey]; ok { return false } t.seen[nodeKey] = struct{}{} return true } // Graph represents project as service dependencies type Graph struct { Vertices map[string]*Vertex lock sync.RWMutex } // Vertex represents a service in the dependencies structure type Vertex struct { Key string Service string Status ServiceStatus Children map[string]*Vertex Parents map[string]*Vertex } func getParents(v *Vertex) []*Vertex { return v.GetParents() } // GetParents returns a slice with the parent vertices of the Vertex func (v *Vertex) GetParents() []*Vertex { var res []*Vertex for _, p := range v.Parents { res = append(res, p) } return res } func getChildren(v *Vertex) []*Vertex { return v.GetChildren() } // getAncestors return all descendents for a vertex, might contain duplicates func getAncestors(v *Vertex) []*Vertex { var descendents []*Vertex for _, parent := range v.GetParents() { descendents = append(descendents, parent) descendents = append(descendents, getAncestors(parent)...) } return descendents } // GetChildren returns a slice with the child vertices of the Vertex func (v *Vertex) GetChildren() []*Vertex { var res []*Vertex for _, p := range v.Children { res = append(res, p) } return res } // NewGraph returns the dependency graph of the services func NewGraph(project *types.Project, initialStatus ServiceStatus) (*Graph, error) { graph := &Graph{ lock: sync.RWMutex{}, Vertices: map[string]*Vertex{}, } for _, s := range project.Services { graph.AddVertex(s.Name, s.Name, initialStatus) } for index, s := range project.Services { for _, name := range s.GetDependencies() { err := graph.AddEdge(s.Name, name) if err != nil { if !s.DependsOn[name].Required { delete(s.DependsOn, name) project.Services[index] = s continue } if api.IsNotFoundError(err) { ds, err := project.GetDisabledService(name) if err == nil { return nil, fmt.Errorf("service %s is required by %s but is disabled. Can be enabled by profiles %s", name, s.Name, ds.Profiles) } } return nil, err } } } if b, err := graph.HasCycles(); b { return nil, err } return graph, nil } // NewVertex is the constructor function for the Vertex func NewVertex(key string, service string, initialStatus ServiceStatus) *Vertex { return &Vertex{ Key: key, Service: service, Status: initialStatus, Parents: map[string]*Vertex{}, Children: map[string]*Vertex{}, } } // AddVertex adds a vertex to the Graph func (g *Graph) AddVertex(key string, service string, initialStatus ServiceStatus) { g.lock.Lock() defer g.lock.Unlock() v := NewVertex(key, service, initialStatus) g.Vertices[key] = v } // AddEdge adds a relationship of dependency between vertices `source` and `destination` func (g *Graph) AddEdge(source string, destination string) error { g.lock.Lock() defer g.lock.Unlock() sourceVertex := g.Vertices[source] destinationVertex := g.Vertices[destination] if sourceVertex == nil { return fmt.Errorf("could not find %s: %w", source, api.ErrNotFound) } if destinationVertex == nil { return fmt.Errorf("could not find %s: %w", destination, api.ErrNotFound) } // If they are already connected if _, ok := sourceVertex.Children[destination]; ok { return nil } sourceVertex.Children[destination] = destinationVertex destinationVertex.Parents[source] = sourceVertex return nil } func leaves(g *Graph) []*Vertex { return g.Leaves() } // Leaves returns the slice of leaves of the graph func (g *Graph) Leaves() []*Vertex { g.lock.Lock() defer g.lock.Unlock() var res []*Vertex for _, v := range g.Vertices { if len(v.Children) == 0 { res = append(res, v) } } return res } func roots(g *Graph) []*Vertex { return g.Roots() } // Roots returns the slice of "Roots" of the graph func (g *Graph) Roots() []*Vertex { g.lock.Lock() defer g.lock.Unlock() var res []*Vertex for _, v := range g.Vertices { if len(v.Parents) == 0 { res = append(res, v) } } return res } // UpdateStatus updates the status of a certain vertex func (g *Graph) UpdateStatus(key string, status ServiceStatus) { g.lock.Lock() defer g.lock.Unlock() g.Vertices[key].Status = status } func filterChildren(g *Graph, k string, s ServiceStatus) []*Vertex { return g.FilterChildren(k, s) } // FilterChildren returns children of a certain vertex that are in a certain status func (g *Graph) FilterChildren(key string, status ServiceStatus) []*Vertex { g.lock.Lock() defer g.lock.Unlock() var res []*Vertex vertex := g.Vertices[key] for _, child := range vertex.Children { if child.Status == status { res = append(res, child) } } return res } func filterParents(g *Graph, k string, s ServiceStatus) []*Vertex { return g.FilterParents(k, s) } // FilterParents returns the parents of a certain vertex that are in a certain status func (g *Graph) FilterParents(key string, status ServiceStatus) []*Vertex { g.lock.Lock() defer g.lock.Unlock() var res []*Vertex vertex := g.Vertices[key] for _, parent := range vertex.Parents { if parent.Status == status { res = append(res, parent) } } return res } // HasCycles detects cycles in the graph func (g *Graph) HasCycles() (bool, error) { discovered := []string{} finished := []string{} for _, vertex := range g.Vertices { path := []string{ vertex.Key, } if !slices.Contains(discovered, vertex.Key) && !slices.Contains(finished, vertex.Key) { var err error discovered, finished, err = g.visit(vertex.Key, path, discovered, finished) if err != nil { return true, err } } } return false, nil } func (g *Graph) visit(key string, path []string, discovered []string, finished []string) ([]string, []string, error) { discovered = append(discovered, key) for _, v := range g.Vertices[key].Children { path := append(path, v.Key) if slices.Contains(discovered, v.Key) { return nil, nil, fmt.Errorf("cycle found: %s", strings.Join(path, " -> ")) } if !slices.Contains(finished, v.Key) { if _, _, err := g.visit(v.Key, path, discovered, finished); err != nil { return nil, nil, err } } } discovered = remove(discovered, key) finished = append(finished, key) return discovered, finished, nil } func remove(slice []string, item string) []string { var s []string for _, i := range slice { if i != item { s = append(s, i) } } return s }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/image_pruner.go
pkg/compose/image_pruner.go
/* Copyright 2022 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" "fmt" "sort" "sync" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" "github.com/distribution/reference" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/docker/docker/client" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) // ImagePruneMode controls how aggressively images associated with the project // are removed from the engine. type ImagePruneMode string const ( // ImagePruneNone indicates that no project images should be removed. ImagePruneNone ImagePruneMode = "" // ImagePruneLocal indicates that only images built locally by Compose // should be removed. ImagePruneLocal ImagePruneMode = "local" // ImagePruneAll indicates that all project-associated images, including // remote images should be removed. ImagePruneAll ImagePruneMode = "all" ) // ImagePruneOptions controls the behavior of image pruning. type ImagePruneOptions struct { Mode ImagePruneMode // RemoveOrphans will result in the removal of images that were built for // the project regardless of whether they are for a known service if true. RemoveOrphans bool } // ImagePruner handles image removal during Compose `down` operations. type ImagePruner struct { client client.ImageAPIClient project *types.Project } // NewImagePruner creates an ImagePruner object for a project. func NewImagePruner(imageClient client.ImageAPIClient, project *types.Project) *ImagePruner { return &ImagePruner{ client: imageClient, project: project, } } // ImagesToPrune returns the set of images that should be removed. func (p *ImagePruner) ImagesToPrune(ctx context.Context, opts ImagePruneOptions) ([]string, error) { if opts.Mode == ImagePruneNone { return nil, nil } else if opts.Mode != ImagePruneLocal && opts.Mode != ImagePruneAll { return nil, fmt.Errorf("unsupported image prune mode: %s", opts.Mode) } var images []string if opts.Mode == ImagePruneAll { namedImages, err := p.namedImages(ctx) if err != nil { return nil, err } images = append(images, namedImages...) } projectImages, err := p.labeledLocalImages(ctx) if err != nil { return nil, err } for _, img := range projectImages { if len(img.RepoTags) == 0 { // currently, we're only pruning the tagged references, but // if we start removing the dangling images and grouping by // service, we can remove this (and should rely on `Image::ID`) continue } var shouldPrune bool if opts.RemoveOrphans { // indiscriminately prune all project images even if they're not // referenced by the current Compose state (e.g. the service was // removed from YAML) shouldPrune = true } else { // only prune the image if it belongs to a known service for the project. if _, err := p.project.GetService(img.Labels[api.ServiceLabel]); err == nil { shouldPrune = true } } if shouldPrune { images = append(images, img.RepoTags[0]) } } fallbackImages, err := p.unlabeledLocalImages(ctx) if err != nil { return nil, err } images = append(images, fallbackImages...) images = normalizeAndDedupeImages(images) return images, nil } // namedImages are those that are explicitly named in the service config. // // These could be registry-only images (no local build), hybrid (support build // as a fallback if cannot pull), or local-only (image does not exist in a // registry). func (p *ImagePruner) namedImages(ctx context.Context) ([]string, error) { var images []string for _, service := range p.project.Services { if service.Image == "" { continue } images = append(images, service.Image) } return p.filterImagesByExistence(ctx, images) } // labeledLocalImages are images that were locally-built by a current version of // Compose (it did not always label built images). // // The image name could either have been defined by the user or implicitly // created from the project + service name. func (p *ImagePruner) labeledLocalImages(ctx context.Context) ([]image.Summary, error) { imageListOpts := image.ListOptions{ Filters: filters.NewArgs( projectFilter(p.project.Name), // TODO(milas): we should really clean up the dangling images as // well (historically we have NOT); need to refactor this to handle // it gracefully without producing confusing CLI output, i.e. we // do not want to print out a bunch of untagged/dangling image IDs, // they should be grouped into a logical operation for the relevant // service filters.Arg("dangling", "false"), ), } projectImages, err := p.client.ImageList(ctx, imageListOpts) if err != nil { return nil, err } return projectImages, nil } // unlabeledLocalImages are images that match the implicit naming convention // for locally-built images but did not get labeled, presumably because they // were produced by an older version of Compose. // // This is transitional to ensure `down` continues to work as expected on // projects built/launched by previous versions of Compose. It can safely // be removed after some time. func (p *ImagePruner) unlabeledLocalImages(ctx context.Context) ([]string, error) { var images []string for _, service := range p.project.Services { if service.Image != "" { continue } img := api.GetImageNameOrDefault(service, p.project.Name) images = append(images, img) } return p.filterImagesByExistence(ctx, images) } // filterImagesByExistence returns the subset of images that exist in the // engine store. // // NOTE: Any transient errors communicating with the API will result in an // image being returned as "existing", as this method is exclusively used to // find images to remove, so the worst case of being conservative here is an // attempt to remove an image that doesn't exist, which will cause a warning // but is otherwise harmless. func (p *ImagePruner) filterImagesByExistence(ctx context.Context, imageNames []string) ([]string, error) { var mu sync.Mutex var ret []string eg, ctx := errgroup.WithContext(ctx) for _, img := range imageNames { eg.Go(func() error { _, err := p.client.ImageInspect(ctx, img) if errdefs.IsNotFound(err) { // err on the side of caution: only skip if we successfully // queried the API and got back a definitive "not exists" return nil } mu.Lock() defer mu.Unlock() ret = append(ret, img) return nil }) } if err := eg.Wait(); err != nil { return nil, err } return ret, nil } // normalizeAndDedupeImages returns the unique set of images after normalization. func normalizeAndDedupeImages(images []string) []string { seen := make(map[string]struct{}, len(images)) for _, img := range images { // since some references come from user input (service.image) and some // come from the engine API, we standardize them, opting for the // familiar name format since they'll also be displayed in the CLI ref, err := reference.ParseNormalizedNamed(img) if err == nil { ref = reference.TagNameOnly(ref) img = reference.FamiliarString(ref) } seen[img] = struct{}{} } ret := make([]string, 0, len(seen)) for v := range seen { ret = append(ret, v) } // ensure a deterministic return result - the actual ordering is not useful sort.Strings(ret) return ret }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/monitor.go
pkg/compose/monitor.go
/* 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" "strconv" "github.com/containerd/errdefs" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" "github.com/sirupsen/logrus" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) type monitor struct { apiClient client.APIClient project string // services tells us which service to consider and those we can ignore, maybe ran by a concurrent compose command services map[string]bool listeners []api.ContainerEventListener } func newMonitor(apiClient client.APIClient, project string) *monitor { return &monitor{ apiClient: apiClient, project: project, services: map[string]bool{}, } } func (c *monitor) withServices(services []string) { for _, name := range services { c.services[name] = true } } // Start runs monitor to detect application events and return after termination // //nolint:gocyclo func (c *monitor) Start(ctx context.Context) error { // collect initial application container initialState, err := c.apiClient.ContainerList(ctx, container.ListOptions{ All: true, Filters: filters.NewArgs( projectFilter(c.project), oneOffFilter(false), hasConfigHashLabel(), ), }) if err != nil { return err } // containers is the set if container IDs the application is based on containers := utils.Set[string]{} for _, ctr := range initialState { if len(c.services) == 0 || c.services[ctr.Labels[api.ServiceLabel]] { containers.Add(ctr.ID) } } restarting := utils.Set[string]{} evtCh, errCh := c.apiClient.Events(ctx, events.ListOptions{ Filters: filters.NewArgs( filters.Arg("type", "container"), projectFilter(c.project)), }) for { if len(containers) == 0 { return nil } select { case <-ctx.Done(): return nil case err := <-errCh: return err case event := <-evtCh: if len(c.services) > 0 && !c.services[event.Actor.Attributes[api.ServiceLabel]] { continue } ctr, err := c.getContainerSummary(event) if err != nil { return err } switch event.Action { case events.ActionCreate: if len(c.services) == 0 || c.services[ctr.Labels[api.ServiceLabel]] { containers.Add(ctr.ID) } evtType := api.ContainerEventCreated if _, ok := ctr.Labels[api.ContainerReplaceLabel]; ok { evtType = api.ContainerEventRecreated } for _, listener := range c.listeners { listener(newContainerEvent(event.TimeNano, ctr, evtType)) } logrus.Debugf("container %s created", ctr.Name) case events.ActionStart: restarted := restarting.Has(ctr.ID) if restarted { logrus.Debugf("container %s restarted", ctr.Name) for _, listener := range c.listeners { listener(newContainerEvent(event.TimeNano, ctr, api.ContainerEventStarted, func(e *api.ContainerEvent) { e.Restarting = restarted })) } } else { logrus.Debugf("container %s started", ctr.Name) for _, listener := range c.listeners { listener(newContainerEvent(event.TimeNano, ctr, api.ContainerEventStarted)) } } if len(c.services) == 0 || c.services[ctr.Labels[api.ServiceLabel]] { containers.Add(ctr.ID) } case events.ActionRestart: for _, listener := range c.listeners { listener(newContainerEvent(event.TimeNano, ctr, api.ContainerEventRestarted)) } logrus.Debugf("container %s restarted", ctr.Name) case events.ActionDie: logrus.Debugf("container %s exited with code %d", ctr.Name, ctr.ExitCode) inspect, err := c.apiClient.ContainerInspect(ctx, event.Actor.ID) if errdefs.IsNotFound(err) { // Source is already removed } else if err != nil { return err } if inspect.State != nil && inspect.State.Restarting || inspect.State.Running { // State.Restarting is set by engine when container is configured to restart on exit // on ContainerRestart it doesn't (see https://github.com/moby/moby/issues/45538) // container state still is reported as "running" logrus.Debugf("container %s is restarting", ctr.Name) restarting.Add(ctr.ID) for _, listener := range c.listeners { listener(newContainerEvent(event.TimeNano, ctr, api.ContainerEventExited, func(e *api.ContainerEvent) { e.Restarting = true })) } } else { for _, listener := range c.listeners { listener(newContainerEvent(event.TimeNano, ctr, api.ContainerEventExited)) } containers.Remove(ctr.ID) } } } } } func newContainerEvent(timeNano int64, ctr *api.ContainerSummary, eventType int, opts ...func(e *api.ContainerEvent)) api.ContainerEvent { name := ctr.Name defaultName := getDefaultContainerName(ctr.Project, ctr.Labels[api.ServiceLabel], ctr.Labels[api.ContainerNumberLabel]) if name == defaultName { // remove project- prefix name = name[len(ctr.Project)+1:] } event := api.ContainerEvent{ Type: eventType, Container: ctr, Time: timeNano, Source: name, ID: ctr.ID, Service: ctr.Service, ExitCode: ctr.ExitCode, } for _, opt := range opts { opt(&event) } return event } func (c *monitor) getContainerSummary(event events.Message) (*api.ContainerSummary, error) { ctr := &api.ContainerSummary{ ID: event.Actor.ID, Name: event.Actor.Attributes["name"], Project: c.project, Service: event.Actor.Attributes[api.ServiceLabel], Labels: event.Actor.Attributes, // More than just labels, but that'c the closest the API gives us } if ec, ok := event.Actor.Attributes["exitCode"]; ok { exitCode, err := strconv.Atoi(ec) if err != nil { return nil, err } ctr.ExitCode = exitCode } return ctr, nil } func (c *monitor) withListener(listener api.ContainerEventListener) { c.listeners = append(c.listeners, listener) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/filters.go
pkg/compose/filters.go
/* 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 ( "fmt" "github.com/docker/docker/api/types/filters" "github.com/docker/compose/v5/pkg/api" ) func projectFilter(projectName string) filters.KeyValuePair { return filters.Arg("label", fmt.Sprintf("%s=%s", api.ProjectLabel, projectName)) } func serviceFilter(serviceName string) filters.KeyValuePair { return filters.Arg("label", fmt.Sprintf("%s=%s", api.ServiceLabel, serviceName)) } func networkFilter(name string) filters.KeyValuePair { return filters.Arg("label", fmt.Sprintf("%s=%s", api.NetworkLabel, name)) } func oneOffFilter(b bool) filters.KeyValuePair { v := "False" if b { v = "True" } return filters.Arg("label", fmt.Sprintf("%s=%s", api.OneoffLabel, v)) } func containerNumberFilter(index int) filters.KeyValuePair { return filters.Arg("label", fmt.Sprintf("%s=%d", api.ContainerNumberLabel, index)) } func hasProjectLabelFilter() filters.KeyValuePair { return filters.Arg("label", api.ProjectLabel) } func hasConfigHashLabel() filters.KeyValuePair { return filters.Arg("label", api.ConfigHashLabel) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/remove.go
pkg/compose/remove.go
/* 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" "fmt" "strings" "github.com/docker/docker/api/types/container" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Remove(ctx context.Context, projectName string, options api.RemoveOptions) error { projectName = strings.ToLower(projectName) if options.Stop { err := s.Stop(ctx, projectName, api.StopOptions{ Services: options.Services, Project: options.Project, }) if err != nil { return err } } containers, err := s.getContainers(ctx, projectName, oneOffExclude, true, options.Services...) if err != nil { if api.IsNotFoundError(err) { _, _ = fmt.Fprintln(s.stderr(), "No stopped containers") return nil } return err } if options.Project != nil { containers = containers.filter(isService(options.Project.ServiceNames()...)) } var stoppedContainers Containers for _, ctr := range containers { // We have to inspect containers, as State reported by getContainers suffers a race condition inspected, err := s.apiClient().ContainerInspect(ctx, ctr.ID) if api.IsNotFoundError(err) { // Already removed. Maybe configured with auto-remove continue } if err != nil { return err } if !inspected.State.Running || (options.Stop && s.dryRun) { stoppedContainers = append(stoppedContainers, ctr) } } var names []string stoppedContainers.forEach(func(c container.Summary) { names = append(names, getCanonicalContainerName(c)) }) if len(names) == 0 { return api.ErrNoResources } msg := fmt.Sprintf("Going to remove %s", strings.Join(names, ", ")) if options.Force { _, _ = fmt.Fprintln(s.stdout(), msg) } else { confirm, err := s.prompt(msg, false) if err != nil { return err } if !confirm { return nil } } return Run(ctx, func(ctx context.Context) error { return s.remove(ctx, stoppedContainers, options) }, "remove", s.events) } func (s *composeService) remove(ctx context.Context, containers Containers, options api.RemoveOptions) error { eg, ctx := errgroup.WithContext(ctx) for _, ctr := range containers { eg.Go(func() error { eventName := getContainerProgressName(ctr) s.events.On(removingEvent(eventName)) err := s.apiClient().ContainerRemove(ctx, ctr.ID, container.RemoveOptions{ RemoveVolumes: options.Volumes, Force: options.Force, }) if err == nil { s.events.On(removedEvent(eventName)) } return err }) } return eg.Wait() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/up.go
pkg/compose/up.go
/* 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" "sync" "sync/atomic" "syscall" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" "github.com/docker/cli/cli" "github.com/eiannone/keyboard" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/internal/tracing" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Up(ctx context.Context, project *types.Project, options api.UpOptions) error { //nolint:gocyclo err := Run(ctx, tracing.SpanWrapFunc("project/up", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error { err := s.create(ctx, project, options.Create) if err != nil { return err } if options.Start.Attach == nil { return s.start(ctx, project.Name, options.Start, nil) } return nil }), "up", s.events) if err != nil { return err } if options.Start.Attach == nil { return err } if s.dryRun { _, _ = fmt.Fprintln(s.stdout(), "end of 'compose up' output, interactive run is not supported in dry-run mode") return err } // if we get a second signal during shutdown, we kill the services // immediately, so the channel needs to have sufficient capacity or // we might miss a signal while setting up the second channel read // (this is also why signal.Notify is used vs signal.NotifyContext) signalChan := make(chan os.Signal, 2) signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) defer signal.Stop(signalChan) var isTerminated atomic.Bool var ( logConsumer = options.Start.Attach navigationMenu *formatter.LogKeyboard kEvents <-chan keyboard.KeyEvent ) if options.Start.NavigationMenu { kEvents, err = keyboard.GetKeys(100) if err != nil { logrus.Warnf("could not start menu, an error occurred while starting: %v", err) options.Start.NavigationMenu = false } else { defer keyboard.Close() //nolint:errcheck isDockerDesktopActive, err := s.isDesktopIntegrationActive(ctx) if err != nil { return err } tracing.KeyboardMetrics(ctx, options.Start.NavigationMenu, isDockerDesktopActive) navigationMenu = formatter.NewKeyboardManager(isDockerDesktopActive, signalChan) logConsumer = navigationMenu.Decorate(logConsumer) } } watcher, err := NewWatcher(project, options, s.watch, logConsumer) if err != nil && options.Start.Watch { return err } if navigationMenu != nil && watcher != nil { navigationMenu.EnableWatch(options.Start.Watch, watcher) } printer := newLogPrinter(logConsumer) // global context to handle canceling goroutines globalCtx, cancel := context.WithCancel(ctx) defer cancel() if navigationMenu != nil { navigationMenu.EnableDetach(cancel) } var ( eg errgroup.Group mu sync.Mutex errs []error ) appendErr := func(err error) { if err != nil { mu.Lock() errs = append(errs, err) mu.Unlock() } } eg.Go(func() error { first := true gracefulTeardown := func() { first = false s.events.On(newEvent(api.ResourceCompose, api.Working, api.StatusStopping, "Gracefully Stopping... press Ctrl+C again to force")) eg.Go(func() error { err = s.stop(context.WithoutCancel(globalCtx), project.Name, api.StopOptions{ Services: options.Create.Services, Project: project, }, printer.HandleEvent) appendErr(err) return nil }) isTerminated.Store(true) } for { select { case <-globalCtx.Done(): if watcher != nil { return watcher.Stop() } return nil case <-ctx.Done(): if first { gracefulTeardown() } case <-signalChan: if first { _ = keyboard.Close() gracefulTeardown() break } eg.Go(func() error { err := s.kill(context.WithoutCancel(globalCtx), project.Name, api.KillOptions{ Services: options.Create.Services, Project: project, All: true, }) // Ignore errors indicating that some of the containers were already stopped or removed. if errdefs.IsNotFound(err) || errdefs.IsConflict(err) || errors.Is(err, api.ErrNoResources) { return nil } appendErr(err) return nil }) return nil case event := <-kEvents: navigationMenu.HandleKeyEvents(globalCtx, event, project, options) } } }) if options.Start.Watch && watcher != nil { if err := watcher.Start(globalCtx); err != nil { // cancel the global context to terminate background goroutines cancel() _ = eg.Wait() return err } } monitor := newMonitor(s.apiClient(), project.Name) if len(options.Start.Services) > 0 { monitor.withServices(options.Start.Services) } else { // Start.AttachTo have been already curated with only the services to monitor monitor.withServices(options.Start.AttachTo) } monitor.withListener(printer.HandleEvent) var exitCode int if options.Start.OnExit != api.CascadeIgnore { once := true // detect first container to exit to trigger application shutdown monitor.withListener(func(event api.ContainerEvent) { if once && event.Type == api.ContainerEventExited { if options.Start.OnExit == api.CascadeFail && event.ExitCode == 0 { return } once = false exitCode = event.ExitCode s.events.On(newEvent(api.ResourceCompose, api.Working, api.StatusStopping, "Aborting on container exit...")) eg.Go(func() error { err = s.stop(context.WithoutCancel(globalCtx), project.Name, api.StopOptions{ Services: options.Create.Services, Project: project, }, printer.HandleEvent) appendErr(err) return nil }) } }) } if options.Start.ExitCodeFrom != "" { once := true // capture exit code from first container to exit with selected service monitor.withListener(func(event api.ContainerEvent) { if once && event.Type == api.ContainerEventExited && event.Service == options.Start.ExitCodeFrom { exitCode = event.ExitCode once = false } }) } containers, err := s.attach(globalCtx, project, printer.HandleEvent, options.Start.AttachTo) if err != nil { cancel() _ = eg.Wait() return err } attached := make([]string, len(containers)) for i, ctr := range containers { attached[i] = ctr.ID } monitor.withListener(func(event api.ContainerEvent) { if event.Type != api.ContainerEventStarted { return } if slices.Contains(attached, event.ID) && !event.Restarting { return } eg.Go(func() error { ctr, err := s.apiClient().ContainerInspect(globalCtx, event.ID) if err != nil { appendErr(err) return nil } err = s.doLogContainer(globalCtx, options.Start.Attach, event.Source, ctr, api.LogOptions{ Follow: true, Since: ctr.State.StartedAt, }) if errdefs.IsNotImplemented(err) { // container may be configured with logging_driver: none // as container already started, we might miss the very first logs. But still better than none err := s.doAttachContainer(globalCtx, event.Service, event.ID, event.Source, printer.HandleEvent) appendErr(err) return nil } appendErr(err) return nil }) }) eg.Go(func() error { err := monitor.Start(globalCtx) // cancel the global context to terminate signal-handler goroutines cancel() appendErr(err) return nil }) // We use the parent context without cancellation as we manage sigterm to stop the stack err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent) if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated cancel() _ = eg.Wait() return err } _ = eg.Wait() err = errors.Join(errs...) if exitCode != 0 { errMsg := "" if err != nil { errMsg = err.Error() } return cli.StatusError{StatusCode: exitCode, Status: errMsg} } return err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/envresolver_test.go
pkg/compose/envresolver_test.go
/* 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 ( "testing" "gotest.tools/v3/assert" ) func Test_EnvResolverWithCase(t *testing.T) { tests := []struct { name string environment map[string]string caseInsensitive bool search string expectedValue string expectedOk bool }{ { name: "case sensitive/case match", environment: map[string]string{ "Env1": "Value1", "Env2": "Value2", }, caseInsensitive: false, search: "Env1", expectedValue: "Value1", expectedOk: true, }, { name: "case sensitive/case unmatch", environment: map[string]string{ "Env1": "Value1", "Env2": "Value2", }, caseInsensitive: false, search: "ENV1", expectedValue: "", expectedOk: false, }, { name: "case sensitive/nil environment", environment: nil, caseInsensitive: false, search: "Env1", expectedValue: "", expectedOk: false, }, { name: "case insensitive/case match", environment: map[string]string{ "Env1": "Value1", "Env2": "Value2", }, caseInsensitive: true, search: "Env1", expectedValue: "Value1", expectedOk: true, }, { name: "case insensitive/case unmatch", environment: map[string]string{ "Env1": "Value1", "Env2": "Value2", }, caseInsensitive: true, search: "ENV1", expectedValue: "Value1", expectedOk: true, }, { name: "case insensitive/unmatch", environment: map[string]string{ "Env1": "Value1", "Env2": "Value2", }, caseInsensitive: true, search: "Env3", expectedValue: "", expectedOk: false, }, { name: "case insensitive/nil environment", environment: nil, caseInsensitive: true, search: "Env1", expectedValue: "", expectedOk: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { f := envResolverWithCase(test.environment, test.caseInsensitive) v, ok := f(test.search) assert.Equal(t, v, test.expectedValue) assert.Equal(t, ok, test.expectedOk) }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/attach_service.go
pkg/compose/attach_service.go
/* 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" "strings" "github.com/docker/cli/cli/command/container" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Attach(ctx context.Context, projectName string, options api.AttachOptions) error { projectName = strings.ToLower(projectName) target, err := s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, options.Service, options.Index) if err != nil { return err } detachKeys := options.DetachKeys if detachKeys == "" { detachKeys = s.configFile().DetachKeys } var attach container.AttachOptions attach.DetachKeys = detachKeys attach.NoStdin = options.NoStdin attach.Proxy = options.Proxy return container.RunAttach(ctx, s.dockerCli, target.ID, &attach) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/build_test.go
pkg/compose/build_test.go
/* 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 ( "slices" "testing" "github.com/compose-spec/compose-go/v2/types" "gotest.tools/v3/assert" ) func Test_addBuildDependencies(t *testing.T) { project := &types.Project{Services: types.Services{ "test": types.ServiceConfig{ Build: &types.BuildConfig{ AdditionalContexts: map[string]string{ "foo": "service:foo", "bar": "service:bar", }, }, }, "foo": types.ServiceConfig{ Build: &types.BuildConfig{ AdditionalContexts: map[string]string{ "zot": "service:zot", }, }, }, "bar": types.ServiceConfig{ Build: &types.BuildConfig{}, }, "zot": types.ServiceConfig{ Build: &types.BuildConfig{}, }, }} services := addBuildDependencies([]string{"test"}, project) expected := []string{"test", "foo", "bar", "zot"} slices.Sort(services) slices.Sort(expected) assert.DeepEqual(t, services, expected) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/pause.go
pkg/compose/pause.go
/* 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" "strings" "github.com/docker/docker/api/types/container" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Pause(ctx context.Context, projectName string, options api.PauseOptions) error { return Run(ctx, func(ctx context.Context) error { return s.pause(ctx, strings.ToLower(projectName), options) }, "pause", s.events) } func (s *composeService) pause(ctx context.Context, projectName string, options api.PauseOptions) error { containers, err := s.getContainers(ctx, projectName, oneOffExclude, false, options.Services...) if err != nil { return err } if options.Project != nil { containers = containers.filter(isService(options.Project.ServiceNames()...)) } eg, ctx := errgroup.WithContext(ctx) containers.forEach(func(container container.Summary) { eg.Go(func() error { err := s.apiClient().ContainerPause(ctx, container.ID) if err == nil { eventName := getContainerProgressName(container) s.events.On(newEvent(eventName, api.Done, "Paused")) } return err }) }) return eg.Wait() } func (s *composeService) UnPause(ctx context.Context, projectName string, options api.PauseOptions) error { return Run(ctx, func(ctx context.Context) error { return s.unPause(ctx, strings.ToLower(projectName), options) }, "unpause", s.events) } func (s *composeService) unPause(ctx context.Context, projectName string, options api.PauseOptions) error { containers, err := s.getContainers(ctx, projectName, oneOffExclude, false, options.Services...) if err != nil { return err } if options.Project != nil { containers = containers.filter(isService(options.Project.ServiceNames()...)) } eg, ctx := errgroup.WithContext(ctx) containers.forEach(func(ctr container.Summary) { eg.Go(func() error { err = s.apiClient().ContainerUnpause(ctx, ctr.ID) if err == nil { eventName := getContainerProgressName(ctr) s.events.On(newEvent(eventName, api.Done, "Unpaused")) } return err }) }) return eg.Wait() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/loader_test.go
pkg/compose/loader_test.go
/* 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" "os" "path/filepath" "testing" "github.com/compose-spec/compose-go/v2/cli" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/docker/compose/v5/pkg/api" ) func TestLoadProject_Basic(t *testing.T) { // Create a temporary compose file tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` name: test-project services: web: image: nginx:latest ports: - "8080:80" db: image: postgres:latest environment: POSTGRES_PASSWORD: secret ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) // Create compose service service, err := NewComposeService(nil) require.NoError(t, err) // Load the project ctx := context.Background() project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, }) // Assertions require.NoError(t, err) assert.NotNil(t, project) assert.Equal(t, "test-project", project.Name) assert.Len(t, project.Services, 2) assert.Contains(t, project.Services, "web") assert.Contains(t, project.Services, "db") // Check labels were applied webService := project.Services["web"] assert.Equal(t, "test-project", webService.CustomLabels[api.ProjectLabel]) assert.Equal(t, "web", webService.CustomLabels[api.ServiceLabel]) } func TestLoadProject_WithEnvironmentResolution(t *testing.T) { tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` services: app: image: myapp:latest environment: - TEST_VAR=${TEST_VAR} - LITERAL_VAR=literal_value ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) // Set environment variable require.NoError(t, os.Setenv("TEST_VAR", "resolved_value")) t.Cleanup(func() { require.NoError(t, os.Unsetenv("TEST_VAR")) }) service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // Test with environment resolution (default) t.Run("WithResolution", func(t *testing.T) { project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, }) require.NoError(t, err) appService := project.Services["app"] // Environment should be resolved assert.NotNil(t, appService.Environment["TEST_VAR"]) assert.Equal(t, "resolved_value", *appService.Environment["TEST_VAR"]) assert.NotNil(t, appService.Environment["LITERAL_VAR"]) assert.Equal(t, "literal_value", *appService.Environment["LITERAL_VAR"]) }) // Test without environment resolution t.Run("WithoutResolution", func(t *testing.T) { project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, ProjectOptionsFns: []cli.ProjectOptionsFn{cli.WithoutEnvironmentResolution}, }) require.NoError(t, err) appService := project.Services["app"] // Environment should NOT be resolved, keeping raw values // Note: This depends on compose-go behavior, which may still have some resolution assert.NotNil(t, appService.Environment) }) } func TestLoadProject_ServiceSelection(t *testing.T) { tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` services: web: image: nginx:latest db: image: postgres:latest cache: image: redis:latest ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // Load only specific services project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, Services: []string{"web", "db"}, }) require.NoError(t, err) assert.Len(t, project.Services, 2) assert.Contains(t, project.Services, "web") assert.Contains(t, project.Services, "db") assert.NotContains(t, project.Services, "cache") } func TestLoadProject_WithProfiles(t *testing.T) { tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` services: web: image: nginx:latest debug: image: busybox:latest profiles: ["debug"] ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // Without debug profile t.Run("WithoutProfile", func(t *testing.T) { project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, }) require.NoError(t, err) assert.Len(t, project.Services, 1) assert.Contains(t, project.Services, "web") }) // With debug profile t.Run("WithProfile", func(t *testing.T) { project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, Profiles: []string{"debug"}, }) require.NoError(t, err) assert.Len(t, project.Services, 2) assert.Contains(t, project.Services, "web") assert.Contains(t, project.Services, "debug") }) } func TestLoadProject_WithLoadListeners(t *testing.T) { tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` services: web: image: nginx:latest ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // Track events received var events []string listener := func(event string, metadata map[string]any) { events = append(events, event) } project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, LoadListeners: []api.LoadListener{listener}, }) require.NoError(t, err) assert.NotNil(t, project) // Listeners should have been called (exact events depend on compose-go implementation) // The slice itself is always initialized (non-nil), even if empty _ = events // events may or may not have entries depending on compose-go behavior } func TestLoadProject_ProjectNameInference(t *testing.T) { tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` services: web: image: nginx:latest ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // Without explicit project name t.Run("InferredName", func(t *testing.T) { project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, }) require.NoError(t, err) // Project name should be inferred from directory assert.NotEmpty(t, project.Name) }) // With explicit project name t.Run("ExplicitName", func(t *testing.T) { project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, ProjectName: "my-custom-project", }) require.NoError(t, err) assert.Equal(t, "my-custom-project", project.Name) }) } func TestLoadProject_Compatibility(t *testing.T) { tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` services: web: image: nginx:latest ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // With compatibility mode project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, Compatibility: true, }) require.NoError(t, err) assert.NotNil(t, project) // In compatibility mode, separator should be "_" assert.Equal(t, "_", api.Separator) // Reset separator api.Separator = "-" } func TestLoadProject_InvalidComposeFile(t *testing.T) { tmpDir := t.TempDir() composeFile := filepath.Join(tmpDir, "compose.yaml") composeContent := ` this is not valid yaml: [[[ ` err := os.WriteFile(composeFile, []byte(composeContent), 0o644) require.NoError(t, err) service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // Should return an error for invalid YAML project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{composeFile}, }) require.Error(t, err) assert.Nil(t, project) } func TestLoadProject_MissingComposeFile(t *testing.T) { service, err := NewComposeService(nil) require.NoError(t, err) ctx := context.Background() // Should return an error for missing file project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ ConfigPaths: []string{"/nonexistent/compose.yaml"}, }) require.Error(t, err) assert.Nil(t, project) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/suffix_unix.go
pkg/compose/suffix_unix.go
//go:build !windows /* 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 func executable(s string) string { return s }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/images_test.go
pkg/compose/images_test.go
/* Copyright 2024 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" "strings" "testing" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" compose "github.com/docker/compose/v5/pkg/api" ) func TestImages(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() api, cli := prepareMocks(mockCtrl) tested, err := NewComposeService(cli) assert.NilError(t, err) ctx := context.Background() args := filters.NewArgs(projectFilter(strings.ToLower(testProject))) listOpts := container.ListOptions{All: true, Filters: args} api.EXPECT().ServerVersion(gomock.Any()).Return(types.Version{APIVersion: "1.96"}, nil).AnyTimes() timeStr1 := "2025-06-06T06:06:06.000000000Z" created1, _ := time.Parse(time.RFC3339Nano, timeStr1) timeStr2 := "2025-03-03T03:03:03.000000000Z" created2, _ := time.Parse(time.RFC3339Nano, timeStr2) image1 := imageInspect("image1", "foo:1", 12345, timeStr1) image2 := imageInspect("image2", "bar:2", 67890, timeStr2) api.EXPECT().ImageInspect(anyCancellableContext(), "foo:1").Return(image1, nil).MaxTimes(2) api.EXPECT().ImageInspect(anyCancellableContext(), "bar:2").Return(image2, nil) c1 := containerDetail("service1", "123", "running", "foo:1") c2 := containerDetail("service1", "456", "running", "bar:2") c2.Ports = []container.Port{{PublicPort: 80, PrivatePort: 90, IP: "localhost"}} c3 := containerDetail("service2", "789", "exited", "foo:1") api.EXPECT().ContainerList(ctx, listOpts).Return([]container.Summary{c1, c2, c3}, nil) images, err := tested.Images(ctx, strings.ToLower(testProject), compose.ImagesOptions{}) expected := map[string]compose.ImageSummary{ "123": { ID: "image1", Repository: "foo", Tag: "1", Size: 12345, Created: &created1, }, "456": { ID: "image2", Repository: "bar", Tag: "2", Size: 67890, Created: &created2, }, "789": { ID: "image1", Repository: "foo", Tag: "1", Size: 12345, Created: &created1, }, } assert.NilError(t, err) assert.DeepEqual(t, images, expected) } func imageInspect(id string, imageReference string, size int64, created string) image.InspectResponse { return image.InspectResponse{ ID: id, RepoTags: []string{ "someRepo:someTag", imageReference, }, Size: size, Created: created, } } func containerDetail(service string, id string, status string, imageName string) container.Summary { return container.Summary{ ID: id, Names: []string{"/" + id}, Image: imageName, Labels: containerLabels(service, false), State: status, } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/shellout.go
pkg/compose/shellout.go
/* 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" "os" "os/exec" "path/filepath" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli-plugins/metadata" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/flags" "github.com/docker/docker/client" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/propagation" "github.com/docker/compose/v5/internal" ) // prepareShellOut prepare a shell-out command to be ran by Compose func (s *composeService) prepareShellOut(gctx context.Context, env types.Mapping, cmd *exec.Cmd) error { env = env.Clone() // remove DOCKER_CLI_PLUGIN... variable so a docker-cli plugin will detect it run standalone delete(env, metadata.ReexecEnvvar) // propagate opentelemetry context to child process, see https://github.com/open-telemetry/oteps/blob/main/text/0258-env-context-baggage-carriers.md carrier := propagation.MapCarrier{} otel.GetTextMapPropagator().Inject(gctx, &carrier) env.Merge(types.Mapping(carrier)) cmd.Env = env.Values() return nil } // propagateDockerEndpoint produces DOCKER_* env vars for a child CLI plugin to target the same docker endpoint // `cleanup` func MUST be called after child process completion to enforce removal of cert files func (s *composeService) propagateDockerEndpoint() ([]string, func(), error) { cleanup := func() {} env := types.Mapping{} env[command.EnvOverrideContext] = s.dockerCli.CurrentContext() env["USER_AGENT"] = "compose/" + internal.Version endpoint := s.dockerCli.DockerEndpoint() env[client.EnvOverrideHost] = endpoint.Host if endpoint.TLSData != nil { certs, err := os.MkdirTemp("", "compose") if err != nil { return nil, cleanup, err } cleanup = func() { _ = os.RemoveAll(certs) } env[client.EnvOverrideCertPath] = certs env["DOCKER_TLS"] = "1" if !endpoint.SkipTLSVerify { env[client.EnvTLSVerify] = "1" } err = os.WriteFile(filepath.Join(certs, flags.DefaultKeyFile), endpoint.TLSData.Key, 0o600) if err != nil { return nil, cleanup, err } err = os.WriteFile(filepath.Join(certs, flags.DefaultCertFile), endpoint.TLSData.Cert, 0o600) if err != nil { return nil, cleanup, err } err = os.WriteFile(filepath.Join(certs, flags.DefaultCaFile), endpoint.TLSData.CA, 0o600) if err != nil { return nil, cleanup, err } } return env.Values(), cleanup, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/push.go
pkg/compose/push.go
/* 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" "encoding/base64" "encoding/json" "errors" "fmt" "io" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/distribution/reference" "github.com/docker/docker/api/types/image" "github.com/docker/docker/pkg/jsonmessage" "golang.org/x/sync/errgroup" "github.com/docker/compose/v5/internal/registry" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Push(ctx context.Context, project *types.Project, options api.PushOptions) error { if options.Quiet { return s.push(ctx, project, options) } return Run(ctx, func(ctx context.Context) error { return s.push(ctx, project, options) }, "push", s.events) } func (s *composeService) push(ctx context.Context, project *types.Project, options api.PushOptions) error { eg, ctx := errgroup.WithContext(ctx) eg.SetLimit(s.maxConcurrency) for _, service := range project.Services { if service.Build == nil || service.Image == "" { if options.ImageMandatory && service.Image == "" && service.Provider == nil { return fmt.Errorf("%q attribute is mandatory to push an image for service %q", "service.image", service.Name) } s.events.On(api.Resource{ ID: service.Name, Status: api.Done, Text: "Skipped", }) continue } tags := []string{service.Image} if service.Build != nil { tags = append(tags, service.Build.Tags...) } for _, tag := range tags { eg.Go(func() error { s.events.On(newEvent(tag, api.Working, "Pushing")) err := s.pushServiceImage(ctx, tag, options.Quiet) if err != nil { if !options.IgnoreFailures { s.events.On(newEvent(tag, api.Error, err.Error())) return err } s.events.On(newEvent(tag, api.Warning, err.Error())) } else { s.events.On(newEvent(tag, api.Done, "Pushed")) } return nil }) } } return eg.Wait() } func (s *composeService) pushServiceImage(ctx context.Context, tag string, quietPush bool) error { ref, err := reference.ParseNormalizedNamed(tag) if err != nil { return err } authConfig, err := s.configFile().GetAuthConfig(registry.GetAuthConfigKey(reference.Domain(ref))) if err != nil { return err } buf, err := json.Marshal(authConfig) if err != nil { return err } stream, err := s.apiClient().ImagePush(ctx, tag, image.PushOptions{ RegistryAuth: base64.URLEncoding.EncodeToString(buf), }) if err != nil { return err } dec := json.NewDecoder(stream) for { var jm jsonmessage.JSONMessage if err := dec.Decode(&jm); err != nil { if errors.Is(err, io.EOF) { break } return err } if jm.Error != nil { return errors.New(jm.Error.Message) } if !quietPush { toPushProgressEvent(tag, jm, s.events) } } return nil } func toPushProgressEvent(prefix string, jm jsonmessage.JSONMessage, events api.EventProcessor) { if jm.ID == "" { // skipped return } var ( text string status = api.Working total int64 current int64 percent int ) if isDone(jm) { status = api.Done percent = 100 } if jm.Error != nil { status = api.Error text = jm.Error.Message } if jm.Progress != nil { text = jm.Progress.String() if jm.Progress.Total != 0 { current = jm.Progress.Current total = jm.Progress.Total if jm.Progress.Total > 0 { percent = int(jm.Progress.Current * 100 / jm.Progress.Total) if percent > 100 { percent = 100 } } } } events.On(api.Resource{ ParentID: prefix, ID: jm.ID, Text: text, Status: status, Current: current, Total: total, Percent: percent, }) } func isDone(msg jsonmessage.JSONMessage) bool { // TODO there should be a better way to detect push is done than such a status message check switch strings.ToLower(msg.Status) { case "pushed", "layer already exists": return true default: return false } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/transform/replace.go
pkg/compose/transform/replace.go
/* 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 transform import ( "fmt" "go.yaml.in/yaml/v4" ) // ReplaceExtendsFile changes value for service.extends.file in input yaml stream, preserving formatting func ReplaceExtendsFile(in []byte, service string, value string) ([]byte, error) { var doc yaml.Node err := yaml.Unmarshal(in, &doc) if err != nil { return nil, err } if doc.Kind != yaml.DocumentNode { return nil, fmt.Errorf("expected document kind %v, got %v", yaml.DocumentNode, doc.Kind) } root := doc.Content[0] if root.Kind != yaml.MappingNode { return nil, fmt.Errorf("expected document root to be a mapping, got %v", root.Kind) } services, err := getMapping(root, "services") if err != nil { return nil, err } target, err := getMapping(services, service) if err != nil { return nil, err } extends, err := getMapping(target, "extends") if err != nil { return nil, err } file, err := getMapping(extends, "file") if err != nil { return nil, err } // we've found target `file` yaml node. Let's replace value in stream at node position return replace(in, file.Line, file.Column, value), nil } // ReplaceEnvFile changes value for service.extends.env_file in input yaml stream, preserving formatting func ReplaceEnvFile(in []byte, service string, i int, value string) ([]byte, error) { var doc yaml.Node err := yaml.Unmarshal(in, &doc) if err != nil { return nil, err } if doc.Kind != yaml.DocumentNode { return nil, fmt.Errorf("expected document kind %v, got %v", yaml.DocumentNode, doc.Kind) } root := doc.Content[0] if root.Kind != yaml.MappingNode { return nil, fmt.Errorf("expected document root to be a mapping, got %v", root.Kind) } services, err := getMapping(root, "services") if err != nil { return nil, err } target, err := getMapping(services, service) if err != nil { return nil, err } envFile, err := getMapping(target, "env_file") if err != nil { return nil, err } // env_file can be either a string, sequence of strings, or sequence of mappings with path attribute if envFile.Kind == yaml.SequenceNode { envFile = envFile.Content[i] if envFile.Kind == yaml.MappingNode { envFile, err = getMapping(envFile, "path") if err != nil { return nil, err } } return replace(in, envFile.Line, envFile.Column, value), nil } else { return replace(in, envFile.Line, envFile.Column, value), nil } } func getMapping(root *yaml.Node, key string) (*yaml.Node, error) { var node *yaml.Node l := len(root.Content) for i := 0; i < l; i += 2 { k := root.Content[i] if k.Kind != yaml.ScalarNode || k.Tag != "!!str" { return nil, fmt.Errorf("expected mapping key to be a string, got %v %v", root.Kind, k.Tag) } if k.Value == key { node = root.Content[i+1] return node, nil } } return nil, fmt.Errorf("key %v not found", key) } // replace changes yaml node value in stream at position, preserving content func replace(in []byte, line int, column int, value string) []byte { var out []byte l := 1 pos := 0 for _, b := range in { if b == '\n' { l++ if l == line { break } } pos++ } pos += column out = append(out, in[0:pos]...) out = append(out, []byte(value)...) for ; pos < len(in); pos++ { if in[pos] == '\n' { break } } out = append(out, in[pos:]...) return out }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/transform/replace_test.go
pkg/compose/transform/replace_test.go
/* 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 transform import ( "reflect" "testing" "gotest.tools/v3/assert" ) func TestReplace(t *testing.T) { tests := []struct { name string in string want string }{ { name: "simple", in: `services: test: extends: file: foo.yaml service: foo `, want: `services: test: extends: file: REPLACED service: foo `, }, { name: "last line", in: `services: test: extends: service: foo file: foo.yaml `, want: `services: test: extends: service: foo file: REPLACED `, }, { name: "last line no CR", in: `services: test: extends: service: foo file: foo.yaml`, want: `services: test: extends: service: foo file: REPLACED`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := ReplaceExtendsFile([]byte(tt.in), "test", "REPLACED") assert.NilError(t, err) if !reflect.DeepEqual(got, []byte(tt.want)) { t.Errorf("ReplaceExtendsFile() got = %v, want %v", got, tt.want) } }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/dockerignore_test.go
pkg/watch/dockerignore_test.go
/* 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 watch import ( "testing" ) func TestNewDockerPatternMatcher(t *testing.T) { tests := []struct { name string repoRoot string patterns []string expectedErr bool expectedRoot string expectedPat []string }{ { name: "Basic patterns without wildcard", repoRoot: "/repo", patterns: []string{"dir1/", "file.txt"}, expectedErr: false, expectedRoot: "/repo", expectedPat: []string{"/repo/dir1", "/repo/file.txt"}, }, { name: "Patterns with exclusion", repoRoot: "/repo", patterns: []string{"dir1/", "!file.txt"}, expectedErr: false, expectedRoot: "/repo", expectedPat: []string{"/repo/dir1", "!/repo/file.txt"}, }, { name: "Wildcard with exclusion", repoRoot: "/repo", patterns: []string{"*", "!file.txt"}, expectedErr: false, expectedRoot: "/repo", expectedPat: []string{"!/repo/file.txt"}, }, { name: "No patterns", repoRoot: "/repo", patterns: []string{}, expectedErr: false, expectedRoot: "/repo", expectedPat: nil, }, { name: "Only exclusion pattern", repoRoot: "/repo", patterns: []string{"!file.txt"}, expectedErr: false, expectedRoot: "/repo", expectedPat: []string{"!/repo/file.txt"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Call the function with the test data matcher, err := NewDockerPatternMatcher(tt.repoRoot, tt.patterns) // Check if we expect an error if (err != nil) != tt.expectedErr { t.Fatalf("expected error: %v, got: %v", tt.expectedErr, err) } // If no error is expected, check the output if !tt.expectedErr { if matcher.repoRoot != tt.expectedRoot { t.Errorf("expected root: %v, got: %v", tt.expectedRoot, matcher.repoRoot) } // Compare patterns actualPatterns := matcher.matcher.Patterns() if len(actualPatterns) != len(tt.expectedPat) { t.Errorf("expected patterns length: %v, got: %v", len(tt.expectedPat), len(actualPatterns)) } for i, expectedPat := range tt.expectedPat { actualPatternStr := actualPatterns[i].String() if actualPatterns[i].Exclusion() { actualPatternStr = "!" + actualPatternStr } if actualPatternStr != expectedPat { t.Errorf("expected pattern: %v, got: %v", expectedPat, actualPatterns[i]) } } } }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/notify_test.go
pkg/watch/notify_test.go
/* 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 watch import ( "bytes" "context" "fmt" "os" "path/filepath" "runtime" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // Each implementation of the notify interface should have the same basic // behavior. func TestWindowsBufferSize(t *testing.T) { orig := os.Getenv(WindowsBufferSizeEnvVar) defer os.Setenv(WindowsBufferSizeEnvVar, orig) //nolint:errcheck err := os.Setenv(WindowsBufferSizeEnvVar, "") require.NoError(t, err) assert.Equal(t, defaultBufferSize, DesiredWindowsBufferSize()) err = os.Setenv(WindowsBufferSizeEnvVar, "a") require.NoError(t, err) assert.Equal(t, defaultBufferSize, DesiredWindowsBufferSize()) err = os.Setenv(WindowsBufferSizeEnvVar, "10") require.NoError(t, err) assert.Equal(t, 10, DesiredWindowsBufferSize()) } func TestNoEvents(t *testing.T) { f := newNotifyFixture(t) f.assertEvents() } func TestNoWatches(t *testing.T) { f := newNotifyFixture(t) f.paths = nil f.rebuildWatcher() f.assertEvents() } func TestEventOrdering(t *testing.T) { if runtime.GOOS == "windows" { // https://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw_19.html t.Skip("Windows doesn't make great guarantees about duplicate/out-of-order events") return } f := newNotifyFixture(t) count := 8 dirs := make([]string, count) for i := range dirs { dir := f.TempDir("watched") dirs[i] = dir f.watch(dir) } f.fsync() f.events = nil var expected []string for i, dir := range dirs { base := fmt.Sprintf("%d.txt", i) p := filepath.Join(dir, base) err := os.WriteFile(p, []byte(base), os.FileMode(0o777)) if err != nil { t.Fatal(err) } expected = append(expected, filepath.Join(dir, base)) } f.assertEvents(expected...) } // Simulate a git branch switch that creates a bunch // of directories, creates files in them, then deletes // them all quickly. Make sure there are no errors. func TestGitBranchSwitch(t *testing.T) { f := newNotifyFixture(t) count := 10 dirs := make([]string, count) for i := range dirs { dir := f.TempDir("watched") dirs[i] = dir f.watch(dir) } f.fsync() f.events = nil // consume all the events in the background ctx, cancel := context.WithCancel(context.Background()) done := f.consumeEventsInBackground(ctx) for i, dir := range dirs { for j := 0; j < count; j++ { base := fmt.Sprintf("x/y/dir-%d/x.txt", j) p := filepath.Join(dir, base) f.WriteFile(p, "contents") } if i != 0 { err := os.RemoveAll(dir) require.NoError(t, err) } } cancel() err := <-done if err != nil { t.Fatal(err) } f.fsync() f.events = nil // Make sure the watch on the first dir still works. dir := dirs[0] path := filepath.Join(dir, "change") f.WriteFile(path, "hello\n") f.fsync() f.assertEvents(path) // Make sure there are no errors in the out stream assert.Empty(t, f.out.String()) } func TestWatchesAreRecursive(t *testing.T) { f := newNotifyFixture(t) root := f.TempDir("root") // add a sub directory subPath := filepath.Join(root, "sub") f.MkdirAll(subPath) // watch parent f.watch(root) f.fsync() f.events = nil // change sub directory changeFilePath := filepath.Join(subPath, "change") f.WriteFile(changeFilePath, "change") f.assertEvents(changeFilePath) } func TestNewDirectoriesAreRecursivelyWatched(t *testing.T) { f := newNotifyFixture(t) root := f.TempDir("root") // watch parent f.watch(root) f.fsync() f.events = nil // add a sub directory subPath := filepath.Join(root, "sub") f.MkdirAll(subPath) // change something inside sub directory changeFilePath := filepath.Join(subPath, "change") file, err := os.OpenFile(changeFilePath, os.O_RDONLY|os.O_CREATE, 0o666) if err != nil { t.Fatal(err) } _ = file.Close() f.assertEvents(subPath, changeFilePath) } func TestWatchNonExistentPath(t *testing.T) { f := newNotifyFixture(t) root := f.TempDir("root") path := filepath.Join(root, "change") f.watch(path) f.fsync() d1 := "hello\ngo\n" f.WriteFile(path, d1) f.assertEvents(path) } func TestWatchNonExistentPathDoesNotFireSiblingEvent(t *testing.T) { f := newNotifyFixture(t) root := f.TempDir("root") watchedFile := filepath.Join(root, "a.txt") unwatchedSibling := filepath.Join(root, "b.txt") f.watch(watchedFile) f.fsync() d1 := "hello\ngo\n" f.WriteFile(unwatchedSibling, d1) f.assertEvents() } func TestRemove(t *testing.T) { f := newNotifyFixture(t) root := f.TempDir("root") path := filepath.Join(root, "change") d1 := "hello\ngo\n" f.WriteFile(path, d1) f.watch(path) f.fsync() f.events = nil err := os.Remove(path) if err != nil { t.Fatal(err) } f.assertEvents(path) } func TestRemoveAndAddBack(t *testing.T) { f := newNotifyFixture(t) path := filepath.Join(f.paths[0], "change") d1 := []byte("hello\ngo\n") err := os.WriteFile(path, d1, 0o644) if err != nil { t.Fatal(err) } f.watch(path) f.assertEvents(path) err = os.Remove(path) if err != nil { t.Fatal(err) } f.assertEvents(path) f.events = nil err = os.WriteFile(path, d1, 0o644) if err != nil { t.Fatal(err) } f.assertEvents(path) } func TestSingleFile(t *testing.T) { f := newNotifyFixture(t) root := f.TempDir("root") path := filepath.Join(root, "change") d1 := "hello\ngo\n" f.WriteFile(path, d1) f.watch(path) f.fsync() d2 := []byte("hello\nworld\n") err := os.WriteFile(path, d2, 0o644) if err != nil { t.Fatal(err) } f.assertEvents(path) } func TestWriteBrokenLink(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("no user-space symlinks on windows") } f := newNotifyFixture(t) link := filepath.Join(f.paths[0], "brokenLink") missingFile := filepath.Join(f.paths[0], "missingFile") err := os.Symlink(missingFile, link) if err != nil { t.Fatal(err) } f.assertEvents(link) } func TestWriteGoodLink(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("no user-space symlinks on windows") } f := newNotifyFixture(t) goodFile := filepath.Join(f.paths[0], "goodFile") err := os.WriteFile(goodFile, []byte("hello"), 0o644) if err != nil { t.Fatal(err) } link := filepath.Join(f.paths[0], "goodFileSymlink") err = os.Symlink(goodFile, link) if err != nil { t.Fatal(err) } f.assertEvents(goodFile, link) } func TestWatchBrokenLink(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("no user-space symlinks on windows") } f := newNotifyFixture(t) newRoot, err := NewDir(t.Name()) if err != nil { t.Fatal(err) } defer func() { err := newRoot.TearDown() if err != nil { fmt.Printf("error tearing down temp dir: %v\n", err) } }() link := filepath.Join(newRoot.Path(), "brokenLink") missingFile := filepath.Join(newRoot.Path(), "missingFile") err = os.Symlink(missingFile, link) if err != nil { t.Fatal(err) } f.watch(newRoot.Path()) err = os.Remove(link) require.NoError(t, err) f.assertEvents(link) } func TestMoveAndReplace(t *testing.T) { f := newNotifyFixture(t) root := f.TempDir("root") file := filepath.Join(root, "myfile") f.WriteFile(file, "hello") f.watch(file) tmpFile := filepath.Join(root, ".myfile.swp") f.WriteFile(tmpFile, "world") err := os.Rename(tmpFile, file) if err != nil { t.Fatal(err) } f.assertEvents(file) } func TestWatchBothDirAndFile(t *testing.T) { f := newNotifyFixture(t) dir := f.JoinPath("foo") fileA := f.JoinPath("foo", "a") fileB := f.JoinPath("foo", "b") f.WriteFile(fileA, "a") f.WriteFile(fileB, "b") f.watch(fileA) f.watch(dir) f.fsync() f.events = nil f.WriteFile(fileB, "b-new") f.assertEvents(fileB) } func TestWatchNonexistentFileInNonexistentDirectoryCreatedSimultaneously(t *testing.T) { f := newNotifyFixture(t) root := f.JoinPath("root") err := os.Mkdir(root, 0o777) if err != nil { t.Fatal(err) } file := f.JoinPath("root", "parent", "a") f.watch(file) f.fsync() f.events = nil f.WriteFile(file, "hello") f.assertEvents(file) } func TestWatchNonexistentDirectory(t *testing.T) { f := newNotifyFixture(t) root := f.JoinPath("root") err := os.Mkdir(root, 0o777) if err != nil { t.Fatal(err) } parent := f.JoinPath("parent") file := f.JoinPath("parent", "a") f.watch(parent) f.fsync() f.events = nil err = os.Mkdir(parent, 0o777) if err != nil { t.Fatal(err) } // for directories that were the root of an Add, we don't report creation, cf. watcher_darwin.go f.assertEvents() f.events = nil f.WriteFile(file, "hello") f.assertEvents(file) } func TestWatchNonexistentFileInNonexistentDirectory(t *testing.T) { f := newNotifyFixture(t) root := f.JoinPath("root") err := os.Mkdir(root, 0o777) if err != nil { t.Fatal(err) } parent := f.JoinPath("parent") file := f.JoinPath("parent", "a") f.watch(file) f.assertEvents() err = os.Mkdir(parent, 0o777) if err != nil { t.Fatal(err) } f.assertEvents() f.WriteFile(file, "hello") f.assertEvents(file) } func TestWatchCountInnerFile(t *testing.T) { f := newNotifyFixture(t) root := f.paths[0] a := f.JoinPath(root, "a") b := f.JoinPath(a, "b") file := f.JoinPath(b, "bigFile") f.WriteFile(file, "hello") f.assertEvents(a, b, file) expectedWatches := 3 if isRecursiveWatcher() { expectedWatches = 1 } assert.Equal(t, expectedWatches, int(numberOfWatches.Value())) } func isRecursiveWatcher() bool { return runtime.GOOS == "darwin" || runtime.GOOS == "windows" } type notifyFixture struct { ctx context.Context cancel func() out *bytes.Buffer *TempDirFixture notify Notify paths []string events []FileEvent } func newNotifyFixture(t *testing.T) *notifyFixture { out := bytes.NewBuffer(nil) ctx, cancel := context.WithCancel(context.Background()) nf := &notifyFixture{ ctx: ctx, cancel: cancel, TempDirFixture: NewTempDirFixture(t), paths: []string{}, out: out, } nf.watch(nf.TempDir("watched")) t.Cleanup(nf.tearDown) return nf } func (f *notifyFixture) watch(path string) { f.paths = append(f.paths, path) f.rebuildWatcher() } func (f *notifyFixture) rebuildWatcher() { // sync any outstanding events and close the old watcher if f.notify != nil { f.fsync() f.closeWatcher() } // create a new watcher notify, err := NewWatcher(f.paths) if err != nil { f.T().Fatal(err) } f.notify = notify err = f.notify.Start() if err != nil { f.T().Fatal(err) } } func (f *notifyFixture) assertEvents(expected ...string) { f.fsync() if runtime.GOOS == "windows" { // NOTE(nick): It's unclear to me why an extra fsync() helps // here, but it makes the I/O way more predictable. f.fsync() } if len(f.events) != len(expected) { f.T().Fatalf("Got %d events (expected %d): %v %v", len(f.events), len(expected), f.events, expected) } for i, actual := range f.events { e := FileEvent(expected[i]) if actual != e { f.T().Fatalf("Got event %v (expected %v)", actual, e) } } } func (f *notifyFixture) consumeEventsInBackground(ctx context.Context) chan error { done := make(chan error) go func() { for { select { case <-f.ctx.Done(): close(done) return case <-ctx.Done(): close(done) return case err := <-f.notify.Errors(): done <- err close(done) return case <-f.notify.Events(): } } }() return done } func (f *notifyFixture) fsync() { f.fsyncWithRetryCount(3) } func (f *notifyFixture) fsyncWithRetryCount(retryCount int) { if len(f.paths) == 0 { return } syncPathBase := fmt.Sprintf("sync-%d.txt", time.Now().UnixNano()) syncPath := filepath.Join(f.paths[0], syncPathBase) anySyncPath := filepath.Join(f.paths[0], "sync-") timeout := time.After(250 * time.Second) f.WriteFile(syncPath, time.Now().String()) F: for { select { case <-f.ctx.Done(): return case err := <-f.notify.Errors(): f.T().Fatal(err) case event := <-f.notify.Events(): if strings.Contains(string(event), syncPath) { break F } if strings.Contains(string(event), anySyncPath) { continue } // Don't bother tracking duplicate changes to the same path // for testing. if len(f.events) > 0 && f.events[len(f.events)-1] == event { continue } f.events = append(f.events, event) case <-timeout: if retryCount <= 0 { f.T().Fatalf("fsync: timeout") } else { f.fsyncWithRetryCount(retryCount - 1) } return } } } func (f *notifyFixture) closeWatcher() { notify := f.notify err := notify.Close() if err != nil { f.T().Fatal(err) } // drain channels from watcher go func() { for range notify.Events() { } }() go func() { for range notify.Errors() { } }() } func (f *notifyFixture) tearDown() { f.cancel() f.closeWatcher() numberOfWatches.Set(0) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/ephemeral_test.go
pkg/watch/ephemeral_test.go
/* Copyright 2023 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 watch_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/docker/compose/v5/pkg/watch" ) func TestEphemeralPathMatcher(t *testing.T) { ignored := []string{ ".file.txt.swp", "/path/file.txt~", "/home/moby/proj/.idea/modules.xml", ".#file.txt", "#file.txt#", "/dir/.file.txt.kate-swp", "/go/app/1234-go-tmp-umask", } matcher := watch.EphemeralPathMatcher() for _, p := range ignored { ok, err := matcher.Matches(p) require.NoErrorf(t, err, "Matching %s", p) assert.Truef(t, ok, "Path %s should have matched", p) } const includedPath = "normal.txt" ok, err := matcher.Matches(includedPath) require.NoErrorf(t, err, "Matching %s", includedPath) assert.Falsef(t, ok, "Path %s should NOT have matched", includedPath) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/watcher_darwin.go
pkg/watch/watcher_darwin.go
//go:build fsnotify /* 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 watch import ( "fmt" "os" "path/filepath" "time" "github.com/fsnotify/fsevents" pathutil "github.com/docker/compose/v5/internal/paths" ) // A file watcher optimized for Darwin. // Uses FSEvents to avoid the terrible perf characteristics of kqueue. Requires CGO type fseventNotify struct { stream *fsevents.EventStream events chan FileEvent errors chan error stop chan struct{} pathsWereWatching map[string]any } func (d *fseventNotify) loop() { for { select { case <-d.stop: return case events, ok := <-d.stream.Events: if !ok { return } for _, e := range events { e.Path = filepath.Join(string(os.PathSeparator), e.Path) _, isPathWereWatching := d.pathsWereWatching[e.Path] if e.Flags&fsevents.ItemIsDir == fsevents.ItemIsDir && e.Flags&fsevents.ItemCreated == fsevents.ItemCreated && isPathWereWatching { // This is the first create for the path that we're watching. We always get exactly one of these // even after we get the HistoryDone event. Skip it. continue } d.events <- NewFileEvent(e.Path) } } } } // Add a path to be watched. Should only be called during initialization. func (d *fseventNotify) initAdd(name string) { d.stream.Paths = append(d.stream.Paths, name) if d.pathsWereWatching == nil { d.pathsWereWatching = make(map[string]any) } d.pathsWereWatching[name] = struct{}{} } func (d *fseventNotify) Start() error { if len(d.stream.Paths) == 0 { return nil } numberOfWatches.Add(int64(len(d.stream.Paths))) err := d.stream.Start() if err != nil { return err } go d.loop() return nil } func (d *fseventNotify) Close() error { numberOfWatches.Add(int64(-len(d.stream.Paths))) d.stream.Stop() close(d.errors) close(d.stop) return nil } func (d *fseventNotify) Events() chan FileEvent { return d.events } func (d *fseventNotify) Errors() chan error { return d.errors } func newWatcher(paths []string) (Notify, error) { dw := &fseventNotify{ stream: &fsevents.EventStream{ Latency: 50 * time.Millisecond, Flags: fsevents.FileEvents | fsevents.IgnoreSelf, // NOTE(dmiller): this corresponds to the `sinceWhen` parameter in FSEventStreamCreate // https://developer.apple.com/documentation/coreservices/1443980-fseventstreamcreate EventID: fsevents.LatestEventID(), }, events: make(chan FileEvent), errors: make(chan error), stop: make(chan struct{}), } paths = pathutil.EncompassingPaths(paths) for _, path := range paths { path, err := filepath.Abs(path) if err != nil { return nil, fmt.Errorf("newWatcher: %w", err) } dw.initAdd(path) } return dw, nil } var _ Notify = &fseventNotify{}
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/temp_dir_fixture.go
pkg/watch/temp_dir_fixture.go
/* 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 watch import ( "os" "path/filepath" "regexp" "runtime" "strings" "testing" ) type TempDirFixture struct { t testing.TB dir *TempDir oldDir string } // everything not listed in this character class will get replaced by _, so that it's a safe filename var sanitizeForFilenameRe = regexp.MustCompile("[^a-zA-Z0-9.]") func SanitizeFileName(name string) string { return sanitizeForFilenameRe.ReplaceAllString(name, "_") } func NewTempDirFixture(t testing.TB) *TempDirFixture { dir, err := NewDir(SanitizeFileName(t.Name())) if err != nil { t.Fatalf("Error making temp dir: %v", err) } ret := &TempDirFixture{ t: t, dir: dir, } t.Cleanup(ret.tearDown) return ret } func (f *TempDirFixture) T() testing.TB { return f.t } func (f *TempDirFixture) Path() string { return f.dir.Path() } func (f *TempDirFixture) Chdir() { cwd, err := os.Getwd() if err != nil { f.t.Fatal(err) } f.oldDir = cwd err = os.Chdir(f.Path()) if err != nil { f.t.Fatal(err) } } func (f *TempDirFixture) JoinPath(path ...string) string { p := []string{} isAbs := len(path) > 0 && filepath.IsAbs(path[0]) if isAbs { if !strings.HasPrefix(path[0], f.Path()) { f.t.Fatalf("Path outside fixture tempdir are forbidden: %s", path[0]) } } else { p = append(p, f.Path()) } p = append(p, path...) return filepath.Join(p...) } func (f *TempDirFixture) JoinPaths(paths []string) []string { joined := make([]string, len(paths)) for i, p := range paths { joined[i] = f.JoinPath(p) } return joined } // Returns the full path to the file written. func (f *TempDirFixture) WriteFile(path string, contents string) string { fullPath := f.JoinPath(path) base := filepath.Dir(fullPath) err := os.MkdirAll(base, os.FileMode(0o777)) if err != nil { f.t.Fatal(err) } err = os.WriteFile(fullPath, []byte(contents), os.FileMode(0o777)) if err != nil { f.t.Fatal(err) } return fullPath } // Returns the full path to the file written. func (f *TempDirFixture) CopyFile(originalPath, newPath string) { contents, err := os.ReadFile(originalPath) if err != nil { f.t.Fatal(err) } f.WriteFile(newPath, string(contents)) } // Read the file. func (f *TempDirFixture) ReadFile(path string) string { fullPath := f.JoinPath(path) contents, err := os.ReadFile(fullPath) if err != nil { f.t.Fatal(err) } return string(contents) } func (f *TempDirFixture) WriteSymlink(linkContents, destPath string) { fullDestPath := f.JoinPath(destPath) err := os.MkdirAll(filepath.Dir(fullDestPath), os.FileMode(0o777)) if err != nil { f.t.Fatal(err) } err = os.Symlink(linkContents, fullDestPath) if err != nil { f.t.Fatal(err) } } func (f *TempDirFixture) MkdirAll(path string) { fullPath := f.JoinPath(path) err := os.MkdirAll(fullPath, os.FileMode(0o777)) if err != nil { f.t.Fatal(err) } } func (f *TempDirFixture) TouchFiles(paths []string) { for _, p := range paths { f.WriteFile(p, "") } } func (f *TempDirFixture) Rm(pathInRepo string) { fullPath := f.JoinPath(pathInRepo) err := os.RemoveAll(fullPath) if err != nil { f.t.Fatal(err) } } func (f *TempDirFixture) NewFile(prefix string) (*os.File, error) { return os.CreateTemp(f.dir.Path(), prefix) } func (f *TempDirFixture) TempDir(prefix string) string { name, err := os.MkdirTemp(f.dir.Path(), prefix) if err != nil { f.t.Fatal(err) } return name } func (f *TempDirFixture) tearDown() { if f.oldDir != "" { err := os.Chdir(f.oldDir) if err != nil { f.t.Fatal(err) } } err := f.dir.TearDown() if err != nil && runtime.GOOS == "windows" && (strings.Contains(err.Error(), "The process cannot access the file") || strings.Contains(err.Error(), "Access is denied")) { // NOTE(nick): I'm not convinced that this is a real problem. // I think it might just be clean up of file notification I/O. } else if err != nil { f.t.Fatal(err) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/debounce_test.go
pkg/watch/debounce_test.go
/* 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 watch import ( "context" "slices" "testing" "time" "github.com/jonboulle/clockwork" "gotest.tools/v3/assert" ) func Test_BatchDebounceEvents(t *testing.T) { ch := make(chan FileEvent) clock := clockwork.NewFakeClock() ctx, stop := context.WithCancel(context.Background()) t.Cleanup(stop) eventBatchCh := BatchDebounceEvents(ctx, clock, ch) for i := 0; i < 100; i++ { path := "/a" if i%2 == 0 { path = "/b" } ch <- FileEvent(path) } // we sent 100 events + the debouncer err := clock.BlockUntilContext(ctx, 101) assert.NilError(t, err) clock.Advance(QuietPeriod) select { case batch := <-eventBatchCh: slices.Sort(batch) assert.Equal(t, len(batch), 2) assert.Equal(t, batch[0], FileEvent("/a")) assert.Equal(t, batch[1], FileEvent("/b")) case <-time.After(50 * time.Millisecond): t.Fatal("timed out waiting for events") } err = clock.BlockUntilContext(ctx, 1) assert.NilError(t, err) clock.Advance(QuietPeriod) // there should only be a single batch select { case batch := <-eventBatchCh: t.Fatalf("unexpected events: %v", batch) case <-time.After(50 * time.Millisecond): // channel is empty } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/paths_test.go
pkg/watch/paths_test.go
/* 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 watch import ( "runtime" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGreatestExistingAncestor(t *testing.T) { f := NewTempDirFixture(t) p, err := greatestExistingAncestor(f.Path()) require.NoError(t, err) assert.Equal(t, f.Path(), p) p, err = greatestExistingAncestor(f.JoinPath("missing")) require.NoError(t, err) assert.Equal(t, f.Path(), p) missingTopLevel := "/missingDir/a/b/c" if runtime.GOOS == "windows" { missingTopLevel = "C:\\missingDir\\a\\b\\c" } _, err = greatestExistingAncestor(missingTopLevel) assert.Contains(t, err.Error(), "cannot watch root directory") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/watcher_naive.go
pkg/watch/watcher_naive.go
//go:build !fsnotify /* 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 watch import ( "fmt" "io/fs" "os" "path/filepath" "runtime" "strings" "github.com/sirupsen/logrus" "github.com/tilt-dev/fsnotify" pathutil "github.com/docker/compose/v5/internal/paths" ) // A naive file watcher that uses the plain fsnotify API. // Used on all non-Darwin systems (including Windows & Linux). // // All OS-specific codepaths are handled by fsnotify. type naiveNotify struct { // Paths that we're watching that should be passed up to the caller. // Note that we may have to watch ancestors of these paths // in order to fulfill the API promise. // // We often need to check if paths are a child of a path in // the notify list. It might be better to store this in a tree // structure, so we can filter the list quickly. notifyList map[string]bool isWatcherRecursive bool watcher *fsnotify.Watcher events chan fsnotify.Event wrappedEvents chan FileEvent errors chan error numWatches int64 } func (d *naiveNotify) Start() error { if len(d.notifyList) == 0 { return nil } pathsToWatch := []string{} for path := range d.notifyList { pathsToWatch = append(pathsToWatch, path) } pathsToWatch, err := greatestExistingAncestors(pathsToWatch) if err != nil { return err } if d.isWatcherRecursive { pathsToWatch = pathutil.EncompassingPaths(pathsToWatch) } for _, name := range pathsToWatch { fi, err := os.Stat(name) if err != nil && !os.IsNotExist(err) { return fmt.Errorf("notify.Add(%q): %w", name, err) } // if it's a file that doesn't exist, // we should have caught that above, let's just skip it. if os.IsNotExist(err) { continue } if fi.IsDir() { err = d.watchRecursively(name) if err != nil { return fmt.Errorf("notify.Add(%q): %w", name, err) } } else { err = d.add(filepath.Dir(name)) if err != nil { return fmt.Errorf("notify.Add(%q): %w", filepath.Dir(name), err) } } } go d.loop() return nil } func (d *naiveNotify) watchRecursively(dir string) error { if d.isWatcherRecursive { err := d.add(dir) if err == nil || os.IsNotExist(err) { return nil } return fmt.Errorf("watcher.Add(%q): %w", dir, err) } return filepath.WalkDir(dir, func(path string, info fs.DirEntry, err error) error { if err != nil { return err } if !info.IsDir() { return nil } if d.shouldSkipDir(path) { logrus.Debugf("Ignoring directory and its contents (recursively): %s", path) return filepath.SkipDir } err = d.add(path) if err != nil { if os.IsNotExist(err) { return nil } return fmt.Errorf("watcher.Add(%q): %w", path, err) } return nil }) } func (d *naiveNotify) Close() error { numberOfWatches.Add(-d.numWatches) d.numWatches = 0 return d.watcher.Close() } func (d *naiveNotify) Events() chan FileEvent { return d.wrappedEvents } func (d *naiveNotify) Errors() chan error { return d.errors } func (d *naiveNotify) loop() { //nolint:gocyclo defer close(d.wrappedEvents) for e := range d.events { // The Windows fsnotify event stream sometimes gets events with empty names // that are also sent to the error stream. Hmmmm... if e.Name == "" { continue } if e.Op&fsnotify.Create != fsnotify.Create { if d.shouldNotify(e.Name) { d.wrappedEvents <- FileEvent(e.Name) } continue } if d.isWatcherRecursive { if d.shouldNotify(e.Name) { d.wrappedEvents <- FileEvent(e.Name) } continue } // If the watcher is not recursive, we have to walk the tree // and add watches manually. We fire the event while we're walking the tree. // because it's a bit more elegant that way. // // TODO(dbentley): if there's a delete should we call d.watcher.Remove to prevent leaking? err := filepath.WalkDir(e.Name, func(path string, info fs.DirEntry, err error) error { if err != nil { return err } if d.shouldNotify(path) { d.wrappedEvents <- FileEvent(path) } // TODO(dmiller): symlinks 😭 shouldWatch := false if info.IsDir() { // watch directories unless we can skip them entirely if d.shouldSkipDir(path) { return filepath.SkipDir } shouldWatch = true } else { // watch files that are explicitly named, but don't watch others _, ok := d.notifyList[path] if ok { shouldWatch = true } } if shouldWatch { err := d.add(path) if err != nil && !os.IsNotExist(err) { logrus.Infof("Error watching path %s: %s", e.Name, err) } } return nil }) if err != nil && !os.IsNotExist(err) { logrus.Infof("Error walking directory %s: %s", e.Name, err) } } } func (d *naiveNotify) shouldNotify(path string) bool { if _, ok := d.notifyList[path]; ok { // We generally don't care when directories change at the root of an ADD stat, err := os.Lstat(path) isDir := err == nil && stat.IsDir() return !isDir } for root := range d.notifyList { if pathutil.IsChild(root, path) { return true } } return false } func (d *naiveNotify) shouldSkipDir(path string) bool { // If path is directly in the notifyList, we should always watch it. if d.notifyList[path] { return false } // Suppose we're watching // /src/.tiltignore // but the .tiltignore file doesn't exist. // // Our watcher will create an inotify watch on /src/. // // But then we want to make sure we don't recurse from /src/ down to /src/node_modules. // // To handle this case, we only want to traverse dirs that are: // - A child of a directory that's in our notify list, or // - A parent of a directory that's in our notify list // (i.e., to cover the "path doesn't exist" case). for root := range d.notifyList { if pathutil.IsChild(root, path) || pathutil.IsChild(path, root) { return false } } return true } func (d *naiveNotify) add(path string) error { err := d.watcher.Add(path) if err != nil { return err } d.numWatches++ numberOfWatches.Add(1) return nil } func newWatcher(paths []string) (Notify, error) { fsw, err := fsnotify.NewWatcher() if err != nil { if strings.Contains(err.Error(), "too many open files") && runtime.GOOS == "linux" { return nil, fmt.Errorf("hit OS limits creating a watcher.\n" + "Run 'sysctl fs.inotify.max_user_instances' to check your inotify limits.\n" + "To raise them, run 'sudo sysctl fs.inotify.max_user_instances=1024'") } return nil, fmt.Errorf("creating file watcher: %w", err) } MaybeIncreaseBufferSize(fsw) err = fsw.SetRecursive() isWatcherRecursive := err == nil wrappedEvents := make(chan FileEvent) notifyList := make(map[string]bool, len(paths)) if isWatcherRecursive { paths = pathutil.EncompassingPaths(paths) } for _, path := range paths { path, err := filepath.Abs(path) if err != nil { return nil, fmt.Errorf("newWatcher: %w", err) } notifyList[path] = true } wmw := &naiveNotify{ notifyList: notifyList, watcher: fsw, events: fsw.Events, wrappedEvents: wrappedEvents, errors: fsw.Errors, isWatcherRecursive: isWatcherRecursive, } return wmw, nil } var _ Notify = &naiveNotify{} func greatestExistingAncestors(paths []string) ([]string, error) { result := []string{} for _, p := range paths { newP, err := greatestExistingAncestor(p) if err != nil { return nil, fmt.Errorf("finding ancestor of %s: %w", p, err) } result = append(result, newP) } return result, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/watcher_nonwin.go
pkg/watch/watcher_nonwin.go
//go:build !windows /* 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 watch import "github.com/tilt-dev/fsnotify" func MaybeIncreaseBufferSize(w *fsnotify.Watcher) { // Not needed on non-windows }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/debounce.go
pkg/watch/debounce.go
/* 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 watch import ( "context" "time" "github.com/jonboulle/clockwork" "github.com/sirupsen/logrus" "github.com/docker/compose/v5/pkg/utils" ) const QuietPeriod = 500 * time.Millisecond // BatchDebounceEvents groups identical file events within a sliding time window and writes the results to the returned // channel. // // The returned channel is closed when the debouncer is stopped via context cancellation or by closing the input channel. func BatchDebounceEvents(ctx context.Context, clock clockwork.Clock, input <-chan FileEvent) <-chan []FileEvent { out := make(chan []FileEvent) go func() { defer close(out) seen := utils.Set[FileEvent]{} flushEvents := func() { if len(seen) == 0 { return } logrus.Debugf("flush: %d events %s", len(seen), seen) events := make([]FileEvent, 0, len(seen)) for e := range seen { events = append(events, e) } out <- events seen = utils.Set[FileEvent]{} } t := clock.NewTicker(QuietPeriod) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.Chan(): flushEvents() case e, ok := <-input: if !ok { // input channel was closed flushEvents() return } if _, ok := seen[e]; !ok { seen.Add(e) } t.Reset(QuietPeriod) } } }() return out }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/paths.go
pkg/watch/paths.go
/* 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 watch import ( "fmt" "os" "path/filepath" ) func greatestExistingAncestor(path string) (string, error) { if path == string(filepath.Separator) || path == fmt.Sprintf("%s%s", filepath.VolumeName(path), string(filepath.Separator)) { return "", fmt.Errorf("cannot watch root directory") } _, err := os.Stat(path) if err != nil && !os.IsNotExist(err) { return "", fmt.Errorf("os.Stat(%q): %w", path, err) } if os.IsNotExist(err) { return greatestExistingAncestor(filepath.Dir(path)) } return path, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/dockerignore.go
pkg/watch/dockerignore.go
/* 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 watch import ( "fmt" "io" "os" "path/filepath" "slices" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/moby/patternmatcher" "github.com/moby/patternmatcher/ignorefile" "github.com/docker/compose/v5/internal/paths" ) type dockerPathMatcher struct { repoRoot string matcher *patternmatcher.PatternMatcher } func (i dockerPathMatcher) Matches(f string) (bool, error) { if !filepath.IsAbs(f) { f = filepath.Join(i.repoRoot, f) } return i.matcher.MatchesOrParentMatches(f) } func (i dockerPathMatcher) MatchesEntireDir(f string) (bool, error) { matches, err := i.Matches(f) if !matches || err != nil { return matches, err } // We match the dir, but we might exclude files underneath it. if i.matcher.Exclusions() { for _, pattern := range i.matcher.Patterns() { if !pattern.Exclusion() { continue } if paths.IsChild(f, pattern.String()) { // Found an exclusion match -- we don't match this whole dir return false, nil } } return true, nil } return true, nil } func LoadDockerIgnore(build *types.BuildConfig) (PathMatcher, error) { if build == nil { return EmptyMatcher{}, nil } repoRoot := build.Context absRoot, err := filepath.Abs(repoRoot) if err != nil { return nil, err } // first try Dockerfile-specific ignore-file f, err := os.Open(filepath.Join(repoRoot, build.Dockerfile+".dockerignore")) if os.IsNotExist(err) { // defaults to a global .dockerignore f, err = os.Open(filepath.Join(repoRoot, ".dockerignore")) if os.IsNotExist(err) { return NewDockerPatternMatcher(repoRoot, nil) } } if err != nil { return nil, err } defer func() { _ = f.Close() }() patterns, err := readDockerignorePatterns(f) if err != nil { return nil, err } return NewDockerPatternMatcher(absRoot, patterns) } // Make all the patterns use absolute paths. func absPatterns(absRoot string, patterns []string) []string { absPatterns := make([]string, 0, len(patterns)) for _, p := range patterns { // The pattern parsing here is loosely adapted from fileutils' NewPatternMatcher p = strings.TrimSpace(p) if p == "" { continue } p = filepath.Clean(p) pPath := p isExclusion := false if p[0] == '!' { pPath = p[1:] isExclusion = true } if !filepath.IsAbs(pPath) { pPath = filepath.Join(absRoot, pPath) } absPattern := pPath if isExclusion { absPattern = fmt.Sprintf("!%s", pPath) } absPatterns = append(absPatterns, absPattern) } return absPatterns } func NewDockerPatternMatcher(repoRoot string, patterns []string) (*dockerPathMatcher, error) { absRoot, err := filepath.Abs(repoRoot) if err != nil { return nil, err } // Check if "*" is present in patterns hasAllPattern := slices.Contains(patterns, "*") if hasAllPattern { // Remove all non-exclusion patterns (those that don't start with '!') patterns = slices.DeleteFunc(patterns, func(p string) bool { return p != "" && p[0] != '!' // Only keep exclusion patterns }) } pm, err := patternmatcher.New(absPatterns(absRoot, patterns)) if err != nil { return nil, err } return &dockerPathMatcher{ repoRoot: absRoot, matcher: pm, }, nil } func readDockerignorePatterns(r io.Reader) ([]string, error) { patterns, err := ignorefile.ReadAll(r) if err != nil { return nil, fmt.Errorf("error reading .dockerignore: %w", err) } return patterns, nil } func DockerIgnoreTesterFromContents(repoRoot string, contents string) (*dockerPathMatcher, error) { patterns, err := ignorefile.ReadAll(strings.NewReader(contents)) if err != nil { return nil, fmt.Errorf("error reading .dockerignore: %w", err) } return NewDockerPatternMatcher(repoRoot, patterns) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/notify.go
pkg/watch/notify.go
/* 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 watch import ( "expvar" "fmt" "os" "path/filepath" "strconv" ) var numberOfWatches = expvar.NewInt("watch.naive.numberOfWatches") type FileEvent string func NewFileEvent(p string) FileEvent { if !filepath.IsAbs(p) { panic(fmt.Sprintf("NewFileEvent only accepts absolute paths. Actual: %s", p)) } return FileEvent(p) } type Notify interface { // Start watching the paths set at init time Start() error // Stop watching and close all channels Close() error // A channel to read off incoming file changes Events() chan FileEvent // A channel to read off show-stopping errors Errors() chan error } // When we specify directories to watch, we often want to // ignore some subset of the files under those directories. // // For example: // - Watch /src/repo, but ignore /src/repo/.git // - Watch /src/repo, but ignore everything in /src/repo/bazel-bin except /src/repo/bazel-bin/app-binary // // The PathMatcher interface helps us manage these ignores. type PathMatcher interface { Matches(file string) (bool, error) // If this matches the entire dir, we can often optimize filetree walks a bit. MatchesEntireDir(file string) (bool, error) } // AnyMatcher is a PathMatcher to match any path type AnyMatcher struct{} func (AnyMatcher) Matches(f string) (bool, error) { return true, nil } func (AnyMatcher) MatchesEntireDir(f string) (bool, error) { return true, nil } var _ PathMatcher = AnyMatcher{} // EmptyMatcher is a PathMatcher to match no path type EmptyMatcher struct{} func (EmptyMatcher) Matches(f string) (bool, error) { return false, nil } func (EmptyMatcher) MatchesEntireDir(f string) (bool, error) { return false, nil } var _ PathMatcher = EmptyMatcher{} func NewWatcher(paths []string) (Notify, error) { return newWatcher(paths) } const WindowsBufferSizeEnvVar = "COMPOSE_WATCH_WINDOWS_BUFFER_SIZE" const defaultBufferSize int = 65536 func DesiredWindowsBufferSize() int { envVar := os.Getenv(WindowsBufferSizeEnvVar) if envVar != "" { size, err := strconv.Atoi(envVar) if err == nil { return size } } return defaultBufferSize } type CompositePathMatcher struct { Matchers []PathMatcher } func NewCompositeMatcher(matchers ...PathMatcher) PathMatcher { if len(matchers) == 0 { return EmptyMatcher{} } return CompositePathMatcher{Matchers: matchers} } func (c CompositePathMatcher) Matches(f string) (bool, error) { for _, t := range c.Matchers { ret, err := t.Matches(f) if err != nil { return false, err } if ret { return true, nil } } return false, nil } func (c CompositePathMatcher) MatchesEntireDir(f string) (bool, error) { for _, t := range c.Matchers { matches, err := t.MatchesEntireDir(f) if matches || err != nil { return matches, err } } return false, nil } var _ PathMatcher = CompositePathMatcher{}
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/watcher_naive_test.go
pkg/watch/watcher_naive_test.go
/* 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 watch import ( "fmt" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "testing" "github.com/stretchr/testify/require" ) func TestDontWatchEachFile(t *testing.T) { if runtime.GOOS != "linux" { t.Skip("This test uses linux-specific inotify checks") } // fsnotify is not recursive, so we need to watch each directory // you can watch individual files with fsnotify, but that is more prone to exhaust resources // this test uses a Linux way to get the number of watches to make sure we're watching // per-directory, not per-file f := newNotifyFixture(t) watched := f.TempDir("watched") // there are a few different cases we want to test for because the code paths are slightly // different: // 1) initial: data there before we ever call watch // 2) inplace: data we create while the watch is happening // 3) staged: data we create in another directory and then atomically move into place // initial f.WriteFile(f.JoinPath(watched, "initial.txt"), "initial data") initialDir := f.JoinPath(watched, "initial_dir") if err := os.Mkdir(initialDir, 0o777); err != nil { t.Fatal(err) } for i := 0; i < 100; i++ { f.WriteFile(f.JoinPath(initialDir, fmt.Sprintf("%d", i)), "initial data") } f.watch(watched) f.fsync() if len(f.events) != 0 { t.Fatalf("expected 0 initial events; got %d events: %v", len(f.events), f.events) } f.events = nil // inplace inplace := f.JoinPath(watched, "inplace") if err := os.Mkdir(inplace, 0o777); err != nil { t.Fatal(err) } f.WriteFile(f.JoinPath(inplace, "inplace.txt"), "inplace data") inplaceDir := f.JoinPath(inplace, "inplace_dir") if err := os.Mkdir(inplaceDir, 0o777); err != nil { t.Fatal(err) } for i := 0; i < 100; i++ { f.WriteFile(f.JoinPath(inplaceDir, fmt.Sprintf("%d", i)), "inplace data") } f.fsync() if len(f.events) < 100 { t.Fatalf("expected >100 inplace events; got %d events: %v", len(f.events), f.events) } f.events = nil // staged staged := f.TempDir("staged") f.WriteFile(f.JoinPath(staged, "staged.txt"), "staged data") stagedDir := f.JoinPath(staged, "staged_dir") if err := os.Mkdir(stagedDir, 0o777); err != nil { t.Fatal(err) } for i := 0; i < 100; i++ { f.WriteFile(f.JoinPath(stagedDir, fmt.Sprintf("%d", i)), "staged data") } if err := os.Rename(staged, f.JoinPath(watched, "staged")); err != nil { t.Fatal(err) } f.fsync() if len(f.events) < 100 { t.Fatalf("expected >100 staged events; got %d events: %v", len(f.events), f.events) } f.events = nil n, err := inotifyNodes() require.NoError(t, err) if n > 10 { t.Fatalf("watching more than 10 files: %d", n) } } func inotifyNodes() (int, error) { pid := os.Getpid() output, err := exec.Command("/bin/sh", "-c", fmt.Sprintf( "find /proc/%d/fd -lname anon_inode:inotify -printf '%%hinfo/%%f\n' | xargs cat | grep -c '^inotify'", pid)).Output() if err != nil { return 0, fmt.Errorf("error running command to determine number of watched files: %w\n %s", err, output) } n, err := strconv.Atoi(strings.TrimSpace(string(output))) if err != nil { return 0, fmt.Errorf("couldn't parse number of watched files: %w", err) } return n, nil } func TestDontRecurseWhenWatchingParentsOfNonExistentFiles(t *testing.T) { if runtime.GOOS != "linux" { t.Skip("This test uses linux-specific inotify checks") } f := newNotifyFixture(t) watched := f.TempDir("watched") f.watch(filepath.Join(watched, ".tiltignore")) excludedDir := f.JoinPath(watched, "excluded") for i := 0; i < 10; i++ { f.WriteFile(f.JoinPath(excludedDir, fmt.Sprintf("%d", i), "data.txt"), "initial data") } f.fsync() n, err := inotifyNodes() require.NoError(t, err) if n > 5 { t.Fatalf("watching more than 5 files: %d", n) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/temp.go
pkg/watch/temp.go
/* 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 watch import ( "os" "path/filepath" ) // TempDir holds a temp directory and allows easy access to new temp directories. type TempDir struct { dir string } // NewDir creates a new TempDir in the default location (typically $TMPDIR) func NewDir(prefix string) (*TempDir, error) { return NewDirAtRoot("", prefix) } // NewDirAtRoot creates a new TempDir at the given root. func NewDirAtRoot(root, prefix string) (*TempDir, error) { tmpDir, err := os.MkdirTemp(root, prefix) if err != nil { return nil, err } realTmpDir, err := filepath.EvalSymlinks(tmpDir) if err != nil { return nil, err } return &TempDir{dir: realTmpDir}, nil } // NewDirAtSlashTmp creates a new TempDir at /tmp func NewDirAtSlashTmp(prefix string) (*TempDir, error) { fullyResolvedPath, err := filepath.EvalSymlinks("/tmp") if err != nil { return nil, err } return NewDirAtRoot(fullyResolvedPath, prefix) } // d.NewDir creates a new TempDir under d func (d *TempDir) NewDir(prefix string) (*TempDir, error) { d2, err := os.MkdirTemp(d.dir, prefix) if err != nil { return nil, err } return &TempDir{d2}, nil } func (d *TempDir) NewDeterministicDir(name string) (*TempDir, error) { d2 := filepath.Join(d.dir, name) err := os.Mkdir(d2, 0o700) if os.IsExist(err) { return nil, err } else if err != nil { return nil, err } return &TempDir{d2}, nil } func (d *TempDir) TearDown() error { return os.RemoveAll(d.dir) } func (d *TempDir) Path() string { return d.dir } // Possible extensions: // temp file // named directories or files (e.g., we know we want one git repo for our object, but it should be temporary)
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/watcher_windows.go
pkg/watch/watcher_windows.go
//go:build windows /* 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 watch import ( "github.com/tilt-dev/fsnotify" ) // TODO(nick): I think the ideal API would be to automatically increase the // size of the buffer when we exceed capacity. But this gets messy, // because each time we get a short read error, we need to invalidate // everything we know about the currently changed files. So for now, // we just provide a way for people to increase the buffer ourselves. // // It might also pay to be clever about sizing the buffer // relative the number of files in the directory we're watching. func MaybeIncreaseBufferSize(w *fsnotify.Watcher) { w.SetBufferSize(DesiredWindowsBufferSize()) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/watch/ephemeral.go
pkg/watch/ephemeral.go
/* 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 watch // EphemeralPathMatcher filters out spurious changes that we don't want to // rebuild on, like IDE temp/lock files. // // This isn't an ideal solution. In an ideal world, the user would put // everything to ignore in their tiltignore/dockerignore files. This is a // stop-gap so they don't have a terrible experience if those files aren't // there or aren't in the right places. // // NOTE: The underlying `patternmatcher` is NOT always Goroutine-safe, so // this is not a singleton; we create an instance for each watcher currently. func EphemeralPathMatcher() PathMatcher { golandPatterns := []string{"**/*___jb_old___", "**/*___jb_tmp___", "**/.idea/**"} emacsPatterns := []string{"**/.#*", "**/#*#"} // if .swp is taken (presumably because multiple vims are running in that dir), // vim will go with .swo, .swn, etc, and then even .svz, .svy! // https://github.com/vim/vim/blob/ea781459b9617aa47335061fcc78403495260315/src/memline.c#L5076 // ignoring .sw? seems dangerous, since things like .swf or .swi exist, but ignoring the first few // seems safe and should catch most cases vimPatterns := []string{"**/4913", "**/*~", "**/.*.swp", "**/.*.swx", "**/.*.swo", "**/.*.swn"} // kate (the default text editor for KDE) uses a file similar to Vim's .swp // files, but it doesn't have the "incrementing" character problem mentioned // above katePatterns := []string{"**/.*.kate-swp"} // go stdlib creates tmpfiles to determine umask for setting permissions // during file creation; they are then immediately deleted // https://github.com/golang/go/blob/0b5218cf4e3e5c17344ea113af346e8e0836f6c4/src/cmd/go/internal/work/exec.go#L1764 goPatterns := []string{"**/*-go-tmp-umask"} var allPatterns []string allPatterns = append(allPatterns, golandPatterns...) allPatterns = append(allPatterns, emacsPatterns...) allPatterns = append(allPatterns, vimPatterns...) allPatterns = append(allPatterns, katePatterns...) allPatterns = append(allPatterns, goPatterns...) matcher, err := NewDockerPatternMatcher("/", allPatterns) if err != nil { panic(err) } return matcher }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/main.go
cmd/main.go
/* 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 main import ( "os" dockercli "github.com/docker/cli/cli" "github.com/docker/cli/cli-plugins/metadata" "github.com/docker/cli/cli-plugins/plugin" "github.com/docker/cli/cli/command" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/cmdtrace" "github.com/docker/compose/v5/cmd/compatibility" commands "github.com/docker/compose/v5/cmd/compose" "github.com/docker/compose/v5/cmd/prompt" "github.com/docker/compose/v5/internal" "github.com/docker/compose/v5/pkg/compose" ) func pluginMain() { plugin.Run( func(cli command.Cli) *cobra.Command { backendOptions := &commands.BackendOptions{ Options: []compose.Option{ compose.WithPrompt(prompt.NewPrompt(cli.In(), cli.Out()).Confirm), }, } cmd := commands.RootCommand(cli, backendOptions) originalPreRunE := cmd.PersistentPreRunE cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { // initialize the cli instance if err := plugin.PersistentPreRunE(cmd, args); err != nil { return err } if err := cmdtrace.Setup(cmd, cli, os.Args[1:]); err != nil { logrus.Debugf("failed to enable tracing: %v", err) } if originalPreRunE != nil { return originalPreRunE(cmd, args) } return nil } cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error { return dockercli.StatusError{ StatusCode: 1, Status: err.Error(), } }) return cmd }, metadata.Metadata{ SchemaVersion: "0.1.0", Vendor: "Docker Inc.", Version: internal.Version, }, command.WithUserAgent("compose/"+internal.Version), ) } func main() { if plugin.RunningStandalone() { os.Args = append([]string{"docker"}, compatibility.Convert(os.Args[1:])...) } pluginMain() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/cmdtrace/cmd_span_test.go
cmd/cmdtrace/cmd_span_test.go
/* 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 cmdtrace import ( "reflect" "testing" "github.com/spf13/cobra" flag "github.com/spf13/pflag" commands "github.com/docker/compose/v5/cmd/compose" ) func TestGetFlags(t *testing.T) { // Initialize flagSet with flags fs := flag.NewFlagSet("up", flag.ContinueOnError) var ( detach string timeout string ) fs.StringVar(&detach, "detach", "d", "") fs.StringVar(&timeout, "timeout", "t", "") _ = fs.Set("detach", "detach") _ = fs.Set("timeout", "timeout") tests := []struct { name string input *flag.FlagSet expected []string }{ { name: "NoFlags", input: flag.NewFlagSet("NoFlags", flag.ContinueOnError), expected: nil, }, { name: "Flags", input: fs, expected: []string{"detach", "timeout"}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { result := getFlags(test.input) if !reflect.DeepEqual(result, test.expected) { t.Errorf("Expected %v, but got %v", test.expected, result) } }) } } func TestCommandName(t *testing.T) { tests := []struct { name string setupCmd func() *cobra.Command want []string }{ { name: "docker compose alpha watch -> [watch, alpha]", setupCmd: func() *cobra.Command { dockerCmd := &cobra.Command{Use: "docker"} composeCmd := &cobra.Command{Use: commands.PluginName} alphaCmd := &cobra.Command{Use: "alpha"} watchCmd := &cobra.Command{Use: "watch"} dockerCmd.AddCommand(composeCmd) composeCmd.AddCommand(alphaCmd) alphaCmd.AddCommand(watchCmd) return watchCmd }, want: []string{"watch", "alpha"}, }, { name: "docker-compose up -> [up]", setupCmd: func() *cobra.Command { dockerComposeCmd := &cobra.Command{Use: commands.PluginName} upCmd := &cobra.Command{Use: "up"} dockerComposeCmd.AddCommand(upCmd) return upCmd }, want: []string{"up"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cmd := tt.setupCmd() got := commandName(cmd) if !reflect.DeepEqual(got, tt.want) { t.Errorf("commandName() = %v, want %v", got, tt.want) } }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/cmdtrace/cmd_span.go
cmd/cmdtrace/cmd_span.go
/* Copyright 2023 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 cmdtrace import ( "context" "errors" "fmt" "sort" "strings" "time" dockercli "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" flag "github.com/spf13/pflag" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" commands "github.com/docker/compose/v5/cmd/compose" "github.com/docker/compose/v5/internal/tracing" ) // Setup should be called as part of the command's PersistentPreRunE // as soon as possible after initializing the dockerCli. // // It initializes the tracer for the CLI using both auto-detection // from the Docker context metadata as well as standard OTEL_ env // vars, creates a root span for the command, and wraps the actual // command invocation to ensure the span is properly finalized and // exported before exit. func Setup(cmd *cobra.Command, dockerCli command.Cli, args []string) error { tracingShutdown, err := tracing.InitTracing(dockerCli) if err != nil { return fmt.Errorf("initializing tracing: %w", err) } ctx := cmd.Context() ctx, cmdSpan := otel.Tracer("").Start( ctx, "cli/"+strings.Join(commandName(cmd), "-"), ) cmdSpan.SetAttributes( attribute.StringSlice("cli.flags", getFlags(cmd.Flags())), attribute.Bool("cli.isatty", dockerCli.In().IsTerminal()), ) cmd.SetContext(ctx) wrapRunE(cmd, cmdSpan, tracingShutdown) return nil } // wrapRunE injects a wrapper function around the command's actual RunE (or Run) // method. This is necessary to capture the command result for reporting as well // as flushing any spans before exit. // // Unfortunately, PersistentPostRun(E) can't be used for this purpose because it // only runs if RunE does _not_ return an error, but this should run unconditionally. func wrapRunE(c *cobra.Command, cmdSpan trace.Span, tracingShutdown tracing.ShutdownFunc) { origRunE := c.RunE if origRunE == nil { origRun := c.Run //nolint:unparam // wrapper function for RunE, always returns nil by design origRunE = func(cmd *cobra.Command, args []string) error { origRun(cmd, args) return nil } c.Run = nil } c.RunE = func(cmd *cobra.Command, args []string) error { cmdErr := origRunE(cmd, args) if cmdSpan != nil { if cmdErr != nil && !errors.Is(cmdErr, context.Canceled) { // default exit code is 1 if a more descriptive error // wasn't returned exitCode := 1 var statusErr dockercli.StatusError if errors.As(cmdErr, &statusErr) { exitCode = statusErr.StatusCode } cmdSpan.SetStatus(codes.Error, "CLI command returned error") cmdSpan.RecordError(cmdErr, trace.WithAttributes( attribute.Int("exit_code", exitCode), )) } else { cmdSpan.SetStatus(codes.Ok, "") } cmdSpan.End() } if tracingShutdown != nil { // use background for root context because the cmd's context might have // been canceled already ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() // TODO(milas): add an env var to enable logging from the // OTel components for debugging purposes _ = tracingShutdown(ctx) } return cmdErr } } // commandName returns the path components for a given command, // in reverse alphabetical order for consistent usage metrics. // // The root Compose command and anything before (i.e. "docker") // are not included. // // For example: // - docker compose alpha watch -> [watch, alpha] // - docker-compose up -> [up] func commandName(cmd *cobra.Command) []string { var name []string for c := cmd; c != nil; c = c.Parent() { if c.Name() == commands.PluginName { break } name = append(name, c.Name()) } sort.Sort(sort.Reverse(sort.StringSlice(name))) return name } func getFlags(fs *flag.FlagSet) []string { var result []string fs.Visit(func(flag *flag.Flag) { result = append(result, flag.Name) }) return result }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/json.go
cmd/formatter/json.go
/* 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 formatter import ( "bytes" "encoding/json" ) const standardIndentation = " " // ToStandardJSON return a string with the JSON representation of the interface{} func ToStandardJSON(i any) (string, error) { return ToJSON(i, "", standardIndentation) } // ToJSON return a string with the JSON representation of the interface{} func ToJSON(i any, prefix string, indentation string) (string, error) { buffer := &bytes.Buffer{} encoder := json.NewEncoder(buffer) encoder.SetEscapeHTML(false) encoder.SetIndent(prefix, indentation) err := encoder.Encode(i) return buffer.String(), err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/formatter_test.go
cmd/formatter/formatter_test.go
/* 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 formatter import ( "bytes" "fmt" "io" "testing" "go.uber.org/goleak" "gotest.tools/v3/assert" ) type testStruct struct { Name string Status string } // Print prints formatted lists in different formats func TestPrint(t *testing.T) { testList := []testStruct{ { Name: "myName1", Status: "myStatus1", }, { Name: "myName2", Status: "myStatus2", }, } b := &bytes.Buffer{} assert.NilError(t, Print(testList, TABLE, b, func(w io.Writer) { for _, t := range testList { _, _ = fmt.Fprintf(w, "%s\t%s\n", t.Name, t.Status) } }, "NAME", "STATUS")) assert.Equal(t, b.String(), "NAME STATUS\nmyName1 myStatus1\nmyName2 myStatus2\n") b.Reset() assert.NilError(t, Print(testList, JSON, b, func(w io.Writer) { for _, t := range testList { _, _ = fmt.Fprintf(w, "%s\t%s\n", t.Name, t.Status) } }, "NAME", "STATUS")) assert.Equal(t, b.String(), `[{"Name":"myName1","Status":"myStatus1"},{"Name":"myName2","Status":"myStatus2"}] `) b.Reset() assert.NilError(t, Print(testList, TemplateLegacyJSON, b, func(w io.Writer) { for _, t := range testList { _, _ = fmt.Fprintf(w, "%s\t%s\n", t.Name, t.Status) } }, "NAME", "STATUS")) json := b.String() assert.Equal(t, json, `{"Name":"myName1","Status":"myStatus1"} {"Name":"myName2","Status":"myStatus2"} `) } func TestColorsGoroutinesLeak(t *testing.T) { goleak.VerifyNone(t) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false