Commit f6fb6811 by Jocelyn Delalande

munin-node: add role

imported from faimaison adminsys repo
parent a0453847
Munin-node
==========
- Install munin-node
- Deploy custom plugins
- Allows one or several munin master to connect
- Configurable plugin lists:
- list of required plugins
- blacklist of munin plugins.
Variables
---------
- `munin_enabled_modules`: a list of dicts with two keys
- `name`: the name of the module (mind the trailing "_")
- `arg`: arg passed to the module (optional, does not apply to all modules)
- `munin_disabled_modules`: a list of module names you want to disable (names
include args)
- `munin_master_hosts`: the munin masters (graphing servers) allowed to gather
data from this host.
Example
-------
munin_disabled_modules:
- ntp_kernel_err
- ntp_kernel_pll_freq
- ntp_kernel_pll_off
- ntp_offset
- entropy
munin_enabled_modules:
- name: openvpn
arg: stfelix
- name: openvpn
arg: bottiere
- name: ping_
arg: 89.234.176.1
munin_master_hosts:
- 1.2.3.4
munin_node_custom_plugins_path: /usr/local/munin/lib/plugins
munin_node_custom_plugins:
- ubntdiscovery_
- mpower_
#!/usr/bin/env python2
#! -*- coding: utf-8 -*-
"""
Copyright ⓒ 2014 CNRS/LAAS
Copyright ⓒ 2017 Jocelyn Delalande
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
# Comme mentioné dans la notice ci-dessus, une partie du code est dérivée du travail de mherbb
# https://git.openrobots.org/projects/mpower/repository/revisions/master/entry/python/mpower.py
import subprocess
import sys
import json
import pycurl
def munin_print(s):
""" Munin, until 2.1.1 accept only latin1
See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=598554
:param s: unicode string to be printed
"""
print(s.encode('latin1'))
class MPower:
class APIError(Exception):
def __str__(self):
return 'Error querying mPower API: {}'.format(
super(Exception, self).__str__())
def __init__(self, host):
self.contents = ''
self.host = host
self.handle = pycurl.Curl()
self.handle.setopt(self.handle.AUTOREFERER, 1)
self.handle.setopt(self.handle.FOLLOWLOCATION, 1)
self.handle.setopt(self.handle.COOKIEFILE, "")
self.handle.setopt(self.handle.WRITEFUNCTION, self.body_callback)
def __del__(self):
self.handle.close()
def body_callback(self, buf):
self.contents = self.contents + buf
def login(self, user, password):
self.contents = ''
self.handle.setopt(self.handle.URL,
"http://" + self.host + "/index.cgi")
try:
self.handle.perform()
except pycurl.error as e:
raise self.APIError(
'mPower HTTP seems unreachable: "{}"'.format(e.args[1]))
self.handle.setopt(self.handle.POSTFIELDS,
"username="+user +"&password="+password)
self.handle.setopt(self.handle.URL,
"http://" + self.host + "/login.cgi")
self.handle.perform()
if (self.handle.getinfo(self.handle.RESPONSE_CODE) != 200):
raise APIError('Login page error')
if (str.find(self.contents, "Invalid credentials.") > 0):
raise APIError('Login page error')
def query_outputs(self):
self.contents = ''
self.handle.setopt(self.handle.URL,
"http://"+self.host+"/mfi/sensors.cgi")
self.handle.setopt(self.handle.CUSTOMREQUEST, "GET")
self.handle.setopt(self.handle.HTTPGET, 1)
self.handle.perform()
decoded = json.loads(self.contents);
if (decoded['status'] != "success"):
raise APIError('mPower API returned status {}'.format(decoded['status']))
return decoded['sensors']
class PluginError(Exception):
def __str__(self):
return 'Error calling plugin: {}'.format(
super(Exception, self).__str__())
def print_values(mpower):
data = mpower.query_outputs()
for row in data:
munin_print(u'current-{port}.value {current}'.format(**row))
def print_config(mpower):
data = mpower.query_outputs()
munin_print(
u'graph_title Courant consommé (mPower {})'.format(
mpower.host))
munin_print(u'graph_vlabel Ampères')
munin_print(u'graph_category sensors')
munin_print(u'graph_info Courant consommé, par prise')
munin_print(u'graph_total Total')
for row in data:
munin_print(u'current-{port}.label {label}'.format(**row))
munin_print(u'current-{port}.draw LINE'.format(**row))
def main():
script_name, mpower_ip = sys.argv[0].rsplit('_', 1)
if not mpower_ip:
raise PluginError('This plugin symlink must include the host name of the mpower, ex: "mpower_10.10.10.10"')
mpower = MPower(mpower_ip)
mpower.login('readonly', 'readonly')
if (len(sys.argv) > 1) and sys.argv[1] == 'config':
print_config(mpower)
else:
print_values(mpower)
if __name__ == '__main__':
try:
main()
except Exception as e:
sys.stderr.write('{}\n'.format(e))
exit(1)
#!/usr/bin/env python3
import subprocess
import sys
import json
class PluginError(Exception):
pass
def get_data(iface):
try:
raw_data = subprocess.check_output(['/usr/local/bin/ubnt_discovery', '--output-format=json', iface])
data = json.loads(raw_data.decode())
except subprocess.CalledProcessError:
raise PluginError('Failed to run device discovery')
except ValueError:
raise PluginError('Error during JSON parsing')
except Exception as e:
raise PluginError(e)
else:
model_counters = {}
for row in data:
model_short = row['model_short']
model = row['model']
if model_short not in model_counters.keys():
model_counters[model_short] = {'value': 1, 'title': row['model']}
else:
model_counters[model_short]['value'] += 1
return model_counters
def print_values(iface):
data = get_data(iface)
for key, values in data.items():
print('{}.value {}'.format(key, values['value']))
def print_config(iface):
data = get_data(iface)
print('graph_title Ubiquiti devices')
print('graph_vlabel number of devices')
print('graph_category wireless')
print('graph_category network')
print('graph_info Monitors active devices on the network, using ubiquiti discovery protocol')
for key, values in data.items():
print('{}.label {}'.format(key, values['title']))
print('{}.draw AREASTACK'.format(key))
if __name__ == '__main__':
try:
script_name, iface = sys.argv[0].rsplit('_', 1)
except ValueError:
raise PluginError('This plugin symlink must include the iface name, ex: "ubnt_discovery_eth1"')
if (len(sys.argv) > 1) and sys.argv[1] == 'config':
print_config(iface)
else:
print_values(iface)
- name: restart munin-node
service: name=munin-node state=restarted
- name: Ensure custom plugins dependencies are installed
apt: pkg={{ item }} cache_valid_time=1800
with_items:
- python3-minimal
- python-pycurl
- name: Create custom plugins dir
file:
path: "{{ munin_node_custom_plugins_path }}"
owner: munin
group: munin
state: directory
- name: Deploy custom plugins
copy:
src: "files/plugins/{{ item }}"
dest: "{{ munin_node_custom_plugins_path }}/{{ item }}"
mode: 0755
with_items: "{{ munin_node_custom_plugins }}"
notify: restart munin-node
- name: Deploy custom plugin configs
copy:
src: "{{ item }}"
dest: "/etc/munin/plugin-conf.d/"
with_fileglob: "files/plugin-confs/*"
notify: restart munin-node
\ No newline at end of file
- name: Install munin-node and smartmontools
apt: pkg={{item}} state=present
with_items:
- munin-node
- smartmontools
- include: custom-plugins.yml
- name: Allow our munin-master(s)
blockinfile:
dest: /etc/munin/munin-node.conf
marker: "### {mark} ANSIBLE MANAGED BLOCK ###"
content: |
{% for i in munin_master_hosts %}
allow {{ i }}
{% endfor %}
notify: restart munin-node
- name: enable munin modules
file:
src: "{% if item.name in munin_node_custom_plugins %}{{ munin_node_custom_plugins_path }}{% else %}/usr/share/munin/plugins{% endif %}/{{ item.name }}"
dest: "/etc/munin/plugins/{{ item.name}}{{ item.get('arg', '') }}"
state: link
with_items: "{{ munin_enabled_modules }}"
notify: restart munin-node
- name: disable munin modules
file: path=/etc/munin/plugins/{{ item }} state=absent
with_items: "{{ munin_disabled_modules }}"
notify: restart munin-node
# See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=788736#12
# This task could go away as soon as the Debian bugfix lands into stable
- name: fix df and df_inode modules to prevent false positives
copy:
src: files/plugin-conf-fix-df-false-positive-fix
dest: /etc/munin/plugin-conf.d/df-false-positive-fix
notify: restart munin-node
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment