13 import arvados.commands._util as arv_cmd
14 from arvados_fuse import crunchstat
15 from arvados_fuse import *
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('mountpoint', type=str, help="""Mount point.""")
28 self.add_argument('--allow-other', action='store_true',
29 help="""Let other users read the mount""")
31 mode = self.add_mutually_exclusive_group()
33 mode.add_argument('--all', action='store_const', const='all', dest='mode',
34 help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default if no --mount-* arguments are given).""")
35 mode.add_argument('--custom', action='store_const', const=None, dest='mode',
36 help="""Mount a top level meta-directory with subdirectories as specified by additional --mount-* arguments (default if any --mount-* arguments are given).""")
37 mode.add_argument('--home', action='store_const', const='home', dest='mode',
38 help="""Mount only the user's home project.""")
39 mode.add_argument('--shared', action='store_const', const='shared', dest='mode',
40 help="""Mount only list of projects shared with the user.""")
41 mode.add_argument('--by-tag', action='store_const', const='by_tag', dest='mode',
42 help="""Mount subdirectories listed by tag.""")
43 mode.add_argument('--by-id', action='store_const', const='by_id', dest='mode',
44 help="""Mount subdirectories listed by portable data hash or uuid.""")
45 mode.add_argument('--by-pdh', action='store_const', const='by_pdh', dest='mode',
46 help="""Mount subdirectories listed by portable data hash.""")
47 mode.add_argument('--project', type=str, metavar='UUID',
48 help="""Mount the specified project.""")
49 mode.add_argument('--collection', type=str, metavar='UUID_or_PDH',
50 help="""Mount only the specified collection.""")
52 mounts = self.add_argument_group('Custom mount options')
53 mounts.add_argument('--mount-by-pdh',
54 type=str, metavar='PATH', action='append', default=[],
55 help="Mount each readable collection at mountpoint/PATH/P where P is the collection's portable data hash.")
56 mounts.add_argument('--mount-by-id',
57 type=str, metavar='PATH', action='append', default=[],
58 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.")
59 mounts.add_argument('--mount-by-tag',
60 type=str, metavar='PATH', action='append', default=[],
61 help="Mount all collections with tag TAG at mountpoint/PATH/TAG/UUID.")
62 mounts.add_argument('--mount-home',
63 type=str, metavar='PATH', action='append', default=[],
64 help="Mount the current user's home project at mountpoint/PATH.")
65 mounts.add_argument('--mount-shared',
66 type=str, metavar='PATH', action='append', default=[],
67 help="Mount projects shared with the current user at mountpoint/PATH.")
68 mounts.add_argument('--mount-tmp',
69 type=str, metavar='PATH', action='append', default=[],
70 help="Create a new collection, mount it in read/write mode at mountpoint/PATH, and delete it when unmounting.")
72 self.add_argument('--debug', action='store_true', help="""Debug mode""")
73 self.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
74 self.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
75 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")
77 self.add_argument('--file-cache', type=int, help="File data cache size, in bytes (default 256MiB)", default=256*1024*1024)
78 self.add_argument('--directory-cache', type=int, help="Directory data cache size, in bytes (default 128MiB)", default=128*1024*1024)
80 self.add_argument('--read-only', action='store_false', help="Mount will be read only (default)", dest="enable_write", default=False)
81 self.add_argument('--read-write', action='store_true', help="Mount will be read-write", dest="enable_write", default=False)
83 self.add_argument('--crunchstat-interval', type=float, help="Write stats to stderr every N seconds (default disabled)", default=0)
85 self.add_argument('--unmount-timeout',
86 type=float, default=2.0,
87 help="Time to wait for graceful shutdown after --exec program exits and filesystem is unmounted")
89 self.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
90 dest="exec_args", metavar=('command', 'args', '...', '--'),
91 help="""Mount, run a command, then unmount and exit""")
95 def __init__(self, args, logger=logging.getLogger('arvados.arv-mount')):
99 self.args.mountpoint = os.path.realpath(self.args.mountpoint)
100 if self.args.logfile:
101 self.args.logfile = os.path.realpath(self.args.logfile)
104 self._setup_logging()
107 except Exception as e:
108 self.logger.exception("arv-mount: exception during setup: %s", e)
112 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
113 if self.args.mode != 'by_pdh':
114 self.operations.listen_for_events()
115 self.llfuse_thread = threading.Thread(None, lambda: self._llfuse_main())
116 self.llfuse_thread.daemon = True
117 self.llfuse_thread.start()
118 self.operations.initlock.wait()
120 def __exit__(self, exc_type, exc_value, traceback):
121 subprocess.call(["fusermount", "-u", "-z", self.args.mountpoint])
122 self.llfuse_thread.join(timeout=self.args.unmount_timeout)
123 if self.llfuse_thread.is_alive():
124 self.logger.warning("Mount.__exit__:"
125 " llfuse thread still alive %fs after umount"
126 " -- abandoning and exiting anyway",
127 self.args.unmount_timeout)
130 if self.args.exec_args:
133 self._run_standalone()
135 def _fuse_options(self):
136 """FUSE mount options; see mount.fuse(8)"""
137 opts = [optname for optname in ['allow_other', 'debug']
138 if getattr(self.args, optname)]
139 # Increase default read/write size from 4KiB to 128KiB
140 opts += ["big_writes", "max_read=131072"]
143 def _setup_logging(self):
144 # Configure a log handler based on command-line switches.
145 if self.args.logfile:
146 log_handler = logging.FileHandler(self.args.logfile)
150 if log_handler is not None:
151 arvados.logger.removeHandler(arvados.log_handler)
152 arvados.logger.addHandler(log_handler)
155 arvados.logger.setLevel(logging.DEBUG)
156 self.logger.debug("arv-mount debugging enabled")
158 self.logger.info("enable write is %s", self.args.enable_write)
160 def _setup_api(self):
161 self.api = arvados.safeapi.ThreadSafeApiCache(
162 apiconfig=arvados.config.settings(),
164 'block_cache': arvados.keep.KeepBlockCache(self.args.file_cache),
165 'num_retries': self.args.retries,
167 # Do a sanity check that we have a working arvados host + token.
168 self.api.users().current().execute()
170 def _setup_mount(self):
171 self.operations = Operations(
175 encoding=self.args.encoding,
176 inode_cache=InodeCache(cap=self.args.directory_cache),
177 enable_write=self.args.enable_write)
179 if self.args.crunchstat_interval:
180 statsthread = threading.Thread(
181 target=crunchstat.statlogger,
182 args=(self.args.crunchstat_interval,
185 statsthread.daemon = True
188 usr = self.api.users().current().execute(num_retries=self.args.retries)
191 dir_args = [llfuse.ROOT_INODE, self.operations.inodes, self.api, self.args.retries]
194 if self.args.collection is not None:
195 # Set up the request handler with the collection at the root
196 # First check that the collection is readable
197 self.api.collections().get(uuid=self.args.collection).execute()
198 self.args.mode = 'collection'
199 dir_class = CollectionDirectory
200 dir_args.append(self.args.collection)
201 elif self.args.project is not None:
202 self.args.mode = 'project'
203 dir_class = ProjectDirectory
205 self.api.groups().get(uuid=self.args.project).execute(
206 num_retries=self.args.retries))
208 if (self.args.mount_by_id or
209 self.args.mount_by_pdh or
210 self.args.mount_by_tag or
211 self.args.mount_home or
212 self.args.mount_shared or
213 self.args.mount_tmp):
214 if self.args.mode is not None:
216 "Cannot combine '{}' mode with custom --mount-* options.".
217 format(self.args.mode))
218 elif self.args.mode is None:
219 # If no --mount-custom or custom mount args, --all is the default
220 self.args.mode = 'all'
222 if self.args.mode in ['by_id', 'by_pdh']:
223 # Set up the request handler with the 'magic directory' at the root
224 dir_class = MagicDirectory
225 dir_args.append(self.args.mode == 'by_pdh')
226 elif self.args.mode == 'by_tag':
227 dir_class = TagsDirectory
228 elif self.args.mode == 'shared':
229 dir_class = SharedDirectory
231 elif self.args.mode == 'home':
232 dir_class = ProjectDirectory
234 dir_args.append(True)
235 elif self.args.mode == 'all':
236 self.args.mount_by_id = ['by_id']
237 self.args.mount_by_tag = ['by_tag']
238 self.args.mount_home = ['home']
239 self.args.mount_shared = ['shared']
242 if dir_class is not None:
243 self.operations.inodes.add_entry(dir_class(*dir_args))
246 e = self.operations.inodes.add_entry(Directory(
247 llfuse.ROOT_INODE, self.operations.inodes))
248 dir_args[0] = e.inode
250 for name in self.args.mount_by_id:
251 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=False))
252 for name in self.args.mount_by_pdh:
253 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=True))
254 for name in self.args.mount_by_tag:
255 self._add_mount(e, name, TagsDirectory(*dir_args))
256 for name in self.args.mount_home:
257 self._add_mount(e, name, ProjectDirectory(*dir_args, project_object=usr, poll=True))
258 for name in self.args.mount_shared:
259 self._add_mount(e, name, SharedDirectory(*dir_args, exclude=usr, poll=True))
260 for name in self.args.mount_tmp:
261 self._add_mount(e, name, TmpCollectionDirectory(*dir_args))
264 text = self._readme_text(
265 arvados.config.get('ARVADOS_API_HOST'),
267 self._add_mount(e, 'README', StringFile(e.inode, text, now))
269 def _add_mount(self, tld, name, ent):
270 if name in ['', '.', '..'] or '/' in name:
271 sys.exit("Mount point '{}' is not supported.".format(name))
272 tld._entries[name] = self.operations.inodes.add_entry(ent)
274 def _readme_text(self, api_host, user_email):
276 Welcome to Arvados! This directory provides file system access to
277 files and objects available on the Arvados installation located at
278 '{}' using credentials for user '{}'.
280 From here, the following directories are available:
282 by_id/ Access to Keep collections by uuid or portable data hash (see by_id/README for details).
283 by_tag/ Access to Keep collections organized by tag.
284 home/ The contents of your home project.
285 shared/ Projects shared with you.
287 '''.format(api_host, user_email)
293 sp = subprocess.Popen(self.args.exec_args, shell=False)
295 # forward signals to the process.
296 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
297 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
298 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
300 # wait for process to complete.
303 # restore default signal handlers.
304 signal.signal(signal.SIGINT, signal.SIG_DFL)
305 signal.signal(signal.SIGTERM, signal.SIG_DFL)
306 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
307 except Exception as e:
308 self.logger.exception(
309 'arv-mount: exception during exec %s', self.args.exec_args)
312 except AttributeError:
316 def _run_standalone(self):
318 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
320 if not self.args.foreground:
321 self.daemon_ctx = daemon.DaemonContext(
322 working_directory=os.path.dirname(self.args.mountpoint),
323 files_preserve=range(
324 3, resource.getrlimit(resource.RLIMIT_NOFILE)[1]))
325 self.daemon_ctx.open()
327 # Subscribe to change events from API server
328 self.operations.listen_for_events()
331 except Exception as e:
332 self.logger.exception('arv-mount: exception during mount: %s', e)
333 exit(getattr(e, 'errno', 1))
336 def _llfuse_main(self):
340 llfuse.close(unmount=False)