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