12 import arvados.commands._util as arv_cmd
13 from arvados_fuse import *
14 from arvados.safeapi import ThreadSafeApiCache
16 logger = logging.getLogger('arvados.arv-mount')
18 if __name__ == '__main__':
19 # Handle command line parameters
20 parser = argparse.ArgumentParser(
21 parents=[arv_cmd.retry_opt],
22 description='''Mount Keep data under the local filesystem. Default mode is --home''',
24 Note: When using the --exec feature, you must either specify the
25 mountpoint before --exec, or mark the end of your --exec arguments
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""")
32 mount_mode = parser.add_mutually_exclusive_group()
34 mount_mode.add_argument('--all', action='store_true', help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default).""")
35 mount_mode.add_argument('--home', action='store_true', help="""Mount only the user's home project.""")
36 mount_mode.add_argument('--shared', action='store_true', help="""Mount only list of projects shared with the user.""")
37 mount_mode.add_argument('--by-tag', action='store_true',
38 help="""Mount subdirectories listed by tag.""")
39 mount_mode.add_argument('--by-id', action='store_true',
40 help="""Mount subdirectories listed by portable data hash or uuid.""")
41 mount_mode.add_argument('--project', type=str, help="""Mount a specific project.""")
42 mount_mode.add_argument('--collection', type=str, help="""Mount only the specified collection.""")
44 parser.add_argument('--debug', action='store_true', help="""Debug mode""")
45 parser.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
46 parser.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
47 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")
49 parser.add_argument('--inode-cache', type=int, help="Inode cache size (default 128MiB)", default=128*1024*1024)
51 parser.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
52 dest="exec_args", metavar=('command', 'args', '...', '--'),
53 help="""Mount, run a command, then unmount and exit""")
55 args = parser.parse_args()
56 args.mountpoint = os.path.realpath(args.mountpoint)
58 args.logfile = os.path.realpath(args.logfile)
60 # Daemonize as early as possible, so we don't accidentally close
61 # file descriptors we're using.
62 if not (args.exec_args or args.foreground):
63 os.chdir(args.mountpoint)
64 daemon_ctx = daemon.DaemonContext(working_directory='.')
69 # Configure a log handler based on command-line switches.
71 log_handler = logging.FileHandler(args.logfile)
73 log_handler = logging.NullHandler()
77 if log_handler is not None:
78 arvados.logger.removeHandler(arvados.log_handler)
79 arvados.logger.addHandler(log_handler)
82 arvados.logger.setLevel(logging.DEBUG)
83 logger.debug("arv-mount debugging enabled")
86 # Create the request handler
87 operations = Operations(os.getuid(), os.getgid(), args.encoding,
88 arvados_fuse.InodeCache(args.inode_cache))
89 api = ThreadSafeApiCache(arvados.config.settings())
91 usr = api.users().current().execute(num_retries=args.retries)
94 dir_args = [llfuse.ROOT_INODE, operations.inodes, api, args.retries]
96 # Set up the request handler with the 'magic directory' at the root
97 dir_class = MagicDirectory
99 dir_class = TagsDirectory
101 dir_class = SharedDirectory
104 dir_class = ProjectDirectory
106 dir_args.append(True)
107 elif args.collection is not None:
108 # Set up the request handler with the collection at the root
109 dir_class = CollectionDirectory
110 dir_args.append(args.collection)
111 elif args.project is not None:
112 dir_class = ProjectDirectory
113 dir_args.append(api.groups().get(uuid=args.project).execute(
114 num_retries=args.retries))
116 if dir_class is not None:
117 operations.inodes.add_entry(dir_class(*dir_args))
119 e = operations.inodes.add_entry(Directory(llfuse.ROOT_INODE, operations.inodes))
120 dir_args[0] = e.inode
122 e._entries['by_id'] = operations.inodes.add_entry(MagicDirectory(*dir_args))
123 e._entries['by_tag'] = operations.inodes.add_entry(TagsDirectory(*dir_args))
126 dir_args.append(True)
127 e._entries['home'] = operations.inodes.add_entry(ProjectDirectory(*dir_args))
128 e._entries['shared'] = operations.inodes.add_entry(SharedDirectory(*dir_args))
131 Welcome to Arvados! This directory provides file system access to files and objects
132 available on the Arvados installation located at '{}'
133 using credentials for user '{}'.
135 From here, the following directories are available:
137 by_id/ Access to Keep collections by uuid or portable data hash (see by_id/README for details).
138 by_tag/ Access to Keep collections organized by tag.
139 home/ The contents of your home project.
140 shared/ Projects shared with you.
141 '''.format(arvados.config.get('ARVADOS_API_HOST'), usr['email'])
143 e._entries["README"] = operations.inodes.add_entry(StringFile(e.inode, text, now))
147 logger.exception("arv-mount: exception during API setup")
150 # FUSE options, see mount.fuse(8)
151 opts = [optname for optname in ['allow_other', 'debug']
152 if getattr(args, optname)]
155 # Initialize the fuse connection
156 llfuse.init(operations, args.mountpoint, opts)
158 t = threading.Thread(None, lambda: llfuse.main())
161 # wait until the driver is finished initializing
162 operations.initlock.wait()
166 sp = subprocess.Popen(args.exec_args, shell=False)
168 # forward signals to the process.
169 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
170 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
171 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
173 # wait for process to complete.
176 # restore default signal handlers.
177 signal.signal(signal.SIGINT, signal.SIG_DFL)
178 signal.signal(signal.SIGTERM, signal.SIG_DFL)
179 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
180 except Exception as e:
181 logger.exception('arv-mount: exception during exec %s',
185 except AttributeError:
188 subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
193 llfuse.init(operations, args.mountpoint, opts)
195 except Exception as e:
196 logger.exception('arv-mount: exception during mount')
197 exit(getattr(e, 'errno', 1))