-
Notifications
You must be signed in to change notification settings - Fork 39
/
ratarmount.py
executable file
·1922 lines (1600 loc) · 85.5 KB
/
ratarmount.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# mypy: disable-error-code="method-assign"
import argparse
import errno
import importlib
import json
import math
import os
import re
import shutil
import sqlite3
import stat
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import traceback
import urllib.parse
import urllib.request
import zipfile
from typing import Any, Callable, Dict, Iterable, IO, List, Optional, Tuple, Union
try:
from ratarmountcore.fusepy import fuse
except AttributeError as importException:
traceback.print_exc()
print("[Error] Some internal exception occurred while trying to load the bundled fusepy:", importException)
sys.exit(1)
except (ImportError, OSError) as importException:
print("[Warning] Failed to load bundled fusepy. Will try to load system fusepy. Exception was:", importException)
try:
import fuse # type: ignore
except (ImportError, OSError) as fuseException:
try:
import fusepy as fuse # type: ignore
except ImportError as fusepyException:
print("[Error] Did not find any FUSE installation. Please install it, e.g., with:")
print("[Error] - apt install libfuse2")
print("[Error] - yum install fuse fuse-libs")
print("[Error] Exception for fuse:", fuseException)
print("[Error] Exception for fusepy:", fusepyException)
sys.exit(1)
try:
import rarfile
except ImportError:
pass
try:
import fsspec
except ImportError:
fsspec = None # type: ignore
import ratarmountcore as core
from ratarmountcore import (
AutoMountLayer,
MountSource,
FileVersionLayer,
FolderMountSource,
SQLiteIndexedTar,
UnionMountSource,
findModuleVersion,
findAvailableOpen,
openMountSource,
overrides,
supportedCompressions,
stripSuffixFromTarFile,
RatarmountError,
SubvolumesMountSource,
FileInfo,
)
from ratarmountcore.utils import imeta, getXdgCacheHome
__version__ = '1.0.0'
def hasNonEmptySupport() -> bool:
try:
# Check suffix of shared library
if 'fuse' in globals() and getattr(fuse, '_libfuse_path', '').endswith(".so.2"):
return True
# Note that in Ubuntu 22.04 libfuse3 and libfuse2 can be installed side-by-side with fusermount 3 being
# detected with precedence even though fusepy will use libfuse-2.9.9.
with os.popen('fusermount -V') as pipe:
match = re.search(r'([0-9]+)[.][0-9]+[.][0-9]+', pipe.read())
if match:
return int(match.group(1)) < 3
except Exception:
pass
return False # On macOS, fusermount does not exist and macfuse also seems to complain with nonempty option.
class WritableFolderMountSource(fuse.Operations):
"""
This class manages one folder as mount source offering methods for reading and modification.
"""
_overlayMetadataSchema = """
CREATE TABLE "files" (
"path" VARCHAR(65535) NOT NULL, /* path with leading and without trailing slash */
"name" VARCHAR(65535) NOT NULL,
/* Some file systems may not support some metadata like permissions on NTFS, so also save them. */
"mtime" INTEGER,
"mode" INTEGER,
"uid" INTEGER,
"gid" INTEGER,
"deleted" BOOL,
PRIMARY KEY (path,name)
);
"""
hiddenDatabaseName = '.ratarmount.overlay.sqlite'
def __init__(self, path: str, mountSource: MountSource) -> None:
if os.path.exists(path):
if not os.path.isdir(path):
raise ValueError("Overlay path must be a folder!")
else:
os.makedirs(path, exist_ok=True)
self.root: str = path
self.mountSource = mountSource
self.sqlConnection = self._openSqlDb(os.path.join(path, self.hiddenDatabaseName))
self._statfs = self._getStatfsForFolder(self.root)
# Add table if necessary
tables = [row[0] for row in self.sqlConnection.execute('SELECT name FROM sqlite_master WHERE type = "table";')]
if "files" not in tables:
self.sqlConnection.executescript(WritableFolderMountSource._overlayMetadataSchema)
# Check that the mount source contains this overlay folder with top priority
databaseFileInfo = self.mountSource.getFileInfo('/' + self.hiddenDatabaseName)
assert databaseFileInfo is not None
path, databaseMountSource, fileInfo = self.mountSource.getMountSource(databaseFileInfo)
assert stat.S_ISREG(fileInfo.mode)
assert isinstance(databaseMountSource, FolderMountSource)
assert databaseMountSource.root == self.root
@staticmethod
def _getStatfsForFolder(path: str) -> Dict[str, Any]:
result = os.statvfs(path)
return {
key: getattr(result, key)
for key in (
'f_bavail',
'f_bfree',
'f_blocks',
'f_bsize',
'f_favail',
'f_ffree',
'f_files',
'f_flag',
'f_frsize',
'f_namemax',
)
}
@staticmethod
def _openSqlDb(path: str, **kwargs) -> sqlite3.Connection:
# isolation_level None is important so that changes are autocommitted because there is no manual commit call.
sqlConnection = sqlite3.connect(path, isolation_level=None, **kwargs)
sqlConnection.row_factory = sqlite3.Row
sqlConnection.executescript(
# Locking mode exclusive leads to a measurable speedup. E.g., find on 2k recursive files tar
# improves from ~1s to ~0.4s!
# https://blog.devart.com/increasing-sqlite-performance.html
"""
PRAGMA LOCKING_MODE = EXCLUSIVE;
"""
)
return sqlConnection
def setFolderDescriptor(self, fd: int) -> None:
"""
Make this mount source manage the special "." folder by changing to that directory.
Because we change to that directory, it may only be used for one mount source but it also works
when that mount source is mounted on!
"""
os.fchdir(fd)
self.root = '.'
self._statfs = self._getStatfsForFolder(self.root)
@staticmethod
def _splitPath(path: str) -> Tuple[str, str]:
result = ('/' + os.path.normpath(path).lstrip('/')).rsplit('/', 1)
assert len(result) == 2
return result[0], result[1]
def _realpath(self, path: str) -> str:
"""Path given relative to folder root. Leading '/' is acceptable"""
return os.path.join(self.root, path.lstrip(os.path.sep))
def _ensureParentExists(self, path):
"""
Creates parent folders for given path inside overlay folder if and only if they exist in the mount source.
"""
parentPath = self._splitPath(path)[0]
if not os.path.exists(self._realpath(parentPath)) and self.mountSource.isdir(parentPath):
os.makedirs(self._realpath(parentPath), exist_ok=True)
def _ensureFileIsModifiable(self, path):
self._ensureParentExists(path)
with self.mountSource.open(self.mountSource.getFileInfo(path)) as sourceObject, open(
self._realpath(path), 'wb'
) as targetObject:
shutil.copyfileobj(sourceObject, targetObject)
def _open(self, path: str, mode):
self._ensureParentExists(path)
folder, name = self._splitPath(path)
self.sqlConnection.execute(
'INSERT OR IGNORE INTO "files" (path,name,mode,deleted) VALUES (?,?,?,?)', (folder, name, mode, False)
)
self.sqlConnection.execute(
'UPDATE "files" SET deleted=0 WHERE path == (?) AND name == (?)',
(folder, name),
)
def _markAsDeleted(self, path: str):
"""Hides the given path if it exists in the underlying mount source."""
folder, name = self._splitPath(path)
if self.mountSource.exists(path):
self.sqlConnection.execute(
'INSERT OR REPLACE INTO "files" (path,name,deleted) VALUES (?,?,?)', (folder, name, True)
)
else:
self.sqlConnection.execute('DELETE FROM "files" WHERE (path,name) == (?,?)', (folder, name))
def listDeleted(self, path: str) -> List[str]:
"""Return list of files marked as deleted in the given path."""
result = self.sqlConnection.execute(
'SELECT name FROM "files" WHERE path == (?) AND deleted == 1', (path.rstrip('/'),)
)
# For temporary SQLite file suffixes, see https://www.sqlite.org/tempfiles.html
suffixes = ['', '-journal', '-shm', '-wal']
return [x[0] for x in result] + [self.hiddenDatabaseName + suffix for suffix in suffixes]
def isDeleted(self, path: str) -> bool:
folder, name = self._splitPath(path)
result = self.sqlConnection.execute(
'SELECT COUNT(*) > 0 FROM "files" WHERE path == (?) AND name == (?) AND deleted == 1', (folder, name)
)
return bool(result.fetchone()[0])
def _setMetadata(self, path: str, metadata: Dict[str, Any]):
if not metadata:
raise ValueError("Need arguments to know what to update.")
allowedKeys = ["path", "name", "mtime", "mode", "uid", "gid"]
for key in metadata:
if key not in allowedKeys:
raise ValueError(f"Invalid metadata key ({key}) specified")
folder, name = self._splitPath(path)
# https://stackoverflow.com/questions/31277027/using-placeholder-in-sqlite3-statements
assignments = []
values = []
for key, value in metadata.items():
values.append(value)
assignments.append(f"{key} = (?)")
self.sqlConnection.execute(
f"""UPDATE "files" SET {', '.join(assignments)} WHERE "path" == ? and "name" == ?""",
tuple(values) + (folder, name),
)
def _initFileMetadata(self, path: str):
# Note that we do not have to check the overlay folder assuming that it is inside the (union) mount source!
sourceFileInfo = self.mountSource.getFileInfo(path)
if not sourceFileInfo:
raise fuse.FuseOSError(errno.ENOENT)
# Initialize new metadata entry from existing file
sfi = self.mountSource.getMountSource(sourceFileInfo)[2]
folder, name = self._splitPath(path)
self.sqlConnection.execute(
f'INSERT OR REPLACE INTO "files" VALUES ({",".join(["?"] * 7)})',
(folder, name, sfi.mtime, sfi.mode, sfi.uid, sfi.gid, False),
)
def _setFileMetadata(self, path: str, applyMetadataToFile: Callable[[str], None], metadata: Dict[str, Any]):
folder, name = self._splitPath(path)
existsInMetadata = self.sqlConnection.execute(
'SELECT COUNT(*) > 0 FROM "files" WHERE "path" == (?) and "name" == (?)', (folder, name)
).fetchone()[0]
if not existsInMetadata:
self._initFileMetadata(path)
self._setMetadata(path, metadata)
# Apply the metadata change for the file in the overlay folder if it exists there.
# This is only because it might be confusing for the user else but in general, the metadata in the SQLite
# database should take precedence if e.g. the underlying file systems does not support them.
try:
if os.path.exists(self._realpath(path)):
applyMetadataToFile(self._realpath(path))
except Exception:
traceback.print_exc()
print("[Info] Caught exception when trying to apply metadata to real file.")
print("[Info] It was applied in the metadata database!")
def updateFileInfo(self, path: str, fileInfo: FileInfo):
folder, name = self._splitPath(path)
row = self.sqlConnection.execute(
"""SELECT * FROM "files" WHERE "path" == (?) AND "name" == (?);""", (folder, name)
).fetchone()
if not row:
return fileInfo
return FileInfo(
# fmt: off
size = fileInfo.size,
mtime = row['mtime'] if row['mtime'] is not None else fileInfo.mtime,
mode = row['mode'] if row['mode'] is not None else fileInfo.mode,
linkname = fileInfo.linkname,
uid = row['uid'] if row['uid'] is not None else fileInfo.uid,
gid = row['gid'] if row['gid'] is not None else fileInfo.gid,
userdata = fileInfo.userdata,
# fmt: on
)
# Metadata modification
@overrides(fuse.Operations)
def chmod(self, path, mode):
self._setFileMetadata(path, lambda p: os.chmod(p, mode), {'mode': mode})
@overrides(fuse.Operations)
def chown(self, path, uid, gid):
data = {}
if uid != -1:
data['uid'] = uid
if gid != -1:
data['gid'] = gid
# os.chown
# > Change the owner and group id of path to the numeric uid and gid. To leave one of the ids unchanged,
# > set it to -1.
# No reason to change the file owner in the overlay folder, which may often not even be possible.
self._setFileMetadata(path, lambda p: None, data)
@overrides(fuse.Operations)
def utimens(self, path, times=None):
"""Argument "times" is a (atime, mtime) tuple. If "times" is None, use the current time."""
if times is None:
mtime = time.time()
else:
mtime = times[1]
self._setFileMetadata(path, lambda p: os.utime(p, times), {'mtime': mtime})
@overrides(fuse.Operations)
def rename(self, old, new):
if not self.mountSource.exists(old) or self.isDeleted(old):
raise fuse.FuseOSError(errno.ENOENT)
folder, name = self._splitPath(new)
# Delete target path from metadata database to avoid uniqueness restraint being invalidated
self.sqlConnection.execute('DELETE FROM "files" WHERE "path" == (?) and "name" == (?)', (folder, name))
self._setFileMetadata(old, lambda p: None, {'path': folder, 'name': name})
if os.path.exists(self._realpath(old)):
os.rename(self._realpath(old), self._realpath(new))
else:
self._ensureParentExists(new)
with self.mountSource.open(self.mountSource.getFileInfo(old)) as sourceObject, open(
self._realpath(new), 'wb'
) as targetObject:
shutil.copyfileobj(sourceObject, targetObject)
self._markAsDeleted(old)
# Links
@overrides(fuse.Operations)
def symlink(self, target, source):
os.symlink(source, self._realpath(target))
@overrides(fuse.Operations)
def link(self, target, source):
# Can only hardlink to files which are also in the overlay folder.
overlaySource = self._realpath(source)
if not os.path.exists(overlaySource) and self.mountSource.getFileInfo(source):
raise fuse.FuseOSError(errno.EXDEV)
target = self._realpath(target)
os.link(overlaySource, target)
# Folders
@overrides(fuse.Operations)
def mkdir(self, path, mode):
self._open(path, mode | stat.S_IFDIR)
os.mkdir(self._realpath(path), mode)
@overrides(fuse.Operations)
def rmdir(self, path):
if not self.mountSource.exists(path) or self.isDeleted(path):
raise fuse.FuseOSError(errno.ENOENT)
contents = self.mountSource.listDir(path)
if contents is not None and set(contents.keys()) - set(self.listDeleted(path)):
raise fuse.FuseOSError(errno.ENOTEMPTY)
try:
if os.path.exists(self._realpath(path)):
os.rmdir(self._realpath(path))
except Exception as exception:
traceback.print_exc()
raise fuse.FuseOSError(errno.EIO) from exception
finally:
self._markAsDeleted(path)
# Files
@overrides(fuse.Operations)
def open(self, path, flags):
# if flags & os.O_CREAT != 0: # I hope that FUSE simple calls create in this case.
# self._open(path) # what would the default mode even be?
if not os.path.exists(self._realpath(path)):
if not self.mountSource.exists(path):
raise fuse.FuseOSError(errno.ENOENT)
if flags & (os.O_WRONLY | os.O_RDWR):
self._ensureFileIsModifiable(path)
return os.open(self._realpath(path), flags)
@overrides(fuse.Operations)
def create(self, path, mode, fi=None):
self._open(path, mode)
return os.open(self._realpath(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
@overrides(fuse.Operations)
def unlink(self, path):
# Note that despite the name this is called for removing both, files and links.
if not self.mountSource.exists(path) or self.isDeleted(path):
# This is for the rare case that the file only exists in the overlay metadata database.
self._markAsDeleted(path)
raise fuse.FuseOSError(errno.ENOENT)
try:
if os.path.exists(self._realpath(path)):
os.unlink(self._realpath(path))
except Exception as exception:
traceback.print_exc()
raise fuse.FuseOSError(errno.EIO) from exception
finally:
self._markAsDeleted(path)
@overrides(fuse.Operations)
def mknod(self, path, mode, dev):
self._ensureParentExists(path)
os.mknod(self._realpath(path), mode, dev)
@overrides(fuse.Operations)
def truncate(self, path, length, fh=None):
self._ensureFileIsModifiable(path)
os.truncate(self._realpath(path), length)
# Actual writing
@overrides(fuse.Operations)
def write(self, path, data, offset, fh):
os.lseek(fh, offset, 0)
return os.write(fh, data)
# Flushing
@overrides(fuse.Operations)
def flush(self, path, fh):
return os.fsync(fh)
@overrides(fuse.Operations)
def fsync(self, path, datasync, fh):
return os.fsync(fh) if datasync == 0 else os.fdatasync(fh)
@overrides(fuse.Operations)
def statfs(self, path):
return self._statfs.copy()
class FuseMount(fuse.Operations):
"""
This class implements the fusepy interface in order to create a mounted file system view to a MountSource.
This class itself is a relatively thin wrapper around the ratarmountcore mount sources.
It also handles the write overlay because it does not fit into the MountSource interface and because it
must be part of the UnionMountSource for correct file versioning but at the same time it must know of the
union mount source.
Documentation for FUSE methods can be found in the fusepy or libfuse headers. There seems to be no complete
rendered documentation aside from the header comments.
https://github.com/fusepy/fusepy/blob/master/fuse.py
https://github.com/libfuse/libfuse/blob/master/include/fuse.h
https://man7.org/linux/man-pages/man3/errno.3.html
All path arguments for overridden fusepy methods do have a leading slash ('/')!
This is why MountSource also should expect leading slashes in all paths.
"""
# Use a relatively large minimum 256 KiB block size to get filesystem users to use larger reads
# because reads have a relative large overhead because of the fusepy, libfuse, kernel FUSE, SQLite,
# ratarmountcore, StenciledFile, and other layers they have to go through.
MINIMUM_BLOCK_SIZE = 256 * 1024
def __init__(self, pathToMount: Union[str, List[str]], mountPoint: str, foreground: bool = True, **options) -> None:
self.printDebug: int = int(options.get('printDebug', 0))
self.writeOverlay: Optional[WritableFolderMountSource] = None
self.overlayPath: Optional[str] = None
self.mountPoint = os.path.realpath(mountPoint)
# This check is important for the self-bind test below, which assumes a folder.
if os.path.exists(self.mountPoint) and not os.path.isdir(self.mountPoint):
raise ValueError("Mount point must either not exist or be a directory!")
if not isinstance(pathToMount, list):
try:
os.fspath(pathToMount)
pathToMount = [pathToMount]
except Exception:
pass
hadPathsToMount = bool(pathToMount)
pathToMount = list(filter(lambda x: os.path.exists(x) or '://' in x, pathToMount))
if hadPathsToMount and not pathToMount:
raise ValueError("No paths to mount left over after filtering!")
options['writeIndex'] = True
if 'recursive' not in options and options.get('recursionDepth', 0) != 0:
options['recursive'] = True
# Add write overlay as folder mount source to read from with highest priority.
if 'writeOverlay' in options and isinstance(options['writeOverlay'], str) and options['writeOverlay']:
self.overlayPath = os.path.realpath(options['writeOverlay'])
if not os.path.exists(self.overlayPath):
os.makedirs(self.overlayPath, exist_ok=True)
pathToMount.append(self.overlayPath)
assert isinstance(pathToMount, list)
if not pathToMount:
raise ValueError("No paths to mount given!")
# Take care that bind-mounting folders to itself works
mountSources: List[Tuple[str, MountSource]] = []
self.mountPointFd: Optional[int] = None
self.selfBindMount: Optional[FolderMountSource] = None
for path in pathToMount:
if os.path.realpath(path) != self.mountPoint:
# This also will create or load the block offsets for compressed formats
mountSources.append((os.path.basename(path), openMountSource(path, **options)))
continue
if self.mountPointFd is not None:
continue
mountSource = FolderMountSource(path)
mountSources.append((os.path.basename(path), mountSource))
self.selfBindMount = mountSource
self.mountPointFd = os.open(self.mountPoint, os.O_RDONLY)
# Lazy mounting can result in locking recursive calls into our own FUSE mount point.
# Opening the archives is already handled correctly without calling FUSE inside AutoMountLayer.
# Here we need to ensure that indexes are not tried to being read from or written to our own
# FUSE mount point.
if options.get('lazyMounting', False):
def pointsIntoMountPoint(pathToTest):
return os.path.commonpath([pathToTest, self.mountPoint]) == self.mountPoint
hasIndexPath = False
if 'indexFilePath' in options and isinstance(options['indexFilePath'], str):
indexFilePath = options['indexFilePath']
# Strip a single file://, not any more because URL chaining is supported by fsspec.
if options['indexFilePath'].count('://') == 1:
fileURLPrefix = 'file://'
if indexFilePath.startswith(fileURLPrefix):
indexFilePath = indexFilePath[len(fileURLPrefix) :]
if '://' not in indexFilePath:
indexFilePath = os.path.realpath(options['indexFilePath'])
if pointsIntoMountPoint(indexFilePath):
del options['indexFilePath']
else:
options['indexFilePath'] = indexFilePath
hasIndexPath = True
if 'indexFolders' in options and isinstance(options['indexFolders'], list):
indexFolders = options['indexFolders']
newIndexFolders = []
for folder in indexFolders:
if pointsIntoMountPoint(folder):
continue
newIndexFolders.append(os.path.realpath(folder))
options['indexFolders'] = newIndexFolders
if newIndexFolders:
hasIndexPath = True
# Force in-memory indexes if no folder remains because the default for no indexFilePath being
# specified would be in a file in the same folder as the archive.
if not hasIndexPath:
options['indexFilePath'] = ':memory:'
def createMultiMount() -> MountSource:
if not options.get('disableUnionMount', False):
return UnionMountSource([x[1] for x in mountSources], **options)
# Create unique keys.
submountSources: Dict[str, MountSource] = {}
suffix = 1
for key, mountSource in mountSources:
if key in submountSources:
while f"{key}.{suffix}" in submountSources:
suffix += 1
submountSources[f"{key}.{suffix}"] = mountSource
else:
submountSources[key] = mountSource
return SubvolumesMountSource(submountSources, printDebug=self.printDebug)
self.mountSource: MountSource = mountSources[0][1] if len(mountSources) == 1 else createMultiMount()
if options.get('recursionDepth', 0):
self.mountSource = AutoMountLayer(self.mountSource, **options)
# No threads should be created and still be open before FUSE forks.
# Instead, they should be created in 'init'.
# Therefore, close threads opened by the ParallelBZ2Reader for creating the block offsets.
# Those threads will be automatically recreated again on the next read call.
# Without this, the ratarmount background process won't quit even after unmounting!
joinThreads = getattr(self.mountSource, 'joinThreads', None)
if joinThreads is not None:
joinThreads()
self.mountSource = FileVersionLayer(self.mountSource)
# Maps handles to either opened I/O objects or os module file handles for the writeOverlay and the open flags.
self.openedFiles: Dict[int, Tuple[int, Union[IO[bytes], int]]] = {}
self.lastFileHandle: int = 0 # It will be incremented before being returned. It can't hurt to never return 0.
if self.overlayPath:
self.writeOverlay = WritableFolderMountSource(self.overlayPath, self.mountSource)
self.chmod = self.writeOverlay.chmod
self.chown = self.writeOverlay.chown
self.utimens = self.writeOverlay.utimens
self.rename = self.writeOverlay.rename
self.symlink = self.writeOverlay.symlink
self.link = self.writeOverlay.link
self.unlink = self.writeOverlay.unlink
self.mkdir = self.writeOverlay.mkdir
self.rmdir = self.writeOverlay.rmdir
self.mknod = self.writeOverlay.mknod
self.truncate = self.writeOverlay.truncate
# Create mount point if it does not exist
self.mountPointWasCreated = False
if mountPoint and not os.path.exists(mountPoint):
os.mkdir(mountPoint)
self.mountPointWasCreated = True
statResults = os.lstat(self.mountPoint)
self.mountPointInfo = {key: getattr(statResults, key) for key in dir(statResults) if key.startswith('st_')}
if self.printDebug >= 1:
print("Created mount point at:", self.mountPoint)
# Note that this will not detect threads started in shared libraries, only those started via "threading".
if not foreground and len(threading.enumerate()) > 1:
threadNames = [thread.name for thread in threading.enumerate() if thread.name != "MainThread"]
# Fix FUSE hangs with: https://unix.stackexchange.com/a/713621/111050
raise ValueError(
"Daemonizing FUSE into the background may result in errors or unkillable hangs because "
f"there are threads still open: {', '.join(threadNames)}!\nCall ratarmount with -f or --foreground."
)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
if hasattr(super(), "__exit__"):
super().__exit__(exception_type, exception_value, exception_traceback)
self._close()
def _close(self) -> None:
try:
if self.mountPointWasCreated:
os.rmdir(self.mountPoint)
except Exception:
pass
try:
mountPointFd = getattr(self, 'mountPointFd', None)
if mountPointFd is not None:
os.close(mountPointFd)
self.mountPointFd = None
except Exception as exception:
if self.printDebug >= 1:
print("[Warning] Failed to close mount point folder descriptor because of:", exception)
try:
# If there is some exception in the constructor, then some members may not exist!
if hasattr(self, 'mountSource'):
self.mountSource.__exit__(None, None, None)
except Exception as exception:
if self.printDebug >= 1:
print("[Warning] Failed to tear down root mount source because of:", exception)
def __del__(self) -> None:
self._close()
def _addNewHandle(self, handle, flags):
# Note that fh in fuse_common.h is 64-bit and Python also supports 64-bit (long integers) out of the box.
# So, there should practically be no overflow and file handle reuse possible.
self.lastFileHandle += 1
self.openedFiles[self.lastFileHandle] = (flags, handle)
return self.lastFileHandle
def _getFileInfo(self, path: str) -> FileInfo:
if self.writeOverlay and self.writeOverlay.isDeleted(path):
raise fuse.FuseOSError(errno.ENOENT)
fileInfo = self.mountSource.getFileInfo(path)
if fileInfo is None:
raise fuse.FuseOSError(errno.ENOENT)
if not self.writeOverlay:
return fileInfo
# Request exact metadata from write overlay, e.g., if the actual file in the folder
# does not support permission changes
result = self.mountSource.getMountSource(fileInfo)
subMountPoint = result[0]
# TODO Note that if the path contains special .version versioning, then it will most likely fail
# to find the path in the write overlay, which is problematic for things like foo.versions/0.
# Would be really helpful if the file info would contain the actual path and name, too :/
return self.writeOverlay.updateFileInfo(path[len(subMountPoint) :], fileInfo)
@overrides(fuse.Operations)
def init(self, path) -> None:
if self.selfBindMount is not None and self.mountPointFd is not None:
self.selfBindMount.setFolderDescriptor(self.mountPointFd)
if self.writeOverlay and self.writeOverlay.root == self.mountPoint:
self.writeOverlay.setFolderDescriptor(self.mountPointFd)
@staticmethod
def _fileInfoToDict(fileInfo: FileInfo):
# dictionary keys: https://pubs.opengroup.org/onlinepubs/007904875/basedefs/sys/stat.h.html
statDict = {"st_" + key: getattr(fileInfo, key) for key in ('size', 'mtime', 'mode', 'uid', 'gid')}
statDict['st_mtime'] = int(statDict['st_mtime'])
statDict['st_nlink'] = 1 # TODO: this is wrong for files with hardlinks
# `du` sums disk usage (the number of blocks used by a file) instead of the file sizes by default.
# So, we need to return some valid values. Tar files are usually a series of 512 B blocks, but this
# block size is also used by Python as the default read call size, so it should be something larger
# for better performance.
blockSize = FuseMount.MINIMUM_BLOCK_SIZE
statDict['st_blksize'] = blockSize
statDict['st_blocks'] = 1 + ((fileInfo.size + blockSize - 1) // blockSize)
return statDict
@overrides(fuse.Operations)
def getattr(self, path: str, fh=None) -> Dict[str, Any]:
return self._fileInfoToDict(self._getFileInfo(path))
@overrides(fuse.Operations)
def readdir(self, path: str, fh):
'''
Can return either a list of names, or a list of (name, attrs, offset)
tuples. attrs is a dict as in getattr.
'''
files = self.mountSource.listDirModeOnly(path)
# we only need to return these special directories. FUSE automatically expands these and will not ask
# for paths like /../foo/./../bar, so we don't need to worry about cleaning such paths
if isinstance(files, dict):
yield '.', self.getattr(path), 0
if path == '/':
yield '..', self.mountPointInfo, 0
else:
yield '..', self.getattr(path.rsplit('/', 1)[0]), 0
else:
yield '.'
yield '..'
deletedFiles = self.writeOverlay.listDeleted(path) if self.writeOverlay else []
if isinstance(files, dict):
for name, mode in files.items():
if name not in deletedFiles:
yield name, {'st_mode': mode}, 0
elif files is not None:
for key in files:
if key not in deletedFiles:
yield key
@overrides(fuse.Operations)
def readlink(self, path: str) -> str:
return self._getFileInfo(path).linkname
@overrides(fuse.Operations)
def open(self, path, flags):
"""Returns file handle of opened path."""
fileInfo = self._getFileInfo(path)
try:
# If the flags indicate "open for modification", then still open it as read-only through the mount source
# but store information to reopen it for write access on write calls.
# @see https://man7.org/linux/man-pages/man2/open.2.html
# > The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR.
return self._addNewHandle(self.mountSource.open(fileInfo, buffering=0), flags)
except Exception as exception:
traceback.print_exc()
print("Caught exception when trying to open file.", fileInfo)
raise fuse.FuseOSError(errno.EIO) from exception
@overrides(fuse.Operations)
def release(self, path, fh):
if fh not in self.openedFiles:
raise fuse.FuseOSError(errno.ESTALE)
openedFile = self._resolveFileHandle(fh)
if isinstance(openedFile, int):
os.close(openedFile)
else:
openedFile.close()
del openedFile
return fh
@overrides(fuse.Operations)
def read(self, path: str, size: int, offset: int, fh: int) -> bytes:
if fh in self.openedFiles:
openedFile = self._resolveFileHandle(fh)
if isinstance(openedFile, int):
os.lseek(openedFile, offset, os.SEEK_SET)
return os.read(openedFile, size)
openedFile.seek(offset, os.SEEK_SET)
return openedFile.read(size)
# As far as I understand FUSE and my own file handle cache, this should never happen. But you never know.
if self.printDebug >= 1:
print("[Warning] Given file handle does not exist. Will open file before reading which might be slow.")
fileInfo = self._getFileInfo(path)
try:
return self.mountSource.read(fileInfo, size, offset)
except Exception as exception:
traceback.print_exc()
print("Caught exception when trying to read data from underlying TAR file! Returning errno.EIO.")
raise fuse.FuseOSError(errno.EIO) from exception
# Methods for the write overlay which require file handle translations
def _isWriteOverlayHandle(self, fh):
return self.writeOverlay and fh in self.openedFiles and isinstance(self._resolveFileHandle(fh), int)
def _resolveFileHandle(self, fh):
return self.openedFiles[fh][1]
@overrides(fuse.Operations)
def create(self, path, mode, fi=None):
if self.writeOverlay:
return self._addNewHandle(self.writeOverlay.create(path, mode, fi), 0)
raise fuse.FuseOSError(errno.EROFS)
@overrides(fuse.Operations)
def write(self, path, data, offset, fh):
if not self._isWriteOverlayHandle(fh):
flags, openedFile = self.openedFiles[fh]
if self.writeOverlay and not isinstance(openedFile, int) and (flags & (os.O_WRONLY | os.O_RDWR)):
openedFile.close()
self.openedFiles[fh] = (flags, self.writeOverlay.open(path, flags))
if self._isWriteOverlayHandle(fh):
return self.writeOverlay.write(path, data, offset, self._resolveFileHandle(fh))
raise fuse.FuseOSError(errno.EROFS)
@overrides(fuse.Operations)
def flush(self, path, fh):
if self._isWriteOverlayHandle(fh):
self.writeOverlay.flush(path, self._resolveFileHandle(fh))
return 0 # Nothing to flush, so return success
@overrides(fuse.Operations)
def fsync(self, path, datasync, fh):
if self._isWriteOverlayHandle(fh):
self.writeOverlay.fsync(path, datasync, self._resolveFileHandle(fh))
return 0 # Nothing to flush, so return success
@overrides(fuse.Operations)
def statfs(self, path):
# The filesystem block size is used, e.g., by Python as the default buffer size and therefore the
# default (p)read size when possible. For network file systems such as Lustre, or block compression
# such as in SquashFS, this proved to be highly insufficient to reach optimal performance!
# Note that there are some efforts to get rid of Python's behavior to use the block size and to
# increase the fixed default buffer size:
# https://github.com/python/cpython/issues/117151
if self.writeOverlay:
# Merge the block size from other mount sources while throwing away b_free and similar members
# that are set to 0 because those are read-only mount sources.
keys = ['f_bsize', 'f_frsize']
result = self.writeOverlay.statfs(path).copy()
result.update({key: value for key, value in self.mountSource.statfs().items() if key in keys})
result = self.mountSource.statfs()
# Use a relatively large minimum 256 KiB block size to direct filesystem users to use larger reads
# because they have a relative large overhead because of the fusepy, libfuse, kernel FUSE, SQLite,
# ratarmountcore, StenciledFile, and other layers.
for key in ['f_bsize', 'f_frsize']:
result[key] = max(result.get(key, 0), FuseMount.MINIMUM_BLOCK_SIZE)
return result
def checkInputFileType(
tarFile: str, encoding: str = tarfile.ENCODING, printDebug: int = 0
) -> Tuple[str, Optional[str]]:
"""Raises an exception if it is not an accepted archive format else returns the real path and compression type."""
splitURI = tarFile.split('://')
if len(splitURI) > 1:
protocol = splitURI[0]
if fsspec is None:
raise argparse.ArgumentTypeError("Detected an URI, but fsspec was not found. Try: pip install fsspec.")
if protocol not in fsspec.available_protocols():
raise argparse.ArgumentTypeError(
f"URI: {tarFile} uses an unknown protocol. Protocols known by fsspec are: "
+ ', '.join(fsspec.available_protocols())
)
return tarFile, None
if not os.path.isfile(tarFile):
raise argparse.ArgumentTypeError(f"File '{tarFile}' is not a file!")
tarFile = os.path.realpath(tarFile)
result = core.checkForSplitFile(tarFile)
if result:
return result[0][0], 'part' + result[1]
with open(tarFile, 'rb') as fileobj:
fileSize = os.stat(tarFile).st_size
# Header checks are enough for this step.
oldOffset = fileobj.tell()
compression = None
for compressionId, compressionInfo in supportedCompressions.items():
try:
if compressionInfo.checkHeader(fileobj):
compression = compressionId
break
finally:
fileobj.seek(oldOffset)
try:
# Determining if there are many frames in zstd is O(1) with is_multiframe
if compression != 'zst':
raise Exception() # early exit because we catch it anyways
formatOpen = findAvailableOpen(compression)
if not formatOpen:
raise Exception() # early exit because we catch it anyways
zstdFile = formatOpen(fileobj)
if not zstdFile.is_multiframe() and fileSize > 1024 * 1024:
print(f"[Warning] The specified file '{tarFile}'")
print("[Warning] is compressed using zstd but only contains one zstd frame. This makes it ")
print("[Warning] impossible to use true seeking! Please (re)compress your TAR using multiple ")
print("[Warning] frames in order for ratarmount to do be able to do fast seeking to requested ")
print("[Warning] files. Else, each file access will decompress the whole TAR from the beginning!")
print("[Warning] You can try out t2sz for creating such archives:")