/
docker.go
341 lines (305 loc) · 7.36 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
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
package docker
import (
"context"
"errors"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/hamster-shared/hamster-provider/core/modules/provider"
"github.com/hamster-shared/hamster-provider/core/modules/utils"
"github.com/hamster-shared/hamster-provider/log"
"io"
"os"
"os/exec"
"strconv"
"time"
)
type DockerManager struct {
template *provider.Template
//access port
accessPort int
// docker client
cli *client.Client
// context
ctx context.Context
// image
image string
}
func NewDockerManager(t provider.Template) (*DockerManager, error) {
cli, err := client.NewClientWithOpts(client.WithVersion("1.38"))
if err != nil {
log.GetLogger().Error(err)
return nil, err
}
manager := &DockerManager{
cli: cli,
ctx: context.Background(),
}
err = manager.SetTemplate(t)
return manager, err
}
func (d *DockerManager) SetTemplate(t provider.Template) error {
d.template = &t
d.image = t.Image
d.accessPort = 22
return nil
}
func (d *DockerManager) Status(name string) (*provider.Status, error) {
containers, err := d.cli.ContainerList(d.ctx, types.ContainerListOptions{
All: true,
Filters: filters.NewArgs(filters.Arg("name", name)),
})
if err != nil {
return nil, err
}
if len(containers) == 0 {
return &provider.Status{}, errors.New("container not exists")
}
// status Status 0: Off, 1: On, 2: Paused, 3, other
var status provider.StatusValue
switch containers[0].State {
case "created":
status = provider.STOP
break
case "restarting":
status = provider.OTHER
break
case "running":
status = provider.RUNNING
break
case "removing":
status = provider.OTHER
break
case "paused":
status = provider.OTHER
break
case "exited":
case "dead":
status = 0
break
}
return &provider.Status{
Status: status,
Id: containers[0].ID,
}, nil
}
// query container ip address
func (d *DockerManager) GetIp(name string) (string, error) {
//status, err := d.Status()
//
//if err != nil {
// return "", err
//}
//
//if status.Id == "" {
// return "", errors.New("container id cannot be empty")
//}
//
//containerJson, err := d.cli.ContainerInspect(d.ctx, status.Id)
//if err != nil {
// return "", err
//}
//return containerJson.NetworkSettings.IPAddress, nil
// macos cannot directly access container ip
return "127.0.0.1", nil
}
func (d *DockerManager) GetAccessPort(name string) int {
inspect, err := d.cli.ContainerInspect(d.ctx, name)
if err != nil {
return 0
}
portMap := inspect.NetworkSettings.Ports
port, _ := nat.NewPort("tcp", strconv.Itoa(d.accessPort))
arrays := portMap[port]
if len(arrays) > 0 {
hostPort, _ := strconv.Atoi(arrays[0].HostPort)
return hostPort
}
return 0
}
func (d *DockerManager) Create(name string) (string, error) {
// view all images
imageLists, err := d.cli.ImageList(d.ctx, types.ImageListOptions{
All: true,
Filters: filters.NewArgs(filters.Arg("reference", d.image)),
})
if err != nil {
log.GetLogger().Error(err)
return "", err
}
if len(imageLists) == 0 {
// pull image
out, err := d.cli.ImagePull(d.ctx, d.image, types.ImagePullOptions{})
if err != nil {
log.GetLogger().Error(err)
return "", err
}
_, err = io.Copy(os.Stdout, out)
if err != nil {
return "", err
}
}
// determine whether there is a repeated start
status, err := d.Status(name)
if err != nil {
log.GetLogger().Error(err.Error())
}
if status.Id != "" {
err = d.cli.ContainerRemove(d.ctx, status.Id, types.ContainerRemoveOptions{Force: true})
if err != nil {
return status.Id, err
}
}
port, err := nat.NewPort("tcp", strconv.Itoa(d.accessPort))
// create a container
resp, err := d.cli.ContainerCreate(d.ctx, &container.Config{
Image: d.image, //image name
//Tty: true,
//OpenStdin: true,
//Cmd: []string{cmd},
//WorkingDir: workDir,
ExposedPorts: nat.PortSet{
port: struct{}{}, //docker container open port
},
},
&container.HostConfig{
Resources: container.Resources{
CPUCount: int64(d.template.Cpu),
Memory: int64(d.template.Memory << 30),
},
PortBindings: nat.PortMap{
port: []nat.PortBinding{
{
HostPort: strconv.Itoa(utils.RandomPort()),
},
},
},
}, nil, nil, name)
if err != nil {
log.GetLogger().Error(err)
return resp.ID, err
}
log.GetLogger().WithField("containerId", resp.ID).Info("container created")
return resp.ID, err
}
// StartContainer running containers in the background
func (d *DockerManager) Start(name string) error {
status, err := d.Status(name)
if err != nil {
return err
}
id := status.Id
if status.Status == 0 && id != "" {
err = d.cli.ContainerStart(d.ctx, id, types.ContainerStartOptions{})
return err
} else {
return errors.New("container status is invalid")
}
}
func (d *DockerManager) CreateAndStart(name string) (string, error) {
id, err := d.Create(name)
if err != nil {
return id, err
}
err = d.Start(name)
return id, err
}
func (d *DockerManager) CreateAndStartAndInjectionPublicKey(name, publicKey string) (string, error) {
// create a virtual machine
id, err := d.CreateAndStart(name)
if err != nil {
return id, err
}
// wait for the virtual machine to start successfully
for {
status, err := d.Status(name)
if err != nil {
return id, err
}
if status.IsRunning() {
break
}
time.Sleep(time.Second * 3)
}
err = d.InjectionPublicKey(name, publicKey)
return id, err
}
func (d *DockerManager) Stop(name string) error {
status, err := d.Status(name)
if status.Status != 1 {
return errors.New("invalid container status")
}
if err != nil {
return err
}
id := status.Id
timeout := time.Second * 3
if id != "" {
return d.cli.ContainerStop(d.ctx, status.Id, &timeout)
} else {
return errors.New("container id is invalid")
}
}
func (d *DockerManager) Reboot(name string) error {
status, err := d.Status(name)
if err != nil {
return err
}
id := status.Id
timeout := time.Second * 3
if id != "" {
return d.cli.ContainerRestart(d.ctx, status.Id, &timeout)
} else {
return errors.New("container id is invalid")
}
}
func (d *DockerManager) Shutdown(name string) error {
status, err := d.Status(name)
if status.Status != 1 {
return errors.New("invalid container status")
}
if err != nil {
return err
}
id := status.Id
timeout := time.Second * 3
if id != "" {
return d.cli.ContainerStop(d.ctx, status.Id, &timeout)
} else {
return errors.New("container id is invalid")
}
}
// Destroy delete container
func (d *DockerManager) Destroy(name string) error {
status, err := d.Status(name)
if err != nil {
return err
}
id := status.Id
if id != "" {
return d.cli.ContainerRemove(d.ctx, status.Id, types.ContainerRemoveOptions{Force: true})
} else {
return errors.New("container id is invalid")
}
}
// InjectionPublicKey add the public key to the container
func (d *DockerManager) InjectionPublicKey(name, publicKey string) error {
status, err := d.Status(name)
if !status.IsRunning() {
return errors.New("invalid container status")
}
if err != nil {
return err
}
id := status.Id
if id != "" {
cmd := fmt.Sprintf("echo %s > /root/.ssh/authorized_keys", publicKey)
command := exec.Command("docker", "exec", id, "bash", "-c", cmd)
return command.Run()
} else {
return errors.New("container status is invalid")
}
}