-
Notifications
You must be signed in to change notification settings - Fork 0
/
swarm.go
551 lines (477 loc) · 14.1 KB
/
swarm.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package swarm
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/docker/docker/pkg/namesgenerator"
"github.com/fsouza/go-dockerclient"
"github.com/ovh/cds/engine/log"
"github.com/ovh/cds/sdk"
"github.com/ovh/cds/sdk/hatchery"
"github.com/spf13/viper"
)
var hatcherySwarm *HatcherySwarm
//HatcherySwarm is a hatchery which can be connected to a remote to a docker remote api
type HatcherySwarm struct {
hatch *sdk.Hatchery
dockerClient *docker.Client
onlyWithServiceReq bool
maxContainers int
defaultMemory int
workerTTL int
}
//Init connect the hatchery to the docker api
func (h *HatcherySwarm) Init() error {
var err error
h.dockerClient, err = docker.NewClientFromEnv()
if err != nil {
log.Critical("Unable to connect to a docker client")
return err
}
if errPing := h.dockerClient.Ping(); errPing != nil {
log.Critical("Unable to ping docker host")
return errPing
}
// Register without declaring model
name, err := os.Hostname()
if err != nil {
log.Warning("Cannot retrieve hostname: %s\n", err)
name = "cds-hatchery"
}
name += "-swarm"
h.hatch = &sdk.Hatchery{
Name: name,
}
if err := hatchery.Register(h.hatch, viper.GetString("token")); err != nil {
log.Warning("Cannot register hatchery: %s\n", err)
return err
}
log.Notice("Swarm Hatchery ready to run !")
go h.killAwolWorkerRoutine()
return nil
}
// KillWorker kill the worker
func (h *HatcherySwarm) KillWorker(worker sdk.Worker) error {
log.Warning("killing container %s", worker.Name)
containers, err := h.dockerClient.ListContainers(docker.ListContainersOptions{
All: true,
})
if err != nil {
return err
}
for i := range containers {
if strings.Replace(containers[i].Names[0], "/", "", 1) == strings.Replace(worker.Name, "/", "", 1) {
//Kill the container, and all linked containers
h.killAndRemove(containers[i].ID)
}
}
return nil
}
func (h *HatcherySwarm) getContainer(name string) (*docker.APIContainers, error) {
containers, err := h.dockerClient.ListContainers(docker.ListContainersOptions{
All: true,
})
if err != nil {
return nil, err
}
for i := range containers {
if strings.Replace(containers[i].Names[0], "/", "", 1) == strings.Replace(name, "/", "", 1) {
return &containers[i], nil
}
}
return nil, nil
}
func (h *HatcherySwarm) killAndRemove(ID string) error {
container, err := h.dockerClient.InspectContainer(ID)
if err != nil {
return err
}
network, err := h.dockerClient.NetworkInfo(container.NetworkSettings.NetworkID)
if err != nil {
return err
}
if netname, ok := network.Labels["worker_net"]; ok {
log.Notice("Remove network %s", netname)
for id := range network.Containers {
log.Notice("Remove container %s", id)
if err := h.dockerClient.KillContainer(docker.KillContainerOptions{
ID: id,
Signal: docker.SIGKILL,
}); err != nil {
log.Warning("Unable to kill container %s", err)
continue
}
if err := h.dockerClient.RemoveContainer(docker.RemoveContainerOptions{
ID: id,
RemoveVolumes: true,
Force: true,
}); err != nil {
log.Warning("Unable to remove container %s", err)
}
}
} else {
log.Notice("Remove container %s", ID)
if err := h.dockerClient.KillContainer(docker.KillContainerOptions{
ID: ID,
Signal: docker.SIGKILL,
}); err != nil {
log.Warning("Unable to kill container %s", err)
}
if err := h.dockerClient.RemoveContainer(docker.RemoveContainerOptions{
ID: ID,
}); err != nil {
log.Warning("Unable to remove container %s", err)
}
}
return nil
}
//SpawnWorker start a new docker container
func (h *HatcherySwarm) SpawnWorker(model *sdk.Model, req []sdk.Requirement) error {
//name is the name of the worker and the name of the container
name := fmt.Sprintf("swarmy-%s-%s", strings.ToLower(model.Name), strings.Replace(namesgenerator.GetRandomName(0), "_", "-", -1))
log.Notice("Spawning worker %s with requirements %v", name, req)
//Create a network
network := name + "-net"
h.createNetwork(network)
//Memory for the worker
memory := int64(h.defaultMemory)
for _, r := range req {
if r.Type == sdk.MemoryRequirement {
var err error
memory, err = strconv.ParseInt(r.Value, 10, 64)
if err != nil {
log.Warning("SpawnWorker>Unable to parse memory requirement %s :s\n", memory, err)
return err
}
}
}
//Prepare worker services from requirements
services := []string{}
for _, r := range req {
if r.Type == sdk.ServiceRequirement {
//name= <alias> => the name of the host put in /etc/hosts of the worker
//value= "postgres:latest env_1=blabla env_2=blabla"" => we can add env variables in requirement name
tuple := strings.Split(r.Value, " ")
img := tuple[0]
env := []string{}
serviceMemory := int64(1024)
if len(tuple) > 1 {
env = append(env, tuple[1:]...)
}
//option for power user : set the service memory with CDS_SERVICE_MEMORY=1024
for _, e := range env {
if strings.HasPrefix(e, "CDS_SERVICE_MEMORY=") {
m := strings.Replace(e, "CDS_SERVICE_MEMORY=", "", -1)
i, err := strconv.Atoi(m)
if err != nil {
log.Warning("SpawnWorker> Unable to parse service option %s : %s", e, err)
continue
}
serviceMemory = int64(i)
}
}
serviceName := r.Name + "-" + name
//labels are used to make container cleanup easier. We "link" the service to its worker this way.
labels := map[string]string{
"service_worker": name,
"service_name": serviceName,
}
//Start the services
if err := h.createAndStartContainer(serviceName, img, network, r.Name, []string{}, env, labels, serviceMemory); err != nil {
log.Warning("SpawnWorker>Unable to start required container: %s\n", err)
return err
}
services = append(services, serviceName)
}
}
//cmd is the command to start the worker (we need curl to download current version of the worker binary)
cmd := []string{"sh", "-c", fmt.Sprintf("curl %s/download/worker/`uname -m` -o worker && echo chmod worker && chmod +x worker && echo starting worker && ./worker", sdk.Host)}
//CDS env needed by the worker binary
env := []string{
"CDS_API" + "=" + sdk.Host,
"CDS_NAME" + "=" + name,
"CDS_KEY" + "=" + viper.GetString("token"),
"CDS_MODEL" + "=" + strconv.FormatInt(model.ID, 10),
"CDS_HATCHERY" + "=" + strconv.FormatInt(h.hatch.ID, 10),
"CDS_TTL" + "=" + strconv.Itoa(h.workerTTL),
"CDS_SINGLE_USE=1",
}
//labels are used to make container cleanup easier
labels := map[string]string{
"worker_model": strconv.FormatInt(model.ID, 10),
"worker_name": name,
"worker_requirements": strings.Join(services, ","),
}
//start the worker
if err := h.createAndStartContainer(name, model.Image, network, "worker", cmd, env, labels, memory); err != nil {
log.Warning("SpawnWorker> Unable to start container %s\n", err)
}
return nil
}
//create the docker bridge
func (h *HatcherySwarm) createNetwork(name string) error {
log.Debug("createAndStartContainer> Create network %s\n", name)
_, err := h.dockerClient.CreateNetwork(docker.CreateNetworkOptions{
Name: name,
Driver: "bridge",
Internal: false,
CheckDuplicate: true,
EnableIPv6: false,
IPAM: docker.IPAMOptions{
Driver: "default",
},
Labels: map[string]string{
"worker_net": name,
},
})
return err
}
//shortcut to create+start(=run) a container
func (h *HatcherySwarm) createAndStartContainer(name, image, network, networkAlias string, cmd, env []string, labels map[string]string, memory int64) error {
//Memory is set to 1GB by default
if memory <= 4 {
memory = 1024
} else {
//Moaaaaar memory
memory = memory * 110 / 100
}
log.Notice("createAndStartContainer> Create container %s from %s on network %s as %s (memory=%dMB)", name, image, network, networkAlias, memory)
opts := docker.CreateContainerOptions{
Name: name,
Config: &docker.Config{
Image: image,
Cmd: cmd,
Env: env,
Labels: labels,
Memory: memory * 1024 * 1024, //from MB to B
MemorySwap: -1,
},
NetworkingConfig: &docker.NetworkingConfig{
EndpointsConfig: map[string]*docker.EndpointConfig{
network: &docker.EndpointConfig{
Aliases: []string{networkAlias, name},
},
},
},
}
c, err := h.dockerClient.CreateContainer(opts)
if err != nil {
log.Warning("startAndCreateContainer> Unable to create container %s\n", err)
return err
}
if err := h.dockerClient.StartContainer(c.ID, nil); err != nil {
log.Warning("startAndCreateContainer> Unable to start container %s\n", err)
return err
}
return nil
}
// CanSpawn checks if the model can be spawned by this hatchery
func (h *HatcherySwarm) CanSpawn(model *sdk.Model, req []sdk.Requirement) bool {
if model.Type != sdk.Docker {
return false
}
//List all containers to check if we can spawn a new one
if cs, _ := h.dockerClient.ListContainers(docker.ListContainersOptions{}); len(cs) > h.maxContainers {
return false
}
//Get links from requirements
var atLeastOneLink bool
links := map[string]string{}
for _, r := range req {
if r.Type == sdk.ServiceRequirement {
atLeastOneLink = true
links[r.Name] = strings.Split(r.Value, " ")[0]
}
}
//This hatchery may only manage container with links
if (!atLeastOneLink) && h.onlyWithServiceReq {
return false
}
log.Notice("CanSpawn> %s need %v", model.Name, links)
images, err := h.dockerClient.ListImages(docker.ListImagesOptions{})
if err != nil {
log.Warning("Unable to get images : %s", err)
}
var imageFound bool
checkImage:
for _, img := range images {
for _, t := range img.RepoTags {
if model.Image == t {
imageFound = true
break checkImage
}
}
}
if !imageFound {
//Pull the worker image
opts := docker.PullImageOptions{
Repository: model.Image,
OutputStream: nil,
}
auth := docker.AuthConfiguration{}
log.Notice("CanSpawn> pulling image %s", model.Image)
if err := h.dockerClient.PullImage(opts, auth); err != nil {
log.Warning("Unable to pull image %s : %s", model.Image, err)
return false
}
}
//Pull the service image
for _, i := range links {
var imageFound2 bool
checkLink:
for _, img := range images {
for _, t := range img.RepoTags {
if i == t {
imageFound2 = true
break checkLink
}
}
}
if !imageFound2 {
opts := docker.PullImageOptions{
Repository: i,
OutputStream: nil,
}
auth := docker.AuthConfiguration{}
log.Notice("CanSpawn> pulling image %s", i)
if err := h.dockerClient.PullImage(opts, auth); err != nil {
log.Warning("Unable to pull image %s : %s", i, err)
return false
}
}
}
//Ready to spawn
log.Notice("CanSpawn> %s can be spawned", model.Name)
return true
}
// WorkerStarted returns the number of started workers
func (h *HatcherySwarm) WorkerStarted(model *sdk.Model) int {
if model.Type != sdk.Docker {
return 0
}
containers, err := h.dockerClient.ListContainers(docker.ListContainersOptions{})
if err != nil {
log.Warning("WorkerStarted> error listing containers : %s", err)
}
list := []string{}
for _, c := range containers {
log.Info("Container : %s %s [%s]", c.ID, c.Image, c.Status)
if c.Image == model.Image {
list = append(list, c.ID)
}
}
log.Notice("WorkerStarted> %s \t %d", model.Name, len(list))
return len(list)
}
// Hatchery returns Hatchery instances
func (h *HatcherySwarm) Hatchery() *sdk.Hatchery {
return h.hatch
}
// ID returns ID of the Hatchery
func (h *HatcherySwarm) ID() int64 {
if h.hatch == nil {
return 0
}
return h.hatch.ID
}
func (h *HatcherySwarm) killAwolWorkerRoutine() {
for {
time.Sleep(30 * time.Second)
h.killAwolWorker()
}
}
func (h *HatcherySwarm) killAwolWorker() {
apiworkers, err := sdk.GetWorkers()
if err != nil {
log.Warning("Cannot get workers: %s", err)
os.Exit(1)
}
containers, errList := h.dockerClient.ListContainers(docker.ListContainersOptions{
All: true,
})
if errList != nil {
log.Warning("Cannot list containers: %s", errList)
os.Exit(1)
}
//Checking workers
oldContainers := []docker.APIContainers{}
for _, c := range containers {
//Ignore containers spawned by other things that this Hatchery
if c.Labels["worker_name"] == "" {
continue
}
//If there isn't any worker registered on the API. Kill the container
if len(apiworkers) == 0 {
oldContainers = append(oldContainers, c)
continue
}
//Loop on all worker registered on the API
//Try to find the worker matching this container
var found = false
for _, n := range apiworkers {
if n.Name == c.Names[0] || n.Name == strings.Replace(c.Names[0], "/", "", 1) {
found = true
// If worker is disabled, kill it
if n.Status == sdk.StatusDisabled {
log.Info("Worker %s is disabled. Kill it with fire !\n", c.Names[0])
oldContainers = append(oldContainers, c)
break
}
}
}
//If the container doesn't match any worker : Kill it.
if !found {
oldContainers = append(oldContainers, c)
}
}
//Delete the workers
for _, c := range oldContainers {
h.killAndRemove(c.ID)
log.Notice("HatcherySwarm.killAwolWorker> Delete worker %s\n", c.Names[0])
}
var errLC error
containers, errLC = h.dockerClient.ListContainers(docker.ListContainersOptions{
All: true,
})
if errLC != nil {
log.Warning("Cannot get containers: %s", errLC)
return
}
//Checking services
for _, c := range containers {
if c.Labels["service_worker"] == "" {
continue
}
if w, _ := h.getContainer(c.Labels["service_worker"]); w == nil {
oldContainers = append(oldContainers, c)
continue
}
}
for _, c := range oldContainers {
h.killAndRemove(c.ID)
log.Notice("HatcherySwarm.killAwolWorker> Delete worker %s\n", c.Names[0])
}
//Checking networks
nets, errLN := h.dockerClient.ListNetworks()
if errLN != nil {
log.Warning("Cannot get networks: %s", errLN)
return
}
for _, n := range nets {
if n.Driver != "bridge" || n.Name == "docker0" || n.Name == "bridge" {
continue
}
if _, ok := n.Labels["worker_net"]; !ok {
continue
}
if len(n.Containers) > 0 {
continue
}
log.Notice("HatcherySwarm.killAwolWorker> Delete network %s", n.Name)
if err := h.dockerClient.RemoveNetwork(n.ID); err != nil {
log.Warning("HatcherySwarm.killAwolWorker> Unable to delete network %s", n.Name)
}
}
}