Add linux specific autosnapsmf module and dependencies
[time-slider.git] / usr / share / time-slider / lib / time_slider / util.py
1 #!/usr/bin/python2
2 #
3 # CDDL HEADER START
4 #
5 # The contents of this file are subject to the terms of the
6 # Common Development and Distribution License (the "License").
7 # You may not use this file except in compliance with the License.
8 #
9 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 # or http://www.opensolaris.org/os/licensing.
11 # See the License for the specific language governing permissions
12 # and limitations under the License.
13 #
14 # When distributing Covered Code, include this CDDL HEADER in each
15 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 # If applicable, add the following below this CDDL HEADER, with the
17 # fields enclosed by brackets "[]" replaced with your own identifying
18 # information: Portions Copyright [yyyy] [name of copyright owner]
19 #
20 # CDDL HEADER END
21 #
22
23 import os
24 import subprocess
25 import sys
26 import syslog
27 import statvfs
28 import math
29 import gio
30
31 def run_command(command, raise_on_try=True):
32     """
33     Wrapper function around subprocess.Popen
34     Returns a tuple of standard out and stander error.
35     Throws a RunTimeError if the command failed to execute or
36     if the command returns a non-zero exit status.
37     """
38     try:
39         p = subprocess.Popen(command,
40                              stdout=subprocess.PIPE,
41                              stderr=subprocess.PIPE,
42                              close_fds=True)
43         outdata,errdata = p.communicate()
44         err = p.wait()
45     except OSError, message:
46         raise RuntimeError, "%s subprocess error:\n %s" % \
47                             (command, str(message))
48     if err != 0 and raise_on_try:
49         raise RuntimeError, '%s failed with exit code %d\n%s' % \
50                             (str(command), err, errdata)
51     return outdata,errdata
52
53 def debug(message, verbose):
54     """
55     Prints message out to standard error and syslog if
56     verbose = True.
57     Note that the caller needs to first establish a syslog
58     context using syslog.openlog()
59     """
60     if verbose:
61         syslog.syslog(syslog.LOG_NOTICE, message + '\n')
62         sys.stderr.write(message + '\n')
63
64 def log_error(loglevel, message):
65     """
66     Trivial syslog wrapper that also outputs to stderr
67     Requires caller to have first opened a syslog session
68     using syslog.openlog()
69     """
70     syslog.syslog(loglevel, message + '\n')
71     sys.stderr.write(message + '\n')
72
73 def get_filesystem_capacity(path):
74     """Returns filesystem space usage of path as an integer percentage of
75        the entire capacity of path.
76     """
77     if not os.path.exists(path):
78         raise ValueError("%s is a non-existent path" % path)
79     f = os.statvfs(path)
80
81     unavailBlocks = f[statvfs.F_BLOCKS] - f[statvfs.F_BAVAIL]
82     capacity = int(math.ceil(100 * (unavailBlocks / float(f[statvfs.F_BLOCKS]))))
83
84     return capacity
85
86 def get_available_size(path):
87     """Returns the available space in bytes under path"""
88     if not os.path.exists(path):
89         raise ValueError("%s is a non-existent path" % path)
90     f = os.statvfs(path)
91     free = long(f[statvfs.F_BAVAIL] * f[statvfs.F_FRSIZE])
92     
93     return free
94
95 def get_used_size(path):
96     """Returns the used space in bytes of fileystem associated
97        with path"""
98     if not os.path.exists(path):
99         raise ValueError("%s is a non-existent path" % path)
100     f = os.statvfs(path)
101
102     unavailBlocks = f[statvfs.F_BLOCKS] - f[statvfs.F_BAVAIL]
103     used = long(unavailBlocks * f[statvfs.F_FRSIZE])
104
105     return used
106
107 def get_total_size(path):
108     """Returns the total storage space in bytes of fileystem
109        associated with path"""
110     if not os.path.exists(path):
111         raise ValueError("%s is a non-existent path" % path)
112     f = os.statvfs(path)
113     total = long(f[statvfs.F_BLOCKS] * f[statvfs.F_FRSIZE])
114
115     return total
116
117 def path_to_volume(path):
118     """
119        Tries to map a given path name to a gio Volume and
120        returns the gio.Volume object the enclosing
121        volume.
122        If it fails to find an enclosing volume it returns
123        None
124     """
125     gFile = gio.File(path)
126     try:
127         mount = gFile.find_enclosing_mount()
128     except gio.Error:
129         return None
130     else:
131         if mount != None:
132             volume = mount.get_volume()
133             return volume
134     return None