600240e0f8af82da1ec0371633aebe4fd98e98ce
[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
39     debug("Trying to run command %s" % (command), True)
40     try:
41         p = subprocess.Popen(command,
42                              stdout=subprocess.PIPE,
43                              stderr=subprocess.PIPE,
44                              close_fds=True)
45         outdata,errdata = p.communicate()
46         err = p.wait()
47     except OSError, message:
48         raise RuntimeError, "%s subprocess error:\n %s" % \
49                             (command, str(message))
50     if err != 0 and raise_on_try:
51         raise RuntimeError, '%s failed with exit code %d\n%s' % \
52                             (str(command), err, errdata)
53     return outdata,errdata
54
55 def debug(message, verbose):
56     """
57     Prints message out to standard error and syslog if
58     verbose = True.
59     Note that the caller needs to first establish a syslog
60     context using syslog.openlog()
61     """
62     if verbose:
63         syslog.syslog(syslog.LOG_NOTICE, message + '\n')
64         sys.stderr.write(message + '\n')
65
66 def log_error(loglevel, message):
67     """
68     Trivial syslog wrapper that also outputs to stderr
69     Requires caller to have first opened a syslog session
70     using syslog.openlog()
71     """
72     syslog.syslog(loglevel, message + '\n')
73     sys.stderr.write(message + '\n')
74
75 def get_filesystem_capacity(path):
76     """Returns filesystem space usage of path as an integer percentage of
77        the entire capacity of path.
78     """
79     if not os.path.exists(path):
80         raise ValueError("%s is a non-existent path" % path)
81     f = os.statvfs(path)
82
83     unavailBlocks = f[statvfs.F_BLOCKS] - f[statvfs.F_BAVAIL]
84     capacity = int(math.ceil(100 * (unavailBlocks / float(f[statvfs.F_BLOCKS]))))
85
86     return capacity
87
88 def get_available_size(path):
89     """Returns the available space in bytes under path"""
90     if not os.path.exists(path):
91         raise ValueError("%s is a non-existent path" % path)
92     f = os.statvfs(path)
93     free = long(f[statvfs.F_BAVAIL] * f[statvfs.F_FRSIZE])
94     
95     return free
96
97 def get_used_size(path):
98     """Returns the used space in bytes of fileystem associated
99        with path"""
100     if not os.path.exists(path):
101         raise ValueError("%s is a non-existent path" % path)
102     f = os.statvfs(path)
103
104     unavailBlocks = f[statvfs.F_BLOCKS] - f[statvfs.F_BAVAIL]
105     used = long(unavailBlocks * f[statvfs.F_FRSIZE])
106
107     return used
108
109 def get_total_size(path):
110     """Returns the total storage space in bytes of fileystem
111        associated with path"""
112     if not os.path.exists(path):
113         raise ValueError("%s is a non-existent path" % path)
114     f = os.statvfs(path)
115     total = long(f[statvfs.F_BLOCKS] * f[statvfs.F_FRSIZE])
116
117     return total
118
119 def path_to_volume(path):
120     """
121        Tries to map a given path name to a gio Volume and
122        returns the gio.Volume object the enclosing
123        volume.
124        If it fails to find an enclosing volume it returns
125        None
126     """
127     gFile = gio.File(path)
128     try:
129         mount = gFile.find_enclosing_mount()
130     except gio.Error:
131         return None
132     else:
133         if mount != None:
134             volume = mount.get_volume()
135             return volume
136     return None