FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
container-compose/main.go at main · dgodd/container-compose · GitHub
dgodd
container-compose
Repository navigation
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
container-compose
/
main.go
Copy path
More file actions
More file actions
Latest commit
History
History
History
831 lines (759 loc) · 22.4 KB
Breadcrumbs
container-compose
/
main.go
Copy path
File metadata and controls
831 lines (759 loc) · 22.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
package
main
import
(
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"gopkg.in/yaml.v3"
)
// Version is set at build time via ldflags (e.g. -ldflags="-X main.Version=1.0.0").
// When built without ldflags it reports "dev".
var
Version
=
"dev"
type
Config
struct
{
Name
string
`yaml:"name"`
Services
map
[
string
]
*
Service
`yaml:"services"`
}
type
Service
struct
{
Name
string
`yaml:"-"`
Image
string
`yaml:"image"`
Platform
string
`yaml:"platform"`
Ports
[]
string
`yaml:"ports"`
Workdir
string
`yaml:"working_dir"`
Environment
Environment
`yaml:"environment"`
Command
StringOrStringList
`yaml:"command"`
Entrypoint
string
`yaml:"entrypoint"`
DependsOn
[]
string
`yaml:"depends_on"`
Volumes
[]
string
`yaml:"volumes"`
Profiles
[]
string
`yaml:"profiles"`
Restart
string
`yaml:"restart"`
Deploy
struct
{
Resources
struct
{
Limits
struct
{
Memory
string
`yaml:"memory"`
}
`yaml:"limits"`
}
`yaml:"resources"`
}
`yaml:"deploy"`
}
func
getConfig
(
path
string
) (
*
Config
,
error
) {
// Load the base compose file into a generic map
baseMap
,
err
:=
loadYAMLToMap
(
path
)
if
err
!=
nil
{
return
nil
,
err
}
// Check for an override file and deep-merge if present
override
:=
overridePath
(
path
)
if
override
!=
""
{
overrideMap
,
err
:=
loadYAMLToMap
(
override
)
if
err
==
nil
{
log
.
Printf
(
"Using override file %s
\n
"
,
override
)
baseMap
=
deepMerge
(
baseMap
,
overrideMap
).(
map
[
string
]
interface
{})
}
}
// Decode the merged map into Config
merged
,
err
:=
yaml
.
Marshal
(
baseMap
)
if
err
!=
nil
{
return
nil
,
err
}
var
config
Config
if
err
:=
yaml
.
Unmarshal
(
merged
,
&
config
);
err
!=
nil
{
return
nil
,
err
}
if
config
.
Name
==
""
{
dir
,
err
:=
os
.
Getwd
()
if
err
!=
nil
{
return
nil
,
err
}
dir
=
filepath
.
Base
(
dir
)
config
.
Name
=
dir
}
for
name
,
service
:=
range
config
.
Services
{
service
.
Name
=
config
.
Name
+
"-"
+
name
}
return
&
config
,
nil
}
// loadYAMLToMap decodes a YAML file into a generic map[string]interface{}.
func
loadYAMLToMap
(
path
string
) (
map
[
string
]
interface
{},
error
) {
fh
,
err
:=
os
.
Open
(
path
)
if
err
!=
nil
{
return
nil
,
err
}
defer
fh
.
Close
()
var
m
map
[
string
]
interface
{}
if
err
:=
yaml
.
NewDecoder
(
fh
).
Decode
(
&
m
);
err
!=
nil
{
return
nil
,
err
}
return
m
,
nil
}
// overridePath returns the path to an override file if one exists alongside the base file.
// It checks both known filenames and both .yml / .yaml extensions:
// <base-stem>.override<ext>
// where ext is first the base extension, then the alternate (.yml ↔ .yaml)
// and for the alternate compose stem as well.
// Returns "" when no override file is found.
func
overridePath
(
base
string
)
string
{
ext
:=
filepath
.
Ext
(
base
)
stem
:=
strings
.
TrimSuffix
(
base
,
ext
)
altExt
:=
alternateYAMLExt
(
ext
)
altStem
:=
alternateComposeStem
(
stem
)
candidates
:=
[]
string
{
stem
+
".override"
+
ext
,
stem
+
".override"
+
altExt
,
}
if
altStem
!=
""
{
candidates
=
append
(
candidates
,
altStem
+
".override"
+
ext
,
altStem
+
".override"
+
altExt
,
)
}
for
_
,
c
:=
range
candidates
{
if
_
,
err
:=
os
.
Stat
(
c
);
err
==
nil
{
return
c
}
}
return
""
}
// alternateYAMLExt returns the alternate YAML extension (.yml ↔ .yaml).
func
alternateYAMLExt
(
ext
string
)
string
{
switch
ext
{
case
".yml"
:
return
".yaml"
case
".yaml"
:
return
".yml"
default
:
return
ext
}
}
// alternateComposeStem returns the alternate stem name for a compose file stem.
// e.g. "docker-compose" <-> "compose", otherwise "".
func
alternateComposeStem
(
stem
string
)
string
{
base
:=
filepath
.
Base
(
stem
)
switch
base
{
case
"docker-compose"
:
return
filepath
.
Join
(
filepath
.
Dir
(
stem
),
"compose"
)
case
"compose"
:
return
filepath
.
Join
(
filepath
.
Dir
(
stem
),
"docker-compose"
)
default
:
return
""
}
}
// deepMerge merges src into dst and returns the result.
// Slices are replaced, maps are merged recursively, scalars are overwritten.
func
deepMerge
(
dst
,
src
interface
{})
interface
{} {
switch
src
:=
src
.(
type
) {
case
map
[
string
]
interface
{}:
dstMap
,
ok
:=
dst
.(
map
[
string
]
interface
{})
if
!
ok
{
// dst is not a map; src wins
return
src
}
for
k
,
v
:=
range
src
{
dstMap
[
k
]
=
deepMerge
(
dstMap
[
k
],
v
)
}
return
dstMap
default
:
// Scalars and slices: src wins
return
src
}
}
type
Environment
[]
string
// StringOrStringList accepts a YAML string or array of strings.
type
StringOrStringList
[]
string
func
(
s
*
StringOrStringList
)
UnmarshalYAML
(
value
*
yaml.
Node
)
error
{
var
single
string
if
err
:=
value
.
Decode
(
&
single
);
err
==
nil
{
*
s
=
[]
string
{
single
}
return
nil
}
var
list
[]
string
if
err
:=
value
.
Decode
(
&
list
);
err
==
nil
{
*
s
=
list
return
nil
}
return
fmt
.
Errorf
(
"expected a string or array of strings"
)
}
func
(
e
*
Environment
)
UnmarshalYAML
(
value
*
yaml.
Node
)
error
{
// Try array format: ["KEY=VALUE", ...]
var
arr
[]
string
if
err
:=
value
.
Decode
(
&
arr
);
err
==
nil
{
*
e
=
arr
return
nil
}
// Try hash format: {KEY: VALUE, ...}
var
m
map
[
string
]
interface
{}
if
err
:=
value
.
Decode
(
&
m
);
err
==
nil
{
var
result
[]
string
for
k
,
v
:=
range
m
{
switch
val
:=
v
.(
type
) {
case
nil
:
result
=
append
(
result
,
k
)
default
:
result
=
append
(
result
,
k
+
"="
+
fmt
.
Sprint
(
val
))
}
}
*
e
=
result
return
nil
}
return
fmt
.
Errorf
(
"environment must be an array of KEY=VALUE strings or a mapping"
)
}
type
Network
struct
{
Address
string
`json:"ipv4Address"`
Gateway
string
`json:"ipv4Gateway"`
Hostname
string
`json:"hostname"`
Network
string
`json:"network"`
}
type
InspectConfigImage
struct
{
Reference
string
`json:"reference"`
}
type
InspectConfiguration
struct
{
Image
InspectConfigImage
`json:"image"`
}
type
InspectStatus
struct
{
State
string
`json:"state"`
Networks
[]
Network
`json:"networks"`
}
type
InspectData
struct
{
Status
InspectStatus
`json:"status"`
Configuration
InspectConfiguration
`json:"configuration"`
}
func
(
service
*
Service
)
Inspect
() (
*
InspectData
,
error
) {
cmd
:=
exec
.
Command
(
"container"
,
"inspect"
,
service
.
Name
)
out
,
err
:=
cmd
.
Output
()
if
err
!=
nil
{
if
exitErr
,
ok
:=
err
.(
*
exec.
ExitError
);
ok
{
return
nil
,
fmt
.
Errorf
(
"%s"
,
strings
.
TrimSpace
(
string
(
exitErr
.
Stderr
)))
}
return
nil
,
err
}
var
inspectData
[]
InspectData
if
err
:=
json
.
Unmarshal
(
out
,
&
inspectData
);
err
!=
nil
{
return
nil
,
err
}
if
len
(
inspectData
)
==
0
{
return
nil
,
fmt
.
Errorf
(
"no data found for service %s"
,
service
.
Name
)
}
return
&
inspectData
[
0
],
nil
}
func
(
service
*
Service
)
Start
(
detach
bool
,
runArgs
[]
string
)
error
{
// TODO: better name (eg. prefix name with service)
args
:=
[]
string
{
"run"
,
"--name"
,
service
.
Name
,
"--rm"
,
"--dns-domain"
,
"test"
}
if
detach
{
args
=
append
(
args
,
"--detach"
)
}
if
service
.
Platform
!=
""
{
arch
:=
strings
.
TrimPrefix
(
service
.
Platform
,
"linux/"
)
args
=
append
(
args
,
"--arch"
,
arch
)
}
if
service
.
Workdir
!=
""
{
args
=
append
(
args
,
"--workdir"
,
service
.
Workdir
)
}
if
service
.
Deploy
.
Resources
.
Limits
.
Memory
!=
""
{
args
=
append
(
args
,
"--memory"
,
service
.
Deploy
.
Resources
.
Limits
.
Memory
)
}
for
_
,
port
:=
range
service
.
Ports
{
args
=
append
(
args
,
"-p"
,
port
)
}
for
_
,
env
:=
range
service
.
Environment
{
args
=
append
(
args
,
"--env"
,
env
)
}
for
_
,
volume
:=
range
service
.
Volumes
{
if
strings
.
HasPrefix
(
volume
,
"./"
) {
volume
=
strings
.
Replace
(
volume
,
"./"
,
""
,
1
)
}
if
!
strings
.
HasPrefix
(
volume
,
"/"
) {
path
,
err
:=
os
.
Getwd
()
if
err
!=
nil
{
return
err
}
volume
=
filepath
.
Join
(
path
,
volume
)
}
args
=
append
(
args
,
"--volume"
,
volume
)
}
if
service
.
Entrypoint
!=
""
{
args
=
append
(
args
,
"--entrypoint"
,
service
.
Entrypoint
)
}
args
=
append
(
args
,
service
.
Image
)
args
=
append
(
args
,
service
.
Command
...
)
args
=
append
(
args
,
runArgs
...
)
// fmt.Println("container", strings.Join(args, " "))
return
runContainerWithAuthRetry
(
args
,
service
.
Image
)
}
// runContainerCmd runs `container <args...>`, streaming stdout/stderr to the
// user while also capturing stderr so callers can inspect it for errors.
func
runContainerCmd
(
args
[]
string
) (
stderrOutput
string
,
err
error
) {
cmd
:=
exec
.
Command
(
"container"
,
args
...
)
var
stderrBuf
bytes.
Buffer
cmd
.
Stdout
=
os
.
Stdout
cmd
.
Stderr
=
io
.
MultiWriter
(
os
.
Stderr
,
&
stderrBuf
)
err
=
cmd
.
Run
()
return
stderrBuf
.
String
(),
err
}
// runContainerWithAuthRetry runs `container <args...>` and, if it fails with a
// registry authentication error, attempts to log in to the image's registry
// and retries once.
func
runContainerWithAuthRetry
(
args
[]
string
,
image
string
)
error
{
stderrOut
,
err
:=
runContainerCmd
(
args
)
if
err
==
nil
||
!
isAuthError
(
stderrOut
) {
return
err
}
host
:=
registryHost
(
image
)
if
host
==
""
{
return
err
}
log
.
Printf
(
"Authentication required for registry %s, attempting login...
\n
"
,
host
)
if
loginErr
:=
loginToRegistry
(
host
);
loginErr
!=
nil
{
return
fmt
.
Errorf
(
"%s (auto-login failed: %v)"
,
strings
.
TrimSpace
(
stderrOut
),
loginErr
)
}
_
,
err
=
runContainerCmd
(
args
)
return
err
}
// isAuthError reports whether container output looks like a registry
// authentication failure (e.g. a 401 from Docker Hub or ECR).
func
isAuthError
(
output
string
)
bool
{
lower
:=
strings
.
ToLower
(
output
)
return
strings
.
Contains
(
output
,
"401"
)
||
strings
.
Contains
(
lower
,
"unauthorized"
)
||
strings
.
Contains
(
lower
,
"access denied"
)
||
strings
.
Contains
(
lower
,
"no credentials found"
)
}
// registryHost extracts the registry hostname from an image reference, or
// returns "" if the image uses the default registry (Docker Hub), which
// needs no login.
func
registryHost
(
image
string
)
string
{
ref
:=
image
if
idx
:=
strings
.
Index
(
ref
,
"@"
);
idx
!=
-
1
{
ref
=
ref
[:
idx
]
}
parts
:=
strings
.
SplitN
(
ref
,
"/"
,
2
)
if
len
(
parts
)
<
2
{
return
""
}
first
:=
parts
[
0
]
if
strings
.
Contains
(
first
,
"."
)
||
strings
.
Contains
(
first
,
":"
)
||
first
==
"localhost"
{
return
first
}
return
""
}
var
ecrHostPattern
=
regexp
.
MustCompile
(
`^\d+\.dkr\.ecr\.([a-z0-9-]+)\.amazonaws\.com$`
)
// loginToRegistry logs the container runtime in to the given registry host.
// For AWS ECR hosts, it uses the AWS CLI (via AWS_PROFILE, or a prompt if
// unset) to mint a short-lived password. For any other registry, it uses
// CONTAINER_REGISTRY_USERNAME/CONTAINER_REGISTRY_PASSWORD, or prompts for
// them if unset.
func
loginToRegistry
(
host
string
)
error
{
if
m
:=
ecrHostPattern
.
FindStringSubmatch
(
host
);
m
!=
nil
{
return
loginToECR
(
host
,
m
[
1
])
}
return
loginGeneric
(
host
)
}
func
loginToECR
(
host
,
region
string
)
error
{
profile
:=
os
.
Getenv
(
"AWS_PROFILE"
)
if
profile
==
""
{
profile
=
readLine
(
fmt
.
Sprintf
(
"AWS profile for %s (blank for default credentials): "
,
host
))
}
args
:=
[]
string
{
"ecr"
,
"get-login-password"
,
"--region"
,
region
}
if
profile
!=
""
{
args
=
append
(
args
,
"--profile"
,
profile
)
}
cmd
:=
exec
.
Command
(
"aws"
,
args
...
)
var
out
,
stderr
bytes.
Buffer
cmd
.
Stdout
=
&
out
cmd
.
Stderr
=
&
stderr
if
err
:=
cmd
.
Run
();
err
!=
nil
{
return
fmt
.
Errorf
(
"aws ecr get-login-password failed: %s"
,
strings
.
TrimSpace
(
stderr
.
String
()))
}
return
containerRegistryLogin
(
host
,
"AWS"
,
strings
.
TrimSpace
(
out
.
String
()))
}
func
loginGeneric
(
host
string
)
error
{
username
:=
os
.
Getenv
(
"CONTAINER_REGISTRY_USERNAME"
)
if
username
==
""
{
username
=
readLine
(
fmt
.
Sprintf
(
"Username for %s: "
,
host
))
}
password
:=
os
.
Getenv
(
"CONTAINER_REGISTRY_PASSWORD"
)
if
password
==
""
{
password
=
readSecret
(
fmt
.
Sprintf
(
"Password for %s: "
,
host
))
}
return
containerRegistryLogin
(
host
,
username
,
password
)
}
func
containerRegistryLogin
(
host
,
username
,
password
string
)
error
{
cmd
:=
exec
.
Command
(
"container"
,
"registry"
,
"login"
,
host
,
"--username"
,
username
,
"--password-stdin"
)
cmd
.
Stdin
=
strings
.
NewReader
(
password
)
var
stderr
bytes.
Buffer
cmd
.
Stderr
=
&
stderr
if
err
:=
cmd
.
Run
();
err
!=
nil
{
return
fmt
.
Errorf
(
"container registry login failed: %s"
,
strings
.
TrimSpace
(
stderr
.
String
()))
}
log
.
Printf
(
"Logged in to registry %s
\n
"
,
host
)
return
nil
}
// readLine prompts on stderr and reads a line of input from stdin.
func
readLine
(
prompt
string
)
string
{
fmt
.
Fprint
(
os
.
Stderr
,
prompt
)
line
,
_
:=
bufio
.
NewReader
(
os
.
Stdin
).
ReadString
(
'\n'
)
return
strings
.
TrimSpace
(
line
)
}
// readSecret prompts on stderr and reads a line of input from stdin with
// terminal echo disabled where possible.
func
readSecret
(
prompt
string
)
string
{
fmt
.
Fprint
(
os
.
Stderr
,
prompt
)
disable
:=
exec
.
Command
(
"stty"
,
"-echo"
)
disable
.
Stdin
=
os
.
Stdin
echoDisabled
:=
disable
.
Run
()
==
nil
if
echoDisabled
{
defer
func
() {
restore
:=
exec
.
Command
(
"stty"
,
"echo"
)
restore
.
Stdin
=
os
.
Stdin
restore
.
Run
()
fmt
.
Fprintln
(
os
.
Stderr
)
}()
}
line
,
_
:=
bufio
.
NewReader
(
os
.
Stdin
).
ReadString
(
'\n'
)
return
strings
.
TrimSpace
(
line
)
}
func
(
service
*
Service
)
Stop
()
error
{
return
exec
.
Command
(
"container"
,
"stop"
,
service
.
Name
).
Run
()
}
func
(
service
*
Service
)
StartExisting
()
error
{
log
.
Printf
(
"Starting existing container %s
\n
"
,
service
.
Name
)
cmd
:=
exec
.
Command
(
"container"
,
"start"
,
service
.
Name
)
cmd
.
Stdout
=
os
.
Stdout
cmd
.
Stderr
=
os
.
Stderr
return
cmd
.
Run
()
}
func
(
service
*
Service
)
Logs
(
follow
bool
,
tail
int
)
error
{
args
:=
[]
string
{
"logs"
}
if
follow
{
args
=
append
(
args
,
"-f"
)
}
if
tail
>
0
{
args
=
append
(
args
,
"-n"
,
fmt
.
Sprintf
(
"%d"
,
tail
))
}
args
=
append
(
args
,
service
.
Name
)
cmd
:=
exec
.
Command
(
"container"
,
args
...
)
cmd
.
Stdout
=
os
.
Stdout
cmd
.
Stderr
=
os
.
Stderr
return
cmd
.
Run
()
}
// imageExists checks whether the given image reference is available in the container runtime.
func
imageExists
(
image
string
)
bool
{
return
exec
.
Command
(
"container"
,
"image"
,
"inspect"
,
image
).
Run
()
==
nil
}
func
imageTagsDiffer
(
configured
,
reference
string
)
bool
{
// Extract tag from configured image (default "latest")
cfgTag
:=
"latest"
if
idx
:=
strings
.
LastIndex
(
configured
,
":"
);
idx
!=
-
1
{
cfgTag
=
configured
[
idx
+
1
:]
}
// Extract tag from reference
refTag
:=
"latest"
if
idx
:=
strings
.
LastIndex
(
reference
,
":"
);
idx
!=
-
1
{
refTag
=
reference
[
idx
+
1
:]
}
return
cfgTag
!=
refTag
}
func
sortedServices
(
config
*
Config
) []
*
Service
{
// Map names to services for lookup
byName
:=
make
(
map
[
string
]
*
Service
)
for
_
,
svc
:=
range
config
.
Services
{
byName
[
svc
.
Name
]
=
svc
}
// Topological sort using Kahn's algorithm
inDegree
:=
make
(
map
[
string
]
int
)
dependents
:=
make
(
map
[
string
][]
string
)
// service -> services that depend on it
for
_
,
svc
:=
range
config
.
Services
{
if
_
,
ok
:=
inDegree
[
svc
.
Name
];
!
ok
{
inDegree
[
svc
.
Name
]
=
0
}
for
_
,
dep
:=
range
svc
.
DependsOn
{
inDegree
[
svc
.
Name
]
++
dependents
[
dep
]
=
append
(
dependents
[
dep
],
svc
.
Name
)
}
}
var
queue
[]
string
for
name
,
degree
:=
range
inDegree
{
if
degree
==
0
{
queue
=
append
(
queue
,
name
)
}
}
var
sorted
[]
*
Service
for
len
(
queue
)
>
0
{
name
:=
queue
[
0
]
queue
=
queue
[
1
:]
sorted
=
append
(
sorted
,
byName
[
name
])
for
_
,
dep
:=
range
dependents
[
name
] {
inDegree
[
dep
]
--
if
inDegree
[
dep
]
==
0
{
queue
=
append
(
queue
,
dep
)
}
}
}
// Append any services not in the sort (e.g. circular deps) at the end
for
_
,
svc
:=
range
config
.
Services
{
found
:=
false
for
_
,
s
:=
range
sorted
{
if
s
.
Name
==
svc
.
Name
{
found
=
true
break
}
}
if
!
found
{
sorted
=
append
(
sorted
,
svc
)
}
}
return
sorted
}
// servicesByProfile filters the sorted service list to only those
// matching at least one active profile. Services with no profiles
// are always included.
func
servicesByProfile
(
config
*
Config
,
activeProfiles
[]
string
) []
*
Service
{
all
:=
sortedServices
(
config
)
var
filtered
[]
*
Service
for
_
,
svc
:=
range
all
{
if
profileEnabled
(
svc
.
Profiles
,
activeProfiles
) {
filtered
=
append
(
filtered
,
svc
)
}
}
return
filtered
}
// profileEnabled returns true if the service should be included.
// A service with no profiles is always included.
// Otherwise, at least one of its profiles must be in the active set.
func
profileEnabled
(
serviceProfiles
,
activeProfiles
[]
string
)
bool
{
if
len
(
serviceProfiles
)
==
0
{
return
true
}
for
_
,
sp
:=
range
serviceProfiles
{
for
_
,
ap
:=
range
activeProfiles
{
if
sp
==
ap
{
return
true
}
}
}
return
false
}
func
printUsage
() {
fmt
.
Print
(
`Usage: container-compose [OPTIONS] <COMMAND> [ARGS]
A lightweight Docker Compose alternative for Apple's container runtime.
Options:
-f, --file <file> Path to docker-compose.yml (default: docker-compose.yml)
--profile <name> Activate a profile (can be specified multiple times)
-h, --help Show this help message and exit
-v, --version Show version information and exit
Commands:
start [services...] Start services (creates containers if needed).
Defaults to all services, filtered by active profiles.
stop Stop all services
status, ps, ls Show status of all services
logs [options] Print or stream logs from services
run <service> Run a single service command (attached)
login [services...] Log in to the registries used by services' images
Run 'container-compose <command> --help' for more information on a command.
`
+
"
\n
"
)
}
func
main
() {
composeFile
:=
"docker-compose.yml"
var
activeProfiles
[]
string
// Read COMPOSE_PROFILES from environment (comma-separated)
if
envProfiles
:=
os
.
Getenv
(
"COMPOSE_PROFILES"
);
envProfiles
!=
""
{
for
_
,
p
:=
range
strings
.
Split
(
envProfiles
,
","
) {
p
=
strings
.
TrimSpace
(
p
)
if
p
!=
""
{
activeProfiles
=
append
(
activeProfiles
,
p
)
}
}
}
args
:=
os
.
Args
[
1
:]
for
len
(
args
)
>
0
{
switch
args
[
0
] {
case
"-f"
,
"--file"
:
if
len
(
args
)
<
2
{
fmt
.
Fprintln
(
os
.
Stderr
,
"Usage: container-compose [-f <file>] <command> [args]"
)
os
.
Exit
(
1
)
}
composeFile
=
args
[
1
]
args
=
args
[
2
:]
case
"--profile"
:
if
len
(
args
)
<
2
{
fmt
.
Fprintln
(
os
.
Stderr
,
"Usage: container-compose --profile <name>"
)
os
.
Exit
(
1
)
}
activeProfiles
=
append
(
activeProfiles
,
args
[
1
])
args
=
args
[
2
:]
case
"-v"
,
"--version"
:
fmt
.
Printf
(
"container-compose version %s
\n
"
,
Version
)
os
.
Exit
(
0
)
case
"-h"
,
"--help"
:
printUsage
()
os
.
Exit
(
0
)
default
:
goto
parseCommand
}
}
parseCommand:
if
len
(
args
)
<
1
{
printUsage
()
os
.
Exit
(
1
)
}
config
,
err
:=
getConfig
(
composeFile
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
// run requires a service name; all other commands accept optional service names.
if
args
[
0
]
==
"run"
&&
len
(
args
)
<
2
{
fmt
.
Fprintln
(
os
.
Stderr
,
"Usage: container-compose run <service> [args]"
)
os
.
Exit
(
1
)
}
switch
args
[
0
] {
case
"start"
:
var
selectedServices
[]
*
Service
if
len
(
args
)
>
1
{
// User specified service names; only start those
for
_
,
name
:=
range
args
[
1
:] {
svc
,
ok
:=
config
.
Services
[
name
]
if
!
ok
{
log
.
Fatalf
(
"Unknown service: %s"
,
name
)
}
selectedServices
=
append
(
selectedServices
,
svc
)
}
}
else
{
selectedServices
=
servicesByProfile
(
config
,
activeProfiles
)
}
var
alerts
[]
string
for
_
,
service
:=
range
selectedServices
{
name
:=
service
.
Name
inspectData
,
err
:=
service
.
Inspect
()
if
err
==
nil
{
// Container exists
if
inspectData
.
Configuration
.
Image
.
Reference
!=
""
{
if
imageTagsDiffer
(
service
.
Image
,
inspectData
.
Configuration
.
Image
.
Reference
) {
alert
:=
fmt
.
Sprintf
(
"WARNING: Service %s is using image %s but docker-compose.yml specifies %s"
,
name
,
inspectData
.
Configuration
.
Image
.
Reference
,
service
.
Image
)
log
.
Println
(
alert
)
alerts
=
append
(
alerts
,
alert
)
}
}
if
inspectData
.
Status
.
State
==
"running"
{
log
.
Printf
(
"Service %s is already running
\n
"
,
name
)
continue
}
if
err
:=
service
.
StartExisting
();
err
!=
nil
{
log
.
Println
(
"ERROR:"
,
err
)
}
}
else
{
// Container doesn't exist, create a new one
log
.
Printf
(
"Starting service %s
\n
"
,
service
.
Name
)
if
err
:=
service
.
Start
(
true
,
nil
);
err
!=
nil
{
log
.
Println
(
"ERROR:"
,
err
)
}
}
}
if
len
(
alerts
)
>
0
{
log
.
Println
(
"--- Image version alerts ---"
)
for
_
,
alert
:=
range
alerts
{
log
.
Println
(
alert
)
}
}
case
"status"
,
"ps"
,
"ls"
:
var
statusErrors
[]
string
for
_
,
service
:=
range
servicesByProfile
(
config
,
activeProfiles
) {
inspectData
,
err
:=
service
.
Inspect
()
if
err
!=
nil
{
if
imageExists
(
service
.
Image
) {
statusErrors
=
append
(
statusErrors
,
fmt
.
Sprintf
(
"Service %s: %s (image %s is available)"
,
service
.
Name
,
err
,
service
.
Image
))
}
else
{
statusErrors
=
append
(
statusErrors
,
fmt
.
Sprintf
(
"Service %s: %s (image %s not pulled)"
,
service
.
Name
,
err
,
service
.
Image
))
}
}
else
{
log
.
Printf
(
"Service %s: %s
\n
"
,
service
.
Name
,
inspectData
.
Status
.
State
)
}
}
if
len
(
statusErrors
)
>
0
{
log
.
Println
(
"--- Errors ---"
)
for
_
,
errMsg
:=
range
statusErrors
{
log
.
Println
(
errMsg
)
}
}
case
"run"
:
for
name
,
service
:=
range
config
.
Services
{
if
name
==
os
.
Args
[
2
] {
log
.
Printf
(
"Running service %s
\n
"
,
service
.
Name
)
if
err
:=
service
.
Start
(
false
,
os
.
Args
[
3
:]);
err
!=
nil
{
log
.
Fatal
(
err
)
}
log
.
Printf
(
"Service %s started
\n
"
,
name
)
}
}
case
"stop"
:
var
stopErrors
[]
string
// Stop in reverse dependency order (dependents first, then dependencies)
sorted
:=
servicesByProfile
(
config
,
activeProfiles
)
for
i
:=
len
(
sorted
)
-
1
;
i
>=
0
;
i
--
{
service
:=
sorted
[
i
]
log
.
Printf
(
"Stopping service %s
\n
"
,
service
.
Name
)
err
:=
service
.
Stop
()
if
err
!=
nil
{
stopErrors
=
append
(
stopErrors
,
fmt
.
Sprintf
(
"Service %s: %s"
,
service
.
Name
,
err
))
}
}
if
len
(
stopErrors
)
>
0
{
log
.
Println
(
"--- Errors ---"
)
for
_
,
errMsg
:=
range
stopErrors
{
log
.
Println
(
errMsg
)
}
}
case
"login"
:
var
selectedServices
[]
*
Service
if
len
(
args
)
>
1
{
for
_
,
name
:=
range
args
[
1
:] {
svc
,
ok
:=
config
.
Services
[
name
]
if
!
ok
{
log
.
Fatalf
(
"Unknown service: %s"
,
name
)
}
selectedServices
=
append
(
selectedServices
,
svc
)
}
}
else
{
selectedServices
=
servicesByProfile
(
config
,
activeProfiles
)
}
seenHosts
:=
make
(
map
[
string
]
bool
)
for
_
,
service
:=
range
selectedServices
{
host
:=
registryHost
(
service
.
Image
)
if
host
==
""
||
seenHosts
[
host
] {
continue
}
seenHosts
[
host
]
=
true
if
err
:=
loginToRegistry
(
host
);
err
!=
nil
{
log
.
Println
(
"ERROR:"
,
err
)
}
}
case
"logs"
:
follow
:=
false
tail
:=
0
for
i
:=
1
;
i
<
len
(
args
);
i
++
{
switch
args
[
i
] {
case
"-f"
,
"--follow"
:
follow
=
true
case
"-n"
:
if
i
+
1
<
len
(
args
) {
fmt
.
Sscanf
(
args
[
i
+
1
],
"%d"
,
&
tail
)
i
++
}
default
:
log
.
Fatalf
(
"Usage: container-compose logs [-f] [-n N]"
)
}
}
for
_
,
service
:=
range
servicesByProfile
(
config
,
activeProfiles
) {
err
:=
service
.
Logs
(
follow
,
tail
)
if
err
!=
nil
{
log
.
Println
(
"ERROR:"
,
err
)
}
}
default
:
log
.
Fatalf
(
"Usage: %s <start|status|ps|ls|run|stop|logs>"
,
os
.
Args
[
0
])
}
}
Back
|
FazBrowse Home
|
New Git URL