kea.py.j2 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/python
  2. import collectd,datetime,socket,os,json,collections{% if kea.database.type == "postgresql" %},psycopg2
  3. {% endif %}
  4. {% if kea.database.type == "postgresql" %}
  5. def performPSQL():
  6. conn = psycopg2.connect("host='{{kea.database.db_host}}' dbname='{{kea.database.db_name}}' user='{{kea.database.db_user}}' password='{{kea.database.db_pass}}'")
  7. cursor = conn.cursor()
  8. cursor.execute("SELECT subnet_id, COUNT(*) FROM lease4 WHERE state=0 GROUP BY subnet_id")
  9. return dict((int(x), int(y)) for x, y in cursor.fetchall())
  10. {% endif %}
  11. def read(data=None):
  12. resDict = {}
  13. resDict[u'all_interfaces'] = collections.defaultdict(int)
  14. {% if kea.database.type == "postgresql" %}
  15. active_leases = performPSQL()
  16. for k, v in active_leases.items():
  17. if_name = 'bat' + str(k)
  18. resDict[if_name] = collections.defaultdict(int)
  19. resDict[if_name]['active-leases'] = v
  20. resDict[u'all_interfaces']['active-leases'] += v
  21. {% endif %}
  22. BUFF_SIZE = 1024
  23. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  24. s.connect("/var/kea/control.sock")
  25. s.send('{"command":"statistic-get-all","arguments":{}}')
  26. result = ""
  27. part = s.recv(BUFF_SIZE)
  28. while len(part) == BUFF_SIZE:
  29. result += part
  30. part = s.recv(1024)
  31. result += part
  32. jsonData = json.loads(result)
  33. for k,v in jsonData["arguments"].iteritems():
  34. k = k.split('.')
  35. interface = k[0].replace('subnet[','bat').replace(']','')
  36. if len(k) != 2:
  37. continue
  38. if interface not in resDict:
  39. resDict[interface] = collections.defaultdict(int)
  40. resDict[interface][k[1]] = v[0][0]
  41. resDict['all_interfaces'][k[1]] += v[0][0]
  42. s.close()
  43. for k,v in resDict.iteritems():
  44. vl = collectd.Values(type='kea_leases')
  45. vl.plugin='kea_leases'
  46. vl.type_instance = k
  47. {% if kea.database.type == "postgresql" %}
  48. vl.dispatch(values=[v['total-addresses'], v['assigned-addresses'], v['declined-addresses'], v['declined-reclaimed-addresses'], v['reclaimed-leases'], v['active-leases']])
  49. {% else %}
  50. vl.dispatch(values=[v['total-addresses'], v['assigned-addresses'], v['declined-addresses'], v['declined-reclaimed-addresses'], v['reclaimed-leases'], -1])
  51. {% endif %}
  52. def write(vl, data=None):
  53. for i in vl.values:
  54. print "%s (%s): %f" % (vl.plugin, vl.type, i)
  55. collectd.register_read(read)
  56. collectd.register_write(write);