-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
121 lines (106 loc) · 2.57 KB
/
docker.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
package docker
import (
"context"
"fmt"
_types "github.com/docker/docker/api/types"
_container "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
specs "github.com/opencontainers/image-spec/specs-go/v1"
)
type PsOptions struct {
All bool
FilterNames []string
}
type RunOptions struct {
Image string
Name string
Force bool
Env map[string]string
Ports map[string]string
}
var ctx context.Context
var cli *client.Client
var platform specs.Platform
func Ps(options *PsOptions) ([]_types.Container, error) {
var filter filters.Args
if len(options.FilterNames) > 0 {
filter = filters.NewArgs()
for _, f := range options.FilterNames {
filter.Add("name", f)
}
}
clo := _types.ContainerListOptions{}
clo.Filters = filter
clo.All = options.All
containers, err := cli.ContainerList(ctx, clo)
if err != nil {
return nil, err
}
return containers, nil
}
func Run(options *RunOptions) error {
ps_opts := PsOptions{}
ps_opts.All = true
ps_opts.FilterNames = append(ps_opts.FilterNames, options.Name)
containers, err := Ps(&ps_opts)
if err != nil {
return err
}
var container_id string
// container does not exist => create
if len(containers) == 0 {
env := make([]string, len(options.Env))
i := 0
for k, v := range options.Env {
env[i] = fmt.Sprintf("%s=%s", k, v)
i++
}
// create container
config := _container.Config{
Image: options.Image,
Env: env,
}
hostConfig := _container.HostConfig{
NetworkMode: "host",
}
networkConfig := network.NetworkingConfig{}
result, err := cli.ContainerCreate(ctx, &config, &hostConfig, &networkConfig, &platform, options.Name)
if err != nil {
return err
}
container_id = result.ID
} else { // container exists
con := containers[0]
if options.Force {
container_id = con.ID
switch con.State {
case "running": // restart
cli.ContainerStop(ctx, container_id, nil)
// case "created":
// case "exited":
// default:
}
} else {
return fmt.Errorf("container <%s> already exists: state = %s\nuse option `Force` or another container name\n", options.Name, con.State)
}
}
// start container
err = cli.ContainerStart(ctx, container_id, _types.ContainerStartOptions{})
if err != nil {
return err
}
return nil
}
func init() {
var err error
ctx = context.Background()
cli, err = client.NewClientWithOpts(client.FromEnv)
if err != nil {
panic(err)
}
cli.NegotiateAPIVersion(ctx)
platform = specs.Platform{}
platform.OS = "linux"
}