source: ogClient-Git/src/utils/fs.py @ 621d1b9

Last change on this file since 621d1b9 was 621d1b9, checked in by Jose M. Guisado <jguisado@…>, 3 years ago

utils: mount_mkdir success if target is a mountpoint

Returns true if target is already a mountpoint. Does not call mount.

It's possible that another device might be mounted in the target
mountpoint. A future check between the source and target for
equal device major:minor must be added.

  • Property mode set to 100644
File size: 1.7 KB
Line 
1#
2# Copyright (C) 2022 Soleta Networks <info@soleta.eu>
3#
4# This program is free software: you can redistribute it and/or modify it under
5# the terms of the GNU Affero General Public License as published by the
6# Free Software Foundation; either version 3 of the License, or
7# (at your option) any later version.
8
9import os
10import subprocess
11
12from subprocess import DEVNULL
13
14import psutil
15
16
17def find_mountpoint(path):
18    """
19    Returns mountpoint of a given path
20    """
21    path = os.path.abspath(path)
22    while not os.path.ismount(path):
23        path = os.path.dirname(path)
24    return path
25
26
27def mount_mkdir(source, target):
28    """
29    Mounts and creates the mountpoint directory if it's not present.
30
31    Return True if mount is sucessful or if target is already a mountpoint.
32    """
33    if not os.path.exists(target):
34        os.mkdir(target)
35
36    if not os.path.ismount(target):
37        return mount(source, target)
38    else:
39        return True
40
41    return False
42
43
44def mount(source, target):
45    """
46    Mounts source into target directoru using mount(8).
47
48    Return true if exit code is 0. False otherwise.
49    """
50    cmd = f'mount {source} {target}'
51    proc = subprocess.run(cmd.split(), stderr=DEVNULL)
52
53    return not proc.returncode
54
55
56def umount(target):
57    """
58    Umounts target using umount(8).
59
60    Return true if exit code is 0. False otherwise.
61    """
62    cmd = f'umount {target}'
63    proc = subprocess.run(cmd.split(), stderr=DEVNULL)
64
65    return not proc.returncode
66
67
68def get_usedperc(mountpoint):
69    """
70    Returns percetage of used filesystem as decimal number.
71    """
72    try:
73        total, used, free, perc = psutil.disk_usage(mountpoint)
74    except FileNotFoundError:
75        return '0'
76    return str(perc)
Note: See TracBrowser for help on using the repository browser.