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