fuse.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import argparse
  2. import logging
  3. import os
  4. import stat
  5. import threading
  6. import time
  7. from errno import EIO, ENOENT
  8. from fuse import FUSE, FuseOSError, LoggingMixIn, Operations
  9. from fsspec import __version__
  10. from fsspec.core import url_to_fs
  11. logger = logging.getLogger("fsspec.fuse")
  12. class FUSEr(Operations):
  13. def __init__(self, fs, path, ready_file=False):
  14. self.fs = fs
  15. self.cache = {}
  16. self.root = path.rstrip("/") + "/"
  17. self.counter = 0
  18. logger.info("Starting FUSE at %s", path)
  19. self._ready_file = ready_file
  20. def getattr(self, path, fh=None):
  21. logger.debug("getattr %s", path)
  22. if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
  23. return {"type": "file", "st_size": 5}
  24. path = "".join([self.root, path.lstrip("/")]).rstrip("/")
  25. try:
  26. info = self.fs.info(path)
  27. except FileNotFoundError as exc:
  28. raise FuseOSError(ENOENT) from exc
  29. data = {"st_uid": info.get("uid", 1000), "st_gid": info.get("gid", 1000)}
  30. perm = info.get("mode", 0o777)
  31. if info["type"] != "file":
  32. data["st_mode"] = stat.S_IFDIR | perm
  33. data["st_size"] = 0
  34. data["st_blksize"] = 0
  35. else:
  36. data["st_mode"] = stat.S_IFREG | perm
  37. data["st_size"] = info["size"]
  38. data["st_blksize"] = 5 * 2**20
  39. data["st_nlink"] = 1
  40. data["st_atime"] = info["atime"] if "atime" in info else time.time()
  41. data["st_ctime"] = info["ctime"] if "ctime" in info else time.time()
  42. data["st_mtime"] = info["mtime"] if "mtime" in info else time.time()
  43. return data
  44. def readdir(self, path, fh):
  45. logger.debug("readdir %s", path)
  46. path = "".join([self.root, path.lstrip("/")])
  47. files = self.fs.ls(path, False)
  48. files = [os.path.basename(f.rstrip("/")) for f in files]
  49. return [".", ".."] + files
  50. def mkdir(self, path, mode):
  51. path = "".join([self.root, path.lstrip("/")])
  52. self.fs.mkdir(path)
  53. return 0
  54. def rmdir(self, path):
  55. path = "".join([self.root, path.lstrip("/")])
  56. self.fs.rmdir(path)
  57. return 0
  58. def read(self, path, size, offset, fh):
  59. logger.debug("read %s", (path, size, offset))
  60. if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
  61. # status indicator
  62. return b"ready"
  63. f = self.cache[fh]
  64. f.seek(offset)
  65. out = f.read(size)
  66. return out
  67. def write(self, path, data, offset, fh):
  68. logger.debug("write %s", (path, offset))
  69. f = self.cache[fh]
  70. f.seek(offset)
  71. f.write(data)
  72. return len(data)
  73. def create(self, path, flags, fi=None):
  74. logger.debug("create %s", (path, flags))
  75. fn = "".join([self.root, path.lstrip("/")])
  76. self.fs.touch(fn) # OS will want to get attributes immediately
  77. f = self.fs.open(fn, "wb")
  78. self.cache[self.counter] = f
  79. self.counter += 1
  80. return self.counter - 1
  81. def open(self, path, flags):
  82. logger.debug("open %s", (path, flags))
  83. fn = "".join([self.root, path.lstrip("/")])
  84. if flags % 2 == 0:
  85. # read
  86. mode = "rb"
  87. else:
  88. # write/create
  89. mode = "wb"
  90. self.cache[self.counter] = self.fs.open(fn, mode)
  91. self.counter += 1
  92. return self.counter - 1
  93. def truncate(self, path, length, fh=None):
  94. fn = "".join([self.root, path.lstrip("/")])
  95. if length != 0:
  96. raise NotImplementedError
  97. # maybe should be no-op since open with write sets size to zero anyway
  98. self.fs.touch(fn)
  99. def unlink(self, path):
  100. fn = "".join([self.root, path.lstrip("/")])
  101. try:
  102. self.fs.rm(fn, False)
  103. except (OSError, FileNotFoundError) as exc:
  104. raise FuseOSError(EIO) from exc
  105. def release(self, path, fh):
  106. try:
  107. if fh in self.cache:
  108. f = self.cache[fh]
  109. f.close()
  110. self.cache.pop(fh)
  111. except Exception as e:
  112. print(e)
  113. return 0
  114. def chmod(self, path, mode):
  115. if hasattr(self.fs, "chmod"):
  116. path = "".join([self.root, path.lstrip("/")])
  117. return self.fs.chmod(path, mode)
  118. raise NotImplementedError
  119. def run(
  120. fs,
  121. path,
  122. mount_point,
  123. foreground=True,
  124. threads=False,
  125. ready_file=False,
  126. ops_class=FUSEr,
  127. ):
  128. """Mount stuff in a local directory
  129. This uses fusepy to make it appear as if a given path on an fsspec
  130. instance is in fact resident within the local file-system.
  131. This requires that fusepy by installed, and that FUSE be available on
  132. the system (typically requiring a package to be installed with
  133. apt, yum, brew, etc.).
  134. Parameters
  135. ----------
  136. fs: file-system instance
  137. From one of the compatible implementations
  138. path: str
  139. Location on that file-system to regard as the root directory to
  140. mount. Note that you typically should include the terminating "/"
  141. character.
  142. mount_point: str
  143. An empty directory on the local file-system where the contents of
  144. the remote path will appear.
  145. foreground: bool
  146. Whether or not calling this function will block. Operation will
  147. typically be more stable if True.
  148. threads: bool
  149. Whether or not to create threads when responding to file operations
  150. within the mounter directory. Operation will typically be more
  151. stable if False.
  152. ready_file: bool
  153. Whether the FUSE process is ready. The ``.fuse_ready`` file will
  154. exist in the ``mount_point`` directory if True. Debugging purpose.
  155. ops_class: FUSEr or Subclass of FUSEr
  156. To override the default behavior of FUSEr. For Example, logging
  157. to file.
  158. """
  159. func = lambda: FUSE(
  160. ops_class(fs, path, ready_file=ready_file),
  161. mount_point,
  162. nothreads=not threads,
  163. foreground=foreground,
  164. )
  165. if not foreground:
  166. th = threading.Thread(target=func)
  167. th.daemon = True
  168. th.start()
  169. return th
  170. else: # pragma: no cover
  171. try:
  172. func()
  173. except KeyboardInterrupt:
  174. pass
  175. def main(args):
  176. """Mount filesystem from chained URL to MOUNT_POINT.
  177. Examples:
  178. python3 -m fsspec.fuse memory /usr/share /tmp/mem
  179. python3 -m fsspec.fuse local /tmp/source /tmp/local \\
  180. -l /tmp/fsspecfuse.log
  181. You can also mount chained-URLs and use special settings:
  182. python3 -m fsspec.fuse 'filecache::zip::file://data.zip' \\
  183. / /tmp/zip \\
  184. -o 'filecache-cache_storage=/tmp/simplecache'
  185. You can specify the type of the setting by using `[int]` or `[bool]`,
  186. (`true`, `yes`, `1` represents the Boolean value `True`):
  187. python3 -m fsspec.fuse 'simplecache::ftp://ftp1.at.proftpd.org' \\
  188. /historic/packages/RPMS /tmp/ftp \\
  189. -o 'simplecache-cache_storage=/tmp/simplecache' \\
  190. -o 'simplecache-check_files=false[bool]' \\
  191. -o 'ftp-listings_expiry_time=60[int]' \\
  192. -o 'ftp-username=anonymous' \\
  193. -o 'ftp-password=xieyanbo'
  194. """
  195. class RawDescriptionArgumentParser(argparse.ArgumentParser):
  196. def format_help(self):
  197. usage = super().format_help()
  198. parts = usage.split("\n\n")
  199. parts[1] = self.description.rstrip()
  200. return "\n\n".join(parts)
  201. parser = RawDescriptionArgumentParser(prog="fsspec.fuse", description=main.__doc__)
  202. parser.add_argument("--version", action="version", version=__version__)
  203. parser.add_argument("url", type=str, help="fs url")
  204. parser.add_argument("source_path", type=str, help="source directory in fs")
  205. parser.add_argument("mount_point", type=str, help="local directory")
  206. parser.add_argument(
  207. "-o",
  208. "--option",
  209. action="append",
  210. help="Any options of protocol included in the chained URL",
  211. )
  212. parser.add_argument(
  213. "-l", "--log-file", type=str, help="Logging FUSE debug info (Default: '')"
  214. )
  215. parser.add_argument(
  216. "-f",
  217. "--foreground",
  218. action="store_false",
  219. help="Running in foreground or not (Default: False)",
  220. )
  221. parser.add_argument(
  222. "-t",
  223. "--threads",
  224. action="store_false",
  225. help="Running with threads support (Default: False)",
  226. )
  227. parser.add_argument(
  228. "-r",
  229. "--ready-file",
  230. action="store_false",
  231. help="The `.fuse_ready` file will exist after FUSE is ready. "
  232. "(Debugging purpose, Default: False)",
  233. )
  234. args = parser.parse_args(args)
  235. kwargs = {}
  236. for item in args.option or []:
  237. key, sep, value = item.partition("=")
  238. if not sep:
  239. parser.error(message=f"Wrong option: {item!r}")
  240. val = value.lower()
  241. if val.endswith("[int]"):
  242. value = int(value[: -len("[int]")])
  243. elif val.endswith("[bool]"):
  244. value = val[: -len("[bool]")] in ["1", "yes", "true"]
  245. if "-" in key:
  246. fs_name, setting_name = key.split("-", 1)
  247. if fs_name in kwargs:
  248. kwargs[fs_name][setting_name] = value
  249. else:
  250. kwargs[fs_name] = {setting_name: value}
  251. else:
  252. kwargs[key] = value
  253. if args.log_file:
  254. logging.basicConfig(
  255. level=logging.DEBUG,
  256. filename=args.log_file,
  257. format="%(asctime)s %(message)s",
  258. )
  259. class LoggingFUSEr(FUSEr, LoggingMixIn):
  260. pass
  261. fuser = LoggingFUSEr
  262. else:
  263. fuser = FUSEr
  264. fs, url_path = url_to_fs(args.url, **kwargs)
  265. logger.debug("Mounting %s to %s", url_path, str(args.mount_point))
  266. run(
  267. fs,
  268. args.source_path,
  269. args.mount_point,
  270. foreground=args.foreground,
  271. threads=args.threads,
  272. ready_file=args.ready_file,
  273. ops_class=fuser,
  274. )
  275. if __name__ == "__main__":
  276. import sys
  277. main(sys.argv[1:])