-
Notifications
You must be signed in to change notification settings - Fork 132
/
build.go
387 lines (348 loc) · 12.5 KB
/
build.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
// Copyright (c) Contributors to the Apptainer project, established as
// Apptainer a Series of LF Projects LLC.
// For website terms of use, trademark policy, privacy policy and other
// project policies see https://lfprojects.org/policies
// Copyright (c) 2020, Control Command Inc. All rights reserved.
// Copyright (c) 2018-2021, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package cli
import (
"fmt"
"io/ioutil"
"os"
"syscall"
"github.com/apptainer/apptainer/docs"
"github.com/apptainer/apptainer/internal/pkg/util/fs"
"github.com/apptainer/apptainer/internal/pkg/util/interactive"
"github.com/apptainer/apptainer/pkg/cmdline"
"github.com/apptainer/apptainer/pkg/image"
ocitypes "github.com/containers/image/v5/types"
"github.com/spf13/cobra"
"golang.org/x/term"
)
var buildArgs struct {
sections []string
bindPaths []string
mounts []string
libraryURL string
keyServerURL string
webURL string
encrypt bool
fakeroot bool
fixPerms bool
isJSON bool
noCleanUp bool
noTest bool
sandbox bool
update bool
nvidia bool
nvccli bool
rocm bool
writableTmpfs bool // For test section only
}
// -s|--sandbox
var buildSandboxFlag = cmdline.Flag{
ID: "buildSandboxFlag",
Value: &buildArgs.sandbox,
DefaultValue: false,
Name: "sandbox",
ShortHand: "s",
Usage: "build image as sandbox format (chroot directory structure)",
EnvKeys: []string{"SANDBOX"},
}
// --section
var buildSectionFlag = cmdline.Flag{
ID: "buildSectionFlag",
Value: &buildArgs.sections,
DefaultValue: []string{"all"},
Name: "section",
Usage: "only run specific section(s) of deffile (setup, post, files, environment, test, labels, none)",
EnvKeys: []string{"SECTION"},
}
// --json
var buildJSONFlag = cmdline.Flag{
ID: "buildJSONFlag",
Value: &buildArgs.isJSON,
DefaultValue: false,
Name: "json",
Usage: "interpret build definition as JSON",
EnvKeys: []string{"JSON"},
}
// -u|--update
var buildUpdateFlag = cmdline.Flag{
ID: "buildUpdateFlag",
Value: &buildArgs.update,
DefaultValue: false,
Name: "update",
ShortHand: "u",
Usage: "run definition over existing container (skips header)",
EnvKeys: []string{"UPDATE"},
}
// -T|--notest
var buildNoTestFlag = cmdline.Flag{
ID: "buildNoTestFlag",
Value: &buildArgs.noTest,
DefaultValue: false,
Name: "notest",
ShortHand: "T",
Usage: "build without running tests in %test section",
EnvKeys: []string{"NOTEST"},
}
// --library
var buildLibraryFlag = cmdline.Flag{
ID: "buildLibraryFlag",
Value: &buildArgs.libraryURL,
DefaultValue: "",
Name: "library",
Usage: "container Library URL",
EnvKeys: []string{"LIBRARY"},
}
// --disable-cache
var buildDisableCacheFlag = cmdline.Flag{
ID: "buildDisableCacheFlag",
Value: &disableCache,
DefaultValue: false,
Name: "disable-cache",
Usage: "do not use cache or create cache",
EnvKeys: []string{"DISABLE_CACHE"},
}
// --no-cleanup
var buildNoCleanupFlag = cmdline.Flag{
ID: "buildNoCleanupFlag",
Value: &buildArgs.noCleanUp,
DefaultValue: false,
Name: "no-cleanup",
Usage: "do NOT clean up bundle after failed build, can be helpful for debugging",
EnvKeys: []string{"NO_CLEANUP"},
}
// --fakeroot
var buildFakerootFlag = cmdline.Flag{
ID: "buildFakerootFlag",
Value: &buildArgs.fakeroot,
DefaultValue: false,
Name: "fakeroot",
ShortHand: "f",
Usage: "build using user namespace to fake root user (requires a privileged installation)",
EnvKeys: []string{"FAKEROOT"},
}
// -e|--encrypt
var buildEncryptFlag = cmdline.Flag{
ID: "buildEncryptFlag",
Value: &buildArgs.encrypt,
DefaultValue: false,
Name: "encrypt",
ShortHand: "e",
Usage: "build an image with an encrypted file system",
}
// TODO: Deprecate at 3.6, remove at 3.8
// --fix-perms
var buildFixPermsFlag = cmdline.Flag{
ID: "fixPermsFlag",
Value: &buildArgs.fixPerms,
DefaultValue: false,
Name: "fix-perms",
Usage: "ensure owner has rwX permissions on all container content for oci/docker sources",
EnvKeys: []string{"FIXPERMS"},
}
// --nv
var buildNvFlag = cmdline.Flag{
ID: "nvFlag",
Value: &buildArgs.nvidia,
DefaultValue: false,
Name: "nv",
Usage: "inject host Nvidia libraries during build for post and test sections",
}
// --nvccli
var buildNvCCLIFlag = cmdline.Flag{
ID: "buildNvCCLIFlag",
Value: &buildArgs.nvccli,
DefaultValue: false,
Name: "nvccli",
Usage: "use nvidia-container-cli for GPU setup (experimental)",
EnvKeys: []string{"NVCCLI"},
}
// --rocm
var buildRocmFlag = cmdline.Flag{
ID: "rocmFlag",
Value: &buildArgs.rocm,
DefaultValue: false,
Name: "rocm",
Usage: "inject host Rocm libraries during build for post and test sections",
}
// -B|--bind
var buildBindFlag = cmdline.Flag{
ID: "buildBindFlag",
Value: &buildArgs.bindPaths,
DefaultValue: cmdline.StringArray{}, // to allow commas in bind path
Name: "bind",
ShortHand: "B",
Usage: "a user-bind path specification. spec has the format src[:dest[:opts]]," +
"where src and dest are outside and inside paths. If dest is not given," +
"it is set equal to src. Mount options ('opts') may be specified as 'ro'" +
"(read-only) or 'rw' (read/write, which is the default)." +
"Multiple bind paths can be given by a comma separated list.",
}
// --mount
var buildMountFlag = cmdline.Flag{
ID: "buildMountFlag",
Value: &buildArgs.mounts,
DefaultValue: cmdline.StringArray{}, // to allow commas in bind path
Name: "mount",
Usage: "a mount specification e.g. 'type=bind,source=/opt,destination=/hostopt'.",
EnvKeys: []string{"MOUNT"},
Tag: "<spec>",
EnvHandler: cmdline.EnvAppendValue,
}
// --writable-tmpfs
var buildWritableTmpfsFlag = cmdline.Flag{
ID: "buildWritableTmpfsFlag",
Value: &buildArgs.writableTmpfs,
DefaultValue: false,
Name: "writable-tmpfs",
Usage: "during the %test section, makes the file system accessible as read-write with non persistent data (with overlay support only)",
EnvKeys: []string{"WRITABLE_TMPFS"},
}
func init() {
addCmdInit(func(cmdManager *cmdline.CommandManager) {
cmdManager.RegisterCmd(buildCmd)
cmdManager.RegisterFlagForCmd(&buildDisableCacheFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildEncryptFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildFakerootFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildFixPermsFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildJSONFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildLibraryFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildNoCleanupFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildNoTestFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildSandboxFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildSectionFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildUpdateFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&commonForceFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&commonNoHTTPSFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&commonTmpDirFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&dockerUsernameFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&dockerPasswordFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&dockerLoginFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&commonPromptForPassphraseFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&commonPEMFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildNvFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildNvCCLIFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildRocmFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildBindFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildMountFlag, buildCmd)
cmdManager.RegisterFlagForCmd(&buildWritableTmpfsFlag, buildCmd)
})
}
// buildCmd represents the build command.
var buildCmd = &cobra.Command{
DisableFlagsInUseLine: true,
Args: cobra.ExactArgs(2),
Use: docs.BuildUse,
Short: docs.BuildShort,
Long: docs.BuildLong,
Example: docs.BuildExample,
PreRun: preRun,
Run: runBuild,
TraverseChildren: true,
}
func preRun(cmd *cobra.Command, args []string) {
if buildArgs.fakeroot {
fakerootExec(args)
}
}
// checkBuildTarget makes sure output target doesn't exist, or is ok to overwrite.
// And checks that update flag will update an existing directory.
func checkBuildTarget(path string) error {
abspath, err := fs.Abs(path)
if err != nil {
return fmt.Errorf("failed to get absolute path for %q: %v", path, err)
}
if !buildArgs.sandbox && buildArgs.update {
return fmt.Errorf("only sandbox update is supported: --sandbox flag is missing")
}
if f, err := os.Stat(abspath); err == nil {
if buildArgs.update && !f.IsDir() {
return fmt.Errorf("only sandbox update is supported: %s is not a directory", abspath)
}
// check if the sandbox image being overwritten looks like an Apptainer
// image and inform users to check its content and use --force option if
// the sandbox image is not an Apptainer image
if f.IsDir() && !forceOverwrite {
files, err := ioutil.ReadDir(abspath)
if err != nil {
return fmt.Errorf("could not read sandbox directory %s: %s", abspath, err)
} else if len(files) > 0 {
required := 0
for _, f := range files {
switch f.Name() {
case ".singularity.d", "dev", "proc", "sys":
required++
}
}
if required != 4 {
return fmt.Errorf("%s is not empty and is not an Apptainer sandbox, check its content first and use --force if you want to overwrite it", abspath)
}
}
}
if !buildArgs.update && !forceOverwrite {
// If non-interactive, die... don't try to prompt the user y/n
if !term.IsTerminal(syscall.Stdin) {
return fmt.Errorf("build target '%s' already exists. Use --force if you want to overwrite it", f.Name())
}
question := fmt.Sprintf("Build target '%s' already exists and will be deleted during the build process. Do you want to continue? [N/y] ", f.Name())
img, err := image.Init(abspath, false)
if err != nil {
if err != image.ErrUnknownFormat {
return fmt.Errorf("while determining '%s' format: %s", f.Name(), err)
}
// unknown image file format
question = fmt.Sprintf("Build target '%s' may be a definition file or a text/binary file that will be overwritten. Do you still want to overwrite it? [N/y] ", f.Name())
} else {
img.File.Close()
}
input, err := interactive.AskYNQuestion("n", question)
if err != nil {
return fmt.Errorf("while reading the input: %s", err)
}
if input != "y" {
return fmt.Errorf("stopping build")
}
forceOverwrite = true
}
} else if os.IsNotExist(err) && buildArgs.update && buildArgs.sandbox {
return fmt.Errorf("could not update sandbox %s: doesn't exist", abspath)
}
return nil
}
// makeDockerCredentials creates an *ocitypes.DockerAuthConfig to use for
// OCI/Docker registry operation configuration. Note that if we don't have a
// username or password set it will return a nil pointer, as containers/image
// requires this to fall back to .docker/config based authentication.
func makeDockerCredentials(cmd *cobra.Command) (authConf *ocitypes.DockerAuthConfig, err error) {
usernameFlag := cmd.Flags().Lookup("docker-username")
passwordFlag := cmd.Flags().Lookup("docker-password")
if dockerLogin {
if !usernameFlag.Changed {
dockerAuthConfig.Username, err = interactive.AskQuestion("Enter Docker Username: ")
if err != nil {
return authConf, err
}
usernameFlag.Value.Set(dockerAuthConfig.Username)
usernameFlag.Changed = true
}
dockerAuthConfig.Password, err = interactive.AskQuestionNoEcho("Enter Docker Password: ")
if err != nil {
return authConf, err
}
passwordFlag.Value.Set(dockerAuthConfig.Password)
passwordFlag.Changed = true
}
if usernameFlag.Changed || passwordFlag.Changed {
return &dockerAuthConfig, nil
}
// If a username / password have not been explicitly set, return a nil
// pointer, which will mean containers/image falls back to looking for
// .docker/config.json
return nil, nil
}