-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathapi_server.go
More file actions
889 lines (794 loc) · 28.2 KB
/
api_server.go
File metadata and controls
889 lines (794 loc) · 28.2 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
package api
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"maps"
"net/http"
"net/url"
"slices"
"strings"
"time"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/auditlog"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/backends/prom"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/hostedrunner"
"github.com/buildbuddy-io/buildbuddy/proto/workflow"
"github.com/buildbuddy-io/buildbuddy/server/build_event_protocol/build_event_handler"
"github.com/buildbuddy-io/buildbuddy/server/environment"
"github.com/buildbuddy-io/buildbuddy/server/eventlog"
"github.com/buildbuddy-io/buildbuddy/server/http/protolet"
"github.com/buildbuddy-io/buildbuddy/server/interfaces"
"github.com/buildbuddy-io/buildbuddy/server/real_environment"
"github.com/buildbuddy-io/buildbuddy/server/remote_cache/digest"
"github.com/buildbuddy-io/buildbuddy/server/tables"
"github.com/buildbuddy-io/buildbuddy/server/util/capabilities"
"github.com/buildbuddy-io/buildbuddy/server/util/claims"
"github.com/buildbuddy-io/buildbuddy/server/util/clickhouse/schema"
"github.com/buildbuddy-io/buildbuddy/server/util/db"
"github.com/buildbuddy-io/buildbuddy/server/util/flag"
"github.com/buildbuddy-io/buildbuddy/server/util/log"
"github.com/buildbuddy-io/buildbuddy/server/util/perms"
"github.com/buildbuddy-io/buildbuddy/server/util/prefix"
"github.com/buildbuddy-io/buildbuddy/server/util/proto"
"github.com/buildbuddy-io/buildbuddy/server/util/query_builder"
"github.com/buildbuddy-io/buildbuddy/server/util/status"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/protobuf/types/known/timestamppb"
api_common "github.com/buildbuddy-io/buildbuddy/server/api/common"
requestcontext "github.com/buildbuddy-io/buildbuddy/server/util/request_context"
apipb "github.com/buildbuddy-io/buildbuddy/proto/api/v1"
bespb "github.com/buildbuddy-io/buildbuddy/proto/build_event_stream"
cappb "github.com/buildbuddy-io/buildbuddy/proto/capability"
elpb "github.com/buildbuddy-io/buildbuddy/proto/eventlog"
gitpb "github.com/buildbuddy-io/buildbuddy/proto/git"
inpb "github.com/buildbuddy-io/buildbuddy/proto/invocation"
repb "github.com/buildbuddy-io/buildbuddy/proto/remote_execution"
rspb "github.com/buildbuddy-io/buildbuddy/proto/resource"
rnpb "github.com/buildbuddy-io/buildbuddy/proto/runner"
)
var (
enableAPI = flag.Bool("api.enable_api", true, "Whether or not to enable the BuildBuddy API.")
enableCache = flag.Bool("api.enable_cache", false, "Whether or not to enable the API cache.")
enableCacheDeleteAPI = flag.Bool("enable_cache_delete_api", false, "If true, enable access to cache delete API.")
enableMetricsAPI = flag.Bool("api.enable_metrics_api", false, "If true, enable access to metrics API.")
)
const (
minAuditLogPageSize = 1
defaultAuditLogPageSize = 100
maxAuditLogPageSize = 1_000
)
type APIServer struct {
env environment.Env
metricsFederationURL *url.URL
metricsFederationClient *http.Client
}
func Register(env *real_environment.RealEnv) error {
if *enableAPI {
env.SetAPIService(NewAPIServer(env))
}
return nil
}
func NewAPIServer(env environment.Env) *APIServer {
return &APIServer{
env: env,
}
}
func (s *APIServer) authorizeWrites(ctx context.Context) error {
canWrite, err := capabilities.IsGranted(ctx, s.env.GetAuthenticator(), cappb.Capability_CACHE_WRITE)
if err != nil {
return err
}
if !canWrite {
return status.PermissionDeniedError("You do not have permission to perform this action.")
}
return nil
}
func (s *APIServer) GetInvocation(ctx context.Context, req *apipb.GetInvocationRequest) (*apipb.GetInvocationResponse, error) {
user, err := s.env.GetAuthenticator().AuthenticatedUser(ctx)
if err != nil {
return nil, err
}
if req.GetSelector().GetInvocationId() == "" && req.GetSelector().GetCommitSha() == "" {
return nil, status.InvalidArgumentErrorf("InvocationSelector must contain a valid invocation_id or commit_sha")
}
q := query_builder.NewQuery(`SELECT * FROM "Invocations"`)
q = q.AddWhereClause(`group_id = ?`, user.GetGroupID())
if req.GetSelector().GetInvocationId() != "" {
q = q.AddWhereClause(`invocation_id = ?`, req.GetSelector().GetInvocationId())
}
if req.GetSelector().GetCommitSha() != "" {
q = q.AddWhereClause(`commit_sha = ?`, req.GetSelector().GetCommitSha())
}
if err := perms.AddPermissionsCheckToQuery(ctx, s.env, q); err != nil {
return nil, err
}
queryStr, args := q.Build()
rq := s.env.GetDBHandle().NewQuery(ctx, "api_server_get_invocations").Raw(queryStr, args...)
invocations := []*apipb.Invocation{}
err = db.ScanEach(rq, func(ctx context.Context, ti *tables.Invocation) error {
apiInvocation := &apipb.Invocation{
Id: &apipb.Invocation_Id{
InvocationId: ti.InvocationID,
},
Success: ti.Success,
User: ti.User,
DurationUsec: ti.DurationUsec,
Host: ti.Host,
Command: ti.Command,
Pattern: ti.Pattern,
ActionCount: ti.ActionCount,
CreatedAtUsec: ti.CreatedAtUsec,
UpdatedAtUsec: ti.UpdatedAtUsec,
RepoUrl: ti.RepoURL,
BranchName: ti.BranchName,
CommitSha: ti.CommitSHA,
Role: ti.Role,
BazelExitCode: ti.BazelExitCode,
InvocationStatus: apipb.InvocationStatus(ti.InvocationStatus),
}
invocations = append(invocations, apiInvocation)
return nil
})
if err != nil {
return nil, err
}
if req.IncludeMetadata || req.IncludeArtifacts || req.IncludeChildInvocations {
for _, i := range invocations {
_, err := build_event_handler.LookupInvocationWithCallback(ctx, s.env, i.Id.InvocationId, func(event *inpb.InvocationEvent) error {
switch p := event.GetBuildEvent().GetPayload().(type) {
case *bespb.BuildEvent_BuildMetadata:
if req.IncludeMetadata {
for k, v := range p.BuildMetadata.GetMetadata() {
i.BuildMetadata = append(i.BuildMetadata, &apipb.InvocationMetadata{
Key: k,
Value: v,
})
}
}
if req.IncludeChildInvocations {
for k, v := range p.BuildMetadata.GetMetadata() {
if k == "RUN_ID" {
childrenInvocationIDs, err := s.env.GetInvocationDB().LookupChildInvocations(ctx, v)
if err != nil {
return err
}
for _, iid := range childrenInvocationIDs {
i.ChildInvocations = append(i.ChildInvocations, &apipb.Invocation_Id{
InvocationId: iid,
})
}
break
}
}
}
case *bespb.BuildEvent_WorkspaceStatus:
if req.IncludeMetadata {
for _, item := range p.WorkspaceStatus.GetItem() {
i.WorkspaceStatus = append(i.WorkspaceStatus, &apipb.InvocationMetadata{
Key: item.Key,
Value: item.Value,
})
}
}
case *bespb.BuildEvent_NamedSetOfFiles:
if req.IncludeArtifacts {
for _, file := range p.NamedSetOfFiles.GetFiles() {
i.Artifacts = append(i.Artifacts, &apipb.File{
Name: file.GetName(),
Uri: file.GetUri(),
})
}
}
}
return nil
})
if err != nil {
return nil, err
}
}
}
return &apipb.GetInvocationResponse{
Invocation: invocations,
}, nil
}
func (s *APIServer) CacheEnabled() bool {
return *enableCache
}
func (s *APIServer) redisCachedTarget(ctx context.Context, userInfo interfaces.UserInfo, iid, targetLabel string) (*apipb.Target, error) {
if !s.CacheEnabled() || s.env.GetMetricsCollector() == nil {
return nil, nil
}
if targetLabel == "" {
return nil, nil
}
key := api_common.TargetLabelKey(userInfo.GetGroupID(), iid, targetLabel)
blobs, err := s.env.GetMetricsCollector().GetAll(ctx, key)
if err != nil {
return nil, err
}
if len(blobs) != 1 {
return nil, nil
}
t := &apipb.Target{}
if err := proto.Unmarshal([]byte(blobs[0]), t); err != nil {
return nil, err
}
return t, nil
}
func (s *APIServer) GetTarget(ctx context.Context, req *apipb.GetTargetRequest) (*apipb.GetTargetResponse, error) {
userInfo, err := s.env.GetAuthenticator().AuthenticatedUser(ctx)
if err != nil {
return nil, err
}
if req.GetSelector().GetInvocationId() == "" {
return nil, status.InvalidArgumentErrorf("TargetSelector must contain a valid invocation_id")
}
iid := req.GetSelector().GetInvocationId()
rsp := &apipb.GetTargetResponse{
Target: make([]*apipb.Target, 0),
}
cacheKey := req.GetSelector().GetLabel()
// Target ID is equal to the target label, so either can be used as a cache key.
if targetId := req.GetSelector().GetTargetId(); targetId != "" {
cacheKey = targetId
}
cachedTarget, err := s.redisCachedTarget(ctx, userInfo, iid, cacheKey)
if err != nil {
log.Debugf("redisCachedTarget err: %s", err)
} else if cachedTarget != nil {
if api_common.TargetMatchesSelector(cachedTarget, req.GetSelector()) {
rsp.Target = append(rsp.Target, cachedTarget)
}
}
if len(rsp.Target) > 0 {
return rsp, nil
}
targetMap := api_common.NewTargetMap(req.GetSelector())
_, err = build_event_handler.LookupInvocationWithCallback(ctx, s.env, req.GetSelector().GetInvocationId(), func(event *inpb.InvocationEvent) error {
targetMap.ProcessEvent(req.GetSelector().GetInvocationId(), event.GetBuildEvent())
return nil
})
if err != nil {
return nil, err
}
return &apipb.GetTargetResponse{
// Collect all the map values into a slice.
Target: slices.Collect(maps.Values(targetMap.Targets)),
}, nil
}
func (s *APIServer) redisCachedActions(ctx context.Context, userInfo interfaces.UserInfo, iid, targetLabel string) ([]*apipb.Action, error) {
if !s.CacheEnabled() || s.env.GetMetricsCollector() == nil {
return nil, nil
}
if targetLabel == "" {
return nil, nil
}
const limit = 100_000
key := api_common.ActionLabelKey(userInfo.GetGroupID(), iid, targetLabel)
serializedResults, err := s.env.GetMetricsCollector().ListRange(ctx, key, 0, limit-1)
if err != nil {
return nil, err
}
a := &apipb.Action{}
actions := make([]*apipb.Action, 0)
for _, serializedResult := range serializedResults {
if err := proto.Unmarshal([]byte(serializedResult), a); err != nil {
return nil, err
}
actions = append(actions, a)
}
return actions, nil
}
func (s *APIServer) GetAction(ctx context.Context, req *apipb.GetActionRequest) (*apipb.GetActionResponse, error) {
userInfo, err := s.env.GetAuthenticator().AuthenticatedUser(ctx)
if err != nil {
return nil, err
}
if req.GetSelector().GetInvocationId() == "" {
return nil, status.InvalidArgumentErrorf("ActionSelector must contain a valid invocation_id")
}
iid := req.GetSelector().GetInvocationId()
rsp := &apipb.GetActionResponse{
Action: make([]*apipb.Action, 0),
}
cacheKey := req.GetSelector().GetTargetLabel()
// Target ID is equal to the target label, so either can be used as a cache key.
if targetId := req.GetSelector().GetTargetId(); targetId != "" {
cacheKey = targetId
}
cachedActions, err := s.redisCachedActions(ctx, userInfo, iid, cacheKey)
if err != nil {
log.Debugf("redisCachedAction err: %s", err)
}
for _, action := range cachedActions {
if action != nil && actionMatchesActionSelector(action, req.GetSelector()) {
rsp.Action = append(rsp.Action, action)
}
}
if len(rsp.Action) > 0 {
return rsp, nil
}
_, err = build_event_handler.LookupInvocationWithCallback(ctx, s.env, iid, func(event *inpb.InvocationEvent) error {
action := &apipb.Action{
Id: &apipb.Action_Id{
InvocationId: iid,
},
}
action = api_common.FillActionFromBuildEvent(event.GetBuildEvent(), action)
// Filter to only selected actions.
if action != nil && actionMatchesActionSelector(action, req.GetSelector()) {
action = api_common.FillActionOutputFilesFromBuildEvent(event.GetBuildEvent(), action)
rsp.Action = append(rsp.Action, action)
}
return nil
})
if err != nil {
return nil, err
}
return rsp, nil
}
func (s *APIServer) GetLog(ctx context.Context, req *apipb.GetLogRequest) (*apipb.GetLogResponse, error) {
// Check whether the user is authenticated. No need for the returned user
// here, because user filters will be applied by LookupInvocation.
if _, err := s.env.GetAuthenticator().AuthenticatedUser(ctx); err != nil {
return nil, err
}
if req.GetSelector().GetInvocationId() == "" {
return nil, status.InvalidArgumentErrorf("LogSelector must contain a valid invocation_id")
}
chunkReq := &elpb.GetEventLogChunkRequest{
InvocationId: req.GetSelector().GetInvocationId(),
ChunkId: req.GetPageToken(),
}
resp, err := eventlog.GetEventLogChunk(ctx, s.env, chunkReq)
if err != nil {
log.Errorf("Encountered error getting event log chunk: %s\nRequest: %s", err, chunkReq)
return nil, err
}
return &apipb.GetLogResponse{
Log: &apipb.Log{
Contents: string(resp.GetBuffer()),
},
NextPageToken: resp.GetNextChunkId(),
}, nil
}
func (s *APIServer) GetAuditLog(ctx context.Context, req *apipb.GetAuditLogRequest) (*apipb.GetAuditLogResponse, error) {
selector := req.GetSelector()
if selector == nil {
selector = &apipb.AuditLogSelector{}
}
pageToken, err := parseAuditLogPageToken(req.GetPageToken())
if err != nil {
return nil, err
}
startTime := selector.GetStartTime()
if startTime == nil {
startTime = timestamppb.New(time.Unix(0, 0))
}
if err := startTime.CheckValid(); err != nil {
return nil, status.InvalidArgumentErrorf("invalid start_time: %s", err)
}
endTime := selector.GetEndTime()
if endTime == nil {
endTime = timestamppb.Now()
}
if err := endTime.CheckValid(); err != nil {
return nil, status.InvalidArgumentErrorf("invalid end_time: %s", err)
}
if startTime.AsTime().After(endTime.AsTime()) {
return nil, status.InvalidArgumentErrorf("start_time must not be after end_time")
}
startUsec := startTime.AsTime().UnixMicro()
endUsec := endTime.AsTime().UnixMicro()
if pageToken != nil {
if selector.GetEndTime() != nil && endUsec != pageToken.EndTimeUsec {
return nil, status.InvalidArgumentError("page_token does not match selector.end_time")
}
endUsec = pageToken.EndTimeUsec
}
if startUsec > endUsec {
return nil, status.InvalidArgumentErrorf("start_time must not be after end_time")
}
if s.env.GetAuditLogger() == nil || s.env.GetOLAPDBHandle() == nil {
return nil, status.UnimplementedError("Audit logger not configured")
}
// Check whether the user is authenticated. No need for the returned user
// here, because user filters will be applied before returning entries.
user, err := s.env.GetAuthenticator().AuthenticatedUser(ctx)
if err != nil {
return nil, err
}
userCaps, err := capabilities.ForAuthenticatedUser(ctx, s.env.GetAuthenticator())
if err != nil {
return nil, err
}
if !slices.Contains(userCaps, cappb.Capability_ORG_ADMIN) && !slices.Contains(userCaps, cappb.Capability_AUDIT_LOG_READ) {
return nil, status.PermissionDeniedError("missing required capabilities")
}
isServerAdmin := claims.AuthorizeServerAdmin(ctx) == nil
pageSize := req.GetPageSize()
if pageSize < minAuditLogPageSize {
pageSize = defaultAuditLogPageSize
}
pageSize = min(pageSize, maxAuditLogPageSize)
q := query_builder.NewQuery(`SELECT * FROM AuditLogs`)
q.AddWhereClause("group_id = ?", user.GetGroupID())
q.AddWhereClause("event_time_usec >= ?", startUsec)
q.AddWhereClause("event_time_usec < ?", endUsec)
if pageToken != nil {
q.AddWhereClause("(event_time_usec, audit_log_id) > (?, ?)", pageToken.EventTimeUsec, pageToken.AuditLogID)
}
// Match AuditLogs sort key to keep keyset pagination index-friendly.
q.SetOrderBy("group_id, event_time_usec, audit_log_id", true)
// Request one extra row as lookahead so we can determine whether a next
// page exists without issuing an additional query.
q.SetLimit(int64(pageSize + 1))
queryStr, args := q.Build()
rq := s.env.GetOLAPDBHandle().NewQuery(ctx, "api_server_get_audit_logs").Raw(queryStr, args...)
rsp := &apipb.GetAuditLogResponse{}
var lastReturnedToken auditLogPageToken
err = db.ScanEach(rq, func(ctx context.Context, row *schema.AuditLog) error {
if len(rsp.Entry) == int(pageSize) {
nextPageToken, err := encodeAuditLogPageToken(lastReturnedToken)
if err != nil {
return err
}
rsp.NextPageToken = nextPageToken
return nil
}
entry, err := auditlog.EntryFromDBRow(row)
if err != nil {
return err
}
if !isServerAdmin {
auditlog.FilterEntry(entry, row.AuthUserEmail)
}
rsp.Entry = append(rsp.Entry, entry)
lastReturnedToken = auditLogPageToken{
EndTimeUsec: endUsec,
EventTimeUsec: row.EventTimeUsec,
AuditLogID: row.AuditLogID,
}
return nil
})
if err != nil {
return nil, err
}
return rsp, nil
}
type auditLogPageToken struct {
EndTimeUsec int64 `json:"end_time_usec"`
EventTimeUsec int64 `json:"event_time_usec"`
AuditLogID string `json:"audit_log_id"`
}
func encodeAuditLogPageToken(token auditLogPageToken) (string, error) {
data, err := json.Marshal(token)
if err != nil {
return "", status.InternalErrorf("failed to encode page_token: %s", err)
}
return base64.RawURLEncoding.EncodeToString(data), nil
}
func parseAuditLogPageToken(pageToken string) (*auditLogPageToken, error) {
if pageToken == "" {
return nil, nil
}
data, err := base64.RawURLEncoding.DecodeString(pageToken)
if err != nil {
return nil, status.InvalidArgumentErrorf("invalid page_token")
}
token := &auditLogPageToken{}
if err := json.Unmarshal(data, token); err != nil {
return nil, status.InvalidArgumentErrorf("invalid page_token")
}
if token.AuditLogID == "" {
return nil, status.InvalidArgumentErrorf("invalid page_token")
}
return token, nil
}
type getFileWriter struct {
s apipb.ApiService_GetFileServer
}
func (gfs *getFileWriter) Write(data []byte) (int, error) {
err := gfs.s.Send(&apipb.GetFileResponse{
Data: data,
})
return len(data), err
}
func (s *APIServer) GetFile(req *apipb.GetFileRequest, server apipb.ApiService_GetFileServer) error {
ctx := server.Context()
if _, err := s.env.GetAuthenticator().AuthenticatedUser(ctx); err != nil {
return err
}
parsedURL, err := url.Parse(req.GetUri())
if err != nil {
return status.InvalidArgumentErrorf("Invalid URL")
}
writer := &getFileWriter{s: server}
return s.env.GetPooledByteStreamClient().StreamBytestreamFile(ctx, parsedURL, writer)
}
func (s *APIServer) DeleteFile(ctx context.Context, req *apipb.DeleteFileRequest) (*apipb.DeleteFileResponse, error) {
if !*enableCacheDeleteAPI {
return nil, status.PermissionDeniedError("DeleteFile API not enabled")
}
ctx, err := prefix.AttachUserPrefixToContext(ctx, s.env.GetAuthenticator())
if err != nil {
return nil, err
}
if _, err = s.env.GetAuthenticator().AuthenticatedUser(ctx); err != nil {
return nil, err
}
if err = s.authorizeWrites(ctx); err != nil {
return nil, err
}
parsedURL, err := url.Parse(req.GetUri())
if err != nil {
return nil, status.InvalidArgumentErrorf("Invalid URL")
}
urlStr := strings.TrimPrefix(parsedURL.RequestURI(), "/")
var resourceName *rspb.ResourceName
parsedACRN, err := digest.ParseActionCacheResourceName(urlStr)
if err == nil {
resourceName = digest.NewResourceName(parsedACRN.GetDigest(), parsedACRN.GetInstanceName(), rspb.CacheType_AC, parsedACRN.GetDigestFunction()).ToProto()
} else {
parsedCASRN, err := digest.ParseDownloadResourceName(urlStr)
if err != nil {
return nil, status.InvalidArgumentErrorf("Invalid URL. Only actioncache and CAS URIs supported.")
}
resourceName = digest.NewResourceName(parsedCASRN.GetDigest(), parsedCASRN.GetInstanceName(), rspb.CacheType_CAS, parsedCASRN.GetDigestFunction()).ToProto()
}
err = s.env.GetCache().Delete(ctx, resourceName)
if err != nil && !status.IsNotFoundError(err) {
return nil, err
}
return &apipb.DeleteFileResponse{}, nil
}
func (s *APIServer) GetFileHandler() http.Handler {
return http.HandlerFunc(s.handleGetFileRequest)
}
// Handle streaming http GetFile request since protolet doesn't handle streaming rpcs yet.
func (s *APIServer) handleGetFileRequest(w http.ResponseWriter, r *http.Request) {
if _, err := s.env.GetAuthenticator().AuthenticatedUser(r.Context()); err != nil {
http.Error(w, "Invalid API key", http.StatusUnauthorized)
return
}
req := apipb.GetFileRequest{}
protolet.ReadRequestToProto(r, &req)
parsedURL, err := url.Parse(req.GetUri())
if err != nil {
http.Error(w, "Invalid URI", http.StatusBadRequest)
return
}
err = s.env.GetPooledByteStreamClient().StreamBytestreamFile(r.Context(), parsedURL, w)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
}
}
func (s *APIServer) GetMetricsHandler() http.Handler {
return http.HandlerFunc(s.handleGetMetricsRequest)
}
func (s *APIServer) handleGetMetricsRequest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if !*enableMetricsAPI {
http.Error(w, "API not enabled", http.StatusNotImplemented)
return
}
userInfo, err := s.env.GetAuthenticator().AuthenticatedUser(r.Context())
if err != nil {
http.Error(w, "Invalid API key", http.StatusUnauthorized)
return
}
if userInfo.GetGroupID() == "" {
http.Error(w, "Invalid API key", http.StatusUnauthorized)
return
}
// query prometheus
reg, err := prom.NewRegistry(s.env, userInfo.GetGroupID())
if err != nil {
http.Error(w, "unable to get registry", http.StatusInternalServerError)
return
}
opts := promhttp.HandlerOpts{
ErrorHandling: promhttp.ContinueOnError,
Registry: reg,
// Gzip is handlered by intercepters already.
DisableCompression: true,
}
handler := promhttp.HandlerFor(reg, opts)
handler.ServeHTTP(w, r)
// If enabled, also fetch federated metrics matching the authenticated group
fp := s.env.GetExperimentFlagProvider()
if fp != nil && fp.Boolean(ctx, "api.metrics_federation.enabled", false) {
// Get configured match parameters for filtering federated metrics, e.g.
// {"__name__": "remote_execution_.*", "jobs": "(mac-executor|mac-node)"}
paramsObj := fp.Object(ctx, "api.metrics_federation.match_parameters", nil)
params := map[string]string{}
for k, v := range paramsObj {
s, ok := v.(string)
if !ok {
log.CtxWarningf(ctx, "Invalid match parameter %q (type %T)", k, v)
continue
}
params[k] = s
}
if err := s.fetchFederatedMetrics(ctx, w, userInfo.GetGroupID(), params); err != nil && ctx.Err() == nil {
log.CtxWarningf(ctx, "Fetching federated metrics failed: %s", err)
}
}
}
func (s *APIServer) fetchFederatedMetrics(ctx context.Context, w http.ResponseWriter, groupID string, matchParams map[string]string) error {
if _, ok := matchParams["job"]; !ok {
log.CtxErrorf(ctx, "Missing 'job' filter - refusing to fetch federated metrics.")
return nil
}
parts := make([]string, 0, 1+len(matchParams))
parts = append(parts, fmt.Sprintf("group_id=%q", groupID))
for k, v := range matchParams {
parts = append(parts, fmt.Sprintf("%s=~%q", k, v))
}
match := fmt.Sprintf("{%s}", strings.Join(parts, ","))
log.CtxDebugf(ctx, "Fetching federated metrics: %s", match)
return s.env.GetPromQuerier().FetchFederatedMetrics(ctx, w, match)
}
// Returns true if a selector doesn't specify a particular id or matches the target's ID
func actionMatchesActionSelector(action *apipb.Action, selector *apipb.ActionSelector) bool {
return (selector.TargetId == "" || selector.TargetId == action.GetId().TargetId) &&
(selector.TargetLabel == "" || selector.TargetLabel == action.GetTargetLabel()) &&
(selector.ConfigurationId == "" || selector.ConfigurationId == action.GetId().ConfigurationId) &&
(selector.ActionId == "" || selector.ActionId == action.GetId().ActionId)
}
func (s *APIServer) ExecuteWorkflow(ctx context.Context, req *apipb.ExecuteWorkflowRequest) (*apipb.ExecuteWorkflowResponse, error) {
user, err := s.env.GetAuthenticator().AuthenticatedUser(ctx)
if err != nil {
return nil, err
}
if user.GetGroupID() == "" {
return nil, status.InternalErrorf("authenticated user's group ID is empty")
}
wfs := s.env.GetWorkflowService()
requestCtx := requestcontext.ProtoRequestContextFromContext(ctx)
wfID := wfs.GetLegacyWorkflowIDForGitRepository(user.GetGroupID(), req.GetRepoUrl())
branch := req.GetBranch()
if branch == "" && req.GetCommitSha() == "" {
// For backwards compatibility, set branch from `ref` if neither `branch`
// or `commit_sha` are set
branch = req.GetRef()
}
r := &workflow.ExecuteWorkflowRequest{
RequestContext: requestCtx,
WorkflowId: wfID,
ActionNames: req.GetActionNames(),
PushedRepoUrl: req.GetRepoUrl(),
PushedBranch: branch,
// Set target repo since we always use the target repo field for status
// publishing.
TargetRepoUrl: req.GetRepoUrl(),
TargetBranch: branch,
CommitSha: req.GetCommitSha(),
Visibility: req.GetVisibility(),
Async: req.GetAsync(),
Env: req.GetEnv(),
DisableRetry: req.GetDisableRetry(),
}
rsp, err := wfs.ExecuteWorkflow(ctx, r)
if err != nil {
return nil, err
}
actionStatuses := make([]*apipb.ExecuteWorkflowResponse_ActionStatus, len(rsp.GetActionStatuses()))
for i, as := range rsp.GetActionStatuses() {
actionStatuses[i] = &apipb.ExecuteWorkflowResponse_ActionStatus{
ActionName: as.ActionName,
InvocationId: as.InvocationId,
Status: as.Status,
}
}
return &apipb.ExecuteWorkflowResponse{
ActionStatuses: actionStatuses,
}, nil
}
func (s *APIServer) Run(ctx context.Context, req *apipb.RunRequest) (*apipb.RunResponse, error) {
r, err := hostedrunner.New(s.env)
if err != nil {
return nil, err
}
steps := make([]*rnpb.Step, 0, len(req.GetSteps()))
for _, s := range req.GetSteps() {
steps = append(steps, &rnpb.Step{Run: s.Run})
}
execProps := make([]*repb.Platform_Property, 0, len(req.GetPlatformProperties()))
for k, v := range req.GetPlatformProperties() {
execProps = append(execProps, &repb.Platform_Property{
Name: k,
Value: v,
})
}
var runnerFlags []string
if req.GetSkipAutoCheckout() {
runnerFlags = append(runnerFlags, "--skip_auto_checkout")
}
rsp, err := r.Run(ctx, &rnpb.RunRequest{
GitRepo: &gitpb.GitRepo{RepoUrl: req.GetRepo()},
RepoState: &gitpb.RepoState{
CommitSha: req.GetCommitSha(),
Branch: req.GetBranch(),
Patch: req.GetPatches(),
},
Steps: steps,
Async: req.GetAsync(),
WaitUntil: fromApiWaitCondition(req.GetWaitUntil()),
Env: req.GetEnv(),
Timeout: req.GetTimeout(),
ExecProperties: execProps,
RemoteHeaders: req.GetRemoteHeaders(),
RunRemotely: true,
RunnerFlags: runnerFlags,
})
if err != nil {
return nil, err
}
return &apipb.RunResponse{InvocationId: rsp.InvocationId}, nil
}
// Converts from internal wait mode to api wait mode.
func fromApiWaitCondition(waitCondition apipb.WaitCondition) rnpb.WaitCondition {
switch waitCondition {
case apipb.WaitCondition_QUEUED:
return rnpb.WaitCondition_QUEUED
case apipb.WaitCondition_STARTED:
return rnpb.WaitCondition_STARTED
case apipb.WaitCondition_COMPLETED:
return rnpb.WaitCondition_COMPLETED
case apipb.WaitCondition_UNKNOWN_CONDITION:
return rnpb.WaitCondition_UNKNOWN_CONDITION
}
return rnpb.WaitCondition_UNKNOWN_CONDITION
}
func (s *APIServer) CreateUserApiKey(ctx context.Context, req *apipb.CreateUserApiKeyRequest) (*apipb.CreateUserApiKeyResponse, error) {
u, err := s.env.GetAuthenticator().AuthenticatedUser(ctx)
if err != nil {
return nil, err
}
authdb := s.env.GetAuthDB()
if authdb == nil {
return nil, status.UnimplementedError("not implemented")
}
userdb := s.env.GetUserDB()
if userdb == nil {
return nil, status.UnimplementedError("not implemented")
}
// Get user's role-based capabilities within the group.
reqUser, err := userdb.GetUserByIDWithoutAuthCheck(ctx, req.GetUserId())
if err != nil {
return nil, err
}
var groupRole *tables.GroupRole
for _, g := range reqUser.Groups {
if g.Group.GroupID == u.GetGroupID() {
groupRole = g
break
}
}
if groupRole == nil {
return nil, status.PermissionDeniedError("permission denied")
}
roleBasedCapabilities := capabilities.ApplyMask(groupRole.Capabilities, capabilities.UserAPIKeyCapabilitiesMask)
// Note: authdb performs additional authentication checks, such as making
// sure the authenticated user has ORG_ADMIN capability if needed.
apiKey, err := authdb.CreateUserAPIKey(
ctx, u.GetGroupID(), req.GetUserId(), req.GetLabel(),
roleBasedCapabilities, req.GetExpiresIn().AsDuration(),
)
if err != nil {
return nil, err
}
rsp := &apipb.CreateUserApiKeyResponse{
ApiKey: &apipb.ApiKey{
ApiKeyId: apiKey.APIKeyID,
Value: apiKey.Value,
Label: apiKey.Label,
},
}
if apiKey.ExpiryUsec != 0 {
rsp.ApiKey.ExpirationTimestamp = timestamppb.New(time.UnixMicro(apiKey.ExpiryUsec))
}
return rsp, nil
}