forked from pachyderm/pachyderm
/
api_server.go
2885 lines (2717 loc) · 91.6 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 (
"bufio"
"bytes"
"encoding/json"
goerr "errors"
"fmt"
"io"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/pachyderm/pachyderm/src/client"
"github.com/pachyderm/pachyderm/src/client/auth"
"github.com/pachyderm/pachyderm/src/client/limit"
"github.com/pachyderm/pachyderm/src/client/pfs"
"github.com/pachyderm/pachyderm/src/client/pkg/grpcutil"
"github.com/pachyderm/pachyderm/src/client/pps"
"github.com/pachyderm/pachyderm/src/server/pkg/ancestry"
"github.com/pachyderm/pachyderm/src/server/pkg/backoff"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/hashtree"
"github.com/pachyderm/pachyderm/src/server/pkg/log"
"github.com/pachyderm/pachyderm/src/server/pkg/metrics"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsconsts"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsdb"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsutil"
"github.com/pachyderm/pachyderm/src/server/pkg/uuid"
"github.com/pachyderm/pachyderm/src/server/pkg/watch"
ppsserver "github.com/pachyderm/pachyderm/src/server/pps"
"github.com/pachyderm/pachyderm/src/server/pps/server/githook"
workerpkg "github.com/pachyderm/pachyderm/src/server/worker"
"github.com/robfig/cron"
"github.com/willf/bloom"
etcd "github.com/coreos/etcd/clientv3"
"github.com/gogo/protobuf/jsonpb"
"github.com/gogo/protobuf/types"
logrus "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kube "k8s.io/client-go/kubernetes"
)
const (
// DefaultUserImage is the image used for jobs when the user does not specify
// an image.
DefaultUserImage = "ubuntu:16.04"
// DefaultDatumTries is the default number of times a datum will be tried
// before we give up and consider the job failed.
DefaultDatumTries = 3
)
var (
zeroVal = int64(0)
suite = "pachyderm"
defaultGCMemory = 20 * 1024 * 1024 // 20 MB
pipelineNameMatcher = regexp.MustCompile("^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$")
)
func newErrJobNotFound(job string) error {
return fmt.Errorf("job %v not found", job)
}
func newErrPipelineNotFound(pipeline string) error {
return fmt.Errorf("pipeline %v not found", pipeline)
}
func newErrPipelineExists(pipeline string) error {
return fmt.Errorf("pipeline %v already exists", pipeline)
}
type errEmptyInput struct {
error
}
func newErrEmptyInput(commitID string) *errEmptyInput {
return &errEmptyInput{
error: fmt.Errorf("job was not started due to empty input at commit %v", commitID),
}
}
type errGithookServiceNotFound struct {
error
}
func newErrParentInputsMismatch(parent string) error {
return fmt.Errorf("job does not have the same set of inputs as its parent %v", parent)
}
type ctxAndCancel struct {
ctx context.Context
cancel context.CancelFunc
}
type apiServer struct {
log.Logger
etcdPrefix string
hasher *ppsserver.Hasher
address string
etcdClient *etcd.Client
kubeClient *kube.Clientset
pachClient *client.APIClient
pachClientOnce sync.Once
namespace string
workerImage string
workerSidecarImage string
workerImagePullPolicy string
storageRoot string
storageBackend string
storageHostPath string
iamRole string
imagePullSecret string
noExposeDockerSocket bool
reporter *metrics.Reporter
monitorCancels map[string]func()
workerUsesRoot bool
workerGrpcPort uint16
port uint16
pprofPort uint16
httpPort uint16
peerPort uint16
// collections
pipelines col.Collection
jobs col.Collection
}
func merge(from, to map[string]bool) {
for s := range from {
to[s] = true
}
}
func validateNames(names map[string]bool, input *pps.Input) error {
switch {
case input.Atom != nil:
if names[input.Atom.Name] {
return fmt.Errorf(`name "%s" was used more than once`, input.Atom.Name)
}
names[input.Atom.Name] = true
case input.Pfs != nil:
if names[input.Pfs.Name] {
return fmt.Errorf(`name "%s" was used more than once`, input.Pfs.Name)
}
names[input.Pfs.Name] = true
case input.Cron != nil:
if names[input.Cron.Name] {
return fmt.Errorf(`name "%s" was used more than once`, input.Cron.Name)
}
names[input.Cron.Name] = true
case input.Union != nil:
for _, input := range input.Union {
namesCopy := make(map[string]bool)
merge(names, namesCopy)
if err := validateNames(namesCopy, input); err != nil {
return err
}
// we defer this because subinputs of a union input are allowed to
// have conflicting names but other inputs that are, for example,
// crossed with this union cannot conflict with any of the names it
// might present
defer merge(namesCopy, names)
}
case input.Cross != nil:
for _, input := range input.Cross {
if err := validateNames(names, input); err != nil {
return err
}
}
case input.Git != nil:
if names[input.Git.Name] == true {
return fmt.Errorf(`name "%s" was used more than once`, input.Git.Name)
}
names[input.Git.Name] = true
}
return nil
}
func (a *apiServer) validateInput(pachClient *client.APIClient, pipelineName string, input *pps.Input, job bool) error {
if err := validateNames(make(map[string]bool), input); err != nil {
return err
}
var result error
pps.VisitInput(input, func(input *pps.Input) {
if err := func() error {
set := false
if input.Atom != nil {
set = true
switch {
case len(input.Atom.Name) == 0:
return fmt.Errorf("input must specify a name")
case input.Atom.Name == "out":
return fmt.Errorf("input cannot be named \"out\", as pachyderm " +
"already creates /pfs/out to collect job output")
case input.Atom.Repo == "":
return fmt.Errorf("input must specify a repo")
case input.Atom.Branch == "" && !job:
return fmt.Errorf("input must specify a branch")
case len(input.Atom.Glob) == 0:
return fmt.Errorf("input must specify a glob")
}
// Note that input.Atom.Commit is empty if a) this is a job b) one of
// the job pipeline's input branches has no commits yet
if job && input.Atom.Commit != "" {
// for jobs we check that the input commit exists
if _, err := pachClient.InspectCommit(input.Atom.Repo, input.Atom.Commit); err != nil {
return err
}
} else {
// for pipelines we only check that the repo exists
if _, err := pachClient.InspectRepo(input.Atom.Repo); err != nil {
return err
}
}
}
if input.Pfs != nil {
set = true
switch {
case len(input.Pfs.Name) == 0:
return fmt.Errorf("input must specify a name")
case input.Pfs.Name == "out":
return fmt.Errorf("input cannot be named \"out\", as pachyderm " +
"already creates /pfs/out to collect job output")
case input.Pfs.Repo == "":
return fmt.Errorf("input must specify a repo")
case input.Pfs.Branch == "" && !job:
return fmt.Errorf("input must specify a branch")
case len(input.Pfs.Glob) == 0:
return fmt.Errorf("input must specify a glob")
}
// Note that input.Pfs.Commit is empty if a) this is a job b) one of
// the job pipeline's input branches has no commits yet
if job && input.Pfs.Commit != "" {
// for jobs we check that the input commit exists
if _, err := pachClient.InspectCommit(input.Pfs.Repo, input.Pfs.Commit); err != nil {
return err
}
} else {
// for pipelines we only check that the repo exists
if _, err := pachClient.InspectRepo(input.Pfs.Repo); err != nil {
return err
}
}
}
if input.Cross != nil {
if set {
return fmt.Errorf("multiple input types set")
}
set = true
}
if input.Union != nil {
if set {
return fmt.Errorf("multiple input types set")
}
set = true
}
if input.Cron != nil {
if set {
return fmt.Errorf("multiple input types set")
}
set = true
if _, err := cron.ParseStandard(input.Cron.Spec); err != nil {
return fmt.Errorf("error parsing cron-spec: %v", err)
}
}
if input.Git != nil {
if set {
return fmt.Errorf("multiple input types set")
}
set = true
if err := pps.ValidateGitCloneURL(input.Git.URL); err != nil {
return err
}
}
if !set {
return fmt.Errorf("no input set")
}
return nil
}(); err != nil && result == nil {
result = err
}
})
return result
}
func validateTransform(transform *pps.Transform) error {
return nil
}
func (a *apiServer) validateJob(pachClient *client.APIClient, jobInfo *pps.JobInfo) error {
if err := validateTransform(jobInfo.Transform); err != nil {
return err
}
return a.validateInput(pachClient, jobInfo.Pipeline.Name, jobInfo.Input, true)
}
func (a *apiServer) validateKube() {
errors := false
_, err := a.kubeClient.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
errors = true
logrus.Errorf("unable to access kubernetes nodeslist, Pachyderm will continue to work but it will not be possible to use COEFFICIENT parallelism. error: %v", err)
}
_, err = a.kubeClient.CoreV1().Pods(a.namespace).Watch(metav1.ListOptions{Watch: true})
if err != nil {
errors = true
logrus.Errorf("unable to access kubernetes pods, Pachyderm will continue to work but certain pipeline errors will result in pipelines being stuck indefinitely in \"starting\" state. error: %v", err)
}
pods, err := a.rcPods("pachd")
if err != nil {
errors = true
logrus.Errorf("unable to access kubernetes pods, Pachyderm will continue to work but get-logs will not work. error: %v", err)
} else {
for _, pod := range pods {
_, err = a.kubeClient.CoreV1().Pods(a.namespace).GetLogs(
pod.ObjectMeta.Name, &v1.PodLogOptions{
Container: "pachd",
}).Timeout(10 * time.Second).Do().Raw()
if err != nil {
errors = true
logrus.Errorf("unable to access kubernetes logs, Pachyderm will continue to work but get-logs will not work. error: %v", err)
}
break
}
}
name := uuid.NewWithoutDashes()
labels := map[string]string{"app": 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"},
},
},
},
},
},
}
if _, err := a.kubeClient.CoreV1().ReplicationControllers(a.namespace).Create(rc); err != nil {
if err != nil {
errors = true
logrus.Errorf("unable to create kubernetes replication controllers, Pachyderm will not function properly until this is fixed. error: %v", err)
}
}
if err := a.kubeClient.CoreV1().ReplicationControllers(a.namespace).Delete(name, nil); err != nil {
if err != nil {
errors = true
logrus.Errorf("unable to delete kubernetes replication controllers, Pachyderm function properly but pipeline cleanup will not work. error: %v", err)
}
}
if !errors {
logrus.Infof("validating kubernetes access returned no errors")
}
}
func checkLoggedIn(pachClient *client.APIClient) error {
_, err := pachClient.WhoAmI(pachClient.Ctx(), &auth.WhoAmIRequest{})
if err != nil && !auth.IsErrNotActivated(err) {
return err
}
return nil
}
// 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
)
// authorizePipelineOp checks if the user indicated by 'ctx' is authorized
// to perform 'operation' on the pipeline in 'info'
func (a *apiServer) authorizePipelineOp(pachClient *client.APIClient, operation pipelineOperation, input *pps.Input, output string) error {
ctx := pachClient.Ctx()
me, err := pachClient.WhoAmI(ctx, &auth.WhoAmIRequest{})
if auth.IsErrNotActivated(err) {
return nil // Auth isn't activated, skip authorization completely
} else if err != nil {
return err
}
if input != nil {
// 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)
var eg errgroup.Group
done := make(map[string]struct{}) // don't double-authorize repos
pps.VisitInput(input, func(in *pps.Input) {
var repo string
if in.Pfs != nil {
repo = in.Pfs.Repo
} else if in.Atom != nil {
repo = in.Atom.Repo
} else {
return
}
if _, ok := done[repo]; ok {
return
}
done[repo] = struct{}{}
eg.Go(func() error {
resp, err := pachClient.Authorize(ctx, &auth.AuthorizeRequest{
Repo: repo,
Scope: auth.Scope_READER,
})
if err != nil {
return err
}
if !resp.Authorized {
return &auth.ErrNotAuthorized{
Subject: me.Username,
Repo: repo,
Required: auth.Scope_READER,
}
}
return nil
})
})
if err := eg.Wait(); err != nil {
return err
}
}
// Check that the user is authorized to write to the output repo.
// Note: authorizePipelineOp is called before CreateRepo creates a
// PipelineInfo proto in etcd, so PipelineManager won't have created an output
// repo yet, and it's possible to check that the output repo doesn't exist
// (if it did exist, we'd have to check that the user has permission to write
// to it, and this is simpler)
var required auth.Scope
switch operation {
case pipelineOpCreate:
if _, err := pachClient.InspectRepo(output); err == nil {
return fmt.Errorf("cannot overwrite repo \"%s\" with new output repo", output)
} else if !isNotFoundErr(err) {
return err
}
case pipelineOpListDatum, pipelineOpGetLogs:
required = auth.Scope_READER
case pipelineOpUpdate:
required = auth.Scope_WRITER
case pipelineOpDelete:
required = auth.Scope_OWNER
default:
return fmt.Errorf("internal error, unrecognized operation %v", operation)
}
if required != auth.Scope_NONE {
resp, err := pachClient.Authorize(ctx, &auth.AuthorizeRequest{
Repo: output,
Scope: required,
})
if err != nil {
return err
}
if !resp.Authorized {
return &auth.ErrNotAuthorized{
Subject: me.Username,
Repo: output,
Required: required,
}
}
}
return nil
}
func (a *apiServer) CreateJob(ctx context.Context, request *pps.CreateJobRequest) (response *pps.Job, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
pachClient := a.getPachClient().WithCtx(ctx)
ctx = pachClient.Ctx() // pachClient will propagate auth info
if err := checkLoggedIn(pachClient); err != nil {
return nil, err
}
job := client.NewJob(uuid.NewWithoutDashes())
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
jobPtr := &pps.EtcdJobInfo{
Job: job,
OutputCommit: request.OutputCommit,
Pipeline: request.Pipeline,
Stats: &pps.ProcessStats{},
}
return ppsutil.UpdateJobState(a.pipelines.ReadWrite(stm), a.jobs.ReadWrite(stm), jobPtr, pps.JobState_JOB_STARTING, "")
})
if err != nil {
return nil, err
}
return job, nil
}
func (a *apiServer) InspectJob(ctx context.Context, request *pps.InspectJobRequest) (response *pps.JobInfo, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
pachClient := a.getPachClient().WithCtx(ctx)
if err := checkLoggedIn(pachClient); err != nil {
return nil, err
}
if request.Job == nil && request.OutputCommit == nil {
return nil, fmt.Errorf("must specify either a Job or an OutputCommit")
}
jobs := a.jobs.ReadOnly(ctx)
if request.OutputCommit != nil {
if request.Job != nil {
return nil, fmt.Errorf("can't set both Job and OutputCommit")
}
ci, err := pachClient.InspectCommit(request.OutputCommit.Repo.Name, request.OutputCommit.ID)
if err != nil {
return nil, err
}
if err := a.listJob(pachClient, nil, ci.Commit, nil, func(ji *pps.JobInfo) error {
if request.Job != nil {
return fmt.Errorf("internal error, more than 1 Job has output commit: %v (this is likely a bug)", request.OutputCommit)
}
request.Job = ji.Job
return nil
}); err != nil {
return nil, err
}
if request.Job == nil {
return nil, fmt.Errorf("job with output commit %s not found", request.OutputCommit.ID)
}
}
if request.BlockState {
watcher, err := jobs.WatchOne(request.Job.ID)
if err != nil {
return nil, err
}
defer watcher.Close()
for {
ev, ok := <-watcher.Watch()
if !ok {
return nil, fmt.Errorf("the stream for job updates closed unexpectedly")
}
switch ev.Type {
case watch.EventError:
return nil, ev.Err
case watch.EventDelete:
return nil, fmt.Errorf("job %s was deleted", request.Job.ID)
case watch.EventPut:
var jobID string
jobPtr := &pps.EtcdJobInfo{}
if err := ev.Unmarshal(&jobID, jobPtr); err != nil {
return nil, err
}
if ppsutil.IsTerminal(jobPtr.State) {
return a.jobInfoFromPtr(pachClient, jobPtr)
}
}
}
}
jobPtr := &pps.EtcdJobInfo{}
if err := jobs.Get(request.Job.ID, jobPtr); err != nil {
return nil, err
}
jobInfo, err := a.jobInfoFromPtr(pachClient, jobPtr)
if err != nil {
return nil, err
}
// If the job is running we fill in WorkerStatus field, otherwise we just
// return the jobInfo.
if jobInfo.State != pps.JobState_JOB_RUNNING {
return jobInfo, nil
}
workerPoolID := ppsutil.PipelineRcName(jobInfo.Pipeline.Name, jobInfo.PipelineVersion)
workerStatus, err := workerpkg.Status(ctx, workerPoolID, a.etcdClient, a.etcdPrefix, a.workerGrpcPort)
if err != nil {
logrus.Errorf("failed to get worker status with err: %s", err.Error())
} 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 {
jobInfo.WorkerStatus = append(jobInfo.WorkerStatus, status)
}
}
}
return jobInfo, nil
}
// listJob is the internal implementation of ListJob shared between ListJob and
// ListJobStream. When ListJob is removed, this should be inlined into
// ListJobStream.
func (a *apiServer) listJob(pachClient *client.APIClient, pipeline *pps.Pipeline, outputCommit *pfs.Commit, inputCommits []*pfs.Commit, f func(*pps.JobInfo) error) error {
authIsActive := true
me, err := pachClient.WhoAmI(pachClient.Ctx(), &auth.WhoAmIRequest{})
if auth.IsErrNotActivated(err) {
authIsActive = false
} else if err != nil {
return err
}
if authIsActive && pipeline != nil {
// 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.
resp, err := pachClient.Authorize(pachClient.Ctx(), &auth.AuthorizeRequest{
Repo: pipeline.Name,
Scope: auth.Scope_READER,
})
if err != nil {
return err
}
if !resp.Authorized {
return &auth.ErrNotAuthorized{
Subject: me.Username,
Repo: pipeline.Name,
Required: auth.Scope_READER,
}
}
}
if outputCommit != nil {
outputCommit, err = a.resolveCommit(pachClient, outputCommit)
if err != nil {
return err
}
}
for i, inputCommit := range inputCommits {
inputCommits[i], err = a.resolveCommit(pachClient, inputCommit)
if err != nil {
return err
}
}
jobs := a.jobs.ReadOnly(pachClient.Ctx())
jobPtr := &pps.EtcdJobInfo{}
_f := func(key string) error {
jobInfo, err := a.jobInfoFromPtr(pachClient, jobPtr)
if err != nil {
if isNotFoundErr(err) {
// This can happen if a user deletes an upstream commit and thereby
// deletes this job's output commit, but doesn't delete the etcdJobInfo.
// In this case, the job is effectively deleted, but isn't removed from
// etcd yet.
return nil
} else if auth.IsErrNotAuthorized(err) {
return nil // skip job--see note under 'authIsActive && pipeline != nil'
}
return err
}
if len(inputCommits) > 0 {
found := make([]bool, len(inputCommits))
pps.VisitInput(jobInfo.Input, func(in *pps.Input) {
if in.Atom != nil {
for i, inputCommit := range inputCommits {
if in.Atom.Commit == inputCommit.ID {
found[i] = true
}
}
}
if in.Pfs != nil {
for i, inputCommit := range inputCommits {
if in.Pfs.Commit == inputCommit.ID {
found[i] = true
}
}
}
})
for _, found := range found {
if !found {
return nil
}
}
}
return f(jobInfo)
}
if pipeline != nil {
return jobs.GetByIndex(ppsdb.JobsPipelineIndex, pipeline, jobPtr, col.DefaultOptions, _f)
} else if outputCommit != nil {
return jobs.GetByIndex(ppsdb.JobsOutputIndex, outputCommit, jobPtr, col.DefaultOptions, _f)
} else {
return jobs.List(jobPtr, col.DefaultOptions, _f)
}
}
func (a *apiServer) jobInfoFromPtr(pachClient *client.APIClient, jobPtr *pps.EtcdJobInfo) (*pps.JobInfo, error) {
result := &pps.JobInfo{
Job: jobPtr.Job,
Pipeline: jobPtr.Pipeline,
OutputCommit: jobPtr.OutputCommit,
Restart: jobPtr.Restart,
DataProcessed: jobPtr.DataProcessed,
DataSkipped: jobPtr.DataSkipped,
DataTotal: jobPtr.DataTotal,
DataFailed: jobPtr.DataFailed,
Stats: jobPtr.Stats,
StatsCommit: jobPtr.StatsCommit,
State: jobPtr.State,
Reason: jobPtr.Reason,
Started: jobPtr.Started,
Finished: jobPtr.Finished,
}
commitInfo, err := pachClient.InspectCommit(jobPtr.OutputCommit.Repo.Name, jobPtr.OutputCommit.ID)
if err != nil {
if isNotFoundErr(err) {
if _, err := a.DeleteJob(pachClient.Ctx(), &pps.DeleteJobRequest{Job: jobPtr.Job}); err != nil {
return nil, err
}
return nil, fmt.Errorf("job %s not found", jobPtr.Job.ID)
}
return nil, err
}
var specCommit *pfs.Commit
for i, provCommit := range commitInfo.Provenance {
provBranch := commitInfo.BranchProvenance[i]
if provBranch.Repo.Name == ppsconsts.SpecRepo && provBranch.Name == jobPtr.Pipeline.Name {
specCommit = provCommit
break
}
}
if specCommit == nil {
return nil, fmt.Errorf("couldn't find spec commit for job %s, (this is likely a bug)", jobPtr.Job.ID)
}
pipelinePtr := &pps.EtcdPipelineInfo{}
if err := a.pipelines.ReadOnly(pachClient.Ctx()).Get(jobPtr.Pipeline.Name, pipelinePtr); err != nil {
return nil, 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.
pipelinePtr.SpecCommit = specCommit
pipelineInfo, err := ppsutil.GetPipelineInfo(pachClient, pipelinePtr)
if err != nil {
return nil, err
}
result.Transform = pipelineInfo.Transform
result.PipelineVersion = pipelineInfo.Version
result.ParallelismSpec = pipelineInfo.ParallelismSpec
result.Egress = pipelineInfo.Egress
result.Service = pipelineInfo.Service
result.OutputRepo = &pfs.Repo{Name: jobPtr.Pipeline.Name}
result.OutputBranch = pipelineInfo.OutputBranch
result.ResourceRequests = pipelineInfo.ResourceRequests
result.ResourceLimits = pipelineInfo.ResourceLimits
result.Input = ppsutil.JobInput(pipelineInfo, commitInfo)
result.EnableStats = pipelineInfo.EnableStats
result.Salt = pipelineInfo.Salt
result.Batch = pipelineInfo.Batch
result.ChunkSpec = pipelineInfo.ChunkSpec
result.DatumTimeout = pipelineInfo.DatumTimeout
result.JobTimeout = pipelineInfo.JobTimeout
result.DatumTries = pipelineInfo.DatumTries
result.SchedulingSpec = pipelineInfo.SchedulingSpec
result.PodSpec = pipelineInfo.PodSpec
result.PodPatch = pipelineInfo.PodPatch
return result, nil
}
func (a *apiServer) ListJob(ctx context.Context, request *pps.ListJobRequest) (response *pps.JobInfos, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) {
if response != nil && len(response.JobInfo) > client.MaxListItemsLog {
logrus.Infof("Response contains %d objects; logging the first %d", len(response.JobInfo), client.MaxListItemsLog)
a.Log(request, &pps.JobInfos{JobInfo: response.JobInfo[:client.MaxListItemsLog]}, retErr, time.Since(start))
} else {
a.Log(request, response, retErr, time.Since(start))
}
}(time.Now())
pachClient := a.getPachClient().WithCtx(ctx)
var jobInfos []*pps.JobInfo
if err := a.listJob(pachClient, request.Pipeline, request.OutputCommit, request.InputCommit, func(ji *pps.JobInfo) error {
jobInfos = append(jobInfos, ji)
return nil
}); err != nil {
return nil, err
}
return &pps.JobInfos{JobInfo: jobInfos}, nil
}
func (a *apiServer) ListJobStream(request *pps.ListJobRequest, resp pps.API_ListJobStreamServer) (retErr error) {
func() { a.Log(request, nil, nil, 0) }()
sent := 0
defer func(start time.Time) {
a.Log(request, fmt.Sprintf("stream containing %d JobInfos", sent), retErr, time.Since(start))
}(time.Now())
pachClient := a.getPachClient().WithCtx(resp.Context())
return a.listJob(pachClient, request.Pipeline, request.OutputCommit, request.InputCommit, func(ji *pps.JobInfo) error {
if err := resp.Send(ji); err != nil {
return err
}
sent++
return nil
})
}
func (a *apiServer) FlushJob(request *pps.FlushJobRequest, resp pps.API_FlushJobServer) (retErr error) {
func() { a.Log(request, nil, nil, 0) }()
sent := 0
defer func(start time.Time) {
a.Log(request, fmt.Sprintf("stream containing %d JobInfos", sent), retErr, time.Since(start))
}(time.Now())
pachClient := a.getPachClient().WithCtx(resp.Context())
if err := checkLoggedIn(pachClient); err != nil {
return err
}
var toRepos []*pfs.Repo
for _, pipeline := range request.ToPipelines {
toRepos = append(toRepos, client.NewRepo(pipeline.Name))
}
return pachClient.FlushCommitF(request.Commits, toRepos, func(ci *pfs.CommitInfo) error {
var jis []*pps.JobInfo
if err := a.listJob(pachClient, nil, ci.Commit, nil, func(ji *pps.JobInfo) error {
jis = append(jis, ji)
return nil
}); err != nil {
return err
}
if len(jis) == 0 {
// This is possible because the commit may be part of the stats
// branch of a pipeline, in which case it's not the output commit
// of any job, thus we ignore it, the job will be returned in
// another call to this function, the one for the job's output
// commit.
return nil
}
if len(jis) > 1 {
return fmt.Errorf("found too many jobs (%d) for output commit: %s/%s", len(jis), ci.Commit.Repo.Name, ci.Commit.ID)
}
// Even though the commit has been finished the job isn't necessarily
// finished yet, so we block on its state as well.
ji, err := a.InspectJob(resp.Context(), &pps.InspectJobRequest{Job: jis[0].Job, BlockState: true})
if err != nil {
return err
}
return resp.Send(ji)
})
}
func (a *apiServer) DeleteJob(ctx context.Context, request *pps.DeleteJobRequest) (response *types.Empty, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
pachClient := a.getPachClient().WithCtx(ctx)
if err := checkLoggedIn(pachClient); err != nil {
return nil, err
}
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
return a.jobs.ReadWrite(stm).Delete(request.Job.ID)
})
if err != nil {
return nil, err
}
return &types.Empty{}, nil
}
func (a *apiServer) StopJob(ctx context.Context, request *pps.StopJobRequest) (response *types.Empty, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
pachClient := a.getPachClient().WithCtx(ctx)
if err := checkLoggedIn(pachClient); err != nil {
return nil, err
}
// Lookup jobInfo
jobPtr := &pps.EtcdJobInfo{}
if err := a.jobs.ReadOnly(ctx).Get(request.Job.ID, jobPtr); err != nil {
return nil, err
}
// Finish the job's output commit without a tree -- worker/master will mark
// the job 'killed'
if _, err := pachClient.PfsAPIClient.FinishCommit(ctx,
&pfs.FinishCommitRequest{
Commit: jobPtr.OutputCommit,
Empty: true,
}); err != nil {
return nil, err
}
return &types.Empty{}, nil
}
func (a *apiServer) RestartDatum(ctx context.Context, request *pps.RestartDatumRequest) (response *types.Empty, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
pachClient := a.getPachClient().WithCtx(ctx)
if err := checkLoggedIn(pachClient); err != nil {
return nil, err
}
jobInfo, err := a.InspectJob(ctx, &pps.InspectJobRequest{
Job: request.Job,
})
if err != nil {
return nil, err
}
workerPoolID := ppsutil.PipelineRcName(jobInfo.Pipeline.Name, jobInfo.PipelineVersion)
if err := workerpkg.Cancel(ctx, workerPoolID, a.etcdClient, a.etcdPrefix, a.workerGrpcPort, request.Job.ID, request.DataFilters); err != nil {
return nil, err
}
return &types.Empty{}, nil
}
// listDatum contains our internal implementation of ListDatum, which is shared
// between ListDatum and ListDatumStream. When ListDatum is removed, this should
// be inlined into ListDatumStream
func (a *apiServer) listDatum(pachClient *client.APIClient, job *pps.Job, page, pageSize int64) (response *pps.ListDatumResponse, retErr error) {
if err := checkLoggedIn(pachClient); err != nil {
return nil, err
}
response = &pps.ListDatumResponse{}
ctx := pachClient.Ctx()
pfsClient := pachClient.PfsAPIClient
// get information about 'job'
jobInfo, err := a.InspectJob(ctx, &pps.InspectJobRequest{
Job: &pps.Job{
ID: job.ID,
},
})
if err != nil {
return nil, err
}
// authorize ListDatum (must have READER access to all inputs)
if err := a.authorizePipelineOp(pachClient,
pipelineOpListDatum,
jobInfo.Input,
jobInfo.Pipeline.Name,
); err != nil {
return nil, err
}
// helper functions for pagination
getTotalPages := func(totalSize int) int64 {
return (int64(totalSize) + pageSize - 1) / pageSize // == ceil(totalSize/pageSize)
}
getPageBounds := func(totalSize int) (int, int, error) {
start := int(page * pageSize)
end := int((page + 1) * pageSize)
switch {
case totalSize <= start:
return 0, 0, io.EOF
case totalSize <= end:
return start, totalSize, nil
case end < totalSize:
return start, end, nil
}
return 0, 0, goerr.New("getPageBounds: unreachable code")
}
df, err := workerpkg.NewDatumFactory(pachClient, jobInfo.Input)
if err != nil {
return nil, err
}
// If there's no stats commit (job not finished), compute datums using jobInfo
if jobInfo.StatsCommit == nil {
start := 0
end := df.Len()
if pageSize > 0 {
var err error
start, end, err = getPageBounds(df.Len())
if err != nil {
return nil, err