12 import arvados.commands._util as arv_cmd
13 from arvados_fuse import *
14 from arvados.safeapi import ThreadSafeApiCache
17 logger = logging.getLogger('arvados.arv-mount')
19 if __name__ == '__main__':
20 # Handle command line parameters
21 parser = argparse.ArgumentParser(
22 parents=[arv_cmd.retry_opt],
23 description='''Mount Keep data under the local filesystem. Default mode is --home''',
25 Note: When using the --exec feature, you must either specify the
26 mountpoint before --exec, or mark the end of your --exec arguments
29 parser.add_argument('mountpoint', type=str, help="""Mount point.""")
30 parser.add_argument('--allow-other', action='store_true',
31 help="""Let other users read the mount""")
33 mount_mode = parser.add_mutually_exclusive_group()
35 mount_mode.add_argument('--all', action='store_true', help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default).""")
36 mount_mode.add_argument('--home', action='store_true', help="""Mount only the user's home project.""")
37 mount_mode.add_argument('--shared', action='store_true', help="""Mount only list of projects shared with the user.""")
38 mount_mode.add_argument('--by-tag', action='store_true',
39 help="""Mount subdirectories listed by tag.""")
40 mount_mode.add_argument('--by-id', action='store_true',
41 help="""Mount subdirectories listed by portable data hash or uuid.""")
42 mount_mode.add_argument('--by-pdh', action='store_true',
43 help="""Mount subdirectories listed by portable data hash.""")
44 mount_mode.add_argument('--project', type=str, help="""Mount a specific project.""")
45 mount_mode.add_argument('--collection', type=str, help="""Mount only the specified collection.""")
47 parser.add_argument('--debug', action='store_true', help="""Debug mode""")
48 parser.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
49 parser.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
50 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")
52 parser.add_argument('--file-cache', type=int, help="File data cache size, in bytes (default 256MiB)", default=256*1024*1024)
53 parser.add_argument('--directory-cache', type=int, help="Directory data cache size, in bytes (default 128MiB)", default=128*1024*1024)
55 parser.add_argument('--read-only', action='store_false', help="Mount will be read only (default)", dest="enable_write", default=False)
56 parser.add_argument('--read-write', action='store_true', help="Mount will be read-write", dest="enable_write", default=False)
58 parser.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
59 dest="exec_args", metavar=('command', 'args', '...', '--'),
60 help="""Mount, run a command, then unmount and exit""")
62 args = parser.parse_args()
63 args.mountpoint = os.path.realpath(args.mountpoint)
65 args.logfile = os.path.realpath(args.logfile)
67 # Daemonize as early as possible, so we don't accidentally close
68 # file descriptors we're using.
69 if not (args.exec_args or args.foreground):
70 os.chdir(args.mountpoint)
71 daemon_ctx = daemon.DaemonContext(working_directory='.')
76 # Configure a log handler based on command-line switches.
78 log_handler = logging.FileHandler(args.logfile)
80 log_handler = logging.NullHandler()
84 if log_handler is not None:
85 arvados.logger.removeHandler(arvados.log_handler)
86 arvados.logger.addHandler(log_handler)
89 arvados.logger.setLevel(logging.DEBUG)
90 logger.debug("arv-mount debugging enabled")
92 logger.info("enable write is %s", args.enable_write)
95 # Create the request handler
96 operations = Operations(os.getuid(),
98 encoding=args.encoding,
99 inode_cache=InodeCache(cap=args.directory_cache),
100 enable_write=args.enable_write)
101 api = ThreadSafeApiCache(apiconfig=arvados.config.settings(),
102 keep_params={"block_cache": arvados.keep.KeepBlockCache(args.file_cache)})
104 usr = api.users().current().execute(num_retries=args.retries)
107 dir_args = [llfuse.ROOT_INODE, operations.inodes, api, args.retries]
108 if args.by_id or args.by_pdh:
109 # Set up the request handler with the 'magic directory' at the root
110 dir_class = MagicDirectory
112 dir_class = TagsDirectory
114 dir_class = SharedDirectory
117 dir_class = ProjectDirectory
119 dir_args.append(True)
120 elif args.collection is not None:
121 # Set up the request handler with the collection at the root
122 dir_class = CollectionDirectory
123 dir_args.append(args.collection)
124 elif args.project is not None:
125 dir_class = ProjectDirectory
126 dir_args.append(api.groups().get(uuid=args.project).execute(
127 num_retries=args.retries))
129 if dir_class is not None:
130 operations.inodes.add_entry(dir_class(*dir_args))
132 e = operations.inodes.add_entry(Directory(llfuse.ROOT_INODE, operations.inodes))
133 dir_args[0] = e.inode
135 e._entries['by_id'] = operations.inodes.add_entry(MagicDirectory(*dir_args, pdh_only=True if args.by_pdh else False))
137 e._entries['by_tag'] = operations.inodes.add_entry(TagsDirectory(*dir_args))
140 dir_args.append(True)
141 e._entries['home'] = operations.inodes.add_entry(ProjectDirectory(*dir_args))
142 e._entries['shared'] = operations.inodes.add_entry(SharedDirectory(*dir_args))
145 Welcome to Arvados! This directory provides file system access to files and objects
146 available on the Arvados installation located at '{}'
147 using credentials for user '{}'.
149 From here, the following directories are available:
151 by_id/ Access to Keep collections by uuid or portable data hash (see by_id/README for details).
152 by_tag/ Access to Keep collections organized by tag.
153 home/ The contents of your home project.
154 shared/ Projects shared with you.
155 '''.format(arvados.config.get('ARVADOS_API_HOST'), usr['email'])
157 e._entries["README"] = operations.inodes.add_entry(StringFile(e.inode, text, now))
161 logger.exception("arv-mount: exception during API setup")
164 # FUSE options, see mount.fuse(8)
165 opts = [optname for optname in ['allow_other', 'debug']
166 if getattr(args, optname)]
168 # Increase default read/write size from 4KiB to 128KiB
169 opts += ["big_writes", "max_read=131072"]
172 # Initialize the fuse connection
173 llfuse.init(operations, args.mountpoint, opts)
175 # Subscribe to change events from API server
177 operations.listen_for_events(api)
179 t = threading.Thread(None, lambda: llfuse.main())
182 # wait until the driver is finished initializing
183 operations.initlock.wait()
187 sp = subprocess.Popen(args.exec_args, shell=False)
189 # forward signals to the process.
190 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
191 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
192 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
194 # wait for process to complete.
197 # restore default signal handlers.
198 signal.signal(signal.SIGINT, signal.SIG_DFL)
199 signal.signal(signal.SIGTERM, signal.SIG_DFL)
200 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
201 except Exception as e:
202 logger.exception('arv-mount: exception during exec %s',
206 except AttributeError:
209 subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
215 llfuse.init(operations, args.mountpoint, opts)
217 # Subscribe to change events from API server
218 operations.listen_for_events(api)
221 except Exception as e:
222 logger.exception('arv-mount: exception during mount')
223 exit(getattr(e, 'errno', 1))