-
Notifications
You must be signed in to change notification settings - Fork 568
/
server.go
1774 lines (1613 loc) · 49.1 KB
/
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 fuse
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/signal"
pathpkg "path"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/hanwen/go-fuse/v2/fs"
gofuse "github.com/hanwen/go-fuse/v2/fuse"
"go.uber.org/zap"
"golang.org/x/exp/slices"
"github.com/pachyderm/pachyderm/v2/src/auth"
"github.com/pachyderm/pachyderm/v2/src/internal/client"
"github.com/pachyderm/pachyderm/v2/src/internal/config"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
"github.com/pachyderm/pachyderm/v2/src/internal/errutil"
"github.com/pachyderm/pachyderm/v2/src/internal/grpcutil"
"github.com/pachyderm/pachyderm/v2/src/internal/log"
"github.com/pachyderm/pachyderm/v2/src/internal/pctx"
"github.com/pachyderm/pachyderm/v2/src/internal/ppsutil"
"github.com/pachyderm/pachyderm/v2/src/internal/progress"
"github.com/pachyderm/pachyderm/v2/src/internal/serde"
"github.com/pachyderm/pachyderm/v2/src/internal/signals"
"github.com/pachyderm/pachyderm/v2/src/internal/uuid"
"github.com/pachyderm/pachyderm/v2/src/pfs"
"github.com/pachyderm/pachyderm/v2/src/pps"
)
type ServerOptions struct {
MountDir string
// Unmount is a channel that will be closed when the filesystem has been
// unmounted. It can be nil in which case it's ignored.
Unmount chan struct{}
// True if allow-other option is to be specified
AllowOther bool
}
type ConfigRequest struct {
PachdAddress string `json:"pachd_address"`
ServerCas string `json:"server_cas"`
}
type MountRequest struct {
Mounts []*MountInfo `json:"mounts"`
}
type UnmountRequest struct {
Mounts []string `json:"mounts"`
}
type CommitRequest struct {
Mount string `json:"mount"`
}
type MountDatumResponse struct {
Id string `json:"id"`
Idx int `json:"idx"`
NumDatums int `json:"num_datums"`
}
type DatumsResponse struct {
NumDatums int `json:"num_datums"`
Input *pps.Input `json:"input"`
CurrIdx int `json:"curr_idx"`
}
type MountInfo struct {
Name string `json:"name"`
Project string `json:"project"`
Repo string `json:"repo"`
Branch string `json:"branch"`
Commit string `json:"commit"` // "" for no commit (commit as noun)
Files []string `json:"files"`
Mode string `json:"mode"` // "ro", "rw"
}
type Request struct {
*MountInfo
Action string // default empty, set to "commit" if we want to commit (verb) a mounted branch
}
type Response struct {
Project string
Repo string
Branch string
Commit string // "" for no commit
Name string
MountState MountState
Error error
}
type MountManager struct {
Client *client.APIClient
// only put a value into the States map when we have a goroutine running for
// it. i.e. when we try to mount it for the first time.
States map[string]*MountStateMachine
Datums []*pps.DatumInfo
DatumInput *pps.Input
DatumInputsToMounts map[string]string
CurrDatumIdx int
// map from mount name onto mfc for that mount
mfcs map[string]*client.ModifyFileClient
root *loopbackRoot
opts *Options
tmpDir string
target string
mu sync.Mutex
configMu sync.RWMutex
Cleanup chan struct{}
}
func (mm *MountManager) ListByRepos() (ListRepoResponse, error) {
// fetch list of available repos & branches from pachyderm, and overlay that
// with their mount states
lr := ListRepoResponse{}
repos, err := mm.Client.ListRepo()
if err != nil {
log.Info(pctx.TODO(), "Error listing repos", zap.Error(err))
return lr, err
}
for _, repo := range repos {
projectName := repo.Repo.GetProject().GetName()
repoName := repo.Repo.Name
rr := RepoResponse{Repo: repoName, Project: projectName}
readAccess := true
if repo.AuthInfo != nil {
readAccess = hasRepoRead(repo.AuthInfo.Permissions)
rr.Authorization = "none"
}
if readAccess {
bis, err := mm.Client.ListBranch(projectName, repoName)
if err != nil {
// Repo was deleted between ListRepo and ListBranch RPCs
if auth.IsErrNoRoleBinding(err) {
continue
}
return lr, err
}
for _, bi := range bis {
rr.Branches = append(rr.Branches, bi.Branch.Name)
}
if repo.AuthInfo == nil {
rr.Authorization = "off"
} else if hasRepoWrite(repo.AuthInfo.Permissions) {
rr.Authorization = "write"
} else {
rr.Authorization = "read"
}
}
lr = append(lr, rr)
}
return lr, nil
}
func (mm *MountManager) ListByMounts() (ListMountResponse, error) {
mm.mu.Lock()
defer mm.mu.Unlock()
mr := ListMountResponse{
Mounted: []MountState{},
Unmounted: []RepoResponse{},
}
for name, msm := range mm.States {
if msm.State == "mounted" {
// Check if a mounted repo/branch was deleted to remove it from state.
var exists bool
if msm.Mode == "ro" {
exists, _ = msm.MountInfo.verifyProjectRepoBranchCommitExist(mm.Client)
} else {
exists, _ = msm.MountInfo.verifyProjectRepoExist(mm.Client)
}
if !exists {
mm.unmountDeletedRepos(name)
continue
}
if err := msm.RefreshMountState(); err != nil {
return mr, err
}
ms := msm.MountState
ms.Files = nil
mr.Mounted = append(mr.Mounted, ms)
}
}
lr, err := mm.ListByRepos()
if err != nil {
return mr, err
}
mr.Unmounted = lr
return mr, nil
}
func (mm *MountManager) unmountDeletedRepos(name string) {
mm.States[name].requests <- Request{
Action: "unmount",
}
<-mm.States[name].responses
}
func NewMountStateMachine(name string, mm *MountManager) *MountStateMachine {
return &MountStateMachine{
MountState: MountState{
MountInfo: MountInfo{
Name: name,
},
},
manager: mm,
mu: sync.Mutex{},
requests: make(chan Request),
responses: make(chan Response),
}
}
func (mm *MountManager) MaybeStartFsm(name string) {
mm.mu.Lock()
defer mm.mu.Unlock()
_, ok := mm.States[name]
if !ok {
// set minimal state and kick it off!
m := NewMountStateMachine(name, mm)
mm.States[name] = m
go func() {
m.Run()
// when execution completes, remove ourselves from the map so that
// we can infer from the key in the map that the state machine is
// running
mm.mu.Lock()
defer mm.mu.Unlock()
delete(mm.States, name)
}()
} // else: fsm was already running
}
func (mm *MountManager) MountRepo(mi *MountInfo) (Response, error) {
mm.MaybeStartFsm(mi.Name)
mm.States[mi.Name].requests <- Request{
Action: "mount",
MountInfo: mi,
}
response := <-mm.States[mi.Name].responses
return response, response.Error
}
func (mm *MountManager) UnmountRepo(name string) (Response, error) {
mm.MaybeStartFsm(name)
mm.States[name].requests <- Request{
Action: "unmount",
}
response := <-mm.States[name].responses
return response, response.Error
}
func (mm *MountManager) CommitRepo(name string) (Response, error) {
mm.MaybeStartFsm(name)
mm.States[name].requests <- Request{
Action: "commit",
}
response := <-mm.States[name].responses
return response, response.Error
}
func (mm *MountManager) UnmountAll() error {
for name, msm := range mm.States {
if msm.State == "mounted" {
if _, err := mm.UnmountRepo(name); err != nil {
return err
}
}
}
return removeOutDir(mm)
}
func NewMountManager(c *client.APIClient, target string, opts *Options) (ret *MountManager, retErr error) {
if err := opts.validate(c); err != nil {
return nil, err
}
rootDir, err := os.MkdirTemp("", "pfs")
if err != nil {
return nil, errors.WithStack(err)
}
log.Info(pctx.TODO(), "Creating root directory", zap.String("path", rootDir))
if err := os.MkdirAll(rootDir, 0777); err != nil {
return nil, errors.WithStack(err)
}
root, err := newLoopbackRoot(rootDir, target, c, opts)
if err != nil {
return nil, errors.WithStack(err)
}
log.Info(pctx.TODO(), "Loopback root created", zap.Stringer("path", root))
return &MountManager{
Client: c,
States: map[string]*MountStateMachine{},
mfcs: map[string]*client.ModifyFileClient{},
root: root,
opts: opts,
target: target,
tmpDir: rootDir,
mu: sync.Mutex{},
configMu: sync.RWMutex{},
Cleanup: make(chan struct{}),
}, nil
}
func CreateMount(c *client.APIClient, mountDir string, allowOther bool) (*MountManager, error) {
mountOpts := &Options{
Write: true,
Fuse: &fs.Options{
MountOptions: gofuse.MountOptions{
Debug: false,
FsName: "pfs",
Name: "pfs",
AllowOther: allowOther,
},
},
RepoOptions: make(map[string]*RepoOptions),
// thread this through for the tests
Unmount: make(chan struct{}),
}
mm, err := NewMountManager(c, mountDir, mountOpts)
if err != nil {
return nil, err
}
go mm.Start()
return mm, nil
}
func (mm *MountManager) Start() {
if err := mm.Run(); err != nil {
log.Info(pctx.TODO(), "Error running mount manager", zap.Error(err))
os.Exit(1)
}
}
func (mm *MountManager) Run() error {
fuse := mm.opts.getFuse()
server, err := fs.Mount(mm.target, mm.root, fuse)
if err != nil {
return errors.WithStack(err)
}
go func() {
<-mm.opts.getUnmount()
server.Unmount() //nolint:errcheck
}()
server.Wait()
defer mm.FinishAll() //nolint:errcheck
if err := mm.uploadFiles(""); err != nil {
return err
}
if err := os.RemoveAll(mm.tmpDir); err != nil {
return nil
}
close(mm.Cleanup)
return nil
}
func (mm *MountManager) FinishAll() (retErr error) {
for _, mfc := range mm.mfcs {
if err := mfc.Close(); err != nil && retErr == nil {
retErr = err
}
}
return retErr
}
func Server(sopts *ServerOptions, existingClient *client.APIClient) error {
log.Info(pctx.TODO(), "Dynamically mounting pfs", zap.String("mountDir", sopts.MountDir))
// This variable points to the MountManager for each connected cluster.
// Updated when the config is updated.
var mm *MountManager = &MountManager{}
if existingClient != nil {
var err error
mm, err = CreateMount(existingClient, sopts.MountDir, sopts.AllowOther)
if err != nil {
return err
}
log.Info(pctx.TODO(), "Connected to existing client", zap.String("address", existingClient.GetAddress().Qualified()))
}
router := mux.NewRouter()
router.Methods("GET").Path("/repos").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
reposList, err := mm.ListByRepos()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := json.Marshal(reposList)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("GET").Path("/projects").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
projectsList, err := mm.Client.ListProject()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := json.Marshal(projectsList)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("GET").Path("/mounts").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
mountsList, err := mm.ListByMounts()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := json.Marshal(mountsList)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("PUT").Path("/_mount").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
if len(mm.Datums) > 0 {
http.Error(w, "can't mount repos while in mounted datum mode", http.StatusBadRequest)
return
}
// Verify request payload
var mreq MountRequest
defer req.Body.Close()
if err := json.NewDecoder(req.Body).Decode(&mreq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := mm.verifyMountRequest(mreq.Mounts); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for _, mi := range mreq.Mounts {
if _, err := mm.MountRepo(mi); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
mountsList, err := mm.ListByMounts()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := jsonMarshal(mountsList)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("PUT").Path("/_unmount").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
if len(mm.Datums) > 0 {
http.Error(w, "can't unmount repos while in mounted datum mode", http.StatusBadRequest)
return
}
var umreq UnmountRequest
defer req.Body.Close()
if err := json.NewDecoder(req.Body).Decode(&umreq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for _, name := range umreq.Mounts {
if _, err := mm.UnmountRepo(name); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
mountsList, err := mm.ListByMounts()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := jsonMarshal(mountsList)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("PUT").Path("/_commit").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
var creq CommitRequest
defer req.Body.Close()
if err := json.NewDecoder(req.Body).Decode(&creq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if _, err := mm.CommitRepo(creq.Mount); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
mountsList, err := mm.ListByMounts()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := jsonMarshal(mountsList)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("PUT").Path("/_unmount_all").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
if err := mm.UnmountAll(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
func() {
mm.mu.Lock()
defer mm.mu.Unlock()
mm.Datums = nil
mm.DatumInput = nil
mm.CurrDatumIdx = -1
mm.DatumInputsToMounts = nil
}()
mountsList, err := mm.ListByMounts()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := jsonMarshal(mountsList)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("PUT").Path("/_mount_datums").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
defer req.Body.Close()
pipelineReader, err := ppsutil.NewPipelineManifestReader(req.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// TODO(INT-1006): This is a bit of a hack: the body is a tagged
// pipeline input spec, not a full pipeline. In order for
// parsing to succeed, the next line disables spec validation.
pipelineReader.DisableValidation()
pipelineReq, err := pipelineReader.NextCreatePipelineRequest()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
datumInputsToMounts, err := sanitizeInputAndGetAlias(pipelineReq.Input, mm.Client)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
datums, err := mm.Client.ListDatumInputAll(pipelineReq.Input)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(datums) == 0 {
http.Error(w, "no datums match the given input spec", http.StatusBadRequest)
return
}
func() {
mm.mu.Lock()
defer mm.mu.Unlock()
mm.CurrDatumIdx = 0
mm.Datums = datums
mm.DatumInput = pipelineReq.Input
mm.DatumInputsToMounts = datumInputsToMounts
}()
if err := mm.UnmountAll(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Info(pctx.TODO(), "Mounting first datum", zap.String("datumID", datums[0].Datum.Id))
mis := mm.datumToMounts(datums[0])
for _, mi := range mis {
if _, err := mm.MountRepo(mi); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
createLocalOutDir(mm)
resp := MountDatumResponse{
Id: datums[0].Datum.Id,
Idx: 0,
NumDatums: len(datums),
}
marshalled, err := jsonMarshal(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("PUT").Path("/_show_datum").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
if len(mm.Datums) == 0 {
http.Error(w, "no datums mounted", http.StatusBadRequest)
return
}
vs := req.URL.Query()
idxStr := vs.Get("idx")
id := vs.Get("id")
if idxStr == "" && id == "" {
http.Error(w, "need to specify either datum idx or id", http.StatusBadRequest)
return
}
idx := 0
if idxStr != "" {
var err error
idx, err = strconv.Atoi(idxStr)
if err != nil {
http.Error(w, "used a non-integer for datum index", http.StatusBadRequest)
return
}
}
var di *pps.DatumInfo
if id != "" {
foundDatum := false
for idx, di = range mm.Datums {
if di.Datum.Id == id {
foundDatum = true
break
}
}
if !foundDatum {
http.Error(w, "specify a valid datum id", http.StatusBadRequest)
return
}
} else {
di = mm.Datums[idx]
}
if err := mm.UnmountAll(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
mis := mm.datumToMounts(di)
for _, mi := range mis {
if _, err := mm.MountRepo(mi); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
createLocalOutDir(mm)
func() {
mm.mu.Lock()
defer mm.mu.Unlock()
mm.CurrDatumIdx = idx
}()
resp := MountDatumResponse{
Id: di.Datum.Id,
Idx: idx,
NumDatums: len(mm.Datums),
}
marshalled, err := jsonMarshal(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("GET").Path("/datums").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
var resp DatumsResponse
if len(mm.Datums) == 0 {
resp = DatumsResponse{
NumDatums: 0,
}
} else {
resp = DatumsResponse{
NumDatums: len(mm.Datums),
Input: mm.DatumInput,
CurrIdx: mm.CurrDatumIdx,
}
}
marshalled, err := jsonMarshal(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("GET").Path("/config").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, false)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
mm.configMu.RLock()
defer mm.configMu.RUnlock()
clusterStatus, err := getClusterStatus(mm.Client)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := jsonMarshal(clusterStatus)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
router.Methods("PUT").Path("/config").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
mm.configMu.Lock()
defer mm.configMu.Unlock()
var cfgReq ConfigRequest
defer req.Body.Close()
if err := json.NewDecoder(req.Body).Decode(&cfgReq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pachdAddress, err := grpcutil.ParsePachdAddress(cfgReq.PachdAddress)
if err != nil {
http.Error(w, "either empty or poorly formatted cluster endpoint", http.StatusBadRequest)
return
}
if isNewCluster(mm, pachdAddress) {
newClient, err := getNewClient(cfgReq)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if mm.Client != nil {
close(mm.opts.getUnmount())
<-mm.Cleanup
mm.Client.Close()
}
log.Info(pctx.TODO(), "Updating pachd_address", zap.String("address", pachdAddress.Qualified()))
if mm, err = CreateMount(newClient, sopts.MountDir, sopts.AllowOther); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
clusterStatus, err := getClusterStatus(mm.Client)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
marshalled, err := jsonMarshal(clusterStatus)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
// We have split login into two endpoints, both of which must be called to complete the login flow.
// /auth/_login gets the OIDC login, which the user should be redirected to for login. Following this,
// /auth/_login_token should be called to retrieve the session token so that the caller may use it as well.
router.Methods("PUT").Path("/auth/_login").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, false)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
authActive, _ := mm.Client.IsAuthActive()
if !authActive {
http.Error(w, "auth isn't activated on the cluster", http.StatusInternalServerError)
return
}
loginInfo, err := mm.Client.GetOIDCLogin(mm.Client.Ctx(), &auth.GetOIDCLoginRequest{})
if err != nil {
http.Error(w, "no authentication providers configured", http.StatusInternalServerError)
return
}
authUrl := loginInfo.LoginUrl
state := loginInfo.State
r := map[string]string{"auth_url": authUrl, "oidc_state": state}
marshalled, err := jsonMarshal(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
// takes oidc state as arg
// returns pachyderm config for the mount-server
router.Methods("PUT").Path("/auth/_login_token").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
oidcState, err := io.ReadAll(req.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := mm.Client.Authenticate(mm.Client.Ctx(), &auth.AuthenticateRequest{OidcState: string(oidcState)})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
config.WritePachTokenToConfig(resp.PachToken, false) //nolint:errcheck
mm.Client.SetAuthToken(resp.PachToken)
cfg, err := config.Read(false, false)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json, err := serde.EncodeJSON(cfg, serde.WithIndent(2))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(json) //nolint:errcheck
})
router.Methods("PUT").Path("/auth/_logout").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
errMsg, webCode := initialChecks(mm, true)
if errMsg != "" {
http.Error(w, errMsg, webCode)
return
}
cfg, err := config.Read(false, false)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, context, err := cfg.ActiveContext(true)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := mm.UnmountAll(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
context.SessionToken = ""
cfg.Write() //nolint:errcheck
mm.Client.SetAuthToken("")
})
router.Methods("GET").Path("/health").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
health := map[string]string{"status": "running"}
marshalled, err := jsonMarshal(health)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(marshalled) //nolint:errcheck
})
// TODO: switch http server for gRPC server and bind to a unix socket not a
// TCP port (just for convenient manual testing with curl for now...)
// TODO: make port and bind ip parameterizable
srv := &http.Server{Addr: ":9002", Handler: router}
log.AddLoggerToHTTPServer(pctx.TODO(), "http", srv)
go func() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, signals.TerminationSignals...)
select {
case <-sigChan:
case <-sopts.Unmount:
}
if mm.Client != nil {
close(mm.opts.getUnmount())
<-mm.Cleanup
}
srv.Shutdown(context.Background()) //nolint:errcheck
}()
return errors.EnsureStack(srv.ListenAndServe())
}
func initialChecks(mm *MountManager, authCheck bool) (string, int) {
if mm.Client == nil {
return "not connected to a cluster", http.StatusNotFound
}
if authCheck && isAuthOnAndUserUnauthenticated(mm.Client) {
return "user unauthenticated", http.StatusUnauthorized
}
return "", 0
}
func isAuthOnAndUserUnauthenticated(c *client.APIClient) bool {
active, _ := c.IsAuthActive()
if !active {
return false
}
_, err := c.WhoAmI(c.Ctx(), &auth.WhoAmIRequest{})
return err != nil
}
func getClusterStatus(c *client.APIClient) (map[string]string, error) {
clusterStatus := "INVALID"
if err := c.Health(); err == nil {
authActive, err := c.IsAuthActive()
if err != nil {
return nil, err
}
if authActive {
clusterStatus = "AUTH_ENABLED"
} else {
clusterStatus = "AUTH_DISABLED"
}