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