-
Notifications
You must be signed in to change notification settings - Fork 339
Expand file tree
/
Copy pathexecutor.go
More file actions
1345 lines (1153 loc) · 44.7 KB
/
executor.go
File metadata and controls
1345 lines (1153 loc) · 44.7 KB
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 job provides management of the phases of execution of a
// Buildkite job.
//
// It is intended for internal use by buildkite-agent only.
package job
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/buildkite/agent/v3/agent/plugin"
"github.com/buildkite/agent/v3/api"
"github.com/buildkite/agent/v3/env"
"github.com/buildkite/agent/v3/internal/file"
"github.com/buildkite/agent/v3/internal/job/hook"
"github.com/buildkite/agent/v3/internal/osutil"
"github.com/buildkite/agent/v3/internal/redact"
"github.com/buildkite/agent/v3/internal/replacer"
"github.com/buildkite/agent/v3/internal/secrets"
"github.com/buildkite/agent/v3/internal/shell"
"github.com/buildkite/agent/v3/internal/shellscript"
"github.com/buildkite/agent/v3/internal/tempfile"
"github.com/buildkite/agent/v3/logger"
"github.com/buildkite/agent/v3/process"
"github.com/buildkite/agent/v3/tracetools"
"github.com/buildkite/go-pipeline"
"github.com/buildkite/roko"
"github.com/buildkite/shellwords"
)
// Executor represents the phases of execution in a Buildkite Job. It's run as
// a sub-process of the buildkite-agent and finishes at the conclusion of a job.
//
// Historically (prior to v3) the job executor was a shell script, but was ported
// to Go for portability and testability.
type Executor struct {
// ExecutorConfig provides the executor configuration
ExecutorConfig
// Shell is the shell environment for the executor
shell *shell.Shell
// The checkout directory root
checkoutRoot *os.Root
// Plugins to use
plugins []*plugin.Plugin
// Plugin checkouts from the plugin phases
pluginCheckouts []*pluginCheckout
// Directories to clean up at end of job execution
cleanupDirs []string
// A channel to track cancellation
cancelMu sync.Mutex
cancelCh chan struct{}
cancelled bool
// redactors for the job logs. The will be populated with values both from environment variable and through the Job API.
// In order for the latter to happen, a reference is passed into the the Job API server as well
redactors *replacer.Mux
}
// New returns a new executor instance
func New(conf ExecutorConfig) *Executor {
return &Executor{
ExecutorConfig: conf,
cancelCh: make(chan struct{}),
redactors: replacer.NewMux(),
}
}
// Run the job and return the exit code
func (e *Executor) Run(ctx context.Context) (exitCode int) {
// Create a context to use for cancelation of the job
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Start with stdout and stderr as their usual selves.
stdout, stderr := io.Writer(os.Stdout), io.Writer(os.Stderr)
// The shell environment is initially the current environment, needed for setupRedactors.
environ := env.FromSlice(os.Environ())
// Create a logger to stderr that can be used for things prior to the
// redactor setup.
// Be careful not to log customer secrets here!
tempLog := shell.NewWriterLogger(stderr, true, e.DisabledWarnings)
// setup the redactors here once and for the life of the executor
// they will be flushed at the end of each hook
preRedactedStdout, preRedactedLogger := e.setupRedactors(tempLog, environ, stdout, stderr)
// Check if not nil to allow for tests to overwrite shell.
if e.shell == nil {
sh, err := shell.New(
shell.WithDebug(e.Debug),
shell.WithEnv(environ),
shell.WithLogger(preRedactedLogger), // shell -> logger -> redactor -> real stderr
shell.WithInterruptSignal(e.CancelSignal),
shell.WithPTY(e.RunInPty),
shell.WithStdout(preRedactedStdout), // shell -> redactor -> real stdout
shell.WithSignalGracePeriod(e.SignalGracePeriod),
shell.WithTraceContextCodec(e.TraceContextCodec),
)
if err != nil {
fmt.Printf("Error creating shell: %v", err)
return 1
}
e.shell = sh
}
var err error
span, ctx, stopper := e.startTracing(ctx)
defer stopper()
defer func() { span.FinishWithError(err) }()
// Listen for cancellation. Once ctx is cancelled, some tasks can run
// afterwards during the signal grace period. These use graceCtx.
graceCtx, graceCancel := WithGracePeriod(ctx, e.SignalGracePeriod)
defer graceCancel()
go func() {
<-e.cancelCh
e.shell.Commentf("Received cancellation signal, interrupting")
cancel()
}()
// Create an empty env for us to keep track of our env changes in
e.shell.Env = env.FromSlice(os.Environ())
// Initialize the job API, iff the experiment is enabled. Noop otherwise
if e.JobAPI {
cleanup, err := e.startJobAPI()
if err != nil {
e.shell.Errorf("Error setting up Job API: %v", err)
return 1
}
defer cleanup()
} else {
e.shell.OptionalWarningf("job-api-disabled", "The Job API has been disabled. Features like automatic redaction of secrets and polyglot hooks will either not work or have degraded functionality")
}
// Tear down the environment (and fire pre-exit hook) before we exit
defer func() {
// We strive to let the executor tear-down happen whether or not the job
// (and thus ctx) is cancelled, so it can run during the grace period.
if err := e.tearDown(graceCtx); err != nil {
e.shell.Errorf("Error tearing down job executor: %v", err)
// this gets passed back via the named return
exitCode = shell.ExitCode(err)
}
}()
if env, ok := e.shell.Env.Get("BUILDKITE_USE_GITHUB_APP_GIT_CREDENTIALS"); ok && env == "true" {
// On hosted compute, we are not going to use SSH keys, so we don't need to scan for SSH keys.
//
// TODO: This may break non-GitHub SSH checkout for other SCMs on self-hosted compute.
// So we need to revise this before enabling the code access app on self-hosted agents.
e.SSHKeyscan = false
err := e.configureGitCredentialHelper(ctx)
if err != nil {
e.shell.Errorf("Error configuring git credential helper: %v", err)
return shell.ExitCode(err)
}
// so that the new credential helper will be used for all github urls
err = e.configureHTTPSInsteadOfSSH(ctx)
if err != nil {
e.shell.Errorf("Error configuring https instead of ssh: %v", err)
return shell.ExitCode(err)
}
}
// Initialize the environment, a failure here will still call the tearDown
if err = e.setUp(ctx); err != nil {
e.shell.Errorf("Error setting up job executor: %v", err)
return shell.ExitCode(err)
}
// Execute the job phases in order
var phaseErr error
if e.includePhase("plugin") {
phaseErr = e.preparePlugins()
if phaseErr == nil {
phaseErr = e.PluginPhase(ctx)
}
}
if phaseErr == nil && e.includePhase("checkout") {
phaseErr = e.CheckoutPhase(ctx)
} else {
// For various reasons we should still pretend there was a checkout
// phase. It might have happened in a different container, or may have
// been disabled, but there can be important files at the checkout path,
// e.g. local hooks, which require a checkout root.
checkoutDir, exists := e.shell.Env.Get("BUILDKITE_BUILD_CHECKOUT_PATH")
if exists {
_ = e.shell.Chdir(checkoutDir)
}
root, err := os.OpenRoot(e.shell.Getwd())
if err != nil {
phaseErr = cmp.Or(phaseErr, err)
}
if root != nil {
e.checkoutRoot = root
runtime.AddCleanup(e, func(r *os.Root) { r.Close() }, root)
}
}
if phaseErr == nil && e.includePhase("plugin") {
phaseErr = e.VendoredPluginPhase(ctx)
}
if phaseErr == nil && e.includePhase("command") {
var commandErr error
phaseErr, commandErr = e.CommandPhase(ctx)
/*
Five possible states at this point:
Pre-command failed
Pre-command succeeded, command failed, post-command succeeded
Pre-command succeeded, command failed, post-command failed
Pre-command succeeded, command succeeded, post-command succeeded
Pre-command succeeded, command succeeded, post-command failed
All states should attempt an artifact upload, to change this would
not be backwards compatible.
At this point, if commandErr != nil, BUILDKITE_COMMAND_EXIT_STATUS
has been set.
*/
// Add command exit error info. This is distinct from a phaseErr, which is
// an error from the hook/job logic. These are both good to report but
// shouldn't override each other in reporting.
if commandErr != nil {
e.shell.Printf("user command error: %v", commandErr)
span.RecordError(commandErr)
}
// Only upload artifacts as part of the command phase.
// The artifacts might be relevant for debugging job timeouts, so it can
// run during the grace period.
if err := e.artifactPhase(graceCtx); err != nil {
e.shell.Errorf("%v", err)
if commandErr != nil {
// Both command and upload have errored.
//
// Ignore the agent upload error, rely on the phase and command
// error reporting below.
} else {
// Only upload has errored, report its error.
return shell.ExitCode(err)
}
}
}
// Phase errors are where something of ours broke that merits a big red error
// this won't include command failures, as we view that as more in the user space
if phaseErr != nil {
err = phaseErr
e.shell.Errorf("%v", phaseErr)
return shell.ExitCode(phaseErr)
}
// Use the exit code from the command phase
exitStatus, _ := e.shell.Env.Get("BUILDKITE_COMMAND_EXIT_STATUS")
exitStatusCode, _ := strconv.Atoi(exitStatus)
return exitStatusCode
}
func (e *Executor) includePhase(phase string) bool {
if len(e.Phases) == 0 {
return true
}
return slices.Contains(e.Phases, phase)
}
// Cancel interrupts any running shell processes and causes the job to stop.
func (e *Executor) Cancel() error {
// Closing e.cancelCh broadcasts to any goroutine receiving that the job is
// being cancelled/stopped.
// Double-closing a channel is a panic, so guard it with a bool and a mutex.
e.cancelMu.Lock()
defer e.cancelMu.Unlock()
if e.cancelled {
return errors.New("already cancelled")
}
e.cancelled = true
e.shell.Env.Set("BUILDKITE_JOB_CANCELLED", "true")
close(e.cancelCh)
return nil
}
const (
HookScopeAgent = "agent"
HookScopeRepository = "repository"
HookScopePlugin = "plugin"
)
type HookConfig struct {
Name string
Scope string
Path string
Env *env.Environment
SpanAttributes map[string]string
PluginName string
}
func (e *Executor) tracingImplementationSpecificHookScope(scope string) string {
if e.TracingBackend != tracetools.BackendDatadog {
return scope
}
// In olden times, when the datadog tracing backend was written, these hook scopes were named "local" and "global"
// We need to maintain backwards compatibility with the old names for span attribute reasons, so we map them here
switch scope {
case HookScopeRepository:
return "local"
case HookScopeAgent:
return "global"
default:
return scope
}
}
// executeHook runs a hook script with the hookRunner
func (e *Executor) executeHook(ctx context.Context, hookCfg HookConfig) error {
scopeName := e.tracingImplementationSpecificHookScope(hookCfg.Scope)
spanName := e.implementationSpecificSpanName(fmt.Sprintf("%s %s hook", scopeName, hookCfg.Name), "hook.execute")
span, ctx := tracetools.StartSpanFromContext(ctx, spanName, e.TracingBackend)
var err error
defer func() { span.FinishWithError(err) }()
span.AddAttributes(map[string]string{
"hook.type": scopeName,
"hook.name": hookCfg.Name,
"hook.command": hookCfg.Path,
})
span.AddAttributes(hookCfg.SpanAttributes)
hookName := hookCfg.Scope
if hookCfg.PluginName != "" {
hookName += " " + hookCfg.PluginName
}
hookName += " " + hookCfg.Name
if !osutil.FileExists(hookCfg.Path) {
if e.Debug {
e.shell.Commentf("Skipping %s hook, no script at \"%s\"", hookName, hookCfg.Path)
}
return nil
}
e.shell.Headerf("Running %s hook", hookName)
hookType, err := hook.Type(hookCfg.Path)
if err != nil {
return fmt.Errorf("determining hook type for %q hook: %w", hookName, err)
}
switch hookType {
case hook.TypeScript:
if runtime.GOOS == "windows" {
// We use shebangs to figure out how to run scripts, and Windows has no way to interpret a shebang
// ie, on linux, we can just point the OS to a file of some sort and say "run that", and as part of that it will try to
// read a shebang, and run the script using the interpreter specified. Windows can't do this, so we can't run scripts
// directly on Windows
// Potentially there's something that we could do with file extensions, but that's a bit of a minefield, and would
// probably mean that we have to have a list of blessed hook runtimes on windows only... or something.
// Regardless: not supported right now, or potentially ever.
sheb, _ := shellscript.ShebangLine(hookCfg.Path) // we know this won't error because it must have a shebang to be a script
err := fmt.Errorf(`when trying to run the hook at %q, the agent found that it was a script with a shebang that isn't for a shellscripting language - in this case, %q.
Hooks of this kind are unfortunately not supported on Windows, as we have no way of interpreting a shebang on Windows`, hookCfg.Path, sheb)
return err
}
// It's a script, and we can rely on the OS to figure out how to run it (because we're not on windows), so run it
// directly without wrapping
if err := e.runUnwrappedHook(ctx, hookName, hookCfg); err != nil {
return fmt.Errorf("running %q script hook: %w", hookName, err)
}
return nil
case hook.TypeBinary:
// It's a binary, so we'll just run it directly, no wrapping needed or possible
if err := e.runUnwrappedHook(ctx, hookName, hookCfg); err != nil {
return fmt.Errorf("running %q binary hook: %w", hookName, err)
}
return nil
case hook.TypeShell:
// It's definitely a shell script, wrap it so that we can snaffle the changed environment variables
if err := e.runWrappedShellScriptHook(ctx, hookName, hookCfg); err != nil {
return fmt.Errorf("running %q shell hook: %w", hookName, err)
}
return nil
default:
return fmt.Errorf("unknown hook type %q for %q hook", hookType, hookName)
}
}
func (e *Executor) runUnwrappedHook(ctx context.Context, _ string, hookCfg HookConfig) error {
environ := hookCfg.Env.Copy()
environ.Set("BUILDKITE_HOOK_PHASE", hookCfg.Name)
environ.Set("BUILDKITE_HOOK_PATH", hookCfg.Path)
environ.Set("BUILDKITE_HOOK_SCOPE", hookCfg.Scope)
if err := e.shell.Command(hookCfg.Path).Run(ctx, shell.WithExtraEnv(environ)); err != nil {
return err
}
// Passing an empty env changes through because in polyglot hook we can't detect
// env change.
// But we call this method anyway because a hook might use buildkite-agent env set to update environment.
e.applyEnvironmentChanges(hook.EnvChanges{})
return nil
}
func logOpenedHookInfo(l shell.Logger, debug bool, hookName, path string) {
switch {
case runtime.GOOS == "linux":
procPath, err := file.OpenedBy(l, debug, path)
if err != nil {
l.Errorf("The %s hook failed to run because it was already open. We couldn't find out what process had the hook open", hookName)
} else {
l.Errorf("The %s hook failed to run the %s process has the hook file open", hookName, procPath)
}
case osutil.FileExists("/dev/fd"):
isOpened, err := file.IsOpened(l, debug, path)
if err == nil {
if isOpened {
l.Errorf("The %s hook failed to run because it was opened by this buildkite-agent")
} else {
l.Errorf("The %s hook failed to run because it was opened by another process")
}
break
}
fallthrough
default:
l.Errorf("The %s hook failed to run because it was opened", hookName)
}
}
func logMissingHookInfo(l shell.Logger, hookName, wrapperPath string) {
// It's unlikely, but possible, that the script wrapper was spontaneously
// deleted or corrupted (it's usually in /tmp, which is fair game).
// A common setup error is to try to run a Bash hook in a container or other
// environment without Bash (or Bash is not in the expected location).
shebang, err := shellscript.ShebangLine(wrapperPath)
if err != nil {
// It's reasonable to assume the script wrapper was spontaneously
// deleted, or had something equally horrible happen to it.
l.Errorf("The %s hook failed to run - perhaps the wrapper script %q was spontaneously deleted", hookName, wrapperPath)
return
}
interpreter := strings.TrimPrefix(shebang, "#!")
if interpreter == "" {
// Either the script never had a shebang, or the script was
// spontaneously corrupted.
// If it didn't have a shebang line, we defaulted to using Bash, and if
// that's not present we already logged a warning.
// If it was spontaneously corrupted, we should expect a different error
// than ENOENT.
return
}
l.Errorf("The %s hook failed to run - perhaps the script interpreter %q is missing", hookName, interpreter)
}
func (e *Executor) runWrappedShellScriptHook(ctx context.Context, hookName string, hookCfg HookConfig) error {
defer e.redactors.Flush()
script, err := hook.NewWrapper(hook.WithPath(hookCfg.Path))
if err != nil {
e.shell.Errorf("Error creating hook script: %v", err)
return err
}
defer script.Close()
cleanHookPath := hookCfg.Path
// Show a relative path if we can
if strings.HasPrefix(hookCfg.Path, e.shell.Getwd()) {
var err error
if cleanHookPath, err = filepath.Rel(e.shell.Getwd(), hookCfg.Path); err != nil {
cleanHookPath = hookCfg.Path
}
}
// Show the hook runner in debug, but the thing being run otherwise 💅🏻
if e.Debug {
e.shell.Commentf("A hook runner was written to %q with the following:", script.Path())
e.shell.Promptf("%s", process.FormatCommand(script.Path(), nil))
} else {
e.shell.Promptf("%s", process.FormatCommand(cleanHookPath, []string{}))
}
const maxHookRetry = 30
// Run the wrapper script
err = roko.NewRetrier(
roko.WithStrategy(roko.Constant(100*time.Millisecond)),
roko.WithMaxAttempts(maxHookRetry),
).DoWithContext(ctx, func(r *roko.Retrier) error {
// Run the script and only retry on ETXTBSY.
// This error occurs because of an unavoidable race between forking
// (which acquires open file descriptors of the parent process) and
// writing an executable (the script wrapper).
// See https://github.com/golang/go/issues/22315.
script, err := e.shell.Script(script.Path(), e.HooksShell)
if err != nil {
r.Break()
return err
}
err = script.Run(ctx, shell.ShowPrompt(false), shell.WithExtraEnv(hookCfg.Env))
if errors.Is(err, syscall.ETXTBSY) {
return err
}
r.Break()
return err
})
if err != nil {
exitCode := shell.ExitCode(err)
e.shell.Env.Set("BUILDKITE_LAST_HOOK_EXIT_STATUS", strconv.Itoa(exitCode))
// If the hook exited with a non-zero exit code, then we should pass that back to the executor
// so it may inform the Buildkite API
if shell.IsExitError(err) {
return &shell.ExitError{
Code: exitCode,
Err: fmt.Errorf("The %s hook exited with status %d", hookName, exitCode),
}
}
switch {
case errors.Is(err, syscall.ETXTBSY):
// If the underlying error is _still_ ETXTBSY, then inspect the file
// to see what process had it open for write, to log something helpful
logOpenedHookInfo(e.shell.Logger, e.Debug, hookName, script.Path())
case errors.Is(err, syscall.ENOENT):
// Unfortunately the wrapping os.PathError's Path is always the
// program we tried to exec, even if the missing file/directory was
// actually the interpreter specified on the shebang line.
// Try to figure out which part is missing from the wrapper.
logMissingHookInfo(e.shell.Logger, hookName, script.Path())
}
return err
}
// Store the last hook exit code for subsequent steps
e.shell.Env.Set("BUILDKITE_LAST_HOOK_EXIT_STATUS", "0")
// Get changed environment
changes, err := script.Changes()
if err != nil {
// Could not compute the changes in environment or working directory
// for some reason...
switch err.(type) {
case *hook.ExitError:
// ...because the hook called exit(), tsk we ignore any changes
// since we can't discern them but continue on with the job
break
default:
// ...because something else happened, report it and stop the job
return fmt.Errorf("Failed to get environment: %w", err)
}
} else {
// Hook exited successfully (and not early!) We have an environment and
// wd change we can apply to our subsequent phases
e.applyEnvironmentChanges(changes)
}
return nil
}
// 1. Apply env changes -> e.shell.Env
// 2. Refresh executor config (e.shell.Env might change via Job API)
// 3. Log all changes.
func (e *Executor) applyEnvironmentChanges(changes hook.EnvChanges) {
if afterWd, err := changes.GetAfterWd(); err == nil {
if afterWd != e.shell.Getwd() {
_ = e.shell.Chdir(afterWd)
}
}
e.shell.Env.Apply(changes.Diff)
e.addOutputRedactors()
// First, let see any of the environment variables are supposed
// to change the job configuration at run time.
// Note this func mutates/refreshes the ExecutorConfig too.
executorConfigEnvChanges := e.ReadFromEnvironment(e.shell.Env)
// Print out the env vars that changed. As we go through each
// one, we'll determine if it was a special environment variable
// that has changed the executor configuration at runtime.
//
// If it's "special", we'll show the value it was changed to -
// otherwise we'll hide it. Since we don't know if an
// environment variable contains sensitive information (such as
// THIRD_PARTY_API_KEY) we'll just not show any values for
// anything not controlled by us.
executorConfigEnvChangesLogged := make(map[string]bool)
for k, v := range changes.Diff.Added {
if _, ok := executorConfigEnvChanges[k]; ok {
executorConfigEnvChangesLogged[k] = true
e.shell.Commentf("%s is now %q", k, v)
} else {
e.shell.Commentf("%s added", k)
}
}
for k, v := range changes.Diff.Changed {
if _, ok := executorConfigEnvChanges[k]; ok {
executorConfigEnvChangesLogged[k] = true
e.shell.Commentf("%s was %q and is now %q", k, v.Old, v.New)
} else {
e.shell.Commentf("%s changed", k)
}
}
for k, v := range changes.Diff.Removed {
if _, ok := executorConfigEnvChanges[k]; ok {
executorConfigEnvChangesLogged[k] = true
e.shell.Commentf("%s is now %q", k, v)
} else {
e.shell.Commentf("%s removed", k)
}
}
// When an env var is changed via buildkite-agent env set instead,
// it might not appear in the script "changes".
for k, v := range executorConfigEnvChanges {
if !executorConfigEnvChangesLogged[k] {
e.shell.Commentf("%s is now %q", k, v)
}
}
}
// Should be called whenever we updated our e.shell.Env.
func (e *Executor) addOutputRedactors() {
// reset output redactors based on new environment variable values
toRedact, short, err := redact.Vars(e.RedactedVars, e.shell.Env.DumpPairs())
if err != nil {
e.shell.OptionalWarningf("bad-redacted-vars", "Couldn't match environment variable names against redacted-vars: %v", err)
}
if len(short) > 0 {
slices.Sort(short)
e.shell.OptionalWarningf("short-redacted-vars", "Some variables have values below minimum length (%d bytes) and will not be redacted: %s", redact.LengthMin, strings.Join(short, ", "))
}
// This should probably be a reset rather than a mutate.
// But does a particular string stop being a secret if we learn new secret strings?
// For produence, we use Add.
for _, pair := range toRedact {
e.redactors.Add(pair.Value)
}
}
func (e *Executor) hasGlobalHook(name string) bool {
_, err := hook.Find(nil, e.HooksPath, name)
if err == nil {
return true
}
for _, additional := range e.AdditionalHooksPaths {
_, err := hook.Find(nil, additional, name)
if err == nil {
return true
}
}
return false
}
// find all matching paths for the specified hook
func (e *Executor) getAllGlobalHookPaths(name string) ([]string, error) {
hooks := []string{}
p, err := hook.Find(nil, e.HooksPath, name)
if err != nil {
if !os.IsNotExist(err) {
return []string{}, err
}
} else {
hooks = append(hooks, p)
}
for _, additional := range e.AdditionalHooksPaths {
p, err = hook.Find(nil, additional, name)
// as this is an additional hook, don't fail if there's a problem here
if err == nil {
hooks = append(hooks, p)
}
}
return hooks, nil
}
// Executes a global hook if one exists
func (e *Executor) executeGlobalHook(ctx context.Context, name string) error {
allHooks, err := e.getAllGlobalHookPaths(name)
if err != nil {
return nil
}
for _, h := range allHooks {
err = e.executeHook(ctx, HookConfig{
Scope: HookScopeAgent,
Name: name,
Path: h,
})
if err != nil {
return err
}
}
return nil
}
// Returns the absolute path to a local hook, or os.ErrNotExist if none is found
func (e *Executor) localHookPath(name string) (string, error) {
// The local hooks dir must exist within the checkout root.
dir := filepath.Join(".buildkite", "hooks")
return hook.Find(e.checkoutRoot, dir, name)
}
func (e *Executor) hasLocalHook(name string) bool {
_, err := e.localHookPath(name)
return err == nil
}
// Executes a local hook
func (e *Executor) executeLocalHook(ctx context.Context, name string) error {
localHookPath, err := e.localHookPath(name)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// If the hook doesn't exist, that's fine, we'll just skip it
if e.Debug {
e.shell.Commentf("Local hook %s doesn't exist: %s, skipping", name, err)
}
return nil
}
// This should not be possible under the current state of the code base
// as hook.Find only returns os.ErrNotExist but that assumes implementation
// details that could change in the future
return err
}
// For high-security configs, we allow the disabling of local hooks.
localHooksEnabled := e.LocalHooksEnabled
// Allow hooks to disable local hooks by setting BUILDKITE_NO_LOCAL_HOOKS=true
noLocalHooks, _ := e.shell.Env.Get("BUILDKITE_NO_LOCAL_HOOKS")
if noLocalHooks == "true" || noLocalHooks == "1" {
localHooksEnabled = false
}
if !localHooksEnabled {
return fmt.Errorf("Refusing to run %s, local hooks are disabled", localHookPath)
}
return e.executeHook(ctx, HookConfig{
Scope: HookScopeRepository,
Name: name,
Path: localHookPath,
})
}
func dirForAgentName(agentName string) string {
badCharsPattern := regexp.MustCompile("[[:^alnum:]]")
return badCharsPattern.ReplaceAllString(agentName, "-")
}
func dirForRepository(repository string) string {
badCharsPattern := regexp.MustCompile("[[:^alnum:]]")
return badCharsPattern.ReplaceAllString(repository, "-")
}
// Given a repository, it will add the host to the set of SSH known_hosts on the machine
func addRepositoryHostToSSHKnownHosts(ctx context.Context, sh *shell.Shell, repository string) {
if osutil.FileExists(repository) {
return
}
knownHosts, err := findKnownHosts(sh)
if err != nil {
sh.Warningf("Failed to find SSH known_hosts file: %v", err)
return
}
if err = knownHosts.AddFromRepository(ctx, repository); err != nil {
sh.Warningf("Error adding to known_hosts: %v", err)
return
}
}
// setUp is run before all the phases run. It's responsible for initializing the
// job environment
func (e *Executor) setUp(ctx context.Context) error {
span, ctx := tracetools.StartSpanFromContext(ctx, "environment", e.TracingBackend)
var err error
defer func() { span.FinishWithError(err) }()
// Add the $BUILDKITE_BIN_PATH to the $PATH if we've been given one
if e.BinPath != "" {
path, _ := e.shell.Env.Get("PATH")
// BinPath goes last so we don't disturb other tools
e.shell.Env.Set("PATH", fmt.Sprintf("%s%c%s", path, os.PathListSeparator, e.BinPath))
}
// Set a BUILDKITE_BUILD_CHECKOUT_PATH unless one exists already. We do this here
// so that the environment will have a checkout path to work with
if _, exists := e.shell.Env.Get("BUILDKITE_BUILD_CHECKOUT_PATH"); !exists {
if e.BuildPath == "" {
return fmt.Errorf("Must set either a BUILDKITE_BUILD_PATH or a BUILDKITE_BUILD_CHECKOUT_PATH")
}
e.shell.Env.Set("BUILDKITE_BUILD_CHECKOUT_PATH",
filepath.Join(e.BuildPath, dirForAgentName(e.AgentName), e.OrganizationSlug, e.PipelineSlug))
}
// The job runner sets BUILDKITE_IGNORED_ENV with any keys that were ignored
// or overwritten. This shows a warning to the user so they don't get confused
// when their environment changes don't seem to do anything
if ignored, _ := e.shell.Env.Get("BUILDKITE_IGNORED_ENV"); ignored != "" {
e.shell.Headerf("Detected protected environment variables")
e.shell.Commentf("Your pipeline environment has protected environment variables set. " +
"These can only be set via hooks, plugins or the agent configuration.")
for env := range strings.SplitSeq(ignored, ",") {
e.shell.Warningf("Ignored %s", env)
}
e.shell.Printf("^^^ +++")
}
if e.Debug {
e.shell.Headerf("Buildkite environment variables")
for _, envar := range e.shell.Env.ToSlice() {
if strings.HasPrefix(envar, "BUILDKITE_AGENT_ACCESS_TOKEN=") {
e.shell.Printf("BUILDKITE_AGENT_ACCESS_TOKEN=******************")
} else if strings.HasPrefix(envar, "BUILDKITE") || strings.HasPrefix(envar, "CI") || strings.HasPrefix(envar, "PATH") {
e.shell.Printf("%s", strings.ReplaceAll(envar, "\n", "\\n"))
}
}
}
// Disable any interactive Git/SSH prompting
e.shell.Env.Set("GIT_TERMINAL_PROMPT", "0")
// Fetch and set secrets before environment hook execution
if e.Secrets != "" {
if err := e.fetchAndSetSecrets(ctx); err != nil {
return fmt.Errorf("failed to fetch secrets for job: %w", err)
}
}
// It's important to do this before checking out plugins, in case you want
// to use the global environment hook to whitelist the plugins that are
// allowed to be used.
err = e.executeGlobalHook(ctx, "environment")
return err
}
// fetchAndSetSecrets handles secrets fetching and processing directly
func (e *Executor) fetchAndSetSecrets(ctx context.Context) error {
if e.Secrets == "" {
return nil // No secrets to process
}
// Parse secrets from JSON using the pipeline.Secret type
var pipelineSecrets []*pipeline.Secret
if err := json.Unmarshal([]byte(e.Secrets), &pipelineSecrets); err != nil {
return fmt.Errorf("failed to parse secrets JSON: %w", err)
}
if len(pipelineSecrets) == 0 {
return nil // No secrets to process
}
e.shell.Headerf("Preparing secrets")
// Extract keys for fetching
keys := make([]string, len(pipelineSecrets))
for i, ps := range pipelineSecrets {
keys[i] = ps.Key
}
// Create API client for fetching secrets.
secretLogger := logger.NewBuffer()
apiClient := api.NewClient(secretLogger, api.Config{
Endpoint: e.shell.Env.GetString("BUILDKITE_AGENT_ENDPOINT", ""),
Token: e.shell.Env.GetString("BUILDKITE_AGENT_ACCESS_TOKEN", ""),
})
// Fetch all secrets
fetchedSecrets, errs := secrets.FetchSecrets(ctx, secretLogger, apiClient, e.JobID, keys, 10)
if len(errs) > 0 {
var errorMsg strings.Builder
for _, err := range errs {
fmt.Fprintf(&errorMsg, "\n %s", err)
}
return errors.New(errorMsg.String())
}
secretValuesByKey := make(map[string]string, len(fetchedSecrets))
for _, fetchedSecret := range fetchedSecrets {
secretValuesByKey[fetchedSecret.Key] = fetchedSecret.Value
}
// Set environment variables and register for redaction
for _, pipelineSecret := range pipelineSecrets {
if secretValue, exists := secretValuesByKey[pipelineSecret.Key]; exists {
// Always register the secret value for redaction regardless of env var setting
e.redactors.Add(secretValue)
// Set the environment variable only if environment_variable is specified and non-nil
if pipelineSecret.EnvironmentVariable != "" {
// Check if the environment variable is protected
if env.IsProtected(pipelineSecret.EnvironmentVariable) {
return fmt.Errorf("secret %q cannot set protected environment variable %q", pipelineSecret.Key, pipelineSecret.EnvironmentVariable)
}
var alreadySet bool
_, alreadySet = e.shell.Env.Get(pipelineSecret.EnvironmentVariable)
e.shell.Env.Set(pipelineSecret.EnvironmentVariable, secretValue)
if alreadySet {
e.shell.Commentf("Secret %s added as environment variable %s (overwritten)", pipelineSecret.Key, pipelineSecret.EnvironmentVariable)
} else {
e.shell.Commentf("Secret %s added as environment variable %s", pipelineSecret.Key, pipelineSecret.EnvironmentVariable)
}
}
}
}
return nil
}
// tearDown is called before the executor exits, even on error
func (e *Executor) tearDown(ctx context.Context) error {
span, ctx := tracetools.StartSpanFromContext(ctx, "pre-exit", e.TracingBackend)
var err error
defer func() { span.FinishWithError(err) }()
// In vanilla agent usage, there's always a command phase.
// But over in agent-stack-k8s, which splits the agent phases among
// containers (the checkout phase happens in a separate container to the
// command phase), the two phases have different environments.
// Unfortunately pre-exit hooks are often not written with this split in
// mind.
if e.includePhase("command") {
if err = e.executeGlobalHook(ctx, "pre-exit"); err != nil {
return err
}
if err = e.executeLocalHook(ctx, "pre-exit"); err != nil {
return err
}
if err = e.executePluginHook(ctx, "pre-exit", e.pluginCheckouts); err != nil {
return err
}
}
// Support deprecated BUILDKITE_DOCKER* env vars
if hasDeprecatedDockerIntegration(e.shell) {
return tearDownDeprecatedDockerIntegration(ctx, e.shell)
}
for _, dir := range e.cleanupDirs {
if err = os.RemoveAll(dir); err != nil {
e.shell.Warningf("Failed to remove dir %s: %v", dir, err)
}
}
return nil