3644: More renaming GroupDirectory to ProjectDirectory, removing name links.
[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.  Default mode is --home''',
19         epilog="""
20 Note: When using the --exec feature, you must either specify the
21 mountpoint before --exec, or mark the end of your --exec arguments
22 with "--".
23 """)
24     parser.add_argument('mountpoint', type=str, help="""Mount point.""")
25     parser.add_argument('--allow-other', action='store_true',
26                         help="""Let other users read the mount""")
27
28     mount_mode = parser.add_mutually_exclusive_group()
29
30     mount_mode.add_argument('--home', action='store_true', help="""Mount the user's home project (default).""")
31     mount_mode.add_argument('--collection', type=str, help="""Mount only the specified collection at the mount point.""")
32     mount_mode.add_argument('--tags', action='store_true',
33                             help="""Mount as a virtual directory consisting of subdirectories representing
34 tagged collections on the server.""")
35     mount_mode.add_argument('--project', type=str, help="""Mount a specific project by uuid.""")
36     mount_mode.add_argument('--by-hash', action='store_true',
37                             help="""Mount as a virtual directory consisting of subdirectories for each
38 collection by portable data hash.""")
39
40     parser.add_argument('--debug', action='store_true', help="""Debug mode""")
41     parser.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
42     parser.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
43     parser.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
44                         dest="exec_args", metavar=('command', 'args', '...', '--'),
45                         help="""Mount, run a command, then unmount and exit""")
46
47     args = parser.parse_args()
48     args.mountpoint = os.path.realpath(args.mountpoint)
49     if args.logfile:
50         args.logfile = os.path.realpath(args.logfile)
51
52     # Daemonize as early as possible, so we don't accidentally close
53     # file descriptors we're using.
54     if not (args.exec_args or args.foreground):
55         os.chdir(args.mountpoint)
56         daemon_ctx = daemon.DaemonContext(working_directory='.')
57         daemon_ctx.open()
58     else:
59         daemon_ctx = None
60
61     # Configure a logger based on command-line switches.
62     # If we're using a contemporary Python SDK (mid-August 2014),
63     # configure the arvados hierarchy logger.
64     # Otherwise, configure the program root logger.
65     base_logger = getattr(arvados, 'logger', None)
66
67     if args.logfile:
68         log_handler = logging.FileHandler(args.logfile)
69     elif daemon_ctx:
70         log_handler = logging.NullHandler()
71     elif base_logger:
72         log_handler = arvados.log_handler
73     else:
74         log_handler = logging.StreamHandler()
75
76     if base_logger is None:
77         base_logger = logging.getLogger()
78     else:
79         base_logger.removeHandler(arvados.log_handler)
80     base_logger.addHandler(log_handler)
81
82     if args.debug:
83         base_logger.setLevel(logging.DEBUG)
84         logger.debug("arv-mount debugging enabled")
85
86     try:
87         # Create the request handler
88         operations = Operations(os.getuid(), os.getgid())
89         api = arvados.api('v1')
90
91         if args.by_hash:
92             # Set up the request handler with the 'magic directory' at the root
93             operations.inodes.add_entry(MagicDirectory(llfuse.ROOT_INODE, operations.inodes))
94         elif args.tags:
95             e = operations.inodes.add_entry(TagsDirectory(llfuse.ROOT_INODE, operations.inodes, api))
96         elif args.collection != None:
97             # Set up the request handler with the collection at the root
98             e = operations.inodes.add_entry(CollectionDirectory(llfuse.ROOT_INODE, operations.inodes, args.collection))
99         elif args.project != None:
100             e = operations.inodes.add_entry(ProjectDirectory(llfuse.ROOT_INODE, operations.inodes, args.project))
101         else:
102             e = operations.inodes.add_entry(HomeDirectory(llfuse.ROOT_INODE, operations.inodes, api))
103
104     except Exception:
105         logger.exception("arv-mount: exception during API setup")
106         exit(1)
107
108     # FUSE options, see mount.fuse(8)
109     opts = [optname for optname in ['allow_other', 'debug']
110             if getattr(args, optname)]
111
112     if args.exec_args:
113         # Initialize the fuse connection
114         llfuse.init(operations, args.mountpoint, opts)
115
116         t = threading.Thread(None, lambda: llfuse.main())
117         t.start()
118
119         # wait until the driver is finished initializing
120         operations.initlock.wait()
121
122         rc = 255
123         try:
124             sp = subprocess.Popen(args.exec_args, shell=False)
125
126             # forward signals to the process.
127             signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
128             signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
129             signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
130
131             # wait for process to complete.
132             rc = sp.wait()
133
134             # restore default signal handlers.
135             signal.signal(signal.SIGINT, signal.SIG_DFL)
136             signal.signal(signal.SIGTERM, signal.SIG_DFL)
137             signal.signal(signal.SIGQUIT, signal.SIG_DFL)
138         except Exception as e:
139             logger.exception('arv-mount: exception during exec %s',
140                              args.exec_args)
141             try:
142                 rc = e.errno
143             except AttributeError:
144                 pass
145         finally:
146             subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
147
148         exit(rc)
149     else:
150         try:
151             llfuse.init(operations, args.mountpoint, opts)
152             llfuse.main()
153         except Exception as e:
154             logger.exception('arv-mount: exception during mount')
155             exit(getattr(e, 'errno', 1))