closes #3454
[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('--exec', type=str, nargs=argparse.REMAINDER,
54                         dest="exec_args", metavar=('command', 'args', '...', '--'),
55                         help="""Mount, run a command, then unmount and exit""")
56
57     args = parser.parse_args()
58     args.mountpoint = os.path.realpath(args.mountpoint)
59     if args.logfile:
60         args.logfile = os.path.realpath(args.logfile)
61
62     # Daemonize as early as possible, so we don't accidentally close
63     # file descriptors we're using.
64     if not (args.exec_args or args.foreground):
65         os.chdir(args.mountpoint)
66         daemon_ctx = daemon.DaemonContext(working_directory='.')
67         daemon_ctx.open()
68     else:
69         daemon_ctx = None
70
71     # Configure a log handler based on command-line switches.
72     if args.logfile:
73         log_handler = logging.FileHandler(args.logfile)
74     elif daemon_ctx:
75         log_handler = logging.NullHandler()
76     else:
77         log_handler = None
78
79     if log_handler is not None:
80         arvados.logger.removeHandler(arvados.log_handler)
81         arvados.logger.addHandler(log_handler)
82
83     if args.debug:
84         arvados.logger.setLevel(logging.DEBUG)
85         logger.debug("arv-mount debugging enabled")
86
87     try:
88         # Create the request handler
89         operations = Operations(os.getuid(),
90                                 os.getgid(),
91                                 encoding=args.encoding,
92                                 inode_cache=InodeCache(cap=args.directory_cache))
93         api = ThreadSafeApiCache(apiconfig=arvados.config.settings(),
94                                   keep_params={"block_cache": arvados.keep.KeepBlockCache(args.file_cache)})
95
96         usr = api.users().current().execute(num_retries=args.retries)
97         now = time.time()
98         dir_class = None
99         dir_args = [llfuse.ROOT_INODE, operations.inodes, api, args.retries]
100         if args.by_id:
101             # Set up the request handler with the 'magic directory' at the root
102             dir_class = MagicDirectory
103         elif args.by_tag:
104             dir_class = TagsDirectory
105         elif args.shared:
106             dir_class = SharedDirectory
107             dir_args.append(usr)
108         elif args.home:
109             dir_class = ProjectDirectory
110             dir_args.append(usr)
111             dir_args.append(True)
112         elif args.collection is not None:
113             # Set up the request handler with the collection at the root
114             dir_class = CollectionDirectory
115             dir_args.append(args.collection)
116         elif args.project is not None:
117             dir_class = ProjectDirectory
118             dir_args.append(api.groups().get(uuid=args.project).execute(
119                     num_retries=args.retries))
120
121         if dir_class is not None:
122             operations.inodes.add_entry(dir_class(*dir_args))
123         else:
124             e = operations.inodes.add_entry(Directory(llfuse.ROOT_INODE, operations.inodes))
125             dir_args[0] = e.inode
126
127             e._entries['by_id'] = operations.inodes.add_entry(MagicDirectory(*dir_args))
128             e._entries['by_tag'] = operations.inodes.add_entry(TagsDirectory(*dir_args))
129
130             dir_args.append(usr)
131             dir_args.append(True)
132             e._entries['home'] = operations.inodes.add_entry(ProjectDirectory(*dir_args))
133             e._entries['shared'] = operations.inodes.add_entry(SharedDirectory(*dir_args))
134
135             text = '''
136 Welcome to Arvados!  This directory provides file system access to files and objects
137 available on the Arvados installation located at '{}'
138 using credentials for user '{}'.
139
140 From here, the following directories are available:
141
142   by_id/     Access to Keep collections by uuid or portable data hash (see by_id/README for details).
143   by_tag/    Access to Keep collections organized by tag.
144   home/      The contents of your home project.
145   shared/    Projects shared with you.
146 '''.format(arvados.config.get('ARVADOS_API_HOST'), usr['email'])
147
148             e._entries["README"] = operations.inodes.add_entry(StringFile(e.inode, text, now))
149
150
151     except Exception:
152         logger.exception("arv-mount: exception during API setup")
153         exit(1)
154
155     # FUSE options, see mount.fuse(8)
156     opts = [optname for optname in ['allow_other', 'debug']
157             if getattr(args, optname)]
158
159     if args.exec_args:
160         # Initialize the fuse connection
161         llfuse.init(operations, args.mountpoint, opts)
162
163         t = threading.Thread(None, lambda: llfuse.main())
164         t.start()
165
166         # wait until the driver is finished initializing
167         operations.initlock.wait()
168
169         rc = 255
170         try:
171             sp = subprocess.Popen(args.exec_args, shell=False)
172
173             # forward signals to the process.
174             signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
175             signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
176             signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
177
178             # wait for process to complete.
179             rc = sp.wait()
180
181             # restore default signal handlers.
182             signal.signal(signal.SIGINT, signal.SIG_DFL)
183             signal.signal(signal.SIGTERM, signal.SIG_DFL)
184             signal.signal(signal.SIGQUIT, signal.SIG_DFL)
185         except Exception as e:
186             logger.exception('arv-mount: exception during exec %s',
187                              args.exec_args)
188             try:
189                 rc = e.errno
190             except AttributeError:
191                 pass
192         finally:
193             subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
194
195         exit(rc)
196     else:
197         try:
198             llfuse.init(operations, args.mountpoint, opts)
199             llfuse.main()
200         except Exception as e:
201             logger.exception('arv-mount: exception during mount')
202             exit(getattr(e, 'errno', 1))