12 import arvados.commands._util as arv_cmd
13 from arvados_fuse import crunchstat
14 from arvados_fuse import *
16 class ArgumentParser(argparse.ArgumentParser):
18 super(ArgumentParser, self).__init__(
19 parents=[arv_cmd.retry_opt],
20 description='''Mount Keep data under the local filesystem. Default mode is --home''',
22 Note: When using the --exec feature, you must either specify the
23 mountpoint before --exec, or mark the end of your --exec arguments
26 self.add_argument('mountpoint', type=str, help="""Mount point.""")
27 self.add_argument('--allow-other', action='store_true',
28 help="""Let other users read the mount""")
30 mode = self.add_mutually_exclusive_group()
32 mode.add_argument('--all', action='store_const', const='all', dest='mode',
33 help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default if no --mount-* arguments are given).""")
34 mode.add_argument('--custom', action='store_const', const=None, dest='mode',
35 help="""Mount a top level meta-directory with subdirectories as specified by additional --mount-* arguments (default if any --mount-* arguments are given).""")
36 mode.add_argument('--home', action='store_const', const='home', dest='mode',
37 help="""Mount only the user's home project.""")
38 mode.add_argument('--shared', action='store_const', const='shared', dest='mode',
39 help="""Mount only list of projects shared with the user.""")
40 mode.add_argument('--by-tag', action='store_const', const='by_tag', dest='mode',
41 help="""Mount subdirectories listed by tag.""")
42 mode.add_argument('--by-id', action='store_const', const='by_id', dest='mode',
43 help="""Mount subdirectories listed by portable data hash or uuid.""")
44 mode.add_argument('--by-pdh', action='store_const', const='by_pdh', dest='mode',
45 help="""Mount subdirectories listed by portable data hash.""")
46 mode.add_argument('--project', type=str, metavar='UUID',
47 help="""Mount the specified project.""")
48 mode.add_argument('--collection', type=str, metavar='UUID_or_PDH',
49 help="""Mount only the specified collection.""")
51 mounts = self.add_argument_group('Custom mount options')
52 mounts.add_argument('--mount-by-pdh',
53 type=str, metavar='PATH', action='append', default=[],
54 help="Mount each readable collection at mountpoint/PATH/P where P is the collection's portable data hash.")
55 mounts.add_argument('--mount-by-id',
56 type=str, metavar='PATH', action='append', default=[],
57 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.")
58 mounts.add_argument('--mount-by-tag',
59 type=str, metavar='PATH', action='append', default=[],
60 help="Mount all collections with tag TAG at mountpoint/PATH/TAG/UUID.")
61 mounts.add_argument('--mount-home',
62 type=str, metavar='PATH', action='append', default=[],
63 help="Mount the current user's home project at mountpoint/PATH.")
64 mounts.add_argument('--mount-shared',
65 type=str, metavar='PATH', action='append', default=[],
66 help="Mount projects shared with the current user at mountpoint/PATH.")
67 mounts.add_argument('--mount-tmp',
68 type=str, metavar='PATH', action='append', default=[],
69 help="Create a new collection, mount it in read/write mode at mountpoint/PATH, and delete it when unmounting.")
71 self.add_argument('--debug', action='store_true', help="""Debug mode""")
72 self.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
73 self.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
74 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")
76 self.add_argument('--file-cache', type=int, help="File data cache size, in bytes (default 256MiB)", default=256*1024*1024)
77 self.add_argument('--directory-cache', type=int, help="Directory data cache size, in bytes (default 128MiB)", default=128*1024*1024)
79 self.add_argument('--read-only', action='store_false', help="Mount will be read only (default)", dest="enable_write", default=False)
80 self.add_argument('--read-write', action='store_true', help="Mount will be read-write", dest="enable_write", default=False)
82 self.add_argument('--crunchstat-interval', type=float, help="Write stats to stderr every N seconds (default disabled)", default=0)
84 self.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
85 dest="exec_args", metavar=('command', 'args', '...', '--'),
86 help="""Mount, run a command, then unmount and exit""")
90 def __init__(self, args, logger=logging.getLogger('arvados.arv-mount')):
94 self.args.mountpoint = os.path.realpath(self.args.mountpoint)
96 self.args.logfile = os.path.realpath(self.args.logfile)
98 # Daemonize as early as possible, so we don't accidentally close
99 # file descriptors we're using.
100 self.daemon_ctx = None
101 if not (self.args.exec_args or self.args.foreground):
102 os.chdir(self.args.mountpoint)
103 self.daemon_ctx = daemon.DaemonContext(working_directory='.')
104 self.daemon_ctx.open()
107 self._setup_logging()
110 except Exception as e:
111 self.logger.exception("arv-mount: exception during setup: %s", e)
115 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
116 if self.args.mode != 'by_pdh':
117 self.operations.listen_for_events()
118 t = threading.Thread(None, lambda: llfuse.main())
120 self.operations.initlock.wait()
122 def __exit__(self, exc_type, exc_value, traceback):
123 subprocess.call(["fusermount", "-u", "-z", self.args.mountpoint])
124 self.operations.destroy()
127 if self.args.exec_args:
130 self._run_standalone()
132 def _fuse_options(self):
133 """FUSE mount options; see mount.fuse(8)"""
134 opts = [optname for optname in ['allow_other', 'debug']
135 if getattr(self.args, optname)]
136 # Increase default read/write size from 4KiB to 128KiB
137 opts += ["big_writes", "max_read=131072"]
140 def _setup_logging(self):
141 # Configure a log handler based on command-line switches.
142 if self.args.logfile:
143 log_handler = logging.FileHandler(self.args.logfile)
144 elif self.daemon_ctx:
145 log_handler = logging.NullHandler()
149 if log_handler is not None:
150 arvados.logger.removeHandler(arvados.log_handler)
151 arvados.logger.addHandler(log_handler)
154 arvados.logger.setLevel(logging.DEBUG)
155 self.logger.debug("arv-mount debugging enabled")
157 self.logger.info("enable write is %s", self.args.enable_write)
159 def _setup_api(self):
160 self.api = arvados.safeapi.ThreadSafeApiCache(
161 apiconfig=arvados.config.settings(),
163 "block_cache": arvados.keep.KeepBlockCache(self.args.file_cache)
166 def _setup_mount(self):
167 self.operations = Operations(
171 encoding=self.args.encoding,
172 inode_cache=InodeCache(cap=self.args.directory_cache),
173 enable_write=self.args.enable_write)
175 if self.args.crunchstat_interval:
176 statsthread = threading.Thread(
177 target=crunchstat.statlogger,
178 args=(self.args.crunchstat_interval,
181 statsthread.daemon = True
184 usr = self.api.users().current().execute(num_retries=self.args.retries)
187 dir_args = [llfuse.ROOT_INODE, self.operations.inodes, self.api, self.args.retries]
190 if self.args.collection is not None:
191 # Set up the request handler with the collection at the root
192 self.args.mode = 'collection'
193 dir_class = CollectionDirectory
194 dir_args.append(self.args.collection)
195 elif self.args.project is not None:
196 self.args.mode = 'project'
197 dir_class = ProjectDirectory
199 self.api.groups().get(uuid=self.args.project).execute(
200 num_retries=self.args.retries))
202 if (self.args.mount_by_id or
203 self.args.mount_by_pdh or
204 self.args.mount_by_tag or
205 self.args.mount_home or
206 self.args.mount_shared or
207 self.args.mount_tmp):
208 if self.args.mode is not None:
210 "Cannot combine '{}' mode with custom --mount-* options.".
211 format(self.args.mode))
212 elif self.args.mode is None:
213 # If no --mount-custom or custom mount args, --all is the default
214 self.args.mode = 'all'
216 if self.args.mode in ['by_id', 'by_pdh']:
217 # Set up the request handler with the 'magic directory' at the root
218 dir_class = MagicDirectory
219 dir_args.append(self.args.mode == 'by_pdh')
220 elif self.args.mode == 'by_tag':
221 dir_class = TagsDirectory
222 elif self.args.mode == 'shared':
223 dir_class = SharedDirectory
225 elif self.args.mode == 'home':
226 dir_class = ProjectDirectory
228 dir_args.append(True)
229 elif self.args.mode == 'all':
230 self.args.mount_by_id = ['by_id']
231 self.args.mount_by_tag = ['by_tag']
232 self.args.mount_home = ['home']
233 self.args.mount_shared = ['shared']
236 if dir_class is not None:
237 self.operations.inodes.add_entry(dir_class(*dir_args))
240 e = self.operations.inodes.add_entry(Directory(
241 llfuse.ROOT_INODE, self.operations.inodes))
242 dir_args[0] = e.inode
244 for name in self.args.mount_by_id:
245 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=False))
246 for name in self.args.mount_by_pdh:
247 self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=True))
248 for name in self.args.mount_by_tag:
249 self._add_mount(e, name, TagsDirectory(*dir_args))
250 for name in self.args.mount_home:
251 self._add_mount(e, name, ProjectDirectory(*dir_args, project_object=usr, poll=True))
252 for name in self.args.mount_shared:
253 self._add_mount(e, name, SharedDirectory(*dir_args, exclude=usr, poll=True))
254 for name in self.args.mount_tmp:
255 self._add_mount(e, name, TmpCollectionDirectory(*dir_args))
258 text = self._readme_text(
259 arvados.config.get('ARVADOS_API_HOST'),
261 self._add_mount(e, 'README', StringFile(e.inode, text, now))
263 def _add_mount(self, tld, name, ent):
264 if name in ['', '.', '..'] or '/' in name:
265 sys.exit("Mount point '{}' is not supported.".format(name))
266 tld._entries[name] = self.operations.inodes.add_entry(ent)
268 def _readme_text(self, api_host, user_email):
270 Welcome to Arvados! This directory provides file system access to
271 files and objects available on the Arvados installation located at
272 '{}' using credentials for user '{}'.
274 From here, the following directories are available:
276 by_id/ Access to Keep collections by uuid or portable data hash (see by_id/README for details).
277 by_tag/ Access to Keep collections organized by tag.
278 home/ The contents of your home project.
279 shared/ Projects shared with you.
281 '''.format(api_host, user_email)
284 # Initialize the fuse connection
285 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
287 # Subscribe to change events from API server
288 if self.args.mode != 'by_pdh':
289 self.operations.listen_for_events()
291 t = threading.Thread(None, lambda: llfuse.main())
294 # wait until the driver is finished initializing
295 self.operations.initlock.wait()
299 sp = subprocess.Popen(self.args.exec_args, shell=False)
301 # forward signals to the process.
302 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
303 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
304 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
306 # wait for process to complete.
309 # restore default signal handlers.
310 signal.signal(signal.SIGINT, signal.SIG_DFL)
311 signal.signal(signal.SIGTERM, signal.SIG_DFL)
312 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
313 except Exception as e:
314 self.logger.exception(
315 'arv-mount: exception during exec %s', self.args.exec_args)
318 except AttributeError:
321 subprocess.call(["fusermount", "-u", "-z", self.args.mountpoint])
322 self.operations.destroy()
325 def _run_standalone(self):
327 llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
329 # Subscribe to change events from API server
330 self.operations.listen_for_events()
333 except Exception as e:
334 self.logger.exception('arv-mount: exception during mount: %s', e)
335 exit(getattr(e, 'errno', 1))
337 self.operations.destroy()