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