13 import arvados.commands._util as arv_cmd
14 from arvados_fuse import *
15 from arvados.safeapi import ThreadSafeApiCache
18 logger = logging.getLogger('arvados.arv-mount')
21 def __init__(self, prefix, interval,
25 self.interval = interval
26 self.egr_name = egr_name
27 self.ing_name = ing_name
28 self.egress = egr_func
29 self.ingress = ing_func
30 self.egr_prev = self.egress()
31 self.ing_prev = self.ingress()
37 delta = " -- interval %.4f seconds %d %s %d %s" % (self.interval,
43 sys.stderr.write("crunchstat: %s %d %s %d %s%s\n" % (self.prefix,
54 def statlogger(interval, keep, ops):
55 calls = Stat("keepcalls", interval, "put", "get",
58 net = Stat("net:keep0", interval, "tx", "rx",
59 keep.upload_counter.get,
60 keep.download_counter.get)
61 cache = Stat("keepcache", interval, "hit", "miss",
62 keep.hits_counter.get,
63 keep.misses_counter.get)
64 fuseops = Stat("fuseops", interval,"write", "read",
65 ops.write_ops_counter.get,
66 ops.read_ops_counter.get)
67 blk = Stat("blkio:0:0", interval, "write", "read",
68 ops.write_counter.get,
80 if __name__ == '__main__':
81 # Handle command line parameters
82 parser = argparse.ArgumentParser(
83 parents=[arv_cmd.retry_opt],
84 description='''Mount Keep data under the local filesystem. Default mode is --home''',
86 Note: When using the --exec feature, you must either specify the
87 mountpoint before --exec, or mark the end of your --exec arguments
90 parser.add_argument('mountpoint', type=str, help="""Mount point.""")
91 parser.add_argument('--allow-other', action='store_true',
92 help="""Let other users read the mount""")
94 mount_mode = parser.add_mutually_exclusive_group()
96 mount_mode.add_argument('--all', action='store_const', const='all', dest='mode',
97 help="""Mount a subdirectory for each mode: home, shared, by_tag, by_id (default if no --mount-* arguments are given).""")
98 mount_mode.add_argument('--custom', action='store_const', const=None, dest='mode',
99 help="""Mount a top level meta-directory with subdirectories as specified by additional --mount-* arguments (default if any --mount-* arguments are given).""")
100 mount_mode.add_argument('--home', action='store_const', const='home', dest='mode',
101 help="""Mount only the user's home project.""")
102 mount_mode.add_argument('--shared', action='store_const', const='shared', dest='mode',
103 help="""Mount only list of projects shared with the user.""")
104 mount_mode.add_argument('--by-tag', action='store_const', const='by_tag', dest='mode',
105 help="""Mount subdirectories listed by tag.""")
106 mount_mode.add_argument('--by-id', action='store_const', const='by_id', dest='mode',
107 help="""Mount subdirectories listed by portable data hash or uuid.""")
108 mount_mode.add_argument('--by-pdh', action='store_const', const='by_pdh', dest='mode',
109 help="""Mount subdirectories listed by portable data hash.""")
110 mount_mode.add_argument('--project', type=str, metavar='UUID',
111 help="""Mount the specified project.""")
112 mount_mode.add_argument('--collection', type=str, metavar='UUID_or_PDH',
113 help="""Mount only the specified collection.""")
115 mounts = parser.add_argument_group('Custom mount options')
116 mounts.add_argument('--mount-by-pdh',
117 type=str, metavar='PATH', action='append', default=[],
118 help="Mount each readable collection at mountpoint/PATH/P where P is the collection's portable data hash.")
119 mounts.add_argument('--mount-by-id',
120 type=str, metavar='PATH', action='append', default=[],
121 help="Mount each readable collection at mountpoint/PATH/UUID and mountpoint/PATH/PDH where PDH is the collection's portable data hash and UUID is its UUID.")
122 mounts.add_argument('--mount-by-tag',
123 type=str, metavar='PATH', action='append', default=[],
124 help="Mount all collections with tag TAG at mountpoint/PATH/TAG/UUID.")
125 mounts.add_argument('--mount-home',
126 type=str, metavar='PATH', action='append', default=[],
127 help="Mount the current user's home project at mountpoint/PATH.")
128 mounts.add_argument('--mount-shared',
129 type=str, metavar='PATH', action='append', default=[],
130 help="Mount projects shared with the current user at mountpoint/PATH.")
131 mounts.add_argument('--mount-tmp',
132 type=str, metavar='PATH', action='append', default=[],
133 help="Create a new collection, mount it in read/write mode at mountpoint/PATH, and delete it when unmounting.")
135 parser.add_argument('--debug', action='store_true', help="""Debug mode""")
136 parser.add_argument('--logfile', help="""Write debug logs and errors to the specified file (default stderr).""")
137 parser.add_argument('--foreground', action='store_true', help="""Run in foreground (default is to daemonize unless --exec specified)""", default=False)
138 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")
140 parser.add_argument('--file-cache', type=int, help="File data cache size, in bytes (default 256MiB)", default=256*1024*1024)
141 parser.add_argument('--directory-cache', type=int, help="Directory data cache size, in bytes (default 128MiB)", default=128*1024*1024)
143 parser.add_argument('--read-only', action='store_false', help="Mount will be read only (default)", dest="enable_write", default=False)
144 parser.add_argument('--read-write', action='store_true', help="Mount will be read-write", dest="enable_write", default=False)
146 parser.add_argument('--crunchstat-interval', type=float, help="Write stats to stderr every N seconds (default disabled)", default=0)
148 parser.add_argument('--exec', type=str, nargs=argparse.REMAINDER,
149 dest="exec_args", metavar=('command', 'args', '...', '--'),
150 help="""Mount, run a command, then unmount and exit""")
152 args = parser.parse_args()
153 args.mountpoint = os.path.realpath(args.mountpoint)
155 args.logfile = os.path.realpath(args.logfile)
157 # Daemonize as early as possible, so we don't accidentally close
158 # file descriptors we're using.
159 if not (args.exec_args or args.foreground):
160 os.chdir(args.mountpoint)
161 daemon_ctx = daemon.DaemonContext(working_directory='.')
166 # Configure a log handler based on command-line switches.
168 log_handler = logging.FileHandler(args.logfile)
170 log_handler = logging.NullHandler()
174 if log_handler is not None:
175 arvados.logger.removeHandler(arvados.log_handler)
176 arvados.logger.addHandler(log_handler)
179 arvados.logger.setLevel(logging.DEBUG)
180 logger.debug("arv-mount debugging enabled")
182 logger.info("enable write is %s", args.enable_write)
185 api = ThreadSafeApiCache(apiconfig=arvados.config.settings(),
186 keep_params={"block_cache": arvados.keep.KeepBlockCache(args.file_cache)})
188 # Create the request handler
189 operations = Operations(os.getuid(),
192 encoding=args.encoding,
193 inode_cache=InodeCache(cap=args.directory_cache),
194 enable_write=args.enable_write)
196 if args.crunchstat_interval:
197 statsthread = threading.Thread(target=statlogger, args=(args.crunchstat_interval, api.keep, operations))
198 statsthread.daemon = True
201 usr = api.users().current().execute(num_retries=args.retries)
204 dir_args = [llfuse.ROOT_INODE, operations.inodes, api, args.retries]
207 if args.mode is not None and (
214 args.mount_collection):
215 sys.exit("Cannot combine '{}' mode with custom --mount-* options.".
218 if args.mode in ['by_id', 'by_pdh']:
219 # Set up the request handler with the 'magic directory' at the root
220 dir_class = MagicDirectory
221 dir_args.append(args.mode == 'by_pdh')
222 elif args.mode == 'by_tag':
223 dir_class = TagsDirectory
224 elif args.mode == 'shared':
225 dir_class = SharedDirectory
227 elif args.mode == 'home':
228 dir_class = ProjectDirectory
230 dir_args.append(True)
231 elif args.mode == 'all':
232 args.mount_by_id = ['by_id']
233 args.mount_by_tag = ['by_tag']
234 args.mount_home = ['home']
235 args.mount_shared = ['shared']
237 elif args.collection is not None:
238 # Set up the request handler with the collection at the root
239 dir_class = CollectionDirectory
240 dir_args.append(args.collection)
241 elif args.project is not None:
242 dir_class = ProjectDirectory
243 dir_args.append(api.groups().get(uuid=args.project).execute(
244 num_retries=args.retries))
246 if dir_class is not None:
247 operations.inodes.add_entry(dir_class(*dir_args))
249 e = operations.inodes.add_entry(Directory(llfuse.ROOT_INODE, operations.inodes))
250 dir_args[0] = e.inode
252 def addMount(tld, name, ent):
253 if name in ['', '.', '..'] or '/' in name:
254 sys.exit("Mount point '{}' is not supported.".format(name))
255 tld._entries[name] = operations.inodes.add_entry(ent)
257 for name in args.mount_by_id:
258 addMount(e, name, MagicDirectory(*dir_args, pdh_only=False))
259 for name in args.mount_by_pdh:
260 addMount(e, name, MagicDirectory(*dir_args, pdh_only=True))
261 for name in args.mount_by_tag:
262 addMount(e, name, TagsDirectory(*dir_args))
263 for name in args.mount_home:
264 addMount(e, name, ProjectDirectory(*dir_args, project_object=usr, poll=True))
265 for name in args.mount_shared:
266 addMount(e, name, SharedDirectory(*dir_args, exclude=usr, poll=True))
267 for name in args.mount_tmp:
268 addMount(e, name, TmpCollectionDirectory(*dir_args))
272 Welcome to Arvados! This directory provides file system access to
273 files and objects available on the Arvados installation located at
274 '{}' using credentials for user '{}'.
276 From here, the following directories are available:
278 by_id/ Access to Keep collections by uuid or portable data hash (see by_id/README for details).
279 by_tag/ Access to Keep collections organized by tag.
280 home/ The contents of your home project.
281 shared/ Projects shared with you.
282 '''.format(arvados.config.get('ARVADOS_API_HOST'), usr['email'])
283 addMount(e, StringFile(e.inode, text, now))
286 logger.exception("arv-mount: exception during API setup")
289 # FUSE options, see mount.fuse(8)
290 opts = [optname for optname in ['allow_other', 'debug']
291 if getattr(args, optname)]
293 # Increase default read/write size from 4KiB to 128KiB
294 opts += ["big_writes", "max_read=131072"]
297 # Initialize the fuse connection
298 llfuse.init(operations, args.mountpoint, opts)
300 # Subscribe to change events from API server
301 if args.mode != 'by_pdh':
302 operations.listen_for_events()
304 t = threading.Thread(None, lambda: llfuse.main())
307 # wait until the driver is finished initializing
308 operations.initlock.wait()
312 sp = subprocess.Popen(args.exec_args, shell=False)
314 # forward signals to the process.
315 signal.signal(signal.SIGINT, lambda signum, frame: sp.send_signal(signum))
316 signal.signal(signal.SIGTERM, lambda signum, frame: sp.send_signal(signum))
317 signal.signal(signal.SIGQUIT, lambda signum, frame: sp.send_signal(signum))
319 # wait for process to complete.
322 # restore default signal handlers.
323 signal.signal(signal.SIGINT, signal.SIG_DFL)
324 signal.signal(signal.SIGTERM, signal.SIG_DFL)
325 signal.signal(signal.SIGQUIT, signal.SIG_DFL)
326 except Exception as e:
327 logger.exception('arv-mount: exception during exec %s',
331 except AttributeError:
334 subprocess.call(["fusermount", "-u", "-z", args.mountpoint])
340 llfuse.init(operations, args.mountpoint, opts)
342 # Subscribe to change events from API server
343 operations.listen_for_events()
346 except Exception as e:
347 logger.exception('arv-mount: exception during mount')
348 exit(getattr(e, 'errno', 1))