7167: update the progress message to say "est. time remaining" instead of "ETA" which...
[arvados.git] / services / fuse / bin / arv-mount
1 #!/usr/bin/env python
2
3 import argparse
4 import arvados
5 import daemon
6 import logging
7 import os
8 import signal
9 import subprocess
10 import time
11
12 import arvados.commands._util as arv_cmd
13 from arvados_fuse import *
14 from arvados.safeapi import ThreadSafeApiCache
15 import arvados.keep
16
17 logger = logging.getLogger('arvados.arv-mount')
18
19 if __name__ == '__main__':
20     # Handle command line parameters
21     parser = argparse.ArgumentParser(
22         parents=[arv_cmd.retry_opt],
23         description='''Mount Keep data under the local filesystem.  Default mode is --home''',
24         epilog="""
25 Note: When using the --exec feature, you must either specify the
26 mountpoint before --exec, or mark the end of your --exec arguments
27 with "--".
28 """)
29     parser.add_argument('mountpoint', type=str, help="""Mount point.""")
30     parser.add_argument('--allow-other', action='store_true',
31                         help="""Let other users read the mount""")
32
33     mount_mode = parser.add_mutually_exclusive_group()
34
35     mount_mode.add_argument('--all', action='store_true', help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default).""")
36     mount_mode.add_argument('--home', action='store_true', help="""Mount only the user's home project.""")
37     mount_mode.add_argument('--shared', action='store_true', help="""Mount only list of projects shared with the user.""")
38     mount_mode.add_argument('--by-tag', action='store_true',
39                             help="""Mount subdirectories listed by tag.""")
40     mount_mode.add_argument('--by-id', action='store_true',
41                             help="""Mount subdirectories listed by portable data hash or uuid.""")
42     mount_mode.add_argument('--project', type=str, help="""Mount a specific project.""")
43     mount_mode.add_argument('--collection', type=str, help="""Mount only the specified collection.""")
44
45     parser.add_argument('--debug', action='store_true', help="""Debug mode""")
46     parser.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
47     parser.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
48     parser.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")
49
50     parser.add_argument('--file-cache', type=int, help="File data cache size, in bytes (default 256MiB)", default=256*1024*1024)
51     parser.add_argument('--directory-cache', type=int, help="Directory data cache size, in bytes (default 128MiB)", default=128*1024*1024)
52
53     parser.add_argument('--read-only', action='store_false', help="Mount will be read only (default)", dest="enable_write", default=False)
54     parser.add_argument('--read-write', action='store_true', help="Mount will be read-write", dest="enable_write", default=False)
55
56     parser.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
57                         dest="exec_args", metavar=('command', 'args', '...', '--'),
58                         help="""Mount, run a command, then unmount and exit""")
59
60     args = parser.parse_args()
61     args.mountpoint = os.path.realpath(args.mountpoint)
62     if args.logfile:
63         args.logfile = os.path.realpath(args.logfile)
64
65     # Daemonize as early as possible, so we don't accidentally close
66     # file descriptors we're using.
67     if not (args.exec_args or args.foreground):
68         os.chdir(args.mountpoint)
69         daemon_ctx = daemon.DaemonContext(working_directory='.')
70         daemon_ctx.open()
71     else:
72         daemon_ctx = None
73
74     # Configure a log handler based on command-line switches.
75     if args.logfile:
76         log_handler = logging.FileHandler(args.logfile)
77     elif daemon_ctx:
78         log_handler = logging.NullHandler()
79     else:
80         log_handler = None
81
82     if log_handler is not None:
83         arvados.logger.removeHandler(arvados.log_handler)
84         arvados.logger.addHandler(log_handler)
85
86     if args.debug:
87         arvados.logger.setLevel(logging.DEBUG)
88         logger.debug("arv-mount debugging enabled")
89
90     logger.info("enable write is %s", args.enable_write)
91
92     try:
93         # Create the request handler
94         operations = Operations(os.getuid(),
95                                 os.getgid(),
96                                 encoding=args.encoding,
97                                 inode_cache=InodeCache(cap=args.directory_cache),
98                                 enable_write=args.enable_write)
99         api = ThreadSafeApiCache(apiconfig=arvados.config.settings(),
100                                  keep_params={"block_cache": arvados.keep.KeepBlockCache(args.file_cache)})
101
102         usr = api.users().current().execute(num_retries=args.retries)
103         now = time.time()
104         dir_class = None
105         dir_args = [llfuse.ROOT_INODE, operations.inodes, api, args.retries]
106         if args.by_id:
107             # Set up the request handler with the 'magic directory' at the root
108             dir_class = MagicDirectory
109         elif args.by_tag:
110             dir_class = TagsDirectory
111         elif args.shared:
112             dir_class = SharedDirectory
113             dir_args.append(usr)
114         elif args.home:
115             dir_class = ProjectDirectory
116             dir_args.append(usr)
117             dir_args.append(True)
118         elif args.collection is not None:
119             # Set up the request handler with the collection at the root
120             dir_class = CollectionDirectory
121             dir_args.append(args.collection)
122         elif args.project is not None:
123             dir_class = ProjectDirectory
124             dir_args.append(api.groups().get(uuid=args.project).execute(
125                     num_retries=args.retries))
126
127         if dir_class is not None:
128             operations.inodes.add_entry(dir_class(*dir_args))
129         else:
130             e = operations.inodes.add_entry(Directory(llfuse.ROOT_INODE, operations.inodes))
131             dir_args[0] = e.inode
132
133             e._entries['by_id'] = operations.inodes.add_entry(MagicDirectory(*dir_args))
134             e._entries['by_tag'] = operations.inodes.add_entry(TagsDirectory(*dir_args))
135
136             dir_args.append(usr)
137             dir_args.append(True)
138             e._entries['home'] = operations.inodes.add_entry(ProjectDirectory(*dir_args))
139             e._entries['shared'] = operations.inodes.add_entry(SharedDirectory(*dir_args))
140
141             text = '''
142 Welcome to Arvados!  This directory provides file system access to files and objects
143 available on the Arvados installation located at '{}'
144 using credentials for user '{}'.
145
146 From here, the following directories are available:
147
148   by_id/     Access to Keep collections by uuid or portable data hash (see by_id/README for details).
149   by_tag/    Access to Keep collections organized by tag.
150   home/      The contents of your home project.
151   shared/    Projects shared with you.
152 '''.format(arvados.config.get('ARVADOS_API_HOST'), usr['email'])
153
154             e._entries["README"] = operations.inodes.add_entry(StringFile(e.inode, text, now))
155
156
157     except Exception:
158         logger.exception("arv-mount: exception during API setup")
159         exit(1)
160
161     # FUSE options, see mount.fuse(8)
162     opts = [optname for optname in ['allow_other', 'debug']
163             if getattr(args, optname)]
164
165     # Increase default read/write size from 4KiB to 128KiB
166     opts += ["big_writes", "max_read=131072"]
167
168     if args.exec_args:
169         # Initialize the fuse connection
170         llfuse.init(operations, args.mountpoint, opts)
171
172         # Subscribe to change events from API server
173         operations.listen_for_events(api)
174
175         t = threading.Thread(None, lambda: llfuse.main())
176         t.start()
177
178         # wait until the driver is finished initializing
179         operations.initlock.wait()
180
181         rc = 255
182         try:
183             sp = subprocess.Popen(args.exec_args, shell=False)
184
185             # forward signals to the process.
186             signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
187             signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
188             signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
189
190             # wait for process to complete.
191             rc = sp.wait()
192
193             # restore default signal handlers.
194             signal.signal(signal.SIGINT, signal.SIG_DFL)
195             signal.signal(signal.SIGTERM, signal.SIG_DFL)
196             signal.signal(signal.SIGQUIT, signal.SIG_DFL)
197         except Exception as e:
198             logger.exception('arv-mount: exception during exec %s',
199                              args.exec_args)
200             try:
201                 rc = e.errno
202             except AttributeError:
203                 pass
204         finally:
205             subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
206             operations.destroy()
207
208         exit(rc)
209     else:
210         try:
211             llfuse.init(operations, args.mountpoint, opts)
212
213             # Subscribe to change events from API server
214             operations.listen_for_events(api)
215
216             llfuse.main()
217         except Exception as e:
218             logger.exception('arv-mount: exception during mount')
219             exit(getattr(e, 'errno', 1))
220         finally:
221             operations.destroy()