forked from dnanexus/dxfuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dxfuse.go
1966 lines (1720 loc) · 47.2 KB
/
dxfuse.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 dxfuse
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/dnanexus/dxda"
"github.com/hashicorp/go-retryablehttp" // use http libraries from hashicorp for implement retry logic
"github.com/jacobsa/fuse"
"github.com/jacobsa/fuse/fuseops"
"github.com/jacobsa/fuse/fuseutil"
// for the sqlite driver
_ "github.com/mattn/go-sqlite3"
)
const (
// namespace for xattrs
XATTR_TAG = "tag"
XATTR_PROP = "prop"
XATTR_BASE = "base"
)
func NewDxfuse(
dxEnv dxda.DXEnvironment,
manifest Manifest,
options Options) (*Filesys, error) {
// initialize a pool of http-clients.
httpIoPool := make(chan *retryablehttp.Client, HttpClientPoolSize)
for i:=0; i < HttpClientPoolSize; i++ {
httpIoPool <- dxda.NewHttpClient(true)
}
fsys := &Filesys{
dxEnv : dxEnv,
options: options,
dbFullPath : DatabaseFile,
mutex : sync.Mutex{},
httpClientPool: httpIoPool,
ops : NewDxOps(dxEnv, options),
fhCounter : 1,
fhTable : make(map[fuseops.HandleID]*FileHandle),
dhCounter : 1,
dhTable : make(map[fuseops.HandleID]*DirHandle),
nonce : NewNonce(),
tmpFileCounter : 0,
shutdownCalled : false,
}
// Create a fresh SQL database
dbParentFolder := filepath.Dir(DatabaseFile)
if _, err := os.Stat(dbParentFolder); os.IsNotExist(err) {
os.Mkdir(dbParentFolder, 0755)
}
fsys.log("Removing old version of the database (%s)", DatabaseFile)
if err := os.RemoveAll(DatabaseFile); err != nil {
fsys.log("error removing old database %b", err)
os.Exit(1)
}
// Create a directory for new files
os.RemoveAll(CreatedFilesDir)
if _, err := os.Stat(CreatedFilesDir); os.IsNotExist(err) {
os.Mkdir(CreatedFilesDir, 0755)
}
// create the metadata database
mdb, err := NewMetadataDb(fsys.dbFullPath, dxEnv, options)
if err != nil {
return nil, err
}
fsys.mdb = mdb
if err := fsys.mdb.Init(); err != nil {
return nil, err
}
oph := fsys.OpOpen()
if err := fsys.mdb.PopulateRoot(context.TODO(), oph, manifest); err != nil {
fsys.OpClose(oph)
return nil, err
}
fsys.OpClose(oph)
fsys.pgs = NewPrefetchGlobalState(options.VerboseLevel, dxEnv)
// describe all the projects, we need their upload parameters
httpClient := <- fsys.httpClientPool
defer func() {
fsys.httpClientPool <- httpClient
} ()
if options.ReadOnly {
// we don't need the file upload module
return fsys, nil
}
projId2Desc := make(map[string]DxDescribePrj)
for _, d := range manifest.Directories {
pDesc, err := DxDescribeProject(context.TODO(), httpClient, &fsys.dxEnv, d.ProjId)
if err != nil {
fsys.log("Could not describe project %s, check permissions", d.ProjId)
return nil, err
}
projId2Desc[pDesc.Id] = *pDesc
}
// initialize background upload state
fsys.fugs = NewFileUploadGlobalState(options, dxEnv, projId2Desc)
// Provide the upload module with a reference to the database.
// This is needed to report the end of an upload.
fsys.fugs.mdb = mdb
return fsys, nil
}
// write a log message, and add a header
func (fsys *Filesys) log(a string, args ...interface{}) {
LogMsg("dxfuse", a, args...)
}
func (fsys *Filesys) OpOpen() *OpHandle {
txn, err := fsys.mdb.BeginTxn()
if err != nil {
log.Panic("Could not open transaction")
}
httpClient := <- fsys.httpClientPool
return &OpHandle{
httpClient : httpClient,
txn : txn,
err : nil,
}
}
func (fsys *Filesys) OpClose(oph *OpHandle) {
fsys.httpClientPool <- oph.httpClient
if oph.err == nil {
err := oph.txn.Commit()
if err != nil {
log.Panic("could not commit transaction")
}
} else {
err := oph.txn.Rollback()
if err != nil {
log.Panic("could not rollback transaction")
}
}
}
func (fsys *Filesys) Shutdown() {
if fsys.shutdownCalled {
// shutdown has already been called.
// We are not waiting for anything, and just
// unmounting the filesystem here.
fsys.log("Shutdown called a second time, skipping the normal sequence")
return
}
fsys.shutdownCalled = true
// Close the sql database.
//
// If there is an error, we report it. There is nothing actionable
// to do with it.
//
// We do not remove the metadata database file, so it could be inspected offline.
fsys.log("Shutting down dxfuse")
// stop any background operations the metadata database may be running.
fsys.mdb.Shutdown()
// stop the running threads in the prefetch module
fsys.pgs.Shutdown()
// complete pending uploads
if !fsys.options.ReadOnly {
fsys.fugs.Shutdown()
}
}
func (fsys *Filesys) dxErrorToFilesystemError(dxErr dxda.DxError) error {
switch dxErr.EType {
case "InvalidInput":
return fuse.EINVAL
case "PermissionDenied":
return syscall.EPERM
case "InvalidType":
return fuse.EINVAL
case "ResourceNotFound":
return fuse.ENOENT
case "Unauthorized":
return syscall.EPERM
default:
fsys.log("unexpected dnanexus error type (%s), returning EIO which will unmount the filesystem",
dxErr.EType)
return fuse.EIO
}
}
func (fsys *Filesys) translateError(err error) error {
switch err.(type) {
case *dxda.DxError:
// A dnanexus error
dxErr := err.(*dxda.DxError)
return fsys.dxErrorToFilesystemError(*dxErr)
default:
// A "regular" error
fsys.log("A regular error from an API call %s, converting to EIO", err.Error())
return fuse.EIO
}
}
func (fsys *Filesys) StatFS(ctx context.Context, op *fuseops.StatFSOp) error {
return nil
}
func (fsys *Filesys) calcExpirationTime(a fuseops.InodeAttributes) time.Time {
if !a.Mode.IsDir() && a.Mode != 0444 {
// A file created locally. It is probably being written to,
// so there is no sense in caching for a long time
if fsys.options.Verbose {
fsys.log("Setting small attribute expiration time")
}
return time.Now().Add(1 * time.Second)
}
// We don't spontaneously mutate, so the kernel can cache as long as it wants
// (since it also handles invalidation).
return time.Now().Add(365 * 24 * time.Hour)
}
func (fsys *Filesys) LookUpInode(ctx context.Context, op *fuseops.LookUpInodeOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
parentDir, ok, err := fsys.mdb.LookupDirByInode(ctx, oph, int64(op.Parent))
if err != nil {
fsys.log("database error in LookupInode: %s", err.Error())
return fuse.EIO
}
if !ok {
// parent directory does not exist
return fuse.ENOENT
}
node, ok, err := fsys.mdb.LookupInDir(ctx, oph, &parentDir, op.Name)
if err != nil {
fsys.log("database error in LookUpInode: %s", err.Error())
return fuse.EIO
}
if !ok {
// file does not exist
return fuse.ENOENT
}
// Fill in the response.
op.Entry.Child = node.GetInode()
op.Entry.Attributes = node.GetAttrs()
// We don't spontaneously mutate, so the kernel can cache as long as it wants
// (since it also handles invalidation).
op.Entry.AttributesExpiration = fsys.calcExpirationTime(op.Entry.Attributes)
op.Entry.EntryExpiration = op.Entry.AttributesExpiration
return nil
}
func (fsys *Filesys) GetInodeAttributes(ctx context.Context, op *fuseops.GetInodeAttributesOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
// Grab the inode.
node, ok, err := fsys.mdb.LookupByInode(ctx, oph, int64(op.Inode))
if err != nil {
fsys.log("database error in GetInodeAttributes: %s", err.Error())
return fuse.EIO
}
if !ok {
return fuse.ENOENT
}
if fsys.options.Verbose {
fsys.log("GetInodeAttributes(inode=%d, %v)", int64(op.Inode), node)
}
// Fill in the response.
op.Attributes = node.GetAttrs()
op.AttributesExpiration = fsys.calcExpirationTime(op.Attributes)
return nil
}
// if the file is writable, we can modify some of the attributes.
// otherwise, this is a permission error.
func (fsys *Filesys) SetInodeAttributes(ctx context.Context, op *fuseops.SetInodeAttributesOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
// Grab the inode.
node, ok, err := fsys.mdb.LookupByInode(ctx, oph, int64(op.Inode))
if err != nil {
fsys.log("SetInodeAttributes: database error %s", err.Error())
return fuse.EIO
}
if !ok {
return fuse.ENOENT
}
if fsys.options.Verbose {
fsys.log("SetInodeAttributes(inode=%d, %v)", int64(op.Inode), node)
}
var file File
switch node.(type) {
case File:
file = node.(File)
case Dir:
// can't modify directory attributes
return syscall.EPERM
}
// we know it is a file.
// check if this is a read-only file.
attrs := file.GetAttrs()
if attrs.Mode == fileReadOnlyMode {
return syscall.EPERM
}
// update the file
oldSize := attrs.Size
if op.Size != nil {
attrs.Size = *op.Size
}
if op.Mode != nil {
attrs.Mode = *op.Mode
}
if op.Mtime != nil {
attrs.Mtime = *op.Mtime
}
// we don't handle atime
if err := fsys.mdb.UpdateFile(ctx, oph, file, int64(attrs.Size), attrs.Mtime, attrs.Mode); err != nil {
fsys.log("database error in OpenFile %s", err.Error())
return fuse.EIO
}
if op.Size != nil && *op.Size != oldSize {
// The size changed, truncate the file
localPath := file.InlineData
if err := os.Truncate(localPath, int64(*op.Size)); err != nil {
fsys.log("Error truncating inode=%d from %d to %d",
op.Inode, oldSize, op.Size)
return err
}
}
// Fill in the response.
op.Attributes = attrs
op.AttributesExpiration = fsys.calcExpirationTime(attrs)
return nil
}
// make a pass through the open handles, and
// release handles that reference this inode.
func (fsys *Filesys) removeFileHandlesWithInode(inode int64) {
handles := make([]fuseops.HandleID, 0)
for hid, fh := range fsys.fhTable {
if fh.f.Inode == inode {
handles = append(handles, hid)
}
}
for _, hid := range handles {
delete(fsys.fhTable, hid)
}
}
func (fsys *Filesys) removeDirHandlesWithInode(inode int64) {
handles := make([]fuseops.HandleID, 0)
for did, dh := range fsys.dhTable {
if dh.d.Inode == inode {
handles = append(handles, did)
}
}
for _, did := range handles {
delete(fsys.dhTable, did)
}
}
// This may be the wrong way to do it. We may need to actually delete the inode at this point,
// instead of inside RmDir/Unlink.
func (fsys *Filesys) ForgetInode(ctx context.Context, op *fuseops.ForgetInodeOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
if fsys.options.Verbose {
fsys.log("ForgetInode (%d)", op.Inode)
}
fsys.removeFileHandlesWithInode(int64(op.Inode))
fsys.removeDirHandlesWithInode(int64(op.Inode))
return nil
}
func (fsys *Filesys) MkDir(ctx context.Context, op *fuseops.MkDirOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
if fsys.options.Verbose {
fsys.log("CreateDir(%s)", op.Name)
}
// the parent is supposed to be a directory
parentDir, ok, err := fsys.mdb.LookupDirByInode(ctx, oph, int64(op.Parent))
if err != nil {
fsys.log("database error in MkDir")
return fuse.EIO
}
if !ok {
// parent directory does not exist
return fuse.ENOENT
}
// Check if the directory exists
_, ok, err = fsys.mdb.LookupInDir(ctx, oph, &parentDir, op.Name)
if err != nil {
fsys.log("database error in MkDir")
return fuse.EIO
}
if ok {
// The directory already exists
return fuse.EEXIST
}
// The mode must be 777 for fuse to work properly
// We -ignore- the mode set by the user.
mode := dirReadWriteMode
// create the directory on dnanexus
folderFullPath := parentDir.ProjFolder + "/" + op.Name
err = fsys.ops.DxFolderNew(ctx, oph.httpClient, parentDir.ProjId, folderFullPath)
if err != nil {
fsys.log("Error in creating directory (%s:%s) on dnanexus: %s",
parentDir.ProjId, folderFullPath, err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
// Add the directory to the database
now := time.Now()
nowSeconds := now.Unix()
dnode, err := fsys.mdb.CreateDir(
oph,
parentDir.ProjId,
folderFullPath,
nowSeconds,
nowSeconds,
mode,
parentDir.FullPath + "/" + op.Name)
if err != nil {
fsys.log("database error in MkDir")
return fuse.EIO
}
// Fill in the response, the details for the new subdirectory
childAttrs := fuseops.InodeAttributes{
Nlink: 1,
Mode: mode,
Atime: now,
Mtime: now,
Ctime: now,
Crtime: now,
Uid: fsys.options.Uid,
Gid: fsys.options.Gid,
}
tWindow := fsys.calcExpirationTime(childAttrs)
op.Entry = fuseops.ChildInodeEntry{
Child : fuseops.InodeID(dnode),
Attributes : childAttrs,
AttributesExpiration : tWindow,
EntryExpiration : tWindow,
}
return nil
}
func (fsys *Filesys) RmDir(ctx context.Context, op *fuseops.RmDirOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
if fsys.options.Verbose {
fsys.log("Remove Dir(%s)", op.Name)
}
// the parent is supposed to be a directory
parentDir, ok, err := fsys.mdb.LookupDirByInode(ctx, oph, int64(op.Parent))
if err != nil {
fsys.log("database error in RmDir")
return fuse.EIO
}
if !ok {
// parent directory does not exist
return fuse.ENOENT
}
// Check if the directory exists
childNode, ok, err := fsys.mdb.LookupInDir(ctx, oph, &parentDir, op.Name)
if err != nil {
fsys.log("database error in RmDir")
return fuse.EIO
}
if !ok {
// The directory does not exist
return fuse.ENOENT
}
var childDir Dir
switch childNode.(type) {
case File:
return fuse.ENOTDIR
case Dir:
childDir = childNode.(Dir)
}
// check that the directory is empty
dentries, err := fsys.readEntireDir(ctx, oph, childDir)
if err != nil {
return err
}
if len(dentries) > 0 {
return fuse.ENOTEMPTY
}
if !childDir.faux {
// The directory exists and is empty, we can remove it.
folderFullPath := parentDir.ProjFolder + "/" + op.Name
err = fsys.ops.DxFolderRemove(ctx, oph.httpClient, parentDir.ProjId, folderFullPath)
if err != nil {
fsys.log("Error in removing directory (%s:%s) on dnanexus: %s",
parentDir.ProjId, folderFullPath, err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
} else {
// A faux directory doesn't have a matching project folder.
// It exists only on the local machine.
}
// Remove the directory from the database
if err := fsys.mdb.RemoveEmptyDir(oph, childDir.Inode); err != nil {
return err
}
return nil
}
// Allocate an unused file handle.
//
// Note: We want to have a guarantied O(1) algorithm, otherwise, we would use a
// randomized approach.
//
func (fsys *Filesys) insertIntoFileHandleTable(fh *FileHandle) fuseops.HandleID {
fsys.fhCounter++
hid := fuseops.HandleID(fsys.fhCounter)
fsys.fhTable[hid] = fh
fh.hid = hid
return hid
}
func (fsys *Filesys) insertIntoDirHandleTable(dh *DirHandle) fuseops.HandleID {
fsys.dhCounter++
did := fuseops.HandleID(fsys.dhCounter)
fsys.dhTable[did] = dh
return did
}
// A CreateRequest asks to create and open a file (not a directory).
//
func (fsys *Filesys) CreateFile(ctx context.Context, op *fuseops.CreateFileOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
if fsys.options.Verbose {
fsys.log("CreateFile(%s)", op.Name)
}
// the parent is supposed to be a directory
parentDir, ok, err := fsys.mdb.LookupDirByInode(ctx, oph, int64(op.Parent))
if err != nil {
return err
}
if !ok {
// parent directory does not exist
return fuse.ENOENT
}
if parentDir.faux {
// cannot write new files into faux directories
return syscall.EPERM
}
// Check if the file already exists
_, ok, err = fsys.mdb.LookupInDir(ctx, oph, &parentDir, op.Name)
if err != nil {
return err
}
if ok {
// The file already exists
return fuse.EEXIST
}
// we now know that the parent directory exists, and the file
// does not.
// Create a temporary file in a protected directory, used only
// by dxfuse.
cnt := atomic.AddUint64(&fsys.tmpFileCounter, 1)
localPath := fmt.Sprintf("%s/%d_%s", CreatedFilesDir, cnt, op.Name)
// create the file object on the platform.
fileId, err := fsys.ops.DxFileNew(
ctx, oph.httpClient, fsys.nonce.String(),
parentDir.ProjId, op.Name, parentDir.ProjFolder)
if err != nil {
fsys.log("Error in creating file (%s:%s/%s) on dnanexus: %s",
parentDir.ProjId, parentDir.ProjFolder, op.Name,
err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
file, err := fsys.mdb.CreateFile(ctx, oph, &parentDir, fileId, op.Name, op.Mode, localPath)
if err != nil {
return err
}
// Set up attributes for the child.
now := time.Now()
childAttrs := fuseops.InodeAttributes{
Nlink: 1,
Mode: op.Mode,
Atime: now,
Mtime: now,
Ctime: now,
Crtime: now,
Uid: fsys.options.Uid,
Gid: fsys.options.Gid,
}
// We need a short time window, because the file attributes are likely to
// soon change. We are writing new content into the file.
tWindow := fsys.calcExpirationTime(childAttrs)
op.Entry = fuseops.ChildInodeEntry{
Child : fuseops.InodeID(file.Inode),
Attributes : childAttrs,
AttributesExpiration : tWindow,
EntryExpiration : tWindow,
}
// Note: we can't open the file in exclusive mode, because another process
// may read it before it is closed.
writer, err := os.OpenFile(localPath, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
oph.RecordError(err)
return err
}
fh := FileHandle{
fKind : RW_File,
f : file,
url : nil,
localPath : &localPath,
fd : writer,
}
op.Handle = fsys.insertIntoFileHandleTable(&fh)
return nil
}
func (fsys *Filesys) CreateLink(ctx context.Context, op *fuseops.CreateLinkOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
if fsys.options.Verbose {
fsys.log("CreateLink (inode=%d) -> (parent-inode=%d name=%s)",
op.Target, op.Parent, op.Name)
}
// parent is supposed to be a directory
parentDir, ok, err := fsys.mdb.LookupDirByInode(ctx, oph, int64(op.Parent))
if err != nil {
return err
}
if !ok {
// parent directory does not exist
return fuse.ENOENT
}
// Make sure the destination doesn't already exist
_, ok, err = fsys.mdb.LookupInDir(ctx, oph, &parentDir, op.Name)
if err != nil {
return err
}
if ok {
// The link file already exists
return fuse.EEXIST
}
// make sure that target node exists
targetNode, ok, err := fsys.mdb.LookupByInode(ctx, oph, int64(op.Target))
if err != nil {
return err
}
if !ok {
return fuse.ENOENT
}
var targetFile File
switch targetNode.(type) {
case Dir:
// can't make a hard link to a directory
return fuse.EINVAL
case File:
targetFile = targetNode.(File)
}
if targetFile.Name != op.Name {
fsys.log("cloning is only allowed if the destination and source names are the same")
return fuse.EINVAL
}
if fsys.options.Verbose {
fsys.log("CreateLink %s/%s -> %s",
parentDir.FullPath, op.Name, targetFile.Name)
}
// create a link on the platform. This is done with the clone call.
ok, err = fsys.ops.DxClone(
ctx, oph.httpClient,
targetFile.ProjId, // source project
targetFile.Id, // source id
parentDir.ProjId, // destination project id
parentDir.ProjFolder) // destination folder
if err != nil {
fsys.log("dx clone error %s", err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
if !ok {
fsys.log("(%s) object not cloned because it already exists in the target project (%s)",
targetFile.Id, parentDir.ProjId)
return syscall.EINVAL
}
destFile, err := fsys.mdb.CreateLink(ctx, oph, targetFile, parentDir, op.Name)
if err != nil {
fsys.log("database error in create-link %s", err.Error())
return fuse.EIO
}
// fill in child information
op.Entry.Child = destFile.GetInode()
op.Entry.Attributes = destFile.GetAttrs()
// We don't spontaneously mutate, so the kernel can cache as long as it wants
// (since it also handles invalidation).
op.Entry.AttributesExpiration = fsys.calcExpirationTime(op.Entry.Attributes)
op.Entry.EntryExpiration = op.Entry.AttributesExpiration
return nil
}
func (fsys *Filesys) renameFile(
ctx context.Context,
oph *OpHandle,
oldParentDir Dir,
newParentDir Dir,
file File,
newName string) error {
if oldParentDir.Inode == newParentDir.Inode {
// /file-xxxx/rename API call
err := fsys.ops.DxRename(ctx, oph.httpClient, file.ProjId, file.Id, newName)
if err != nil {
fsys.log("Error in renaming file (%s:%s%s) on dnanexus: %s",
file.ProjId, oldParentDir.ProjFolder, file.Name,
err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
} else {
// /project-xxxx/move {objects, folders} -> destination
// move the file on the platform
var objIds []string
objIds = append(objIds, file.Id)
err := fsys.ops.DxMove(ctx, oph.httpClient, file.ProjId,
objIds, nil, newParentDir.ProjFolder)
if err != nil {
fsys.log("Error in moving file (%s:%s/%s) on dnanexus: %s",
file.ProjId, oldParentDir.ProjFolder, file.Name,
err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
}
err := fsys.mdb.MoveFile(ctx, oph, file.Inode, newParentDir, newName)
if err != nil {
fsys.log("database error in rename")
return fuse.EIO
}
return nil
}
func (fsys *Filesys) renameDir(
ctx context.Context,
oph *OpHandle,
oldParentDir Dir,
newParentDir Dir,
oldDir Dir,
newName string) error {
projId := oldParentDir.ProjId
if oldParentDir.Inode == newParentDir.Inode {
// rename a folder, but leave it under the same parent
err := fsys.ops.DxRenameFolder(
ctx, oph.httpClient,
projId,
oldDir.ProjFolder,
newName)
if err != nil {
fsys.log("Error in folder rename %s -> %s on dnanexus, %s",
oldDir.FullPath, newName, err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
} else {
// we are moving a directory to another directory. For example:
// mkdir A
// mkdir B
// mv A B/
// The name "A" should not change.
check(newName == filepath.Base(oldDir.Dname))
// move a folder to a new parent
objIds := make([]string, 0)
folders := make([]string, 1)
folders[0] = oldDir.ProjFolder
err := fsys.ops.DxMove(
ctx, oph.httpClient,
projId,
objIds, folders,
newParentDir.ProjFolder)
if err != nil {
fsys.log("Error in moving directory %s:%s -> %s on dnanexus: %s",
projId, oldDir.ProjFolder, newParentDir.ProjFolder,
err.Error())
oph.RecordError(err)
return fsys.translateError(err)
}
}
err := fsys.mdb.MoveDir(ctx, oph, oldParentDir, newParentDir, oldDir, newName)
if err != nil {
fsys.log("Database error in moving directory %s -> %s/%s",
oldDir.FullPath, newParentDir.FullPath, newName)
return fuse.EIO
}
return nil
}
func (fsys *Filesys) Rename(ctx context.Context, op *fuseops.RenameOp) error {
fsys.mutex.Lock()
defer fsys.mutex.Unlock()
oph := fsys.OpOpen()
defer fsys.OpClose(oph)
if fsys.options.Verbose {
fsys.log("Rename (inode=%d name=%s) -> (inode=%d, name=%s)",
op.OldParent, op.OldName,
op.NewParent, op.NewName)
}
// the old parent is supposed to be a directory
oldParentDir, ok, err := fsys.mdb.LookupDirByInode(ctx, oph, int64(op.OldParent))
if err != nil {
return err
}
if !ok {
// parent directory does not exist
return fuse.ENOENT
}
// the new parent is supposed to be a directory
newParentDir, ok, err := fsys.mdb.LookupDirByInode(ctx, oph, int64(op.NewParent))
if err != nil {
return err
}
if !ok {
// parent directory does not exist
return fuse.ENOENT
}
if newParentDir.faux {
fsys.log("can not move files into a faux dir")
return syscall.EPERM
}
// Find the source file
srcNode, ok, err := fsys.mdb.LookupInDir(ctx, oph, &oldParentDir, op.OldName)
if err != nil {
return err
}
if !ok {
// The source file doesn't exist
return fuse.ENOENT
}
// check if the target exists.
_, ok, err = fsys.mdb.LookupInDir(ctx, oph, &newParentDir, op.NewName)
if err != nil {
return err
}
if ok {
fsys.log(`
Target already exists. We do not support atomically remove in conjunction with
a rename. You will need to issue a separate remove operation prior to rename.
`)
return syscall.EPERM
}
oldDir := filepath.Clean(oldParentDir.FullPath + "/" + op.OldName)
if oldDir == "/" {
fsys.log("can not move the root directory")
return syscall.EPERM
}
if oldParentDir.Inode == InodeRoot {
// project directories are immediate children of the root.
// these cannot be moved
fsys.log("Can not move a project directory")
return syscall.EPERM
}
if newParentDir.Inode == InodeRoot {
// can't move into the root directory
fsys.log("Can not move into the root directory")
return syscall.EPERM
}
if oldParentDir.ProjId != newParentDir.ProjId {
// can't move between projects
fsys.log("Can not move objects between projects")
return syscall.EPERM
}
if oldParentDir.Inode == newParentDir.Inode &&
op.OldName == op.NewName {
fsys.log("can't move a file onto itself")
return syscall.EPERM
}
switch srcNode.(type) {
case File:
return fsys.renameFile(ctx, oph, oldParentDir, newParentDir, srcNode.(File), op.NewName)
case Dir:
srcDir := srcNode.(Dir)
if srcDir.faux {
fsys.log("can not move a faux directory")
return syscall.EPERM
}
return fsys.renameDir(ctx, oph, oldParentDir, newParentDir, srcDir, op.NewName)
default:
log.Panic(fmt.Sprintf("bad type for srcNode %v", srcNode))
}
return nil
}