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