-
Notifications
You must be signed in to change notification settings - Fork 85
/
main.go
1588 lines (1441 loc) · 51.6 KB
/
main.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 main
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/auth"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/build_event_publisher"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/workflow/config"
"github.com/buildbuddy-io/buildbuddy/server/remote_cache/cachetools"
"github.com/buildbuddy-io/buildbuddy/server/remote_cache/digest"
"github.com/buildbuddy-io/buildbuddy/server/util/bazel"
"github.com/buildbuddy-io/buildbuddy/server/util/bazelisk"
"github.com/buildbuddy-io/buildbuddy/server/util/flagutil"
"github.com/buildbuddy-io/buildbuddy/server/util/grpc_client"
"github.com/buildbuddy-io/buildbuddy/server/util/lockingbuffer"
"github.com/buildbuddy-io/buildbuddy/server/util/log"
"github.com/buildbuddy-io/buildbuddy/server/util/status"
"github.com/creack/pty"
"github.com/google/shlex"
"github.com/google/uuid"
"github.com/logrusorgru/aurora"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"gopkg.in/yaml.v2"
bespb "github.com/buildbuddy-io/buildbuddy/proto/build_event_stream"
repb "github.com/buildbuddy-io/buildbuddy/proto/remote_execution"
gitutil "github.com/buildbuddy-io/buildbuddy/server/util/git"
bspb "google.golang.org/genproto/googleapis/bytestream"
gstatus "google.golang.org/grpc/status"
)
const (
// buildbuddyBazelrcPath is the path where we write a bazelrc file to be
// applied to all bazel commands. The path is relative to the runner workspace
// root, which notably is not the same as the bazel workspace / git repo root.
//
// This bazelrc takes lower precedence than the workspace .bazelrc.
buildbuddyBazelrcPath = "buildbuddy.bazelrc"
// Name of the dir into which the repo is cloned.
repoDirName = "repo-root"
// Name of the bazel output base dir. This is written under the workspace
// so that it can be cleaned up when the workspace is cleaned up.
outputBaseDirName = "output-base"
defaultGitRemoteName = "origin"
forkGitRemoteName = "fork"
// Env vars set by workflow runner
// NOTE: These env vars are not populated for non-private repos.
buildbuddyAPIKeyEnvVarName = "BUILDBUDDY_API_KEY"
repoUserEnvVarName = "REPO_USER"
repoTokenEnvVarName = "REPO_TOKEN"
// Exit code placeholder used when a command doesn't return an exit code on its own.
noExitCode = -1
failedExitCodeName = "Failed"
// progressFlushInterval specifies how often we should flush
// each Bazel command's output while it is running.
progressFlushInterval = 1 * time.Second
// progressFlushThresholdBytes specifies how full the log buffer
// should be before we force a flush, regardless of the flush interval.
progressFlushThresholdBytes = 1_000
// Bazel binary constants
bazelBinaryName = "bazel"
bazeliskBinaryName = "bazelisk"
// ANSI codes for cases where the aurora equivalent is not supported by our UI
// (ex: aurora's "grayscale" mode results in some ANSI codes that we don't currently
// parse correctly).
ansiGray = "\033[90m"
ansiReset = "\033[0m"
)
var (
besBackend = flag.String("bes_backend", "", "gRPC endpoint for BuildBuddy's BES backend.")
cacheBackend = flag.String("cache_backend", "", "gRPC endpoint for BuildBuddy Cache.")
rbeBackend = flag.String("rbe_backend", "", "gRPC endpoint for BuildBuddy RBE.")
besResultsURL = flag.String("bes_results_url", "", "URL prefix for BuildBuddy invocation URLs.")
remoteInstanceName = flag.String("remote_instance_name", "", "Remote instance name used to retrieve patches.")
triggerEvent = flag.String("trigger_event", "", "Event type that triggered the action runner.")
pushedRepoURL = flag.String("pushed_repo_url", "", "URL of the pushed repo.")
pushedBranch = flag.String("pushed_branch", "", "Branch name of the commit to be checked out.")
commitSHA = flag.String("commit_sha", "", "Commit SHA to report statuses for.")
targetRepoURL = flag.String("target_repo_url", "", "URL of the target repo.")
targetBranch = flag.String("target_branch", "", "Branch to check action triggers against.")
targetCommitSHA = flag.String("target_commit_sha", "", "If set, target repo URL is checked out at the given commit instead of the tip of the branch.")
workflowID = flag.String("workflow_id", "", "ID of the workflow associated with this CI run.")
actionName = flag.String("action_name", "", "If set, run the specified action and *only* that action, ignoring trigger conditions.")
invocationID = flag.String("invocation_id", "", "If set, use the specified invocation ID for the workflow action. Ignored if action_name is not set.")
visibility = flag.String("visibility", "", "If set, use the specified value for VISIBILITY build metadata for the workflow invocation.")
bazelSubCommand = flag.String("bazel_sub_command", "", "If set, run the bazel command specified by these args and ignore all triggering and configured actions.")
patchDigests = flagutil.Slice("patch_digest", []string{}, "Digests of patches to apply to the repo after checkout. Can be specified multiple times to apply multiple patches.")
recordRunMetadata = flag.Bool("record_run_metadata", false, "Instead of running a target, extract metadata about it and report it in the build event stream.")
shutdownAndExit = flag.Bool("shutdown_and_exit", false, "If set, runs bazel shutdown with the configured bazel_command, and exits. No other commands are run.")
bazelCommand = flag.String("bazel_command", "", "Bazel command to use.")
bazelStartupFlags = flag.String("bazel_startup_flags", "", "Startup flags to pass to bazel. The value can include spaces and will be properly tokenized.")
extraBazelArgs = flag.String("extra_bazel_args", "", "Extra flags to pass to the bazel command. The value can include spaces and will be properly tokenized.")
debug = flag.Bool("debug", false, "Print additional debug information in the action logs.")
// Test-only flags
fallbackToCleanCheckout = flag.Bool("fallback_to_clean_checkout", true, "Fallback to cloning the repo from scratch if sync fails (for testing purposes only).")
shellCharsRequiringQuote = regexp.MustCompile(`[^\w@%+=:,./-]`)
)
type workspace struct {
// Whether the workspace setup phase duration and logs were reported as part
// of any action's logs yet.
reportedInitMetrics bool
// The machine's hostname.
hostname string
// The operating user's username.
username string
// The buildbuddy API key, or "" if none was found.
buildbuddyAPIKey string
// An invocation ID that should be forced, or "" if any is allowed.
forcedInvocationID string
// An error that occurred while setting up the workspace, which should be
// reported for all action logs instead of actually executing the action.
setupError error
// The start time of the setup phase.
startTime time.Time
// log contains logs from the workspace setup phase (cloning the git repo and
// deciding which actions to run), which are reported as part of the first
// action's logs.
log io.Writer
}
type buildEventReporter struct {
isWorkflow bool
apiKey string
bep *build_event_publisher.Publisher
log *invocationLog
invocationID string
startTime time.Time
cancelBackgroundFlush func()
mu sync.Mutex // protects(progressCount)
progressCount int32
}
func newBuildEventReporter(ctx context.Context, besBackend string, apiKey string, forcedInvocationID string, isWorkflow bool) (*buildEventReporter, error) {
iid := forcedInvocationID
if iid == "" {
var err error
iid, err = newUUID()
if err != nil {
return nil, err
}
}
bep, err := build_event_publisher.New(besBackend, apiKey, iid)
if err != nil {
return nil, status.UnavailableErrorf("failed to initialize build event publisher: %s", err)
}
bep.Start(ctx)
return &buildEventReporter{apiKey: apiKey, bep: bep, log: newInvocationLog(), invocationID: iid, isWorkflow: isWorkflow}, nil
}
func (r *buildEventReporter) InvocationID() string {
return r.invocationID
}
func (r *buildEventReporter) Publish(event *bespb.BuildEvent) error {
return r.bep.Publish(event)
}
type parsedBazelArgs struct {
cmd string
flags []string
patterns []string
}
func parseBazelArgs(cmd string) (*parsedBazelArgs, error) {
args, err := shlex.Split(cmd)
if err != nil {
return nil, err
}
if len(args) < 1 {
return nil, status.FailedPreconditionError("missing command")
}
parsedArgs := &parsedBazelArgs{
cmd: args[0],
}
for _, arg := range args[1:] {
if strings.HasPrefix(arg, "--") {
parsedArgs.flags = append(parsedArgs.flags, arg)
} else {
parsedArgs.patterns = append(parsedArgs.patterns, arg)
}
}
return parsedArgs, nil
}
func (r *buildEventReporter) Start(startTime time.Time) error {
if !r.startTime.IsZero() {
// Already started.
return nil
}
r.startTime = startTime
options := []string{}
if *besBackend != "" {
options = append(options, fmt.Sprintf("--bes_backend=%s'", *besBackend))
}
if r.apiKey != "" {
options = append(options, fmt.Sprintf("--remote_header='x-buildbuddy-api-key=%s'", r.apiKey))
}
optionsDescription := strings.Join(options, " ")
cmd := ""
patterns := []string{}
if !r.isWorkflow {
parsedArgs, err := parseBazelArgs(*bazelSubCommand)
if err != nil {
return err
}
cmd = parsedArgs.cmd
patterns = parsedArgs.patterns
}
startedEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_Started{Started: &bespb.BuildEventId_BuildStartedId{}}},
Children: []*bespb.BuildEventId{
{Id: &bespb.BuildEventId_BuildMetadata{BuildMetadata: &bespb.BuildEventId_BuildMetadataId{}}},
{Id: &bespb.BuildEventId_ChildInvocationsConfigured{ChildInvocationsConfigured: &bespb.BuildEventId_ChildInvocationsConfiguredId{}}},
{Id: &bespb.BuildEventId_Progress{Progress: &bespb.BuildEventId_ProgressId{OpaqueCount: 0}}},
{Id: &bespb.BuildEventId_WorkspaceStatus{WorkspaceStatus: &bespb.BuildEventId_WorkspaceStatusId{}}},
{Id: &bespb.BuildEventId_BuildFinished{BuildFinished: &bespb.BuildEventId_BuildFinishedId{}}},
},
Payload: &bespb.BuildEvent_Started{Started: &bespb.BuildStarted{
Uuid: r.invocationID,
StartTimeMillis: startTime.UnixMilli(),
StartTime: timestamppb.New(startTime),
OptionsDescription: optionsDescription,
Command: cmd,
}},
}
if r.isWorkflow {
startedEvent.Children = append(startedEvent.Children, &bespb.BuildEventId{Id: &bespb.BuildEventId_WorkflowConfigured{WorkflowConfigured: &bespb.BuildEventId_WorkflowConfiguredId{}}})
} else {
startedEvent.Children = append(startedEvent.Children, &bespb.BuildEventId{Id: &bespb.BuildEventId_Pattern{Pattern: &bespb.BuildEventId_PatternExpandedId{Pattern: patterns}}})
}
if err := r.bep.Publish(startedEvent); err != nil {
return err
}
if !r.isWorkflow {
patternEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_Pattern{Pattern: &bespb.BuildEventId_PatternExpandedId{Pattern: patterns}}},
Payload: &bespb.BuildEvent_Expanded{Expanded: &bespb.PatternExpanded{}},
}
if err := r.bep.Publish(patternEvent); err != nil {
return err
}
}
// Flush whenever the log buffer fills past a certain threshold.
r.log.writeListener = func() {
if size := r.log.Len(); size >= progressFlushThresholdBytes {
r.FlushProgress() // ignore error; it will surface in `bep.Finish()`
}
}
stopFlushingProgress := r.startBackgroundProgressFlush()
r.cancelBackgroundFlush = stopFlushingProgress
return nil
}
func (r *buildEventReporter) Stop(exitCode int, exitCodeName string) error {
if r.cancelBackgroundFlush != nil {
r.cancelBackgroundFlush()
r.cancelBackgroundFlush = nil
}
r.FlushProgress()
now := time.Now()
r.Publish(&bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_BuildFinished{BuildFinished: &bespb.BuildEventId_BuildFinishedId{}}},
Children: []*bespb.BuildEventId{
{Id: &bespb.BuildEventId_BuildToolLogs{BuildToolLogs: &bespb.BuildEventId_BuildToolLogsId{}}},
},
Payload: &bespb.BuildEvent_Finished{Finished: &bespb.BuildFinished{
OverallSuccess: exitCode == 0,
ExitCode: &bespb.BuildFinished_ExitCode{
Name: exitCodeName,
Code: int32(exitCode),
},
FinishTimeMillis: now.UnixMilli(),
FinishTime: timestamppb.New(now),
}},
})
elapsedTimeSeconds := float64(time.Since(r.startTime)) / float64(time.Second)
// NB: This is the last message -- if more are added afterwards, be sure to
// update the `LastMessage` flag
r.Publish(&bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_BuildToolLogs{BuildToolLogs: &bespb.BuildEventId_BuildToolLogsId{}}},
Payload: &bespb.BuildEvent_BuildToolLogs{BuildToolLogs: &bespb.BuildToolLogs{
Log: []*bespb.File{
{Name: "elapsed time", File: &bespb.File_Contents{Contents: []byte(string(fmt.Sprintf("%.6f", elapsedTimeSeconds)))}},
},
}},
LastMessage: true,
})
if err := r.bep.Finish(); err != nil {
// If we don't publish a build event successfully, then the status may not be
// reported to the Git provider successfully. Terminate with a code indicating
// that the executor can retry the action, so that we have another chance.
return status.UnavailableErrorf("failed to publish build event: %s", err)
}
return nil
}
func (r *buildEventReporter) FlushProgress() error {
event, err := r.nextProgressEvent()
if err != nil {
return err
}
if event == nil {
// No progress to flush.
return nil
}
return r.bep.Publish(event)
}
func (r *buildEventReporter) nextProgressEvent() (*bespb.BuildEvent, error) {
r.mu.Lock()
defer r.mu.Unlock()
buf, err := r.log.ReadAll()
if err != nil {
return nil, status.WrapError(err, "failed to read action logs")
}
if len(buf) == 0 {
return nil, nil
}
count := r.progressCount
r.progressCount++
output := string(buf)
return &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_Progress{Progress: &bespb.BuildEventId_ProgressId{OpaqueCount: count}}},
Children: []*bespb.BuildEventId{
{Id: &bespb.BuildEventId_Progress{Progress: &bespb.BuildEventId_ProgressId{OpaqueCount: count + 1}}},
},
Payload: &bespb.BuildEvent_Progress{Progress: &bespb.Progress{
// Only outputting to stderr for now, like Bazel does.
Stderr: output,
}},
}, nil
}
func (r *buildEventReporter) startBackgroundProgressFlush() func() {
stop := make(chan struct{}, 1)
go func() {
for {
select {
case <-stop:
break
case <-time.After(progressFlushInterval):
r.FlushProgress()
}
}
}()
return func() {
stop <- struct{}{}
}
}
func main() {
if err := run(); err != nil {
log.Errorf("%s", err)
os.Exit(int(gstatus.Code(err)))
}
}
func run() error {
flag.Parse()
ws := &workspace{
startTime: time.Now(),
buildbuddyAPIKey: os.Getenv(buildbuddyAPIKeyEnvVarName),
forcedInvocationID: *invocationID,
}
ctx := context.Background()
if ws.buildbuddyAPIKey != "" {
ctx = metadata.AppendToOutgoingContext(ctx, auth.APIKeyHeader, ws.buildbuddyAPIKey)
}
buildEventReporter, err := newBuildEventReporter(ctx, *besBackend, ws.buildbuddyAPIKey, *invocationID, *workflowID != "" /*=isWorkflow*/)
if err != nil {
return err
}
// Write setup logs to the current task's stderr (to make debugging easier),
// and also to the invocation.
ws.log = io.MultiWriter(os.Stderr, buildEventReporter)
ws.hostname, ws.username = getHostAndUserName()
// Change the current working directory to respect WORKDIR_OVERRIDE, if set.
if wd := os.Getenv("WORKDIR_OVERRIDE"); wd != "" {
if err := os.MkdirAll(wd, 0755); err != nil {
return status.WrapError(err, "create WORKDIR_OVERRIDE directory")
}
if err := os.Chdir(wd); err != nil {
return err
}
}
// Bazel needs a HOME dir; ensure that one is set.
if err := ensureHomeDir(); err != nil {
return status.WrapError(err, "ensure HOME")
}
// Bazel also needs USER to be set.
if err := ensureUser(); err != nil {
return status.WrapError(err, "ensure USER")
}
// Make sure PATH is set.
if err := ensurePath(); err != nil {
return status.WrapError(err, "ensure PATH")
}
// Write default bazelrc
if err := writeBazelrc(buildbuddyBazelrcPath, buildEventReporter.invocationID); err != nil {
return status.WrapError(err, "write "+buildbuddyBazelrcPath)
}
// Delete bazelrc before exiting. Use abs path since we might cd after this
// point.
absBazelrcPath, err := filepath.Abs(buildbuddyBazelrcPath)
if err != nil {
return err
}
defer func() {
if err := os.Remove(absBazelrcPath); err != nil {
log.Error(err.Error())
}
}()
// Configure TERM to get prettier output from executed commands.
if err := os.Setenv("TERM", "xterm-256color"); err != nil {
return status.WrapError(err, "could not setup TERM")
}
// Make sure we have a bazel / bazelisk binary available.
if *bazelCommand == "" {
wd, err := os.Getwd()
if err != nil {
return err
}
bazeliskPath := filepath.Join(wd, bazeliskBinaryName)
if err := extractBazelisk(bazeliskPath); err != nil {
return status.WrapError(err, "failed to extract bazelisk")
}
*bazelCommand = bazeliskPath
}
if *shutdownAndExit {
log.Info("--shutdown_and_exit requested; will run bazel shutdown then exit.")
if _, err := os.Stat(repoDirName); err != nil {
log.Info("Workspace does not exist; exiting.")
return nil
}
if err := os.Chdir(repoDirName); err != nil {
return err
}
args, err := bazelArgs("shutdown")
if err != nil {
return err
}
printCommandLine(os.Stderr, *bazelCommand, args...)
if err := runCommand(ctx, *bazelCommand, args, nil, os.Stderr); err != nil {
return err
}
log.Info("Shutdown complete.")
return nil
}
if err := buildEventReporter.Start(ws.startTime); err != nil {
return status.WrapError(err, "could not publish started event")
}
if err := ws.setup(ctx); err != nil {
_ = buildEventReporter.Stop(noExitCode, failedExitCodeName)
return status.WrapError(err, "failed to set up git repo")
}
cfg, err := readConfig()
if err != nil {
_ = buildEventReporter.Stop(noExitCode, failedExitCodeName)
return status.WrapError(err, "failed to read BuildBuddy config")
}
var action *config.Action
if *bazelSubCommand != "" {
action = &config.Action{
Name: "run",
BazelCommands: []string{
*bazelSubCommand,
},
}
} else if *actionName != "" {
// If a specific action was specified, filter to configured
// actions with a matching action name.
action, err = findAction(cfg.Actions, *actionName)
if err != nil {
return err
}
} else {
return status.InvalidArgumentError("One of --action or --bazel_sub_command must be specified.")
}
result, err := ws.RunAction(ctx, action, buildEventReporter)
if err != nil {
return err
}
if err := buildEventReporter.Stop(result.exitCode, result.exitCodeName); err != nil {
return err
}
return nil
}
type actionResult struct {
exitCode int
exitCodeName string
}
// RunAction runs the specified action and streams the progress to the invocation via the buildEventReporter.
func (ws *workspace) RunAction(ctx context.Context, action *config.Action, buildEventReporter *buildEventReporter) (*actionResult, error) {
// NB: Anything logged to `ar.log` gets output to both the stdout of this binary
// and the logs uploaded to BuildBuddy for this action. Anything that we want
// the user to see in the invocation UI needs to go in that log, instead of
// the global `log.Print`.
ar := &actionRunner{
isWorkflow: *workflowID != "",
action: action,
reporter: buildEventReporter,
hostname: ws.hostname,
username: ws.username,
}
exitCode := 0
exitCodeName := "OK"
if err := ar.Run(ctx, ws); err != nil {
ar.reporter.Printf(aurora.Sprintf(aurora.Red("\nAction failed: %s"), status.Message(err)))
exitCode = getExitCode(err)
// TODO: More descriptive exit code names, so people have a better
// sense of what happened without even needing to open the invocation.
exitCodeName = failedExitCodeName
}
return &actionResult{exitCode, exitCodeName}, nil
}
func (r *buildEventReporter) Write(b []byte) (int, error) {
return r.log.Write(b)
}
func (r *buildEventReporter) Println(vals ...interface{}) {
r.log.Println(vals...)
}
func (r *buildEventReporter) Printf(format string, vals ...interface{}) {
r.log.Printf(format, vals...)
}
type invocationLog struct {
lockingbuffer.LockingBuffer
writer io.Writer
writeListener func()
}
func newInvocationLog() *invocationLog {
invLog := &invocationLog{writeListener: func() {}}
invLog.writer = io.MultiWriter(&invLog.LockingBuffer, os.Stderr)
return invLog
}
func (invLog *invocationLog) Write(b []byte) (int, error) {
n, err := invLog.writer.Write(b)
invLog.writeListener()
return n, err
}
func (invLog *invocationLog) Println(vals ...interface{}) {
invLog.Write([]byte(fmt.Sprintln(vals...)))
}
func (invLog *invocationLog) Printf(format string, vals ...interface{}) {
invLog.Write([]byte(fmt.Sprintf(format+"\n", vals...)))
}
// actionRunner runs a single action in the BuildBuddy config.
type actionRunner struct {
isWorkflow bool
action *config.Action
reporter *buildEventReporter
username string
hostname string
}
func (ar *actionRunner) Run(ctx context.Context, ws *workspace) error {
ar.reporter.Printf("Running action %q", ar.action.Name)
// Only print this to the local logs -- it's mostly useful for development purposes.
log.Infof("Invocation URL: %s", invocationURL(ar.reporter.InvocationID()))
// NOTE: In this func we return immediately with an error of nil if event publishing fails,
// because that error is instead surfaced in the caller func when calling
// `buildEventPublisher.Wait()`
wfc := &bespb.WorkflowConfigured{
WorkflowId: *workflowID,
ActionName: ar.action.Name,
ActionTriggerEvent: *triggerEvent,
PushedRepoUrl: *pushedRepoURL,
PushedBranch: *pushedBranch,
CommitSha: *commitSHA,
TargetRepoUrl: *targetRepoURL,
TargetBranch: *targetBranch,
}
wfcEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_WorkflowConfigured{WorkflowConfigured: &bespb.BuildEventId_WorkflowConfiguredId{}}},
Payload: &bespb.BuildEvent_WorkflowConfigured{WorkflowConfigured: wfc},
}
cic := &bespb.ChildInvocationsConfigured{}
cicEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_ChildInvocationsConfigured{ChildInvocationsConfigured: &bespb.BuildEventId_ChildInvocationsConfiguredId{}}},
Payload: &bespb.BuildEvent_ChildInvocationsConfigured{ChildInvocationsConfigured: cic},
}
// If the triggering commit merges cleanly with the target branch, the runner
// will execute the configured bazel commands. Otherwise, the runner will
// exit early without running those commands and does not need to create
// invocation streams for them.
if ws.setupError == nil {
for _, bazelCmd := range ar.action.BazelCommands {
iid, err := newUUID()
if err != nil {
return err
}
wfc.Invocation = append(wfc.Invocation, &bespb.WorkflowConfigured_InvocationMetadata{
InvocationId: iid,
BazelCommand: bazelCmd,
})
wfcEvent.Children = append(wfcEvent.Children, &bespb.BuildEventId{
Id: &bespb.BuildEventId_WorkflowCommandCompleted{WorkflowCommandCompleted: &bespb.BuildEventId_WorkflowCommandCompletedId{
InvocationId: iid,
}},
})
cic.Invocation = append(cic.Invocation, &bespb.ChildInvocationsConfigured_InvocationMetadata{
InvocationId: iid,
BazelCommand: bazelCmd,
})
cicEvent.Children = append(cicEvent.Children, &bespb.BuildEventId{
Id: &bespb.BuildEventId_ChildInvocationCompleted{ChildInvocationCompleted: &bespb.BuildEventId_ChildInvocationCompletedId{
InvocationId: iid,
}},
})
}
}
if ar.isWorkflow {
if err := ar.reporter.Publish(wfcEvent); err != nil {
return nil
}
}
if err := ar.reporter.Publish(cicEvent); err != nil {
return nil
}
buildMetadata := &bespb.BuildMetadata{
Metadata: map[string]string{},
}
if ar.isWorkflow {
buildMetadata.Metadata["ROLE"] = "CI_RUNNER"
} else {
buildMetadata.Metadata["ROLE"] = "HOSTED_BAZEL"
}
if *visibility != "" {
buildMetadata.Metadata["VISIBILITY"] = *visibility
}
buildMetadataEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_BuildMetadata{BuildMetadata: &bespb.BuildEventId_BuildMetadataId{}}},
Payload: &bespb.BuildEvent_BuildMetadata{BuildMetadata: buildMetadata},
}
if err := ar.reporter.Publish(buildMetadataEvent); err != nil {
return nil
}
workspaceStatusEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_WorkspaceStatus{WorkspaceStatus: &bespb.BuildEventId_WorkspaceStatusId{}}},
Payload: &bespb.BuildEvent_WorkspaceStatus{WorkspaceStatus: &bespb.WorkspaceStatus{
Item: []*bespb.WorkspaceStatus_Item{
{Key: "BUILD_USER", Value: ar.username},
{Key: "BUILD_HOST", Value: ar.hostname},
{Key: "GIT_BRANCH", Value: *pushedBranch},
{Key: "GIT_TREE_STATUS", Value: "Clean"},
// Note: COMMIT_SHA may not actually reflect the current state of the
// repo since we merge the target branch before running the workflow;
// we set this for the purpose of reporting statuses to GitHub.
{Key: "COMMIT_SHA", Value: *commitSHA},
// REPO_URL is used to report statuses, so always set it to the
// target repo URL (which should be the same URL on which the workflow
// is configured).
{Key: "REPO_URL", Value: *targetRepoURL},
},
}},
}
if err := ar.reporter.Publish(workspaceStatusEvent); err != nil {
return nil
}
if ws.setupError != nil {
return ws.setupError
}
for i, bazelCmd := range ar.action.BazelCommands {
cmdStartTime := time.Now()
if i >= len(wfc.GetInvocation()) {
return status.InternalErrorf("No invocation metadata generated for bazel_commands[%d]; this should never happen", i)
}
iid := wfc.GetInvocation()[i].GetInvocationId()
args, err := bazelArgs(bazelCmd)
if err != nil {
return status.InvalidArgumentErrorf("failed to parse bazel command: %s", err)
}
printCommandLine(ar.reporter, *bazelCommand, args...)
// Transparently set the invocation ID from the one we computed ahead of
// time. The UI is expecting this invocation ID so that it can render a
// BuildBuddy invocation URL for each bazel_command that is executed.
args = appendBazelSubcommandArgs(args, fmt.Sprintf("--invocation_id=%s", iid))
// Instead of actually running the target, have Bazel write out a run script using the --script_path flag and
// extract run options (i.e. args, runfile information) from the generated run script.
runScript := ""
if *recordRunMetadata {
tmpDir, err := os.MkdirTemp("", "bazel-run-script-*")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
runScript = filepath.Join(tmpDir, "run.sh")
args = appendBazelSubcommandArgs(args, "--script_path="+runScript)
}
runErr := runCommand(ctx, *bazelCommand, args, nil /*=env*/, ar.reporter)
exitCode := getExitCode(runErr)
if exitCode != noExitCode {
ar.reporter.Printf("%s(command exited with code %d)%s\n", ansiGray, exitCode, ansiReset)
}
// If this is a successfully "bazel run" invocation from which we are extracting run information via
// --script_path, go ahead and extract run information from the script and send it via the event stream.
if exitCode == 0 && runScript != "" {
runInfo, err := processRunScript(ctx, runScript)
if err != nil {
return err
}
e := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_RunTargetAnalyzed{}},
Payload: &bespb.BuildEvent_RunTargetAnalyzed{RunTargetAnalyzed: &bespb.RunTargetAnalyzed{
Arguments: runInfo.args,
RunfilesRoot: runInfo.runfilesRoot,
Runfiles: runInfo.runfiles,
RunfileDirectories: runInfo.runfileDirs,
}},
}
if err := ar.reporter.Publish(e); err != nil {
break
}
}
// Publish the status of each command as well as the finish time.
// Stop execution early on BEP failure, but ignore error -- it will surface in `bep.Finish()`.
duration := time.Since(cmdStartTime)
completedEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_WorkflowCommandCompleted{WorkflowCommandCompleted: &bespb.BuildEventId_WorkflowCommandCompletedId{
InvocationId: iid,
}}},
Payload: &bespb.BuildEvent_WorkflowCommandCompleted{WorkflowCommandCompleted: &bespb.WorkflowCommandCompleted{
ExitCode: int32(exitCode),
StartTimeMillis: cmdStartTime.UnixMilli(),
StartTime: timestamppb.New(cmdStartTime),
Duration: durationpb.New(duration),
DurationMillis: duration.Milliseconds(),
}},
}
if err := ar.reporter.Publish(completedEvent); err != nil {
break
}
duration = time.Since(cmdStartTime)
childCompletedEvent := &bespb.BuildEvent{
Id: &bespb.BuildEventId{Id: &bespb.BuildEventId_ChildInvocationCompleted{ChildInvocationCompleted: &bespb.BuildEventId_ChildInvocationCompletedId{
InvocationId: iid,
}}},
Payload: &bespb.BuildEvent_ChildInvocationCompleted{ChildInvocationCompleted: &bespb.ChildInvocationCompleted{
ExitCode: int32(exitCode),
StartTimeMillis: cmdStartTime.UnixMilli(),
StartTime: timestamppb.New(cmdStartTime),
Duration: durationpb.New(duration),
DurationMillis: duration.Milliseconds(),
}},
}
if err := ar.reporter.Publish(childCompletedEvent); err != nil {
break
}
if runErr != nil {
// Return early if the command failed.
// Note, even though we don't hit the `FlushProgress` call below in this case,
// we'll still flush progress before closing the BEP stream.
return runErr
}
// Flush progress after every command.
// Stop execution early on BEP failure, but ignore error -- it will surface in `bep.Finish()`.
if err := ar.reporter.FlushProgress(); err != nil {
break
}
}
return nil
}
type runInfo struct {
args []string
runfiles []*bespb.File
runfileDirs []*bespb.Tree
runfilesRoot string
}
func collectRunfiles(runfilesDir string) (map[digest.Key]string, map[string]string, error) {
fileDigestMap := make(map[digest.Key]string)
dirsToUpload := make(map[string]string)
err := filepath.WalkDir(runfilesDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if d.Type()&fs.ModeSymlink != 0 {
t, err := os.Readlink(path)
if err != nil {
return err
}
fi, err := os.Stat(t)
if err != nil {
return err
}
if fi.IsDir() {
dirsToUpload[path] = t
return nil
}
}
rn, err := cachetools.ComputeFileDigest(path, *remoteInstanceName)
if err != nil {
return err
}
fileDigestMap[digest.NewKey(rn.GetDigest())] = path
return nil
})
if err != nil && !os.IsNotExist(err) {
return nil, nil, status.UnknownErrorf("could not setup runtime files: %s", err)
}
return fileDigestMap, dirsToUpload, err
}
func uploadRunfiles(ctx context.Context, workspaceRoot, runfilesDir string) ([]*bespb.File, []*bespb.Tree, error) {
fileDigestMap, dirs, err := collectRunfiles(runfilesDir)
if err != nil {
return nil, nil, err
}
conn, err := grpc_client.DialTarget(*cacheBackend)
if err != nil {
return nil, nil, err
}
bsClient := bspb.NewByteStreamClient(conn)
casClient := repb.NewContentAddressableStorageClient(conn)
backendURL, err := url.Parse(*cacheBackend)
if err != nil {
return nil, nil, err
}
bytestreamURIPrefix := "bytestream://" + backendURL.Host
var digests []*repb.Digest
var runfiles []*bespb.File
for d, runfilePath := range fileDigestMap {
digests = append(digests, d.ToDigest())
relPath, err := filepath.Rel(workspaceRoot, runfilePath)
if err != nil {
return nil, nil, err
}
runfiles = append(runfiles, &bespb.File{
Name: relPath,
File: &bespb.File_Uri{
Uri: fmt.Sprintf("%s%s", bytestreamURIPrefix, digest.NewResourceName(d.ToDigest(), *remoteInstanceName).DownloadString()),
},
})
}
rsp, err := casClient.FindMissingBlobs(ctx, &repb.FindMissingBlobsRequest{
InstanceName: *remoteInstanceName,
BlobDigests: digests,
})
if err != nil {
return nil, nil, status.UnknownErrorf("could not check digest existence: %s", err)
}
missingDigests := rsp.GetMissingBlobDigests()
eg, ctx := errgroup.WithContext(ctx)
u, err := cachetools.NewBatchCASUploader(ctx, bsClient, casClient, nil /*=fileCache*/, *remoteInstanceName)
if err != nil {
return nil, nil, err
}
for _, d := range missingDigests {
runfilePath, ok := fileDigestMap[digest.NewKey(d)]
if !ok {
// not supposed to happen...
return nil, nil, status.InternalErrorf("missing digest not in our digest map")
}
f, err := os.Open(runfilePath)
if err != nil {
return nil, nil, err
}
if err := u.Upload(d, f); err != nil {
return nil, nil, err
}
}
eg.Go(func() error {
return u.Wait()
})
var runfileDirs []*bespb.Tree
var mu sync.Mutex
// Output directories in runfiles are symlinks to physical directories.
// We upload the real directory, but return the logical directory that the binary expects.
for placePath, realPath := range dirs {
placePath := placePath
realPath := realPath
eg.Go(func() error {
_, td, err := cachetools.UploadDirectoryToCAS(ctx, bsClient, casClient, nil, *remoteInstanceName, realPath)
if err != nil {
return err
}
relPath, err := filepath.Rel(workspaceRoot, placePath)
if err != nil {
return err
}
mu.Lock()
runfileDirs = append(runfileDirs, &bespb.Tree{
Name: relPath,
Uri: fmt.Sprintf("%s%s", bytestreamURIPrefix, digest.NewResourceName(td, *remoteInstanceName).DownloadString()),
})
mu.Unlock()
return nil
})
}
if err := eg.Wait(); err != nil {
return nil, nil, err
}
return runfiles, runfileDirs, nil
}
// processRunScript processes the contents of a bazel run script (produced via bazel run --script_path) and extracts