fuse.py 11 KB

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