This repository has been archived by the owner on Mar 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
compose-ref.go
368 lines (329 loc) · 8.68 KB
/
compose-ref.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
/*
Copyright 2020 The Compose Specification Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
"github.com/compose-spec/compose-go/loader"
compose "github.com/compose-spec/compose-go/types"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/client"
"github.com/docker/go-units"
commandLine "github.com/urfave/cli/v2"
"github.com/compose-spec/compose-ref/internal"
)
const banner = `
.---.
( )
)@ @(
//|||\\
`
func main() {
var file string
var project string
fmt.Print(banner)
app := &commandLine.App{
Name: "compose-ref",
Usage: "Reference Compose Specification implementation",
Flags: []commandLine.Flag{
&commandLine.StringFlag{
Name: "file",
Aliases: []string{"f"},
Value: "compose.yaml",
Usage: "Load Compose file `FILE`",
Destination: &file,
},
&commandLine.StringFlag{
Name: "project-name",
Aliases: []string{"n"},
Value: "",
Usage: "Set project name `NAME` (default: Compose file's folder name)",
Destination: &project,
},
},
Commands: []*commandLine.Command{
{
Name: "up",
Usage: "Create and start application services",
Action: func(c *commandLine.Context) error {
config, err := load(file)
if err != nil {
return err
}
project, err = getProject(project, file)
if err != nil {
return err
}
return doUp(project, config)
},
},
{
Name: "down",
Usage: "Stop services created by `up`",
Action: func(c *commandLine.Context) error {
config, err := load(file)
if err != nil {
return err
}
project, err = getProject(project, file)
if err != nil {
return err
}
return doDown(project, config)
},
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func getProject(project string, file string) (string, error) {
if project == "" {
abs, err := filepath.Abs(file)
if err != nil {
return "", err
}
project = filepath.Base(filepath.Dir(abs))
}
return project, nil
}
func getClient() (*client.Client, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return nil, err
}
cli.NegotiateAPIVersion(context.Background())
return cli, nil
}
func doUp(project string, config *compose.Config) error {
cli, err := getClient()
if err != nil {
return err
}
prjDir, err := filepath.Abs(filepath.Dir(config.Filename))
if err != nil {
return err
}
networks, err := internal.GetNetworksFromConfig(cli, project, config)
if err != nil {
return err
}
err = internal.GetVolumesFromConfig(cli, project, config)
if err != nil {
return err
}
err = internal.GetConfigsFromConfig(prjDir, config)
if err != nil {
return err
}
err = internal.GetSecretsFromConfig(prjDir, config)
if err != nil {
return err
}
observedState, err := internal.CollectContainers(cli, project)
if err != nil {
return err
}
err = config.WithServices(nil, func(service compose.ServiceConfig) error {
containers := observedState[service.Name]
delete(observedState, service.Name)
// If no container exists for the service yet, then we just need to create them
if len(containers) == 0 {
return createService(cli, project, prjDir, service, networks)
}
// We compare container config stored as plain yaml in a label with expected one
b, err := yaml.Marshal(service)
if err != nil {
return err
}
expected := string(b)
diverged := false
for _, cntr := range containers {
config := cntr.Labels[internal.LabelConfig]
if config != expected {
diverged = true
break
}
}
if !diverged {
// Existing containers are up-to-date with the Compose file configuration, so just keep them running
return nil
}
// Some containers exist for service but with an obsolete configuration. We need to replace them
err = internal.RemoveContainers(cli, containers)
if err != nil {
return err
}
return createService(cli, project, prjDir, service, networks)
})
if err != nil {
return err
}
// Remaining containers in observed state don't have a matching service in Compose file => orphaned to be removed
for _, orphaned := range observedState {
err = internal.RemoveContainers(cli, orphaned)
if err != nil {
return err
}
}
return nil
}
func createService(cli *client.Client, project string, prjDir string, s compose.ServiceConfig, networks map[string]string) error {
ctx := context.Background()
var shmSize int64
if s.ShmSize != "" {
v, err := units.RAMInBytes(s.ShmSize)
if err != nil {
return err
}
shmSize = v
}
labels := map[string]string{}
for k, v := range s.Labels {
labels[k] = v
}
labels[internal.LabelProject] = project
labels[internal.LabelService] = s.Name
b, err := yaml.Marshal(s)
if err != nil {
return err
}
labels[internal.LabelConfig] = string(b)
fmt.Printf("Creating container for service %s ... ", s.Name)
networkMode := internal.NetworkMode(project, s, networks)
mounts, err := internal.CreateContainerMounts(s, prjDir)
if err != nil {
return err
}
configMounts, err := internal.CreateContainerConfigMounts(s, prjDir)
if err != nil {
return err
}
secretsMounts, err := internal.CreateContainerSecretMounts(s, prjDir)
if err != nil {
return err
}
mounts = append(mounts, configMounts...)
mounts = append(mounts, secretsMounts...)
create, err := cli.ContainerCreate(ctx,
&container.Config{
Hostname: s.Hostname,
Domainname: s.DomainName,
User: s.User,
Tty: s.Tty,
OpenStdin: s.StdinOpen,
Cmd: strslice.StrSlice(s.Command),
Image: s.Image,
Labels: labels,
WorkingDir: s.WorkingDir,
Entrypoint: strslice.StrSlice(s.Entrypoint),
NetworkDisabled: s.NetworkMode == "disabled",
MacAddress: s.MacAddress,
StopSignal: s.StopSignal,
ExposedPorts: internal.ExposedPorts(s.Ports),
},
&container.HostConfig{
NetworkMode: networkMode,
RestartPolicy: container.RestartPolicy{Name: s.Restart},
CapAdd: s.CapAdd,
CapDrop: s.CapDrop,
DNS: s.DNS,
DNSSearch: s.DNSSearch,
ExtraHosts: s.ExtraHosts,
IpcMode: container.IpcMode(s.Ipc),
Links: s.Links,
Mounts: mounts,
PidMode: container.PidMode(s.Pid),
Privileged: s.Privileged,
ReadonlyRootfs: s.ReadOnly,
SecurityOpt: s.SecurityOpt,
UsernsMode: container.UsernsMode(s.UserNSMode),
ShmSize: shmSize,
Sysctls: s.Sysctls,
Isolation: container.Isolation(s.Isolation),
Init: s.Init,
PortBindings: internal.BuildContainerPortBindingsOptions(s),
},
internal.BuildDefaultNetworkConfig(s, networkMode),
"")
if err != nil {
return err
}
err = internal.ConnectContainerToNetworks(ctx, cli, s, create.ID, networks)
if err != nil {
return err
}
err = cli.ContainerStart(ctx, create.ID, types.ContainerStartOptions{})
if err != nil {
return err
}
fmt.Println(create.ID)
return nil
}
func doDown(project string, config *compose.Config) error {
cli, err := getClient()
if err != nil {
return nil
}
err = removeServices(cli, project)
if err != nil {
return err
}
err = internal.RemoveVolumes(cli, project)
if err != nil {
return err
}
err = internal.RemoveNetworks(cli, project)
if err != nil {
return err
}
return nil
}
func removeServices(cli *client.Client, project string) error {
containers, err := internal.CollectContainers(cli, project)
if err != nil {
return err
}
for _, replicaList := range containers {
err = internal.RemoveContainers(cli, replicaList)
if err != nil {
return err
}
}
return nil
}
func load(file string) (*compose.Config, error) {
b, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
config, err := loader.ParseYAML(b)
if err != nil {
return nil, err
}
var files []compose.ConfigFile
files = append(files, compose.ConfigFile{Filename: file, Config: config})
return loader.Load(compose.ConfigDetails{
WorkingDir: ".",
ConfigFiles: files,
})
}