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