3644: Added choose-your-own-adventure README files to the --all and --by-id
[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('--all', action='store_true', help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default).""")
31     mount_mode.add_argument('--home', action='store_true', help="""Mount only the user's home project.""")
32     mount_mode.add_argument('--shared', action='store_true', help="""Mount only list of projects shared with the user.""")
33     mount_mode.add_argument('--by-tag', action='store_true',
34                             help="""Mount subdirectories listed by tag.""")
35     mount_mode.add_argument('--by-id', action='store_true',
36                             help="""Mount subdirectories listed by portable data hash or uuid.""")
37     mount_mode.add_argument('--project', type=str, help="""Mount a specific project.""")
38     mount_mode.add_argument('--collection', type=str, help="""Mount only the specified collection.""")
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 = SafeApi(arvados.config)
90
91         usr = api.users().current().execute()
92         if args.by_id:
93             # Set up the request handler with the 'magic directory' at the root
94             operations.inodes.add_entry(MagicDirectory(llfuse.ROOT_INODE, operations.inodes, api))
95         elif args.by_tag:
96             operations.inodes.add_entry(TagsDirectory(llfuse.ROOT_INODE, operations.inodes, api))
97         elif args.shared:
98             operations.inodes.add_entry(SharedDirectory(llfuse.ROOT_INODE, operations.inodes, api, usr))
99         elif args.home:
100             operations.inodes.add_entry(ProjectDirectory(llfuse.ROOT_INODE, operations.inodes, api, usr))
101         elif args.collection != None:
102             # Set up the request handler with the collection at the root
103             operations.inodes.add_entry(CollectionDirectory(llfuse.ROOT_INODE, operations.inodes, api, args.collection))
104         elif args.project != None:            
105             operations.inodes.add_entry(ProjectDirectory(llfuse.ROOT_INODE, operations.inodes, api, api.groups().get(uuid=args.project).execute()))
106         else:
107             e = operations.inodes.add_entry(Directory(llfuse.ROOT_INODE))
108             e._entries['home'] = operations.inodes.add_entry(ProjectDirectory(e.inode, operations.inodes, api, usr))
109             e._entries['shared'] = operations.inodes.add_entry(SharedDirectory(e.inode, operations.inodes, api, usr))
110             e._entries['by_tag'] = operations.inodes.add_entry(TagsDirectory(e.inode, operations.inodes, api))
111             e._entries['by_id'] = operations.inodes.add_entry(MagicDirectory(e.inode, operations.inodes, api))
112
113             text = '''
114 Welcome to Arvados!  This directory provides file system access to files and objects 
115 available on the Arvados installation located at '{}' 
116 using credentials for user '{}'.
117
118 From here, the following directories are available:
119
120   by_id/     Access to Keep collections by uuid or portable data hash (see by_id/README for details).
121   by_tag/    Access to Keep collections organized by tag.
122   home/      The contents of your home project.
123   shared/    Projects shared with you.
124 '''.format(arvados.config.get('ARVADOS_API_HOST'), usr['email'])
125
126             e._entries["README"] = operations.inodes.add_entry(StringFile(e.inode, text, 0, 0))
127
128
129     except Exception:
130         logger.exception("arv-mount: exception during API setup")
131         exit(1)
132
133     # FUSE options, see mount.fuse(8)
134     opts = [optname for optname in ['allow_other', 'debug']
135             if getattr(args, optname)]
136
137     if args.exec_args:
138         # Initialize the fuse connection
139         llfuse.init(operations, args.mountpoint, opts)
140
141         t = threading.Thread(None, lambda: llfuse.main())
142         t.start()
143
144         # wait until the driver is finished initializing
145         operations.initlock.wait()
146
147         rc = 255
148         try:
149             sp = subprocess.Popen(args.exec_args, shell=False)
150
151             # forward signals to the process.
152             signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
153             signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
154             signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
155
156             # wait for process to complete.
157             rc = sp.wait()
158
159             # restore default signal handlers.
160             signal.signal(signal.SIGINT, signal.SIG_DFL)
161             signal.signal(signal.SIGTERM, signal.SIG_DFL)
162             signal.signal(signal.SIGQUIT, signal.SIG_DFL)
163         except Exception as e:
164             logger.exception('arv-mount: exception during exec %s',
165                              args.exec_args)
166             try:
167                 rc = e.errno
168             except AttributeError:
169                 pass
170         finally:
171             subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
172
173         exit(rc)
174     else:
175         try:
176             llfuse.init(operations, args.mountpoint, opts)
177             llfuse.main()
178         except Exception as e:
179             logger.exception('arv-mount: exception during mount')
180             exit(getattr(e, 'errno', 1))