-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathenvbuilder.go
1079 lines (982 loc) · 33.3 KB
/
envbuilder.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
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package envbuilder
import (
"bufio"
"bytes"
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"syscall"
"time"
dcontext "github.com/distribution/distribution/v3/context"
"github.com/kballard/go-shellquote"
"github.com/mattn/go-isatty"
"github.com/GoogleContainerTools/kaniko/pkg/config"
"github.com/GoogleContainerTools/kaniko/pkg/creds"
"github.com/GoogleContainerTools/kaniko/pkg/executor"
"github.com/GoogleContainerTools/kaniko/pkg/util"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/envbuilder/devcontainer"
"github.com/containerd/containerd/platforms"
"github.com/distribution/distribution/v3/configuration"
"github.com/distribution/distribution/v3/registry/handlers"
_ "github.com/distribution/distribution/v3/registry/storage/driver/filesystem"
"github.com/docker/cli/cli/config/configfile"
"github.com/fatih/color"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/osfs"
"github.com/go-git/go-git/v5/plumbing/transport"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/sirupsen/logrus"
"github.com/tailscale/hujson"
"golang.org/x/xerrors"
)
const (
// WorkspacesDir is the path to the directory where
// all workspaces are stored by default.
WorkspacesDir = "/workspaces"
// EmptyWorkspaceDir is the path to a workspace that has
// nothing going on... it's empty!
EmptyWorkspaceDir = WorkspacesDir + "/empty"
// MagicDir is where all envbuilder related files are stored.
// This is a special directory that must not be modified
// by the user or images.
MagicDir = "/.envbuilder"
)
var (
ErrNoFallbackImage = errors.New("no fallback image has been specified")
// MagicFile is a file that is created in the workspace
// when envbuilder has already been run. This is used
// to skip building when a container is restarting.
// e.g. docker stop -> docker start
MagicFile = filepath.Join(MagicDir, "built")
)
// DockerConfig represents the Docker configuration file.
type DockerConfig configfile.ConfigFile
// Run runs the envbuilder.
// Logger is the logf to use for all operations.
// Filesystem is the filesystem to use for all operations.
// Defaults to the host filesystem.
func Run(ctx context.Context, options Options) error {
// Default to the shell!
initArgs := []string{"-c", options.InitScript}
if options.InitArgs != "" {
var err error
initArgs, err = shellquote.Split(options.InitArgs)
if err != nil {
return fmt.Errorf("parse init args: %w", err)
}
}
if options.Filesystem == nil {
options.Filesystem = &osfsWithChmod{osfs.New("/")}
}
if options.WorkspaceFolder == "" {
f, err := DefaultWorkspaceFolder(options.GitURL)
if err != nil {
return err
}
options.WorkspaceFolder = f
}
stageNumber := 1
startStage := func(format string, args ...any) func(format string, args ...any) {
now := time.Now()
stageNum := stageNumber
stageNumber++
options.Logger(codersdk.LogLevelInfo, "#%d: %s", stageNum, fmt.Sprintf(format, args...))
return func(format string, args ...any) {
options.Logger(codersdk.LogLevelInfo, "#%d: %s [%s]", stageNum, fmt.Sprintf(format, args...), time.Since(now))
}
}
options.Logger(codersdk.LogLevelInfo, "%s - Build development environments from repositories in a container", newColor(color.Bold).Sprintf("envbuilder"))
var caBundle []byte
if options.SSLCertBase64 != "" {
certPool, err := x509.SystemCertPool()
if err != nil {
return xerrors.Errorf("get global system cert pool: %w", err)
}
data, err := base64.StdEncoding.DecodeString(options.SSLCertBase64)
if err != nil {
return xerrors.Errorf("base64 decode ssl cert: %w", err)
}
ok := certPool.AppendCertsFromPEM(data)
if !ok {
return xerrors.Errorf("failed to append the ssl cert to the global pool: %s", data)
}
caBundle = data
}
if options.DockerConfigBase64 != "" {
decoded, err := base64.StdEncoding.DecodeString(options.DockerConfigBase64)
if err != nil {
return fmt.Errorf("decode docker config: %w", err)
}
var configFile DockerConfig
decoded, err = hujson.Standardize(decoded)
if err != nil {
return fmt.Errorf("humanize json for docker config: %w", err)
}
err = json.Unmarshal(decoded, &configFile)
if err != nil {
return fmt.Errorf("parse docker config: %w", err)
}
err = os.WriteFile(filepath.Join(MagicDir, "config.json"), decoded, 0644)
if err != nil {
return fmt.Errorf("write docker config: %w", err)
}
}
var fallbackErr error
var cloned bool
if options.GitURL != "" {
endStage := startStage("📦 Cloning %s to %s...",
newColor(color.FgCyan).Sprintf(options.GitURL),
newColor(color.FgCyan).Sprintf(options.WorkspaceFolder),
)
reader, writer := io.Pipe()
defer reader.Close()
defer writer.Close()
go func() {
data := make([]byte, 4096)
for {
read, err := reader.Read(data)
if err != nil {
return
}
content := data[:read]
for _, line := range strings.Split(string(content), "\r") {
if line == "" {
continue
}
options.Logger(codersdk.LogLevelInfo, "#1: %s", strings.TrimSpace(line))
}
}
}()
cloneOpts := CloneRepoOptions{
Path: options.WorkspaceFolder,
Storage: options.Filesystem,
Insecure: options.Insecure,
Progress: writer,
SingleBranch: options.GitCloneSingleBranch,
Depth: int(options.GitCloneDepth),
CABundle: caBundle,
}
cloneOpts.RepoAuth = SetupRepoAuth(&options)
if options.GitHTTPProxyURL != "" {
cloneOpts.ProxyOptions = transport.ProxyOptions{
URL: options.GitHTTPProxyURL,
}
}
cloneOpts.RepoURL = options.GitURL
cloned, fallbackErr = CloneRepo(ctx, cloneOpts)
if fallbackErr == nil {
if cloned {
endStage("📦 Cloned repository!")
} else {
endStage("📦 The repository already exists!")
}
} else {
options.Logger(codersdk.LogLevelError, "Failed to clone repository: %s", fallbackErr.Error())
options.Logger(codersdk.LogLevelError, "Falling back to the default image...")
}
}
defaultBuildParams := func() (*devcontainer.Compiled, error) {
dockerfile := filepath.Join(MagicDir, "Dockerfile")
file, err := options.Filesystem.OpenFile(dockerfile, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
defer file.Close()
if options.FallbackImage == "" {
if fallbackErr != nil {
return nil, xerrors.Errorf("%s: %w", fallbackErr.Error(), ErrNoFallbackImage)
}
// We can't use errors.Join here because our tests
// don't support parsing a multiline error.
return nil, ErrNoFallbackImage
}
content := "FROM " + options.FallbackImage
_, err = file.Write([]byte(content))
if err != nil {
return nil, err
}
return &devcontainer.Compiled{
DockerfilePath: dockerfile,
DockerfileContent: content,
BuildContext: MagicDir,
}, nil
}
var (
buildParams *devcontainer.Compiled
scripts devcontainer.LifecycleScripts
)
if options.DockerfilePath == "" {
// Only look for a devcontainer if a Dockerfile wasn't specified.
// devcontainer is a standard, so it's reasonable to be the default.
devcontainerPath, devcontainerDir, err := findDevcontainerJSON(options)
if err != nil {
options.Logger(codersdk.LogLevelError, "Failed to locate devcontainer.json: %s", err.Error())
options.Logger(codersdk.LogLevelError, "Falling back to the default image...")
} else {
// We know a devcontainer exists.
// Let's parse it and use it!
file, err := options.Filesystem.Open(devcontainerPath)
if err != nil {
return fmt.Errorf("open devcontainer.json: %w", err)
}
defer file.Close()
content, err := io.ReadAll(file)
if err != nil {
return fmt.Errorf("read devcontainer.json: %w", err)
}
devContainer, err := devcontainer.Parse(content)
if err == nil {
var fallbackDockerfile string
if !devContainer.HasImage() && !devContainer.HasDockerfile() {
defaultParams, err := defaultBuildParams()
if err != nil {
return fmt.Errorf("no Dockerfile or image found: %w", err)
}
options.Logger(codersdk.LogLevelInfo, "No Dockerfile or image specified; falling back to the default image...")
fallbackDockerfile = defaultParams.DockerfilePath
}
buildParams, err = devContainer.Compile(options.Filesystem, devcontainerDir, MagicDir, fallbackDockerfile, options.WorkspaceFolder, false)
if err != nil {
return fmt.Errorf("compile devcontainer.json: %w", err)
}
scripts = devContainer.LifecycleScripts
} else {
options.Logger(codersdk.LogLevelError, "Failed to parse devcontainer.json: %s", err.Error())
options.Logger(codersdk.LogLevelError, "Falling back to the default image...")
}
}
} else {
// If a Dockerfile was specified, we use that.
dockerfilePath := filepath.Join(options.WorkspaceFolder, options.DockerfilePath)
// If the dockerfilePath is specified and deeper than the base of WorkspaceFolder AND the BuildContextPath is
// not defined, show a warning
dockerfileDir := filepath.Dir(dockerfilePath)
if dockerfileDir != filepath.Clean(options.WorkspaceFolder) && options.BuildContextPath == "" {
options.Logger(codersdk.LogLevelWarn, "given dockerfile %q is below %q and no custom build context has been defined", dockerfilePath, options.WorkspaceFolder)
options.Logger(codersdk.LogLevelWarn, "\t-> set BUILD_CONTEXT_PATH to %q to fix", dockerfileDir)
}
dockerfile, err := options.Filesystem.Open(dockerfilePath)
if err == nil {
content, err := io.ReadAll(dockerfile)
if err != nil {
return fmt.Errorf("read Dockerfile: %w", err)
}
buildParams = &devcontainer.Compiled{
DockerfilePath: dockerfilePath,
DockerfileContent: string(content),
BuildContext: filepath.Join(options.WorkspaceFolder, options.BuildContextPath),
}
}
}
if buildParams == nil {
// If there isn't a devcontainer.json file in the repository,
// we fallback to whatever the `DefaultImage` is.
var err error
buildParams, err = defaultBuildParams()
if err != nil {
return fmt.Errorf("no Dockerfile or devcontainer.json found: %w", err)
}
}
HijackLogrus(func(entry *logrus.Entry) {
for _, line := range strings.Split(entry.Message, "\r") {
options.Logger(codersdk.LogLevelInfo, "#2: %s", color.HiBlackString(line))
}
})
var closeAfterBuild func()
// Allows quick testing of layer caching using a local directory!
if options.LayerCacheDir != "" {
cfg := &configuration.Configuration{
Storage: configuration.Storage{
"filesystem": configuration.Parameters{
"rootdirectory": options.LayerCacheDir,
},
},
}
// Disable all logging from the registry...
l := logrus.New()
l.SetOutput(io.Discard)
entry := logrus.NewEntry(l)
dcontext.SetDefaultLogger(entry)
ctx = dcontext.WithLogger(ctx, entry)
// Spawn an in-memory registry to cache built layers...
registry := handlers.NewApp(ctx, cfg)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err
}
tcpAddr, ok := listener.Addr().(*net.TCPAddr)
if !ok {
return fmt.Errorf("listener addr was of wrong type: %T", listener.Addr())
}
srv := &http.Server{
Handler: registry,
}
go func() {
err := srv.Serve(listener)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
options.Logger(codersdk.LogLevelError, "Failed to serve registry: %s", err.Error())
}
}()
closeAfterBuild = func() {
_ = srv.Close()
_ = listener.Close()
}
if options.CacheRepo != "" {
options.Logger(codersdk.LogLevelWarn, "Overriding cache repo with local registry...")
}
options.CacheRepo = fmt.Sprintf("localhost:%d/local/cache", tcpAddr.Port)
}
// IgnorePaths in the Kaniko options doesn't properly ignore paths.
// So we add them to the default ignore list. See:
// https://github.com/GoogleContainerTools/kaniko/blob/63be4990ca5a60bdf06ddc4d10aa4eca0c0bc714/cmd/executor/cmd/root.go#L136
ignorePaths := append([]string{
MagicDir,
options.LayerCacheDir,
options.WorkspaceFolder,
// See: https://github.com/coder/envbuilder/issues/37
"/etc/resolv.conf",
}, options.IgnorePaths...)
for _, ignorePath := range ignorePaths {
util.AddToDefaultIgnoreList(util.IgnoreListEntry{
Path: ignorePath,
PrefixMatchOnly: false,
})
}
skippedRebuild := false
build := func() (v1.Image, error) {
_, err := options.Filesystem.Stat(MagicFile)
if err == nil && options.SkipRebuild {
endStage := startStage("🏗️ Skipping build because of cache...")
imageRef, err := devcontainer.ImageFromDockerfile(buildParams.DockerfileContent)
if err != nil {
return nil, fmt.Errorf("image from dockerfile: %w", err)
}
image, err := remote.Image(imageRef, remote.WithAuthFromKeychain(creds.GetKeychain()))
if err != nil {
return nil, fmt.Errorf("image from remote: %w", err)
}
endStage("🏗️ Found image from remote!")
skippedRebuild = true
return image, nil
}
// This is required for deleting the filesystem prior to build!
err = util.InitIgnoreList(true)
if err != nil {
return nil, fmt.Errorf("init ignore list: %w", err)
}
// It's possible that the container will already have files in it, and
// we don't want to merge a new container with the old one.
if err := maybeDeleteFilesystem(options.Logger, options.ForceSafe); err != nil {
return nil, fmt.Errorf("delete filesystem: %w", err)
}
stdoutReader, stdoutWriter := io.Pipe()
stderrReader, stderrWriter := io.Pipe()
defer stdoutReader.Close()
defer stdoutWriter.Close()
defer stderrReader.Close()
defer stderrWriter.Close()
go func() {
scanner := bufio.NewScanner(stdoutReader)
for scanner.Scan() {
options.Logger(codersdk.LogLevelInfo, "%s", scanner.Text())
}
}()
go func() {
scanner := bufio.NewScanner(stderrReader)
for scanner.Scan() {
options.Logger(codersdk.LogLevelInfo, "%s", scanner.Text())
}
}()
cacheTTL := time.Hour * 24 * 7
if options.CacheTTLDays != 0 {
cacheTTL = time.Hour * 24 * time.Duration(options.CacheTTLDays)
}
endStage := startStage("🏗️ Building image...")
// At this point we have all the context, we can now build!
registryMirror := []string{}
if val, ok := os.LookupEnv("KANIKO_REGISTRY_MIRROR"); ok {
registryMirror = strings.Split(val, ";")
}
image, err := executor.DoBuild(&config.KanikoOptions{
// Boilerplate!
CustomPlatform: platforms.Format(platforms.Normalize(platforms.DefaultSpec())),
SnapshotMode: "redo",
RunV2: true,
RunStdout: stdoutWriter,
RunStderr: stderrWriter,
Destinations: []string{"local"},
CacheRunLayers: true,
CacheCopyLayers: true,
CompressedCaching: true,
Compression: config.ZStd,
// Maps to "default" level, ~100-300 MB/sec according to
// benchmarks in klauspost/compress README
// https://github.com/klauspost/compress/blob/67a538e2b4df11f8ec7139388838a13bce84b5d5/zstd/encoder_options.go#L188
CompressionLevel: 3,
CacheOptions: config.CacheOptions{
// Cache for a week by default!
CacheTTL: cacheTTL,
CacheDir: options.BaseImageCacheDir,
},
ForceUnpack: true,
BuildArgs: buildParams.BuildArgs,
CacheRepo: options.CacheRepo,
Cache: options.CacheRepo != "" || options.BaseImageCacheDir != "",
DockerfilePath: buildParams.DockerfilePath,
DockerfileContent: buildParams.DockerfileContent,
RegistryOptions: config.RegistryOptions{
Insecure: options.Insecure,
InsecurePull: options.Insecure,
SkipTLSVerify: options.Insecure,
// Enables registry mirror features in Kaniko, see more in link below
// https://github.com/GoogleContainerTools/kaniko?tab=readme-ov-file#flag---registry-mirror
// Related to PR #114
// https://github.com/coder/envbuilder/pull/114
RegistryMirrors: registryMirror,
},
SrcContext: buildParams.BuildContext,
})
if err != nil {
return nil, err
}
endStage("🏗️ Built image!")
return image, err
}
// At this point we have all the context, we can now build!
image, err := build()
if err != nil {
fallback := false
switch {
case strings.Contains(err.Error(), "parsing dockerfile"):
fallback = true
fallbackErr = err
case strings.Contains(err.Error(), "error building stage"):
fallback = true
fallbackErr = err
// This occurs when the image cannot be found!
case strings.Contains(err.Error(), "authentication required"):
fallback = true
fallbackErr = err
// This occurs from Docker Hub when the image cannot be found!
case strings.Contains(err.Error(), "manifest unknown"):
fallback = true
fallbackErr = err
case strings.Contains(err.Error(), "unexpected status code 401 Unauthorized"):
options.Logger(codersdk.LogLevelError, "Unable to pull the provided image. Ensure your registry credentials are correct!")
}
if !fallback || options.ExitOnBuildFailure {
return err
}
options.Logger(codersdk.LogLevelError, "Failed to build: %s", err)
options.Logger(codersdk.LogLevelError, "Falling back to the default image...")
buildParams, err = defaultBuildParams()
if err != nil {
return err
}
image, err = build()
}
if err != nil {
return fmt.Errorf("build with kaniko: %w", err)
}
if closeAfterBuild != nil {
closeAfterBuild()
}
// Create the magic file to indicate that this build
// has already been ran before!
file, err := options.Filesystem.Create(MagicFile)
if err != nil {
return fmt.Errorf("create magic file: %w", err)
}
_ = file.Close()
configFile, err := image.ConfigFile()
if err != nil {
return fmt.Errorf("get image config: %w", err)
}
containerEnv := make(map[string]string)
remoteEnv := make(map[string]string)
// devcontainer metadata can be persisted through a standard label
devContainerMetadata, exists := configFile.Config.Labels["devcontainer.metadata"]
if exists {
var devContainer []*devcontainer.Spec
devContainerMetadataBytes, err := hujson.Standardize([]byte(devContainerMetadata))
if err != nil {
return fmt.Errorf("humanize json for dev container metadata: %w", err)
}
err = json.Unmarshal(devContainerMetadataBytes, &devContainer)
if err != nil {
return fmt.Errorf("unmarshal metadata: %w", err)
}
options.Logger(codersdk.LogLevelInfo, "#3: 👀 Found devcontainer.json label metadata in image...")
for _, container := range devContainer {
if container.RemoteUser != "" {
options.Logger(codersdk.LogLevelInfo, "#3: 🧑 Updating the user to %q!", container.RemoteUser)
configFile.Config.User = container.RemoteUser
}
maps.Copy(containerEnv, container.ContainerEnv)
maps.Copy(remoteEnv, container.RemoteEnv)
if !container.OnCreateCommand.IsEmpty() {
scripts.OnCreateCommand = container.OnCreateCommand
}
if !container.UpdateContentCommand.IsEmpty() {
scripts.UpdateContentCommand = container.UpdateContentCommand
}
if !container.PostCreateCommand.IsEmpty() {
scripts.PostCreateCommand = container.PostCreateCommand
}
if !container.PostStartCommand.IsEmpty() {
scripts.PostStartCommand = container.PostStartCommand
}
}
}
// Sanitize the environment of any options!
unsetOptionsEnv()
// Remove the Docker config secret file!
if options.DockerConfigBase64 != "" {
err = os.Remove(filepath.Join(MagicDir, "config.json"))
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove docker config: %w", err)
}
}
environ, err := os.ReadFile("/etc/environment")
if err == nil {
for _, env := range strings.Split(string(environ), "\n") {
pair := strings.SplitN(env, "=", 2)
if len(pair) != 2 {
continue
}
os.Setenv(pair[0], pair[1])
}
}
allEnvKeys := make(map[string]struct{})
// It must be set in this parent process otherwise nothing will be found!
for _, env := range configFile.Config.Env {
pair := strings.SplitN(env, "=", 2)
os.Setenv(pair[0], pair[1])
allEnvKeys[pair[0]] = struct{}{}
}
maps.Copy(containerEnv, buildParams.ContainerEnv)
maps.Copy(remoteEnv, buildParams.RemoteEnv)
for _, env := range []map[string]string{containerEnv, remoteEnv} {
envKeys := make([]string, 0, len(env))
for key := range env {
envKeys = append(envKeys, key)
allEnvKeys[key] = struct{}{}
}
sort.Strings(envKeys)
for _, envVar := range envKeys {
value := devcontainer.SubstituteVars(env[envVar], options.WorkspaceFolder)
os.Setenv(envVar, value)
}
}
// Do not export env if we skipped a rebuild, because ENV directives
// from the Dockerfile would not have been processed and we'd miss these
// in the export. We should have generated a complete set of environment
// on the intial build, so exporting environment variables a second time
// isn't useful anyway.
if options.ExportEnvFile != "" && !skippedRebuild {
exportEnvFile, err := os.Create(options.ExportEnvFile)
if err != nil {
return fmt.Errorf("failed to open EXPORT_ENV_FILE %q: %w", options.ExportEnvFile, err)
}
envKeys := make([]string, 0, len(allEnvKeys))
for key := range allEnvKeys {
envKeys = append(envKeys, key)
}
sort.Strings(envKeys)
for _, key := range envKeys {
fmt.Fprintf(exportEnvFile, "%s=%s\n", key, os.Getenv(key))
}
exportEnvFile.Close()
}
username := configFile.Config.User
if buildParams.User != "" {
username = buildParams.User
}
if username == "" {
options.Logger(codersdk.LogLevelWarn, "#3: no user specified, using root")
}
userInfo, err := getUser(username)
if err != nil {
return fmt.Errorf("update user: %w", err)
}
// We only need to do this if we cloned!
// Git doesn't store file permissions as part of the repository.
if cloned {
endStage := startStage("🔄 Updating the ownership of the workspace...")
// By default, we clone the Git repository into the workspace folder.
// It will have root permissions, because that's the user that built it.
//
// We need to change the ownership of the files to the user that will
// be running the init script.
filepath.Walk(options.WorkspaceFolder, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
return os.Chown(path, userInfo.uid, userInfo.gid)
})
endStage("👤 Updated the ownership of the workspace!")
}
err = os.MkdirAll(options.WorkspaceFolder, 0755)
if err != nil {
return fmt.Errorf("create workspace folder: %w", err)
}
err = os.Chdir(options.WorkspaceFolder)
if err != nil {
return fmt.Errorf("change directory: %w", err)
}
// This is called before the Setuid to TARGET_USER because we want the
// lifecycle scripts to run using the default user for the container,
// rather than the user specified for running the init command. For
// example, TARGET_USER may be set to root in the case where we will
// exec systemd as the init command, but that doesn't mean we should
// run the lifecycle scripts as root.
os.Setenv("HOME", userInfo.user.HomeDir)
if err := execLifecycleScripts(ctx, options, scripts, skippedRebuild, userInfo); err != nil {
return err
}
// The setup script can specify a custom initialization command
// and arguments to run instead of the default shell.
//
// This is useful for hooking into the environment for a specific
// init to PID 1.
if options.SetupScript != "" {
// We execute the initialize script as the root user!
os.Setenv("HOME", "/root")
options.Logger(codersdk.LogLevelInfo, "=== Running the setup command %q as the root user...", options.SetupScript)
envKey := "ENVBUILDER_ENV"
envFile := filepath.Join("/", MagicDir, "environ")
file, err := os.Create(envFile)
if err != nil {
return fmt.Errorf("create environ file: %w", err)
}
_ = file.Close()
cmd := exec.CommandContext(ctx, "/bin/sh", "-c", options.SetupScript)
cmd.Env = append(os.Environ(),
fmt.Sprintf("%s=%s", envKey, envFile),
fmt.Sprintf("TARGET_USER=%s", userInfo.user.Username),
)
cmd.Dir = options.WorkspaceFolder
// This allows for a really nice and clean experience to experiement with!
// e.g. docker run --it --rm -e INIT_SCRIPT bash ...
if isatty.IsTerminal(os.Stdout.Fd()) && isatty.IsTerminal(os.Stdin.Fd()) {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
} else {
var buf bytes.Buffer
go func() {
scanner := bufio.NewScanner(&buf)
for scanner.Scan() {
options.Logger(codersdk.LogLevelInfo, "%s", scanner.Text())
}
}()
cmd.Stdout = &buf
cmd.Stderr = &buf
}
err = cmd.Run()
if err != nil {
return fmt.Errorf("run setup script: %w", err)
}
environ, err := os.ReadFile(envFile)
if errors.Is(err, os.ErrNotExist) {
err = nil
environ = []byte{}
}
if err != nil {
return fmt.Errorf("read environ: %w", err)
}
updatedCommand := false
updatedArgs := false
for _, env := range strings.Split(string(environ), "\n") {
pair := strings.SplitN(env, "=", 2)
if len(pair) != 2 {
continue
}
key := pair[0]
switch key {
case "INIT_COMMAND":
options.InitCommand = pair[1]
updatedCommand = true
case "INIT_ARGS":
initArgs, err = shellquote.Split(pair[1])
if err != nil {
return fmt.Errorf("split init args: %w", err)
}
updatedArgs = true
case "TARGET_USER":
userInfo, err = getUser(pair[1])
if err != nil {
return fmt.Errorf("update user: %w", err)
}
default:
return fmt.Errorf("unknown environ key %q", key)
}
}
if updatedCommand && !updatedArgs {
// Because our default is a shell we need to empty the args
// if the command was updated. This a tragic hack, but it works.
initArgs = []string{}
}
}
// Hop into the user that should execute the initialize script!
os.Setenv("HOME", userInfo.user.HomeDir)
err = syscall.Setgid(userInfo.gid)
if err != nil {
return fmt.Errorf("set gid: %w", err)
}
err = syscall.Setuid(userInfo.uid)
if err != nil {
return fmt.Errorf("set uid: %w", err)
}
options.Logger(codersdk.LogLevelInfo, "=== Running the init command %s %+v as the %q user...", options.InitCommand, initArgs, userInfo.user.Username)
err = syscall.Exec(options.InitCommand, append([]string{options.InitCommand}, initArgs...), os.Environ())
if err != nil {
return fmt.Errorf("exec init script: %w", err)
}
return nil
}
// DefaultWorkspaceFolder returns the default workspace folder
// for a given repository URL.
func DefaultWorkspaceFolder(repoURL string) (string, error) {
if repoURL == "" {
return "/workspaces/empty", nil
}
parsed, err := url.Parse(repoURL)
if err != nil {
return "", err
}
name := strings.Split(parsed.Path, "/")
return fmt.Sprintf("/workspaces/%s", name[len(name)-1]), nil
}
type userInfo struct {
uid int
gid int
user *user.User
}
func getUser(username string) (userInfo, error) {
user, err := findUser(username)
if err != nil {
return userInfo{}, fmt.Errorf("find user: %w", err)
}
uid, err := strconv.Atoi(user.Uid)
if err != nil {
return userInfo{}, fmt.Errorf("parse uid: %w", err)
}
gid, err := strconv.Atoi(user.Gid)
if err != nil {
return userInfo{}, fmt.Errorf("parse gid: %w", err)
}
if user.Username == "" && uid == 0 {
// This is nice for the visual display in log messages,
// but has no actual functionality since the credential
// in the syscall is what matters.
user.Username = "root"
user.HomeDir = "/root"
}
return userInfo{
uid: uid,
gid: gid,
user: user,
}, nil
}
// findUser looks up a user by name or ID.
func findUser(nameOrID string) (*user.User, error) {
if nameOrID == "" {
return &user.User{
Uid: "0",
Gid: "0",
}, nil
}
_, err := strconv.Atoi(nameOrID)
if err == nil {
return user.LookupId(nameOrID)
}
return user.Lookup(nameOrID)
}
func execOneLifecycleScript(
ctx context.Context,
logf func(level codersdk.LogLevel, format string, args ...any),
s devcontainer.LifecycleScript,
scriptName string,
userInfo userInfo,
) error {
if s.IsEmpty() {
return nil
}
logf(codersdk.LogLevelInfo, "=== Running %s as the %q user...", scriptName, userInfo.user.Username)
if err := s.Execute(ctx, userInfo.uid, userInfo.gid); err != nil {
logf(codersdk.LogLevelError, "Failed to run %s: %v", scriptName, err)
return err
}
return nil
}
func execLifecycleScripts(
ctx context.Context,
options Options,
scripts devcontainer.LifecycleScripts,
skippedRebuild bool,
userInfo userInfo,
) error {
if options.PostStartScriptPath != "" {
_ = os.Remove(options.PostStartScriptPath)
}
if !skippedRebuild {
if err := execOneLifecycleScript(ctx, options.Logger, scripts.OnCreateCommand, "onCreateCommand", userInfo); err != nil {
// skip remaining lifecycle commands
return nil
}
}
if err := execOneLifecycleScript(ctx, options.Logger, scripts.UpdateContentCommand, "updateContentCommand", userInfo); err != nil {
// skip remaining lifecycle commands
return nil
}
if err := execOneLifecycleScript(ctx, options.Logger, scripts.PostCreateCommand, "postCreateCommand", userInfo); err != nil {
// skip remaining lifecycle commands
return nil
}
if !scripts.PostStartCommand.IsEmpty() {
// If PostStartCommandPath is set, the init command is responsible
// for running the postStartCommand. Otherwise, we execute it now.
if options.PostStartScriptPath != "" {
if err := createPostStartScript(options.PostStartScriptPath, scripts.PostStartCommand); err != nil {
return fmt.Errorf("failed to create post-start script: %w", err)
}
} else {
_ = execOneLifecycleScript(ctx, options.Logger, scripts.PostStartCommand, "postStartCommand", userInfo)
}
}
return nil
}
func createPostStartScript(path string, postStartCommand devcontainer.LifecycleScript) error {
postStartScript, err := os.Create(path)
if err != nil {
return err
}
defer postStartScript.Close()
if err := postStartScript.Chmod(0755); err != nil {
return err
}
if _, err := postStartScript.WriteString("#!/bin/sh\n\n" + postStartCommand.ScriptLines()); err != nil {
return err
}
return nil
}
// unsetOptionsEnv unsets all environment variables that are used
// to configure the options.
func unsetOptionsEnv() {
val := reflect.ValueOf(&Options{}).Elem()
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
fieldTyp := typ.Field(i)
env := fieldTyp.Tag.Get("env")
if env == "" {
continue
}
os.Unsetenv(env)
}
}
func newColor(value ...color.Attribute) *color.Color {
c := color.New(value...)
c.EnableColor()
return c
}
type osfsWithChmod struct {
billy.Filesystem
}
func (fs *osfsWithChmod) Chmod(name string, mode os.FileMode) error {
return os.Chmod(name, mode)
}
func findDevcontainerJSON(options Options) (string, string, error) {
// 0. Check if custom devcontainer directory or path is provided.
if options.DevcontainerDir != "" || options.DevcontainerJSONPath != "" {
devcontainerDir := options.DevcontainerDir
if devcontainerDir == "" {
devcontainerDir = ".devcontainer"
}
// If `devcontainerDir` is not an absolute path, assume it is relative to the workspace folder.
if !filepath.IsAbs(devcontainerDir) {