-
Notifications
You must be signed in to change notification settings - Fork 5
/
run.go
59 lines (53 loc) · 1.36 KB
/
run.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
package docker
import (
"context"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
)
func (d Docker) Run(ctx context.Context, env map[string]string, cmd ...string) (ContainerID, error) {
resp, err := d.ContainerCreate(ctx, &container.Config{
Image: d.image,
Env: mapToSlice(env),
Cmd: cmd,
}, &container.HostConfig{
AutoRemove: true, // --rm; FIXME: this causes "No such container" if the container exits early
PublishAllPorts: true, // -P
Resources: container.Resources{
Memory: int64(d.memory),
},
}, nil, parsePlatform(d.platform), "")
if err != nil {
return nil, err
}
return &resp.ID, d.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
}
func mapToSlice(m map[string]string) []string {
s := make([]string, 0, len(m))
for k, v := range m {
// Ensure no = in key
if strings.ContainsRune(k, '=') {
panic("invalid environment variable key")
}
s = append(s, k+"="+v)
}
return s
}
func parsePlatform(platform string) *v1.Platform {
parts := strings.Split(platform, "/")
var p = &v1.Platform{}
switch len(parts) {
case 3:
p.Variant = parts[2]
fallthrough
case 2:
p.OS = parts[0]
p.Architecture = parts[1]
case 1:
p.Architecture = parts[0]
default:
panic("invalid platform: " + platform)
}
return p
}