13 import arvados.commands._util as arv_cmd
14 from arvados_fuse import crunchstat
15 from arvados_fuse import *
16 from arvados_fuse.unmount import unmount
17 from arvados_fuse._version import __version__
19 class ArgumentParser(argparse.ArgumentParser):
21 super(ArgumentParser, self).__init__(
22 parents=[arv_cmd.retry_opt],
23 description='''Mount Keep data under the local filesystem. Default mode is --home''',
25 Note: When using the --exec feature, you must either specify the
26 mountpoint before --exec, or mark the end of your --exec arguments
29 self.add_argument('--version', action='version',
30 version="%s %s" % (sys.argv[0], __version__),
31 help='Print version and exit.')
32 self.add_argument('mountpoint', type=str, help="""Mount point.""")
33 self.add_argument('--allow-other', action='store_true',
34 help="""Let other users read the mount""")
35 self.add_argument('--subtype', type=str, metavar='STRING',
36 help="""Report mounted filesystem type as "fuse.STRING", instead of just "fuse".""")
38 mode = self.add_mutually_exclusive_group()
40 mode.add_argument('--all', action='store_const', const='all', dest='mode',
41 help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default if no --mount-* arguments are given).""")
42 mode.add_argument('--custom', action='store_const', const=None, dest='mode',
43 help="""Mount a top level meta-directory with subdirectories as specified by additional --mount-* arguments (default if any --mount-* arguments are given).""")
44 mode.add_argument('--home', action='store_const', const='home', dest='mode',
45 help="""Mount only the user's home project.""")
46 mode.add_argument('--shared', action='store_const', const='shared', dest='mode',
47 help="""Mount only list of projects shared with the user.""")
48 mode.add_argument('--by-tag', action='store_const', const='by_tag', dest='mode',
49 help="""Mount subdirectories listed by tag.""")
50 mode.add_argument('--by-id', action='store_const', const='by_id', dest='mode',
51 help="""Mount subdirectories listed by portable data hash or uuid.""")
52 mode.add_argument('--by-pdh', action='store_const', const='by_pdh', dest='mode',
53 help="""Mount subdirectories listed by portable data hash.""")
54 mode.add_argument('--project', type=str, metavar='UUID',
55 help="""Mount the specified project.""")
56 mode.add_argument('--collection', type=str, metavar='UUID_or_PDH',
57 help="""Mount only the specified collection.""")
59 mounts = self.add_argument_group('Custom mount options')
60 mounts.add_argument('--mount-by-pdh',
61 type=str, metavar='PATH', action='append', default=[],
62 help="Mount each readable collection at mountpoint/PATH/P where P is the collection's portable data hash.")
63 mounts.add_argument('--mount-by-id',
64 type=str, metavar='PATH', action='append', default=[],
65 help="Mount each readable collection at mountpoint/PATH/UUID and mountpoint/PATH/PDH where PDH is the collection's portable data hash and UUID is its UUID.")
66 mounts.add_argument('--mount-by-tag',
67 type=str, metavar='PATH', action='append', default=[],
68 help="Mount all collections with tag TAG at mountpoint/PATH/TAG/UUID.")
69 mounts.add_argument('--mount-home',
70 type=str, metavar='PATH', action='append', default=[],
71 help="Mount the current user's home project at mountpoint/PATH.")
72 mounts.add_argument('--mount-shared',
73 type=str, metavar='PATH', action='append', default=[],
74 help="Mount projects shared with the current user at mountpoint/PATH.")
75 mounts.add_argument('--mount-tmp',
76 type=str, metavar='PATH', action='append', default=[],
77 help="Create a new collection, mount it in read/write mode at mountpoint/PATH, and delete it when unmounting.")
79 self.add_argument('--debug', action='store_true', help="""Debug mode""")
80 self.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
81 self.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
82 self.add_argument('--encoding', type=str, help="Character encoding to use for filesystem, default is utf-8 (see Python codec registry for list of available encodings)", default="utf-8")
84 self.add_argument('--file-cache', type=int, help="File data cache size, in bytes (default 256MiB)", default=256*1024*1024)
85 self.add_argument('--directory-cache', type=int, help="Directory data cache size, in bytes (default 128MiB)", default=128*1024*1024)
87 self.add_argument('--disable-event-listening', action='store_true', help="Don't subscribe to events on the API server", dest="disable_event_listening", default=False)
89 self.add_argument('--read-only', action='store_false', help="Mount will be read only (default)", dest="enable_write", default=False)
90 self.add_argument('--read-write', action='store_true', help="Mount will be read-write", dest="enable_write", default=False)
92 self.add_argument('--crunchstat-interval', type=float, help="Write stats to stderr every N seconds (default disabled)", default=0)
94 unmount = self.add_mutually_exclusive_group()
95 unmount.add_argument('--unmount', action='store_true', default=False,
96 help="Forcefully unmount the specified mountpoint (if it's a fuse mount) and exit. If --subtype is given, unmount only if the mount has the specified subtype. WARNING: This command can affect any kind of fuse mount, not just arv-mount.")
97 unmount.add_argument('--unmount-all', action='store_true', default=False,
98 help="Forcefully unmount every fuse mount at or below the specified path and exit. If --subtype is given, unmount only mounts that have the specified subtype. Exit non-zero if any other types of mounts are found at or below the given path. WARNING: This command can affect any kind of fuse mount, not just arv-mount.")
99 unmount.add_argument('--replace', action='store_true', default=False,
100 help="If a fuse mount is already present at mountpoint, forcefully unmount it before mounting")
101 self.add_argument('--unmount-timeout',
102 type=float, default=2.0,
103 help="Time to wait for graceful shutdown after --exec program exits and filesystem is unmounted")
105 self.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
106 dest="exec_args", metavar=('command', 'args', '...', '--'),
107 help="""Mount, run a command, then unmount and exit""")
111 def __init__(self, args, logger=logging.getLogger('arvados.arv-mount')):
115 self.listen_for_events = False
117 self.args.mountpoint = os.path.realpath(self.args.mountpoint)
118 if self.args.logfile:
119 self.args.logfile = os.path.realpath(self.args.logfile)
122 self._setup_logging()
125 except Exception as e:
126 self.logger.exception("arv-mount: exception during setup: %s", e)
130 if self.args.replace:
131 unmount(path=self.args.mountpoint,
132 timeout=self.args.unmount_timeout)
133 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
135 daemon.DaemonContext(
136 working_directory=os.path.dirname(self.args.mountpoint),
137 files_preserve=range(
138 3, resource.getrlimit(resource.RLIMIT_NOFILE)[1])
140 if self.listen_for_events and not self.args.disable_event_listening:
141 self.operations.listen_for_events()
142 self.llfuse_thread = threading.Thread(None, lambda: self._llfuse_main())
143 self.llfuse_thread.daemon = True
144 self.llfuse_thread.start()
145 self.operations.initlock.wait()
148 def __exit__(self, exc_type, exc_value, traceback):
149 if self.operations.events:
150 self.operations.events.close(timeout=self.args.unmount_timeout)
151 subprocess.call(["fusermount", "-u", "-z", self.args.mountpoint])
152 self.llfuse_thread.join(timeout=self.args.unmount_timeout)
153 if self.llfuse_thread.is_alive():
154 self.logger.warning("Mount.__exit__:"
155 " llfuse thread still alive %fs after umount"
156 " -- abandoning and exiting anyway",
157 self.args.unmount_timeout)
160 if self.args.unmount or self.args.unmount_all:
161 unmount(path=self.args.mountpoint,
162 subtype=self.args.subtype,
163 timeout=self.args.unmount_timeout,
164 recursive=self.args.unmount_all)
165 elif self.args.exec_args:
168 self._run_standalone()
170 def _fuse_options(self):
171 """FUSE mount options; see mount.fuse(8)"""
172 opts = [optname for optname in ['allow_other', 'debug']
173 if getattr(self.args, optname)]
174 # Increase default read/write size from 4KiB to 128KiB
175 opts += ["big_writes", "max_read=131072"]
176 if self.args.subtype:
177 opts += ["subtype="+self.args.subtype]
180 def _setup_logging(self):
181 # Configure a log handler based on command-line switches.
182 if self.args.logfile:
183 log_handler = logging.FileHandler(self.args.logfile)
184 log_handler.setFormatter(logging.Formatter(
185 '%(asctime)s %(name)s[%(process)d] %(levelname)s: %(message)s',
186 '%Y-%m-%d %H:%M:%S'))
190 if log_handler is not None:
191 arvados.logger.removeHandler(arvados.log_handler)
192 arvados.logger.addHandler(log_handler)
195 arvados.logger.setLevel(logging.DEBUG)
196 logging.getLogger('arvados.keep').setLevel(logging.DEBUG)
197 logging.getLogger('arvados.api').setLevel(logging.DEBUG)
198 logging.getLogger('arvados.collection').setLevel(logging.DEBUG)
199 self.logger.debug("arv-mount debugging enabled")
201 self.logger.info("enable write is %s", self.args.enable_write)
203 def _setup_api(self):
204 self.api = arvados.safeapi.ThreadSafeApiCache(
205 apiconfig=arvados.config.settings(),
207 'block_cache': arvados.keep.KeepBlockCache(self.args.file_cache),
208 'num_retries': self.args.retries,
210 # Do a sanity check that we have a working arvados host + token.
211 self.api.users().current().execute()
213 def _setup_mount(self):
214 self.operations = Operations(
218 encoding=self.args.encoding,
219 inode_cache=InodeCache(cap=self.args.directory_cache),
220 enable_write=self.args.enable_write)
222 if self.args.crunchstat_interval:
223 statsthread = threading.Thread(
224 target=crunchstat.statlogger,
225 args=(self.args.crunchstat_interval,
228 statsthread.daemon = True
231 usr = self.api.users().current().execute(num_retries=self.args.retries)
234 dir_args = [llfuse.ROOT_INODE, self.operations.inodes, self.api, self.args.retries]
237 if self.args.collection is not None:
238 # Set up the request handler with the collection at the root
239 # First check that the collection is readable
240 self.api.collections().get(uuid=self.args.collection).execute()
241 self.args.mode = 'collection'
242 dir_class = CollectionDirectory
243 dir_args.append(self.args.collection)
244 elif self.args.project is not None:
245 self.args.mode = 'project'
246 dir_class = ProjectDirectory
248 self.api.groups().get(uuid=self.args.project).execute(
249 num_retries=self.args.retries))
251 if (self.args.mount_by_id or
252 self.args.mount_by_pdh or
253 self.args.mount_by_tag or
254 self.args.mount_home or
255 self.args.mount_shared or
256 self.args.mount_tmp):
257 if self.args.mode is not None:
259 "Cannot combine '{}' mode with custom --mount-* options.".
260 format(self.args.mode))
261 elif self.args.mode is None:
262 # If no --mount-custom or custom mount args, --all is the default
263 self.args.mode = 'all'
265 if self.args.mode in ['by_id', 'by_pdh']:
266 # Set up the request handler with the 'magic directory' at the root
267 dir_class = MagicDirectory
268 dir_args.append(self.args.mode == 'by_pdh')
269 elif self.args.mode == 'by_tag':
270 dir_class = TagsDirectory
271 elif self.args.mode == 'shared':
272 dir_class = SharedDirectory
274 elif self.args.mode == 'home':
275 dir_class = ProjectDirectory
277 dir_args.append(True)
278 elif self.args.mode == 'all':
279 self.args.mount_by_id = ['by_id']
280 self.args.mount_by_tag = ['by_tag']
281 self.args.mount_home = ['home']
282 self.args.mount_shared = ['shared']
285 if dir_class is not None:
286 ent = dir_class(*dir_args)
287 self.operations.inodes.add_entry(ent)
288 self.listen_for_events = ent.want_event_subscribe()
291 e = self.operations.inodes.add_entry(Directory(
292 llfuse.ROOT_INODE, self.operations.inodes))
293 dir_args[0] = e.inode
295 for name in self.args.mount_by_id:
296 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=False))
297 for name in self.args.mount_by_pdh:
298 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=True))
299 for name in self.args.mount_by_tag:
300 self._add_mount(e, name, TagsDirectory(*dir_args))
301 for name in self.args.mount_home:
302 self._add_mount(e, name, ProjectDirectory(*dir_args, project_object=usr, poll=True))
303 for name in self.args.mount_shared:
304 self._add_mount(e, name, SharedDirectory(*dir_args, exclude=usr, poll=True))
305 for name in self.args.mount_tmp:
306 self._add_mount(e, name, TmpCollectionDirectory(*dir_args))
309 text = self._readme_text(
310 arvados.config.get('ARVADOS_API_HOST'),
312 self._add_mount(e, 'README', StringFile(e.inode, text, now))
314 def _add_mount(self, tld, name, ent):
315 if name in ['', '.', '..'] or '/' in name:
316 sys.exit("Mount point '{}' is not supported.".format(name))
317 tld._entries[name] = self.operations.inodes.add_entry(ent)
318 self.listen_for_events = (self.listen_for_events or ent.want_event_subscribe())
320 def _readme_text(self, api_host, user_email):
322 Welcome to Arvados! This directory provides file system access to
323 files and objects available on the Arvados installation located at
324 '{}' using credentials for user '{}'.
326 From here, the following directories are available:
328 by_id/ Access to Keep collections by uuid or portable data hash (see by_id/README for details).
329 by_tag/ Access to Keep collections organized by tag.
330 home/ The contents of your home project.
331 shared/ Projects shared with you.
333 '''.format(api_host, user_email)
339 sp = subprocess.Popen(self.args.exec_args, shell=False)
341 # forward signals to the process.
342 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
343 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
344 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
346 # wait for process to complete.
349 # restore default signal handlers.
350 signal.signal(signal.SIGINT, signal.SIG_DFL)
351 signal.signal(signal.SIGTERM, signal.SIG_DFL)
352 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
353 except Exception as e:
354 self.logger.exception(
355 'arv-mount: exception during exec %s', self.args.exec_args)
358 except AttributeError:
362 def _run_standalone(self):
364 self.daemon = not self.args.foreground
366 self.llfuse_thread.join(timeout=None)
367 except Exception as e:
368 self.logger.exception('arv-mount: exception during mount: %s', e)
369 exit(getattr(e, 'errno', 1))
372 def _llfuse_main(self):
376 llfuse.close(unmount=False)