1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
12 MountInfo = collections.namedtuple(
13 'MountInfo', ['is_fuse', 'major', 'minor', 'mnttype', 'path'])
18 with open('/proc/self/mountinfo') as f:
19 for m in f.readlines():
20 mntid, pmntid, dev, root, path, extra = m.split(" ", 5)
21 mnttype = extra.split(" - ")[1].split(" ", 1)[0]
22 major, minor = dev.split(":")
24 is_fuse=(mnttype == "fuse" or mnttype.startswith("fuse.")),
33 def paths_to_unmount(path, mnttype):
36 if m.path == path or m.path.startswith(path+"/"):
38 if not (m.is_fuse and (mnttype is None or
39 mnttype == m.mnttype)):
41 "cannot unmount {}: mount type is {}".format(
46 def safer_realpath(path, loop=True):
47 """Similar to os.path.realpath(), but avoids calling lstat().
49 Leaves some symlinks unresolved."""
52 elif not path.startswith('/'):
53 path = os.path.abspath(path)
55 path = path.rstrip('/')
56 dirname, basename = os.path.split(path)
58 path, resolved = safer_realpath(os.path.join(dirname, os.readlink(path)), loop=False)
60 # Path is not a symlink (EINVAL), or is unreadable, or
61 # doesn't exist. If the error was EINVAL and dirname can
62 # be resolved, we will have eliminated all symlinks and it
63 # will be safe to call normpath().
64 dirname, resolved = safer_realpath(dirname, loop=loop)
65 path = os.path.join(dirname, basename)
66 if resolved and e.errno == errno.EINVAL:
67 return os.path.normpath(path), True
72 # Unwind to the point where we first started following
75 # Resolving the whole path landed in a symlink cycle, but
76 # we might still be able to resolve dirname.
77 dirname, _ = safer_realpath(dirname, loop=loop)
78 return os.path.join(dirname, basename), False
81 def unmount(path, subtype=None, timeout=10, recursive=False):
82 """Unmount the fuse mount at path.
84 Unmounting is done by writing 1 to the "abort" control file in
85 sysfs to kill the fuse driver process, then executing "fusermount
86 -u -z" to detach the mount point, and repeating these steps until
87 the mount is no longer listed in /proc/self/mountinfo.
89 This procedure should enable a non-root user to reliably unmount
90 their own fuse filesystem without risk of deadlock.
92 Returns True if unmounting was successful, False if it wasn't a
93 fuse mount at all. Raises an exception if it cannot be unmounted.
96 path, _ = safer_realpath(path)
103 mnttype = 'fuse.' + subtype
106 paths = paths_to_unmount(path, mnttype)
108 # We might not have found any mounts merely because path
109 # contains symlinks, so we should resolve them and try
110 # again. We didn't do this from the outset because
111 # realpath() can hang (see explanation below).
112 paths = paths_to_unmount(os.path.realpath(path), mnttype)
113 for path in sorted(paths, key=len, reverse=True):
114 unmount(path, timeout=timeout, recursive=False)
115 return len(paths) > 0
119 fusermount_output = b''
123 deadline = time.time() + timeout
127 for m in mountinfo():
128 if m.is_fuse and (mnttype is None or mnttype == m.mnttype):
136 if not was_mounted and path != os.path.realpath(path):
137 # If the specified path contains symlinks, it won't appear
138 # verbatim in mountinfo.
140 # It might seem like we should have called realpath() from
141 # the outset. But we can't: realpath() hangs (in lstat())
142 # if we call it on an unresponsive mount point, and this
143 # is an important and common scenario.
145 # By waiting until now to try realpath(), we avoid this
146 # problem in the most common cases, which are: (1) the
147 # specified path has no symlinks and is a mount point, in
148 # which case was_mounted==True and we can proceed without
149 # calling realpath(); and (2) the specified path is not a
150 # mount point (e.g., it was already unmounted by someone
151 # else, or it's a typo), and realpath() can determine that
152 # without hitting any other unresponsive mounts.
153 path = os.path.realpath(path)
159 # Report buffered stderr from previous call to fusermount,
160 # now that we know it didn't succeed.
161 sys.stderr.write(fusermount_output)
165 delay = min(delay, deadline - time.time())
167 raise Exception("timed out")
171 with open('/sys/fs/fuse/connections/{}/abort'.format(m.minor),
175 if e.errno != errno.ENOENT:
180 subprocess.check_output(
181 ["fusermount", "-u", "-z", path],
182 stderr=subprocess.STDOUT)
183 except subprocess.CalledProcessError as e:
184 fusermount_output = e.output
186 fusermount_output = b''