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