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