8784: Fix test for latest firefox.
[arvados.git] / services / fuse / arvados_fuse / command.py
1 import argparse
2 import arvados
3 import daemon
4 import llfuse
5 import logging
6 import os
7 import resource
8 import signal
9 import subprocess
10 import sys
11 import time
12
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__
18
19 class ArgumentParser(argparse.ArgumentParser):
20     def __init__(self):
21         super(ArgumentParser, self).__init__(
22             parents=[arv_cmd.retry_opt],
23             description='''Mount Keep data under the local filesystem.  Default mode is --home''',
24             epilog="""
25     Note: When using the --exec feature, you must either specify the
26     mountpoint before --exec, or mark the end of your --exec arguments
27     with "--".
28             """)
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".""")
37
38         mode = self.add_mutually_exclusive_group()
39
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.""")
58
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.")
78
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")
83
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)
86
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)
88
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)
91
92         self.add_argument('--crunchstat-interval', type=float, help="Write stats to stderr every N seconds (default disabled)", default=0)
93
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")
104
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""")
108
109
110 class Mount(object):
111     def __init__(self, args, logger=logging.getLogger('arvados.arv-mount')):
112         self.daemon = False
113         self.logger = logger
114         self.args = args
115         self.listen_for_events = False
116
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)
120
121         try:
122             self._setup_logging()
123             self._setup_api()
124             self._setup_mount()
125         except Exception as e:
126             self.logger.exception("arv-mount: exception during setup: %s", e)
127             exit(1)
128
129     def __enter__(self):
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())
134         if self.daemon:
135             daemon.DaemonContext(
136                 working_directory=os.path.dirname(self.args.mountpoint),
137                 files_preserve=range(
138                     3, resource.getrlimit(resource.RLIMIT_NOFILE)[1])
139             ).open()
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()
146         return self
147
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)
158
159     def run(self):
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:
166             self._run_exec()
167         else:
168             self._run_standalone()
169
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]
178         return opts
179
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'))
187         else:
188             log_handler = None
189
190         if log_handler is not None:
191             arvados.logger.removeHandler(arvados.log_handler)
192             arvados.logger.addHandler(log_handler)
193
194         if self.args.debug:
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")
200
201         self.logger.info("enable write is %s", self.args.enable_write)
202
203     def _setup_api(self):
204         self.api = arvados.safeapi.ThreadSafeApiCache(
205             apiconfig=arvados.config.settings(),
206             keep_params={
207                 'block_cache': arvados.keep.KeepBlockCache(self.args.file_cache),
208                 'num_retries': self.args.retries,
209             })
210         # Do a sanity check that we have a working arvados host + token.
211         self.api.users().current().execute()
212
213     def _setup_mount(self):
214         self.operations = Operations(
215             os.getuid(),
216             os.getgid(),
217             api_client=self.api,
218             encoding=self.args.encoding,
219             inode_cache=InodeCache(cap=self.args.directory_cache),
220             enable_write=self.args.enable_write)
221
222         if self.args.crunchstat_interval:
223             statsthread = threading.Thread(
224                 target=crunchstat.statlogger,
225                 args=(self.args.crunchstat_interval,
226                       self.api.keep,
227                       self.operations))
228             statsthread.daemon = True
229             statsthread.start()
230
231         usr = self.api.users().current().execute(num_retries=self.args.retries)
232         now = time.time()
233         dir_class = None
234         dir_args = [llfuse.ROOT_INODE, self.operations.inodes, self.api, self.args.retries]
235         mount_readme = False
236
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
247             dir_args.append(
248                 self.api.groups().get(uuid=self.args.project).execute(
249                     num_retries=self.args.retries))
250
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:
258                 sys.exit(
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'
264
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
273             dir_args.append(usr)
274         elif self.args.mode == 'home':
275             dir_class = ProjectDirectory
276             dir_args.append(usr)
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']
283             mount_readme = True
284
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()
289             return
290
291         e = self.operations.inodes.add_entry(Directory(
292             llfuse.ROOT_INODE, self.operations.inodes))
293         dir_args[0] = e.inode
294
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))
307
308         if mount_readme:
309             text = self._readme_text(
310                 arvados.config.get('ARVADOS_API_HOST'),
311                 usr['email'])
312             self._add_mount(e, 'README', StringFile(e.inode, text, now))
313
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())
319
320     def _readme_text(self, api_host, user_email):
321         return '''
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 '{}'.
325
326 From here, the following directories are available:
327
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.
332
333 '''.format(api_host, user_email)
334
335     def _run_exec(self):
336         rc = 255
337         with self:
338             try:
339                 sp = subprocess.Popen(self.args.exec_args, shell=False)
340
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))
345
346                 # wait for process to complete.
347                 rc = sp.wait()
348
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)
356                 try:
357                     rc = e.errno
358                 except AttributeError:
359                     pass
360         exit(rc)
361
362     def _run_standalone(self):
363         try:
364             self.daemon = not self.args.foreground
365             with self:
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))
370         exit(0)
371
372     def _llfuse_main(self):
373         try:
374             llfuse.main()
375         except:
376             llfuse.close(unmount=False)
377             raise
378         llfuse.close()