-
Notifications
You must be signed in to change notification settings - Fork 4
/
nix.go
340 lines (298 loc) · 8.45 KB
/
nix.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
package main
import (
"fmt"
"io"
"strings"
"text/template"
)
// Compose V2 uses "-" for container names: https://docs.docker.com/compose/migrate/#service-container-names
//
// Volumes and networks still use "_", but we'll ignore that here: https://github.com/docker/compose/issues/9618
const DefaultProjectSeparator = "-"
type ContainerRuntime int
const (
ContainerRuntimeInvalid ContainerRuntime = iota
ContainerRuntimeDocker
ContainerRuntimePodman
)
func (c ContainerRuntime) String() string {
switch c {
case ContainerRuntimeDocker:
return "docker"
case ContainerRuntimePodman:
return "podman"
case ContainerRuntimeInvalid:
return "invalid-container-runtime"
default:
panic("Unreachable")
}
}
type Project struct {
Name string
separator string
}
func NewProject(name string) *Project {
if name == "" {
return nil
}
return &Project{Name: name, separator: DefaultProjectSeparator}
}
func (p *Project) With(name string) string {
if p == nil {
return name
}
return fmt.Sprintf("%s%s%s", p.Name, p.separator, name)
}
type IpamConfig struct {
Subnet string
IPRange string
Gateway string
AuxAddresses []string
}
type NixNetwork struct {
Runtime ContainerRuntime
Name string
OriginalName string
Driver string
DriverOpts map[string]string
External bool
Labels map[string]string
IpamDriver string
IpamConfigs []IpamConfig
ExtraOptions []string
}
func (n *NixNetwork) Unit() string {
return fmt.Sprintf("%s-network-%s.service", n.Runtime, n.Name)
}
func (n *NixNetwork) Command() string {
cmd := fmt.Sprintf("%[1]s network inspect %[2]s || %[1]s network create %[2]s", n.Runtime, n.Name)
if n.Driver != "" {
cmd += fmt.Sprintf(" --driver=%s", n.Driver)
}
if len(n.DriverOpts) > 0 {
driverOpts := mapToRepeatedKeyValFlag("--opt", n.DriverOpts)
cmd += " " + strings.Join(driverOpts, " ")
}
if n.IpamDriver != "" {
cmd += fmt.Sprintf(" --ipam-driver=%s", n.IpamDriver)
}
for _, cfg := range n.IpamConfigs {
if cfg.Subnet != "" {
cmd += fmt.Sprintf(" --subnet=%s", cfg.Subnet)
}
if cfg.IPRange != "" {
cmd += fmt.Sprintf(" --ip-range=%s", cfg.IPRange)
}
if cfg.Gateway != "" {
cmd += fmt.Sprintf(" --gateway=%s", cfg.Gateway)
}
for _, addr := range cfg.AuxAddresses {
cmd += fmt.Sprintf(` --aux-address="%s"`, addr)
}
}
if len(n.ExtraOptions) > 0 {
cmd += " " + strings.Join(n.ExtraOptions, " ")
}
if len(n.Labels) > 0 {
labels := mapToRepeatedKeyValFlag("--label", n.Labels)
cmd += " " + strings.Join(labels, " ")
}
return cmd
}
type NixVolume struct {
Runtime ContainerRuntime
Name string
Driver string
DriverOpts map[string]string
External bool
Labels map[string]string
RemoveOnStop bool
RequiresMountsFor []string
}
func (v *NixVolume) Path() string {
return v.DriverOpts["device"]
}
func (v *NixVolume) Unit() string {
return fmt.Sprintf("%s-volume-%s.service", v.Runtime, v.Name)
}
func (v *NixVolume) Command() string {
cmd := fmt.Sprintf("%[1]s volume inspect %[2]s || %[1]s volume create %[2]s", v.Runtime, v.Name)
if v.Driver != "" {
cmd += fmt.Sprintf(" --driver=%s", v.Driver)
}
if len(v.DriverOpts) > 0 {
driverOpts := mapToRepeatedKeyValFlag("--opt", v.DriverOpts)
cmd += " " + strings.Join(driverOpts, " ")
}
if len(v.Labels) > 0 {
labels := mapToRepeatedKeyValFlag("--label", v.Labels)
cmd += " " + strings.Join(labels, " ")
}
return cmd
}
// NixContainerSystemdConfig configures the container's systemd config.
// In particular, this allows control of the container restart policy through systemd
// service and unit configs.
//
// Each key-value pair in a map represents a systemd key and its value (e.g., Restart=always).
// Users can provide custom config keys by setting the compose2nix.systemd.* label on the service.
type NixContainerSystemdConfig struct {
Service ServiceConfig
Unit UnitConfig
// NixOS treats these differently, probably to fix the rename issue in
// earlier systemd versions.
// See: https://unix.stackexchange.com/a/464098
StartLimitBurst *int
}
func NewNixContainerSystemdConfig() *NixContainerSystemdConfig {
return &NixContainerSystemdConfig{
Service: ServiceConfig{},
Unit: UnitConfig{},
}
}
// https://search.nixos.org/options?channel=unstable&from=0&size=50&sort=relevance&type=packages&query=oci-container
type NixContainer struct {
Runtime ContainerRuntime
Name string
Image string
Environment map[string]string
EnvFiles []string
Volumes map[string]string
Ports []string
Labels map[string]string
Networks []string
DependsOn []string
LogDriver string
ExtraOptions []string
SystemdConfig *NixContainerSystemdConfig
User string
Command []string
AutoStart bool
}
func (c *NixContainer) Unit() string {
return fmt.Sprintf("%s-%s.service", c.Runtime, c.Name)
}
// https://docs.docker.com/reference/compose-file/services/#pull_policy
// https://docs.podman.io/en/latest/markdown/podman-build.1.html#pull-policy
type ServicePullPolicy int
const (
ServicePullPolicyInvalid ServicePullPolicy = iota
ServicePullPolicyAlways
ServicePullPolicyNever
ServicePullPolicyMissing
ServicePullPolicyBuild
ServicePullPolicyUnset
)
func NewServicePullPolicy(s string) ServicePullPolicy {
switch strings.TrimSpace(s) {
case "always":
return ServicePullPolicyAlways
case "never":
return ServicePullPolicyNever
case "missing", "if_not_present":
return ServicePullPolicyMissing
case "build":
return ServicePullPolicyBuild
default:
return ServicePullPolicyUnset
}
}
// https://docs.docker.com/reference/compose-file/build/
// https://docs.docker.com/reference/cli/docker/buildx/build/
type NixBuild struct {
Runtime ContainerRuntime
Context string
PullPolicy ServicePullPolicy
IsGitRepo bool
Args map[string]*string
Tags []string
Dockerfile string // Relative to context path.
ContainerName string // Name of the resolved Nix container.
}
func (b *NixBuild) UnitName() string {
return fmt.Sprintf("%s-build-%s", b.Runtime, b.ContainerName)
}
func (b *NixBuild) Unit() string {
return b.UnitName() + ".service"
}
func (b *NixBuild) Command() string {
cmd := fmt.Sprintf("%s build", b.Runtime)
for _, tag := range b.Tags {
cmd += fmt.Sprintf(" -t %s", tag)
}
for name, arg := range b.Args {
if arg != nil {
cmd += fmt.Sprintf(" --build-arg %s=%s", name, *arg)
} else {
cmd += fmt.Sprintf(" --build-arg %s", name)
}
}
if b.Dockerfile != "" && b.Dockerfile != "Dockerfile" {
cmd += fmt.Sprintf(" -f %s", b.Dockerfile)
}
if b.IsGitRepo {
cmd += " " + b.Context
} else {
cmd += " ."
}
return cmd
}
type NixContainerConfig struct {
Version string
Project *Project
Runtime ContainerRuntime
Containers []*NixContainer
Builds []*NixBuild
Networks []*NixNetwork
Volumes []*NixVolume
CreateRootTarget bool
WriteNixSetup bool
AutoFormat bool
AutoStart bool
IncludeBuild bool
}
func (c *NixContainerConfig) String() string {
s := strings.Builder{}
internalFuncMap := template.FuncMap{
"cfg": c.configTemplateFunc,
"execTemplate": execTemplate(nixTemplates),
"rootTarget": c.rootTargetTemplateFunc,
}
nixTemplates := template.Must(nixTemplates.Funcs(internalFuncMap).ParseFS(templateFS, "templates/*.tmpl"))
if err := nixTemplates.ExecuteTemplate(&s, "main.nix.tmpl", c); err != nil {
// This should never be hit under normal operation.
panic(err)
}
return s.String()
}
// Write writes out the Nix config to the provided Writer.
//
// If the AutoFormat option on this struct is set to "true", this method will
// attempt to format the Nix config by calling "nixfmt" and passing in the
// fully built config via stdin.
func (c *NixContainerConfig) Write(out io.Writer) error {
config := []byte(c.String())
if c.AutoFormat {
formatted, err := formatNixCode(config)
if err != nil {
return err
}
config = formatted
}
if _, err := out.Write(config); err != nil {
return fmt.Errorf("failed to write Nix code: %w", err)
}
return nil
}
func rootTarget(runtime ContainerRuntime, project *Project) string {
return fmt.Sprintf("%s-compose-%s", runtime, project.With("root"))
}
func (c *NixContainerConfig) rootTargetTemplateFunc() string {
if !c.CreateRootTarget {
return ""
}
return rootTarget(c.Runtime, c.Project)
}
func (c *NixContainerConfig) configTemplateFunc() *NixContainerConfig {
return c
}