- Check if the given device is mounted, optionally validating destination.
- This relies on absolute path devices, it will ignore non-absolute
- entries like::
+ Detect if a file path is a binary or not. Will falsely report as binary
+ when utf-16 encoded. In the ceph universe there is no such risk (yet)
+ """
+ with open(path, 'rb') as fp:
+ contents = fp.read(8192)
+ if b'\x00' in contents: # a null byte may signal binary
+ return True
+ return False
+
+
+class tmp_mount(object):
+ """
+ Temporarily mount a device on a temporary directory,
+ and unmount it upon exit
+ """
+
+ def __init__(self, device):
+ self.device = device
+ self.path = None
+
+ def __enter__(self):
+ self.path = tempfile.mkdtemp()
+ process.run([
+ 'sudo',
+ 'mount',
+ '-v',
+ self.device,
+ self.path
+ ])
+ return self.path
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ process.run([
+ 'sudo',
+ 'umount',
+ '-v',
+ self.path
+ ])
+
+
+def path_is_mounted(path, destination=None):
+ """
+ Check if the given path is mounted
+ """
+ mounts = get_mounts(paths=True)
+ realpath = os.path.realpath(path)
+ mounted_locations = mounts.get(realpath, [])
+
+ if destination:
+ if destination.startswith('/'):
+ destination = os.path.realpath(destination)
+ return destination in mounted_locations
+ return mounted_locations != []
+