closes #3821
[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 *
15 from arvados_fuse.unmount import unmount
16 from arvados_fuse._version import __version__
17
18 class ArgumentParser(argparse.ArgumentParser):
19     def __init__(self):
20         super(ArgumentParser, self).__init__(
21             parents=[arv_cmd.retry_opt],
22             description='''Mount Keep data under the local filesystem.  Default mode is --home''',
23             epilog="""
24     Note: When using the --exec feature, you must either specify the
25     mountpoint before --exec, or mark the end of your --exec arguments
26     with "--".
27             """)
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".""")
36
37         mode = self.add_mutually_exclusive_group()
38
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.""")
57
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.")
77
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")
82
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)
85
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)
87
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)
90
91         self.add_argument('--crunchstat-interval', type=float, help="Write stats to stderr every N seconds (default disabled)", default=0)
92
93         unmount = self.add_mutually_exclusive_group()
94         unmount.add_argument('--unmount', action='store_true', default=False,
95                              help="Forcefully unmount the specified mountpoint (if it's a fuse mount) and exit.")
96         unmount.add_argument('--unmount-all', action='store_true', default=False,
97                              help="Forcefully unmount every fuse mount at or below the specified mountpoint and exit.")
98         unmount.add_argument('--replace', action='store_true', default=False,
99                              help="If a fuse mount is already present at mountpoint, forcefully unmount it before mounting")
100         self.add_argument('--unmount-timeout',
101                           type=float, default=2.0,
102                           help="Time to wait for graceful shutdown after --exec program exits and filesystem is unmounted")
103
104         self.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
105                             dest="exec_args", metavar=('command', 'args', '...', '--'),
106                             help="""Mount, run a command, then unmount and exit""")
107
108
109 class Mount(object):
110     def __init__(self, args, logger=logging.getLogger('arvados.arv-mount')):
111         self.daemon = False
112         self.logger = logger
113         self.args = args
114         self.listen_for_events = False
115
116         self.args.mountpoint = os.path.realpath(self.args.mountpoint)
117         if self.args.logfile:
118             self.args.logfile = os.path.realpath(self.args.logfile)
119
120         try:
121             self._setup_logging()
122             self._setup_api()
123             self._setup_mount()
124         except Exception as e:
125             self.logger.exception("arv-mount: exception during setup: %s", e)
126             exit(1)
127
128     def __enter__(self):
129         if self.args.replace:
130             unmount(path=self.args.mountpoint,
131                     timeout=self.args.unmount_timeout)
132         llfuse.init(self.operations, self.args.mountpoint, self._fuse_options())
133         if self.daemon:
134             daemon.DaemonContext(
135                 working_directory=os.path.dirname(self.args.mountpoint),
136                 files_preserve=range(
137                     3, resource.getrlimit(resource.RLIMIT_NOFILE)[1])
138             ).open()
139         if self.listen_for_events and not self.args.disable_event_listening:
140             self.operations.listen_for_events()
141         self.llfuse_thread = threading.Thread(None, lambda: self._llfuse_main())
142         self.llfuse_thread.daemon = True
143         self.llfuse_thread.start()
144         self.operations.initlock.wait()
145         return self
146
147     def __exit__(self, exc_type, exc_value, traceback):
148         if self.operations.events:
149             self.operations.events.close(timeout=self.args.unmount_timeout)
150         subprocess.call(["fusermount", "-u", "-z", self.args.mountpoint])
151         self.llfuse_thread.join(timeout=self.args.unmount_timeout)
152         if self.llfuse_thread.is_alive():
153             self.logger.warning("Mount.__exit__:"
154                                 " llfuse thread still alive %fs after umount"
155                                 " -- abandoning and exiting anyway",
156                                 self.args.unmount_timeout)
157
158     def run(self):
159         if self.args.unmount or self.args.unmount_all:
160             unmount(path=self.args.mountpoint,
161                     timeout=self.args.unmount_timeout,
162                     recursive=self.args.unmount_all)
163         elif self.args.exec_args:
164             self._run_exec()
165         else:
166             self._run_standalone()
167
168     def _fuse_options(self):
169         """FUSE mount options; see mount.fuse(8)"""
170         opts = [optname for optname in ['allow_other', 'debug']
171                 if getattr(self.args, optname)]
172         # Increase default read/write size from 4KiB to 128KiB
173         opts += ["big_writes", "max_read=131072"]
174         if self.args.subtype:
175             opts += ["subtype="+self.args.subtype]
176         return opts
177
178     def _setup_logging(self):
179         # Configure a log handler based on command-line switches.
180         if self.args.logfile:
181             log_handler = logging.FileHandler(self.args.logfile)
182             log_handler.setFormatter(logging.Formatter(
183                 '%(asctime)s %(name)s[%(process)d] %(levelname)s: %(message)s',
184                 '%Y-%m-%d %H:%M:%S'))
185         else:
186             log_handler = None
187
188         if log_handler is not None:
189             arvados.logger.removeHandler(arvados.log_handler)
190             arvados.logger.addHandler(log_handler)
191
192         if self.args.debug:
193             arvados.logger.setLevel(logging.DEBUG)
194             logging.getLogger('arvados.keep').setLevel(logging.DEBUG)
195             logging.getLogger('arvados.api').setLevel(logging.DEBUG)
196             logging.getLogger('arvados.collection').setLevel(logging.DEBUG)
197             self.logger.debug("arv-mount debugging enabled")
198
199         self.logger.info("enable write is %s", self.args.enable_write)
200
201     def _setup_api(self):
202         self.api = arvados.safeapi.ThreadSafeApiCache(
203             apiconfig=arvados.config.settings(),
204             keep_params={
205                 'block_cache': arvados.keep.KeepBlockCache(self.args.file_cache),
206                 'num_retries': self.args.retries,
207             })
208         # Do a sanity check that we have a working arvados host + token.
209         self.api.users().current().execute()
210
211     def _setup_mount(self):
212         self.operations = Operations(
213             os.getuid(),
214             os.getgid(),
215             api_client=self.api,
216             encoding=self.args.encoding,
217             inode_cache=InodeCache(cap=self.args.directory_cache),
218             enable_write=self.args.enable_write)
219
220         if self.args.crunchstat_interval:
221             statsthread = threading.Thread(
222                 target=crunchstat.statlogger,
223                 args=(self.args.crunchstat_interval,
224                       self.api.keep,
225                       self.operations))
226             statsthread.daemon = True
227             statsthread.start()
228
229         usr = self.api.users().current().execute(num_retries=self.args.retries)
230         now = time.time()
231         dir_class = None
232         dir_args = [llfuse.ROOT_INODE, self.operations.inodes, self.api, self.args.retries]
233         mount_readme = False
234
235         if self.args.collection is not None:
236             # Set up the request handler with the collection at the root
237             # First check that the collection is readable
238             self.api.collections().get(uuid=self.args.collection).execute()
239             self.args.mode = 'collection'
240             dir_class = CollectionDirectory
241             dir_args.append(self.args.collection)
242         elif self.args.project is not None:
243             self.args.mode = 'project'
244             dir_class = ProjectDirectory
245             dir_args.append(
246                 self.api.groups().get(uuid=self.args.project).execute(
247                     num_retries=self.args.retries))
248
249         if (self.args.mount_by_id or
250             self.args.mount_by_pdh or
251             self.args.mount_by_tag or
252             self.args.mount_home or
253             self.args.mount_shared or
254             self.args.mount_tmp):
255             if self.args.mode is not None:
256                 sys.exit(
257                     "Cannot combine '{}' mode with custom --mount-* options.".
258                     format(self.args.mode))
259         elif self.args.mode is None:
260             # If no --mount-custom or custom mount args, --all is the default
261             self.args.mode = 'all'
262
263         if self.args.mode in ['by_id', 'by_pdh']:
264             # Set up the request handler with the 'magic directory' at the root
265             dir_class = MagicDirectory
266             dir_args.append(self.args.mode == 'by_pdh')
267         elif self.args.mode == 'by_tag':
268             dir_class = TagsDirectory
269         elif self.args.mode == 'shared':
270             dir_class = SharedDirectory
271             dir_args.append(usr)
272         elif self.args.mode == 'home':
273             dir_class = ProjectDirectory
274             dir_args.append(usr)
275             dir_args.append(True)
276         elif self.args.mode == 'all':
277             self.args.mount_by_id = ['by_id']
278             self.args.mount_by_tag = ['by_tag']
279             self.args.mount_home = ['home']
280             self.args.mount_shared = ['shared']
281             mount_readme = True
282
283         if dir_class is not None:
284             ent = dir_class(*dir_args)
285             self.operations.inodes.add_entry(ent)
286             self.listen_for_events = ent.want_event_subscribe()
287             return
288
289         e = self.operations.inodes.add_entry(Directory(
290             llfuse.ROOT_INODE, self.operations.inodes))
291         dir_args[0] = e.inode
292
293         for name in self.args.mount_by_id:
294             self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=False))
295         for name in self.args.mount_by_pdh:
296             self._add_mount(e, name, MagicDirectory(*dir_args, pdh_only=True))
297         for name in self.args.mount_by_tag:
298             self._add_mount(e, name, TagsDirectory(*dir_args))
299         for name in self.args.mount_home:
300             self._add_mount(e, name, ProjectDirectory(*dir_args, project_object=usr, poll=True))
301         for name in self.args.mount_shared:
302             self._add_mount(e, name, SharedDirectory(*dir_args, exclude=usr, poll=True))
303         for name in self.args.mount_tmp:
304             self._add_mount(e, name, TmpCollectionDirectory(*dir_args))
305
306         if mount_readme:
307             text = self._readme_text(
308                 arvados.config.get('ARVADOS_API_HOST'),
309                 usr['email'])
310             self._add_mount(e, 'README', StringFile(e.inode, text, now))
311
312     def _add_mount(self, tld, name, ent):
313         if name in ['', '.', '..'] or '/' in name:
314             sys.exit("Mount point '{}' is not supported.".format(name))
315         tld._entries[name] = self.operations.inodes.add_entry(ent)
316         self.listen_for_events = (self.listen_for_events or ent.want_event_subscribe())
317
318     def _readme_text(self, api_host, user_email):
319         return '''
320 Welcome to Arvados!  This directory provides file system access to
321 files and objects available on the Arvados installation located at
322 '{}' using credentials for user '{}'.
323
324 From here, the following directories are available:
325
326   by_id/     Access to Keep collections by uuid or portable data hash (see by_id/README for details).
327   by_tag/    Access to Keep collections organized by tag.
328   home/      The contents of your home project.
329   shared/    Projects shared with you.
330
331 '''.format(api_host, user_email)
332
333     def _run_exec(self):
334         rc = 255
335         with self:
336             try:
337                 sp = subprocess.Popen(self.args.exec_args, shell=False)
338
339                 # forward signals to the process.
340                 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
341                 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
342                 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
343
344                 # wait for process to complete.
345                 rc = sp.wait()
346
347                 # restore default signal handlers.
348                 signal.signal(signal.SIGINT, signal.SIG_DFL)
349                 signal.signal(signal.SIGTERM, signal.SIG_DFL)
350                 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
351             except Exception as e:
352                 self.logger.exception(
353                     'arv-mount: exception during exec %s', self.args.exec_args)
354                 try:
355                     rc = e.errno
356                 except AttributeError:
357                     pass
358         exit(rc)
359
360     def _run_standalone(self):
361         try:
362             self.daemon = not self.args.foreground
363             with self:
364                 self.llfuse_thread.join(timeout=None)
365         except Exception as e:
366             self.logger.exception('arv-mount: exception during mount: %s', e)
367             exit(getattr(e, 'errno', 1))
368         exit(0)
369
370     def _llfuse_main(self):
371         try:
372             llfuse.main()
373         except:
374             llfuse.close(unmount=False)
375             raise
376         llfuse.close()