2800: Allow api() caller to specify api host and token.
[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 traceback
11
12 from arvados_fuse import *
13
14 if __name__ == '__main__':
15     # Handle command line parameters
16     parser = argparse.ArgumentParser(
17         description='''Mount Keep data under the local filesystem.  By default, if neither
18         --collection or --tags is specified, this mounts as a virtual directory
19         under which all Keep collections are available as subdirectories named
20         with the Keep locator; however directories will not be visible to 'ls'
21         until a program tries to access them.''',
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     parser.add_argument('--collection', type=str, help="""Mount only the specified collection at the mount point.""")
31     parser.add_argument('--tags', action='store_true', help="""Mount as a virtual directory consisting of subdirectories representing tagged
32 collections on the server.""")
33     parser.add_argument('--groups', action='store_true', help="""Mount as a virtual directory consisting of subdirectories representing groups on the server.""")
34     parser.add_argument('--debug', action='store_true', help="""Debug mode""")
35     parser.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
36     parser.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
37     parser.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
38                         dest="exec_args", metavar=('command', 'args', '...', '--'),
39                         help="""Mount, run a command, then unmount and exit""")
40
41     args = parser.parse_args()
42     args.mountpoint = os.path.realpath(args.mountpoint)
43     if args.logfile:
44         args.logfile = os.path.realpath(args.logfile)
45
46     # Daemonize as early as possible, so we don't accidentally close
47     # file descriptors we're using.
48     if not (args.exec_args or args.foreground):
49         os.chdir(args.mountpoint)
50         daemon_ctx = daemon.DaemonContext(working_directory='.')
51         daemon_ctx.open()
52     else:
53         daemon_ctx = None
54
55     # Set up logging.
56     # If we're daemonized without a logfile, there's nowhere to log, so don't.
57     if args.logfile or (daemon_ctx is None):
58         log_conf = {}
59         if args.debug:
60             log_conf['level'] = logging.DEBUG
61             arvados.config.settings()['ARVADOS_DEBUG'] = 'true'
62         if args.logfile:
63             log_conf['filename'] = args.logfile
64         logging.basicConfig(**log_conf)
65         logging.debug("arv-mount debugging enabled")
66
67     try:
68         # Create the request handler
69         operations = Operations(os.getuid(), os.getgid())
70         api = arvados.api('v1')
71
72         if args.groups:
73             e = operations.inodes.add_entry(GroupsDirectory(llfuse.ROOT_INODE, operations.inodes, api))
74         elif args.tags:
75             e = operations.inodes.add_entry(TagsDirectory(llfuse.ROOT_INODE, operations.inodes, api))
76         elif args.collection != None:
77             # Set up the request handler with the collection at the root
78             e = operations.inodes.add_entry(CollectionDirectory(llfuse.ROOT_INODE, operations.inodes, args.collection))
79         else:
80             # Set up the request handler with the 'magic directory' at the root
81             operations.inodes.add_entry(MagicDirectory(llfuse.ROOT_INODE, operations.inodes))
82     except Exception as ex:
83         logging.error("arv-mount: exception during API setup")
84         logging.error(traceback.format_exc())
85         exit(1)
86
87     # FUSE options, see mount.fuse(8)
88     opts = [optname for optname in ['allow_other', 'debug']
89             if getattr(args, optname)]
90
91     if args.exec_args:
92         # Initialize the fuse connection
93         llfuse.init(operations, args.mountpoint, opts)
94
95         t = threading.Thread(None, lambda: llfuse.main())
96         t.start()
97
98         # wait until the driver is finished initializing
99         operations.initlock.wait()
100
101         rc = 255
102         try:
103             sp = subprocess.Popen(args.exec_args, shell=False)
104
105             # forward signals to the process.
106             signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
107             signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
108             signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
109
110             # wait for process to complete.
111             rc = sp.wait()
112
113             # restore default signal handlers.
114             signal.signal(signal.SIGINT, signal.SIG_DFL)
115             signal.signal(signal.SIGTERM, signal.SIG_DFL)
116             signal.signal(signal.SIGQUIT, signal.SIG_DFL)
117         except Exception as e:
118             logging.error('arv-mount: exception during exec %s' % (args.exec_args,))
119             logging.error(traceback.format_exc())
120             try:
121                 rc = e.errno
122             except AttributeError:
123                 pass
124         finally:
125             subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
126
127         exit(rc)
128     else:
129         try:
130             llfuse.init(operations, args.mountpoint, opts)
131             llfuse.main()
132         except Exception as e:
133             logging.error('arv-mount: exception during mount')
134             logging.error(traceback.format_exc())
135             exit(getattr(e, 'errno', 1))