/
fuse.go
1194 lines (1018 loc) · 32.5 KB
/
fuse.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 (
"errors"
"fmt"
"log"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"time"
"github.com/hanwen/go-fuse/v2/fuse"
"github.com/superfly/litefs"
)
var _ fuse.RawFileSystem = (*FileSystem)(nil)
var _ litefs.InodeNotifier = (*FileSystem)(nil)
// FileSystem represents a raw interface to the FUSE file system.
type FileSystem struct {
mu sync.Mutex
path string // mount path
server *fuse.Server
store *litefs.Store
// Manage file handle creation.
nextHandleID uint64
fileHandles map[uint64]*FileHandle
dirHandles map[uint64]*DirHandle
// User ID for all files in the filesystem.
Uid int
// Group ID for all files in the filesystem.
Gid int
// If true, logs debug information about every FUSE call.
Debug bool
}
// NewFileSystem returns a new instance of FileSystem.
func NewFileSystem(path string, store *litefs.Store) *FileSystem {
return &FileSystem{
path: path,
store: store,
nextHandleID: 0xff00,
fileHandles: make(map[uint64]*FileHandle),
dirHandles: make(map[uint64]*DirHandle),
Uid: os.Getuid(),
Gid: os.Getgid(),
}
}
// Path returns the path to the mount point.
func (fs *FileSystem) Path() string { return fs.path }
// Store returns the underlying store.
func (fs *FileSystem) Store() *litefs.Store { return fs.store }
// Mount mounts the file system to the mount point.
func (fs *FileSystem) Mount() (err error) {
// Create FUSE server and mount it.
fs.server, err = fuse.NewServer(fs, fs.path, &fuse.MountOptions{
Name: "litefs",
Debug: fs.Debug,
EnableLocks: true,
SingleThreaded: true, // TODO: Remove; Release() is causing an unexpected race error
})
if err != nil {
return err
}
go fs.server.Serve()
return fs.server.WaitMount()
}
// Unmount unmounts the file system.
func (fs *FileSystem) Unmount() (err error) {
if fs.server != nil {
if e := fs.server.Unmount(); err == nil {
err = e
}
}
return err
}
// This is called on processing the first request. The
// filesystem implementation can use the server argument to
// talk back to the kernel (through notify methods).
func (fs *FileSystem) Init(server *fuse.Server) {
}
func (fs *FileSystem) String() string { return "litefs" }
func (fs *FileSystem) SetDebug(dbg bool) {}
// InodeNotify invalidates a section of a database file in the kernel page cache.
func (fs *FileSystem) InodeNotify(dbID uint32, off int64, length int64) error {
ino := fs.dbIno(dbID, litefs.FileTypeDatabase)
code := fs.server.InodeNotify(ino, off, length)
switch code {
case fuse.OK, fuse.ENOENT:
return nil
default:
return errnoError(code)
}
}
func (fs *FileSystem) Lookup(cancel <-chan struct{}, header *fuse.InHeader, name string, out *fuse.EntryOut) (code fuse.Status) {
// Ensure lookup is only performed on top-level directory.
if header.NodeId != RootNodeID {
log.Printf("fuse: lookup(): invalid inode: %d", header.NodeId)
return fuse.EINVAL
}
switch name {
case PrimaryFilename:
return fs.lookupPrimary(cancel, header, name, out)
default:
return fs.lookupDBFile(cancel, header, name, out)
}
}
func (fs *FileSystem) lookupPrimary(cancel <-chan struct{}, header *fuse.InHeader, name string, out *fuse.EntryOut) (code fuse.Status) {
attr, err := fs.primaryAttr()
if err != nil {
return toErrno(err)
}
out.NodeId = PrimaryNodeID
out.Generation = 1
out.Attr = attr
return fuse.OK
}
func (fs *FileSystem) lookupDBFile(cancel <-chan struct{}, header *fuse.InHeader, name string, out *fuse.EntryOut) (code fuse.Status) {
dbName, fileType := ParseFilename(name)
db := fs.store.DBByName(dbName)
if db == nil {
return fuse.ENOENT
}
attr, err := fs.dbFileAttr(db, fileType)
if os.IsNotExist(err) {
return fuse.ENOENT
} else if err != nil {
log.Printf("fuse: lookup(): attr error: %s", err)
return fuse.EIO
}
out.NodeId = attr.Ino
out.Generation = 1
out.Attr = attr
return fuse.OK
}
func (fs *FileSystem) GetAttr(cancel <-chan struct{}, input *fuse.GetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
switch input.NodeId {
case RootNodeID:
return fs.getAttrRoot(cancel, input, out)
case PrimaryNodeID:
return fs.getAttrPrimary(cancel, input, out)
default:
return fs.getAttrDBFile(cancel, input, out)
}
}
func (fs *FileSystem) getAttrRoot(cancel <-chan struct{}, input *fuse.GetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
out.Attr = fuse.Attr{
Ino: RootNodeID,
Mode: 040777,
Nlink: 1,
Blksize: 4096,
Owner: fuse.Owner{
Uid: uint32(fs.Uid),
Gid: uint32(fs.Gid),
},
}
return fuse.OK
}
func (fs *FileSystem) getAttrPrimary(cancel <-chan struct{}, input *fuse.GetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
attr, err := fs.primaryAttr()
if err != nil {
return toErrno(err)
}
out.Attr = attr
return fuse.OK
}
func (fs *FileSystem) getAttrDBFile(cancel <-chan struct{}, input *fuse.GetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
dbID, fileType, err := ParseInode(input.NodeId)
if err != nil {
log.Printf("fuse: getattr(): cannot parse inode: %d", input.NodeId)
return fuse.ENOENT
}
db := fs.store.DB(dbID)
if db == nil {
return fuse.ENOENT
}
attr, err := fs.dbFileAttr(db, fileType)
if os.IsNotExist(err) {
return fuse.ENOENT
} else if err != nil {
log.Printf("fuse: getattr(): attr error: %s", err)
return fuse.EIO
}
out.Attr = attr
return fuse.OK
}
func (fs *FileSystem) Open(cancel <-chan struct{}, input *fuse.OpenIn, out *fuse.OpenOut) (code fuse.Status) {
switch input.NodeId {
case PrimaryNodeID:
return fs.openPrimary(cancel, input, out)
default:
return fs.openDBFile(cancel, input, out)
}
}
func (fs *FileSystem) openPrimary(cancel <-chan struct{}, input *fuse.OpenIn, out *fuse.OpenOut) (code fuse.Status) {
// fh := fs.NewFileHandle(db, fileType, f)
// out.Fh = fh.ID()
out.OpenFlags = input.Flags
return fuse.OK
}
func (fs *FileSystem) openDBFile(cancel <-chan struct{}, input *fuse.OpenIn, out *fuse.OpenOut) (code fuse.Status) {
dbID, fileType, err := ParseInode(input.NodeId)
if err != nil {
log.Printf("fuse: open(): cannot parse inode: %d", input.NodeId)
return fuse.ENOENT
}
db := fs.store.DB(dbID)
if db == nil {
return fuse.ENOENT
}
f, err := os.OpenFile(filepath.Join(db.Path(), FileTypeFilename(fileType)), int(input.Flags), os.FileMode(input.Mode))
if err != nil {
log.Printf("fuse: open(): cannot open file: %s", err)
return toErrno(err)
}
fh := fs.NewFileHandle(db, fileType, f)
out.Fh = fh.ID()
out.OpenFlags = input.Flags
return fuse.OK
}
func (fs *FileSystem) Unlink(cancel <-chan struct{}, input *fuse.InHeader, name string) (code fuse.Status) {
// Ensure command is only performed on top-level directory.
if input.NodeId != RootNodeID {
log.Printf("fuse: unlink(): invalid parent inode: %d", input.NodeId)
return fuse.EINVAL
}
dbName, fileType := ParseFilename(name)
switch fileType {
case litefs.FileTypeDatabase:
return fs.unlinkDatabase(cancel, input, dbName)
case litefs.FileTypeJournal:
return fs.unlinkJournal(cancel, input, dbName)
case litefs.FileTypeWAL:
return fs.unlinkWAL(cancel, input, dbName)
case litefs.FileTypeSHM:
return fs.unlinkSHM(cancel, input, dbName)
default:
return fuse.EINVAL
}
}
func (fs *FileSystem) unlinkDatabase(cancel <-chan struct{}, input *fuse.InHeader, dbName string) (code fuse.Status) {
return fuse.ENOSYS // TODO: Delete database
}
func (fs *FileSystem) unlinkJournal(cancel <-chan struct{}, input *fuse.InHeader, dbName string) (code fuse.Status) {
db := fs.store.DBByName(dbName)
if db == nil {
return fuse.ENOENT
}
if err := db.CommitJournal(litefs.JournalModeDelete); err != nil {
log.Printf("fuse: unlink(): cannot commit journal: %s", err)
return toErrno(err)
}
return fuse.OK
}
func (fs *FileSystem) unlinkWAL(cancel <-chan struct{}, input *fuse.InHeader, dbName string) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) unlinkSHM(cancel <-chan struct{}, input *fuse.InHeader, dbName string) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) Create(cancel <-chan struct{}, input *fuse.CreateIn, name string, out *fuse.CreateOut) (code fuse.Status) {
if input.NodeId != RootNodeID {
log.Printf("fuse: lookup(): invalid inode: %d", input.NodeId)
return fuse.EINVAL
}
dbName, fileType := ParseFilename(name)
switch fileType {
case litefs.FileTypeDatabase:
return fs.createDatabase(cancel, input, dbName, out)
case litefs.FileTypeJournal:
return fs.createJournal(cancel, input, dbName, out)
case litefs.FileTypeWAL:
return fs.createWAL(cancel, input, dbName, out)
case litefs.FileTypeSHM:
return fs.createSHM(cancel, input, dbName, out)
default:
return fuse.EINVAL
}
}
func (fs *FileSystem) createDatabase(cancel <-chan struct{}, input *fuse.CreateIn, dbName string, out *fuse.CreateOut) (code fuse.Status) {
db, file, err := fs.store.CreateDB(dbName)
if err == litefs.ErrDatabaseExists {
return fuse.Status(syscall.EEXIST)
} else if err != nil {
log.Printf("fuse: create(): cannot create database: %s", err)
return toErrno(err)
}
attr, err := fs.dbFileAttr(db, litefs.FileTypeDatabase)
if err != nil {
log.Printf("fuse: create(): cannot stat database file: %s", err)
return toErrno(err)
}
ino := fs.dbIno(db.ID(), litefs.FileTypeDatabase)
fh := fs.NewFileHandle(db, litefs.FileTypeDatabase, file)
out.Fh = fh.ID()
out.NodeId = ino
out.Attr = attr
return fuse.OK
}
func (fs *FileSystem) createJournal(cancel <-chan struct{}, input *fuse.CreateIn, dbName string, out *fuse.CreateOut) (code fuse.Status) {
db := fs.store.DBByName(dbName)
if db == nil {
log.Printf("fuse: create(): cannot create journal, database not found: %s", dbName)
return fuse.Status(syscall.ENOENT)
}
file, err := db.CreateJournal()
if err != nil {
log.Printf("fuse: create(): cannot create journal: %s", err)
return toErrno(err)
}
attr, err := fs.dbFileAttr(db, litefs.FileTypeJournal)
if err != nil {
log.Printf("fuse: create(): cannot stat journal file: %s", err)
return toErrno(err)
}
ino := fs.dbIno(db.ID(), litefs.FileTypeJournal)
fh := fs.NewFileHandle(db, litefs.FileTypeJournal, file)
out.Fh = fh.ID()
out.NodeId = ino
out.Attr = attr
return fuse.OK
}
func (fs *FileSystem) createWAL(cancel <-chan struct{}, input *fuse.CreateIn, dbName string, out *fuse.CreateOut) (code fuse.Status) {
return fuse.ENOSYS // TODO
}
func (fs *FileSystem) createSHM(cancel <-chan struct{}, input *fuse.CreateIn, dbName string, out *fuse.CreateOut) (code fuse.Status) {
return fuse.ENOSYS // TODO
}
func (fs *FileSystem) Read(cancel <-chan struct{}, input *fuse.ReadIn, buf []byte) (fuse.ReadResult, fuse.Status) {
switch input.NodeId {
case PrimaryNodeID:
return fs.readPrimary(cancel, input, buf)
default:
return fs.readDBFile(cancel, input, buf)
}
}
func (fs *FileSystem) readPrimary(cancel <-chan struct{}, input *fuse.ReadIn, buf []byte) (fuse.ReadResult, fuse.Status) {
primaryURL := fs.store.PrimaryURL()
return fuse.ReadResultData([]byte(primaryURL + "\n")), fuse.OK
}
func (fs *FileSystem) readDBFile(cancel <-chan struct{}, input *fuse.ReadIn, buf []byte) (fuse.ReadResult, fuse.Status) {
fh := fs.FileHandle(input.Fh)
if fh == nil {
log.Printf("fuse: read(): bad file handle: %d", input.Fh)
return nil, fuse.EBADF
}
//n, err := fh.File().ReadAt(buf, int64(input.Offset))
//if err == io.EOF {
// return fuse.ReadResultData(nil), fuse.OK
//} else if err != nil {
// log.Printf("fuse: read(): cannot read: %s", err)
// return nil, fuse.EIO
//}
//return fuse.ReadResultData(buf[:n]), fuse.OK
return fuse.ReadResultFd(fh.File().Fd(), int64(input.Offset), int(input.Size)), fuse.OK
}
func (fs *FileSystem) Write(cancel <-chan struct{}, input *fuse.WriteIn, data []byte) (written uint32, code fuse.Status) {
fh := fs.FileHandle(input.Fh)
if fh == nil {
log.Printf("fuse: write(): invalid file handle: %d", input.Fh)
return 0, fuse.EBADF
}
switch fh.FileType() {
case litefs.FileTypeDatabase:
return fs.writeDatabase(cancel, fh, input, data)
case litefs.FileTypeJournal:
return fs.writeJournal(cancel, fh, input, data)
case litefs.FileTypeWAL:
return fs.writeWAL(cancel, fh, input, data)
case litefs.FileTypeSHM:
return fs.writeSHM(cancel, fh, input, data)
default:
log.Printf("fuse: write(): file handle has invalid file type: %d", fh.FileType())
return 0, fuse.EINVAL
}
}
func (fs *FileSystem) writeDatabase(cancel <-chan struct{}, fh *FileHandle, input *fuse.WriteIn, data []byte) (written uint32, code fuse.Status) {
if err := fh.DB().WriteDatabase(fh.File(), data, int64(input.Offset)); err != nil {
log.Printf("fuse: write(): database error: %s", err)
return 0, toErrno(err)
}
return uint32(len(data)), fuse.OK
}
func (fs *FileSystem) writeJournal(cancel <-chan struct{}, fh *FileHandle, input *fuse.WriteIn, data []byte) (written uint32, code fuse.Status) {
if err := fh.DB().WriteJournal(fh.File(), data, int64(input.Offset)); err != nil {
log.Printf("fuse: write(): journal error: %s", err)
return 0, toErrno(err)
}
return uint32(len(data)), fuse.OK
}
func (fs *FileSystem) writeWAL(cancel <-chan struct{}, fh *FileHandle, input *fuse.WriteIn, data []byte) (written uint32, code fuse.Status) {
return 0, fuse.ENOSYS // TODO
}
func (fs *FileSystem) writeSHM(cancel <-chan struct{}, fh *FileHandle, input *fuse.WriteIn, data []byte) (written uint32, code fuse.Status) {
return 0, fuse.ENOSYS // TODO
}
func (fs *FileSystem) Flush(cancel <-chan struct{}, input *fuse.FlushIn) fuse.Status {
// Ignore if we aren't using a file descriptor.
if input.Fh == 0 {
return fuse.OK
}
fh := fs.FileHandle(input.Fh)
if fh == nil {
log.Printf("fuse: flush(): bad file handle: %d", input.Fh)
return fuse.EBADF
}
return fuse.OK
}
func (fs *FileSystem) Release(cancel <-chan struct{}, input *fuse.ReleaseIn) {
fs.mu.Lock()
defer fs.mu.Unlock()
fh := fs.fileHandles[input.Fh]
if fh == nil {
return
}
if err := fh.File().Close(); err != nil {
log.Printf("fuse: release(): %s", err)
}
delete(fs.fileHandles, input.Fh)
}
func (fs *FileSystem) Fsync(cancel <-chan struct{}, input *fuse.FsyncIn) (code fuse.Status) {
fh := fs.FileHandle(input.Fh)
if fh == nil {
log.Printf("fuse: fsync(): bad file handle: %d", input.Fh)
return fuse.EBADF
}
if err := fh.File().Sync(); err != nil {
log.Printf("fuse: fsync(): cannot sync: %s", err)
return toErrno(err)
}
return fuse.OK
}
func (fs *FileSystem) GetLk(cancel <-chan struct{}, in *fuse.LkIn, out *fuse.LkOut) (code fuse.Status) {
fh := fs.FileHandle(in.Fh)
if fh == nil {
log.Printf("fuse: setlk(): bad file handle: %d", in.Fh)
return fuse.EBADF
}
// If a lock could not be obtained, return a write lock in its place.
// This isn't technically correct but it's good enough for SQLite usage.
if ok, err := fh.GetLk(in.Lk.Typ, litefs.ParseLockRange(in.Lk.Start, in.Lk.End)); err != nil {
log.Printf("fuse: getlk(): error: %s", err)
return fuse.ENOSYS
} else if !ok {
out.Lk = fuse.FileLock{
Start: in.Lk.Start,
End: in.Lk.End,
Typ: syscall.F_WRLCK,
}
return fuse.OK
}
// If lock could be obtained, return UNLCK.
out.Lk = fuse.FileLock{
Start: in.Lk.Start,
End: in.Lk.End,
Typ: syscall.F_UNLCK,
}
return fuse.OK
}
func (fs *FileSystem) SetLk(cancel <-chan struct{}, in *fuse.LkIn) (code fuse.Status) {
fh := fs.FileHandle(in.Fh)
if fh == nil {
log.Printf("fuse: setlk(): bad file handle: %d", in.Fh)
return fuse.EBADF
}
if ok, err := fh.SetLk(in.Lk.Typ, litefs.ParseLockRange(in.Lk.Start, in.Lk.End)); err != nil {
log.Printf("fuse: setlk(): error: %s", err)
return fuse.ENOSYS
} else if !ok {
return fuse.EAGAIN
}
return fuse.OK
}
func (fs *FileSystem) SetLkw(cancel <-chan struct{}, in *fuse.LkIn) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) OpenDir(cancel <-chan struct{}, input *fuse.OpenIn, out *fuse.OpenOut) (status fuse.Status) {
out.Fh = fs.NewDirHandle().ID()
out.OpenFlags = input.Flags
return fuse.OK
}
func (fs *FileSystem) ReadDirPlus(cancel <-chan struct{}, input *fuse.ReadIn, out *fuse.DirEntryList) fuse.Status {
h := fs.DirHandle(input.Fh)
if h == nil {
log.Printf("fuse: readdirplus(): bad file handle: %d", input.Fh)
return fuse.EBADF
}
// Build hidden, fixed entries list first.
var entries []fuse.DirEntry
if primaryURL := fs.store.PrimaryURL(); primaryURL != "" {
entries = append(entries, fuse.DirEntry{
Name: PrimaryFilename,
Ino: PrimaryNodeID,
Mode: 0100444,
})
}
// Write out entries until we fill the buffer.
var index int
for _, entry := range entries {
if index < h.offset {
continue
}
if out.AddDirLookupEntry(entry) == nil {
return fuse.OK
}
index++
h.offset++
}
// Read & sort list of databases from the store.
dbs := fs.store.DBs()
sort.Slice(dbs, func(i, j int) bool { return dbs[i].Name() < dbs[j].Name() })
// Iterate over databases starting from the offset.
for _, db := range dbs {
if index < h.offset {
continue
}
// Write the entry to the buffer; if nil returned then buffer is full.
if out.AddDirLookupEntry(fuse.DirEntry{
Name: db.Name(),
Ino: fs.dbIno(db.ID(), litefs.FileTypeDatabase),
Mode: 0100666},
) == nil {
break
}
index++
h.offset++
}
return fuse.OK
}
func (fs *FileSystem) ReadDir(cancel <-chan struct{}, input *fuse.ReadIn, l *fuse.DirEntryList) fuse.Status {
return fuse.ENOSYS
}
func (fs *FileSystem) ReleaseDir(input *fuse.ReleaseIn) {
fs.mu.Lock()
defer fs.mu.Unlock()
delete(fs.dirHandles, input.Fh)
}
func (fs *FileSystem) FsyncDir(cancel <-chan struct{}, input *fuse.FsyncIn) (code fuse.Status) {
return fuse.OK
}
func (fs *FileSystem) Fallocate(cancel <-chan struct{}, in *fuse.FallocateIn) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) CopyFileRange(cancel <-chan struct{}, input *fuse.CopyFileRangeIn) (written uint32, code fuse.Status) {
return 0, fuse.ENOSYS
}
func (fs *FileSystem) Lseek(cancel <-chan struct{}, in *fuse.LseekIn, out *fuse.LseekOut) fuse.Status {
return fuse.ENOSYS
}
func (fs *FileSystem) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
fh := fs.FileHandle(input.Fh)
if fh == nil {
log.Printf("fuse: setattr(): bad file handle: %d", input.Fh)
return fuse.EBADF
}
switch fileType := fh.FileType(); fileType {
case litefs.FileTypeDatabase:
return fs.setAttrDatabase(cancel, input, fh, out)
case litefs.FileTypeJournal:
return fs.setAttrJournal(cancel, input, fh, out)
case litefs.FileTypeWAL:
return fs.setAttrWAL(cancel, input, fh, out)
case litefs.FileTypeSHM:
return fs.setAttrSHM(cancel, input, fh, out)
default:
log.Printf("fuse: setattr(): invalid file handle type: %d", fileType)
return fuse.ENOENT
}
}
func (fs *FileSystem) setAttrDatabase(cancel <-chan struct{}, input *fuse.SetAttrIn, fh *FileHandle, out *fuse.AttrOut) (code fuse.Status) {
return fuse.EPERM
}
func (fs *FileSystem) setAttrJournal(cancel <-chan struct{}, input *fuse.SetAttrIn, fh *FileHandle, out *fuse.AttrOut) (code fuse.Status) {
if input.Size != 0 {
log.Printf("fuse: setattr(): size must be zero when truncating journal: sz=%d", input.Size)
return fuse.EPERM
}
if err := fh.DB().CommitJournal(litefs.JournalModeTruncate); err != nil {
log.Printf("fuse: setattr(): cannot truncate journal: %s", err)
return fuse.EIO
}
attr, err := fs.dbFileAttr(fh.DB(), fh.FileType())
if os.IsNotExist(err) {
return fuse.ENOENT
} else if err != nil {
log.Printf("fuse: setattr(): attr error: %s", err)
return fuse.EIO
}
out.Attr = attr
return fuse.OK
}
func (fs *FileSystem) setAttrWAL(cancel <-chan struct{}, input *fuse.SetAttrIn, fh *FileHandle, out *fuse.AttrOut) (code fuse.Status) {
return fuse.EPERM
}
func (fs *FileSystem) setAttrSHM(cancel <-chan struct{}, input *fuse.SetAttrIn, fh *FileHandle, out *fuse.AttrOut) (code fuse.Status) {
return fuse.EPERM
}
func (fs *FileSystem) Readlink(cancel <-chan struct{}, header *fuse.InHeader) (out []byte, code fuse.Status) {
return nil, fuse.ENOSYS
}
func (fs *FileSystem) Mknod(cancel <-chan struct{}, input *fuse.MknodIn, name string, out *fuse.EntryOut) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) Mkdir(cancel <-chan struct{}, input *fuse.MkdirIn, name string, out *fuse.EntryOut) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) Rmdir(cancel <-chan struct{}, header *fuse.InHeader, name string) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) Symlink(cancel <-chan struct{}, header *fuse.InHeader, pointedTo string, linkName string, out *fuse.EntryOut) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) Rename(cancel <-chan struct{}, input *fuse.RenameIn, oldName string, newName string) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) Link(cancel <-chan struct{}, input *fuse.LinkIn, name string, out *fuse.EntryOut) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) GetXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr string, dest []byte) (size uint32, code fuse.Status) {
return 0, fuse.ENOSYS
}
func (fs *FileSystem) SetXAttr(cancel <-chan struct{}, input *fuse.SetXAttrIn, attr string, data []byte) fuse.Status {
return fuse.ENOSYS
}
// ListXAttr lists extended attributes as '\0' delimited byte
// slice, and return the number of bytes. If the buffer is too
// small, return ERANGE, with the required buffer size.
func (fs *FileSystem) ListXAttr(cancel <-chan struct{}, header *fuse.InHeader, dest []byte) (n uint32, code fuse.Status) {
return 0, fuse.ENOSYS
}
func (fs *FileSystem) RemoveXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr string) fuse.Status {
return fuse.ENOSYS
}
func (fs *FileSystem) Access(cancel <-chan struct{}, input *fuse.AccessIn) (code fuse.Status) {
return fuse.ENOSYS
}
func (fs *FileSystem) StatFs(cancel <-chan struct{}, header *fuse.InHeader, out *fuse.StatfsOut) fuse.Status {
return fuse.ENOSYS
}
func (fs *FileSystem) Forget(nodeID, nlookup uint64) {}
// dbIno returns the inode for a given database's file.
func (fs FileSystem) dbIno(dbID uint32, fileType litefs.FileType) uint64 {
return (uint64(dbID) << 4) | FileTypeInode(fileType)
}
// dbFileAttr returns an attribute for a given database file.
func (fs FileSystem) dbFileAttr(db *litefs.DB, fileType litefs.FileType) (fuse.Attr, error) {
// Look up stats on the internal data file. May return "not found".
fi, err := os.Stat(filepath.Join(db.Path(), FileTypeFilename(fileType)))
if err != nil {
return fuse.Attr{}, err
}
// Mask mode if it is not writable.
mode := uint32(0100666)
if !fs.store.IsPrimary() {
mode = uint32(0100444)
}
t := time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
return fuse.Attr{
Ino: fs.dbIno(db.ID(), fileType),
Size: uint64(fi.Size()),
Atime: uint64(t.Unix()),
Mtime: uint64(t.Unix()),
Ctime: uint64(t.Unix()),
Mode: mode,
Nlink: 1,
Blksize: 4096,
Owner: fuse.Owner{
Uid: uint32(fs.Uid),
Gid: uint32(fs.Gid),
},
}, nil
}
func (fs FileSystem) primaryAttr() (fuse.Attr, error) {
primaryURL := fs.store.PrimaryURL()
if primaryURL == "" {
return fuse.Attr{}, os.ErrNotExist
}
t := time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
return fuse.Attr{
Ino: PrimaryNodeID,
Size: uint64(len(primaryURL) + 1),
Atime: uint64(t.Unix()),
Mtime: uint64(t.Unix()),
Ctime: uint64(t.Unix()),
Mode: 100444,
Nlink: 1,
Blksize: 4096,
Owner: fuse.Owner{
Uid: uint32(fs.Uid),
Gid: uint32(fs.Gid),
},
}, nil
}
// NewFileHandle returns a new file handle associated with a database file.
func (fs *FileSystem) NewFileHandle(db *litefs.DB, fileType litefs.FileType, file *os.File) *FileHandle {
fs.mu.Lock()
defer fs.mu.Unlock()
fh := NewFileHandle(fs.nextHandleID, db, fileType, file)
fs.nextHandleID++
fs.fileHandles[fh.ID()] = fh
return fh
}
// FileHandle returns a file handle by ID.
func (fs *FileSystem) FileHandle(id uint64) *FileHandle {
fs.mu.Lock()
defer fs.mu.Unlock()
return fs.fileHandles[id]
}
// NewDirHandle returns a new directory handle associated with the root directory.
func (fs *FileSystem) NewDirHandle() *DirHandle {
fs.mu.Lock()
defer fs.mu.Unlock()
h := NewDirHandle(fs.nextHandleID)
fs.nextHandleID++
fs.dirHandles[h.ID()] = h
return h
}
// DirHandle returns a directory handle by ID.
func (fs *FileSystem) DirHandle(id uint64) *DirHandle {
fs.mu.Lock()
defer fs.mu.Unlock()
return fs.dirHandles[id]
}
// FileHandle represents a file system handle that points to a database file.
type FileHandle struct {
id uint64
db *litefs.DB
fileType litefs.FileType
file *os.File
// SQLite locks held
pendingGuard *litefs.RWMutexGuard
sharedGuard *litefs.RWMutexGuard
reservedGuard *litefs.RWMutexGuard
}
// NewFileHandle returns a new instance of FileHandle.
func NewFileHandle(id uint64, db *litefs.DB, fileType litefs.FileType, file *os.File) *FileHandle {
return &FileHandle{
id: id,
db: db,
fileType: fileType,
file: file,
}
}
// ID returns the file handle identifier.
func (fh *FileHandle) ID() uint64 { return fh.id }
// DB returns the database associated with the file handle.
func (fh *FileHandle) DB() *litefs.DB { return fh.db }
// FileType return the type of database file the handle is associated with.
func (fh *FileHandle) FileType() litefs.FileType { return fh.fileType }
// File return the underlying file reference.
func (fh *FileHandle) File() *os.File { return fh.file }
// ID returns the file handle identifier.
func (fh *FileHandle) Close() (err error) {
if fh.file != nil {
return fh.file.Close()
}
return nil
}
// mutexAndGuardRefByLockType returns the mutex and, if held, a guard for that mutex.
func (fh *FileHandle) mutexAndGuardRefByLockType(lockType litefs.LockType) (mu *litefs.RWMutex, guardRef **litefs.RWMutexGuard, err error) {
switch lockType {
case litefs.LockTypePending:
return fh.db.PendingLock(), &fh.pendingGuard, nil
case litefs.LockTypeReserved:
return fh.db.ReservedLock(), &fh.reservedGuard, nil
case litefs.LockTypeShared:
return fh.db.SharedLock(), &fh.sharedGuard, nil
default:
return nil, nil, fmt.Errorf("invalid lock type: %d", lockType)
}
}
// Getlk returns true if one or more locks could be obtained.
// This function does not actually acquire the locks.
func (fh *FileHandle) GetLk(typ uint32, lockTypes []litefs.LockType) (bool, error) {
for _, lockType := range lockTypes {
if ok, err := fh.getLk(typ, lockType); err != nil {
return false, err
} else if !ok {
return false, nil
}
}
return true, nil
}
func (fh *FileHandle) getLk(typ uint32, lockType litefs.LockType) (bool, error) {
// TODO: Hold file handle lock
mu, guardRef, err := fh.mutexAndGuardRefByLockType(lockType)
if err != nil {
return false, err
}
if *guardRef != nil {
switch typ {
case syscall.F_UNLCK:
return true, nil
case syscall.F_RDLCK:
return true, nil
case syscall.F_WRLCK:
return (*guardRef).CanLock(), nil
default:
panic(fmt.Sprintf("invalid posix lock type: %d", typ))
}
}
switch typ {
case syscall.F_UNLCK:
return true, nil
case syscall.F_RDLCK:
return mu.CanRLock(), nil
case syscall.F_WRLCK:
return mu.CanLock(), nil
default:
panic(fmt.Sprintf("invalid posix lock type: %d", typ))
}
}
// SetLk transition a lock to a new state. Only UNLCK can be performed against
// multiple locks. Returns false if not all locks can be transitioned.
func (fh *FileHandle) SetLk(typ uint32, lockTypes []litefs.LockType) (bool, error) {
if len(lockTypes) == 0 {
return false, fmt.Errorf("no locks")
}
// Handle unlock separately since it can handle multiple locks at once.
if typ == syscall.F_UNLCK {
return true, fh.setUnlk(lockTypes)
} else if len(lockTypes) > 1 {
return false, fmt.Errorf("cannot acquire multiple locks at once")
}
lockType := lockTypes[0]
// TODO: Hold file handle lock for rest of function.
mu, guardRef, err := fh.mutexAndGuardRefByLockType(lockType)
if err != nil {
return false, err
}
if *guardRef != nil {
switch typ {
case syscall.F_RDLCK:
(*guardRef).RLock()
return true, nil
case syscall.F_WRLCK:
return (*guardRef).TryLock(), nil
default:
panic(fmt.Sprintf("invalid posix lock type: %d", typ))
}
}
switch typ {
case syscall.F_RDLCK: