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