|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/devcontainers/cli/internal/docker" |
| 9 | + "github.com/devcontainers/cli/internal/log" |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +type stopOpts struct { |
| 14 | + workspaceFolder string |
| 15 | + idLabels []string |
| 16 | + containerID string |
| 17 | + dockerPath string |
| 18 | + removeVolumes bool // down only |
| 19 | +} |
| 20 | + |
| 21 | +func newStopCmd() *cobra.Command { |
| 22 | + var opts stopOpts |
| 23 | + cmd := &cobra.Command{ |
| 24 | + Use: "stop [path]", |
| 25 | + Short: "Stop a workspace's dev container without removing it", |
| 26 | + Long: `Gracefully stop the dev container for a workspace so it stops consuming |
| 27 | +resources, leaving it and its data intact to be restarted with 'up'. For a |
| 28 | +Docker Compose config all of the project's services are stopped. |
| 29 | +
|
| 30 | +Useful on a remote host: pause the container without tearing anything down. |
| 31 | +
|
| 32 | +Go-only command; not part of the upstream @devcontainers/cli.`, |
| 33 | + Args: cobra.MaximumNArgs(1), |
| 34 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 35 | + if len(args) > 0 && opts.workspaceFolder == "" { |
| 36 | + opts.workspaceFolder = args[0] |
| 37 | + } |
| 38 | + return runStopOrDown(cmd.Context(), outputFor(cmd), opts, false) |
| 39 | + }, |
| 40 | + } |
| 41 | + addStopFlags(cmd, &opts) |
| 42 | + return cmd |
| 43 | +} |
| 44 | + |
| 45 | +func newDownCmd() *cobra.Command { |
| 46 | + var opts stopOpts |
| 47 | + cmd := &cobra.Command{ |
| 48 | + Use: "down [path]", |
| 49 | + Short: "Stop and remove a workspace's dev container", |
| 50 | + Long: `Stop and remove the dev container for a workspace (Compose: 'docker compose |
| 51 | +down'). Data in named volumes persists unless --remove-volumes is given; a later |
| 52 | +'up' then provisions a fresh container. |
| 53 | +
|
| 54 | +Go-only command; not part of the upstream @devcontainers/cli.`, |
| 55 | + Args: cobra.MaximumNArgs(1), |
| 56 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 57 | + if len(args) > 0 && opts.workspaceFolder == "" { |
| 58 | + opts.workspaceFolder = args[0] |
| 59 | + } |
| 60 | + return runStopOrDown(cmd.Context(), outputFor(cmd), opts, true) |
| 61 | + }, |
| 62 | + } |
| 63 | + addStopFlags(cmd, &opts) |
| 64 | + cmd.Flags().BoolVar(&opts.removeVolumes, "remove-volumes", false, "Also remove named volumes (Compose). Destructive: deletes persisted data.") |
| 65 | + return cmd |
| 66 | +} |
| 67 | + |
| 68 | +func addStopFlags(cmd *cobra.Command, opts *stopOpts) { |
| 69 | + f := cmd.Flags() |
| 70 | + f.StringVar(&opts.workspaceFolder, "workspace-folder", "", "Workspace folder path (defaults to [path] or the current directory).") |
| 71 | + f.StringArrayVar(&opts.idLabels, "id-label", nil, "id label(s) of the target container (name=value); repeatable.") |
| 72 | + f.StringVar(&opts.containerID, "container-id", "", "Target container id directly.") |
| 73 | + f.StringVar(&opts.dockerPath, "docker-path", "", "Docker CLI path.") |
| 74 | +} |
| 75 | + |
| 76 | +func runStopOrDown(ctx context.Context, out Output, opts stopOpts, remove bool) error { |
| 77 | + if opts.workspaceFolder == "" && len(opts.idLabels) == 0 && opts.containerID == "" { |
| 78 | + opts.workspaceFolder, _ = os.Getwd() |
| 79 | + } |
| 80 | + |
| 81 | + logger := log.New(log.Options{Writer: out.Stderr(), Format: "text"}) |
| 82 | + engine, err := docker.NewEngineClient(logger) |
| 83 | + if err != nil { |
| 84 | + return writeErrorResult(out, fmt.Sprintf("Docker engine: %v", err)) |
| 85 | + } |
| 86 | + defer engine.Close() |
| 87 | + |
| 88 | + id := resolveWorkspaceContainer(ctx, engine, opts) |
| 89 | + if id == "" { |
| 90 | + // Nothing to do — already gone. Not an error (idempotent). |
| 91 | + return writeSuccessJSON(out, map[string]interface{}{"outcome": "success", "result": "no-container-found"}) |
| 92 | + } |
| 93 | + |
| 94 | + // Compose services carry the project label; operate on the whole project so |
| 95 | + // sibling services (db, cache, …) are handled too, not just the dev container. |
| 96 | + project := "" |
| 97 | + if insp, ierr := engine.InspectContainer(ctx, id); ierr == nil && insp.Config != nil { |
| 98 | + project = insp.Config.Labels["com.docker.compose.project"] |
| 99 | + } |
| 100 | + |
| 101 | + action := "stopped" |
| 102 | + if remove { |
| 103 | + action = "removed" |
| 104 | + } |
| 105 | + |
| 106 | + if project != "" { |
| 107 | + compose, cerr := docker.NewComposeClient(opts.dockerPath, "", nil, logger) |
| 108 | + if cerr != nil { |
| 109 | + return writeErrorResult(out, cerr.Error()) |
| 110 | + } |
| 111 | + if remove { |
| 112 | + err = compose.Down(ctx, nil, project, opts.removeVolumes) |
| 113 | + } else { |
| 114 | + err = compose.Stop(ctx, nil, project) |
| 115 | + } |
| 116 | + } else { |
| 117 | + err = engine.StopContainer(ctx, id) |
| 118 | + if err == nil && remove { |
| 119 | + err = engine.RemoveContainer(ctx, id) |
| 120 | + } |
| 121 | + } |
| 122 | + if err != nil { |
| 123 | + return writeErrorResult(out, fmt.Sprintf("%s: %v", action, err)) |
| 124 | + } |
| 125 | + |
| 126 | + return writeSuccessJSON(out, map[string]interface{}{ |
| 127 | + "outcome": "success", |
| 128 | + "containerId": id, |
| 129 | + "result": action, |
| 130 | + }) |
| 131 | +} |
| 132 | + |
| 133 | +// resolveWorkspaceContainer finds the dev container for a workspace: a directly |
| 134 | +// given --container-id, else the first container matching --id-label or the |
| 135 | +// workspace's devcontainer.local_folder label. all=true so a stopped container |
| 136 | +// is still found (down after a prior stop). |
| 137 | +func resolveWorkspaceContainer(ctx context.Context, engine *docker.EngineClient, opts stopOpts) string { |
| 138 | + if opts.containerID != "" { |
| 139 | + return opts.containerID |
| 140 | + } |
| 141 | + labels := opts.idLabels |
| 142 | + if len(labels) == 0 && opts.workspaceFolder != "" { |
| 143 | + labels = []string{fmt.Sprintf("devcontainer.local_folder=%s", resolvePath(opts.workspaceFolder))} |
| 144 | + } |
| 145 | + if len(labels) == 0 { |
| 146 | + return "" |
| 147 | + } |
| 148 | + ids, err := engine.ListContainers(ctx, true, labels) |
| 149 | + if err != nil || len(ids) == 0 { |
| 150 | + return "" |
| 151 | + } |
| 152 | + return ids[0] |
| 153 | +} |
0 commit comments