-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathinterpreter.go
2239 lines (2061 loc) · 75.2 KB
/
interpreter.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 (
"context"
"fmt"
"net"
"os"
"path"
"slices"
"strconv"
"strings"
"sync"
"github.com/earthly/earthly/analytics"
"github.com/earthly/earthly/ast/command"
"github.com/earthly/earthly/ast/commandflag"
"github.com/earthly/earthly/ast/hint"
"github.com/earthly/earthly/ast/spec"
"github.com/earthly/earthly/buildcontext"
"github.com/earthly/earthly/conslogging"
debuggercommon "github.com/earthly/earthly/debugger/common"
"github.com/earthly/earthly/domain"
"github.com/earthly/earthly/internal/version"
"github.com/earthly/earthly/util/flagutil"
"github.com/earthly/earthly/util/oidcutil"
"github.com/earthly/earthly/util/platutil"
"github.com/earthly/earthly/util/shell"
"github.com/earthly/earthly/variables"
"github.com/docker/go-connections/nat"
"github.com/google/uuid"
"github.com/jessevdk/go-flags"
"github.com/pkg/errors"
)
const maxCommandRenameWarnings = 3
var errCannotAsync = errors.New("cannot run async operation")
// use as default to differentiate between an un specified string flag and a specified flag with empty value
var defaultZeroStringFlag = uuid.NewString()
// Interpreter interprets Earthly AST's into calls to the converter.
type Interpreter struct {
converter *Converter
target domain.Target
isBase bool
isWith bool
pushOnlyAllowed bool
local bool
allowPrivileged bool
withDocker *WithDockerOpt
withDockerRan bool
parallelConversion bool
console conslogging.ConsoleLogger
gitLookup *buildcontext.GitLookup
interactiveSaveFiles []debuggercommon.SaveFilesSettings
}
func newInterpreter(c *Converter, t domain.Target, allowPrivileged, parallelConversion bool, console conslogging.ConsoleLogger, gitLookup *buildcontext.GitLookup) *Interpreter {
return &Interpreter{
converter: c,
target: t,
allowPrivileged: allowPrivileged,
parallelConversion: parallelConversion,
console: console,
gitLookup: gitLookup,
}
}
// Run interprets the commands in the given Earthfile AST, for a specific target.
func (i *Interpreter) Run(ctx context.Context, ef spec.Earthfile) (retErr error) {
defer func() {
if retErr != nil {
i.converter.RecordTargetFailure(ctx, retErr)
}
}()
if i.target.Target == "base" {
i.isBase = true
err := i.handleBlock(ctx, ef.BaseRecipe)
i.isBase = false
return err
}
for _, t := range ef.Targets {
if t.Name == i.target.Target {
return i.handleTarget(ctx, t)
}
}
return i.errorf(ef.SourceLocation, "target %s not found", i.target.Target)
}
func (i *Interpreter) handleTarget(ctx context.Context, t spec.Target) error {
ctx = ContextWithSourceLocation(ctx, t.SourceLocation)
// Apply implicit FROM +base
err := i.converter.From(ctx, "+base", platutil.DefaultPlatform, i.allowPrivileged, false, nil)
if err != nil {
return i.wrapError(err, t.SourceLocation, "apply FROM")
}
return i.handleBlock(ctx, t.Recipe)
}
func (i *Interpreter) handleBlock(ctx context.Context, b spec.Block) error {
prevWasArgLike := true // not exactly true, but makes the logic easier
for index, stmt := range b {
if i.parallelConversion && prevWasArgLike {
err := i.handleBlockParallel(ctx, b, index)
if err != nil {
return err
}
}
err := i.handleStatement(ctx, stmt)
if err != nil {
return err
}
prevWasArgLike = i.isArgLike(stmt.Command)
}
return nil
}
func (i *Interpreter) handleBlockParallel(ctx context.Context, b spec.Block, startIndex int) error {
if i.local {
// Don't do any preemptive execution for LOCALLY targets.
return nil
}
// Look ahead of the execution and fire off asynchronous builds for mentioned targets,
// as long as they don't have variable args $(...).
for index := startIndex; index < len(b); index++ {
stmt := b[index]
if stmt.Command != nil {
switch stmt.Command.Name {
case command.Arg, command.Locally, command.From, command.FromDockerfile, command.Let, command.Set:
// Cannot do any further parallel builds - these commands need to be
// executed to ensure that they don't impact the outcome. As such,
// commands following these cannot be executed preemptively.
return nil
case command.Build:
err := i.handleBuild(ctx, *stmt.Command, true)
if err != nil {
if errors.Is(err, errCannotAsync) {
continue // no biggie
}
return err
}
case command.Copy:
// TODO
}
} else if stmt.With != nil {
switch stmt.With.Command.Name {
case command.Docker:
// TODO
}
} else if stmt.If != nil || stmt.For != nil || stmt.Wait != nil || stmt.Try != nil {
// Cannot do any further parallel builds - these commands need to be
// executed to ensure that they don't impact the outcome. As such,
// commands following these cannot be executed preemptively.
return nil
} else {
return i.errorf(stmt.SourceLocation, "unexpected statement type")
}
}
return nil
}
func (i *Interpreter) handleStatement(ctx context.Context, stmt spec.Statement) error {
ctx = ContextWithSourceLocation(ctx, stmt.SourceLocation)
if stmt.Command != nil {
return i.handleCommand(ctx, *stmt.Command)
}
if stmt.With != nil {
return i.handleWith(ctx, *stmt.With)
}
if stmt.If != nil {
return i.handleIf(ctx, *stmt.If)
}
if stmt.For != nil {
return i.handleFor(ctx, *stmt.For)
}
if stmt.Wait != nil {
return i.handleWait(ctx, *stmt.Wait)
}
if stmt.Try != nil {
return i.handleTry(ctx, *stmt.Try)
}
return i.errorf(stmt.SourceLocation, "unexpected statement type")
}
func (i *Interpreter) handleCommand(ctx context.Context, cmd spec.Command) (err error) {
// The AST should not be modified by any operation. This is a consistency check.
argsCopy := flagutil.GetArgsCopy(cmd)
defer func() {
if err != nil {
return
}
if len(argsCopy) != len(cmd.Args) {
err = i.errorf(cmd.SourceLocation, "internal error: args were modified in command handling")
return
}
for index, arg := range cmd.Args {
if arg != argsCopy[index] {
err = i.errorf(cmd.SourceLocation, "internal error: args were modified in command handling")
return
}
}
}()
ctx = ContextWithSourceLocation(ctx, cmd.SourceLocation)
analytics.Count("cmd", cmd.Name)
if i.isWith {
switch cmd.Name {
case command.Docker:
return i.handleWithDocker(ctx, cmd)
default:
return i.errorf(cmd.SourceLocation, "unexpected WITH command %s", cmd.Name)
}
}
switch cmd.Name {
case command.From:
return i.handleFrom(ctx, cmd)
case command.Run:
return i.handleRun(ctx, cmd)
case command.FromDockerfile:
return i.handleFromDockerfile(ctx, cmd)
case command.Locally:
return i.handleLocally(ctx, cmd)
case command.Copy:
return i.handleCopy(ctx, cmd)
case command.SaveArtifact:
return i.handleSaveArtifact(ctx, cmd)
case command.SaveImage:
return i.handleSaveImage(ctx, cmd)
case command.Build:
return i.handleBuild(ctx, cmd, false)
case command.Workdir:
return i.handleWorkdir(ctx, cmd)
case command.User:
return i.handleUser(ctx, cmd)
case command.Cmd:
return i.handleCmd(ctx, cmd)
case command.Entrypoint:
return i.handleEntrypoint(ctx, cmd)
case command.Expose:
return i.handleExpose(ctx, cmd)
case command.Volume:
return i.handleVolume(ctx, cmd)
case command.Env:
return i.handleEnv(ctx, cmd)
case command.Arg:
return i.handleArg(ctx, cmd)
case command.Let:
return i.handleLet(ctx, cmd)
case command.Set:
return i.handleSet(ctx, cmd)
case command.Label:
return i.handleLabel(ctx, cmd)
case command.GitClone:
return i.handleGitClone(ctx, cmd)
case command.HealthCheck:
return i.handleHealthcheck(ctx, cmd)
case command.Add:
return i.handleAdd(ctx, cmd)
case command.StopSignal:
return i.handleStopsignal(ctx, cmd)
case command.OnBuild:
return i.handleOnbuild(ctx, cmd)
case command.Shell:
return i.handleShell(ctx, cmd)
case command.Command:
return i.handleUserCommand(ctx, cmd)
case command.Function:
return i.handleFunction(ctx, cmd)
case command.Do:
return i.handleDo(ctx, cmd)
case command.Import:
return i.handleImport(ctx, cmd)
case command.Cache:
return i.handleCache(ctx, cmd)
case command.Host:
return i.handleHost(ctx, cmd)
case command.Project:
return i.handleProject(ctx, cmd)
default:
return i.errorf(cmd.SourceLocation, "unexpected command %q", cmd.Name)
}
}
func (i *Interpreter) handleWith(ctx context.Context, with spec.WithStatement) error {
i.isWith = true
err := i.handleCommand(ctx, with.Command)
i.isWith = false
if err != nil {
return err
}
if i.withDocker != nil && len(with.Body) > 1 {
return i.errorf(with.SourceLocation, "only one command is allowed in WITH DOCKER and it has to be RUN")
}
err = i.handleBlock(ctx, with.Body)
if err != nil {
return err
}
i.withDocker = nil
if !i.withDockerRan {
return i.errorf(with.SourceLocation, "no RUN command found in WITH DOCKER")
}
i.withDockerRan = false
return nil
}
func (i *Interpreter) handleIf(ctx context.Context, ifStmt spec.IfStatement) error {
if i.pushOnlyAllowed {
return i.errorf(ifStmt.SourceLocation, "no non-push commands allowed after a --push")
}
isZero, err := i.handleIfExpression(ctx, ifStmt.Expression, ifStmt.ExecMode, ifStmt.SourceLocation)
if err != nil {
return err
}
if isZero {
return i.handleBlock(ctx, ifStmt.IfBody)
}
for _, elseIf := range ifStmt.ElseIf {
isZero, err = i.handleIfExpression(ctx, elseIf.Expression, elseIf.ExecMode, elseIf.SourceLocation)
if err != nil {
return err
}
if isZero {
return i.handleBlock(ctx, elseIf.Body)
}
}
if ifStmt.ElseBody != nil {
return i.handleBlock(ctx, *ifStmt.ElseBody)
}
return nil
}
func (i *Interpreter) handleIfExpression(ctx context.Context, expression []string, execMode bool, sl *spec.SourceLocation) (bool, error) {
if len(expression) < 1 {
return false, i.errorf(sl, "not enough arguments for IF")
}
opts := commandflag.IfOpts{}
args, err := flagutil.ParseArgsCleaned("IF", &opts, expression)
if err != nil {
return false, i.wrapError(err, sl, "invalid IF arguments %v", expression)
}
withShell := !execMode
for index, s := range opts.Secrets {
expanded, err := i.expandArgs(ctx, s, true, false)
if err != nil {
return false, i.wrapError(err, sl, "failed to expand IF secret %v", s)
}
opts.Secrets[index] = expanded
}
for index, m := range opts.Mounts {
expanded, err := i.expandArgs(ctx, m, false, false)
if err != nil {
return false, i.wrapError(err, sl, "failed to expand IF mount %v", m)
}
opts.Mounts[index] = expanded
}
// Note: Not expanding args for the expression itself, as that will be take care of by the shell.
var exitCode int
runOpts := ConvertRunOpts{
CommandName: "IF",
Args: args,
Locally: i.local,
Mounts: opts.Mounts,
Secrets: opts.Secrets,
WithShell: withShell,
Privileged: opts.Privileged,
WithSSH: opts.WithSSH,
NoCache: opts.NoCache,
Transient: !i.local,
}
exitCode, err = i.converter.RunExitCode(ctx, runOpts)
if err != nil {
return false, i.wrapError(err, sl, "apply IF")
}
return (exitCode == 0), nil
}
func (i *Interpreter) handleFor(ctx context.Context, forStmt spec.ForStatement) error {
if !i.converter.ftrs.ForIn {
return i.errorf(forStmt.SourceLocation, "the FOR command is not supported in this version")
}
variable, instances, err := i.handleForArgs(ctx, forStmt.Args, forStmt.SourceLocation)
if err != nil {
return err
}
for _, instance := range instances {
err = i.converter.SetArg(ctx, variable, instance)
if err != nil {
return i.wrapError(err, forStmt.SourceLocation, "set %s=%s", variable, instance)
}
err = i.handleBlock(ctx, forStmt.Body)
if err != nil {
return err
}
err = i.converter.UnsetArg(ctx, variable)
if err != nil {
return i.wrapError(err, forStmt.SourceLocation, "unset %s", variable)
}
}
return nil
}
func (i *Interpreter) handleForArgs(ctx context.Context, forArgs []string, sl *spec.SourceLocation) (string, []string, error) {
opts := commandflag.NewForOpts()
args, err := flagutil.ParseArgsCleaned("FOR", &opts, forArgs)
if err != nil {
return "", nil, i.wrapError(err, sl, "invalid FOR arguments %v", forArgs)
}
if len(args) < 3 {
return "", nil, i.errorf(sl, "not enough arguments for FOR")
}
if args[1] != "IN" {
return "", nil, i.errorf(sl, "expected IN, got %s", args[1])
}
variable := args[0]
runOpts := ConvertRunOpts{
CommandName: "FOR",
Args: args[2:],
Locally: i.local,
Mounts: opts.Mounts,
Secrets: opts.Secrets,
WithShell: true,
Privileged: opts.Privileged,
WithSSH: opts.WithSSH,
NoCache: opts.NoCache,
Transient: !i.local,
}
output, err := i.converter.RunExpression(ctx, variable, runOpts)
if err != nil {
return "", nil, i.wrapError(err, sl, "apply FOR ... IN")
}
instances := strings.FieldsFunc(output, func(r rune) bool {
return strings.ContainsRune(opts.Separators, r)
})
return variable, instances, nil
}
func (i *Interpreter) handleWait(ctx context.Context, waitStmt spec.WaitStatement) error {
if !i.converter.ftrs.WaitBlock {
return i.errorf(waitStmt.SourceLocation, "the WAIT command is not supported in this version")
}
if !i.converter.ftrs.ReferencedSaveOnly {
return i.errorf(waitStmt.SourceLocation, "the WAIT command requires the --referenced-save-only feature")
}
if len(waitStmt.Args) != 0 {
return i.errorf(waitStmt.SourceLocation, "WAIT does not accept any options")
}
err := i.converter.PushWaitBlock(ctx)
if err != nil {
return err
}
err = i.handleBlock(ctx, waitStmt.Body)
if err != nil {
return err
}
return i.converter.PopWaitBlock(ctx)
}
func (i *Interpreter) handleTry(ctx context.Context, tryStmt spec.TryStatement) error {
if !i.converter.ftrs.TryFinally {
return i.errorf(tryStmt.SourceLocation, "the TRY/CATCH/FINALLY commands are not supported in this version")
}
if len(tryStmt.TryBody) == 0 {
return i.errorf(tryStmt.SourceLocation, "TRY body is empty")
}
if len(tryStmt.TryBody) != 1 {
return i.errorf(tryStmt.SourceLocation, "TRY body can (currently) only contain a single command")
}
if tryStmt.CatchBody != nil {
return i.errorf(tryStmt.SourceLocation, "TRY/FINALLY doesn't (currently) support CATCH statements")
}
isRun := tryStmt.TryBody[0].Command != nil && tryStmt.TryBody[0].Command.Name == "RUN"
isDocker := tryStmt.TryBody[0].With != nil && tryStmt.TryBody[0].With.Command.Name == "DOCKER"
if isDocker {
if len(tryStmt.TryBody[0].With.Body) != 1 {
return i.errorf(tryStmt.SourceLocation, "TRY body can (currently) only contain a single command")
}
} else if !isRun {
return i.errorf(tryStmt.SourceLocation, "TRY body must (currently) be a RUN command (or a RUN inside a WITH DOCKER)")
}
saveArtifacts := []debuggercommon.SaveFilesSettings{}
if tryStmt.FinallyBody != nil {
for _, cmd := range *tryStmt.FinallyBody {
if cmd.Command == nil || cmd.Command.Name != "SAVE ARTIFACT" {
return i.errorf(tryStmt.SourceLocation, "CATCH/FINALLY body only (currently) supports SAVE ARTIFACT ... AS LOCAL commands; got %s", cmd.Command.Name)
}
opts := commandflag.SaveArtifactOpts{}
args, err := flagutil.ParseArgsCleaned("SAVE ARTIFACT", &opts, flagutil.GetArgsCopy(*cmd.Command))
if err != nil {
return i.wrapError(err, cmd.Command.SourceLocation, "invalid SAVE ARTIFACT arguments %v", cmd.Command.Args)
}
if opts.KeepTs || opts.KeepOwn || opts.SymlinkNoFollow || opts.Force {
return i.wrapError(err, cmd.Command.SourceLocation, "only the SAVE ARTIFACT --if-exists option is allowed in a TRY/FINALLY block: %v", cmd.Command.Args)
}
saveFrom, _, saveAsLocalTo, ok := parseSaveArtifactArgs(args)
if !ok {
return i.errorf(cmd.Command.SourceLocation, "invalid arguments for SAVE ARTIFACT command: %v", cmd.Command.Args)
}
if strings.Contains(saveFrom, "*") {
return i.errorf(cmd.Command.SourceLocation, "TRY/CATCH/FINALLY does not (currently) support wildcard SAVE ARTIFACT paths")
}
if saveAsLocalTo == "" {
return i.errorf(cmd.Command.SourceLocation, "missing local name for SAVE ARTIFACT within TRY/CATCH/FINALLY")
}
if strings.Contains(saveAsLocalTo, "$") {
return i.errorf(cmd.Command.SourceLocation, "TRY/CATCH/FINALLY does not (currently) support expanding args for SAVE ARTIFACT paths")
}
destIsDir := strings.HasSuffix(saveAsLocalTo, "/") || saveAsLocalTo == "."
if destIsDir {
saveAsLocalTo = path.Join(saveAsLocalTo, path.Base(saveFrom))
}
saveArtifacts = append(saveArtifacts, debuggercommon.SaveFilesSettings{
Src: saveFrom,
Dst: saveAsLocalTo,
IfExists: opts.IfExists,
})
}
}
i.interactiveSaveFiles = saveArtifacts
// process TRY body (i.e. perform the single RUN
err := i.handleStatement(ctx, tryStmt.TryBody[0])
if err != nil {
return err
}
// process the FINALLY body (which will only happen when the try RUN succeeds, on failure
// the SAVE ARTIFACTS are handled by the embedded debugger that was run under the try)
if tryStmt.FinallyBody != nil {
for _, cmd := range *tryStmt.FinallyBody {
err := i.handleStatement(ctx, cmd)
if err != nil {
return err
}
}
}
return nil
}
// Commands -------------------------------------------------------------------
func (i *Interpreter) handleFrom(ctx context.Context, cmd spec.Command) error {
if i.pushOnlyAllowed {
return i.pushOnlyErr(cmd.SourceLocation)
}
opts := commandflag.FromOpts{}
args, err := flagutil.ParseArgsCleaned("FROM", &opts, flagutil.GetArgsCopy(cmd))
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "invalid FROM arguments %v", cmd.Args)
}
if len(args) != 1 {
if len(args) == 3 && args[1] == "AS" {
return i.errorf(cmd.SourceLocation, "AS not supported, use earthly targets instead")
}
if len(args) < 1 {
return i.errorf(cmd.SourceLocation, "invalid number of arguments for FROM: %s", cmd.Args)
}
}
imageName, err := i.expandArgs(ctx, args[0], true, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "unable to expand image name for FROM: %s", args[0])
}
expandedPlatform, err := i.expandArgs(ctx, opts.Platform, false, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "unable to expand platform for FROM: %s", opts.Platform)
}
platform, err := i.converter.platr.Parse(expandedPlatform)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "parse platform %s", expandedPlatform)
}
expandedBuildArgs, err := i.expandArgsSlice(ctx, opts.BuildArgs, true, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "unable to expand build args for FROM: %v", opts.BuildArgs)
}
expandedFlagArgs, err := i.expandArgsSlice(ctx, args[1:], true, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "unable to expand flag args for FROM: %v", args[1:])
}
parsedFlagArgs, err := variables.ParseFlagArgs(expandedFlagArgs)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "parse flag args")
}
expandedBuildArgs = append(parsedFlagArgs, expandedBuildArgs...)
allowPrivileged, err := i.getAllowPrivilegedTarget(imageName, opts.AllowPrivileged)
if err != nil {
return err
}
if !i.converter.ftrs.PassArgs && opts.PassArgs {
return i.errorf(cmd.SourceLocation, "the FROM --pass-args flag must be enabled with the VERSION --pass-args feature flag.")
}
i.local = false // FIXME https://github.com/earthly/earthly/issues/2044
err = i.converter.From(ctx, imageName, platform, allowPrivileged, opts.PassArgs, expandedBuildArgs)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "apply FROM %s", imageName)
}
return nil
}
func (i *Interpreter) getAllowPrivilegedTarget(targetName string, allowPrivileged bool) (bool, error) {
if !strings.Contains(targetName, "+") {
return false, nil
}
depTarget, err := domain.ParseTarget(targetName)
if err != nil {
return false, errors.Wrapf(err, "parse target name %s", targetName)
}
return i.getAllowPrivileged(depTarget, allowPrivileged)
}
func (i *Interpreter) getAllowPrivileged(depTarget domain.Target, allowPrivileged bool) (bool, error) {
if depTarget.IsRemote() {
return i.allowPrivileged && allowPrivileged, nil
}
if allowPrivileged {
i.console.Printf("the --allow-privileged flag has no effect when referencing a local target\n")
}
return i.allowPrivileged, nil
}
func (i *Interpreter) getAllowPrivilegedArtifact(artifactName string, allowPrivileged bool) (bool, error) {
artifact, err := domain.ParseArtifact(artifactName)
if err != nil {
return false, errors.Wrapf(err, "parse artifact name %s", artifactName)
}
return i.getAllowPrivileged(artifact.Target, allowPrivileged)
}
func (i *Interpreter) flagValModifierFuncWithContext(ctx context.Context) func(string, *flags.Option, *string) (*string, error) {
return func(flagName string, flagOpt *flags.Option, flagVal *string) (*string, error) {
if flagOpt.IsBool() && flagVal != nil {
newFlag, err := i.expandArgs(ctx, *flagVal, false, false)
if err != nil {
return nil, err
}
return &newFlag, nil
}
return flagVal, nil
}
}
func (i *Interpreter) handleRun(ctx context.Context, cmd spec.Command) error {
if len(cmd.Args) < 1 {
return i.errorf(cmd.SourceLocation, "not enough arguments for RUN")
}
opts := commandflag.RunOpts{OIDC: defaultZeroStringFlag}
args, err := flagutil.ParseArgsWithValueModifierCleaned("RUN", &opts, flagutil.GetArgsCopy(cmd), i.flagValModifierFuncWithContext(ctx))
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "invalid RUN arguments %v", cmd.Args)
}
withShell := !cmd.ExecMode
if opts.WithDocker {
opts.Privileged = true
}
if !opts.Push && i.pushOnlyAllowed {
return i.errorf(cmd.SourceLocation, "no non-push commands allowed after a --push")
}
// TODO: In the bracket case, should flags be outside of the brackets?
for index, s := range opts.Secrets {
expanded, err := i.expandArgs(ctx, s, true, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "failed to expand secrets arg in RUN: %s", s)
}
opts.Secrets[index] = expanded
}
for index, m := range opts.Mounts {
expanded, err := i.expandArgs(ctx, m, false, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "failed to expand mount arg in RUN: %s", m)
}
opts.Mounts[index] = expanded
}
// Note: Not expanding args for the run itself, as that will be take care of by the shell.
if opts.Privileged && !i.allowPrivileged {
return i.errorf(cmd.SourceLocation, "Permission denied: unwilling to run privileged command; did you reference a remote Earthfile without the --allow-privileged flag?")
}
var noNetwork bool
if opts.Network != "" {
if !i.converter.ftrs.NoNetwork {
return i.errorf(cmd.SourceLocation, "the RUN --network=none flag must be enabled with the VERSION --no-network feature flag.")
}
if opts.Network != "none" {
return i.errorf(cmd.SourceLocation, "invalid network value %s; only \"none\" is currently supported", opts.Network)
}
noNetwork = true
}
if opts.WithAWS && !i.converter.opt.Features.RunWithAWS {
return i.errorf(cmd.SourceLocation, "RUN --aws requires the --run-with-aws feature flag")
}
awsOIDCInfo, err := i.handleOIDC(ctx, &cmd, &opts)
if err != nil {
return err
}
if opts.RawOutput && !i.converter.opt.Features.RawOutput {
return i.errorf(cmd.SourceLocation, "RUN --raw-output requires the --raw-output feature flag")
}
if i.withDocker == nil {
if opts.WithDocker {
return i.errorf(cmd.SourceLocation, "--with-docker is obsolete. Please use WITH DOCKER ... RUN ... END instead")
}
opts := ConvertRunOpts{
CommandName: cmd.Name,
Args: args,
Locally: i.local,
Mounts: opts.Mounts,
Secrets: opts.Secrets,
WithShell: withShell,
WithEntrypoint: opts.WithEntrypoint,
Privileged: opts.Privileged,
NoNetwork: noNetwork,
Push: opts.Push,
WithSSH: opts.WithSSH,
NoCache: opts.NoCache,
Interactive: opts.Interactive,
InteractiveKeep: opts.InteractiveKeep,
InteractiveSaveFiles: i.interactiveSaveFiles,
WithAWSCredentials: opts.WithAWS,
OIDCInfo: awsOIDCInfo,
RawOutput: opts.RawOutput,
}
err = i.converter.Run(ctx, opts)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "apply RUN")
}
if opts.Push && !i.converter.ftrs.WaitBlock {
i.pushOnlyAllowed = true
}
} else {
if i.withDockerRan {
return i.errorf(cmd.SourceLocation, "only one RUN command allowed in WITH DOCKER")
}
if opts.Push {
return i.errorf(cmd.SourceLocation, "RUN --push not allowed in WITH DOCKER")
}
i.withDocker.Mounts = opts.Mounts
i.withDocker.Secrets = opts.Secrets
i.withDocker.WithShell = withShell
i.withDocker.WithEntrypoint = opts.WithEntrypoint
i.withDocker.WithSSH = opts.WithSSH
i.withDocker.NoCache = opts.NoCache
i.withDocker.Interactive = opts.Interactive
i.withDocker.interactiveKeep = opts.InteractiveKeep
i.withDocker.WithAWSCredentials = opts.WithAWS
i.withDocker.OIDCInfo = awsOIDCInfo
// TODO: Could this be allowed in the future, if dynamic build args
// are expanded ahead of time?
allowParallel := true
for _, l := range i.withDocker.Loads {
if !isSafeAsyncBuildArgsKVStyle(l.BuildArgs) {
allowParallel = false
break
}
}
if i.local {
err = i.converter.WithDockerRunLocal(ctx, args, *i.withDocker, allowParallel)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "with docker run")
}
} else {
err = i.converter.WithDockerRun(ctx, args, *i.withDocker, allowParallel)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "with docker run")
}
}
i.withDockerRan = true
}
return nil
}
// handleOIDC parse the oidc string value into a struct
// Returns error if the value cannot be parsed of if the feature flag is not set
func (i *Interpreter) handleOIDC(ctx context.Context, cmd *spec.Command, opts *commandflag.RunOpts) (*oidcutil.AWSOIDCInfo, error) {
if opts.OIDC == defaultZeroStringFlag {
// oidc is not in use, set it to empty string just in case
opts.OIDC = ""
return nil, nil
}
if !i.converter.opt.Features.RunWithAWSOIDC {
return nil, i.errorf(cmd.SourceLocation, "RUN --aws-oidc requires the --run-with-aws-oidc feature flag")
}
if !opts.WithAWS {
return nil, i.errorf(cmd.SourceLocation, "RUN --oidc also requires the --aws RUN flag")
}
expanded, err := i.expandArgs(ctx, opts.OIDC, false, false)
if err != nil {
return nil, i.errorf(cmd.SourceLocation, "failed to expand oidc arg in RUN: %s", opts.OIDC)
}
opts.OIDC = expanded
// we currently only support oidc for AWS
awsInfo, err := oidcutil.ParseAWSOIDCInfo(opts.OIDC)
if err != nil {
return nil, i.errorf(cmd.SourceLocation, "invalid value for oidc flag: %v", err)
}
return awsInfo, nil
}
func (i *Interpreter) handleFromDockerfile(ctx context.Context, cmd spec.Command) error {
if i.pushOnlyAllowed {
return i.pushOnlyErr(cmd.SourceLocation)
}
opts := commandflag.FromDockerfileOpts{}
args, err := flagutil.ParseArgsCleaned("FROM DOCKERFILE", &opts, flagutil.GetArgsCopy(cmd))
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "invalid FROM DOCKERFILE arguments %v", cmd.Args)
}
if len(args) < 1 {
return i.errorf(cmd.SourceLocation, "invalid number of arguments for FROM DOCKERFILE")
}
if !i.converter.ftrs.AllowPrivilegedFromDockerfile && opts.AllowPrivileged {
return i.errorf(cmd.SourceLocation, "the FROM DOCKERFILE --allow-privileged flag must be enabled with the VERSION --allow-privileged-from-dockerfile feature flag.")
}
allowPrivileged := opts.AllowPrivileged && i.allowPrivileged
path, err := i.expandArgs(ctx, args[0], false, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "failed to expand FROM DOCKERFILE path arg %s", args[0])
}
_, parseErr := domain.ParseArtifact(path)
if parseErr != nil {
// Treat as context path, not artifact path.
path, err = i.expandArgs(ctx, args[0], false, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "failed to expand FROM DOCKERFILE path arg %s", args[0])
}
}
expandedBuildArgs, err := i.expandArgsSlice(ctx, opts.BuildArgs, true, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "failed to expand FROM DOCKERFILE build args %s", opts.BuildArgs)
}
expandedFlagArgs, err := i.expandArgsSlice(ctx, args[1:], true, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "failed to expand FROM DOCKERFILE flag args %s", args[1:])
}
parsedFlagArgs, err := variables.ParseFlagArgs(expandedFlagArgs)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "parse flag args")
}
expandedBuildArgs = append(parsedFlagArgs, expandedBuildArgs...)
expandedPlatform, err := i.expandArgs(ctx, opts.Platform, false, false)
if err != nil {
return i.errorf(cmd.SourceLocation, "failed to expand FROM DOCKERFILE platform %s", opts.Platform)
}
platform, err := i.converter.platr.Parse(expandedPlatform)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "parse platform %s", expandedPlatform)
}
expandedPath, err := i.expandArgs(ctx, opts.Path, false, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand path %s", opts.Path)
}
expandedTarget, err := i.expandArgs(ctx, opts.Target, false, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand target %s", opts.Target)
}
i.local = false
err = i.converter.FromDockerfile(ctx, path, expandedPath, expandedTarget, platform, allowPrivileged, expandedBuildArgs)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "from dockerfile")
}
return nil
}
func (i *Interpreter) handleLocally(ctx context.Context, cmd spec.Command) error {
if !i.allowPrivileged {
return i.errorf(cmd.SourceLocation, "Permission denied: unwilling to allow locally directive from remote Earthfile; did you reference a remote Earthfile without the --allow-privileged flag?")
}
if i.pushOnlyAllowed {
return i.pushOnlyErr(cmd.SourceLocation)
}
i.local = true
err := i.converter.Locally(ctx)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "apply LOCALLY")
}
return nil
}
func (i *Interpreter) handleCopy(ctx context.Context, cmd spec.Command) error {
if i.pushOnlyAllowed {
return i.pushOnlyErr(cmd.SourceLocation)
}
opts := commandflag.CopyOpts{}
args, err := flagutil.ParseArgsCleaned("COPY", &opts, flagutil.GetArgsCopy(cmd))
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "invalid COPY arguments %v", cmd.Args)
}
if len(args) < 2 {
return i.errorf(cmd.SourceLocation, "not enough COPY arguments %v", cmd.Args)
}
if opts.From != "" {
return i.errorf(cmd.SourceLocation, "COPY --from not implemented. Use COPY artifacts form instead")
}
srcs := args[:len(args)-1]
srcArtifacts := make([]domain.Artifact, len(srcs))
srcFlagArgs := make([][]string, len(srcs))
dest, err := i.expandArgs(ctx, args[len(args)-1], false, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand COPY args %v", args[len(args)-1])
}
expandedBuildArgs, err := i.expandArgsSlice(ctx, opts.BuildArgs, true, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand COPY buildargs %v", opts.BuildArgs)
}
expandedChown, err := i.expandArgs(ctx, opts.Chown, false, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand COPY chown: %v", opts.Chown)
}
var fileModeParsed *os.FileMode
if opts.Chmod != "" {
expandedMode, err := i.expandArgs(ctx, opts.Chmod, false, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand COPY chmod: %v", opts.Platform)
}
mask, err := strconv.ParseUint(expandedMode, 8, 32)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to parse COPY chmod: %v", opts.Platform)
}
mode := os.FileMode(uint32(mask))
fileModeParsed = &mode
}
expandedPlatform, err := i.expandArgs(ctx, opts.Platform, false, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand COPY platform: %v", opts.Platform)
}
platform, err := i.converter.platr.Parse(expandedPlatform)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "parse platform %s", expandedPlatform)
}
allClassical := true
allArtifacts := true
for index, src := range srcs {
var artifactSrc domain.Artifact
var parseErr error
if flagutil.IsInParamsForm(src) {
// COPY (<src> <flag-args>) ...
artifactStr, extraArgs, err := flagutil.ParseParams(src)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "parse params %s", src)
}
expandedArtifact, err := i.expandArgs(ctx, artifactStr, true, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand COPY artifact %s", artifactStr)
}
artifactSrc, parseErr = domain.ParseArtifact(expandedArtifact)
if parseErr != nil {
// Must parse in the params case.
return i.wrapError(err, cmd.SourceLocation, "parse artifact")
}
srcFlagArgs[index] = extraArgs
} else {
expandedSrc, err := i.expandArgs(ctx, src, true, false)
if err != nil {
return i.wrapError(err, cmd.SourceLocation, "failed to expand COPY src %s", src)
}
artifactSrc, parseErr = domain.ParseArtifact(expandedSrc)
}
// If it parses as an artifact, treat as artifact.
if parseErr == nil {
srcs[index] = artifactSrc.String()