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