13 import arvados.commands._util as arv_cmd
14 from arvados_fuse import *
15 from arvados_fuse._version import __version__
17 class ArgumentParser(argparse.ArgumentParser):
19 super(ArgumentParser, self).__init__(
20 parents=[arv_cmd.retry_opt],
21 description='''Mount Keep data under the local filesystem. Default mode is --home''',
23 Note: When using the --exec feature, you must either specify the
24 mountpoint before --exec, or mark the end of your --exec arguments
27 self.add_argument('--version', action='version',
28 version="%s %s" % (sys.argv[0], __version__),
29 help='Print version and exit.')
30 self.add_argument('mountpoint', type=str, help="""Mount point.""")
31 self.add_argument('--allow-other', action='store_true',
32 help="""Let other users read the mount""")
33 self.add_argument('--subtype', type=str, metavar='STRING',
34 help="""Report mounted filesystem type as "fuse.STRING", instead of just "fuse".""")
36 mode = self.add_mutually_exclusive_group()
38 mode.add_argument('--all', action='store_const', const='all', dest='mode',
39 help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default if no --mount-* arguments are given).""")
40 mode.add_argument('--custom', action='store_const', const=None, dest='mode',
41 help="""Mount a top level meta-directory with subdirectories as specified by additional --mount-* arguments (default if any --mount-* arguments are given).""")
42 mode.add_argument('--home', action='store_const', const='home', dest='mode',
43 help="""Mount only the user's home project.""")
44 mode.add_argument('--shared', action='store_const', const='shared', dest='mode',
45 help="""Mount only list of projects shared with the user.""")
46 mode.add_argument('--by-tag', action='store_const', const='by_tag', dest='mode',
47 help="""Mount subdirectories listed by tag.""")
48 mode.add_argument('--by-id', action='store_const', const='by_id', dest='mode',
49 help="""Mount subdirectories listed by portable data hash or uuid.""")
50 mode.add_argument('--by-pdh', action='store_const', const='by_pdh', dest='mode',
51 help="""Mount subdirectories listed by portable data hash.""")
52 mode.add_argument('--project', type=str, metavar='UUID',
53 help="""Mount the specified project.""")
54 mode.add_argument('--collection', type=str, metavar='UUID_or_PDH',
55 help="""Mount only the specified collection.""")
57 mounts = self.add_argument_group('Custom mount options')
58 mounts.add_argument('--mount-by-pdh',
59 type=str, metavar='PATH', action='append', default=[],
60 help="Mount each readable collection at mountpoint/PATH/P where P is the collection's portable data hash.")
61 mounts.add_argument('--mount-by-id',
62 type=str, metavar='PATH', action='append', default=[],
63 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.")
64 mounts.add_argument('--mount-by-tag',
65 type=str, metavar='PATH', action='append', default=[],
66 help="Mount all collections with tag TAG at mountpoint/PATH/TAG/UUID.")
67 mounts.add_argument('--mount-home',
68 type=str, metavar='PATH', action='append', default=[],
69 help="Mount the current user's home project at mountpoint/PATH.")
70 mounts.add_argument('--mount-shared',
71 type=str, metavar='PATH', action='append', default=[],
72 help="Mount projects shared with the current user at mountpoint/PATH.")
73 mounts.add_argument('--mount-tmp',
74 type=str, metavar='PATH', action='append', default=[],
75 help="Create a new collection, mount it in read/write mode at mountpoint/PATH, and delete it when unmounting.")
77 self.add_argument('--debug', action='store_true', help="""Debug mode""")
78 self.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
79 self.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
80 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")
82 self.add_argument('--file-cache', type=int, help="File data cache size, in bytes (default 256MiB)", default=256*1024*1024)
83 self.add_argument('--directory-cache', type=int, help="Directory data cache size, in bytes (default 128MiB)", default=128*1024*1024)
85 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)
87 self.add_argument('--read-only', action='store_false', help="Mount will be read only (default)", dest="enable_write", default=False)
88 self.add_argument('--read-write', action='store_true', help="Mount will be read-write", dest="enable_write", default=False)
90 self.add_argument('--crunchstat-interval', type=float, help="Write stats to stderr every N seconds (default disabled)", default=0)
92 self.add_argument('--unmount', action='store_true', default=False,
93 help="Forcefully unmount the specified mountpoint (if it's a fuse mount) and exit. Use /path/... to unmount all fuse mounts below /path as well as /path itself.")
94 self.add_argument('--replace', action='store_true', default=False,
95 help="If a fuse mount is already present at mountpoint, forcefully unmount it before mounting")
96 self.add_argument('--unmount-timeout',
97 type=float, default=2.0,
98 help="Time to wait for graceful shutdown after --exec program exits and filesystem is unmounted")
100 self.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
101 dest="exec_args", metavar=('command', 'args', '...', '--'),
102 help="""Mount, run a command, then unmount and exit""")
106 def __init__(self, args, logger=logging.getLogger('arvados.arv-mount')):
109 self.listen_for_events = False
111 self.args.mountpoint = os.path.realpath(self.args.mountpoint)
112 if self.args.logfile:
113 self.args.logfile = os.path.realpath(self.args.logfile)
116 self._setup_logging()
119 except Exception as e:
120 self.logger.exception("arv-mount: exception during setup: %s", e)
124 if self.args.replace:
125 unmount(self.args.mountpoint, timeout=self.args.unmount_timeout)
126 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
127 if self.listen_for_events and not self.args.disable_event_listening:
128 self.operations.listen_for_events()
129 self.llfuse_thread = threading.Thread(None, lambda: self._llfuse_main())
130 self.llfuse_thread.daemon = True
131 self.llfuse_thread.start()
132 self.operations.initlock.wait()
135 def __exit__(self, exc_type, exc_value, traceback):
136 if self.operations.events:
137 self.operations.events.close(timeout=self.args.unmount_timeout)
138 subprocess.call(["fusermount", "-u", "-z", self.args.mountpoint])
139 self.llfuse_thread.join(timeout=self.args.unmount_timeout)
140 if self.llfuse_thread.is_alive():
141 self.logger.warning("Mount.__exit__:"
142 " llfuse thread still alive %fs after umount"
143 " -- abandoning and exiting anyway",
144 self.args.unmount_timeout)
147 if self.args.unmount:
148 unmount_all(self.args.mountpoint, timeout=self.args.unmount_timeout)
149 elif self.args.exec_args:
152 self._run_standalone()
154 def _fuse_options(self):
155 """FUSE mount options; see mount.fuse(8)"""
156 opts = [optname for optname in ['allow_other', 'debug']
157 if getattr(self.args, optname)]
158 # Increase default read/write size from 4KiB to 128KiB
159 opts += ["big_writes", "max_read=131072"]
160 if self.args.subtype:
161 opts += ["subtype="+self.args.subtype]
164 def _setup_logging(self):
165 # Configure a log handler based on command-line switches.
166 if self.args.logfile:
167 log_handler = logging.FileHandler(self.args.logfile)
168 log_handler.setFormatter(logging.Formatter(
169 '%(asctime)s %(name)s[%(process)d] %(levelname)s: %(message)s',
170 '%Y-%m-%d %H:%M:%S'))
174 if log_handler is not None:
175 arvados.logger.removeHandler(arvados.log_handler)
176 arvados.logger.addHandler(log_handler)
179 arvados.logger.setLevel(logging.DEBUG)
180 logging.getLogger('arvados.keep').setLevel(logging.DEBUG)
181 logging.getLogger('arvados.api').setLevel(logging.DEBUG)
182 logging.getLogger('arvados.collection').setLevel(logging.DEBUG)
183 self.logger.debug("arv-mount debugging enabled")
185 self.logger.info("enable write is %s", self.args.enable_write)
187 def _setup_api(self):
188 self.api = arvados.safeapi.ThreadSafeApiCache(
189 apiconfig=arvados.config.settings(),
191 'block_cache': arvados.keep.KeepBlockCache(self.args.file_cache),
192 'num_retries': self.args.retries,
194 # Do a sanity check that we have a working arvados host + token.
195 self.api.users().current().execute()
197 def _setup_mount(self):
198 self.operations = Operations(
202 encoding=self.args.encoding,
203 inode_cache=InodeCache(cap=self.args.directory_cache),
204 enable_write=self.args.enable_write)
206 if self.args.crunchstat_interval:
207 statsthread = threading.Thread(
208 target=crunchstat.statlogger,
209 args=(self.args.crunchstat_interval,
212 statsthread.daemon = True
215 usr = self.api.users().current().execute(num_retries=self.args.retries)
218 dir_args = [llfuse.ROOT_INODE, self.operations.inodes, self.api, self.args.retries]
221 if self.args.collection is not None:
222 # Set up the request handler with the collection at the root
223 # First check that the collection is readable
224 self.api.collections().get(uuid=self.args.collection).execute()
225 self.args.mode = 'collection'
226 dir_class = CollectionDirectory
227 dir_args.append(self.args.collection)
228 elif self.args.project is not None:
229 self.args.mode = 'project'
230 dir_class = ProjectDirectory
232 self.api.groups().get(uuid=self.args.project).execute(
233 num_retries=self.args.retries))
235 if (self.args.mount_by_id or
236 self.args.mount_by_pdh or
237 self.args.mount_by_tag or
238 self.args.mount_home or
239 self.args.mount_shared or
240 self.args.mount_tmp):
241 if self.args.mode is not None:
243 "Cannot combine '{}' mode with custom --mount-* options.".
244 format(self.args.mode))
245 elif self.args.mode is None:
246 # If no --mount-custom or custom mount args, --all is the default
247 self.args.mode = 'all'
249 if self.args.mode in ['by_id', 'by_pdh']:
250 # Set up the request handler with the 'magic directory' at the root
251 dir_class = MagicDirectory
252 dir_args.append(self.args.mode == 'by_pdh')
253 elif self.args.mode == 'by_tag':
254 dir_class = TagsDirectory
255 elif self.args.mode == 'shared':
256 dir_class = SharedDirectory
258 elif self.args.mode == 'home':
259 dir_class = ProjectDirectory
261 dir_args.append(True)
262 elif self.args.mode == 'all':
263 self.args.mount_by_id = ['by_id']
264 self.args.mount_by_tag = ['by_tag']
265 self.args.mount_home = ['home']
266 self.args.mount_shared = ['shared']
269 if dir_class is not None:
270 ent = dir_class(*dir_args)
271 self.operations.inodes.add_entry(ent)
272 self.listen_for_events = ent.want_event_subscribe()
275 e = self.operations.inodes.add_entry(Directory(
276 llfuse.ROOT_INODE, self.operations.inodes))
277 dir_args[0] = e.inode
279 for name in self.args.mount_by_id:
280 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=False))
281 for name in self.args.mount_by_pdh:
282 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=True))
283 for name in self.args.mount_by_tag:
284 self._add_mount(e, name, TagsDirectory(*dir_args))
285 for name in self.args.mount_home:
286 self._add_mount(e, name, ProjectDirectory(*dir_args, project_object=usr, poll=True))
287 for name in self.args.mount_shared:
288 self._add_mount(e, name, SharedDirectory(*dir_args, exclude=usr, poll=True))
289 for name in self.args.mount_tmp:
290 self._add_mount(e, name, TmpCollectionDirectory(*dir_args))
293 text = self._readme_text(
294 arvados.config.get('ARVADOS_API_HOST'),
296 self._add_mount(e, 'README', StringFile(e.inode, text, now))
298 def _add_mount(self, tld, name, ent):
299 if name in ['', '.', '..'] or '/' in name:
300 sys.exit("Mount point '{}' is not supported.".format(name))
301 tld._entries[name] = self.operations.inodes.add_entry(ent)
302 self.listen_for_events = (self.listen_for_events or ent.want_event_subscribe())
304 def _readme_text(self, api_host, user_email):
306 Welcome to Arvados! This directory provides file system access to
307 files and objects available on the Arvados installation located at
308 '{}' using credentials for user '{}'.
310 From here, the following directories are available:
312 by_id/ Access to Keep collections by uuid or portable data hash (see by_id/README for details).
313 by_tag/ Access to Keep collections organized by tag.
314 home/ The contents of your home project.
315 shared/ Projects shared with you.
317 '''.format(api_host, user_email)
323 sp = subprocess.Popen(self.args.exec_args, shell=False)
325 # forward signals to the process.
326 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
327 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
328 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
330 # wait for process to complete.
333 # restore default signal handlers.
334 signal.signal(signal.SIGINT, signal.SIG_DFL)
335 signal.signal(signal.SIGTERM, signal.SIG_DFL)
336 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
337 except Exception as e:
338 self.logger.exception(
339 'arv-mount: exception during exec %s', self.args.exec_args)
342 except AttributeError:
346 def _run_standalone(self):
348 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
350 if not self.args.foreground:
351 self.daemon_ctx = daemon.DaemonContext(
352 working_directory=os.path.dirname(self.args.mountpoint),
353 files_preserve=range(
354 3, resource.getrlimit(resource.RLIMIT_NOFILE)[1]))
355 self.daemon_ctx.open()
357 # Subscribe to change events from API server
358 if self.listen_for_events and not self.args.disable_event_listening:
359 self.operations.listen_for_events()
362 except Exception as e:
363 self.logger.exception('arv-mount: exception during mount: %s', e)
364 exit(getattr(e, 'errno', 1))
367 def _llfuse_main(self):
371 llfuse.close(unmount=False)