Debian Codegraph @

gmond/python_modules/disk/diskfree.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Disk Free gmond module for Ganglia
5 #
6 # Copyright (C) 2011 by Michael T. Conigliaro <mike [at] conigliaro [dot] org>.
7 # All rights reserved.
8 #
9 # Permission is hereby granted, free of charge, to any person obtaining a copy
10 # of this software and associated documentation files (the "Software"), to deal
11 # in the Software without restriction, including without limitation the rights
12 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 # copies of the Software, and to permit persons to whom the Software is
14 # furnished to do so, subject to the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be included in
17 # all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 # THE SOFTWARE.
26 #
27
28 # This module reads a list of mountpoints from the "mounts" parameter (probably
29 # /proc/mounts) and creates a "disk_free_(absolute|percent)_*" metric for each
30 # mountpoint it finds.
31
32
33 import re
34 import os
35
36 NAME_PREFIX = 'disk_free_'
37 PARAMS = {
38 'mounts': '/proc/mounts',
39 'min_disk_size': 1,
40 'explicit_mounts_to_check': ''
41 }
42 PATHS = {}
43
44
45 def get_value(name):
46 """Return a value for the requested metric"""
47
48 # parse unit type and path from name
49 name_parser = re.match("^%s(absolute|percent)_(.*)$" % NAME_PREFIX, name)
50 unit_type = name_parser.group(1)
51 if name_parser.group(2) == 'rootfs':
52 path = '/'
53 elif name_parser.group(2) in PATHS:
54 path = '/' + PATHS[name_parser.group(2)]
55 else:
56 path = '/' + name_parser.group(2).replace('_', '/')
57
58 # get fs stats
59 try:
60 disk = os.statvfs(path)
61 if unit_type == 'percent':
62 result = (float(disk.f_bavail) / float(disk.f_blocks)) * 100
63 else:
64 result = (disk.f_bavail * disk.f_frsize) / float(2**30) # GB
65
66 except OSError:
67 result = 0
68
69 except ZeroDivisionError:
70 result = 0
71
72 return result
73
74
75 def metric_init(lparams):
76 """Initialize metric descriptors"""
77
78 global PARAMS, PATHS
79
80 # set parameters
81 for key in lparams:
82 PARAMS[key] = lparams[key]
83
84 # read mounts file
85 try:
86 f = open(PARAMS['mounts'])
87 except IOError:
88 f = []
89
90 # Let's see if there are any mounts we need to add to the explicit list of mounts to check
91 explicit_mounts_to_check = list()
92
93 if "explicit_mounts_to_check" in PARAMS and PARAMS['explicit_mounts_to_check'] != "":
94 explicit_mounts_temp = PARAMS['explicit_mounts_to_check'].split(" ")
95 for mount in explicit_mounts_temp:
96 explicit_mounts_to_check.append( mount[1:].replace('/', '_') )
97
98 del explicit_mounts_temp
99
100 # parse mounts and create descriptors
101 descriptors = []
102 for line in f:
103 # We only want local file systems
104 if line.startswith('/') or line.startswith('tmpfs'):
105 mount_info = line.split()
106
107 # create key from path
108 if mount_info[1] == '/':
109 path_key = 'rootfs'
110 else:
111 # strip off leading slash
112 path_key = mount_info[1][1:].replace('/', '_')
113
114 # Calculate the size of the disk. We'll use it exclude small disks
115 disk = os.statvfs(mount_info[1])
116 disk_size = (disk.f_blocks * disk.f_frsize) / float(2**30)
117
118 if (disk_size > float(PARAMS['min_disk_size']) and mount_info[1] != "/dev") or path_key in explicit_mounts_to_check:
119 PATHS[path_key] = mount_info[1]
120 for unit_type in ['absolute', 'percent']:
121 if unit_type == 'percent':
122 units = '%'
123 else:
124 units = 'GB'
125 descriptors.append({
126 'name': NAME_PREFIX + unit_type + '_' + path_key,
127 'call_back': get_value,
128 'time_max': 60,
129 'value_type': 'float',
130 'units': units,
131 'slope': 'both',
132 'format': '%f',
133 'description': "Disk space available (%s) on %s" % (units, mount_info[1]),
134 'groups': 'disk'
135 })
136
137 return descriptors
138
139
140 def metric_cleanup():
141 """Cleanup"""
142
143 pass
144
145
146 # the following code is for debugging and testing
147 if __name__ == '__main__':
148 PARAMS = {
149 'mounts': '/proc/mounts',
150 'min_disk_size': 1,
151 'explicit_mounts_to_check': ""
152 }
153 descriptors = metric_init(PARAMS)
154 for d in descriptors:
155 print (('%s = %s') % (d['name'], d['format'])) % (d['call_back'](d['name']))