-
Notifications
You must be signed in to change notification settings - Fork 3
/
command.go
366 lines (305 loc) · 10 KB
/
command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright (c) ClaceIO, LLC
// SPDX-License-Identifier: Apache-2.0
package container
import (
"bufio"
"bytes"
"container/ring"
"encoding/base32"
"encoding/json"
"fmt"
"io"
"os/exec"
"strconv"
"strings"
"github.com/claceio/clace/internal/types"
)
type Container struct {
ID string `json:"ID"`
Names string `json:"Names"`
Image string `json:"Image"`
State string `json:"State"`
Status string `json:"Status"`
PortString string `json:"Ports"`
Port int
}
type Image struct {
Repository string `json:"Repository"`
}
type ContainerName string
type ImageName string
type VolumeName string
var base32encoder = base32.StdEncoding.WithPadding(base32.NoPadding)
func genLowerCaseId(name string) string {
// The container id needs to be lower case. Use base32 to encode the name so that it can be lowercased
return strings.ToLower(base32encoder.EncodeToString([]byte(name)))
}
func GenContainerName(appId types.AppId, contentHash string) ContainerName {
if contentHash == "" {
return ContainerName(fmt.Sprintf("clc-%s", appId))
} else {
return ContainerName(fmt.Sprintf("clc-%s-%s", appId, genLowerCaseId(contentHash)))
}
}
func GenImageName(appId types.AppId, contentHash string) ImageName {
if contentHash == "" {
return ImageName(fmt.Sprintf("cli-%s", appId))
} else {
return ImageName(fmt.Sprintf("cli-%s-%s", appId, genLowerCaseId(contentHash)))
}
}
type ContainerCommand struct {
*types.Logger
}
func (c ContainerCommand) RemoveImage(config *types.SystemConfig, name ImageName) error {
cmd := exec.Command(config.ContainerCommand, "rmi", string(name))
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error removing image: %s : %s", output, err)
}
return nil
}
func (c ContainerCommand) BuildImage(config *types.SystemConfig, name ImageName, sourceUrl, containerFile string) error {
c.Debug().Msgf("Building image %s from %s with %s", name, containerFile, sourceUrl)
cmd := exec.Command(config.ContainerCommand, "build", "-t", string(name), "-f", containerFile, ".")
cmd.Dir = sourceUrl
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error building image: %s : %s", output, err)
}
return nil
}
func (c ContainerCommand) RemoveContainer(config *types.SystemConfig, name ContainerName) error {
c.Debug().Msgf("Removing container %s", name)
cmd := exec.Command(config.ContainerCommand, "rm", string(name))
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error removing image: %s : %s", output, err)
}
return nil
}
func (c ContainerCommand) GetContainers(config *types.SystemConfig, name ContainerName, getAll bool) ([]Container, error) {
c.Debug().Msgf("Getting containers with name %s, getAll %t", name, getAll)
args := []string{"ps", "--format", "json"}
if name != "" {
args = append(args, "--filter", fmt.Sprintf("name=%s", name))
}
if getAll {
args = append(args, "--all")
}
cmd := exec.Command(config.ContainerCommand, args...)
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("error listing containers: %s : %s", output, err)
}
resp := []Container{}
if len(output) == 0 {
c.Debug().Msg("No containers found")
return resp, nil
}
if output[0] == '[' {
// Podman format (Names and Ports are arrays)
type Port struct {
// only HostPort is needed
HostPort int `json:"host_port"`
}
type ContainerPodman struct {
ID string `json:"ID"`
Names []string `json:"Names"`
Image string `json:"Image"`
State string `json:"State"`
Status string `json:"Status"`
Ports []Port `json:"Ports"`
}
result := []ContainerPodman{}
// JSON output (podman)
err = json.Unmarshal(output, &result)
if err != nil {
return nil, err
}
for _, c := range result {
port := 0
if len(c.Ports) > 0 {
port = c.Ports[0].HostPort
}
resp = append(resp, Container{
ID: c.ID,
Names: c.Names[0],
Image: c.Image,
State: c.State,
Status: c.Status,
Port: port,
})
}
} else if output[0] == '{' {
// Newline separated JSON (Docker)
decoder := json.NewDecoder(bytes.NewReader(output))
for decoder.More() {
var c Container
if err := decoder.Decode(&c); err != nil {
return nil, fmt.Errorf("error decoding container output: %v", err)
}
if c.PortString != "" {
// "Ports":"127.0.0.1:55000-\u003e5000/tcp"
_, v, ok := strings.Cut(c.PortString, ":")
if !ok {
return nil, fmt.Errorf("error parsing \":\" from port string: %s", c.PortString)
}
v, _, ok = strings.Cut(v, "-")
if !ok {
return nil, fmt.Errorf("error parsing \"-\" from port string: %s", v)
}
c.Port, err = strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf("error converting to int port string: %s", v)
}
}
resp = append(resp, c)
}
} else {
return nil, fmt.Errorf("\"%s ps\" returned unknown output: %s", config.ContainerCommand, output)
}
c.Debug().Msgf("Found containers: %+v", resp)
return resp, nil
}
func (c ContainerCommand) GetContainerLogs(config *types.SystemConfig, name ContainerName) (string, error) {
c.Debug().Msgf("Getting container logs %s", name)
lines, err := c.ExecTailN(config.ContainerCommand, []string{"logs", string(name)}, 1000)
if err != nil {
return "", fmt.Errorf("error getting container %s logs: %s", name, err)
}
return strings.Join(lines, "\n"), nil
}
func (c ContainerCommand) StopContainer(config *types.SystemConfig, name ContainerName) error {
c.Debug().Msgf("Stopping container %s", name)
cmd := exec.Command(config.ContainerCommand, "stop", "-t", "1", string(name))
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error stopping container: %s : %s", output, err)
}
return nil
}
func (c ContainerCommand) StartContainer(config *types.SystemConfig, name ContainerName) error {
c.Debug().Msgf("Starting container %s", name)
cmd := exec.Command(config.ContainerCommand, "start", string(name))
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error starting container: %s : %s", output, err)
}
return nil
}
const LABEL_PREFIX = "io.clace."
func (c ContainerCommand) RunContainer(config *types.SystemConfig, appEntry *types.AppEntry, containerName ContainerName,
imageName ImageName, port int64, envMap map[string]string, mountArgs []string) error {
c.Debug().Msgf("Running container %s from image %s with port %d env %+v mountArgs %+v",
containerName, imageName, port, envMap, mountArgs)
publish := fmt.Sprintf("127.0.0.1::%d", port)
args := []string{"run", "--name", string(containerName), "--detach", "--publish", publish}
if len(mountArgs) > 0 {
args = append(args, mountArgs...)
}
args = append(args, "--label", LABEL_PREFIX+"app.id="+string(appEntry.Id))
if appEntry.IsDev {
args = append(args, "--label", LABEL_PREFIX+"dev=true")
} else {
args = append(args, "--label", LABEL_PREFIX+"dev=false")
args = append(args, "--label", LABEL_PREFIX+"app.version="+strconv.Itoa(appEntry.Metadata.VersionMetadata.Version))
args = append(args, "--label", LABEL_PREFIX+"git.sha="+appEntry.Metadata.VersionMetadata.GitCommit)
args = append(args, "--label", LABEL_PREFIX+"git.message="+appEntry.Metadata.VersionMetadata.GitMessage)
}
for k, v := range envMap {
args = append(args, "--env", fmt.Sprintf("%s=%s", k, v))
}
args = append(args, string(imageName))
c.Debug().Msgf("Running container with args: %v", args)
cmd := exec.Command(config.ContainerCommand, args...)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error running container: %s : %s", output, err)
}
return nil
}
func (c ContainerCommand) GetImages(config *types.SystemConfig, name ImageName) ([]Image, error) {
c.Debug().Msgf("Getting images with name %s", name)
args := []string{"images", "--format", "json"}
if name != "" {
args = append(args, string(name))
}
cmd := exec.Command(config.ContainerCommand, args...)
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("error listing images: %s : %s", output, err)
}
resp := []Image{}
if len(output) == 0 {
return resp, nil
}
if output[0] == '[' {
// Podman format
type ImagePodman struct {
Id string `json:"Id"`
}
result := []ImagePodman{}
// JSON output (podman)
err = json.Unmarshal(output, &result)
if err != nil {
return nil, err
}
for _, i := range result {
resp = append(resp, Image{
Repository: i.Id,
})
}
} else if output[0] == '{' {
// Newline separated JSON (Docker)
decoder := json.NewDecoder(bytes.NewReader(output))
for decoder.More() {
var i Image
if err := decoder.Decode(&i); err != nil {
return nil, fmt.Errorf("error decoding image output: %v", err)
}
resp = append(resp, i)
}
} else {
return nil, fmt.Errorf("\"%s ps\" returned unknown output: %s", config.ContainerCommand, output)
}
c.Debug().Msgf("Found images: %+v", resp)
return resp, nil
}
// ExecTailN executes a command and returns the last n lines of output
func (c ContainerCommand) ExecTailN(command string, args []string, n int) ([]string, error) {
cmd := exec.Command(command, args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("error creating stdout pipe: %s", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, fmt.Errorf("error creating stderr pipe: %s", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("error starting command: %s", err)
}
multi := bufio.NewReader(io.MultiReader(stdout, stderr))
// Create a ring buffer to hold the last 1000 lines of output
ringBuffer := ring.New(n)
scanner := bufio.NewScanner(multi)
for scanner.Scan() {
// Push the latest line into the ring buffer, displacing the oldest line if necessary
ringBuffer.Value = scanner.Text()
ringBuffer = ringBuffer.Next()
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error scanning output: %s", err)
}
if err := cmd.Wait(); err != nil {
return nil, fmt.Errorf("error waiting for command: %s", err)
}
ret := make([]string, 0, n)
ringBuffer.Do(func(p any) {
if line, ok := p.(string); ok {
ret = append(ret, line)
}
})
return ret, nil
}