Merge branch '11332-fix-crunchscript' refs #11332
[arvados.git] / services / fuse / arvados_fuse / unmount.py
1 import collections
2 import errno
3 import os
4 import subprocess
5 import time
6
7
8 MountInfo = collections.namedtuple(
9     'MountInfo', ['is_fuse', 'major', 'minor', 'mnttype', 'path'])
10
11
12 def mountinfo():
13     mi = []
14     with open('/proc/self/mountinfo') as f:
15         for m in f.readlines():
16             mntid, pmntid, dev, root, path, extra = m.split(" ", 5)
17             mnttype = extra.split(" - ")[1].split(" ", 1)[0]
18             major, minor = dev.split(":")
19             mi.append(MountInfo(
20                 is_fuse=(mnttype == "fuse" or mnttype.startswith("fuse.")),
21                 major=major,
22                 minor=minor,
23                 mnttype=mnttype,
24                 path=path,
25             ))
26     return mi
27
28
29 def unmount(path, timeout=10, recursive=False):
30     """Unmount the fuse mount at path.
31
32     Unmounting is done by writing 1 to the "abort" control file in
33     sysfs to kill the fuse driver process, then executing "fusermount
34     -u -z" to detach the mount point, and repeating these steps until
35     the mount is no longer listed in /proc/self/mountinfo.
36
37     This procedure should enable a non-root user to reliably unmount
38     their own fuse filesystem without risk of deadlock.
39
40     Returns True if unmounting was successful, False if it wasn't a
41     fuse mount at all. Raises an exception if it cannot be unmounted.
42     """
43
44     path = os.path.realpath(path)
45
46     if recursive:
47         paths = []
48         for m in mountinfo():
49             if m.path == path or m.path.startswith(path+"/"):
50                 paths.append(m.path)
51                 if not m.is_fuse:
52                     raise Exception(
53                         "cannot unmount {}: non-fuse mountpoint {}".format(
54                             path, m))
55         for path in sorted(paths, key=len, reverse=True):
56             unmount(path, timeout=timeout, recursive=False)
57         return len(paths) > 0
58
59     was_mounted = False
60     attempted = False
61     if timeout is None:
62         deadline = None
63     else:
64         deadline = time.time() + timeout
65
66     while True:
67         mounted = False
68         for m in mountinfo():
69             if m.is_fuse:
70                 try:
71                     if os.path.realpath(m.path) == path:
72                         was_mounted = True
73                         mounted = True
74                         break
75                 except OSError:
76                     continue
77         if not mounted:
78             return was_mounted
79
80         if attempted:
81             delay = 1
82             if deadline:
83                 delay = min(delay, deadline - time.time())
84                 if delay <= 0:
85                     raise Exception("timed out")
86             time.sleep(delay)
87
88         try:
89             with open('/sys/fs/fuse/connections/{}/abort'.format(m.minor),
90                       'w') as f:
91                 f.write("1")
92         except OSError as e:
93             if e.errno != errno.ENOENT:
94                 raise
95
96         attempted = True
97         try:
98             subprocess.check_call(["fusermount", "-u", "-z", path])
99         except subprocess.CalledProcessError:
100             pass