Add Systemd AMP

This commit is contained in:
Nicolargo 2016-04-25 18:03:05 +02:00
parent 84a40237db
commit bad96d34bb
5 changed files with 122 additions and 18 deletions

View File

@ -254,10 +254,18 @@ queue=glances_queue
# AMPS # AMPS
###### ######
[nginx] [amp_nginx]
# Nginx status page should be enable (https://easyengine.io/tutorials/nginx/status-page/) # Nginx status page should be enable (https://easyengine.io/tutorials/nginx/status-page/)
enable=true enable=true
regex=\/usr\/sbin\/nginx regex=\/usr\/sbin\/nginx
refresh=60 refresh=60
one_line=false one_line=false
status_url=http://localhost/nginx_status status_url=http://localhost/nginx_status
[amp_systemd]
# Systemd
enable=true
regex=\/usr\/lib\/systemd\/systemd
refresh=30
one_line=true
systemctl_path=/usr/bin/systemctl --plain

View File

@ -80,14 +80,15 @@ class GlancesAmp(object):
# option1=opt1 # option1=opt1
# ... # ...
# #
amp_section = 'amp_' + self.amp_name
if (hasattr(config, 'has_section') and if (hasattr(config, 'has_section') and
config.has_section(self.amp_name)): config.has_section(amp_section)):
logger.debug("{0}: Load configuration".format(self.NAME)) logger.debug("{0}: Load configuration".format(self.NAME))
for param, _ in config.items(self.amp_name): for param, _ in config.items(amp_section):
try: try:
self.configs[param] = config.get_float_value(self.amp_name, param) self.configs[param] = config.get_float_value(amp_section, param)
except ValueError: except ValueError:
self.configs[param] = config.get_value(self.amp_name, param).split(',') self.configs[param] = config.get_value(amp_section, param).split(',')
if len(self.configs[param]) == 1: if len(self.configs[param]) == 1:
self.configs[param] = self.configs[param][0] self.configs[param] = self.configs[param][0]
logger.debug("{0}: Load parameter: {1} = {2}".format(self.NAME, param, self.configs[param])) logger.debug("{0}: Load parameter: {1} = {2}".format(self.NAME, param, self.configs[param]))
@ -153,9 +154,14 @@ class GlancesAmp(object):
return self.enable() return self.enable()
return False return False
def set_result(self, result): def set_result(self, result, separator=''):
"""Store the result (string) into the result key of the AMP""" """Store the result (string) into the result key of the AMP
self.configs['result'] = str(result) if one_line is true then replace \n by separator
"""
if self.one_line():
self.configs['result'] = str(result).replace('\n', separator)
else:
self.configs['result'] = str(result)
def result(self): def result(self):
""" Return the result of the AMP (as a string)""" """ Return the result of the AMP (as a string)"""

View File

