-
Notifications
You must be signed in to change notification settings - Fork 386
/
converter.go
2977 lines (2715 loc) · 95.1 KB
/
converter.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 earthfile2llb
import (
"bytes"
"context"
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"io/fs"
"net"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/alessio/shellescape"
"github.com/containerd/containerd/platforms"
"github.com/docker/distribution/reference"
"github.com/earthly/cloud-api/logstream"
"github.com/earthly/earthly/analytics"
"github.com/earthly/earthly/ast/commandflag"
"github.com/earthly/earthly/ast/hint"
"github.com/earthly/earthly/ast/spec"
"github.com/earthly/earthly/buildcontext"
debuggercommon "github.com/earthly/earthly/debugger/common"
"github.com/earthly/earthly/domain"
"github.com/earthly/earthly/features"
"github.com/earthly/earthly/inputgraph"
"github.com/earthly/earthly/logbus"
"github.com/earthly/earthly/states"
"github.com/earthly/earthly/states/dedup"
"github.com/earthly/earthly/states/image"
"github.com/earthly/earthly/util/containerutil"
"github.com/earthly/earthly/util/fileutil"
"github.com/earthly/earthly/util/gitutil"
"github.com/earthly/earthly/util/inodeutil"
"github.com/earthly/earthly/util/llbutil"
"github.com/earthly/earthly/util/llbutil/llbfactory"
"github.com/earthly/earthly/util/llbutil/pllb"
"github.com/earthly/earthly/util/llbutil/secretprovider"
"github.com/earthly/earthly/util/oidcutil"
"github.com/earthly/earthly/util/platutil"
"github.com/earthly/earthly/util/shell"
"github.com/earthly/earthly/util/stringutil"
"github.com/earthly/earthly/util/syncutil/semutil"
"github.com/earthly/earthly/util/vertexmeta"
"github.com/earthly/earthly/variables"
"github.com/earthly/earthly/variables/reserved"
"github.com/moby/buildkit/client/llb"
dockerimage "github.com/moby/buildkit/exporter/containerimage/image"
"github.com/moby/buildkit/frontend/dockerfile/dockerfile2llb"
"github.com/moby/buildkit/frontend/dockerui"
gwclient "github.com/moby/buildkit/frontend/gateway/client"
"github.com/moby/buildkit/session/localhost"
solverpb "github.com/moby/buildkit/solver/pb"
"github.com/moby/buildkit/util/apicaps"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type cmdType int
const (
argCmd cmdType = iota + 1 // "ARG"
buildCmd // "BUILD"
cmdCmd // "CMD"
copyCmd // "COPY"
enterScopeDoCmd // "ENTER-SCOPE-DO"
entrypointCmd // "ENTRYPOINT"
envCmd // "ENV"
exposeCmd // "EXPOSE"
fromCmd // "FROM"
fromDockerfileCmd // "FROM DOCKERFILE"
gitCloneCmd // "GIT CLONE"
healthcheckCmd // "HEALTHCHECK"
importCmd // "IMPORT"
labelCmd // "LABEL"
loadCmd // "LOAD"
locallyCmd // "LOCALLY"
runCmd // "RUN"
saveArtifactCmd // "SAVE ARTIFACT"
saveImageCmd // "SAVE IMAGE"
userCmd // "USER"
volumeCmd // "VOLUME"
workdirCmd // "WORKDIR"
cacheCmd // "CACHE"
hostCmd // "HOST"
projectCmd // "PROJECT"
pipelineCmd // "PIPELINE"
triggerCmd // "TRIGGER"
setCmd // "SET"
letCmd // "LET"
)
// Converter turns earthly commands to buildkit LLB representation.
type Converter struct {
target domain.Target
gitMeta *gitutil.GitMetadata
platr *platutil.Resolver
opt ConvertOpt
mts *states.MultiTarget
directDeps []*states.SingleTarget
buildContextFactory llbfactory.Factory
cacheContext pllb.State
persistentCacheDirs map[string]states.CacheMount // maps path->mount
varCollection *variables.Collection
ranSave bool
cmdSet bool
ftrs *features.Features
localWorkingDir string
containerFrontend containerutil.ContainerFrontend
waitBlockStack []*waitBlock
isPipeline bool
logbusTarget *logbus.Target
nextCmdID int
}
// NewConverter constructs a new converter for a given earthly target.
func NewConverter(ctx context.Context, target domain.Target, bc *buildcontext.Data, sts *states.SingleTarget, opt ConvertOpt) (*Converter, error) {
opt.BuildContextProvider.AddDirs(bc.LocalDirs)
sts.HasDangling = opt.HasDangling
mts := &states.MultiTarget{
Final: sts,
Visited: opt.Visited,
}
newCollOpt := variables.NewCollectionOpt{
Console: opt.Console,
Target: target,
Push: opt.DoPushes,
CI: opt.IsCI,
EarthlyCIRunner: opt.EarthlyCIRunner,
PlatformResolver: opt.PlatformResolver,
GitMeta: bc.GitMetadata,
BuiltinArgs: opt.BuiltinArgs,
OverridingVars: opt.OverridingVars,
GlobalImports: opt.GlobalImports,
Features: opt.Features,
}
ovVarsKeysSorted := opt.OverridingVars.Sorted()
ovVars := make([]string, 0, len(ovVarsKeysSorted))
for _, k := range ovVarsKeysSorted {
v, _ := opt.OverridingVars.Get(k)
ovVars = append(ovVars, fmt.Sprintf("%s=%s", k, v))
}
run := opt.Logbus.Run()
logbusTarget, err := run.NewTarget(
sts.ID,
target,
ovVars,
opt.PlatformResolver.Current().String(),
opt.Runner,
)
if err != nil {
return nil, errors.Wrap(err, "new logbus target")
}
logbusTarget.SetStart(time.Now())
c := &Converter{
target: target,
gitMeta: bc.GitMetadata,
platr: opt.PlatformResolver,
opt: opt,
mts: mts,
buildContextFactory: bc.BuildContextFactory,
cacheContext: pllb.Scratch(),
persistentCacheDirs: make(map[string]states.CacheMount),
varCollection: variables.NewCollection(newCollOpt),
ftrs: bc.Features,
localWorkingDir: filepath.Dir(bc.BuildFilePath),
containerFrontend: opt.ContainerFrontend,
waitBlockStack: []*waitBlock{opt.waitBlock},
logbusTarget: logbusTarget,
}
if c.opt.GlobalWaitBlockFtr {
c.ftrs.WaitBlock = true
}
return c, nil
}
// From applies the earthly FROM command.
func (c *Converter) From(ctx context.Context, imageName string, platform platutil.Platform, allowPrivileged, passArgs bool, buildArgs []string) error {
err := c.checkAllowed(fromCmd)
if err != nil {
return err
}
c.nonSaveCommand()
if len(c.persistentCacheDirs) > 0 {
c.persistentCacheDirs = make(map[string]states.CacheMount)
}
c.cmdSet = false
err = c.checkOldPlatformIncompatibility(platform)
if err != nil {
return err
}
c.varCollection.SetLocally(false) // FIXME this will have to change once https://github.com/earthly/earthly/issues/2044 is fixed
platform = c.setPlatform(platform)
if strings.Contains(imageName, "+") {
// Target-based FROM.
return c.fromTarget(ctx, imageName, platform, allowPrivileged, passArgs, buildArgs)
}
// Docker image based FROM.
if len(buildArgs) != 0 {
return errors.New("--build-arg not supported in non-target FROM")
}
return c.fromClassical(ctx, imageName, platform, false)
}
func (c *Converter) fromClassical(ctx context.Context, imageName string, platform platutil.Platform, local bool) error {
var internal bool
if local {
// local mode uses a fake image containing /bin/true
// we want to prefix this as internal so it doesn't show up in the output
internal = true
} else {
internal = false
}
prefix, _, err := c.newVertexMeta(ctx, local, false, internal, nil)
if err != nil {
return err
}
state, img, envVars, err := c.internalFromClassical(
ctx, imageName, platform,
llb.WithCustomNamef("%sFROM %s", prefix, imageName))
if err != nil {
return err
}
c.mts.Final.MainState = state
c.mts.Final.MainImage = img
c.mts.Final.RanFromLike = true
c.varCollection.ResetEnvVars(envVars)
return nil
}
func (c *Converter) fromTarget(ctx context.Context, targetName string, platform platutil.Platform, allowPrivileged, passArgs bool, buildArgs []string) (retErr error) {
cmdID, cmd, err := c.newLogbusCommand(ctx, fmt.Sprintf("FROM %s", targetName))
if err != nil {
return errors.Wrap(err, "failed to create command")
}
defer func() {
cmd.SetEndError(retErr)
}()
depTarget, err := domain.ParseTarget(targetName)
if err != nil {
return errors.Wrapf(err, "parse target name %s", targetName)
}
mts, err := c.buildTarget(ctx, depTarget.String(), platform, allowPrivileged, passArgs, buildArgs, false, fromCmd, cmdID, nil)
if err != nil {
return errors.Wrapf(err, "apply build %s", depTarget.String())
}
if mts.Final.RanInteractive {
return errors.New("cannot FROM a target ending with an --interactive")
}
if depTarget.IsLocalInternal() {
depTarget.LocalPath = c.mts.Final.Target.LocalPath
}
// Look for the built state in the dep states, after we've built it.
relevantDepState := mts.Final
saveImage := relevantDepState.LastSaveImage()
// Pass on dep state over to this state.
c.mts.Final.MainState = relevantDepState.MainState
c.varCollection.ResetEnvVars(mts.Final.VarCollection.EnvVars())
c.mts.Final.MainImage = saveImage.Image.Clone()
c.mts.Final.RanFromLike = mts.Final.RanFromLike
c.mts.Final.RanInteractive = mts.Final.RanInteractive
c.platr.UpdatePlatform(mts.Final.PlatformResolver.Current())
return nil
}
// FromDockerfile applies the earthly FROM DOCKERFILE command.
func (c *Converter) FromDockerfile(ctx context.Context, contextPath string, dfPath string, dfTarget string, platform platutil.Platform, allowPrivileged bool, buildArgs []string) (retErr error) {
var err error
ctx, err = c.ftrs.WithContext(ctx)
if err != nil {
return errors.Wrap(err, "failed to add feature flags to context")
}
err = c.checkAllowed(fromDockerfileCmd)
if err != nil {
return err
}
err = c.checkOldPlatformIncompatibility(platform)
if err != nil {
return err
}
platform = c.setPlatform(platform)
plat := c.platr.ToLLBPlatform(platform)
c.nonSaveCommand()
cmdID, cmd, err := c.newLogbusCommand(ctx, fmt.Sprintf("FROM DOCKERFILE %s", dfPath))
if err != nil {
return errors.Wrap(err, "failed to create command")
}
defer func() {
cmd.SetEndError(retErr)
}()
var dfData []byte
if dfPath != "" {
dfArtifact, parseErr := domain.ParseArtifact(dfPath)
if parseErr == nil {
// The Dockerfile is from a target's artifact.
mts, err := c.buildTarget(ctx, dfArtifact.Target.String(), platform, allowPrivileged, false, buildArgs, false, fromDockerfileCmd, cmdID, nil)
if err != nil {
return err
}
dfData, err = c.readArtifact(ctx, mts, dfArtifact)
if err != nil {
return err
}
} else {
// The Dockerfile is from the host.
dockerfileMetaTarget := domain.Target{
Target: fmt.Sprintf("%s%s", buildcontext.DockerfileMetaTarget, path.Base(dfPath)),
LocalPath: path.Dir(dfPath),
}
dockerfileMetaTargetRef, err := c.joinRefs(dockerfileMetaTarget)
if err != nil {
return errors.Wrap(err, "join targets")
}
dockerfileMetaTarget = dockerfileMetaTargetRef.(domain.Target)
data, err := c.opt.Resolver.Resolve(ctx, c.opt.GwClient, c.platr, dockerfileMetaTarget)
if err != nil {
return errors.Wrap(err, "resolve build context for dockerfile")
}
c.opt.BuildContextProvider.AddDirs(data.LocalDirs)
dfData, err = os.ReadFile(data.BuildFilePath)
if err != nil {
return errors.Wrapf(err, "read file %s", data.BuildFilePath)
}
}
}
var BuildContextFactory llbfactory.Factory
contextArtifact, parseErr := domain.ParseArtifact(contextPath)
if parseErr == nil {
prefix, cmdID, err := c.newVertexMeta(ctx, false, false, true, nil)
if err != nil {
return err
}
// The build context is from a target's artifact.
// TODO: The build args are used for both the artifact and the Dockerfile. This could be
// confusing to the user.
mts, err := c.buildTarget(ctx, contextArtifact.Target.String(), platform, allowPrivileged, false, buildArgs, false, fromDockerfileCmd, cmdID, nil)
if err != nil {
return err
}
if dfPath == "" {
// Imply dockerfile as being ./Dockerfile in the root of the build context.
dfArtifact := contextArtifact
dfArtifact.Artifact = path.Join(dfArtifact.Artifact, "Dockerfile")
dfData, err = c.readArtifact(ctx, mts, dfArtifact)
if err != nil {
return err
}
}
copyState, err := llbutil.CopyOp(ctx,
mts.Final.ArtifactsState, []string{contextArtifact.Artifact},
c.platr.Scratch(), "/", true, true, false, "", nil, false, false,
c.ftrs.UseCopyLink,
llb.WithCustomNamef(
"%sFROM DOCKERFILE (copy build context from) %s%s",
prefix,
joinWrap(buildArgs, "(", " ", ") "), contextArtifact.String()))
if err != nil {
return errors.Wrapf(err, "copyOp FROM DOCKERFILE")
}
BuildContextFactory = llbfactory.PreconstructedState(copyState)
} else {
// The build context is from the host.
if contextPath != "." &&
!strings.HasPrefix(contextPath, "./") &&
!strings.HasPrefix(contextPath, "../") &&
!strings.HasPrefix(contextPath, "/") {
contextPath = fmt.Sprintf("./%s", contextPath)
}
dockerfileMetaTarget := domain.Target{
Target: fmt.Sprintf("%s%s", buildcontext.DockerfileMetaTarget, stringutil.StrOrDefault(dfPath, "Dockerfile")),
LocalPath: path.Join(contextPath),
}
dockerfileMetaTargetRef, err := c.joinRefs(dockerfileMetaTarget)
if err != nil {
return errors.Wrap(err, "join targets")
}
dockerfileMetaTarget = dockerfileMetaTargetRef.(domain.Target)
data, err := c.opt.Resolver.Resolve(ctx, c.opt.GwClient, c.platr, dockerfileMetaTarget)
if err != nil {
return errors.Wrap(err, "resolve build context for dockerfile")
}
c.opt.BuildContextProvider.AddDirs(data.LocalDirs)
if dfPath == "" {
// Imply dockerfile as being ./Dockerfile in the root of the build context.
dfData, err = os.ReadFile(data.BuildFilePath)
if err != nil {
return errors.Wrapf(err, "read file %s", data.BuildFilePath)
}
}
BuildContextFactory = data.BuildContextFactory
}
bc, err := dockerui.NewClient(c.opt.GwClient)
if err != nil {
return errors.Wrap(err, "dockerui.NewClient")
}
var pncvf variables.ProcessNonConstantVariableFunc
if !c.opt.Features.ShellOutAnywhere {
pncvf = c.processNonConstantBuildArgFunc(ctx)
}
overriding, err := variables.ParseArgs(buildArgs, pncvf, c.varCollection)
if err != nil {
return err
}
bcRawState, done := BuildContextFactory.Construct().RawState()
bc.SetBuildContext(&bcRawState, c.mts.FinalTarget().String())
state, dfImg, _, err := dockerfile2llb.Dockerfile2LLB(ctx, dfData, dockerfile2llb.ConvertOpt{
MetaResolver: c.opt.MetaResolver,
LLBCaps: c.opt.LLBCaps,
Config: dockerui.Config{
BuildArgs: overriding.Map(),
Target: dfTarget,
ImageResolveMode: c.opt.ImageResolveMode,
},
TargetPlatform: &plat,
Client: bc,
})
done()
if err != nil {
return errors.Wrapf(err, "dockerfile2llb %s", dfPath)
}
// Convert dockerfile2llb image into earthfile2llb image via JSON.
imgDt, err := json.Marshal(dfImg)
if err != nil {
return errors.Wrap(err, "marshal dockerfile image")
}
var img image.Image
err = json.Unmarshal(imgDt, &img)
if err != nil {
return errors.Wrap(err, "unmarshal dockerfile image")
}
state2, img2, envVars := c.applyFromImage(pllb.FromRawState(*state), &img)
c.mts.Final.MainState = state2
c.mts.Final.MainImage = img2
c.mts.Final.RanFromLike = true
c.varCollection.ResetEnvVars(envVars)
return nil
}
// Locally applies the earthly Locally command.
func (c *Converter) Locally(ctx context.Context) error {
err := c.checkAllowed(locallyCmd)
if err != nil {
return err
}
if !c.opt.AllowLocally {
return errors.New("LOCALLY cannot be used when --strict is specified or otherwise implied")
}
err = c.fromClassical(ctx, "scratch", platutil.NativePlatform, true)
if err != nil {
return err
}
workingDir, err := filepath.Abs(c.localWorkingDir)
if err != nil {
return errors.Wrapf(err, "unable to get abs path of %s", c.localWorkingDir)
}
c.varCollection.SetLocally(true)
// reset WORKDIR to current directory where Earthfile is
c.mts.Final.MainState = c.mts.Final.MainState.Dir(workingDir)
c.mts.Final.MainImage.Config.WorkingDir = workingDir
c.setPlatform(platutil.UserPlatform)
return nil
}
// CopyArtifactLocal applies the earthly COPY artifact command which are invoked under a LOCALLY target.
func (c *Converter) CopyArtifactLocal(ctx context.Context, artifactName string, dest string, platform platutil.Platform, allowPrivileged, passArgs bool, buildArgs []string, isDir bool) error {
err := c.checkAllowed(copyCmd)
if err != nil {
return err
}
c.nonSaveCommand()
artifact, err := domain.ParseArtifact(artifactName)
if err != nil {
return errors.Wrapf(err, "parse artifact name %s", artifactName)
}
prefix, cmdID, err := c.newVertexMeta(ctx, false, false, false, nil)
if err != nil {
return err
}
mts, err := c.buildTarget(ctx, artifact.Target.String(), platform, allowPrivileged, passArgs, buildArgs, false, copyCmd, cmdID, nil)
if err != nil {
return errors.Wrapf(err, "apply build %s", artifact.Target.String())
}
if artifact.Target.IsLocalInternal() {
artifact.Target.LocalPath = c.mts.Final.Target.LocalPath
}
// Grab the artifacts state in the dep states, after we've built it.
relevantDepState := mts.Final
finalArgs := []string{localhost.SendFileMagicStr}
if isDir {
finalArgs = append(finalArgs, "--dir")
}
finalArgs = append(finalArgs, artifact.Artifact, dest)
opts := []llb.RunOption{
llb.Args(finalArgs),
llb.IgnoreCache,
pllb.AddMount("/"+localhost.SendFileMagicStr, relevantDepState.ArtifactsState, llb.Readonly),
llb.WithCustomNamef(
"%sCOPY %s%s%s %s",
prefix,
strIf(isDir, "--dir "),
joinWrap(buildArgs, "(", " ", ") "),
artifact.String(),
dest),
}
c.mts.Final.MainState = c.mts.Final.MainState.Run(opts...).Root()
err = c.forceExecution(ctx, c.mts.Final.MainState, c.platr)
if err != nil {
return err
}
return nil
}
// CopyArtifact applies the earthly COPY artifact command.
func (c *Converter) CopyArtifact(ctx context.Context, artifactName string, dest string, platform platutil.Platform, allowPrivileged, passArgs bool, buildArgs []string, isDir bool, keepTs bool, keepOwn bool, chown string, chmod *fs.FileMode, ifExists, symlinkNoFollow bool) error {
err := c.checkAllowed(copyCmd)
if err != nil {
return err
}
if chmod != nil && !c.ftrs.UseChmod {
return fmt.Errorf("COPY --chmod is not supported in this version")
}
c.nonSaveCommand()
artifact, err := domain.ParseArtifact(artifactName)
if err != nil {
return errors.Wrapf(err, "parse artifact name %s", artifactName)
}
prefix, cmdID, err := c.newVertexMeta(ctx, false, false, false, nil)
if err != nil {
return err
}
mts, err := c.buildTarget(ctx, artifact.Target.String(), platform, allowPrivileged, passArgs, buildArgs, false, copyCmd, cmdID, nil)
if err != nil {
return errors.Wrapf(err, "apply build %s", artifact.Target.String())
}
if artifact.Target.IsLocalInternal() {
artifact.Target.LocalPath = c.mts.Final.Target.LocalPath
}
// Grab the artifacts state in the dep states, after we've built it.
relevantDepState := mts.Final
// Copy.
c.mts.Final.MainState, err = llbutil.CopyOp(ctx,
relevantDepState.ArtifactsState, []string{artifact.Artifact},
c.mts.Final.MainState, dest, true, isDir, keepTs, c.copyOwner(keepOwn, chown), chmod, ifExists, symlinkNoFollow,
c.ftrs.UseCopyLink,
llb.WithCustomNamef(
"%sCOPY %s%s%s%s%s %s",
prefix,
strIf(isDir, "--dir "),
strIf(ifExists, "--if-exists "),
strIf(symlinkNoFollow, "--symlink-no-follow "),
joinWrap(buildArgs, "(", " ", ") "),
artifact.String(),
dest))
if err != nil {
return errors.Wrapf(err, "copyOp CopyArtifact")
}
return nil
}
// CopyClassical applies the earthly COPY command, with classical args.
func (c *Converter) CopyClassical(ctx context.Context, srcs []string, dest string, isDir bool, keepTs bool, keepOwn bool, chown string, chmod *fs.FileMode, ifExists bool) error {
err := c.checkAllowed(copyCmd)
if err != nil {
return err
}
if chmod != nil && !c.ftrs.UseChmod {
return fmt.Errorf("COPY --chmod is not supported in this version")
}
var srcState pllb.State
if c.ftrs.UseCopyIncludePatterns {
// create a new src state with the include patterns set (if this isn't done the entire context will be copied)
srcStateFactory := addIncludePathAndSharedKeyHint(c.buildContextFactory, srcs)
srcState = c.opt.LocalStateCache.getOrConstruct(srcStateFactory)
} else {
srcState = c.buildContextFactory.Construct()
}
c.nonSaveCommand()
prefix, _, err := c.newVertexMeta(ctx, false, false, false, nil)
if err != nil {
return err
}
c.mts.Final.MainState, err = llbutil.CopyOp(ctx,
srcState,
srcs,
c.mts.Final.MainState, dest, true, isDir, keepTs, c.copyOwner(keepOwn, chown), chmod, ifExists, false,
c.ftrs.UseCopyLink,
llb.WithCustomNamef(
"%sCOPY %s%s%s %s",
prefix,
strIf(isDir, "--dir "),
strIf(ifExists, "--if-exists "),
strings.Join(srcs, " "),
dest))
if err != nil {
return errors.Wrapf(err, "copyOp CopyClassical")
}
return nil
}
// ConvertRunOpts represents a set of options needed for the RUN command.
type ConvertRunOpts struct {
CommandName string
Args []string
Locally bool
Mounts []string
Secrets []string
WithEntrypoint bool
WithShell bool
Privileged bool
NoNetwork bool
Push bool
Transient bool
WithSSH bool
NoCache bool
Interactive bool
InteractiveKeep bool
InteractiveSaveFiles []debuggercommon.SaveFilesSettings
WithAWSCredentials bool
OIDCInfo *oidcutil.AWSOIDCInfo
RawOutput bool
// Internal.
shellWrap shellWrapFun
extraRunOpts []llb.RunOption
statePrep func(context.Context, pllb.State) (pllb.State, error)
}
// Run applies the earthly RUN command.
func (c *Converter) Run(ctx context.Context, opts ConvertRunOpts) error {
err := c.checkAllowed(runCmd)
if err != nil {
return err
}
c.nonSaveCommand()
for _, state := range c.persistentCacheDirs {
opts.extraRunOpts = append(opts.extraRunOpts, state.RunOption)
}
_, err = c.internalRun(ctx, opts)
return err
}
// RunExitCode executes a run for the purpose of determining the exit code of the command. This can be used in conditionals.
func (c *Converter) RunExitCode(ctx context.Context, opts ConvertRunOpts) (int, error) {
err := c.checkAllowed(runCmd)
if err != nil {
return 0, err
}
c.nonSaveCommand()
for _, state := range c.persistentCacheDirs {
opts.extraRunOpts = append(opts.extraRunOpts, state.RunOption)
}
var exitCodeFile string
if opts.Locally {
exitCodeDir, err := os.MkdirTemp(os.TempDir(), "earthlyexitcode")
if err != nil {
return 0, errors.Wrap(err, "create temp dir")
}
exitCodeFile = filepath.Join(exitCodeDir, "/exit_code")
c.opt.CleanCollection.Add(func() error {
return os.RemoveAll(exitCodeDir)
})
} else {
exitCodeFile = "/tmp/earthly_if_statement_exit_code"
prefix, _, err := c.newVertexMeta(ctx, false, false, true, nil)
if err != nil {
return 0, err
}
opts.statePrep = func(ctx context.Context, state pllb.State) (pllb.State, error) {
return state.File(
pllb.Mkdir("/run", 0755, llb.WithParents(true)),
llb.WithCustomNamef(
"%smkdir %s",
prefix, "/run"),
), nil
}
}
// Perform execution, but append the command with the right shell incantation that
// causes it to output the exit code to a file. This is done via the shellWrap.
opts.shellWrap = withShellAndEnvVarsExitCode(exitCodeFile)
opts.WithShell = true // force shell wrapping
state, err := c.internalRun(ctx, opts)
if err != nil {
return 0, err
}
var codeDt []byte
if opts.Locally {
codeDt, err = os.ReadFile(exitCodeFile)
if err != nil {
return 0, errors.Wrap(err, "read exit code file")
}
} else {
ref, err := llbutil.StateToRef(
ctx, c.opt.GwClient, state, c.opt.NoCache,
c.platr, c.opt.CacheImports.AsSlice())
if err != nil {
return 0, errors.Wrap(err, "run exit code state to ref")
}
codeDt, err = ref.ReadFile(ctx, gwclient.ReadRequest{
Filename: exitCodeFile,
})
if err != nil {
return 0, errors.Wrap(err, "read exit code")
}
}
exitCode, err := strconv.ParseInt(string(bytes.TrimSpace(codeDt)), 10, 64)
if err != nil {
return 0, errors.Wrap(err, "parse exit code as int")
}
return int(exitCode), err
}
// RunExpression runs an expression and returns its output. The run is transient - any state created
// is not used in subsequent commands.
func (c *Converter) RunExpression(ctx context.Context, expressionName string, opts ConvertRunOpts) (string, error) {
for _, state := range c.persistentCacheDirs {
opts.extraRunOpts = append(opts.extraRunOpts, state.RunOption)
}
return c.runCommand(ctx, expressionName, true, opts)
}
// RunCommand runs a command and returns its output. The run is transient - any state created
// is not used in subsequent commands.
func (c *Converter) RunCommand(ctx context.Context, commandName string, opts ConvertRunOpts) (string, error) {
for _, state := range c.persistentCacheDirs {
opts.extraRunOpts = append(opts.extraRunOpts, state.RunOption)
}
return c.runCommand(ctx, commandName, false, opts)
}
func (c *Converter) runCommand(ctx context.Context, outputFileName string, isExpression bool, opts ConvertRunOpts) (string, error) {
err := c.checkAllowed(runCmd)
if err != nil {
return "", err
}
c.nonSaveCommand()
if !opts.WithShell {
panic("runCommand must be called WithShell")
}
if opts.Locally == opts.Transient {
panic("runCommand Transient xor Locally must be true")
}
if opts.shellWrap != nil {
panic("runCommand expects shellWrap to be nil (as it is overridden)")
}
var outputFile string
if opts.Locally {
outputDir, err := os.MkdirTemp(os.TempDir(), "earthlyexproutput")
if err != nil {
return "", errors.Wrap(err, "create temp dir")
}
outputFile = filepath.Join(outputDir, "/output")
c.opt.CleanCollection.Add(func() error {
return os.RemoveAll(outputDir)
})
} else {
srcBuildArgDir := "/run/buildargs"
prefix, _, err := c.newVertexMeta(ctx, false, false, true, nil)
if err != nil {
return "", err
}
outputFile = path.Join(srcBuildArgDir, outputFileName)
opts.statePrep = func(ctx context.Context, state pllb.State) (pllb.State, error) {
return state.File(
pllb.Mkdir(srcBuildArgDir, 0777, llb.WithParents(true)), // Mkdir is performed as root even when USER is set; we must use 0777
llb.WithCustomNamef(
"%smkdir %s",
prefix, srcBuildArgDir),
), nil
}
}
if isExpression {
opts.shellWrap = expressionWithShellAndEnvVarsOutput(outputFile)
} else {
opts.shellWrap = withShellAndEnvVarsOutput(outputFile)
}
state, err := c.internalRun(ctx, opts)
if err != nil {
return "", err
}
var outputDt []byte
if opts.Locally {
outputDt, err = os.ReadFile(outputFile)
if err != nil {
return "", errors.Wrap(err, "read output file")
}
} else {
ref, err := llbutil.StateToRef(
ctx, c.opt.GwClient, state, c.opt.NoCache,
c.platr, c.opt.CacheImports.AsSlice())
if err != nil {
return "", errors.Wrapf(err, "build arg state to ref")
}
outputDt, err = ref.ReadFile(ctx, gwclient.ReadRequest{Filename: outputFile})
if err != nil {
return "", errors.Wrapf(err, "non constant build arg read request")
}
}
// echo adds a trailing \n.
outputDt = bytes.TrimSuffix(outputDt, []byte("\n"))
return string(outputDt), nil
}
// SaveArtifact applies the earthly SAVE ARTIFACT command.
func (c *Converter) SaveArtifact(ctx context.Context, saveFrom, saveTo, saveAsLocalTo string, keepTs, keepOwn, ifExists, symlinkNoFollow, force, isPush bool) (retErr error) {
err := c.checkAllowed(saveArtifactCmd)
if err != nil {
return err
}
absSaveFrom, err := llbutil.Abs(ctx, c.mts.Final.MainState, saveFrom)
if err != nil {
return err
}
if absSaveFrom == "/" || absSaveFrom == "" {
return errors.New("cannot save root dir as artifact")
}
saveToAdjusted := saveTo
if saveTo == "" || saveTo == "." || strings.HasSuffix(saveTo, "/") {
saveFromRelative := path.Join(".", absSaveFrom)
saveToAdjusted = path.Join(saveTo, path.Base(saveFromRelative))
}
saveToD, saveToF := splitWildcards(saveToAdjusted)
var artifactPath string
if saveToF == "" {
artifactPath = saveToAdjusted
} else {
saveToAdjusted = fmt.Sprintf("%s/", saveToD)
artifactPath = path.Join(saveToAdjusted, saveToF)
}
artifact := domain.Artifact{
Target: c.mts.Final.Target,
Artifact: artifactPath,
}
own := "root:root"
if keepOwn {
own = ""
}
// pcState is a separate state from the main state
// which persists any files cached via CACHE command.
// This is necessary so those cached files can be
// accessed within the CopyOps below.
pcState := c.persistCache(c.mts.Final.MainState)
prefix, cmdID, err := c.newVertexMeta(ctx, false, false, false, nil)
if err != nil {
return err
}
cmd, ok := c.opt.Logbus.Run().Command(cmdID)
if !ok {
return errors.New("command not found")
}
cmd.SetName(fmt.Sprintf("SAVE ARTIFACT %s", saveFrom))
defer func() {
cmd.SetEndError(retErr)
}()
c.mts.Final.ArtifactsState, err = llbutil.CopyOp(ctx,
pcState, []string{saveFrom}, c.mts.Final.ArtifactsState,
saveToAdjusted, true, true, keepTs, own, nil, ifExists, symlinkNoFollow,
c.ftrs.UseCopyLink,
llb.WithCustomNamef(
"%sSAVE ARTIFACT %s%s%s %s",
prefix,
strIf(ifExists, "--if-exists "),
strIf(symlinkNoFollow, "--symlink-no-follow "),
saveFrom,
artifact.String()))
if err != nil {
return errors.Wrapf(err, "copyOp save artifact")
}
if saveAsLocalTo != "" {
separateArtifactsState := c.platr.Scratch()
if isPush {
pushState := c.persistCache(c.mts.Final.RunPush.State)
prefix, _, err := c.newVertexMeta(ctx, false, false, false, nil)
if err != nil {
return err
}
separateArtifactsState, err = llbutil.CopyOp(ctx,
pushState, []string{saveFrom}, separateArtifactsState,
saveToAdjusted, true, true, keepTs, "root:root", nil, ifExists, symlinkNoFollow,
c.ftrs.UseCopyLink,
llb.WithCustomNamef(
"%sSAVE ARTIFACT %s%s%s %s AS LOCAL %s",
prefix,
strIf(ifExists, "--if-exists "),
strIf(symlinkNoFollow, "--symlink-no-follow "),
saveFrom,
artifact.String(),
saveAsLocalTo))
if err != nil {
return errors.Wrapf(err, "copyOp save artifact as local")
}
} else {
prefix, _, err := c.newVertexMeta(ctx, false, false, false, nil)
if err != nil {
return err
}
separateArtifactsState, err = llbutil.CopyOp(ctx,
pcState, []string{saveFrom}, separateArtifactsState,
saveToAdjusted, true, true, keepTs, "root:root", nil, ifExists, symlinkNoFollow,
c.ftrs.UseCopyLink,
llb.WithCustomNamef(
"%sSAVE ARTIFACT %s%s%s %s AS LOCAL %s",
prefix,
strIf(ifExists, "--if-exists "),
strIf(symlinkNoFollow, "--symlink-no-follow "),
saveFrom,
artifact.String(),
saveAsLocalTo))
if err != nil {
return errors.Wrapf(err, "copyOp save artifact as local")
}
}
c.mts.Final.SeparateArtifactsState = append(c.mts.Final.SeparateArtifactsState, separateArtifactsState)
saveAsLocalToAdj := saveAsLocalTo
if saveAsLocalToAdj == "." {
saveAsLocalToAdj = "./"
}
if !force {
canSave, err := c.canSave(ctx, saveAsLocalToAdj)
if err != nil {
return err
}
if !canSave {
if c.ftrs.RequireForceForUnsafeSaves {
return fmt.Errorf("unable to save to %s; path must be located under %s", saveAsLocalTo, c.target.LocalPath)
}
analytics.Count("breaking-change", "save-artifact-force-flag-required-warning")
c.opt.Console.Warnf("saving to path (%s) outside of current directory (%s) will require a --force flag in a future version", saveAsLocalTo, c.target.LocalPath)
}
}
saveLocal := states.SaveLocal{
DestPath: saveAsLocalToAdj,
ArtifactPath: artifactPath,
Index: len(c.mts.Final.SeparateArtifactsState) - 1,
IfExists: ifExists,
}
if c.ftrs.WaitBlock {
waitItem := newSaveArtifactLocal(saveLocal, c, c.opt.DoSaves)
c.waitBlock().AddItem(waitItem)
c.mts.Final.WaitItems = append(c.mts.Final.WaitItems, waitItem)
} else {
if isPush {
c.mts.Final.RunPush.SaveLocals = append(c.mts.Final.RunPush.SaveLocals, saveLocal)
} else {
c.mts.Final.SaveLocals = append(c.mts.Final.SaveLocals, saveLocal)
}
}
}
c.ranSave = true
c.markFakeDeps()
return nil