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