@ -44,7 +44,7 @@ Source (https://easyengine.io/tutorials/nginx/status-page/)
Configuration file example Configuration file example
-------------------------- --------------------------
[nginx] [amp_nginx]
# Nginx status page should be enable (https://easyengine.io/tutorials/nginx/status-page/) # Nginx status page should be enable (https://easyengine.io/tutorials/nginx/status-page/)
enable=true enable=true
regex=\/usr\/sbin\/nginx regex=\/usr\/sbin\/nginx
@ -62,7 +62,7 @@ from glances.amps.glances_amp import GlancesAmp
class Amp(GlancesAmp): class Amp(GlancesAmp):
"""Glances' Nginx AMP.""" """Glances' Nginx AMP."""
NAME = 'Nginx Glances AMP' NAME = 'Nginx'
VERSION = '1.0' VERSION = '1.0'
DESCRIPTION = 'Get Nginx stats from status-page' DESCRIPTION = 'Get Nginx stats from status-page'
AUTHOR = 'Nicolargo' AUTHOR = 'Nicolargo'
@ -78,14 +78,11 @@ class Amp(GlancesAmp):
if self.should_update(): if self.should_update():
# Get the Nginx status # Get the Nginx status
logger.debug('{0}: Update stats using status URL {1}'.format(self.NAME, self.get('status_url'))) logger.debug('{0}: Update stats using status URL {1}'.format(self.NAME, self.get('status_url')))
req = requests.get(self.get('status_url')) res = requests.get(self.get('status_url'))
if req.ok: if res.ok:
# u'Active connections: 1 \nserver accepts handled requests\n 1 1 1 \nReading: 0 Writing: 1 Waiting: 0 \n' # u'Active connections: 1 \nserver accepts handled requests\n 1 1 1 \nReading: 0 Writing: 1 Waiting: 0 \n'
if self.one_line(): self.set_result(res.text)
self.set_result(req.text.replace('\n', ''))
else:
self.set_result(req.text)
else: else:
logger.debug('{0}: Can not grab status URL {1} ({2})'.format(self.NAME, self.get('status_url'), req.reason)) logger.debug('{0}: Can not grab status URL {1} ({2})'.format(self.NAME, self.get('status_url'), res.reason))
return self.result() return self.result()

View File

@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# Copyright (C) 2016 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Systemd AMP
===========
Monitor the Systemd.
How to read the stats
---------------------
...
Configuration file example
--------------------------
[amp_systemd]
# Systemd
enable=true
regex=\/usr\/lib\/systemd\/systemd
refresh=30
one_line=true
systemctl_path=/usr/bin/systemctl
"""
from subprocess import check_output
from glances.logger import logger
from glances.compat import iteritems
from glances.amps.glances_amp import GlancesAmp
class Amp(GlancesAmp):
"""Glances' Systemd AMP."""
NAME = 'Systemd'
VERSION = '1.0'
DESCRIPTION = 'Get daemon list from systemctl (systemd)'
AUTHOR = 'Nicolargo'
EMAIL = 'contact@nicolargo.com'
# def __init__(self, args=None):
# """Init the AMP."""
# super(Amp, self).__init__(args=args)
def update(self):
"""Update the AMP"""
if self.should_update():
# Get the systemctl status
logger.debug('{0}: Update stats using systemctl {1}'.format(self.NAME, self.get('systemctl_path')))
try:
res = check_output(self.get('systemctl_path').split())
except OSError as e:
logger.debug('{0}: Error while executing systemctl ({1})'.format(self.NAME, e))
else:
status = {}
# For each line
for r in res.split('\n')[1:-8]:
# Split per space .*
l = r.split()
if len(l) > 3:
# load column
for c in range(1, 3):
try:
status[l[c]] += 1
except KeyError:
status[l[c]] = 1
# Build the output (string) message
output = 'Services\n'
for k, v in iteritems(status):
output += '{0}: {1}\n'.format(k, v)
self.set_result(output, separator=' ')
return self.result()

View File

@ -58,6 +58,7 @@ class Plugin(GlancesPlugin):
for k, v in iteritems(self.glances_amps.update()): for k, v in iteritems(self.glances_amps.update()):
# self.stats.append({k: v.result()}) # self.stats.append({k: v.result()})
self.stats.append({'key': k, self.stats.append({'key': k,
'name': v.NAME,
'result': v.result(), 'result': v.result(),
'refresh': v.refresh(), 'refresh': v.refresh(),
'timer': v.time_until_refresh()}) 'timer': v.time_until_refresh()})
@ -82,7 +83,7 @@ class Plugin(GlancesPlugin):
if m['result'] is None: if m['result'] is None:
continue continue
# Display AMP # Display AMP
first_column = '{0}'.format(m['key']) first_column = '{0}'.format(m['name'])
# first_column = '{0} {1}/{2}'.format(m['key'], int(m['timer']), int(m['refresh'])) # first_column = '{0} {1}/{2}'.format(m['key'], int(m['timer']), int(m['refresh']))
for l in m['result'].split('\n'): for l in m['result'].split('\n'):
# Display first column with the process name... # Display first column with the process name...