-
Notifications
You must be signed in to change notification settings - Fork 318
/
compose.go
808 lines (686 loc) · 24.1 KB
/
compose.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
package devcontainer
import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"time"
composetypes "github.com/compose-spec/compose-go/types"
"github.com/joho/godotenv"
"github.com/loft-sh/devpod/pkg/compose"
"github.com/loft-sh/devpod/pkg/devcontainer/config"
"github.com/loft-sh/devpod/pkg/devcontainer/feature"
"github.com/loft-sh/devpod/pkg/devcontainer/metadata"
"github.com/loft-sh/devpod/pkg/dockerfile"
"github.com/loft-sh/devpod/pkg/driver"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
const (
ConfigFilesLabel = "com.docker.compose.project.config_files"
FeaturesBuildOverrideFilePrefix = "docker-compose.devcontainer.build"
FeaturesStartOverrideFilePrefix = "docker-compose.devcontainer.containerFeatures"
)
func (r *runner) composeHelper() (*compose.ComposeHelper, error) {
dockerDriver, ok := r.Driver.(driver.DockerDriver)
if !ok {
return nil, fmt.Errorf("docker compose is not supported by this provider, please choose a different one")
}
return dockerDriver.ComposeHelper()
}
func (r *runner) stopDockerCompose(ctx context.Context, projectName string) error {
composeHelper, err := r.composeHelper()
if err != nil {
return errors.Wrap(err, "find docker compose")
}
parsedConfig, _, err := r.prepare(r.WorkspaceConfig.CLIOptions)
if err != nil {
return errors.Wrap(err, "get parsed config")
}
_, _, composeGlobalArgs, err := r.dockerComposeProjectFiles(parsedConfig)
if err != nil {
return errors.Wrap(err, "get compose/env files")
}
err = composeHelper.Stop(ctx, projectName, composeGlobalArgs)
if err != nil {
return err
}
return nil
}
func (r *runner) deleteDockerCompose(ctx context.Context, projectName string) error {
composeHelper, err := r.composeHelper()
if err != nil {
return errors.Wrap(err, "find docker compose")
}
parsedConfig, _, err := r.prepare(r.WorkspaceConfig.CLIOptions)
if err != nil {
return errors.Wrap(err, "get parsed config")
}
_, _, composeGlobalArgs, err := r.dockerComposeProjectFiles(parsedConfig)
if err != nil {
return errors.Wrap(err, "get compose/env files")
}
err = composeHelper.Remove(ctx, projectName, composeGlobalArgs)
if err != nil {
return err
}
return nil
}
func (r *runner) dockerComposeProjectFiles(parsedConfig *config.SubstitutedConfig) ([]string, []string, []string, error) {
envFiles, err := r.getEnvFiles()
if err != nil {
return nil, nil, nil, errors.Wrap(err, "get env files")
}
composeFiles, err := r.getDockerComposeFilePaths(parsedConfig, envFiles)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "get docker compose file paths")
}
var args []string
for _, configFile := range composeFiles {
args = append(args, "-f", configFile)
}
for _, envFile := range envFiles {
args = append(args, "--env-file", envFile)
}
return composeFiles, envFiles, args, nil
}
func (r *runner) runDockerCompose(
ctx context.Context,
parsedConfig *config.SubstitutedConfig,
substitutionContext *config.SubstitutionContext,
options UpOptions,
) (*config.Result, error) {
composeHelper, err := r.composeHelper()
if err != nil {
return nil, errors.Wrap(err, "find docker compose")
}
composeFiles, envFiles, composeGlobalArgs, err := r.dockerComposeProjectFiles(parsedConfig)
if err != nil {
return nil, errors.Wrap(err, "get compose/env files")
}
r.Log.Debugf("Loading docker compose project %+v", composeFiles)
project, err := compose.LoadDockerComposeProject(composeFiles, envFiles)
if err != nil {
return nil, errors.Wrap(err, "load docker compose project")
}
project.Name = composeHelper.GetProjectName(r.ID)
r.Log.Debugf("Loaded project %s", project.Name)
containerDetails, err := composeHelper.FindDevContainer(ctx, project.Name, parsedConfig.Config.Service)
if err != nil {
return nil, errors.Wrap(err, "find dev container")
}
// does the container already exist or is it not running?
if containerDetails == nil || containerDetails.State.Status != "running" || options.Recreate {
didStartProject := false
// Try to find existing project first
existingProjectFiles, err := composeHelper.FindProjectFiles(ctx, project.Name)
if err != nil {
r.Log.Errorf("Error finding project files: %s", err)
} else if len(existingProjectFiles) > 0 && !options.Recreate {
r.Log.Debugf("Found existing project files: %s", existingProjectFiles)
// make sure all project files are still available
for _, file := range existingProjectFiles {
if _, err := os.Stat(file); err != nil {
r.Log.Warnf("Project file %s does not exist anymore, recreating project", file)
containerDetails = nil
break
}
}
// If project is found, we can call `up` with the project name
// If it fails, fall back to rebuilding
upArgs := []string{"--project-name", project.Name}
for _, existingProjectFiles := range existingProjectFiles {
upArgs = append(upArgs, "-f", existingProjectFiles)
}
upArgs = append(upArgs, "up", "-d")
writer := r.Log.Writer(logrus.InfoLevel, false)
err = composeHelper.Run(ctx, upArgs, nil, writer, writer)
if err != nil {
r.Log.Errorf("Error starting project: %s", err)
} else {
// wait for running and get container details
details, err := composeHelper.FindDevContainer(ctx, project.Name, parsedConfig.Config.Service)
if err != nil {
r.Log.Errorf("Error finding dev container: %s", err)
} else {
containerDetails = details
didStartProject = true
}
}
}
// Start container if not running
if !didStartProject {
containerDetails, err = r.startContainer(ctx, parsedConfig, substitutionContext, project, composeHelper, composeGlobalArgs, containerDetails, options)
if err != nil {
return nil, errors.Wrap(err, "start container")
} else if containerDetails == nil {
return nil, fmt.Errorf("couldn't find container after start")
}
}
}
imageMetadataConfig, err := metadata.GetImageMetadataFromContainer(containerDetails, substitutionContext, r.Log)
if err != nil {
return nil, errors.Wrap(err, "get image metadata from container")
}
mergedConfig, err := config.MergeConfiguration(parsedConfig.Config, imageMetadataConfig.Config)
if err != nil {
return nil, errors.Wrap(err, "merge config")
}
// setup container
return r.setupContainer(ctx, parsedConfig.Raw, containerDetails, mergedConfig, substitutionContext)
}
func (r *runner) getDockerComposeFilePaths(parsedConfig *config.SubstitutedConfig, envFiles []string) ([]string, error) {
configFileDir := filepath.Dir(parsedConfig.Config.Origin)
// Use docker compose files from config
var composeFiles []string
if len(parsedConfig.Config.DockerComposeFile) > 0 {
for _, composeFile := range parsedConfig.Config.DockerComposeFile {
absPath := composeFile
if !filepath.IsAbs(composeFile) {
absPath = filepath.Join(configFileDir, composeFile)
}
composeFiles = append(composeFiles, absPath)
}
return composeFiles, nil
}
// Use docker compose files from $COMPOSE_FILE environment variable
envComposeFile := os.Getenv("COMPOSE_FILE")
// Load docker compose files from $COMPOSE_FILE in .env file
if envComposeFile == "" {
for _, envFile := range envFiles {
env, err := godotenv.Read(envFile)
if err != nil {
return nil, err
}
if env["COMPOSE_FILE"] != "" {
envComposeFile = env["COMPOSE_FILE"]
break
}
}
}
if envComposeFile != "" {
return filepath.SplitList(envComposeFile), nil
}
return nil, nil
}
func (r *runner) getEnvFiles() ([]string, error) {
var envFiles []string
envFile := path.Join(r.LocalWorkspaceFolder, ".env")
envFileStat, err := os.Stat(envFile)
if err == nil && envFileStat.Mode().IsRegular() {
envFiles = append(envFiles, envFile)
}
return envFiles, nil
}
func (r *runner) startContainer(
ctx context.Context,
parsedConfig *config.SubstitutedConfig,
substitutionContext *config.SubstitutionContext,
project *composetypes.Project,
composeHelper *compose.ComposeHelper,
composeGlobalArgs []string,
container *config.ContainerDetails,
options UpOptions,
) (*config.ContainerDetails, error) {
service := parsedConfig.Config.Service
composeService, err := project.GetService(service)
if err != nil {
return nil, fmt.Errorf("service '%s' configured in devcontainer.json not found in Docker Compose configuration", service)
}
originalImageName := composeService.Image
if originalImageName == "" {
originalImageName, err = composeHelper.GetDefaultImage(project.Name, service)
if err != nil {
return nil, errors.Wrap(err, "get default image")
}
}
var didRestoreFromPersistedShare bool
if container != nil {
labels := container.Config.Labels
if labels[ConfigFilesLabel] != "" {
configFiles := strings.Split(labels[ConfigFilesLabel], ",")
persistedBuildFileFound, persistedBuildFileExists, persistedBuildFile, err := checkForPersistedFile(configFiles, FeaturesBuildOverrideFilePrefix)
if err != nil {
return nil, errors.Wrap(err, "check for persisted build override")
}
_, persistedStartFileExists, persistedStartFile, err := checkForPersistedFile(configFiles, FeaturesStartOverrideFilePrefix)
if err != nil {
return nil, errors.Wrap(err, "check for persisted start override")
}
if (persistedBuildFileExists || !persistedBuildFileFound) && persistedStartFileExists {
didRestoreFromPersistedShare = true
if persistedBuildFileExists {
composeGlobalArgs = append(composeGlobalArgs, "-f", persistedBuildFile)
}
if persistedStartFileExists {
composeGlobalArgs = append(composeGlobalArgs, "-f", persistedStartFile)
}
}
}
}
if container == nil || !didRestoreFromPersistedShare {
overrideBuildImageName, overrideComposeBuildFilePath, imageMetadata, metadataLabel, err := r.buildAndExtendDockerCompose(ctx, parsedConfig, substitutionContext, project, composeHelper, &composeService, composeGlobalArgs)
if err != nil {
return nil, errors.Wrap(err, "build and extend docker-compose")
}
if overrideComposeBuildFilePath != "" {
composeGlobalArgs = append(composeGlobalArgs, "-f", overrideComposeBuildFilePath)
}
currentImageName := overrideBuildImageName
if currentImageName == "" {
currentImageName = originalImageName
}
imageDetails, err := r.inspectImage(ctx, currentImageName)
if err != nil {
return nil, errors.Wrap(err, "inspect image")
}
mergedConfig, err := config.MergeConfiguration(parsedConfig.Config, imageMetadata.Config)
if err != nil {
return nil, errors.Wrap(err, "merge configuration")
}
additionalLabels := map[string]string{
metadata.ImageMetadataLabel: metadataLabel,
config.UserLabel: imageDetails.Config.User,
}
overrideComposeUpFilePath, err := r.extendedDockerComposeUp(parsedConfig, mergedConfig, composeHelper, &composeService, originalImageName, overrideBuildImageName, imageDetails, additionalLabels)
if err != nil {
return nil, errors.Wrap(err, "extend docker-compose up")
}
if overrideComposeUpFilePath != "" {
composeGlobalArgs = append(composeGlobalArgs, "-f", overrideComposeUpFilePath)
}
}
if container != nil && options.Recreate {
r.Log.Debugf("Deleting dev container %s due to --recreate", container.ID)
if err := r.Driver.StopDevContainer(ctx, r.ID); err != nil {
return nil, errors.Wrap(err, "stop dev container")
}
if err := r.Driver.DeleteDevContainer(ctx, r.ID); err != nil {
return nil, errors.Wrap(err, "delete dev container")
}
}
upArgs := []string{"--project-name", project.Name}
upArgs = append(upArgs, composeGlobalArgs...)
upArgs = append(upArgs, "up", "-d")
if container != nil {
upArgs = append(upArgs, "--no-recreate")
}
if len(parsedConfig.Config.RunServices) > 0 {
upArgs = append(upArgs, composeService.Name)
for _, service := range parsedConfig.Config.RunServices {
if service == composeService.Name {
continue
}
upArgs = append(upArgs, service)
}
}
// start compose
writer := r.Log.Writer(logrus.InfoLevel, false)
defer writer.Close()
err = composeHelper.Run(ctx, upArgs, nil, writer, writer)
if err != nil {
return nil, errors.Wrapf(err, "docker-compose run")
}
// TODO wait for started event?
containerDetails, err := composeHelper.FindDevContainer(ctx, project.Name, composeService.Name)
if err != nil {
return nil, errors.Wrap(err, "find dev container")
}
return containerDetails, nil
}
// This extends the build information for docker compose containers
func (r *runner) buildAndExtendDockerCompose(
ctx context.Context,
parsedConfig *config.SubstitutedConfig,
substitutionContext *config.SubstitutionContext,
project *composetypes.Project,
composeHelper *compose.ComposeHelper,
composeService *composetypes.ServiceConfig,
globalArgs []string,
) (string, string, *config.ImageMetadataConfig, string, error) {
var dockerFilePath, dockerfileContents, dockerComposeFilePath string
var imageBuildInfo *config.ImageBuildInfo
var err error
buildImageName := composeService.Image
buildTarget := "dev_container_auto_added_stage_label"
// Determine base imageName for generated features build
if composeService.Build != nil {
if path.IsAbs(composeService.Build.Dockerfile) {
dockerFilePath = composeService.Build.Dockerfile
} else {
dockerFilePath = filepath.Join(composeService.Build.Context, composeService.Build.Dockerfile)
}
originalDockerfile, err := os.ReadFile(dockerFilePath)
if err != nil {
return "", "", nil, "", err
}
originalTarget := composeService.Build.Target
if originalTarget != "" {
buildTarget = originalTarget
} else {
lastStageName, modifiedDockerfile, err := dockerfile.EnsureDockerfileHasFinalStageName(string(originalDockerfile), config.DockerfileDefaultTarget)
if err != nil {
return "", "", nil, "", err
}
buildTarget = lastStageName
if modifiedDockerfile != "" {
dockerfileContents = modifiedDockerfile
}
}
imageBuildInfo, err = r.getImageBuildInfoFromDockerfile(substitutionContext, string(originalDockerfile), mappingToMap(composeService.Build.Args), originalTarget)
if err != nil {
return "", "", nil, "", err
}
} else {
imageBuildInfo, err = r.getImageBuildInfoFromImage(ctx, substitutionContext, composeService.Image)
if err != nil {
return "", "", nil, "", err
}
}
extendImageBuildInfo, err := feature.GetExtendedBuildInfo(substitutionContext, imageBuildInfo.Metadata, imageBuildInfo.User, buildTarget, parsedConfig, r.Log, false)
if err != nil {
return "", "", nil, "", err
}
if extendImageBuildInfo != nil && extendImageBuildInfo.FeaturesBuildInfo != nil {
if dockerfileContents == "" {
dockerfileContents = fmt.Sprintf("FROM %s AS %s\n", composeService.Image, buildTarget)
}
extendedDockerfilePath, extendedDockerfileContent := r.extendedDockerfile(
extendImageBuildInfo.FeaturesBuildInfo,
dockerFilePath,
dockerfileContents,
)
r.Log.Debugf(
"Creating extended Dockerfile %s with content: \n %s",
extendedDockerfilePath,
extendedDockerfileContent,
)
defer os.RemoveAll(filepath.Dir(extendedDockerfilePath))
err := os.WriteFile(extendedDockerfilePath, []byte(extendedDockerfileContent), 0600)
if err != nil {
return "", "", nil, "", errors.Wrap(err, "write Dockerfile with features")
}
dockerComposeFilePath, err = r.extendedDockerComposeBuild(
composeService,
extendedDockerfilePath,
extendImageBuildInfo.FeaturesBuildInfo,
)
if err != nil {
return buildImageName, "", nil, "", err
}
}
buildArgs := []string{"--project-name", project.Name}
buildArgs = append(buildArgs, globalArgs...)
if dockerComposeFilePath != "" {
buildArgs = append(buildArgs, "-f", dockerComposeFilePath)
}
buildArgs = append(buildArgs, "build")
if extendImageBuildInfo == nil {
buildArgs = append(buildArgs, "--pull")
}
if len(parsedConfig.Config.RunServices) > 0 {
buildArgs = append(buildArgs, composeService.Name)
for _, service := range parsedConfig.Config.RunServices {
if service == composeService.Name {
continue
}
buildArgs = append(buildArgs, service)
}
}
// build image
writer := r.Log.Writer(logrus.InfoLevel, false)
defer writer.Close()
r.Log.Debugf("Run %s %s", composeHelper.Command, strings.Join(buildArgs, " "))
err = composeHelper.Run(ctx, buildArgs, nil, writer, writer)
if err != nil {
return buildImageName, "", nil, "", err
}
imageMetadata, err := metadata.GetDevContainerMetadata(substitutionContext, imageBuildInfo.Metadata, parsedConfig, extendImageBuildInfo.Features)
if err != nil {
return buildImageName, "", nil, "", err
}
return buildImageName, dockerComposeFilePath, imageMetadata, extendImageBuildInfo.MetadataLabel, nil
}
func (r *runner) extendedDockerfile(featureBuildInfo *feature.BuildInfo, dockerfilePath, dockerfileContent string) (string, string) {
// extra args?
finalDockerfilePath := dockerfilePath
finalDockerfileContent := dockerfileContent
// get extended build info
if featureBuildInfo != nil {
// rewrite dockerfile path
finalDockerfilePath = filepath.Join(featureBuildInfo.FeaturesFolder, "Dockerfile-with-features")
// rewrite dockerfile
finalDockerfileContent = dockerfile.RemoveSyntaxVersion(dockerfileContent)
finalDockerfileContent = strings.TrimSpace(strings.Join([]string{
featureBuildInfo.DockerfilePrefixContent,
strings.TrimSpace(finalDockerfileContent),
featureBuildInfo.DockerfileContent,
}, "\n"))
}
return finalDockerfilePath, finalDockerfileContent
}
func (r *runner) extendedDockerComposeBuild(composeService *composetypes.ServiceConfig, dockerFilePath string, featuresBuildInfo *feature.BuildInfo) (string, error) {
service := &composetypes.ServiceConfig{
Name: composeService.Name,
Build: &composetypes.BuildConfig{
Dockerfile: dockerFilePath,
Context: filepath.Dir(featuresBuildInfo.FeaturesFolder),
},
}
if composeService.Build != nil && composeService.Build.Target != "" {
service.Build.Target = featuresBuildInfo.OverrideTarget
}
service.Build.Args = composetypes.NewMappingWithEquals([]string{"BUILDKIT_INLINE_CACHE=1"})
for k, v := range featuresBuildInfo.BuildArgs {
v := v
service.Build.Args[k] = &v
}
project := &composetypes.Project{}
project.Services = composetypes.Services{
*service,
}
dockerComposeFolder := getDockerComposeFolder(r.WorkspaceConfig.Origin)
err := os.MkdirAll(dockerComposeFolder, 0755)
if err != nil {
return "", err
}
dockerComposeData, err := yaml.Marshal(project)
if err != nil {
return "", err
}
dockerComposePath := filepath.Join(dockerComposeFolder, fmt.Sprintf("%s-%d.yml", FeaturesBuildOverrideFilePrefix, time.Now().Second()))
r.Log.Debugf(
"Creating docker-compose build %s with content:\n %s",
dockerComposePath,
string(dockerComposeData),
)
err = os.WriteFile(dockerComposePath, dockerComposeData, 0600)
if err != nil {
return "", err
}
return dockerComposePath, nil
}
func (r *runner) extendedDockerComposeUp(
parsedConfig *config.SubstitutedConfig,
mergedConfig *config.MergedDevContainerConfig,
composeHelper *compose.ComposeHelper,
composeService *composetypes.ServiceConfig,
originalImageName,
overrideImageName string,
imageDetails *config.ImageDetails,
additionalLabels map[string]string,
) (string, error) {
dockerComposeUpProject := r.generateDockerComposeUpProject(parsedConfig, mergedConfig, composeHelper, composeService, originalImageName, overrideImageName, imageDetails, additionalLabels)
dockerComposeData, err := yaml.Marshal(dockerComposeUpProject)
if err != nil {
return "", err
}
dockerComposeFolder := getDockerComposeFolder(r.WorkspaceConfig.Origin)
err = os.MkdirAll(dockerComposeFolder, 0755)
if err != nil {
return "", err
}
dockerComposePath := filepath.Join(dockerComposeFolder, fmt.Sprintf("%s-%d.yml", FeaturesStartOverrideFilePrefix, time.Now().Second()))
r.Log.Debugf(
"Creating docker-compose up %s with content:\n %s",
dockerComposePath,
string(dockerComposeData),
)
err = os.WriteFile(dockerComposePath, dockerComposeData, 0600)
if err != nil {
return "", err
}
return dockerComposePath, nil
}
func (r *runner) generateDockerComposeUpProject(
parsedConfig *config.SubstitutedConfig,
mergedConfig *config.MergedDevContainerConfig,
composeHelper *compose.ComposeHelper,
composeService *composetypes.ServiceConfig,
originalImageName,
overrideImageName string,
imageDetails *config.ImageDetails,
additionalLabels map[string]string,
) *composetypes.Project {
// Configure overridden service
userEntrypoint := composeService.Entrypoint
userCommand := composeService.Command
if mergedConfig.OverrideCommand != nil && *mergedConfig.OverrideCommand {
userEntrypoint = []string{}
userCommand = []string{}
} else {
if len(userEntrypoint) == 0 {
userEntrypoint = imageDetails.Config.Entrypoint
}
if len(userCommand) == 0 {
userCommand = imageDetails.Config.Cmd
}
}
entrypoint := composetypes.ShellCommand{
"/bin/sh",
"-c",
`echo Container started
trap "exit 0" 15
` + strings.Join(mergedConfig.Entrypoints, "\n") + `
exec "$$@"
while sleep 1 & wait $$!; do :; done`,
"-",
}
entrypoint = append(entrypoint, userEntrypoint...)
labels := composetypes.Labels{
config.DockerIDLabel: r.ID,
}
for k, v := range additionalLabels {
// Escape $ and ' to prevent substituting local environment variables!
label := regexp.MustCompile(`\$`).ReplaceAllString(v, "$$$$")
label = regexp.MustCompile(`'`).ReplaceAllString(label, `\'\'`)
labels.Add(k, label)
}
overrideService := &composetypes.ServiceConfig{
Name: composeService.Name,
Entrypoint: entrypoint,
Environment: mappingFromMap(mergedConfig.ContainerEnv),
Init: mergedConfig.Init,
CapAdd: mergedConfig.CapAdd,
SecurityOpt: mergedConfig.SecurityOpt,
Labels: labels,
}
if originalImageName != overrideImageName {
overrideService.Image = overrideImageName
}
if !reflect.DeepEqual(userCommand, composeService.Command) {
overrideService.Command = userCommand
}
if mergedConfig.ContainerUser != "" {
overrideService.User = mergedConfig.ContainerUser
}
if mergedConfig.Privileged != nil {
overrideService.Privileged = *mergedConfig.Privileged
}
gpuSupportEnabled, _ := composeHelper.Docker.GPUSupportEnabled()
if parsedConfig.Config.HostRequirements != nil && parsedConfig.Config.HostRequirements.GPU == "true" && gpuSupportEnabled {
overrideService.Deploy = &composetypes.DeployConfig{
Resources: composetypes.Resources{
Reservations: &composetypes.Resource{
Devices: []composetypes.DeviceRequest{
{
Capabilities: []string{"gpu"},
},
},
},
},
}
}
for _, mount := range mergedConfig.Mounts {
overrideService.Volumes = append(overrideService.Volumes, composetypes.ServiceVolumeConfig{
Type: mount.Type,
Source: mount.Source,
Target: mount.Target,
})
}
project := &composetypes.Project{}
project.Services = composetypes.Services{
*overrideService,
}
// Configure volumes
var volumeMounts []composetypes.VolumeConfig
for _, m := range mergedConfig.Mounts {
if m.Type == "volume" {
volumeMounts = append(volumeMounts, composetypes.VolumeConfig{
Name: m.Source,
External: composetypes.External{
External: m.External,
},
})
}
}
if len(volumeMounts) > 0 {
project.Volumes = map[string]composetypes.VolumeConfig{}
}
for _, volumeMount := range volumeMounts {
project.Volumes[volumeMount.Name] = volumeMount
}
return project
}
func checkForPersistedFile(files []string, prefix string) (foundLabel bool, fileExists bool, filePath string, err error) {
for _, file := range files {
if !strings.HasPrefix(file, prefix) {
continue
}
stat, err := os.Stat(file)
if err == nil && stat.Mode().IsRegular() {
return true, true, file, nil
} else if os.IsNotExist(err) {
return true, false, file, nil
}
}
return false, false, "", nil
}
func getDockerComposeFolder(workspaceOriginFolder string) string {
return filepath.Join(workspaceOriginFolder, ".docker-compose")
}
func mappingFromMap(m map[string]string) composetypes.MappingWithEquals {
if len(m) == 0 {
return nil
}
var values []string
for k, v := range m {
values = append(values, k+"="+v)
}
return composetypes.NewMappingWithEquals(values)
}
func mappingToMap(mapping composetypes.MappingWithEquals) map[string]string {
ret := map[string]string{}
for k, v := range mapping {
ret[k] = *v
}
return ret
}
func isDockerComposeConfig(config *config.DevContainerConfig) bool {
return len(config.DockerComposeFile) > 0
}