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