|
| 1 | +package agent |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "os/exec" |
| 9 | + "sort" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/coder/coder/v2/codersdk" |
| 15 | + |
| 16 | + "golang.org/x/exp/maps" |
| 17 | + "golang.org/x/xerrors" |
| 18 | +) |
| 19 | + |
| 20 | +// dockerCLIContainerLister is a ContainerLister that lists containers using the docker CLI |
| 21 | +type dockerCLIContainerLister struct{} |
| 22 | + |
| 23 | +var _ ContainerLister = &dockerCLIContainerLister{} |
| 24 | + |
| 25 | +func (*dockerCLIContainerLister) List(ctx context.Context) ([]codersdk.WorkspaceAgentContainer, error) { |
| 26 | + var buf bytes.Buffer |
| 27 | + // List all container IDs, one per line, with no truncation |
| 28 | + cmd := exec.CommandContext(ctx, "docker", "ps", "--all", "--quiet", "--no-trunc") |
| 29 | + cmd.Stdout = &buf |
| 30 | + if err := cmd.Run(); err != nil { |
| 31 | + return nil, xerrors.Errorf("run docker ps: %w", err) |
| 32 | + } |
| 33 | + |
| 34 | + // the output is returned with a single item per line, so we have to decode it |
| 35 | + // line-by-line |
| 36 | + ids := make([]string, 0) |
| 37 | + for _, line := range strings.Split(buf.String(), "\n") { |
| 38 | + tmp := strings.TrimSpace(line) |
| 39 | + if tmp == "" { |
| 40 | + continue |
| 41 | + } |
| 42 | + ids = append(ids, tmp) |
| 43 | + } |
| 44 | + |
| 45 | + // now we can get the detailed information for each container |
| 46 | + // Run `docker inspect` on each container ID |
| 47 | + buf.Reset() |
| 48 | + execArgs := []string{"inspect"} |
| 49 | + execArgs = append(execArgs, ids...) |
| 50 | + cmd = exec.CommandContext(ctx, "docker", execArgs...) |
| 51 | + cmd.Stdout = &buf |
| 52 | + if err := cmd.Run(); err != nil { |
| 53 | + return nil, xerrors.Errorf("run docker inspect: %w", err) |
| 54 | + } |
| 55 | + |
| 56 | + // out := make([]codersdk.WorkspaceAgentContainer, 0) |
| 57 | + ins := make([]dockerInspect, 0) |
| 58 | + if err := json.NewDecoder(&buf).Decode(&ins); err != nil { |
| 59 | + return nil, xerrors.Errorf("decode docker inspect output: %w", err) |
| 60 | + } |
| 61 | + |
| 62 | + out := make([]codersdk.WorkspaceAgentContainer, 0) |
| 63 | + for _, in := range ins { |
| 64 | + out = append(out, convertDockerInspect(in)) |
| 65 | + } |
| 66 | + |
| 67 | + return out, nil |
| 68 | +} |
| 69 | + |
| 70 | +// To avoid a direct dependency on the Docker API, we use the docker CLI |
| 71 | +// to fetch information about containers. |
| 72 | +type dockerInspect struct { |
| 73 | + ID string `json:"Id"` |
| 74 | + Created time.Time `json:"Created"` |
| 75 | + Name string `json:"Name"` |
| 76 | + Config dockerInspectConfig `json:"Config"` |
| 77 | + State dockerInspectState `json:"State"` |
| 78 | +} |
| 79 | + |
| 80 | +type dockerInspectConfig struct { |
| 81 | + ExposedPorts map[string]struct{} `json:"ExposedPorts"` |
| 82 | + Image string `json:"Image"` |
| 83 | + Labels map[string]string `json:"Labels"` |
| 84 | + Volumes map[string]struct{} `json:"Volumes"` |
| 85 | +} |
| 86 | + |
| 87 | +type dockerInspectState struct { |
| 88 | + Running bool `json:"Running"` |
| 89 | + ExitCode int `json:"ExitCode"` |
| 90 | + Error string `json:"Error"` |
| 91 | +} |
| 92 | + |
| 93 | +func (dis dockerInspectState) String() string { |
| 94 | + if dis.Running { |
| 95 | + return "running" |
| 96 | + } |
| 97 | + var sb strings.Builder |
| 98 | + _, _ = sb.WriteString("exited") |
| 99 | + if dis.ExitCode != 0 { |
| 100 | + _, _ = sb.WriteString(fmt.Sprintf(" with code %d", dis.ExitCode)) |
| 101 | + } else { |
| 102 | + _, _ = sb.WriteString(" successfully") |
| 103 | + } |
| 104 | + if dis.Error != "" { |
| 105 | + _, _ = sb.WriteString(fmt.Sprintf(": %s", dis.Error)) |
| 106 | + } |
| 107 | + return sb.String() |
| 108 | +} |
| 109 | + |
| 110 | +func convertDockerInspect(in dockerInspect) codersdk.WorkspaceAgentContainer { |
| 111 | + out := codersdk.WorkspaceAgentContainer{ |
| 112 | + CreatedAt: in.Created, |
| 113 | + // Remove the leading slash from the container name |
| 114 | + FriendlyName: strings.TrimPrefix(in.Name, "/"), |
| 115 | + ID: in.ID, |
| 116 | + Image: in.Config.Image, |
| 117 | + Labels: in.Config.Labels, |
| 118 | + Ports: make([]codersdk.WorkspaceAgentListeningPort, 0), |
| 119 | + Running: in.State.Running, |
| 120 | + Status: in.State.String(), |
| 121 | + Volumes: make(map[string]string), |
| 122 | + } |
| 123 | + |
| 124 | + // sort the keys for deterministic output |
| 125 | + portKeys := maps.Keys(in.Config.ExposedPorts) |
| 126 | + sort.Strings(portKeys) |
| 127 | + for _, p := range portKeys { |
| 128 | + port, network, err := convertDockerPort(p) |
| 129 | + if err != nil { |
| 130 | + // ignore invalid ports |
| 131 | + continue |
| 132 | + } |
| 133 | + out.Ports = append(out.Ports, codersdk.WorkspaceAgentListeningPort{ |
| 134 | + Network: network, |
| 135 | + Port: port, |
| 136 | + }) |
| 137 | + } |
| 138 | + |
| 139 | + // sort the keys for deterministic output |
| 140 | + volKeys := maps.Keys(in.Config.Volumes) |
| 141 | + sort.Strings(volKeys) |
| 142 | + for _, k := range volKeys { |
| 143 | + v0, v1 := convertDockerVolume(k) |
| 144 | + out.Volumes[v0] = v1 |
| 145 | + } |
| 146 | + |
| 147 | + return out |
| 148 | +} |
| 149 | + |
| 150 | +// convertDockerPort converts a Docker port string to a port number and network |
| 151 | +// example: "8080/tcp" -> 8080, "tcp" |
| 152 | +// |
| 153 | +// "8080" -> 8080, "tcp" |
| 154 | +func convertDockerPort(in string) (uint16, string, error) { |
| 155 | + parts := strings.Split(in, "/") |
| 156 | + switch len(parts) { |
| 157 | + case 0: |
| 158 | + return 0, "", xerrors.Errorf("invalid port format: %s", in) |
| 159 | + case 1: |
| 160 | + // assume it's a TCP port |
| 161 | + p, err := strconv.Atoi(parts[0]) |
| 162 | + if err != nil { |
| 163 | + return 0, "", xerrors.Errorf("invalid port format: %s", in) |
| 164 | + } |
| 165 | + return uint16(p), "tcp", nil |
| 166 | + default: |
| 167 | + p, err := strconv.Atoi(parts[0]) |
| 168 | + if err != nil { |
| 169 | + return 0, "", xerrors.Errorf("invalid port format: %s", in) |
| 170 | + } |
| 171 | + return uint16(p), parts[1], nil |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +// convertDockerVolume converts a Docker volume string to a host path and |
| 176 | +// container path. If the host path is not specified, the container path is used |
| 177 | +// as the host path. |
| 178 | +// example: "/host/path=/container/path" -> "/host/path", "/container/path" |
| 179 | +// |
| 180 | +// "/container/path" -> "/container/path", "/container/path" |
| 181 | +func convertDockerVolume(in string) (hostPath, containerPath string) { |
| 182 | + parts := strings.Split(in, "=") |
| 183 | + switch len(parts) { |
| 184 | + case 0: |
| 185 | + return in, in |
| 186 | + case 1: |
| 187 | + return parts[0], parts[0] |
| 188 | + default: |
| 189 | + return parts[0], parts[1] |
| 190 | + } |
| 191 | +} |
0 commit comments