]> git.ipfire.org Git - collecty.git/blob - src/collecty/util.py
psi: Add graph template
[collecty.git] / src / collecty / util.py
1 #!/usr/bin/python3
2 ###############################################################################
3 # #
4 # collecty - A system statistics collection daemon for IPFire #
5 # Copyright (C) 2015 IPFire development team #
6 # #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
11 # #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
16 # #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
19 # #
20 ###############################################################################
21
22 import logging
23 import os
24
25 log = logging.getLogger("collecty.util")
26
27 from .constants import *
28
29 def get_network_interfaces():
30 """
31 Returns all real network interfaces
32 """
33 for interface in os.listdir("/sys/class/net"):
34 # Skip some unwanted interfaces.
35 if interface == "lo" or interface.startswith("mon."):
36 continue
37
38 path = os.path.join("/sys/class/net", interface)
39 if not os.path.isdir(path):
40 continue
41
42 yield interface
43
44 def make_interval(interval):
45 intervals = {
46 None : "-3h",
47 "hour" : "-1h",
48 "day" : "-25h",
49 "month": "-30d",
50 "week" : "-360h",
51 "year" : "-365d",
52 }
53
54 try:
55 return intervals[interval]
56 except KeyError:
57 return "end-%s" % interval
58
59 def guess_format(filename):
60 """
61 Returns the best format by filename extension
62 """
63 parts = filename.split(".")
64
65 if parts:
66 # The extension is the last part
67 extension = parts[-1]
68
69 # Image formats are all uppercase
70 extension = extension.upper()
71
72 if extension in SUPPORTED_IMAGE_FORMATS:
73 return extension
74
75 # Otherwise fall back to the default format
76 return DEFAULT_IMAGE_FORMAT
77
78 class ProcNetSnmpParser(object):
79 """
80 This class parses /proc/net/snmp{,6} and allows
81 easy access to the values.
82 """
83 def __init__(self, intf=None):
84 self.intf = intf
85 self._data = {}
86
87 if not self.intf:
88 self._data.update(self._parse())
89
90 self._data.update(self._parse6())
91
92 def _parse(self):
93 res = {}
94
95 with open("/proc/net/snmp") as f:
96 keys = {}
97
98 for line in f.readlines():
99 line = line.strip()
100
101 # Stop after an empty line
102 if not line:
103 break
104
105 type, values = line.split(": ", 1)
106
107 # Check if the keys are already known
108 if type in keys:
109 values = (int(v) for v in values.split())
110 res[type] = dict(zip(keys[type], values))
111
112 # Otherwise remember the keys
113 else:
114 keys[type] = values.split()
115
116 return res
117
118 def _parse6(self):
119 res = {}
120
121 fn = "/proc/net/snmp6"
122 if self.intf:
123 fn = os.path.join("/proc/net/dev_snmp6", self.intf)
124
125 with open(fn) as f:
126 for line in f.readlines():
127 key, val = line.split()
128
129 try:
130 type, key = key.split("6", 1)
131 except ValueError:
132 continue
133
134 type += "6"
135 val = int(val)
136
137 try:
138 res[type][key] = val
139 except KeyError:
140 res[type] = { key : val }
141
142 return res
143
144 def get(self, proto, key):
145 """
146 Retrieves a value from the internally
147 parse dictionary read from /proc/net/snmp.
148 """
149 try:
150 return self._data[proto][key]
151 except KeyError:
152 pass