/
api_server.go
2240 lines (2142 loc) · 69.8 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 worker
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unicode/utf8"
"github.com/LK4D4/joincontext"
etcd "github.com/coreos/etcd/clientv3"
"github.com/gogo/protobuf/jsonpb"
"github.com/gogo/protobuf/types"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
"gopkg.in/go-playground/webhooks.v5/github"
"gopkg.in/src-d/go-git.v4"
gitPlumbing "gopkg.in/src-d/go-git.v4/plumbing"
kube "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"github.com/fsouza/go-dockerclient"
"github.com/pachyderm/pachyderm/src/client"
"github.com/pachyderm/pachyderm/src/client/enterprise"
"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/pbutil"
"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/errutil"
"github.com/pachyderm/pachyderm/src/server/pkg/exec"
"github.com/pachyderm/pachyderm/src/server/pkg/hashtree"
"github.com/pachyderm/pachyderm/src/server/pkg/obj"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsdb"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsutil"
filesync "github.com/pachyderm/pachyderm/src/server/pkg/sync"
"github.com/pachyderm/pachyderm/src/server/pkg/uuid"
"github.com/pachyderm/pachyderm/src/server/pkg/watch"
)
const (
// The maximum number of concurrent download/upload operations
concurrency = 100
logBuffer = 25
planPrefix = "/plan"
chunkPrefix = "/chunk"
mergePrefix = "/merge"
shardPrefix = "/shard"
shardTTL = 30
noShard = int64(-1)
parentTreeBufSize = 50 * (1 << (10 * 2))
)
type ctxKey int
const (
shardKey ctxKey = iota
)
var (
errSpecialFile = errors.New("cannot upload special file")
statsTagSuffix = "_stats"
)
// APIServer implements the worker API
type APIServer struct {
pachClient *client.APIClient
kubeClient *kube.Clientset
etcdClient *etcd.Client
etcdPrefix string
// Information needed to process input data and upload output
pipelineInfo *pps.PipelineInfo
// Information attached to log lines
logMsgTemplate pps.LogMessage
// The k8s pod name of this worker
workerName string
statusMu sync.Mutex
// The currently running job ID
jobID string
// The currently running data
data []*Input
// The time we started the currently running
started time.Time
// Func to cancel the currently running datum
cancel func()
// Stats about the execution of the job
stats *pps.ProcessStats
// queueSize is the number of items enqueued
queueSize int64
// The total number of workers for this pipeline
numWorkers int
// The namespace in which pachyderm is deployed
namespace string
// The jobs collection
jobs col.Collection
// The pipelines collection
pipelines col.Collection
// The plans collection
// Stores chunk layout and merges
plans col.Collection
// The shards collection
// Stores available filesystem shards for a pipeline, workers will claim these
shards col.Collection
// Only one datum can be running at a time because they need to be
// accessing /pfs, runMu enforces this
runMu sync.Mutex
// We only export application statistics if enterprise is enabled
exportStats bool
uid *uint32
gid *uint32
// hashtreeStorage is the where we store on disk hashtrees
hashtreeStorage string
// numShards is the number of filesystem shards for the output of this pipeline
numShards int64
// claimedShard communicates the context for the shard that was claimed
claimedShard chan context.Context
// shardCtx is the context for the shard this worker has claimed
shardCtx context.Context
// shard is the shard this worker has claimed
shard int64
// chunkCache caches chunk hashtrees during a job and can merge them (chunkStatsCache applies to stats)
chunkCache, chunkStatsCache *hashtree.MergeCache
// datumCache caches datum hashtrees during a job and can merge them (datumStatsCache applies to stats)
datumCache, datumStatsCache *hashtree.MergeCache
// clients are the worker clients (used for the shuffle step by mergers)
clients map[string]Client
}
type putObjectResponse struct {
object *pfs.Object
size int64
err error
}
type taggedLogger struct {
template pps.LogMessage
stderrLog log.Logger
marshaler *jsonpb.Marshaler
buffer bytes.Buffer
putObjClient pfs.ObjectAPI_PutObjectClient
objSize int64
msgCh chan string
eg errgroup.Group
}
// DatumID computes the id for a datum, this value is used in ListDatum and
// InspectDatum.
func (a *APIServer) DatumID(data []*Input) string {
hash := sha256.New()
for _, d := range data {
hash.Write([]byte(d.FileInfo.File.Path))
hash.Write(d.FileInfo.Hash)
}
// InputFileID is a single string id for the data from this input, it's used in logs and in
// the statsTree
return hex.EncodeToString(hash.Sum(nil))
}
func (a *APIServer) getTaggedLogger(pachClient *client.APIClient, jobID string, data []*Input, enableStats bool) (*taggedLogger, error) {
result := &taggedLogger{
template: a.logMsgTemplate, // Copy struct
stderrLog: log.Logger{},
marshaler: &jsonpb.Marshaler{},
msgCh: make(chan string, logBuffer),
}
result.stderrLog.SetOutput(os.Stderr)
result.stderrLog.SetFlags(log.LstdFlags | log.Llongfile) // Log file/line
// Add Job ID to log metadata
result.template.JobID = jobID
// Add inputs' details to log metadata, so we can find these logs later
for _, d := range data {
result.template.Data = append(result.template.Data, &pps.InputFile{
Path: d.FileInfo.File.Path,
Hash: d.FileInfo.Hash,
})
}
// InputFileID is a single string id for the data from this input, it's used in logs and in
// the statsTree
result.template.DatumID = a.DatumID(data)
if enableStats {
putObjClient, err := pachClient.ObjectAPIClient.PutObject(pachClient.Ctx())
if err != nil {
return nil, err
}
result.putObjClient = putObjClient
result.eg.Go(func() error {
for msg := range result.msgCh {
for _, chunk := range grpcutil.Chunk([]byte(msg), grpcutil.MaxMsgSize/2) {
if err := result.putObjClient.Send(&pfs.PutObjectRequest{
Value: chunk,
}); err != nil && err != io.EOF {
return err
}
}
result.objSize += int64(len(msg))
}
return nil
})
}
return result, nil
}
// Logf logs the line Sprintf(formatString, args...), but formatted as a json
// message and annotated with all of the metadata stored in 'loginfo'.
//
// Note: this is not thread-safe, as it modifies fields of 'logger.template'
func (logger *taggedLogger) Logf(formatString string, args ...interface{}) {
logger.template.Message = fmt.Sprintf(formatString, args...)
if ts, err := types.TimestampProto(time.Now()); err == nil {
logger.template.Ts = ts
} else {
logger.stderrLog.Printf("could not generate logging timestamp: %s\n", err)
return
}
msg, err := logger.marshaler.MarshalToString(&logger.template)
if err != nil {
logger.stderrLog.Printf("could not marshal %v for logging: %s\n", &logger.template, err)
return
}
fmt.Println(msg)
if logger.putObjClient != nil {
logger.msgCh <- msg + "\n"
}
}
func (logger *taggedLogger) Write(p []byte) (_ int, retErr error) {
// never errors
logger.buffer.Write(p)
r := bufio.NewReader(&logger.buffer)
for {
message, err := r.ReadString('\n')
if err != nil {
if err == io.EOF {
logger.buffer.Write([]byte(message))
return len(p), nil
}
// this shouldn't technically be possible to hit io.EOF should be
// the only error bufio.Reader can return when using a buffer.
return 0, fmt.Errorf("error ReadString: %v", err)
}
// We don't want to make this call as:
// logger.Logf(message)
// because if the message has format characters like %s in it those
// will result in errors being logged.
logger.Logf("%s", strings.TrimSuffix(message, "\n"))
}
}
func (logger *taggedLogger) Close() (*pfs.Object, int64, error) {
close(logger.msgCh)
if logger.putObjClient != nil {
if err := logger.eg.Wait(); err != nil {
return nil, 0, err
}
object, err := logger.putObjClient.CloseAndRecv()
// we set putObjClient to nil so that future calls to Logf won't send
// msg down logger.msgCh as we've just closed that channel.
logger.putObjClient = nil
return object, logger.objSize, err
}
return nil, 0, nil
}
func (logger *taggedLogger) clone() *taggedLogger {
return &taggedLogger{
template: logger.template, // Copy struct
stderrLog: log.Logger{},
marshaler: &jsonpb.Marshaler{},
putObjClient: logger.putObjClient,
msgCh: logger.msgCh,
}
}
func (logger *taggedLogger) userLogger() *taggedLogger {
result := logger.clone()
result.template.User = true
return result
}
// NewAPIServer creates an APIServer for a given pipeline
func NewAPIServer(pachClient *client.APIClient, etcdClient *etcd.Client, etcdPrefix string, pipelineInfo *pps.PipelineInfo, workerName string, namespace string, hashtreeStorage string) (*APIServer, error) {
initPrometheus()
cfg, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
kubeClient, err := kube.NewForConfig(cfg)
if err != nil {
return nil, err
}
server := &APIServer{
pachClient: pachClient,
kubeClient: kubeClient,
etcdClient: etcdClient,
etcdPrefix: etcdPrefix,
pipelineInfo: pipelineInfo,
logMsgTemplate: pps.LogMessage{
PipelineName: pipelineInfo.Pipeline.Name,
WorkerID: os.Getenv(client.PPSPodNameEnv),
},
workerName: workerName,
namespace: namespace,
jobs: ppsdb.Jobs(etcdClient, etcdPrefix),
pipelines: ppsdb.Pipelines(etcdClient, etcdPrefix),
plans: col.NewCollection(etcdClient, path.Join(etcdPrefix, planPrefix), nil, &Plan{}, nil, nil),
shards: col.NewCollection(etcdClient, path.Join(etcdPrefix, shardPrefix, pipelineInfo.Pipeline.Name), nil, &ShardInfo{}, nil, nil),
hashtreeStorage: hashtreeStorage,
claimedShard: make(chan context.Context, 1),
shard: noShard,
clients: make(map[string]Client),
}
logger, err := server.getTaggedLogger(pachClient, "", nil, false)
if err != nil {
return nil, err
}
resp, err := pachClient.Enterprise.GetState(context.Background(), &enterprise.GetStateRequest{})
if err != nil {
logger.Logf("failed to get enterprise state with error: %v\n", err)
} else {
server.exportStats = resp.State == enterprise.State_ACTIVE
}
numWorkers, err := ppsutil.GetExpectedNumWorkers(kubeClient, pipelineInfo.ParallelismSpec)
if err != nil {
logger.Logf("error getting number of workers, default to 1 worker: %v", err)
numWorkers = 1
}
server.numWorkers = numWorkers
numShards, err := ppsutil.GetExpectedNumHashtrees(pipelineInfo.HashtreeSpec)
if err != nil {
logger.Logf("error getting number of shards, default to 1 shard: %v", err)
numShards = 1
}
server.numShards = numShards
root := filepath.Join(hashtreeStorage, uuid.NewWithoutDashes())
if err := os.MkdirAll(filepath.Join(root, "chunk", "stats"), 0777); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Join(root, "datum", "stats"), 0777); err != nil {
return nil, err
}
server.chunkCache = hashtree.NewMergeCache(filepath.Join(root, "chunk"))
server.chunkStatsCache = hashtree.NewMergeCache(filepath.Join(root, "chunk", "stats"))
server.datumCache = hashtree.NewMergeCache(filepath.Join(root, "datum"))
server.datumStatsCache = hashtree.NewMergeCache(filepath.Join(root, "datum", "stats"))
var noDocker bool
if _, err := os.Stat("/var/run/docker.sock"); err != nil {
noDocker = true
}
if pipelineInfo.Transform.Image != "" && !noDocker {
docker, err := docker.NewClientFromEnv()
if err != nil {
return nil, err
}
image, err := docker.InspectImage(pipelineInfo.Transform.Image)
if err != nil {
return nil, fmt.Errorf("error inspecting image %s: %+v", pipelineInfo.Transform.Image, err)
}
if pipelineInfo.Transform.User == "" {
pipelineInfo.Transform.User = image.Config.User
}
if pipelineInfo.Transform.WorkingDir == "" {
pipelineInfo.Transform.WorkingDir = image.Config.WorkingDir
}
if server.pipelineInfo.Transform.Cmd == nil {
server.pipelineInfo.Transform.Cmd = image.Config.Entrypoint
}
}
if pipelineInfo.Transform.User != "" {
user, err := lookupDockerUser(pipelineInfo.Transform.User)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
// If `user` is `nil`, `uid` and `gid` will get set, and we won't
// customize the user that executes the worker process.
if user != nil { // user is nil when os.IsNotExist(err) is true in which case we use root
uid, err := strconv.ParseUint(user.Uid, 10, 32)
if err != nil {
return nil, err
}
uid32 := uint32(uid)
server.uid = &uid32
gid, err := strconv.ParseUint(user.Gid, 10, 32)
if err != nil {
return nil, err
}
gid32 := uint32(gid)
server.gid = &gid32
}
}
switch {
case pipelineInfo.Service != nil:
go server.master("service", server.serviceSpawner)
case pipelineInfo.Spout != nil:
go server.master("spout", server.spoutSpawner)
default:
go server.master("pipeline", server.jobSpawner)
}
go server.worker()
return server, nil
}
func (a *APIServer) downloadGitData(pachClient *client.APIClient, dir string, input *Input) error {
file := input.FileInfo.File
pachydermRepoName := input.Name
var rawJSON bytes.Buffer
err := pachClient.GetFile(pachydermRepoName, file.Commit.ID, "commit.json", 0, 0, &rawJSON)
if err != nil {
return err
}
var payload github.PushPayload
err = json.Unmarshal(rawJSON.Bytes(), &payload)
if err != nil {
return err
}
sha := payload.After
// Clone checks out a reference, not a SHA
r, err := git.PlainClone(
filepath.Join(dir, pachydermRepoName),
false,
&git.CloneOptions{
URL: payload.Repository.CloneURL,
SingleBranch: true,
ReferenceName: gitPlumbing.ReferenceName(payload.Ref),
},
)
if err != nil {
return fmt.Errorf("error cloning repo %v at SHA %v from URL %v: %v", pachydermRepoName, sha, input.GitURL, err)
}
hash := gitPlumbing.NewHash(sha)
wt, err := r.Worktree()
if err != nil {
return err
}
err = wt.Checkout(&git.CheckoutOptions{Hash: hash})
if err != nil {
return fmt.Errorf("error checking out SHA %v from repo %v: %v", sha, pachydermRepoName, err)
}
return nil
}
func (a *APIServer) reportDownloadSizeStats(downSize float64, logger *taggedLogger) {
if a.exportStats {
if hist, err := datumDownloadSize.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get histogram w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
hist.Observe(downSize)
}
if counter, err := datumDownloadBytesCount.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get counter w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
counter.Add(downSize)
}
}
}
func (a *APIServer) reportDownloadTimeStats(start time.Time, stats *pps.ProcessStats, logger *taggedLogger) {
duration := time.Since(start)
stats.DownloadTime = types.DurationProto(duration)
if a.exportStats {
if hist, err := datumDownloadTime.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get histogram w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
hist.Observe(duration.Seconds())
}
if counter, err := datumDownloadSecondsCount.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get counter w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
counter.Add(duration.Seconds())
}
}
}
func (a *APIServer) downloadData(pachClient *client.APIClient, logger *taggedLogger, inputs []*Input, puller *filesync.Puller, stats *pps.ProcessStats, statsTree *hashtree.Ordered) (_ string, retErr error) {
defer a.reportDownloadTimeStats(time.Now(), stats, logger)
logger.Logf("starting to download data")
defer func(start time.Time) {
if retErr != nil {
logger.Logf("errored downloading data after %v: %v", time.Since(start), retErr)
} else {
logger.Logf("finished downloading data after %v", time.Since(start))
}
}(time.Now())
dir := filepath.Join(client.PPSScratchSpace, uuid.NewWithoutDashes())
// Create output directory (currently /pfs/out)
outPath := filepath.Join(dir, "out")
if a.pipelineInfo.Spout != nil {
// Spouts need to create a named pipe at /pfs/out
if err := os.MkdirAll(filepath.Dir(outPath), 0700); err != nil {
return "", fmt.Errorf("mkdirall :%v", err)
}
if err := syscall.Mkfifo(outPath, 0666); err != nil {
return "", fmt.Errorf("mkfifo :%v", err)
}
} else {
if err := os.MkdirAll(outPath, 0777); err != nil {
return "", err
}
}
for _, input := range inputs {
if input.GitURL != "" {
if err := a.downloadGitData(pachClient, dir, input); err != nil {
return "", err
}
continue
}
file := input.FileInfo.File
root := filepath.Join(dir, input.Name, file.Path)
var statsRoot string
if statsTree != nil {
statsRoot = path.Join(input.Name, file.Path)
parent, _ := path.Split(statsRoot)
statsTree.MkdirAll(parent)
}
if err := puller.Pull(pachClient, root, file.Commit.Repo.Name, file.Commit.ID, file.Path, input.Lazy, input.EmptyFiles, concurrency, statsTree, statsRoot); err != nil {
return "", err
}
}
return dir, nil
}
func (a *APIServer) linkData(inputs []*Input, dir string) error {
for _, input := range inputs {
src := filepath.Join(dir, input.Name)
dst := filepath.Join(client.PPSInputPrefix, input.Name)
if err := os.Symlink(src, dst); err != nil {
return err
}
}
return os.Symlink(filepath.Join(dir, "out"), filepath.Join(client.PPSInputPrefix, "out"))
}
func (a *APIServer) unlinkData(inputs []*Input) error {
for _, input := range inputs {
if err := os.RemoveAll(filepath.Join(client.PPSInputPrefix, input.Name)); err != nil {
return err
}
}
return os.RemoveAll(filepath.Join(client.PPSInputPrefix, "out"))
}
func (a *APIServer) reportUserCodeStats(logger *taggedLogger) {
if a.exportStats {
if counter, err := datumCount.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID, "started"); err != nil {
logger.Logf("failed to get histogram w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
counter.Add(1)
}
}
}
func (a *APIServer) reportDeferredUserCodeStats(err error, start time.Time, stats *pps.ProcessStats, logger *taggedLogger) {
duration := time.Since(start)
stats.ProcessTime = types.DurationProto(duration)
if a.exportStats {
state := "errored"
if err == nil {
state = "finished"
}
if counter, err := datumCount.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID, state); err != nil {
logger.Logf("failed to get counter w labels: pipeline (%v) job (%v) state (%v) with error %v", a.pipelineInfo.ID, a.jobID, state, err)
} else {
counter.Add(1)
}
if hist, err := datumProcTime.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID, state); err != nil {
logger.Logf("failed to get counter w labels: pipeline (%v) job (%v) state (%v) with error %v", a.pipelineInfo.ID, a.jobID, state, err)
} else {
hist.Observe(duration.Seconds())
}
if counter, err := datumProcSecondsCount.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get counter w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
counter.Add(duration.Seconds())
}
}
}
// Run user code and return the combined output of stdout and stderr.
func (a *APIServer) runUserCode(ctx context.Context, logger *taggedLogger, environ []string, stats *pps.ProcessStats, rawDatumTimeout *types.Duration) (retErr error) {
a.reportUserCodeStats(logger)
defer func(start time.Time) { a.reportDeferredUserCodeStats(retErr, start, stats, logger) }(time.Now())
logger.Logf("beginning to run user code")
defer func(start time.Time) {
if retErr != nil {
logger.Logf("errored running user code after %v: %v", time.Since(start), retErr)
} else {
logger.Logf("finished running user code after %v", time.Since(start))
}
}(time.Now())
if rawDatumTimeout != nil {
datumTimeout, err := types.DurationFromProto(rawDatumTimeout)
if err != nil {
return err
}
datumTimeoutCtx, cancel := context.WithTimeout(ctx, datumTimeout)
defer cancel()
ctx = datumTimeoutCtx
}
// Run user code
cmd := exec.CommandContext(ctx, a.pipelineInfo.Transform.Cmd[0], a.pipelineInfo.Transform.Cmd[1:]...)
if a.pipelineInfo.Transform.Stdin != nil {
cmd.Stdin = strings.NewReader(strings.Join(a.pipelineInfo.Transform.Stdin, "\n") + "\n")
}
cmd.Stdout = logger.userLogger()
cmd.Stderr = logger.userLogger()
cmd.Env = environ
if a.uid != nil && a.gid != nil {
cmd.SysProcAttr = &syscall.SysProcAttr{
Credential: &syscall.Credential{
Uid: *a.uid,
Gid: *a.gid,
},
}
}
cmd.Dir = a.pipelineInfo.Transform.WorkingDir
err := cmd.Start()
if err != nil {
return fmt.Errorf("error cmd.Start: %v", err)
}
// A context w a deadline will successfully cancel/kill
// the running process (minus zombies)
state, err := cmd.Process.Wait()
if err != nil {
return fmt.Errorf("error cmd.Wait: %v", err)
}
if isDone(ctx) {
if err = ctx.Err(); err != nil {
return err
}
}
// Because of this issue: https://github.com/golang/go/issues/18874
// We forked os/exec so that we can call just the part of cmd.Wait() that
// happens after blocking on the process. Unfortunately calling
// cmd.Process.Wait() then cmd.Wait() will produce an error. So instead we
// close the IO using this helper
err = cmd.WaitIO(state, err)
// We ignore broken pipe errors, these occur very occasionally if a user
// specifies Stdin but their process doesn't actually read everything from
// Stdin. This is a fairly common thing to do, bash by default ignores
// broken pipe errors.
if err != nil && !strings.Contains(err.Error(), "broken pipe") {
// (if err is an acceptable return code, don't return err)
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
for _, returnCode := range a.pipelineInfo.Transform.AcceptReturnCode {
if int(returnCode) == status.ExitStatus() {
return nil
}
}
}
}
return fmt.Errorf("error cmd.WaitIO: %v", err)
}
return nil
}
func (a *APIServer) reportUploadStats(start time.Time, stats *pps.ProcessStats, logger *taggedLogger) {
duration := time.Since(start)
stats.UploadTime = types.DurationProto(duration)
if a.exportStats {
if hist, err := datumUploadTime.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get histogram w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
hist.Observe(duration.Seconds())
}
if counter, err := datumUploadSecondsCount.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get counter w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
counter.Add(duration.Seconds())
}
if hist, err := datumUploadSize.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get histogram w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
hist.Observe(float64(stats.UploadBytes))
}
if counter, err := datumUploadBytesCount.GetMetricWithLabelValues(a.pipelineInfo.ID, a.jobID); err != nil {
logger.Logf("failed to get counter w labels: pipeline (%v) job (%v) with error %v", a.pipelineInfo.ID, a.jobID, err)
} else {
counter.Add(float64(stats.UploadBytes))
}
}
}
func (a *APIServer) uploadOutput(pachClient *client.APIClient, dir string, tag string, logger *taggedLogger, inputs []*Input, stats *pps.ProcessStats, statsTree *hashtree.Ordered, datumIdx int64) (retErr error) {
defer a.reportUploadStats(time.Now(), stats, logger)
logger.Logf("starting to upload output")
defer func(start time.Time) {
if retErr != nil {
logger.Logf("errored uploading output after %v: %v", time.Since(start), retErr)
} else {
logger.Logf("finished uploading output after %v", time.Since(start))
}
}(time.Now())
// Setup client for writing file data
putObjsClient, err := pachClient.ObjectAPIClient.PutObjects(pachClient.Ctx())
if err != nil {
return err
}
block := &pfs.Block{Hash: uuid.NewWithoutDashes()}
if err := putObjsClient.Send(&pfs.PutObjectRequest{
Block: block,
}); err != nil {
return err
}
outputPath := filepath.Join(dir, "out")
buf := grpcutil.GetBuffer()
defer grpcutil.PutBuffer(buf)
var offset uint64
var tree *hashtree.Ordered
// Upload all files in output directory
if err := filepath.Walk(outputPath, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !utf8.ValidString(filePath) {
return fmt.Errorf("file path is not valid utf-8: %s", filePath)
}
if filePath == outputPath {
tree = hashtree.NewOrdered("/")
return nil
}
relPath, err := filepath.Rel(outputPath, filePath)
if err != nil {
return err
}
// Put directory. Even if the directory is empty, that may be useful to
// users
// TODO(msteffen) write a test pipeline that outputs an empty directory and
// make sure it's preserved
if info.IsDir() {
tree.PutDir(relPath)
if statsTree != nil {
statsTree.PutDir(relPath)
}
return nil
}
// Under some circumstances, the user might have copied
// some pipes from the input directory to the output directory.
// Reading from these files will result in job blocking. Thus
// we preemptively detect if the file is a named pipe.
if (info.Mode() & os.ModeNamedPipe) > 0 {
logger.Logf("cannot upload named pipe: %v", relPath)
return errSpecialFile
}
// If the output file is a symlink to an input file, we can skip
// the uploading.
if (info.Mode() & os.ModeSymlink) > 0 {
realPath, err := os.Readlink(filePath)
if err != nil {
return err
}
if strings.HasPrefix(realPath, client.PPSInputPrefix) {
var pathWithInput string
var err error
if strings.HasPrefix(realPath, dir) {
pathWithInput, err = filepath.Rel(dir, realPath)
} else {
pathWithInput, err = filepath.Rel(client.PPSInputPrefix, realPath)
}
if err == nil {
// We can only skip the upload if the real path is
// under /pfs, meaning that it's a file that already
// exists in PFS.
// The name of the input
inputName := strings.Split(pathWithInput, string(os.PathSeparator))[0]
var input *Input
for _, i := range inputs {
if i.Name == inputName {
input = i
}
}
// this changes realPath from `/pfs/input/...` to `/scratch/<id>/input/...`
realPath = filepath.Join(dir, pathWithInput)
if input != nil {
return filepath.Walk(realPath, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(realPath, filePath)
if err != nil {
return err
}
subRelPath := filepath.Join(relPath, rel)
// The path of the input file
pfsPath, err := filepath.Rel(filepath.Join(dir, input.Name), filePath)
if err != nil {
return err
}
if info.IsDir() {
tree.PutDir(subRelPath)
if statsTree != nil {
statsTree.PutDir(subRelPath)
}
return nil
}
fc := input.FileInfo.File.Commit
fileInfo, err := pachClient.InspectFile(fc.Repo.Name, fc.ID, pfsPath)
if err != nil {
return err
}
var blockRefs []*pfs.BlockRef
for _, object := range fileInfo.Objects {
objectInfo, err := pachClient.InspectObject(object.Hash)
if err != nil {
return err
}
blockRefs = append(blockRefs, objectInfo.BlockRef)
}
blockRefs = append(blockRefs, fileInfo.BlockRefs...)
n := &hashtree.FileNodeProto{BlockRefs: blockRefs}
tree.PutFile(subRelPath, fileInfo.Hash, int64(fileInfo.SizeBytes), n)
if statsTree != nil {
statsTree.PutFile(subRelPath, fileInfo.Hash, int64(fileInfo.SizeBytes), n)
}
return nil
})
}
}
}
}
// Open local file that is being uploaded
f, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("os.Open(%s): %v", filePath, err)
}
defer func() {
if err := f.Close(); err != nil && retErr == nil {
retErr = err
}
}()
var size int64
h := pfs.NewHash()
r := io.TeeReader(f, h)
// Write local file to object storage block
for {
n, err := r.Read(buf)
if n == 0 && err != nil {
if err == io.EOF {
break
}
return err
}
if err := putObjsClient.Send(&pfs.PutObjectRequest{
Value: buf[:n],
}); err != nil {
return err
}
size += int64(n)
}
n := &hashtree.FileNodeProto{
BlockRefs: []*pfs.BlockRef{
&pfs.BlockRef{
Block: block,
Range: &pfs.ByteRange{
Lower: offset,
Upper: offset + uint64(size),
},
},
},
}
hash := h.Sum(nil)
tree.PutFile(relPath, hash, size, n)
if statsTree != nil {
statsTree.PutFile(relPath, hash, size, n)
}
offset += uint64(size)
stats.UploadBytes += uint64(size)
return nil
}); err != nil {
return fmt.Errorf("error walking output: %v", err)
}
if err := putObjsClient.CloseSend(); err != nil {
return err
}
// Serialize datum hashtree
b := &bytes.Buffer{}
if err := tree.Serialize(b); err != nil {
return err
}
// Write datum hashtree to object storage
w, err := pachClient.PutObjectAsync([]*pfs.Tag{client.NewTag(tag)})
if err != nil {
return err
}
defer func() {
if err := w.Close(); err != nil && retErr != nil {
retErr = err
}
}()
if _, err := w.Write(b.Bytes()); err != nil {
return err
}
// Cache datum hashtree locally
return a.datumCache.Put(datumIdx, bytes.NewReader(b.Bytes()))
}
// HashDatum computes and returns the hash of datum + pipeline, with a
// pipeline-specific prefix.
func HashDatum(pipelineName string, pipelineSalt string, data []*Input) string {
hash := sha256.New()
for _, datum := range data {
hash.Write([]byte(datum.Name))
hash.Write([]byte(datum.FileInfo.File.Path))
hash.Write(datum.FileInfo.Hash)
}
hash.Write([]byte(pipelineName))
hash.Write([]byte(pipelineSalt))
return client.DatumTagPrefix(pipelineSalt) + hex.EncodeToString(hash.Sum(nil))
}
// HashDatum15 computes and returns the hash of datum + pipeline for version <= 1.5.0, with a
// pipeline-specific prefix.
func HashDatum15(pipelineInfo *pps.PipelineInfo, data []*Input) (string, error) {
hash := sha256.New()
for _, datum := range data {
hash.Write([]byte(datum.Name))
hash.Write([]byte(datum.FileInfo.File.Path))
hash.Write(datum.FileInfo.Hash)
}
// We set env to nil because if env contains more than one elements,
// since it's a map, the output of Marshal() can be non-deterministic.
env := pipelineInfo.Transform.Env
pipelineInfo.Transform.Env = nil
defer func() {
pipelineInfo.Transform.Env = env
}()
bytes, err := pipelineInfo.Transform.Marshal()
if err != nil {
return "", err
}
hash.Write(bytes)
hash.Write([]byte(pipelineInfo.Pipeline.Name))
hash.Write([]byte(pipelineInfo.ID))
hash.Write([]byte(strconv.Itoa(int(pipelineInfo.Version))))
// Note in 1.5.0 this function was called HashPipelineID, it's now called
// HashPipelineName but it has the same implementation.
return client.DatumTagPrefix(pipelineInfo.ID) + hex.EncodeToString(hash.Sum(nil)), nil
}
// Status returns the status of the current worker.
func (a *APIServer) Status(ctx context.Context, _ *types.Empty) (*pps.WorkerStatus, error) {
a.statusMu.Lock()
defer a.statusMu.Unlock()
started, err := types.TimestampProto(a.started)
if err != nil {
return nil, err
}
result := &pps.WorkerStatus{
JobID: a.jobID,
WorkerID: a.workerName,
Started: started,
Data: a.datum(),
QueueSize: atomic.LoadInt64(&a.queueSize),
}
return result, nil
}
// Cancel cancels the currently running datum
func (a *APIServer) Cancel(ctx context.Context, request *CancelRequest) (*CancelResponse, error) {
a.statusMu.Lock()
defer a.statusMu.Unlock()