forked from pachyderm/pachyderm
/
api_server.go
1857 lines (1707 loc) · 53.9 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"
"fmt"
"io"
"path/filepath"
"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/pkg/uuid"
"github.com/pachyderm/pachyderm/src/client/pps"
"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/ppsdb"
"github.com/pachyderm/pachyderm/src/server/pkg/watch"
ppsserver "github.com/pachyderm/pachyderm/src/server/pps"
workerpkg "github.com/pachyderm/pachyderm/src/server/worker"
"github.com/robfig/cron"
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"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/resource"
"k8s.io/kubernetes/pkg/api/unversioned"
kube "k8s.io/kubernetes/pkg/client/unversioned"
kube_labels "k8s.io/kubernetes/pkg/labels"
)
const (
// MaxPodsPerChunk is the maximum number of pods we can schedule for each
// chunk in case of failures.
MaxPodsPerChunk = 3
// DefaultUserImage is the image used for jobs when the user does not specify
// an image.
DefaultUserImage = "ubuntu:16.04"
)
var (
trueVal = true
suite = "pachyderm"
)
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),
}
}
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.Client
pachClient *client.APIClient
pachClientOnce sync.Once
namespace string
workerImage string
workerSidecarImage string
workerImagePullPolicy string
storageRoot string
storageBackend string
storageHostPath string
reporter *metrics.Reporter
// 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.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
}
}
}
return nil
}
func (a *apiServer) validateInput(ctx context.Context, pipelineName string, input *pps.Input, job bool) error {
pachClient, err := a.getPachClient()
if err != nil {
return err
}
if err := validateNames(make(map[string]bool), input); err != nil {
return err
}
pachClient = pachClient.WithCtx(ctx)
repoBranch := make(map[string]string)
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 input.Atom.Commit == "" && job:
return fmt.Errorf("input must specify a commit")
case len(input.Atom.Glob) == 0:
return fmt.Errorf("input must specify a glob")
}
if repoBranch[input.Atom.Repo] != "" && repoBranch[input.Atom.Repo] != input.Atom.Branch {
return fmt.Errorf("cannot use the same repo in multiple inputs with different branches")
}
repoBranch[input.Atom.Repo] = input.Atom.Branch
if job {
// 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.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.Parse(input.Cron.Spec); err != nil {
return err
}
if _, err := pachClient.InspectRepo(input.Cron.Repo); 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 {
if len(transform.Cmd) == 0 {
return fmt.Errorf("no cmd set")
}
return nil
}
func (a *apiServer) validateJob(ctx context.Context, jobInfo *pps.JobInfo) error {
if err := validateTransform(jobInfo.Transform); err != nil {
return err
}
return a.validateInput(ctx, jobInfo.Pipeline.Name, jobInfo.Input, true)
}
func translateJobInputs(inputs []*pps.JobInput) *pps.Input {
result := &pps.Input{}
for _, input := range inputs {
result.Cross = append(result.Cross,
&pps.Input{
Atom: &pps.AtomInput{
Name: input.Name,
Repo: input.Commit.Repo.Name,
Commit: input.Commit.ID,
Glob: input.Glob,
Lazy: input.Lazy,
},
})
}
return result
}
func untranslateJobInputs(input *pps.Input) []*pps.JobInput {
var result []*pps.JobInput
if input.Cross != nil {
for _, input := range input.Cross {
if input.Atom == nil {
return nil
}
result = append(result, &pps.JobInput{
Name: input.Atom.Name,
Commit: client.NewCommit(input.Atom.Repo, input.Atom.Commit),
Glob: input.Atom.Glob,
Lazy: input.Atom.Lazy,
})
}
}
return result
}
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())
// First translate Inputs field to Input field.
if len(request.Inputs) > 0 {
if request.Input != nil {
return nil, fmt.Errorf("cannot set both Inputs and Input field")
}
request.Input = translateJobInputs(request.Inputs)
}
job := &pps.Job{uuid.NewWithoutUnderscores()}
pps.SortInput(request.Input)
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
jobInfo := &pps.JobInfo{
Job: job,
Transform: request.Transform,
Pipeline: request.Pipeline,
ParallelismSpec: request.ParallelismSpec,
Input: request.Input,
OutputRepo: request.OutputRepo,
OutputBranch: request.OutputBranch,
Started: now(),
Finished: nil,
OutputCommit: nil,
Service: request.Service,
ParentJob: request.ParentJob,
ResourceSpec: request.ResourceSpec,
NewBranch: request.NewBranch,
Incremental: request.Incremental,
Stats: &pps.ProcessStats{},
EnableStats: request.EnableStats,
Salt: request.Salt,
PipelineVersion: request.PipelineVersion,
Batch: request.Batch,
}
if request.Pipeline != nil {
pipelineInfo := new(pps.PipelineInfo)
if err := a.pipelines.ReadWrite(stm).Get(request.Pipeline.Name, pipelineInfo); err != nil {
return err
}
if jobInfo.Salt != pipelineInfo.Salt || jobInfo.PipelineVersion != pipelineInfo.Version {
return fmt.Errorf("job is made from an outdated version of the pipeline")
}
jobInfo.Transform = pipelineInfo.Transform
jobInfo.ParallelismSpec = pipelineInfo.ParallelismSpec
jobInfo.OutputRepo = &pfs.Repo{pipelineInfo.Pipeline.Name}
jobInfo.OutputBranch = pipelineInfo.OutputBranch
jobInfo.Egress = pipelineInfo.Egress
jobInfo.ResourceSpec = pipelineInfo.ResourceSpec
jobInfo.Incremental = pipelineInfo.Incremental
jobInfo.EnableStats = pipelineInfo.EnableStats
} else {
if jobInfo.OutputRepo == nil {
jobInfo.OutputRepo = &pfs.Repo{job.ID}
}
}
if err := a.validateJob(ctx, jobInfo); err != nil {
return err
}
return a.updateJobState(stm, jobInfo, 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())
jobs := a.jobs.ReadOnly(ctx)
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
var jobInfo pps.JobInfo
if err := ev.Unmarshal(&jobID, &jobInfo); err != nil {
return nil, err
}
if jobStateToStopped(jobInfo.State) {
return &jobInfo, nil
}
}
}
}
jobInfo := new(pps.JobInfo)
if err := jobs.Get(request.Job.ID, jobInfo); err != nil {
return nil, err
}
if jobInfo.Input == nil {
jobInfo.Input = translateJobInputs(jobInfo.Inputs)
}
// 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 := ppsserver.PipelineRcName(jobInfo.Pipeline.Name, jobInfo.PipelineVersion)
workerStatus, err := status(ctx, workerPoolID, a.etcdClient, a.etcdPrefix)
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
}
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) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
jobs := a.jobs.ReadOnly(ctx)
var iter col.Iterator
var err error
if request.Pipeline != nil {
iter, err = jobs.GetByIndex(ppsdb.JobsPipelineIndex, request.Pipeline)
} else {
iter, err = jobs.List()
}
if err != nil {
return nil, err
}
var jobInfos []*pps.JobInfo
for {
var jobID string
var jobInfo pps.JobInfo
ok, err := iter.Next(&jobID, &jobInfo)
if err != nil {
return nil, err
}
if !ok {
break
}
if jobInfo.Input == nil {
jobInfo.Input = translateJobInputs(jobInfo.Inputs)
}
jobInfos = append(jobInfos, &jobInfo)
}
return &pps.JobInfos{jobInfos}, nil
}
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())
_, 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())
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
jobs := a.jobs.ReadWrite(stm)
jobInfo := new(pps.JobInfo)
if err := jobs.Get(request.Job.ID, jobInfo); err != nil {
return err
}
return a.updateJobState(stm, jobInfo, pps.JobState_JOB_KILLED)
})
if 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())
jobInfo, err := a.InspectJob(ctx, &pps.InspectJobRequest{
Job: request.Job,
})
if err != nil {
return nil, err
}
workerPoolID := ppsserver.PipelineRcName(jobInfo.Pipeline.Name, jobInfo.PipelineVersion)
if err := cancel(ctx, workerPoolID, a.etcdClient, a.etcdPrefix, request.Job.ID, request.DataFilters); err != nil {
return nil, err
}
return &types.Empty{}, nil
}
func (a *apiServer) ListDatum(ctx context.Context, request *pps.ListDatumRequest) (response *pps.DatumInfos, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
jobInfo, err := a.InspectJob(ctx, &pps.InspectJobRequest{
Job: &pps.Job{
ID: request.Job.ID,
},
})
if err != nil {
return nil, err
}
pachClient, err := a.getPachClient()
if err != nil {
return nil, err
}
pfsClient := pachClient.PfsAPIClient
if jobInfo.StatsCommit == nil {
df, err := workerpkg.NewDatumFactory(ctx, pfsClient, jobInfo.Input)
if err != nil {
return nil, err
}
result := &pps.DatumInfos{}
for i := 0; i < df.Len(); i++ {
datum := df.Datum(i)
id := workerpkg.HashDatum(jobInfo.Pipeline.Name, jobInfo.Salt, datum)
datumInfo := &pps.DatumInfo{
Datum: &pps.Datum{
ID: id,
Job: jobInfo.Job,
},
State: pps.DatumState_STARTING,
}
for _, input := range datum {
datumInfo.Data = append(datumInfo.Data, &pps.InputFile{
Path: input.FileInfo.File.Path,
Hash: input.FileInfo.Hash,
})
}
result.DatumInfo = append(result.DatumInfo, datumInfo)
}
return result, nil
}
// List the files under / to get all the datums
file := &pfs.File{
Commit: jobInfo.StatsCommit,
Path: "/",
}
allFileInfos, err := pfsClient.ListFile(ctx, &pfs.ListFileRequest{file})
if err != nil {
return nil, err
}
datums := make(map[string]*pps.DatumInfo)
// Omit files at the top level that correspond to aggregate job stats
blacklist := map[string]bool{
"stats": true,
"logs": true,
"pfs": true,
}
pathToDatumHash := func(path string) (string, error) {
_, datumHash := filepath.Split(path)
if _, ok := blacklist[datumHash]; ok {
return "", fmt.Errorf("value %v is not a datum hash", datumHash)
}
return datumHash, nil
}
var egGetDatums errgroup.Group
limiter := limit.New(200)
var datumsMutex sync.Mutex
for _, fileInfo := range allFileInfos.FileInfo {
fileInfo := fileInfo
egGetDatums.Go(func() error {
limiter.Acquire()
defer limiter.Release()
datumHash, err := pathToDatumHash(fileInfo.File.Path)
if err != nil {
// not a datum, nothing to do here
return nil
}
datum, err := a.getDatum(ctx, jobInfo.StatsCommit.Repo.Name, jobInfo.StatsCommit, request.Job.ID, datumHash)
if err != nil {
return err
}
datumsMutex.Lock()
defer datumsMutex.Unlock()
datums[datumHash] = datum
return nil
})
}
err = egGetDatums.Wait()
if err != nil {
return nil, err
}
var datumInfos []*pps.DatumInfo
for datumHash, datum := range datums {
if _, ok := blacklist[datumHash]; ok {
// not a datum
continue
}
datumInfos = append(datumInfos, datum)
}
// Sort results (failed first, slow first)
sort.Sort(byDatumStateThenTime(datumInfos))
return &pps.DatumInfos{datumInfos}, nil
}
type byDatumStateThenTime []*pps.DatumInfo
func (a byDatumStateThenTime) Len() int { return len(a) }
func (a byDatumStateThenTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byDatumStateThenTime) Less(i, j int) bool {
byState := a[i].State < a[j].State
if a[i].State != a[j].State {
return byState
}
if a[i].Stats == nil || a[j].Stats == nil {
return byState
}
return client.GetDatumTotalTime(a[i].Stats) > client.GetDatumTotalTime(a[j].Stats)
}
func (a *apiServer) getDatum(ctx context.Context, repo string, commit *pfs.Commit, jobID string, datumID string) (datumInfo *pps.DatumInfo, retErr error) {
datumInfo = &pps.DatumInfo{
Datum: &pps.Datum{
ID: datumID,
Job: &pps.Job{jobID},
},
State: pps.DatumState_SUCCESS,
}
pachClient, err := a.getPachClient()
if err != nil {
return nil, err
}
pfsClient := pachClient.PfsAPIClient
// Check if skipped
stateFile := &pfs.File{
Commit: commit,
Path: fmt.Sprintf("/%v/skipped", datumID),
}
_, err = pfsClient.InspectFile(ctx, &pfs.InspectFileRequest{stateFile})
if err == nil {
datumInfo.State = pps.DatumState_SKIPPED
// Datum wasn't added in this commit, so it was skipped
return datumInfo, nil
} else if !isNotFoundErr(err) {
return nil, err
}
// Check if failed
stateFile = &pfs.File{
Commit: commit,
Path: fmt.Sprintf("/%v/failure", datumID),
}
_, err = pfsClient.InspectFile(ctx, &pfs.InspectFileRequest{stateFile})
if err == nil {
datumInfo.State = pps.DatumState_FAILED
} else if !isNotFoundErr(err) {
return nil, err
}
// Populate stats
statsFile := &pfs.File{
Commit: commit,
Path: fmt.Sprintf("/%v/stats", datumID),
}
getFileClient, err := pfsClient.GetFile(ctx, &pfs.GetFileRequest{statsFile, 0, 0})
if err != nil {
return nil, err
}
var buffer bytes.Buffer
if err := grpcutil.WriteFromStreamingBytesClient(getFileClient, &buffer); err != nil {
return nil, err
}
stats := &pps.ProcessStats{}
err = jsonpb.Unmarshal(&buffer, stats)
if err != nil {
return nil, err
}
datumInfo.Stats = stats
datumInfo.PfsState = &pfs.File{
Commit: commit,
Path: fmt.Sprintf("/%v/pfs", datumID),
}
return datumInfo, nil
}
func (a *apiServer) InspectDatum(ctx context.Context, request *pps.InspectDatumRequest) (response *pps.DatumInfo, retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, response, retErr, time.Since(start)) }(time.Now())
jobInfo, err := a.InspectJob(ctx, &pps.InspectJobRequest{
Job: &pps.Job{
ID: request.Datum.Job.ID,
},
})
if err != nil {
return nil, err
}
if !jobInfo.EnableStats {
return nil, fmt.Errorf("stats not enabled on %v", jobInfo.Pipeline.Name)
}
if jobInfo.StatsCommit == nil {
return nil, fmt.Errorf("job not finished, no stats output yet")
}
// Populate datumInfo given a path
datumInfo, err := a.getDatum(ctx, jobInfo.StatsCommit.Repo.Name, jobInfo.StatsCommit, request.Datum.Job.ID, request.Datum.ID)
if err != nil {
return nil, err
}
return datumInfo, nil
}
func (a *apiServer) lookupRcNameForPipeline(ctx context.Context, pipeline *pps.Pipeline) (string, error) {
var pipelineInfo pps.PipelineInfo
err := a.pipelines.ReadOnly(ctx).Get(pipeline.Name, &pipelineInfo)
if err != nil {
return "", fmt.Errorf("could not get pipeline information for %s: %s", pipeline.Name, err.Error())
}
return ppsserver.PipelineRcName(pipeline.Name, pipelineInfo.Version), nil
}
func (a *apiServer) GetLogs(request *pps.GetLogsRequest, apiGetLogsServer pps.API_GetLogsServer) (retErr error) {
func() { a.Log(request, nil, nil, 0) }()
defer func(start time.Time) { a.Log(request, nil, retErr, time.Since(start)) }(time.Now())
// No deadline in request, but we create one here, since we do expect the call
// to finish reasonably quickly
ctx, _ := context.WithTimeout(context.Background(), 60*time.Second)
// Validate request
if request.Pipeline == nil && request.Job == nil {
return fmt.Errorf("must set either pipeline or job filter in call to GetLogs")
}
// Get list of pods containing logs we're interested in (based on pipeline and
// job filters)
var rcName string
if request.Pipeline != nil {
// If the user provides a pipeline, get logs from the pipeline RC directly
var err error
rcName, err = a.lookupRcNameForPipeline(ctx, request.Pipeline)
if err != nil {
return err
}
} else if request.Job != nil {
// If user provides a job, lookup the pipeline from the job info, and then
// get the pipeline RC
var jobInfo pps.JobInfo
err := a.jobs.ReadOnly(ctx).Get(request.Job.ID, &jobInfo)
if err != nil {
return fmt.Errorf("could not get job information for %s: %s", request.Job.ID, err.Error())
}
rcName, err = a.lookupRcNameForPipeline(ctx, jobInfo.Pipeline)
if err != nil {
return err
}
}
pods, err := a.rcPods(rcName)
if err != nil {
return fmt.Errorf("could not get pods in rc \"%s\" containing logs: %s", rcName, err.Error())
}
if len(pods) == 0 {
return fmt.Errorf("no pods belonging to the rc \"%s\" were found", rcName)
}
// Spawn one goroutine per pod. Each goro writes its pod's logs to a channel
// and channels are read into the output server in a stable order.
// (sort the pods to make sure that the order of log lines is stable)
sort.Sort(podSlice(pods))
logChs := make([]chan *pps.LogMessage, len(pods))
errCh := make(chan error)
done := make(chan struct{})
defer close(done)
for i := 0; i < len(pods); i++ {
logChs[i] = make(chan *pps.LogMessage)
}
for i, pod := range pods {
i, pod := i, pod
go func() {
defer close(logChs[i]) // Main thread reads from here, so must close
// Get full set of logs from pod i
err := backoff.Retry(func() error {
result := a.kubeClient.Pods(a.namespace).GetLogs(
pod.ObjectMeta.Name, &api.PodLogOptions{
Container: client.PPSWorkerUserContainerName,
}).Timeout(10 * time.Second).Do()
fullLogs, err := result.Raw()
if err != nil {
if apiStatus, ok := err.(errors.APIStatus); ok &&
strings.Contains(apiStatus.Status().Message, "PodInitializing") {
return nil // No logs to collect from this node yet, just skip it
}
return err
}
// Occasionally, fullLogs is truncated and contains the string
// 'unexpected stream type ""' at the end. I believe this is a recent
// bug in k8s (https://github.com/kubernetes/kubernetes/issues/47800)
// so we're adding a special handler for this corner case.
// TODO(msteffen) remove this handling once the issue is fixed
if bytes.HasSuffix(fullLogs, []byte("unexpected stream type \"\"")) {
return fmt.Errorf("interrupted log stream due to kubernetes/kubernetes/issues/47800")
}
// Parse pods' log lines, and filter out irrelevant ones
scanner := bufio.NewScanner(bytes.NewReader(fullLogs))
for scanner.Scan() {
logBytes := scanner.Bytes()
msg := new(pps.LogMessage)
if err := jsonpb.Unmarshal(bytes.NewReader(logBytes), msg); err != nil {
continue
}
// Filter out log lines that don't match on pipeline or job
if request.Pipeline != nil && request.Pipeline.Name != msg.PipelineName {
continue
}
if request.Job != nil && request.Job.ID != msg.JobID {
continue
}
if request.InputFileID != "" && request.InputFileID != msg.InputFileID {
continue
}
if request.Master != msg.Master {
continue
}
if !workerpkg.MatchDatum(request.DataFilters, msg.Data) {
continue
}
// Log message passes all filters -- return it
select {
case logChs[i] <- msg:
case <-done:
return nil
}
}
return nil
}, backoff.New10sBackOff())
// Used up all retries -- no logs from worker
if err != nil {
select {
case errCh <- err:
case <-done:
}
}
}()
}
nextLogCh:
for _, logCh := range logChs {
for {
select {
case msg, ok := <-logCh:
if !ok {
continue nextLogCh
}
if err := apiGetLogsServer.Send(msg); err != nil {
return err
}
case err := <-errCh:
return err
}
}
}
return nil
}
func (a *apiServer) validatePipeline(ctx context.Context, pipelineInfo *pps.PipelineInfo) error {
if err := a.validateInput(ctx, pipelineInfo.Pipeline.Name, pipelineInfo.Input, false); err != nil {
return err
}
if err := validateTransform(pipelineInfo.Transform); err != nil {
return err
}
if pipelineInfo.ParallelismSpec != nil {
if pipelineInfo.ParallelismSpec.Constant < 0 {
return fmt.Errorf("ParallelismSpec.Constant must be > 0")
}
if pipelineInfo.ParallelismSpec.Coefficient < 0 {
return fmt.Errorf("ParallelismSpec.Coefficient must be > 0")
}
if pipelineInfo.ParallelismSpec.Constant != 0 &&
pipelineInfo.ParallelismSpec.Coefficient != 0 {
return fmt.Errorf("contradictory parallelism strategies: must set at " +
"most one of ParallelismSpec.Constant and ParallelismSpec.Coefficient")
}
}
if pipelineInfo.OutputBranch == "" {
return fmt.Errorf("pipeline needs to specify an output branch")
}
if _, err := resource.ParseQuantity(pipelineInfo.CacheSize); err != nil {
return fmt.Errorf("could not parse cacheSize '%s': %v", pipelineInfo.CacheSize, err)
}
if pipelineInfo.Incremental {
pachClient, err := a.getPachClient()
if err != nil {
return err
}
pfsClient := pachClient.PfsAPIClient
// for incremental jobs we can't have shared provenance
var provenance []*pfs.Repo
for _, commit := range pps.InputCommits(pipelineInfo.Input) {
provenance = append(provenance, commit.Repo)
}
provMap := make(map[string]bool)
for _, provRepo := range provenance {
if provMap[provRepo.Name] {
return fmt.Errorf("can't create an incremental pipeline with inputs that share provenance")
}
provMap[provRepo.Name] = true
repoInfo, err := pfsClient.InspectRepo(ctx, &pfs.InspectRepoRequest{Repo: provRepo})
if err != nil {
return err
}
for _, provRepo := range repoInfo.Provenance {
if provMap[provRepo.Name] {
return fmt.Errorf("can't create an incremental pipeline with inputs that share provenance")
}
provMap[provRepo.Name] = true
}
}
}
return nil
}
func translatePipelineInputs(inputs []*pps.PipelineInput) *pps.Input {
result := &pps.Input{}
for _, input := range inputs {
var fromCommitID string
if input.From != nil {
fromCommitID = input.From.ID
}
atomInput := &pps.AtomInput{
Name: input.Name,
Repo: input.Repo.Name,
Branch: input.Branch,
Glob: input.Glob,
Lazy: input.Lazy,
FromCommit: fromCommitID,
}
result.Cross = append(result.Cross, &pps.Input{
Atom: atomInput,
})
}
return result
}
// AuthorizeCreatePipelineRequest checks if the user indicated by 'ctx' is authorized to create or update
// the pipeline in 'request'
func (a *apiServer) AuthorizeCreatePipeline(ctx context.Context, authClient auth.APIClient, update bool, info *pps.PipelineInfo) error {
_, err := authClient.WhoAmI(auth.In2Out(ctx), &auth.WhoAmIRequest{})
if err != nil {
if auth.IsNotActivatedError(err) {
// TODO(msteffen): Think about how auth will degrade if auth is activated
// then deactivated. This is potentially insecure.
return nil // Auth isn't activated, user may proceed
}
return err
}
// 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)
// collect inputs by bfs info.Input (info.Inputs is no longer set)
if len(info.Inputs) > 0 {
return fmt.Errorf("cannot authorize PipelineInfo with 'Inputs' set")
}
inputRepos := make(map[string]struct{})
queue := []*pps.Input{info.Input}
for len(queue) > 0 {
in := queue[0]
queue = queue[1:]
if in == nil {
break
} else if in.Atom != nil {
inputRepos[in.Atom.Repo] = struct{}{}
} else if len(in.Cross) > 0 {
queue = append(queue, in.Cross...)
} else if len(in.Union) > 0 {
queue = append(queue, in.Union...)
} else {
return fmt.Errorf("cannot authorize pipeline input that is not an atom, a cross, or a union")
}
}
var eg errgroup.Group