-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker.go
More file actions
79 lines (68 loc) · 2.36 KB
/
docker.go
File metadata and controls
79 lines (68 loc) · 2.36 KB
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
package main
import (
"context"
"fmt"
"os/exec"
"strings"
"time"
)
// DockerExecutor runs commands inside a Docker container.
type DockerExecutor struct {
container string
shell string
owned bool // true if we created the container (should stop on Close)
}
// NewDockerExecutor connects to an existing container or creates one from an image.
// If container is set, exec into that container.
// If image is set, create a new container from the image.
func NewDockerExecutor(container, image, shell string) (*DockerExecutor, error) {
if shell == "" {
shell = "sh"
}
if container != "" {
// Verify container is running
out, err := exec.Command("docker", "inspect", "-f", "{{.State.Running}}", container).CombinedOutput()
if err != nil {
return nil, fmt.Errorf("container %q not found or not accessible: %s", container, strings.TrimSpace(string(out)))
}
if strings.TrimSpace(string(out)) != "true" {
return nil, fmt.Errorf("container %q is not running", container)
}
return &DockerExecutor{container: container, shell: shell, owned: false}, nil
}
if image != "" {
// Create a long-running container from the image
out, err := exec.Command("docker", "run", "-d", "--rm", image, "sleep", "infinity").CombinedOutput()
if err != nil {
return nil, fmt.Errorf("failed to create container from image %q: %s", image, strings.TrimSpace(string(out)))
}
containerID := strings.TrimSpace(string(out))
return &DockerExecutor{container: containerID, shell: shell, owned: true}, nil
}
return nil, fmt.Errorf("either container or image must be set")
}
func (e *DockerExecutor) Exec(command string, timeout int) (string, error) {
var ctx context.Context
var cancel context.CancelFunc
if timeout > 0 {
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
} else {
ctx = context.Background()
}
cmd := exec.CommandContext(ctx, "docker", "exec", e.container, e.shell, "-c", command)
output, err := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
return string(output), fmt.Errorf("command timed out after %d seconds", timeout)
}
if err != nil {
return string(output) + "\nError: " + err.Error(), nil
}
return string(output), nil
}
func (e *DockerExecutor) Close() error {
if e.owned && e.container != "" {
exec.Command("docker", "stop", e.container).Run()
}
return nil
}