-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprojectconfig.go
616 lines (536 loc) · 13.1 KB
/
projectconfig.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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package main
import (
"fmt"
"github.com/byrnedo/capitan/consts"
"github.com/byrnedo/capitan/container"
"github.com/byrnedo/capitan/helpers"
. "github.com/byrnedo/capitan/logger"
"github.com/codeskyblue/go-sh"
"os"
"os/signal"
"sort"
"sync"
"syscall"
"text/template"
"github.com/byrnedo/capitan/shellsession"
)
const projectShowTemplate = `-------------------------------------------------
Project Name: {{.ProjectName}}
Blue/Green Mode (Global): {{.BlueGreenMode}}
Hooks (Global): {{range $key, $val := .Hooks}}
{{$key}}
{{range $hook := $val.Scripts}}{{$hook}}
{{end}}{{end}}
-------------------------------------------------
`
const containerShowTemplate = `{{.Name}}:
Name: {{.ServiceName}}
State:
ID: {{.State.ID}}
Color: {{.State.Color}}
Running: {{.State.Running}}
Hash: {{.State.ArgsHash}}
Type: {{.ServiceType}}
Image: {{.Image}}{{if .Build}}
Build: {{.Build}}{{end}}
Order: {{.Placement}}
Blue/Green Mode: {{.BlueGreenMode}}
Links: {{range $ind, $link := .Links}}
{{$link.Container}}{{if $link.Alias}}:{{$link.Alias}}{{end}}{{end}}
Hooks: {{range $key, $val := .Hooks}}
{{$key}}
{{range $hook := $val.Scripts}}{{$hook}}
{{end}}{{end}}
Scale: {{.Scale}}
Volumes From: {{range $ind, $val := .VolumesFrom}}
{{$val}}{{end}}
Run Args: {{range $ind, $val := .RunArguments}}
{{$val}}{{end}}
-------------------------------------------------
`
var (
allDone = make(chan bool, 1)
)
type ProjectConfig struct {
ProjectName string
ProjectSeparator string
BlueGreenMode bool
IsInteractive bool
ContainersState []*helpers.ServiceState
ContainerList SettingsList
ContainerCleanupList SettingsList
Hooks Hooks
}
type Hook struct {
Scripts []string
Ses *shellsession.ShellSession
}
type Hooks map[string]*Hook
// Runs a hook command if it exists for a specific container
func (h Hooks) Run(hookName string, settings *ProjectConfig) error {
var (
hook *Hook
found bool
err error
)
if hook, found = h[hookName]; !found {
return nil
}
for _, script := range hook.Scripts {
hook.Ses = shellsession.NewShellSession(func(s *shellsession.ShellSession){
s.SetEnv("CAPITAN_PROJECT_NAME", settings.ProjectName)
})
hook.Ses.SetEnv("CAPITAN_HOOK_NAME", hookName)
hook.Ses.Command("bash", "-c", script)
hook.Ses.Stdout = os.Stdout
hook.Ses.Stderr = os.Stderr
hook.Ses.Stdin = os.Stdin
if err = hook.Ses.Run(); err != nil {
return err
}
}
return nil
}
type SettingsList []*container.Container
func (s SettingsList) Len() int {
return len(s)
}
func (s SettingsList) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s SettingsList) Less(i, j int) bool {
if s[i].Placement == s[j].Placement {
iSuf, iErr := helpers.GetNumericSuffix(s[i].Name, s[i].ProjectNameSeparator)
jSuf, jErr := helpers.GetNumericSuffix(s[j].Name, s[i].ProjectNameSeparator)
if iErr == nil && jErr == nil {
return iSuf < jSuf
} else {
return sort.StringsAreSorted([]string{s[i].Name, s[j].Name})
}
}
return s[i].Placement < s[j].Placement
}
func (s SettingsList) Filter(cb func(*container.Container) bool) (filtered SettingsList) {
filtered = make(SettingsList, 0)
for _, item := range s {
if cb(item) {
filtered = append(filtered, item)
}
}
return
}
func (settings *ProjectConfig) LaunchSignalWatcher() {
var (
killBegan = make(chan bool, 1)
killDone = make(chan bool, 1)
stopDone = make(chan bool, 1)
signalChannel = make(chan os.Signal)
)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM)
go func() {
var (
killing bool
)
for {
select {
case <-killBegan:
killing = true
case <-stopDone:
if !killing {
allDone <- true
}
case <-killDone:
allDone <- true
}
}
}()
go func() {
// var calls int
for {
sig := <-signalChannel
switch sig {
case os.Interrupt, syscall.SIGTERM:
for _, con := range append(settings.ContainerCleanupList, settings.ContainerList...) {
for _, hooks := range con.Hooks {
if hooks.Ses != nil {
Debug.Println("killing hook...")
hooks.Ses.Kill(syscall.SIGKILL)
}
}
}
// if settings.IsInteractive {
// calls++
// if calls == 1 {
// go func() {
// settings.ContainerList.CapitanStop(nil, false)
// stopDone <- true
// }()
// } else if calls == 2 {
// killBegan <- true
// settings.ContainerList.CapitanKill(nil, false)
// killDone <- true
// }
// } else {
os.Exit(1)
// }
default:
Debug.Println("Unhandled signal", sig)
}
}
Info.Println("Done cleaning up")
}()
}
func (settings *ProjectConfig) RunHook(hookName string) bool {
if err:= settings.Hooks.Run(hookName,settings); err != nil {
Error.Println("Hook failed:", err)
return false
}
return true
}
func (settings *ProjectConfig) CapitanPs(args []string) error {
allArgs := append([]interface{}{"ps"}, helpers.ToInterfaceSlice(args)...)
allArgs = append(allArgs, "-f", fmt.Sprintf("label=%s=%s", consts.ProjectLabelName, settings.ProjectName))
var (
err error
out []byte
)
if out, err = helpers.RunCmd(allArgs...); err != nil {
return err
}
Info.Print(string(out))
return nil
}
func (settings *ProjectConfig) CapitanShow() error {
var (
tmpl *template.Template
err error
)
if tmpl, err = template.New("projectStringer").Parse(projectShowTemplate); err != nil {
return err
}
if err = tmpl.Execute(os.Stdout, settings); err != nil {
return err
}
return settings.ContainerList.CapitanShow()
}
func newerImage(container string, image string) bool {
conImage := helpers.GetContainerImageId(container)
localImage := helpers.GetImageId(image)
if conImage != "" && localImage != "" && conImage != localImage {
return true
}
return false
}
func haveArgsChanged(container string, runArgs []interface{}) bool {
uniqueLabel := helpers.HashInterfaceSlice(runArgs)
if helpers.GetContainerUniqueLabel(container) != uniqueLabel {
return true
}
return false
// remove and restart
}
func (settings SettingsList) CapitanCreate(dryRun bool) error {
sort.Sort(settings)
for _, set := range settings {
if set.Build != "" {
ContainerInfoLog(set.Name, "Building image...")
if ! dryRun {
if err := set.BuildImage(); err != nil {
return err
}
}
}
if helpers.GetImageId(set.Image) == "" {
Warning.Printf("Capitan was unable to find image %s locally\n", set.Image)
ContainerInfoLog(set.Name, "Pulling image...")
if ! dryRun {
if err := helpers.PullImage(set.Image); err != nil {
return err
}
}
}
if err := set.Create(dryRun); err != nil {
return err
}
}
return nil
}
// The 'up' command
//
// Creates a container if it doesn't exist
// Starts a container if stopped
// Recreates a container if the container's image has a newer id locally
// OR if the command used to create the container is now changed (i.e.
// config has changed.
func (settings SettingsList) CapitanUp(attach bool, dryRun bool) error {
sort.Sort(settings)
wg := sync.WaitGroup{}
for _, set := range settings {
var (
err error
)
if set.Build != "" {
ContainerInfoLog(set.Name, "Building image...")
if ! dryRun {
if err := set.BuildImage(); err != nil {
return err
}
}
}
if helpers.GetImageId(set.Image) == "" {
Warning.Printf("Capitan was unable to find image %s locally\n", set.Image)
ContainerInfoLog(set.Name, "Pulling image...")
if ! dryRun {
if err := helpers.PullImage(set.Image); err != nil {
return err
}
}
}
//create new
if !helpers.ContainerExists(set.Name) {
if err = set.Run(attach, dryRun, &wg); err != nil {
return err
}
continue
}
// disabling as this doesn't work with swarm (how do I know which node to look at??)
// if newerImage(set.Name, set.Image) {
// // remove and restart
// Info.Println("Removing (different image available):", set.Name)
// if err = set.RecreateAndRun(attach, dryRun, &wg); err != nil {
// return err
// }
//
// continue
// }
if haveArgsChanged(set.Name, set.GetRunArguments()) {
// remove and restart
if set.BlueGreenMode == container.BGModeOn {
ContainerInfoLog(set.Name, "Run arguments changed, doing blue-green redeploy...")
if err = set.BlueGreenDeploy(attach, dryRun, &wg); err != nil {
return err
}
} else {
ContainerInfoLog(set.Name, "Removing (run arguments changed)")
if err = set.RecreateAndRun(attach, dryRun, &wg); err != nil {
return err
}
}
continue
}
//attach if running
if set.State.Running {
ContainerInfoLog(set.Name, "Already running.")
if attach {
ContainerInfoLog(set.Name, "Attaching")
if err := set.Attach(&wg); err != nil {
return err
}
}
continue
}
ContainerInfoLog(set.Name, "Starting...")
if dryRun {
continue
}
//start if stopped
if err = set.Start(attach, &wg); err != nil {
return err
}
continue
}
wg.Wait()
if !dryRun && attach {
<-allDone
}
return nil
}
// Starts stopped containers
func (settings SettingsList) CapitanStart(attach bool, dryRun bool) error {
sort.Sort(settings)
wg := sync.WaitGroup{}
for _, set := range settings {
if set.State.Running {
ContainerInfoLog(set.Name, "Already running")
if attach {
ContainerInfoLog(set.Name, "Attaching...")
if err := set.Attach(&wg); err != nil {
return err
}
}
continue
}
ContainerInfoLog(set.Name, "Starting")
if !dryRun {
if err := set.Start(attach, &wg); err != nil {
return err
}
}
}
wg.Wait()
if !dryRun && attach {
<-allDone
}
return nil
}
// Command to restart all containers
func (settings SettingsList) CapitanRestart(args []string, dryRun bool) error {
sort.Sort(settings)
for _, set := range settings {
ContainerInfoLog(set.Name, "Restarting")
if !dryRun {
if err := set.Restart(args); err != nil {
return err
}
}
}
return nil
}
// Print all container IPs
func (settings SettingsList) CapitanIP() error {
sort.Sort(settings)
for _, set := range settings {
ips := set.IPs()
ContainerInfoLog(set.Name, ips)
}
return nil
}
// Stream all container logs
func (settings SettingsList) CapitanLogs() error {
sort.Sort(settings)
var wg sync.WaitGroup
for _, set := range settings {
var (
ses *sh.Session
err error
)
if ses, err = set.Logs(); err != nil {
Error.Println("Error getting log for " + set.Name + ": " + err.Error())
continue
}
wg.Add(1)
go func() {
ses.Wait()
wg.Done()
}()
}
wg.Wait()
return nil
}
// Stream all container stats
func (settings SettingsList) CapitanStats() error {
var (
args []interface{}
)
sort.Sort(settings)
args = make([]interface{}, len(settings))
for i, set := range settings {
args[i] = set.Name
}
ses := sh.NewSession()
ses.Command("docker", append([]interface{}{"stats"}, args...)...)
ses.Start()
ses.Wait()
return nil
}
// Kill all running containers in project
func (settings SettingsList) CapitanKill(args []string, dryRun bool) error {
sort.Sort(sort.Reverse(settings))
for _, set := range settings {
if !set.State.Running {
ContainerInfoLog(set.Name, "Already stopped")
continue
}
ContainerInfoLog(set.Name, "Killing...")
if !dryRun {
if err := set.Kill(args); err != nil {
return err
}
}
}
return nil
}
// Stops the containers in the project
func (settings SettingsList) CapitanStop(args []string, dryRun bool) error {
sort.Sort(sort.Reverse(settings))
for _, set := range settings {
if !set.State.Running {
ContainerInfoLog(set.Name, "Already stopped.")
continue
}
ContainerInfoLog(set.Name, "Stopping...")
if !dryRun {
if err := set.Stop(args); err != nil {
return err
}
}
}
return nil
}
// Remove all containers in project
func (settings SettingsList) CapitanRm(args []string, dryRun bool) error {
sort.Sort(sort.Reverse(settings))
for _, set := range settings {
if helpers.ContainerExists(set.Name) {
ContainerInfoLog(set.Name, "Removing....")
if dryRun {
continue
}
if err := set.Rm(args); err != nil {
return err
}
} else {
ContainerInfoLog(set.Name, "Container doesn't exist")
}
}
return nil
}
// The build command
func (settings SettingsList) CapitanBuild(dryRun bool) error {
sort.Sort(settings)
for _, set := range settings {
if len(set.Build) == 0 {
continue
}
ContainerInfoLog(set.Name, "Building...")
if !dryRun {
if err := set.BuildImage(); err != nil {
return err
}
}
}
return nil
}
// The build command
func (settings SettingsList) CapitanPull(dryRun bool) error {
sort.Sort(settings)
for _, set := range settings {
if len(set.Build) > 0 || set.Image == "" {
continue
}
ContainerInfoLog(set.Name, "Pulling ", set.Image, "...")
if !dryRun {
if err := helpers.PullImage(set.Image); err != nil {
return err
}
}
}
return nil
}
func (settings SettingsList) CapitanShow() error {
sort.Sort(settings)
for _, set := range settings {
var (
tmpl *template.Template
err error
)
if tmpl, err = template.New("containerStringer").Parse(containerShowTemplate); err != nil {
return err
}
set.RunArguments = set.GetRunArguments()
if err = tmpl.Execute(os.Stdout, set); err != nil {
return err
}
}
return nil
}