-
Notifications
You must be signed in to change notification settings - Fork 204
/
libfuse2_handler.go
1091 lines (907 loc) · 33.6 KB
/
libfuse2_handler.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
//go:build fuse2
// +build fuse2
/*
_____ _____ _____ ____ ______ _____ ------
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| --- | | | | |-----| |---- | | |-----| |----- ------
| | | | | | | | | | | | |
| ____| |_____ | ____| | ____| | |_____| _____| |_____ |_____
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright © 2020-2024 Microsoft Corporation. All rights reserved.
Author : <blobfusedev@microsoft.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
package libfuse
// CFLAGS: compile time flags -D object file creation. D= Define
// LFLAGS: loader flags link library -l binary file. l=link -ldl is for the extension to dynamically link
// #cgo CFLAGS: -DFUSE_USE_VERSION=29 -D_FILE_OFFSET_BITS=64 -D__FUSE2__
// #cgo LDFLAGS: -lfuse -ldl
// #include "libfuse_wrapper.h"
// #include "extension_handler.h"
import "C"
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"syscall"
"unsafe"
"github.com/Azure/azure-storage-fuse/v2/common"
"github.com/Azure/azure-storage-fuse/v2/common/log"
"github.com/Azure/azure-storage-fuse/v2/internal"
"github.com/Azure/azure-storage-fuse/v2/internal/handlemap"
"github.com/Azure/azure-storage-fuse/v2/internal/stats_manager"
)
/* --- IMPORTANT NOTE ---
In below code lot of places we are doing this sort of conversions:
- fi.fh = C.ulong(uintptr(unsafe.Pointer(handle)))
- handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fi.fh)))
To open/create calls we need to return back a handle to libfuse which shall be an integer value
As in blobfuse we maintain handle as an object, instead of returning back a running integer value as handle
we are converting back the pointer to our handle object to an integer value and sending it to libfuse.
When read/write/flush/close call comes libfuse will supply this handle value back to blobfuse.
In those calls we will convert integer value back to a pointer and get our valid handle object back for that file.
*/
const (
C_ENOENT = int(-C.ENOENT)
C_EIO = int(-C.EIO)
C_EACCES = int(-C.EACCES)
)
// Note: libfuse prepends "/" to the path.
// trimFusePath trims the first character from the path provided by libfuse
func trimFusePath(path *C.char) string {
if path == nil {
return ""
}
str := C.GoString(path)
if str != "" {
return str[1:]
}
return str
}
var fuse_opts C.fuse_options_t // nolint
// convertConfig converts the config options from Go to C
func (lf *Libfuse) convertConfig() *C.fuse_options_t {
fuse_opts := &C.fuse_options_t{}
// Note: C strings are allocated in the heap using malloc. Call C.free when string is no longer needed.
fuse_opts.mount_path = C.CString(lf.mountPath)
fuse_opts.uid = C.uid_t(lf.ownerUID)
fuse_opts.gid = C.gid_t(lf.ownerGID)
fuse_opts.permissions = C.uint(lf.filePermission)
fuse_opts.entry_expiry = C.int(lf.entryExpiration)
fuse_opts.attr_expiry = C.int(lf.attributeExpiration)
fuse_opts.negative_expiry = C.int(lf.negativeTimeout)
fuse_opts.readonly = C.bool(lf.readOnly)
fuse_opts.allow_other = C.bool(lf.allowOther)
fuse_opts.allow_root = C.bool(lf.allowRoot)
fuse_opts.trace_enable = C.bool(lf.traceEnable)
fuse_opts.non_empty = C.bool(lf.nonEmptyMount)
fuse_opts.umask = C.int(lf.umask)
return fuse_opts
}
// initFuse initializes the fuse library by registering callbacks, parsing arguments and mounting the directory
func (lf *Libfuse) initFuse() error {
log.Trace("Libfuse::initFuse : Initializing FUSE")
operations := C.fuse_operations_t{}
if lf.extensionPath != "" {
log.Trace("Libfuse::InitFuse : Going for extension mouting [%s]", lf.extensionPath)
// User has given an extension so we need to register it to fuse
// and then register ourself to it
extensionPath := C.CString(lf.extensionPath)
defer C.free(unsafe.Pointer(extensionPath))
// Load the library
errc := C.load_library(extensionPath)
if errc != 0 {
log.Err("Libfuse::InitFuse : Failed to load extension err code %d", errc)
return errors.New("failed to load extension")
}
log.Trace("Libfuse::InitFuse : Extension loaded")
// Get extension callback table
errc = C.get_extension_callbacks(&operations)
if errc != 0 {
C.unload_library()
log.Err("Libfuse::InitFuse : Failed to get callback table from extension. error code %d", errc)
return errors.New("failed to get callback table from extension")
}
log.Trace("Libfuse::InitFuse : Extension callback retrieved")
// Get our callback table
my_operations := C.fuse_operations_t{}
C.populate_callbacks(&my_operations)
// Send our callback table to the extension
errc = C.register_callback_to_extension(&my_operations)
if errc != 0 {
C.unload_library()
log.Err("Libfuse::InitFuse : Failed to register callback table to extension. error code %d", errc)
return errors.New("failed to register callback table to extension")
}
log.Trace("Libfuse::InitFuse : Callbacks registered to extension")
} else {
// Populate our methods to be registered to libfuse
log.Trace("Libfuse::initFuse : Registering fuse callbacks")
C.populate_callbacks(&operations)
}
log.Trace("Libfuse::initFuse : Populating fuse arguments")
fuse_opts := lf.convertConfig()
var args C.fuse_args_t
fuse_opts, ret := populateFuseArgs(fuse_opts, &args)
if ret != 0 {
log.Err("Libfuse::initFuse : Failed to parse fuse arguments")
return errors.New("failed to parse fuse arguments")
}
// Note: C strings are allocated in the heap using malloc. Calling C.free to release the mount path since it is no longer needed.
C.free(unsafe.Pointer(fuse_opts.mount_path))
log.Info("Libfuse::initFuse : Mounting with fuse2 library")
ret = C.start_fuse(&args, &operations)
if ret != 0 {
log.Err("Libfuse::initFuse : failed to mount fuse")
return errors.New("failed to mount fuse")
}
return nil
}
// populateFuseArgs populates libfuse args before we call start_fuse
func populateFuseArgs(opts *C.fuse_options_t, args *C.fuse_args_t) (*C.fuse_options_t, C.int) {
log.Trace("Libfuse::populateFuseArgs")
if args == nil {
return nil, 1
}
args.argc = 0
args.allocated = 1
arguments := make([]string, 0)
options := fmt.Sprintf("entry_timeout=%d,attr_timeout=%d,negative_timeout=%d",
opts.entry_expiry,
opts.attr_expiry,
opts.negative_expiry)
if opts.allow_other {
options += ",allow_other"
}
if opts.allow_root {
options += ",allow_root"
}
if opts.non_empty {
options += ",nonempty"
}
if opts.readonly {
options += ",ro"
}
if opts.umask != 0 {
options += fmt.Sprintf(",umask=%04d", opts.umask)
}
// direct_io option is used to bypass the kernel cache. It disables the use of
// page cache (file content cache) in the kernel for the filesystem.
if fuseFS.directIO {
options += ",direct_io"
} else {
options += ",kernel_cache"
}
// Why we pass -f
// CGo is not very good with handling forks - so if the user wants to run blobfuse in the
// background we fork on mount in GO (mount.go) and we just always force libfuse to mount in foreground
arguments = append(arguments, "blobfuse2",
C.GoString(opts.mount_path),
"-o", options,
"-f", "-ofsname=blobfuse2")
if opts.trace_enable {
arguments = append(arguments, "-d")
}
for _, a := range arguments {
log.Debug("Libfuse::populateFuseArgs : opts : %s", a)
arg := C.CString(a)
defer C.free(unsafe.Pointer(arg))
err := C.fuse_opt_add_arg(args, arg)
if err != 0 {
return nil, err
}
}
return opts, 0
}
// destroyFuse is a no-op
func (lf *Libfuse) destroyFuse() error {
log.Trace("Libfuse::destroyFuse : Destroying FUSE")
return nil
}
//export libfuse2_init
func libfuse2_init(conn *C.fuse_conn_info_t) (res unsafe.Pointer) {
log.Trace("Libfuse::libfuse2_init : init")
log.Info("Libfuse::NotifyMountToParent : Notifying parent for successful mount")
if err := common.NotifyMountToParent(); err != nil {
log.Err("Libfuse::NotifyMountToParent : Failed to notify parent, error: [%v]", err)
}
C.populate_uid_gid()
log.Info("Libfuse::libfuse2_init : Kernel Caps : %d", conn.capable)
if (conn.capable & C.FUSE_CAP_ASYNC_READ) != 0 {
log.Info("Libfuse::libfuse2_init : Enable Capability : FUSE_CAP_ASYNC_READ")
conn.want |= C.FUSE_CAP_ASYNC_READ
}
if (conn.capable & C.FUSE_CAP_BIG_WRITES) != 0 {
log.Info("Libfuse::libfuse2_init : Enable Capability : FUSE_CAP_BIG_WRITES")
conn.want |= C.FUSE_CAP_BIG_WRITES
}
if (conn.capable & C.FUSE_CAP_SPLICE_WRITE) != 0 {
// While writing to fuse device let libfuse collate the data and write big chunks
log.Info("Libfuse::libfuse2_init : Enable Capability : FUSE_CAP_SPLICE_WRITE")
conn.want |= C.FUSE_CAP_SPLICE_WRITE
}
// Max background thread on the fuse layer for high parallelism
conn.max_background = C.uint(fuseFS.maxFuseThreads)
// While reading a file let kernel do readahed for better perf
conn.max_readahead = (4 * 1024 * 1024)
return nil
}
//export libfuse_destroy
func libfuse_destroy(data unsafe.Pointer) {
log.Trace("Libfuse::libfuse2_destroy : destroy")
}
func (lf *Libfuse) fillStat(attr *internal.ObjAttr, stbuf *C.stat_t) {
(*stbuf).st_uid = C.uint(lf.ownerUID)
(*stbuf).st_gid = C.uint(lf.ownerGID)
(*stbuf).st_nlink = 1
(*stbuf).st_size = C.long(attr.Size)
// Populate mode
// Backing storage implementation has support for mode.
if !attr.IsModeDefault() {
(*stbuf).st_mode = C.uint(attr.Mode) & 0xffffffff
} else {
if attr.IsDir() {
(*stbuf).st_mode = C.uint(lf.dirPermission) & 0xffffffff
} else {
(*stbuf).st_mode = C.uint(lf.filePermission) & 0xffffffff
}
}
if attr.IsDir() {
(*stbuf).st_nlink = 2
(*stbuf).st_size = 4096
(*stbuf).st_mode |= C.S_IFDIR
} else if attr.IsSymlink() {
(*stbuf).st_mode |= C.S_IFLNK
} else {
(*stbuf).st_mode |= C.S_IFREG
}
(*stbuf).st_atim.tv_sec = C.long(attr.Atime.Unix())
(*stbuf).st_atim.tv_nsec = 0
(*stbuf).st_ctim.tv_sec = C.long(attr.Ctime.Unix())
(*stbuf).st_ctim.tv_nsec = 0
(*stbuf).st_mtim.tv_sec = C.long(attr.Mtime.Unix())
(*stbuf).st_mtim.tv_nsec = 0
}
// File System Operations
// Similar to well known UNIX file system operations
// Instead of returning an error in 'errno', return the negated error value (-errno) directly.
// Kernel will perform permission checking if `default_permissions` mount option was passed to `fuse_main()`
// otherwise, perform necessary permission checking
// libfuse2_getattr gets file attributes
//
//export libfuse2_getattr
func libfuse2_getattr(path *C.char, stbuf *C.stat_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
//log.Trace("Libfuse::libfuse2_getattr : %s", name)
// Return the default configuration for the root
if name == "" {
return C.get_root_properties(stbuf)
}
// TODO: How does this work if we trim the path?
// Check if the file is meant to be ignored
if ignore, found := ignoreFiles[name]; found && ignore {
return -C.ENOENT
}
// Get attributes
attr, err := fuseFS.NextComponent().GetAttr(internal.GetAttrOptions{Name: name})
if err != nil {
//log.Err("Libfuse::libfuse2_getattr : Failed to get attributes of %s [%s]", name, err.Error())
if err == syscall.ENOENT {
return -C.ENOENT
} else if err == syscall.EACCES {
return -C.EACCES
} else {
return -C.EIO
}
}
// Populate stat
fuseFS.fillStat(attr, stbuf)
return 0
}
// File Operations
//
//export libfuse_statfs
func libfuse_statfs(path *C.char, buf *C.statvfs_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
log.Trace("Libfuse::libfuse2_statfs : %s", name)
attr, populated, err := fuseFS.NextComponent().StatFs()
if err != nil {
log.Err("Libfuse::libfuse2_statfs: Failed to get stats %s [%s]", name, err.Error())
return -C.EIO
}
// if populated then we need to overwrite root attributes
if populated {
(*buf).f_bsize = C.ulong(attr.Bsize)
(*buf).f_frsize = C.ulong(attr.Frsize)
(*buf).f_blocks = C.ulong(attr.Blocks)
(*buf).f_bavail = C.ulong(attr.Bavail)
(*buf).f_bfree = C.ulong(attr.Bfree)
(*buf).f_files = C.ulong(attr.Files)
(*buf).f_ffree = C.ulong(attr.Ffree)
(*buf).f_flag = C.ulong(attr.Flags)
return 0
}
C.populate_statfs(path, buf)
return 0
}
// Directory Operations
// libfuse_mkdir creates a directory
//
//export libfuse_mkdir
func libfuse_mkdir(path *C.char, mode C.mode_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
log.Trace("Libfuse::libfuse2_mkdir : %s", name)
err := fuseFS.NextComponent().CreateDir(internal.CreateDirOptions{Name: name, Mode: fs.FileMode(uint32(mode) & 0xffffffff)})
if err != nil {
log.Err("Libfuse::libfuse2_mkdir : Failed to create %s [%s]", name, err.Error())
if os.IsPermission(err) {
return -C.EACCES
} else if os.IsExist(err) {
return -C.EEXIST
} else {
return -C.EIO
}
}
libfuseStatsCollector.PushEvents(createDir, name, map[string]interface{}{md: fs.FileMode(uint32(mode) & 0xffffffff)})
libfuseStatsCollector.UpdateStats(stats_manager.Increment, createDir, (int64)(1))
return 0
}
// libfuse_opendir opens handle to given directory
//
//export libfuse_opendir
func libfuse_opendir(path *C.char, fi *C.fuse_file_info_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
if name != "" {
name = name + "/"
}
log.Trace("Libfuse::libfuse2_opendir : %s", name)
handle := handlemap.NewHandle(name)
// For each handle created using opendir we create
// this structure here to hold current block of children to serve readdir
handle.SetValue("cache", &dirChildCache{
sIndex: 0,
eIndex: 0,
token: "",
length: 0,
children: make([]*internal.ObjAttr, 0),
})
handlemap.Add(handle)
fi.fh = C.ulong(uintptr(unsafe.Pointer(handle)))
return 0
}
// libfuse_releasedir opens handle to given directory
//
//export libfuse_releasedir
func libfuse_releasedir(path *C.char, fi *C.fuse_file_info_t) C.int {
handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fi.fh)))
log.Trace("Libfuse::libfuse2_releasedir : %s, handle: %d", handle.Path, handle.ID)
handle.Cleanup()
handlemap.Delete(handle.ID)
return 0
}
// libfuse2_readdir reads a directory
//
//export libfuse2_readdir
func libfuse2_readdir(_ *C.char, buf unsafe.Pointer, filler C.fuse_fill_dir_t, off C.off_t, fi *C.fuse_file_info_t) C.int {
handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fi.fh)))
handle.RLock()
val, found := handle.GetValue("cache")
handle.RUnlock()
if !found {
return C.int(C_EIO)
}
off_64 := uint64(off)
cacheInfo := val.(*dirChildCache)
if off_64 == 0 ||
(off_64 >= cacheInfo.eIndex && cacheInfo.token != "") {
attrs, token, err := fuseFS.NextComponent().StreamDir(internal.StreamDirOptions{
Name: handle.Path,
Offset: off_64,
Token: cacheInfo.token,
Count: common.MaxDirListCount,
})
if err != nil {
log.Err("Libfuse::libfuse2_readdir : Path %s, handle: %d, offset %d. Error in retrieval %s", handle.Path, handle.ID, off_64, err.Error())
if os.IsNotExist(err) {
return C.int(C_ENOENT)
} else if os.IsPermission(err) {
return C.int(C_EACCES)
} else {
return C.int(C_EIO)
}
}
if off_64 == 0 {
attrs = append([]*internal.ObjAttr{{Flags: fuseFS.lsFlags, Name: "."}, {Flags: fuseFS.lsFlags, Name: ".."}}, attrs...)
}
cacheInfo.sIndex = off_64
cacheInfo.eIndex = off_64 + uint64(len(attrs))
cacheInfo.length = uint64(len(attrs))
cacheInfo.token = token
cacheInfo.children = cacheInfo.children[:0]
cacheInfo.children = attrs
}
if off_64 >= cacheInfo.eIndex {
// If offset is still beyond the end index limit then we are done iterating
return 0
}
stbuf := C.stat_t{}
idx := C.long(off)
// Populate the stat by calling filler
for segmentIdx := off_64 - cacheInfo.sIndex; segmentIdx < cacheInfo.length; segmentIdx++ {
fuseFS.fillStat(cacheInfo.children[segmentIdx], &stbuf)
name := C.CString(cacheInfo.children[segmentIdx].Name)
if 0 != C.fill_dir_entry(filler, buf, name, &stbuf, idx+1) {
C.free(unsafe.Pointer(name))
break
}
C.free(unsafe.Pointer(name))
idx++
}
return 0
}
// libfuse_rmdir deletes a directory, which must be empty.
//
//export libfuse_rmdir
func libfuse_rmdir(path *C.char) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
log.Trace("Libfuse::libfuse2_rmdir : %s", name)
empty := fuseFS.NextComponent().IsDirEmpty(internal.IsDirEmptyOptions{Name: name})
if !empty {
return -C.ENOTEMPTY
}
err := fuseFS.NextComponent().DeleteDir(internal.DeleteDirOptions{Name: name})
if err != nil {
log.Err("Libfuse::libfuse2_rmdir : Failed to delete %s [%s]", name, err.Error())
if os.IsNotExist(err) {
return -C.ENOENT
} else {
return -C.EIO
}
}
libfuseStatsCollector.PushEvents(deleteDir, name, nil)
libfuseStatsCollector.UpdateStats(stats_manager.Increment, deleteDir, (int64)(1))
return 0
}
// File Operations
// libfuse_create creates a file with the specified mode and then opens it.
//
//export libfuse_create
func libfuse_create(path *C.char, mode C.mode_t, fi *C.fuse_file_info_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
log.Trace("Libfuse::libfuse2_create : %s", name)
handle, err := fuseFS.NextComponent().CreateFile(internal.CreateFileOptions{Name: name, Mode: fs.FileMode(uint32(mode) & 0xffffffff)})
if err != nil {
log.Err("Libfuse::libfuse2_create : Failed to create %s [%s]", name, err.Error())
if os.IsExist(err) {
return -C.EEXIST
} else if os.IsPermission(err) {
return -C.EACCES
} else {
return -C.EIO
}
}
handlemap.Add(handle)
ret_val := C.allocate_native_file_object(C.ulong(handle.UnixFD), C.ulong(uintptr(unsafe.Pointer(handle))), 0)
if !handle.Cached() {
ret_val.fd = 0
}
log.Trace("Libfuse::libfuse2_create : %s, handle %d", name, handle.ID)
fi.fh = C.ulong(uintptr(unsafe.Pointer(ret_val)))
libfuseStatsCollector.PushEvents(createFile, name, map[string]interface{}{md: fs.FileMode(uint32(mode) & 0xffffffff)})
// increment open file handles count
libfuseStatsCollector.UpdateStats(stats_manager.Increment, openHandles, (int64)(1))
return 0
}
// libfuse_open opens a file
//
//export libfuse_open
func libfuse_open(path *C.char, fi *C.fuse_file_info_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
log.Trace("Libfuse::libfuse2_open : %s", name)
// TODO: Should this sit behind a user option? What if we change something to support these in the future?
// Mask out SYNC and DIRECT flags since write operation will fail
if fi.flags&C.O_SYNC != 0 || fi.flags&C.__O_DIRECT != 0 {
log.Info("Libfuse::libfuse2_open : Reset flags for open %s, fi.flags %X", name, fi.flags)
// Blobfuse2 does not support the SYNC or DIRECT flag. If a user application passes this flag on to blobfuse2
// and we open the file with this flag, subsequent write operations wlil fail with "Invalid argument" error.
// Mask them out here in the open call so that write works.
// Oracle RMAN is one such application that sends these flags during backup
fi.flags = fi.flags &^ C.O_SYNC
fi.flags = fi.flags &^ C.__O_DIRECT
}
handle, err := fuseFS.NextComponent().OpenFile(
internal.OpenFileOptions{
Name: name,
Flags: int(int(fi.flags) & 0xffffffff),
Mode: fs.FileMode(fuseFS.filePermission),
})
if err != nil {
log.Err("Libfuse::libfuse2_open : Failed to open %s [%s]", name, err.Error())
if os.IsNotExist(err) {
return -C.ENOENT
} else if os.IsPermission(err) {
return -C.EACCES
} else {
return -C.EIO
}
}
handlemap.Add(handle)
ret_val := C.allocate_native_file_object(C.ulong(handle.UnixFD), C.ulong(uintptr(unsafe.Pointer(handle))), C.ulong(handle.Size))
if !handle.Cached() {
ret_val.fd = 0
}
log.Trace("Libfuse::libfuse2_open : %s, handle %d", name, handle.ID)
fi.fh = C.ulong(uintptr(unsafe.Pointer(ret_val)))
// increment open file handles count
libfuseStatsCollector.UpdateStats(stats_manager.Increment, openHandles, (int64)(1))
return 0
}
// libfuse_read reads data from an open file
//
//export libfuse_read
func libfuse_read(path *C.char, buf *C.char, size C.size_t, off C.off_t, fi *C.fuse_file_info_t) C.int {
fileHandle := (*C.file_handle_t)(unsafe.Pointer(uintptr(fi.fh)))
handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fileHandle.obj)))
offset := uint64(off)
data := (*[1 << 30]byte)(unsafe.Pointer(buf))
var err error
var bytesRead int
if handle.Cached() {
bytesRead, err = syscall.Pread(handle.FD(), data[:size], int64(offset))
//bytesRead, err = handle.FObj.ReadAt(data[:size], int64(offset))
} else {
bytesRead, err = fuseFS.NextComponent().ReadInBuffer(
internal.ReadInBufferOptions{
Handle: handle,
Offset: int64(offset),
Data: data[:size],
})
}
if err == io.EOF {
err = nil
}
if err != nil {
log.Err("Libfuse::libfuse2_read : error reading file %s, handle: %d [%s]", handle.Path, handle.ID, err.Error())
return -C.EIO
}
return C.int(bytesRead)
}
// libfuse_write writes data to an open file
//
//export libfuse_write
func libfuse_write(path *C.char, buf *C.char, size C.size_t, off C.off_t, fi *C.fuse_file_info_t) C.int {
fileHandle := (*C.file_handle_t)(unsafe.Pointer(uintptr(fi.fh)))
handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fileHandle.obj)))
offset := uint64(off)
data := (*[1 << 30]byte)(unsafe.Pointer(buf))
bytesWritten, err := fuseFS.NextComponent().WriteFile(
internal.WriteFileOptions{
Handle: handle,
Offset: int64(offset),
Data: data[:size],
Metadata: nil,
})
if err != nil {
log.Err("Libfuse::libfuse2_write : error writing file %s, handle: %d [%s]", handle.Path, handle.ID, err.Error())
return -C.EIO
}
return C.int(bytesWritten)
}
// libfuse_flush possibly flushes cached data
//
//export libfuse_flush
func libfuse_flush(path *C.char, fi *C.fuse_file_info_t) C.int {
fileHandle := (*C.file_handle_t)(unsafe.Pointer(uintptr(fi.fh)))
handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fileHandle.obj)))
log.Trace("Libfuse::libfuse2_flush : %s, handle: %d", handle.Path, handle.ID)
// If the file handle is not dirty, there is no need to flush
if fileHandle.dirty != 0 {
handle.Flags.Set(handlemap.HandleFlagDirty)
}
if !handle.Dirty() {
return 0
}
err := fuseFS.NextComponent().FlushFile(internal.FlushFileOptions{Handle: handle})
if err != nil {
log.Err("Libfuse::libfuse2_flush : error flushing file %s, handle: %d [%s]", handle.Path, handle.ID, err.Error())
if err == syscall.ENOENT {
return -C.ENOENT
} else if err == syscall.EACCES {
return -C.EACCES
} else {
return -C.EIO
}
}
return 0
}
// libfuse2_truncate changes the size of a file
//
//export libfuse2_truncate
func libfuse2_truncate(path *C.char, off C.off_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
log.Trace("Libfuse::libfuse2_truncate : %s size %d", name, off)
err := fuseFS.NextComponent().TruncateFile(internal.TruncateFileOptions{Name: name, Size: int64(off)})
if err != nil {
log.Err("Libfuse::libfuse2_truncate : error truncating file %s [%s]", name, err.Error())
if os.IsNotExist(err) {
return -C.ENOENT
}
return -C.EIO
}
libfuseStatsCollector.PushEvents(truncateFile, name, map[string]interface{}{size: int64(off)})
libfuseStatsCollector.UpdateStats(stats_manager.Increment, truncateFile, (int64)(1))
return 0
}
// libfuse_release releases an open file
//
//export libfuse_release
func libfuse_release(path *C.char, fi *C.fuse_file_info_t) C.int {
fileHandle := (*C.file_handle_t)(unsafe.Pointer(uintptr(fi.fh)))
handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fileHandle.obj)))
log.Trace("Libfuse::libfuse2_release : %s, handle: %d", handle.Path, handle.ID)
// If the file handle is dirty then file-cache needs to flush this file
if fileHandle.dirty != 0 {
handle.Flags.Set(handlemap.HandleFlagDirty)
}
err := fuseFS.NextComponent().CloseFile(internal.CloseFileOptions{Handle: handle})
if err != nil {
log.Err("Libfuse::libfuse2_release : error closing file %s, handle: %d [%s]", handle.Path, handle.ID, err.Error())
if err == syscall.ENOENT {
return -C.ENOENT
} else if err == syscall.EACCES {
return -C.EACCES
} else {
return -C.EIO
}
}
handlemap.Delete(handle.ID)
C.release_native_file_object(fi)
// decrement open file handles count
libfuseStatsCollector.UpdateStats(stats_manager.Decrement, openHandles, (int64)(1))
return 0
}
// libfuse_unlink removes a file
//
//export libfuse_unlink
func libfuse_unlink(path *C.char) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
log.Trace("Libfuse::libfuse2_unlink : %s", name)
err := fuseFS.NextComponent().DeleteFile(internal.DeleteFileOptions{Name: name})
if err != nil {
log.Err("Libfuse::libfuse2_unlink : error deleting file %s [%s]", name, err.Error())
if os.IsNotExist(err) {
return -C.ENOENT
} else if os.IsPermission(err) {
return -C.EACCES
}
return -C.EIO
}
libfuseStatsCollector.PushEvents(deleteFile, name, nil)
libfuseStatsCollector.UpdateStats(stats_manager.Increment, deleteFile, (int64)(1))
return 0
}
// libfuse2_rename renames a file or directory
// https://man7.org/linux/man-pages/man2/rename.2.html
// errors handled: EISDIR, ENOENT, ENOTDIR, ENOTEMPTY, EEXIST
// TODO: handle EACCESS, EINVAL?
//
//export libfuse2_rename
func libfuse2_rename(src *C.char, dst *C.char) C.int {
srcPath := trimFusePath(src)
srcPath = common.NormalizeObjectName(srcPath)
dstPath := trimFusePath(dst)
dstPath = common.NormalizeObjectName(dstPath)
log.Trace("Libfuse::libfuse2_rename : %s -> %s", srcPath, dstPath)
// Note: When running other commands from the command line, a lot of them seemed to handle some cases like ENOENT themselves.
// Rename did not, so we manually check here.
// ENOENT. Not covered: a directory component in dst does not exist
if srcPath == "" || dstPath == "" {
log.Err("Libfuse::libfuse2_rename : src: [%s] or dst: [%s] is an empty string", srcPath, dstPath)
return -C.ENOENT
}
srcAttr, srcErr := fuseFS.NextComponent().GetAttr(internal.GetAttrOptions{Name: srcPath})
if os.IsNotExist(srcErr) {
log.Err("Libfuse::libfuse2_rename : Failed to get attributes of %s [%s]", srcPath, srcErr.Error())
return -C.ENOENT
}
dstAttr, dstErr := fuseFS.NextComponent().GetAttr(internal.GetAttrOptions{Name: dstPath})
// EISDIR
if (dstErr == nil || os.IsExist(dstErr)) && dstAttr.IsDir() && !srcAttr.IsDir() {
log.Err("Libfuse::libfuse2_rename : dst [%s] is an existing directory but src [%s] is not a directory", dstPath, srcPath)
return -C.EISDIR
}
// ENOTDIR
if (dstErr == nil || os.IsExist(dstErr)) && !dstAttr.IsDir() && srcAttr.IsDir() {
log.Err("Libfuse::libfuse2_rename : dst [%s] is an existing file but src [%s] is a directory", dstPath, srcPath)
return -C.ENOTDIR
}
if srcAttr.IsDir() {
// ENOTEMPTY
if dstErr == nil || os.IsExist(dstErr) {
empty := fuseFS.NextComponent().IsDirEmpty(internal.IsDirEmptyOptions{Name: dstPath})
if !empty {
return -C.ENOTEMPTY
}
}
err := fuseFS.NextComponent().RenameDir(internal.RenameDirOptions{Src: srcPath, Dst: dstPath})
if err != nil {
log.Err("Libfuse::libfuse2_rename : error renaming directory %s -> %s [%s]", srcPath, dstPath, err.Error())
return -C.EIO
}
libfuseStatsCollector.PushEvents(renameDir, srcPath, map[string]interface{}{source: srcPath, dest: dstPath})
libfuseStatsCollector.UpdateStats(stats_manager.Increment, renameDir, (int64)(1))
} else {
err := fuseFS.NextComponent().RenameFile(internal.RenameFileOptions{Src: srcPath, Dst: dstPath})
if err != nil {
log.Err("Libfuse::libfuse2_rename : error renaming file %s -> %s [%s]", srcPath, dstPath, err.Error())
return -C.EIO
}
libfuseStatsCollector.PushEvents(renameFile, srcPath, map[string]interface{}{source: srcPath, dest: dstPath})
libfuseStatsCollector.UpdateStats(stats_manager.Increment, renameFile, (int64)(1))
}
return 0
}
// Symlink Operations
// libfuse_symlink creates a symbolic link
//
//export libfuse_symlink
func libfuse_symlink(target *C.char, link *C.char) C.int {
name := trimFusePath(link)
name = common.NormalizeObjectName(name)
targetPath := C.GoString(target)
targetPath = common.NormalizeObjectName(targetPath)
log.Trace("Libfuse::libfuse2_symlink : Received for %s -> %s", name, targetPath)
err := fuseFS.NextComponent().CreateLink(internal.CreateLinkOptions{Name: name, Target: targetPath})
if err != nil {
log.Err("Libfuse::libfuse2_symlink : error linking file %s -> %s [%s]", name, targetPath, err.Error())
return -C.EIO
}
libfuseStatsCollector.PushEvents(createLink, name, map[string]interface{}{trgt: targetPath})
libfuseStatsCollector.UpdateStats(stats_manager.Increment, createLink, (int64)(1))
return 0
}
// libfuse_readlink reads the target of a symbolic link
//
//export libfuse_readlink
func libfuse_readlink(path *C.char, buf *C.char, size C.size_t) C.int {
name := trimFusePath(path)
name = common.NormalizeObjectName(name)
//log.Trace("Libfuse::libfuse_readlink : Received for %s", name)
targetPath, err := fuseFS.NextComponent().ReadLink(internal.ReadLinkOptions{Name: name})
if err != nil {
log.Err("Libfuse::libfuse2_readlink : error reading link file %s [%s]", name, err.Error())
if os.IsNotExist(err) {
return -C.ENOENT
}
return -C.EIO
}
data := (*[1 << 30]byte)(unsafe.Pointer(buf))
copy(data[:size-1], targetPath)
data[len(targetPath)] = 0
libfuseStatsCollector.PushEvents(readLink, name, map[string]interface{}{trgt: targetPath})
libfuseStatsCollector.UpdateStats(stats_manager.Increment, readLink, (int64)(1))
return 0
}
// libfuse_fsync synchronizes file contents
//
//export libfuse_fsync
func libfuse_fsync(path *C.char, datasync C.int, fi *C.fuse_file_info_t) C.int {
if fi.fh == 0 {
return C.int(-C.EIO)
}
fileHandle := (*C.file_handle_t)(unsafe.Pointer(uintptr(fi.fh)))
handle := (*handlemap.Handle)(unsafe.Pointer(uintptr(fileHandle.obj)))
log.Trace("Libfuse::libfuse2_fsync : %s, handle: %d", handle.Path, handle.ID)
options := internal.SyncFileOptions{Handle: handle}
// If the datasync parameter is non-zero, then only the user data should be flushed, not the metadata.
// TODO : Should we support this?
err := fuseFS.NextComponent().SyncFile(options)
if err != nil {
log.Err("Libfuse::libfuse2_fsync : error syncing file %s [%s]", handle.Path, err.Error())
return -C.EIO
}
libfuseStatsCollector.PushEvents(syncFile, handle.Path, nil)