fuse.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. from collections import defaultdict
  2. import errno
  3. import io
  4. import llfuse
  5. import os
  6. import stat
  7. import tempfile
  8. import time
  9. from signal import SIGINT
  10. from distutils.version import LooseVersion
  11. import msgpack
  12. from .archive import Archive
  13. from .helpers import daemonize, bigint_to_int
  14. from .logger import create_logger
  15. from .lrucache import LRUCache
  16. logger = create_logger()
  17. # Does this version of llfuse support ns precision?
  18. have_fuse_xtime_ns = hasattr(llfuse.EntryAttributes, 'st_mtime_ns')
  19. fuse_version = LooseVersion(getattr(llfuse, '__version__', '0.1'))
  20. if fuse_version >= '0.42':
  21. def fuse_main():
  22. return llfuse.main(workers=1)
  23. else:
  24. def fuse_main():
  25. llfuse.main(single=True)
  26. return None
  27. class ItemCache:
  28. def __init__(self):
  29. self.fd = tempfile.TemporaryFile(prefix='borg-tmp')
  30. self.offset = 1000000
  31. def add(self, item):
  32. pos = self.fd.seek(0, io.SEEK_END)
  33. self.fd.write(msgpack.packb(item))
  34. return pos + self.offset
  35. def get(self, inode):
  36. self.fd.seek(inode - self.offset, io.SEEK_SET)
  37. return next(msgpack.Unpacker(self.fd, read_size=1024))
  38. class FuseOperations(llfuse.Operations):
  39. """Export archive as a fuse filesystem
  40. """
  41. allow_damaged_files = False
  42. def __init__(self, key, repository, manifest, archive, cached_repo):
  43. super().__init__()
  44. self._inode_count = 0
  45. self.key = key
  46. self.repository = cached_repo
  47. self.items = {}
  48. self.parent = {}
  49. self.contents = defaultdict(dict)
  50. self.default_dir = {b'mode': 0o40755, b'mtime': int(time.time() * 1e9), b'uid': os.getuid(), b'gid': os.getgid()}
  51. self.pending_archives = {}
  52. self.accounted_chunks = {}
  53. self.cache = ItemCache()
  54. data_cache_capacity = int(os.environ.get('BORG_MOUNT_DATA_CACHE_ENTRIES', os.cpu_count() or 1))
  55. logger.debug('mount data cache capacity: %d chunks', data_cache_capacity)
  56. self.data_cache = LRUCache(capacity=data_cache_capacity, dispose=lambda _: None)
  57. self._create_dir(parent=1) # first call, create root dir (inode == 1)
  58. if archive:
  59. self.process_archive(archive)
  60. else:
  61. for archive_name in manifest.archives:
  62. # Create archive placeholder inode
  63. archive_inode = self._create_dir(parent=1)
  64. self.contents[1][os.fsencode(archive_name)] = archive_inode
  65. self.pending_archives[archive_inode] = Archive(repository, key, manifest, archive_name)
  66. def mount(self, mountpoint, mount_options, foreground=False):
  67. """Mount filesystem on *mountpoint* with *mount_options*."""
  68. options = ['fsname=borgfs', 'ro']
  69. if mount_options:
  70. options.extend(mount_options.split(','))
  71. try:
  72. options.remove('allow_damaged_files')
  73. self.allow_damaged_files = True
  74. except ValueError:
  75. pass
  76. llfuse.init(self, mountpoint, options)
  77. if not foreground:
  78. daemonize()
  79. # If the file system crashes, we do not want to umount because in that
  80. # case the mountpoint suddenly appears to become empty. This can have
  81. # nasty consequences, imagine the user has e.g. an active rsync mirror
  82. # job - seeing the mountpoint empty, rsync would delete everything in the
  83. # mirror.
  84. umount = False
  85. try:
  86. signal = fuse_main()
  87. # no crash and no signal (or it's ^C and we're in the foreground) -> umount request
  88. umount = (signal is None or (signal == SIGINT and foreground))
  89. finally:
  90. llfuse.close(umount)
  91. def _create_dir(self, parent):
  92. """Create directory
  93. """
  94. ino = self.allocate_inode()
  95. self.items[ino] = self.default_dir
  96. self.parent[ino] = parent
  97. return ino
  98. def process_archive(self, archive, prefix=[]):
  99. """Build fuse inode hierarchy from archive metadata
  100. """
  101. unpacker = msgpack.Unpacker()
  102. for key, chunk in zip(archive.metadata[b'items'], self.repository.get_many(archive.metadata[b'items'])):
  103. data = self.key.decrypt(key, chunk)
  104. unpacker.feed(data)
  105. for item in unpacker:
  106. try:
  107. # This can happen if an archive was created with a command line like
  108. # $ borg create ... dir1/file dir1
  109. # In this case the code below will have created a default_dir inode for dir1 already.
  110. inode = self._find_inode(item[b'path'], prefix)
  111. except KeyError:
  112. pass
  113. else:
  114. self.items[inode] = item
  115. continue
  116. path = item.pop(b'path')
  117. segments = prefix + os.fsencode(os.path.normpath(path)).split(b'/')
  118. num_segments = len(segments)
  119. parent = 1
  120. for i, segment in enumerate(segments, 1):
  121. # Leaf segment?
  122. if i == num_segments:
  123. if b'source' in item and stat.S_ISREG(item[b'mode']):
  124. try:
  125. inode = self._find_inode(item[b'source'], prefix)
  126. except KeyError:
  127. file = path.decode(errors='surrogateescape')
  128. source = item[b'source'].decode(errors='surrogateescape')
  129. logger.warning('Skipping broken hard link: %s -> %s', file, source)
  130. continue
  131. item = self.cache.get(inode)
  132. item[b'nlink'] = item.get(b'nlink', 1) + 1
  133. self.items[inode] = item
  134. else:
  135. inode = self.cache.add(item)
  136. self.parent[inode] = parent
  137. if segment:
  138. self.contents[parent][segment] = inode
  139. elif segment in self.contents[parent]:
  140. parent = self.contents[parent][segment]
  141. else:
  142. inode = self._create_dir(parent)
  143. if segment:
  144. self.contents[parent][segment] = inode
  145. parent = inode
  146. def allocate_inode(self):
  147. self._inode_count += 1
  148. return self._inode_count
  149. def statfs(self, ctx=None):
  150. stat_ = llfuse.StatvfsData()
  151. stat_.f_bsize = 512
  152. stat_.f_frsize = 512
  153. stat_.f_blocks = 0
  154. stat_.f_bfree = 0
  155. stat_.f_bavail = 0
  156. stat_.f_files = 0
  157. stat_.f_ffree = 0
  158. stat_.f_favail = 0
  159. return stat_
  160. def get_item(self, inode):
  161. try:
  162. return self.items[inode]
  163. except KeyError:
  164. return self.cache.get(inode)
  165. def _find_inode(self, path, prefix=[]):
  166. segments = prefix + os.fsencode(os.path.normpath(path)).split(b'/')
  167. inode = 1
  168. for segment in segments:
  169. inode = self.contents[inode][segment]
  170. return inode
  171. def getattr(self, inode, ctx=None):
  172. item = self.get_item(inode)
  173. size = 0
  174. dsize = 0
  175. try:
  176. for key, chunksize, _ in item[b'chunks']:
  177. size += chunksize
  178. if self.accounted_chunks.get(key, inode) == inode:
  179. self.accounted_chunks[key] = inode
  180. dsize += chunksize
  181. except KeyError:
  182. pass
  183. entry = llfuse.EntryAttributes()
  184. entry.st_ino = inode
  185. entry.generation = 0
  186. entry.entry_timeout = 300
  187. entry.attr_timeout = 300
  188. entry.st_mode = item[b'mode']
  189. entry.st_nlink = item.get(b'nlink', 1)
  190. entry.st_uid = item[b'uid']
  191. entry.st_gid = item[b'gid']
  192. entry.st_rdev = item.get(b'rdev', 0)
  193. entry.st_size = size
  194. entry.st_blksize = 512
  195. entry.st_blocks = (dsize + entry.st_blksize - 1) // entry.st_blksize
  196. # note: older archives only have mtime (not atime nor ctime)
  197. if have_fuse_xtime_ns:
  198. entry.st_mtime_ns = bigint_to_int(item[b'mtime'])
  199. if b'atime' in item:
  200. entry.st_atime_ns = bigint_to_int(item[b'atime'])
  201. else:
  202. entry.st_atime_ns = bigint_to_int(item[b'mtime'])
  203. if b'ctime' in item:
  204. entry.st_ctime_ns = bigint_to_int(item[b'ctime'])
  205. else:
  206. entry.st_ctime_ns = bigint_to_int(item[b'mtime'])
  207. else:
  208. entry.st_mtime = bigint_to_int(item[b'mtime']) / 1e9
  209. if b'atime' in item:
  210. entry.st_atime = bigint_to_int(item[b'atime']) / 1e9
  211. else:
  212. entry.st_atime = bigint_to_int(item[b'mtime']) / 1e9
  213. if b'ctime' in item:
  214. entry.st_ctime = bigint_to_int(item[b'ctime']) / 1e9
  215. else:
  216. entry.st_ctime = bigint_to_int(item[b'mtime']) / 1e9
  217. return entry
  218. def listxattr(self, inode, ctx=None):
  219. item = self.get_item(inode)
  220. return item.get(b'xattrs', {}).keys()
  221. def getxattr(self, inode, name, ctx=None):
  222. item = self.get_item(inode)
  223. try:
  224. return item.get(b'xattrs', {})[name]
  225. except KeyError:
  226. raise llfuse.FUSEError(llfuse.ENOATTR) from None
  227. def _load_pending_archive(self, inode):
  228. # Check if this is an archive we need to load
  229. archive = self.pending_archives.pop(inode, None)
  230. if archive:
  231. self.process_archive(archive, [os.fsencode(archive.name)])
  232. def lookup(self, parent_inode, name, ctx=None):
  233. self._load_pending_archive(parent_inode)
  234. if name == b'.':
  235. inode = parent_inode
  236. elif name == b'..':
  237. inode = self.parent[parent_inode]
  238. else:
  239. inode = self.contents[parent_inode].get(name)
  240. if not inode:
  241. raise llfuse.FUSEError(errno.ENOENT)
  242. return self.getattr(inode)
  243. def open(self, inode, flags, ctx=None):
  244. if not self.allow_damaged_files:
  245. item = self.get_item(inode)
  246. if b'chunks_healthy' in item:
  247. # Processed archive items don't carry the path anymore; for converting the inode
  248. # to the path we'd either have to store the inverse of the current structure,
  249. # or search the entire archive. So we just don't print it. It's easy to correlate anyway.
  250. logger.warning('File has damaged (all-zero) chunks. Try running borg check --repair. '
  251. 'Mount with allow_damaged_files to read damaged files.')
  252. raise llfuse.FUSEError(errno.EIO)
  253. return inode
  254. def opendir(self, inode, ctx=None):
  255. self._load_pending_archive(inode)
  256. return inode
  257. def read(self, fh, offset, size):
  258. parts = []
  259. item = self.get_item(fh)
  260. for id, s, csize in item[b'chunks']:
  261. if s < offset:
  262. offset -= s
  263. continue
  264. n = min(size, s - offset)
  265. if id in self.data_cache:
  266. data = self.data_cache[id]
  267. if offset + n == len(data):
  268. # evict fully read chunk from cache
  269. del self.data_cache[id]
  270. else:
  271. data = self.key.decrypt(id, self.repository.get(id))
  272. if offset + n < len(data):
  273. # chunk was only partially read, cache it
  274. self.data_cache[id] = data
  275. parts.append(data[offset:offset + n])
  276. offset = 0
  277. size -= n
  278. if not size:
  279. break
  280. return b''.join(parts)
  281. def readdir(self, fh, off):
  282. entries = [(b'.', fh), (b'..', self.parent[fh])]
  283. entries.extend(self.contents[fh].items())
  284. for i, (name, inode) in enumerate(entries[off:], off):
  285. yield name, self.getattr(inode), i + 1
  286. def readlink(self, inode, ctx=None):
  287. item = self.get_item(inode)
  288. return os.fsencode(item[b'source'])