-
Notifications
You must be signed in to change notification settings - Fork 568
/
api_server.go
4048 lines (3788 loc) · 149 KB
/
api_server.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 server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"path"
"sort"
"strings"
"sync"
"time"
"unicode"
"github.com/itchyny/gojq"
opentracing "github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/timestamppb"
v1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"github.com/pachyderm/pachyderm/v2/src/auth"
enterpriseclient "github.com/pachyderm/pachyderm/v2/src/enterprise"
"github.com/pachyderm/pachyderm/v2/src/pfs"
"github.com/pachyderm/pachyderm/v2/src/pps"
enterpriselimits "github.com/pachyderm/pachyderm/v2/src/server/enterprise/limits"
enterprisemetrics "github.com/pachyderm/pachyderm/v2/src/server/enterprise/metrics"
enterprisetext "github.com/pachyderm/pachyderm/v2/src/server/enterprise/text"
pfsServer "github.com/pachyderm/pachyderm/v2/src/server/pfs"
ppsServer "github.com/pachyderm/pachyderm/v2/src/server/pps"
"github.com/pachyderm/pachyderm/v2/src/server/worker/common"
"github.com/pachyderm/pachyderm/v2/src/server/worker/datum"
"github.com/pachyderm/pachyderm/v2/src/server/worker/driver"
workerserver "github.com/pachyderm/pachyderm/v2/src/server/worker/server"
taskapi "github.com/pachyderm/pachyderm/v2/src/task"
"github.com/pachyderm/pachyderm/v2/src/internal/ancestry"
"github.com/pachyderm/pachyderm/v2/src/internal/client"
col "github.com/pachyderm/pachyderm/v2/src/internal/collection"
"github.com/pachyderm/pachyderm/v2/src/internal/cronutil"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
"github.com/pachyderm/pachyderm/v2/src/internal/errutil"
"github.com/pachyderm/pachyderm/v2/src/internal/grpcutil"
"github.com/pachyderm/pachyderm/v2/src/internal/log"
"github.com/pachyderm/pachyderm/v2/src/internal/lokiutil"
"github.com/pachyderm/pachyderm/v2/src/internal/metrics"
"github.com/pachyderm/pachyderm/v2/src/internal/miscutil"
"github.com/pachyderm/pachyderm/v2/src/internal/pachtmpl"
"github.com/pachyderm/pachyderm/v2/src/internal/pctx"
"github.com/pachyderm/pachyderm/v2/src/internal/pfsfile"
"github.com/pachyderm/pachyderm/v2/src/internal/ppsdb"
"github.com/pachyderm/pachyderm/v2/src/internal/ppsload"
"github.com/pachyderm/pachyderm/v2/src/internal/ppsutil"
"github.com/pachyderm/pachyderm/v2/src/internal/serde"
"github.com/pachyderm/pachyderm/v2/src/internal/task"
"github.com/pachyderm/pachyderm/v2/src/internal/tracing"
"github.com/pachyderm/pachyderm/v2/src/internal/tracing/extended"
txnenv "github.com/pachyderm/pachyderm/v2/src/internal/transactionenv"
"github.com/pachyderm/pachyderm/v2/src/internal/transactionenv/txncontext"
"github.com/pachyderm/pachyderm/v2/src/internal/uuid"
"github.com/pachyderm/pachyderm/v2/src/internal/watch"
)
const (
// DefaultUserImage is the image used for jobs when the user does not specify
// an image.
DefaultUserImage = "ubuntu:20.04"
// DefaultDatumTries is the default number of times a datum will be tried
// before we give up and consider the job failed.
DefaultDatumTries = 3
// DefaultLogsFrom is the default duration to return logs from, i.e. by
// default we return logs from up to 24 hours ago.
DefaultLogsFrom = time.Hour * 24
// jobClockSkew is how much earlier than the job start time to look for
// logs. It is an attempt to account for clock skew.
jobClockSkew = time.Hour
ppsTaskNamespace = "/pps"
maxPipelineNameLength = 51
// dnsLabelLimit is the maximum length of a ReplicationController
// or Service name.
dnsLabelLimit = 63
)
var (
suite = "pachyderm"
pipelineLastOkMetric = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "pipeline_last_ok_at",
Help: "The last time a pipeline was running within the expected time, as a Unix timestamp.",
}, []string{"pipeline", "project"})
)
// apiServer implements the public interface of the Pachyderm Pipeline System,
// including all RPCs defined in the protobuf spec.
type apiServer struct {
pps.UnsafeAPIServer
etcdPrefix string
env Env
txnEnv *txnenv.TransactionEnv
namespace string
workerImage string
workerSidecarImage string
workerImagePullPolicy string
storageRoot string
storageBackend string
storageHostPath string
imagePullSecrets string
reporter *metrics.Reporter
workerUsesRoot bool
workerGrpcPort uint16
port uint16
peerPort uint16
gcPercent int
// collections
pipelines col.PostgresCollection
jobs col.PostgresCollection
clusterDefaults col.PostgresCollection
projectDefaults col.PostgresCollection
}
func (a *apiServer) validateInput(pipeline *pps.Pipeline, input *pps.Input) error {
if err := ppsutil.ValidateNames(input); err != nil {
return err
}
return pps.VisitInput(input, func(input *pps.Input) error {
set := false
if input.Pfs != nil {
if input.Pfs.Project == "" {
input.Pfs.Project = pipeline.Project.GetName()
}
set = true
switch {
case input.Pfs.Repo == "":
return errors.Errorf("input must specify a repo")
case input.Pfs.Repo == "out" && input.Pfs.Name == "":
return errors.Errorf("inputs based on repos named \"out\" must have " +
"'name' set, as pachyderm already creates /pfs/out to collect " +
"job output")
case input.Pfs.Branch == "":
return errors.Errorf("input must specify a branch")
case !input.Pfs.S3 && len(input.Pfs.Glob) == 0:
return errors.Errorf("input must specify a glob")
case input.Pfs.S3 && input.Pfs.Glob != "/":
return errors.Errorf("inputs that set 's3' to 'true' must also set " +
"'glob', to \"/\", as the S3 gateway is only able to expose data " +
"at the commit level")
case input.Pfs.S3 && input.Pfs.Lazy:
return errors.Errorf("input cannot specify both 's3' and 'lazy', as " +
"'s3' requires input data to be accessed via Pachyderm's S3 " +
"gateway rather than the file system")
case input.Pfs.S3 && input.Pfs.EmptyFiles:
return errors.Errorf("input cannot specify both 's3' and " +
"'empty_files', as 's3' requires input data to be accessed via " +
"Pachyderm's S3 gateway rather than the file system")
case input.Pfs.Commit != "":
return errors.Errorf("input cannot come from a commit; use a branch with head pointing to the commit")
}
}
if input.Cross != nil {
if set {
return errors.Errorf("multiple input types set")
}
set = true
}
if input.Join != nil {
if set {
return errors.Errorf("multiple input types set")
}
set = true
if ppsutil.ContainsS3Inputs(input) {
// The best datum semantics for s3 inputs embedded in join expressions
// are not yet clear, and we see no use case for them yet, so block
// them until we know how they should work
return errors.Errorf("S3 inputs in join expressions are not supported")
}
}
if input.Group != nil {
if set {
return errors.Errorf("multiple input types set")
}
set = true
if ppsutil.ContainsS3Inputs(input) {
// See above for "joins"; block s3 inputs in group expressions until
// we know how they should work
return errors.Errorf("S3 inputs in group expressions are not supported")
}
}
if input.Union != nil {
if set {
return errors.Errorf("multiple input types set")
}
set = true
if ppsutil.ContainsS3Inputs(input) {
// See above for "joins"; block s3 inputs in union expressions until
// we know how they should work
return errors.Errorf("S3 inputs in union expressions are not supported")
}
}
if input.Cron != nil {
if input.Cron.Project == "" {
input.Cron.Project = pipeline.Project.GetName()
}
if set {
return errors.Errorf("multiple input types set")
}
set = true
if _, err := cronutil.ParseCronExpression(input.Cron.Spec); err != nil {
return errors.Wrapf(err, "error parsing cron-spec")
}
}
if !set {
return errors.Errorf("no input set")
}
return nil
})
}
func validateTransform(transform *pps.Transform) error {
if transform == nil {
return errors.Errorf("pipeline must specify a transform")
}
if transform.Image == "" {
return errors.Errorf("pipeline transform must contain an image")
}
return nil
}
func (a *apiServer) validateKube(ctx context.Context) {
ctx = pctx.Child(ctx, "validateKube")
errors := false
kubeClient := a.env.KubeClient
log.Debug(ctx, "checking if a pod watch can be created")
_, err := kubeClient.CoreV1().Pods(a.namespace).Watch(ctx, metav1.ListOptions{Watch: true})
if err != nil {
errors = true
log.Error(ctx, "unable to access kubernetes pods, Pachyderm will continue to work but certain pipeline errors will result in pipelines being stuck indefinitely in \"starting\" state.", zap.Error(err))
} else {
log.Debug(ctx, "pod watch ok")
}
log.Debug(ctx, "checking if pachd pods can be read")
pods, err := a.pachdPods(ctx)
if err != nil || len(pods) == 0 {
errors = true
log.Error(ctx, "unable to access kubernetes pods, Pachyderm will continue to work but 'pachctl logs' may not work", zap.Error(err))
} else {
log.Debug(ctx, "pachd pods found ok", zap.Int("count", len(pods)))
// No need to check all pods since we're just checking permissions.
pod := pods[0]
log.Debug(ctx, "checking if pod logs can be read", zap.String("target", pod.ObjectMeta.Name))
_, err = kubeClient.CoreV1().Pods(a.namespace).GetLogs(
pod.ObjectMeta.Name, &v1.PodLogOptions{
Container: "pachd",
}).Timeout(10 * time.Second).Do(ctx).Raw()
if err != nil {
errors = true
log.Error(ctx, "unable to access kubernetes logs, Pachyderm will continue to work but 'pachctl logs' may not", zap.Error(err))
} else {
log.Debug(ctx, "pod logs read ok")
}
}
name := uuid.NewWithoutDashes()
labels := map[string]string{appLabel: name}
rc := &v1.ReplicationController{
TypeMeta: metav1.TypeMeta{
Kind: "ReplicationController",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: labels,
},
Spec: v1.ReplicationControllerSpec{
Selector: labels,
Replicas: new(int32),
Template: &v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: labels,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "name",
Image: DefaultUserImage,
Command: []string{"true"},
},
},
},
},
},
}
log.Debug(ctx, "checking if replication controllers can be created", zap.String("rc", rc.ObjectMeta.Name))
if _, err := kubeClient.CoreV1().ReplicationControllers(a.namespace).Create(ctx, rc, metav1.CreateOptions{}); err != nil {
errors = true
log.Error(ctx, "unable to create kubernetes replication controllers, Pachyderm will not function properly until this is fixed", zap.Error(err))
} else {
log.Debug(ctx, "rc creation ok")
}
log.Debug(ctx, "checking if replication controllers can be deleted", zap.String("rc", rc.ObjectMeta.Name))
if err := kubeClient.CoreV1().ReplicationControllers(a.namespace).Delete(ctx, name, metav1.DeleteOptions{}); err != nil {
errors = true
log.Error(ctx, "unable to delete kubernetes replication controllers, Pachyderm function properly but pipeline cleanup will not work", zap.Error(err))
} else {
log.Debug(ctx, "rc deletion ok")
}
if !errors {
log.Info(ctx, "validated kubernetes access ok")
}
}
// authorizing a pipeline operation varies slightly depending on whether the
// pipeline is being created, updated, or deleted
type pipelineOperation uint8
const (
// pipelineOpCreate is required for CreatePipeline
pipelineOpCreate pipelineOperation = iota
// pipelineOpListDatum is required for ListDatum
pipelineOpListDatum
// pipelineOpGetLogs is required for GetLogs
pipelineOpGetLogs
// pipelineOpUpdate is required for UpdatePipeline
pipelineOpUpdate
// pipelineOpUpdate is required for DeletePipeline
pipelineOpDelete
// pipelineOpStartStop is required for StartPipeline and StopPipeline
pipelineOpStartStop
)
// authorizePipelineOp checks if the user indicated by 'ctx' is authorized
// to perform 'operation' on the pipeline in 'info'
func (a *apiServer) authorizePipelineOp(ctx context.Context, operation pipelineOperation, input *pps.Input, projectName, outputName string) error {
return a.txnEnv.WithReadContext(ctx, func(txnCtx *txncontext.TransactionContext) error {
return a.authorizePipelineOpInTransaction(ctx, txnCtx, operation, input, projectName, outputName)
})
}
// authorizePipelineOpInTransaction is identical to authorizePipelineOp, but runs in the provided transaction
func (a *apiServer) authorizePipelineOpInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, operation pipelineOperation, input *pps.Input, projectName, outputName string) error {
_, err := txnCtx.WhoAmI()
if auth.IsErrNotActivated(err) {
return nil // Auth isn't activated, skip authorization completely
} else if err != nil {
return err
}
if input != nil && operation != pipelineOpDelete && operation != pipelineOpStartStop {
// Check that the user is authorized to read all input repos, and write to the
// output repo (which the pipeline needs to be able to do on the user's
// behalf)
done := make(map[string]struct{}) // don't double-authorize repos
if err := pps.VisitInput(input, func(in *pps.Input) error {
var project, repo string
if in.Pfs != nil {
if in.Pfs.Project == "" {
project = projectName
} else {
project = in.Pfs.Project
}
repo = in.Pfs.Repo
} else {
return nil
}
if _, ok := done[repo]; ok {
return nil
}
done[repo] = struct{}{}
err := a.env.AuthServer.CheckRepoIsAuthorizedInTransaction(txnCtx, &pfs.Repo{Type: pfs.UserRepoType, Project: &pfs.Project{Name: project}, Name: repo}, auth.Permission_REPO_READ)
return errors.EnsureStack(err)
}); err != nil {
return err
}
}
// Check that the user is authorized to write to the output repo
if outputName != "" {
var required auth.Permission
switch operation {
case pipelineOpCreate:
// no permissions needed, we will error later if the repo already exists
return nil
case pipelineOpListDatum, pipelineOpGetLogs:
required = auth.Permission_REPO_READ
case pipelineOpUpdate, pipelineOpStartStop:
required = auth.Permission_REPO_WRITE
case pipelineOpDelete:
if _, err := a.env.PFSServer.InspectRepoInTransaction(ctx, txnCtx, &pfs.InspectRepoRequest{
Repo: client.NewRepo(projectName, outputName),
}); errutil.IsNotFoundError(err) {
// special case: the pipeline output repo has been deleted (so the
// pipeline is now invalid). It should be possible to delete the pipeline.
return nil
}
required = auth.Permission_REPO_DELETE
default:
return errors.Errorf("internal error, unrecognized operation %v", operation)
}
if err := a.env.AuthServer.CheckRepoIsAuthorizedInTransaction(txnCtx, &pfs.Repo{Type: pfs.UserRepoType, Project: &pfs.Project{Name: projectName}, Name: outputName}, required); err != nil {
return errors.EnsureStack(err)
}
}
return nil
}
func (a *apiServer) UpdateJobState(ctx context.Context, request *pps.UpdateJobStateRequest) (response *emptypb.Empty, retErr error) {
if err := a.txnEnv.WithTransaction(ctx, func(txn txnenv.Transaction) error {
return errors.EnsureStack(txn.UpdateJobState(request))
}); err != nil {
return nil, err
}
return &emptypb.Empty{}, nil
}
func (a *apiServer) UpdateJobStateInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, request *pps.UpdateJobStateRequest) error {
jobs := a.jobs.ReadWrite(txnCtx.SqlTx)
jobInfo := &pps.JobInfo{}
if err := jobs.Get(ppsdb.JobKey(request.Job), jobInfo); err != nil {
return errors.EnsureStack(err)
}
if pps.IsTerminal(jobInfo.State) {
return ppsServer.ErrJobFinished{Job: jobInfo.Job}
}
jobInfo.Restart = request.Restart
jobInfo.DataProcessed = request.DataProcessed
jobInfo.DataSkipped = request.DataSkipped
jobInfo.DataFailed = request.DataFailed
jobInfo.DataRecovered = request.DataRecovered
jobInfo.DataTotal = request.DataTotal
jobInfo.Stats = request.Stats
return ppsutil.UpdateJobState(a.pipelines.ReadWrite(txnCtx.SqlTx), jobs, jobInfo, request.State, request.Reason)
}
// InspectJob implements the protobuf pps.InspectJob RPC
func (a *apiServer) InspectJob(ctx context.Context, request *pps.InspectJobRequest) (response *pps.JobInfo, retErr error) {
if request.Job == nil {
return nil, errors.Errorf("must specify a job")
}
ensurePipelineProject(request.Job.Pipeline)
jobs := a.jobs.ReadOnly(ctx)
// Make sure the job exists
// TODO: there's a race condition between this check and the watch below where
// a deleted job could make this block forever.
jobInfo := &pps.JobInfo{}
if err := jobs.Get(ppsdb.JobKey(request.Job), jobInfo); err != nil {
return nil, errors.EnsureStack(err)
}
if request.Wait {
watcher, err := jobs.WatchOne(ppsdb.JobKey(request.Job))
if err != nil {
return nil, errors.EnsureStack(err)
}
defer watcher.Close()
watchLoop:
for {
ev, ok := <-watcher.Watch()
if !ok {
return nil, errors.Errorf("the stream for job updates closed unexpectedly")
}
switch ev.Type {
case watch.EventError:
return nil, ev.Err
case watch.EventDelete:
return nil, errors.Errorf("job %s was deleted", request.Job.Id)
case watch.EventPut:
var jobID string
if err := ev.Unmarshal(&jobID, jobInfo); err != nil {
return nil, err
}
if pps.IsTerminal(jobInfo.State) {
break watchLoop
}
}
}
}
if request.Details {
if err := a.getJobDetails(ctx, jobInfo); err != nil {
return nil, err
}
}
return jobInfo, nil
}
// InspectJobSet implements the protobuf pps.InspectJobSet RPC
func (a *apiServer) InspectJobSet(request *pps.InspectJobSetRequest, server pps.API_InspectJobSetServer) (retErr error) {
ctx := server.Context()
pachClient := a.env.GetPachClient(ctx)
cb := func(projectName, pipelineName string) error {
jobInfo, err := a.InspectJob(ctx, &pps.InspectJobRequest{
Job: &pps.Job{
Pipeline: &pps.Pipeline{
Project: &pfs.Project{
Name: projectName,
},
Name: pipelineName,
},
Id: request.JobSet.Id,
},
Details: request.Details,
})
if err != nil {
// Not all commits are guaranteed to have an associated job - skip over it
if errutil.IsNotFoundError(err) {
return nil
}
return err
}
return errors.EnsureStack(server.Send(jobInfo))
}
if err := forEachCommitInJob(pachClient, request.JobSet.Id, request.Wait, func(ci *pfs.CommitInfo) error {
if ci.Commit.Repo.Type != pfs.UserRepoType {
return nil
}
return cb(ci.Commit.Repo.Project.GetName(), ci.Commit.Repo.Name)
}); err != nil {
if pfsServer.IsCommitSetNotFoundErr(err) {
// There are no commits for this ID, but there may still be jobs, query
// the jobs table directly and don't worry about the topological sort
// Load all the jobs eagerly to avoid a nested query
pipelines := []*pps.Pipeline{}
jobInfo := &pps.JobInfo{}
if err := a.jobs.ReadOnly(pachClient.Ctx()).GetByIndex(ppsdb.JobsJobSetIndex, request.JobSet.Id, jobInfo, col.DefaultOptions(), func(string) error {
pipelines = append(pipelines, jobInfo.Job.Pipeline)
return nil
}); err != nil {
return errors.EnsureStack(err)
}
for _, pipeline := range pipelines {
if err := cb(pipeline.Project.GetName(), pipeline.Name); err != nil {
return err
}
}
return nil
}
return err
}
return nil
}
func forEachCommitInJob(pachClient *client.APIClient, jobID string, wait bool, cb func(*pfs.CommitInfo) error) error {
if wait {
// Note that while this will return jobs in the same topological sort as the
// commitset, it will block on commits that don't have a job associated with
// them (aliases and input commits, for example).
return pachClient.WaitCommitSet(jobID, cb)
}
commitInfos, err := pachClient.InspectCommitSet(jobID)
if err != nil {
return err
}
for _, ci := range commitInfos {
if err := cb(ci); err != nil {
return err
}
}
return nil
}
// ListJobSet implements the protobuf pps.ListJobSet RPC
func (a *apiServer) ListJobSet(request *pps.ListJobSetRequest, serv pps.API_ListJobSetServer) (retErr error) {
pachClient := a.env.GetPachClient(serv.Context())
// Track the jobsets we've already processed
seen := map[string]struct{}{}
filterJob, err := newMessageFilterFunc(request.GetJqFilter(), request.GetProjects())
if err != nil {
return errors.Wrap(err, "error creating message filter function")
}
number := request.Number
if number < 0 {
return errors.Errorf("number must be non-negative")
}
if number == 0 {
number = math.MaxInt64
}
paginationMarker := request.PaginationMarker
// Return jobsets by the newest job in each set (which can be at a different
// timestamp due to triggers or deferred processing)
jobInfo := &pps.JobInfo{}
opts := &col.Options{Target: col.SortByCreateRevision, Order: col.SortDescend}
if request.Reverse {
opts.Order = col.SortAscend
}
if err := a.jobs.ReadOnly(serv.Context()).List(jobInfo, opts, func(string) error {
if number == 0 {
return errutil.ErrBreak
}
id := jobInfo.GetJob().GetId()
if _, ok := seen[id]; ok {
return nil
}
seen[id] = struct{}{}
if paginationMarker != nil {
createdAt := time.Unix(int64(jobInfo.Created.GetSeconds()), int64(jobInfo.Created.GetNanos())).UTC()
fromTime := time.Unix(int64(paginationMarker.GetSeconds()), int64(paginationMarker.GetNanos())).UTC()
if createdAt.Equal(fromTime) || !request.Reverse && createdAt.After(fromTime) || request.Reverse && createdAt.Before(fromTime) {
return nil
}
}
jobInfos, err := pachClient.InspectJobSet(id, request.Details)
if err != nil {
return err
}
// jobInfos can contain jobs that belong in the same project or different projects due to commit sets.
var jobInfosFiltered []*pps.JobInfo
for _, ji := range jobInfos {
if ok, err := filterJob(serv.Context(), ji); err != nil {
return errors.Wrap(err, "error filtering job")
} else if !ok {
continue
}
jobInfosFiltered = append(jobInfosFiltered, ji)
}
if len(jobInfosFiltered) == 0 {
return nil
}
if err := serv.Send(&pps.JobSetInfo{
JobSet: client.NewJobSet(id),
Jobs: jobInfosFiltered,
}); err != nil {
return errors.Wrap(err, "error sending JobSet")
}
number--
return nil
}); err != nil && err != errutil.ErrBreak {
return errors.EnsureStack(err)
}
return nil
}
// TODO(provenance): rewrite in terms of CommitSubvenance.
// intersectCommitSets finds all commitsets which involve the specified commits
func (a *apiServer) intersectCommitSets(ctx context.Context, commits []*pfs.Commit) (map[string]struct{}, error) {
intersection := map[string]struct{}{}
if len(commits) == 0 {
return intersection, nil
}
listClient, err := a.env.GetPachClient(ctx).ListCommitSet(ctx, &pfs.ListCommitSetRequest{})
if err != nil {
return nil, err
}
if err := grpcutil.ForEach[*pfs.CommitSetInfo](listClient, func(cs *pfs.CommitSetInfo) error {
provCommits := map[string]struct{}{}
for _, c := range cs.Commits {
for _, p := range c.DirectProvenance {
provCommits[p.String()] = struct{}{}
}
}
allCommits := true
for _, c := range commits {
if _, ok := provCommits[c.String()]; !ok {
allCommits = false
break
}
}
if allCommits {
intersection[cs.CommitSet.Id] = struct{}{}
}
return nil
}); err != nil {
return nil, err
}
return intersection, nil
}
func (a *apiServer) getJobDetails(ctx context.Context, jobInfo *pps.JobInfo) error {
projectName := jobInfo.Job.Pipeline.Project.GetName()
pipelineName := jobInfo.Job.Pipeline.Name
if err := a.env.AuthServer.CheckRepoIsAuthorized(ctx, &pfs.Repo{Type: pfs.UserRepoType, Project: &pfs.Project{Name: projectName}, Name: pipelineName}, auth.Permission_PIPELINE_LIST_JOB); err != nil && !auth.IsErrNotActivated(err) {
return errors.EnsureStack(err)
}
// Override the SpecCommit for the pipeline to be what it was when this job
// was created, this prevents races between updating a pipeline and
// previous jobs running.
pipelineInfo := &pps.PipelineInfo{}
if err := a.pipelines.ReadOnly(ctx).GetUniqueByIndex(
ppsdb.PipelinesVersionIndex,
ppsdb.VersionKey(jobInfo.Job.Pipeline, jobInfo.PipelineVersion),
pipelineInfo); err != nil {
return errors.EnsureStack(err)
}
details := &pps.JobInfo_Details{}
details.Transform = pipelineInfo.Details.Transform
details.ParallelismSpec = pipelineInfo.Details.ParallelismSpec
details.Egress = pipelineInfo.Details.Egress
details.Service = pipelineInfo.Details.Service
details.Spout = pipelineInfo.Details.Spout
details.ResourceRequests = pipelineInfo.Details.ResourceRequests
details.ResourceLimits = pipelineInfo.Details.ResourceLimits
details.SidecarResourceLimits = pipelineInfo.Details.SidecarResourceLimits
details.SidecarResourceRequests = pipelineInfo.Details.SidecarResourceRequests
details.Input = ppsutil.JobInput(pipelineInfo, jobInfo.OutputCommit)
details.Salt = pipelineInfo.Details.Salt
details.DatumSetSpec = pipelineInfo.Details.DatumSetSpec
details.DatumTimeout = pipelineInfo.Details.DatumTimeout
details.JobTimeout = pipelineInfo.Details.JobTimeout
details.DatumTries = pipelineInfo.Details.DatumTries
details.SchedulingSpec = pipelineInfo.Details.SchedulingSpec
details.PodSpec = pipelineInfo.Details.PodSpec
details.PodPatch = pipelineInfo.Details.PodPatch
// If the job is running, we fill in WorkerStatus field, otherwise
// we just return the jobInfo.
if jobInfo.State == pps.JobState_JOB_RUNNING {
var pi = &pps.PipelineInfo{
Pipeline: &pps.Pipeline{
Project: &pfs.Project{Name: projectName},
Name: pipelineName,
},
Version: jobInfo.PipelineVersion,
}
workerStatus, err := workerserver.Status(ctx, pi, a.env.EtcdClient, a.etcdPrefix, a.workerGrpcPort)
if err != nil {
log.Error(ctx, "failed to get worker status", zap.Error(err))
} else {
// It's possible that the workers might be working on datums for other
// jobs, we omit those since they're not part of the status for this
// job.
for _, status := range workerStatus {
if status.JobId == jobInfo.Job.Id {
details.WorkerStatus = append(details.WorkerStatus, status)
}
}
}
}
jobInfo.Details = details
return nil
}
// ListJob implements the protobuf pps.ListJob RPC
func (a *apiServer) ListJob(request *pps.ListJobRequest, resp pps.API_ListJobServer) (retErr error) {
filterJob, err := newMessageFilterFunc(request.GetJqFilter(), request.GetProjects())
if err != nil {
return errors.Wrap(err, "error creating message filter function")
}
ctx := resp.Context()
pipeline := request.GetPipeline()
if pipeline != nil {
ensurePipelineProject(pipeline)
// If 'pipeline is set, check that caller has access to the pipeline's
// output repo; currently, that's all that's required for ListJob.
//
// If 'pipeline' isn't set, then we don't return an error (otherwise, a
// caller without access to a single pipeline's output repo couldn't run
// `pachctl list job` at all) and instead silently skip jobs where the user
// doesn't have access to the job's output repo.
if err := a.env.AuthServer.CheckRepoIsAuthorized(ctx, &pfs.Repo{Type: pfs.UserRepoType, Project: pipeline.Project, Name: pipeline.Name}, auth.Permission_PIPELINE_LIST_JOB); err != nil && !auth.IsErrNotActivated(err) {
return errors.EnsureStack(err)
}
}
number := request.Number
// If number is not set, return all jobs that match the query
if number == 0 {
number = math.MaxInt64
}
// pipelineVersions holds the versions of pipelines that we're interested in
pipelineVersions := make(map[string]bool)
if err := ppsutil.ListPipelineInfo(ctx, a.pipelines, pipeline, request.GetHistory(),
func(ptr *pps.PipelineInfo) error {
pipelineVersions[ppsdb.VersionKey(ptr.Pipeline, ptr.Version)] = true
return nil
}); err != nil {
return err
}
jobs := a.jobs.ReadOnly(ctx)
jobInfo := &pps.JobInfo{}
_f := func(string) error {
if number == 0 {
return errutil.ErrBreak
}
if request.PaginationMarker != nil {
createdAt := time.Unix(int64(jobInfo.Created.GetSeconds()), int64(jobInfo.Created.GetNanos())).UTC()
fromTime := time.Unix(int64(request.PaginationMarker.GetSeconds()), int64(request.PaginationMarker.GetNanos())).UTC()
if createdAt.Equal(fromTime) || !request.Reverse && createdAt.After(fromTime) || request.Reverse && createdAt.Before(fromTime) {
return nil
}
}
if request.GetDetails() {
if err := a.getJobDetails(ctx, jobInfo); err != nil {
if auth.IsErrNotAuthorized(err) {
return nil // skip job--see note at top of function
}
return err
}
}
if len(request.GetInputCommit()) > 0 {
// Only include the job if it's in the set of intersected commitset IDs
commitsets, err := a.intersectCommitSets(ctx, request.GetInputCommit())
if err != nil {
return err
}
if _, ok := commitsets[jobInfo.Job.Id]; !ok {
return nil
}
}
if !pipelineVersions[ppsdb.VersionKey(jobInfo.Job.Pipeline, jobInfo.PipelineVersion)] {
return nil
}
if ok, err := filterJob(ctx, jobInfo); err != nil {
return errors.Wrap(err, "error filtering job")
} else if !ok {
return nil
}
// Erase any AuthToken - this shouldn't be returned to anyone (the workers
// won't use this function to get their auth token)
jobInfo.AuthToken = ""
if err := resp.Send(jobInfo); err != nil {
return errors.Wrap(err, "error sending job")
}
number--
return nil
}
opts := &col.Options{Target: col.SortByCreateRevision, Order: col.SortDescend}
if request.Reverse {
opts.Order = col.SortAscend
}
if pipeline != nil {
err = jobs.GetByIndex(ppsdb.JobsPipelineIndex, ppsdb.JobsPipelineKey(pipeline), jobInfo, opts, _f)
} else {
err = jobs.List(jobInfo, opts, _f)
}
if err != nil && err != errutil.ErrBreak {
if errors.Is(err, context.DeadlineExceeded) {
return status.Error(codes.DeadlineExceeded, err.Error())
}
return errors.EnsureStack(err)
}
return nil
}
// SubscribeJob implements the protobuf pps.SubscribeJob RPC
func (a *apiServer) SubscribeJob(request *pps.SubscribeJobRequest, stream pps.API_SubscribeJobServer) (retErr error) {
ensurePipelineProject(request.GetPipeline())
ctx := stream.Context()
// Validate arguments
if request.Pipeline == nil || request.Pipeline.Name == "" {
return errors.New("pipeline must be specified")
}
if err := a.env.AuthServer.CheckRepoIsAuthorized(ctx, &pfs.Repo{Type: pfs.UserRepoType, Project: request.Pipeline.Project, Name: request.Pipeline.Name}, auth.Permission_PIPELINE_LIST_JOB); err != nil && !auth.IsErrNotActivated(err) {
return errors.EnsureStack(err)
}
// keep track of the jobs that have been sent
seen := map[string]struct{}{}
err := a.jobs.ReadOnly(ctx).WatchByIndexF(ppsdb.JobsTerminalIndex, ppsdb.JobsTerminalKey(request.Pipeline, false), func(ev *watch.Event) error {
var key string
jobInfo := &pps.JobInfo{}
if err := ev.Unmarshal(&key, jobInfo); err != nil {
return errors.Wrapf(err, "unmarshal")
}
if _, ok := seen[key]; ok {
return nil
}
seen[key] = struct{}{}
if request.Details {
if err := a.getJobDetails(ctx, jobInfo); err != nil {
return err
}
}
return errors.EnsureStack(stream.Send(jobInfo))
}, watch.WithSort(col.SortByCreateRevision, col.SortAscend), watch.IgnoreDelete)
return errors.EnsureStack(err)
}
// DeleteJob implements the protobuf pps.DeleteJob RPC
func (a *apiServer) DeleteJob(ctx context.Context, request *pps.DeleteJobRequest) (response *emptypb.Empty, retErr error) {
if request.GetJob() == nil {
return nil, errors.New("job cannot be nil")
}
ensurePipelineProject(request.Job.Pipeline)
if err := a.txnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {
return a.deleteJobInTransaction(ctx, txnCtx, request)
}); err != nil {
return nil, err
}
clearJobCache(a.env.GetPachClient(ctx), ppsdb.JobKey(request.Job))
return &emptypb.Empty{}, nil
}
func (a *apiServer) deleteJobInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, request *pps.DeleteJobRequest) error {
if err := a.stopJob(ctx, txnCtx, request.Job, "job deleted"); err != nil {
return err
}
return errors.EnsureStack(a.jobs.ReadWrite(txnCtx.SqlTx).Delete(ppsdb.JobKey(request.Job)))
}
// StopJob implements the protobuf pps.StopJob RPC
func (a *apiServer) StopJob(ctx context.Context, request *pps.StopJobRequest) (response *emptypb.Empty, retErr error) {
ensurePipelineProject(request.GetJob().GetPipeline())
if err := a.txnEnv.WithTransaction(ctx, func(txn txnenv.Transaction) error {
return errors.EnsureStack(txn.StopJob(request))
}); err != nil {
return nil, err
}
clearJobCache(a.env.GetPachClient(ctx), ppsdb.JobKey(request.Job))
return &emptypb.Empty{}, nil
}
// TODO: Remove when job state transition operations are handled by a background process.
func clearJobCache(pachClient *client.APIClient, tagPrefix string) {
if _, err := pachClient.PfsAPIClient.ClearCache(pachClient.Ctx(), &pfs.ClearCacheRequest{
TagPrefix: tagPrefix,
}); err != nil {
log.Error(pachClient.Ctx(), "errored clearing job cache", zap.Error(err))
}
}
// StopJobInTransaction is identical to StopJob except that it can run inside an
// existing postgres transaction. This is not an RPC.
func (a *apiServer) StopJobInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, request *pps.StopJobRequest) error {
reason := request.Reason
if reason == "" {
reason = "job stopped"
}
return a.stopJob(ctx, txnCtx, request.Job, reason)
}
func (a *apiServer) stopJob(ctx context.Context, txnCtx *txncontext.TransactionContext, job *pps.Job, reason string) error {
jobs := a.jobs.ReadWrite(txnCtx.SqlTx)
if job == nil {
return errors.New("Job must be specified")
}
jobInfo := &pps.JobInfo{}
if err := jobs.Get(ppsdb.JobKey(job), jobInfo); err != nil {
return errors.EnsureStack(err)
}
commitInfo, err := a.env.PFSServer.InspectCommitInTransaction(ctx, txnCtx, &pfs.InspectCommitRequest{
Commit: jobInfo.OutputCommit,
})
if err != nil && !pfsServer.IsCommitNotFoundErr(err) && !pfsServer.IsCommitDeletedErr(err) {
return errors.EnsureStack(err)
}
// TODO: Leaning on the reason rather than state for commit errors seems a bit sketchy, but we don't
// store commit states.
if commitInfo != nil {
if err := a.env.PFSServer.FinishCommitInTransaction(ctx, txnCtx, &pfs.FinishCommitRequest{
Commit: ppsutil.MetaCommit(commitInfo.Commit),
Error: reason,
Force: true,
}); err != nil && !pfsServer.IsCommitNotFoundErr(err) && !pfsServer.IsCommitDeletedErr(err) && !pfsServer.IsCommitFinishedErr(err) {
return errors.EnsureStack(err)
}
if err := a.env.PFSServer.FinishCommitInTransaction(ctx, txnCtx, &pfs.FinishCommitRequest{
Commit: commitInfo.Commit,
Error: reason,
Force: true,
}); err != nil && !pfsServer.IsCommitNotFoundErr(err) && !pfsServer.IsCommitDeletedErr(err) && !pfsServer.IsCommitFinishedErr(err) {
return errors.EnsureStack(err)
}
}
// TODO: We can still not update a job's state if we fail here. This is