@cryptotaxi247 / netdata-1 / commits / f526166f3

isc dhcpd plugin added

lgz committed Dec 23, 2016 at 09:52 UTC f526166f37c9c1a8be9b703f17fee68681712697
1 file changed +109
python.d/isc_dhcdp.chart.py new
+109
@@ -0,0 +1,109 @@
1 +# -*- coding: utf-8 -*-
2 +# Description: isc dhcpd lease netdata python.d module
3 +# Author: l2isbad
4 +
5 +from base import SimpleService
6 +from re import compile, search
7 +from time import mktime, strptime, gmtime
8 +try:
9 + from ipaddress import IPv4Address as ipaddress
10 + from ipaddress import ip_network
11 + have_ipaddress = True
12 +except ImportError:
13 + have_ipaddress = False
14 +
15 +priority = 60000
16 +retries = 60
17 +update_every = 60
18 +
19 +class Service(SimpleService):
20 + def __init__(self, configuration=None, name=None):
21 + SimpleService.__init__(self, configuration=configuration, name=name)
22 + self.leases_path = self.configuration.get('leases_path', '/var/lib/dhcp/dhcpd.leases')
23 + self.pools = self.configuration.get('pools')
24 +
25 + # Will work only with 'default' db-time-format (weekday year/month/day hour:minute:second)
26 + # TODO: update the regex to parse correctly 'local' db-time-format
27 + # (epoch <seconds-since-epoch>; # <day-name> <month-name> <day-number> <hours>:<minutes>:<seconds> <year>)
28 + # Also only ipv4 supported
29 + self.regex = compile(r'(\d+(?:\.\d+){3}).*?((?<=ends )[0-9].*?(?=;))')
30 +
31 + def check(self):
32 + if not self._get_raw_data():
33 + self.error('Make sure leases_path is correct and dhcpd.leases is readable by netdata')
34 + return False
35 + elif not have_ipaddress:
36 + self.error('No ipaddress module. Please install (py2-ipaddress in case of python2)')
37 + return False
38 + else:
39 + try:
40 + self.pools = self.pools.split()
41 + if not [ip_network(pool) for pool in self.pools]:
42 + self.error('Pools list is empty')
43 + return False
44 + except (ValueError, IndexError, AttributeError, SyntaxError):
45 + self.error('Pools configurations is incorrect')
46 + return False
47 +
48 + # Creating dynamic charts
49 + self.order = ['utilization']
50 + self.definitions = {'utilization': {'options': [None, 'Pools utilization', 'used %', 'Utulization', 'isc_dhcpd.util', 'line'], 'lines': []} }
51 + for pool in self.pools:
52 + self.definitions['utilization']['lines'].append([''.join(['ut_', pool]), pool, 'absolute'])
53 + self.order.append(''.join(['leases_', pool]))
54 + self.definitions[''.join(['leases_', pool])] = \
55 + {'options': [None, 'Active leases', 'leases', 'Leases', 'isc_dhcpd.lease', 'area'],
56 + 'lines': [[''.join(['le_', pool]), pool, 'absolute']]}
57 +
58 + self.info('Plugin was started succesfully')
59 + return True
60 +
61 + def _get_raw_data(self):
62 + """
63 + Open log file
64 + :return: str
65 + """
66 + try:
67 + with open(self.leases_path, 'rt') as leases:
68 + result = leases.read()
69 + except Exception:
70 + return None
71 + else:
72 + return result
73 +
74 + def _get_data(self):
75 + """
76 + Parse dhcpd.leases file.
77 + """
78 + raw_leases = self._get_raw_data()
79 + all_leases = dict(self.regex.findall(' '.join(raw_leases.split())))
80 +
81 + if not all_leases:
82 + self.error('Cant parse leases file correctly')
83 + return None
84 +
85 + # Result: [active binding, active binding....]. (Expire time (ends date;) - current time > 0)
86 + active_leases = [k for k, v in all_leases.items() if is_bind_active(all_leases[k])]
87 +
88 + # Result: {pool: number of active bindings in pool, ...}
89 + pools_count = {pool: len([lease for lease in active_leases if is_address_in(lease, pool)]) for pool in self.pools}
90 +
91 + # Result: {pool: number of host ip addresses in pool, }
92 + pools_max = {pool: (2 ** (32 - int(pool.split('/')[1])) - 2) for pool in self.pools}
93 +
94 + # Result: {pool: % utilization, ....} (percent)
95 + pools_util = {pool:int(round(float(pools_count[pool]) / pools_max[pool] * 100, 0)) for pool in self.pools}
96 +
97 + # Bulding dicts to send to netdata
98 + final_count = {''.join(['le_', k]): v for k, v in pools_count.items()}
99 + final_util = {''.join(['ut_', k]): v for k, v in pools_util.items()}
100 +
101 + final_count.update(final_util)
102 +
103 + return final_count
104 +
105 +def is_bind_active(binding):
106 + return mktime(strptime(binding, '%w %Y/%m/%d %H:%M:%S')) - mktime(gmtime()) > 0
107 +
108 +def is_address_in(address, pool):
109 + return ipaddress(address) in ip_network(pool)