1
0
Fork 0
mirror of https://github.com/munin-monitoring/contrib.git synced 2025-07-25 18:38:30 +00:00

Format code according to PEP0008

This commit is contained in:
Neraud 2017-07-18 07:36:17 +02:00
parent 0f88253361
commit 5fd233c510

View file

@ -2,303 +2,343 @@
# #
# Munin Wildcard Plugin for Deluge torrent client # Munin Wildcard Plugin for Deluge torrent client
# #
# This plugin has 3 modes : # This plugin has 3 modes :
# - connections : monitors the number of connections # - connections : monitors the number of connections
# - bandwidth : monitors the bandwidth (up, up overhead, down, down overhead) # - bandwidth : monitors the bandwidth (up, up overhead, down, down overhead)
# - states : monitors the torrents' states # - states : monitors the torrents' states
# #
# To use one of these modes, link the this plugin with a name like 'deluge_<mode>' # To use one of these modes, link the this plugin with a name like 'deluge_<mode>'
# For example : # For example :
# ln -s /path/to/deluge_ /etc/munin/plugins/deluge_connections # ln -s /path/to/deluge_ /etc/munin/plugins/deluge_connections
# #
# Use your "/etc/munin/plugin-conf.d/munin-node" to configure this plugin. # Use your "/etc/munin/plugin-conf.d/munin-node" to configure this plugin.
# You must at least add : # You must at least add :
# [deluge_*] # [deluge_*]
# user <user_with_access_to_deluge> # user <user_with_access_to_deluge>
# env.HOME <path_to_deluge_user_home> # env.HOME <path_to_deluge_user_home>
# #
# By default, this plugin will try to access the deluge daemon with the following configuration : # By default, this plugin will try to access the deluge daemon with the following configuration :
# host 127.0.0.1 # host 127.0.0.1
# port 58846 # port 58846
# no username # no username
# no password # no password
# #
# You can change these settings in "plugin-conf.d/munin-node" : # You can change these settings in "plugin-conf.d/munin-node" :
# [deluge_*] # [deluge_*]
# user <user_with_access_to_deluge> # user <user_with_access_to_deluge>
# env.HOME <path_to_deluge_user_home> # env.HOME <path_to_deluge_user_home>
# env.host 127.0.0.1 # env.host 127.0.0.1
# env.port 58846 # env.port 58846
# env.username user # env.username user
# env.password pass # env.password pass
# #
# By default, deluge configuration files will be searched under $XDG_CONFIG_HOME, which is by default set to $HOME/.config # By default, deluge configuration files will be searched under $XDG_CONFIG_HOME, which is by default set to $HOME/.config
# Setting env.HOME allows this default to work. However, you can also explicitly set the env.XDG_CONFIG_HOME if needed. # Setting env.HOME allows this default to work. However, you can also explicitly set the env.XDG_CONFIG_HOME if needed.
# #
# Written by : Neraud # Written by : Neraud
# #
# Markers for munin : # Markers for munin :
#%# family=auto # %# family=auto
#%# capabilities=autoconf suggest # %# capabilities=autoconf suggest
########################################## ##########################################
import logging, commands, sys, os, string import commands
from twisted.internet import reactor, defer
from deluge.ui.client import client
from deluge.log import setupLogger from deluge.log import setupLogger
from deluge.ui.client import client
import logging
import os
import string
import sys
from twisted.internet import reactor, defer
setupLogger() setupLogger()
plugin_version = "1.0.0" plugin_version = "1.0.0"
# create logger
log = logging.getLogger("delugeStats") log = logging.getLogger("delugeStats")
log.setLevel(logging.WARNING) log.setLevel(logging.WARNING)
# Deluge daemon Confs
conf = { conf = {
'host' : os.getenv('host', '127.0.0.1'), 'host': os.getenv('host', '127.0.0.1'),
'port' : int(os.getenv('port', '58846')), 'port': int(os.getenv('port', '58846')),
'username' : os.getenv('username', ''), 'username': os.getenv('username', ''),
'password' : os.getenv('password', '') 'password': os.getenv('password', '')
} }
# names for munin : names_for_munin = {
namesForMunin = { 'numConnections': 'numConnections',
'numConnections' : 'numConnections', 'payloadUploadRate': 'payloadUploadRate',
'payloadUploadRate' : 'payloadUploadRate', 'overheadUploadRate': 'overheadUploadRate',
'overheadUploadRate' : 'overheadUploadRate', 'payloadDownloadRate': 'payloadDownloadRate',
'payloadDownloadRate' : 'payloadDownloadRate', 'overheadDownloadRate': 'overheadDownloadRate',
'overheadDownloadRate' : 'overheadDownloadRate', 'state.Seeding': 'seeding',
'state.Seeding' : 'seeding', 'state.Downloading': 'downloading',
'state.Downloading' : 'downloading', 'state.Paused': 'paused',
'state.Paused' : 'paused', 'state.Error': 'error',
'state.Error' : 'error', 'state.Queued': 'queued',
'state.Queued' : 'queued', 'state.Checking': 'checking',
'state.Checking' : 'checking', 'state.Other': 'other'
'state.Other' : 'other'
} }
torrentStates = [ "Downloading", "Seeding", "Paused", "Error", "Queued", "Checking", "Other" ] torrent_states = ["Downloading",
"Seeding",
"Paused",
"Error",
"Queued",
"Checking",
"Other"]
modes = ["bandwidth", "connections", "states"]
modes = [ "bandwidth", "connections", "states" ]
class StatClient: class StatClient:
def __init__(self, conf, mode) : def __init__(self, conf, mode):
self.conf = conf self.conf = conf
self.mode = mode self.mode = mode
self.connected = False self.connected = False
def endSession(self, msg): def end_session(self, msg):
log.debug("endSession : {0}".format(msg)) log.debug("end_session : {0}".format(msg))
if self.connected: if self.connected:
log.debug("Disconnecting") log.debug("Disconnecting")
client.disconnect() client.disconnect()
reactor.stop() reactor.stop()
def fetchInfo(self): def fetch_info(self):
log.debug("Connecting to {0}:{1} ...".format(self.conf['host'], self.conf['port'])) log.debug("Connecting to {0}:{1} ...".format(
client.connect(self.conf['host'], self.conf['port'], self.conf['username'], self.conf['password']).addCallbacks(self.onConnectSuccess, self.endSession, errbackArgs=("Connection failed: check settings and try again.")) self.conf['host'], self.conf['port']))
reactor.run() client.connect(
self.conf['host'],
def onConnectSuccess(self, result): self.conf['port'],
log.debug("Connection was successful") self.conf['username'],
self.connected = True self.conf['password']).addCallbacks(
self.on_connect_success,
if self.mode == "connections" : self.end_session,
log.debug("Calling get_num_connections") errbackArgs=("Connection failed: check settings and try again."))
client.core.get_num_connections().addCallbacks(self.onNumConnections, self.endSession, errbackArgs=("get_num_connections failed")) reactor.run()
elif self.mode == "bandwidth" :
log.debug("Calling get_session_status") def on_connect_success(self, result):
client.core.get_session_status(['upload_rate', 'payload_upload_rate', 'download_rate', 'payload_download_rate']).addCallbacks(self.onBandwidth, self.endSession, errbackArgs=("get_session_status faileds")) log.debug("Connection was successful")
elif self.mode == "states" : self.connected = True
log.debug("Calling get_session_state")
client.core.get_session_state().addCallbacks(self.onSessionState, self.endSession, errbackArgs=("get_session_state failed")) if self.mode == "connections":
log.debug("Calling get_num_connections")
def onNumConnections(self, num_connections): client.core.get_num_connections().addCallbacks(
log.debug("Got num_connections from the daemon : {0}".format(str(num_connections))) self.on_num_connections,
print "{0}.value {1}".format(namesForMunin["numConnections"], num_connections) self.end_session, errbackArgs=("get_num_connections failed"))
self.endSession("Done") elif self.mode == "bandwidth":
log.debug("Calling get_session_status")
def onBandwidth(self, values): interesting_status = [
log.debug("Got bandwith info from the daemon : {0}".format(str(values))) 'upload_rate', 'payload_upload_rate',
'download_rate', 'payload_download_rate']
downloadRate = values['download_rate'] client.core.get_session_status(interesting_status).addCallbacks(
payloadDownloadRate = values['payload_download_rate'] self.on_bandwidth,
overheadDownloadRate = downloadRate - payloadDownloadRate self.end_session,
uploadRate = values['upload_rate'] errbackArgs=("get_session_status failed"))
payloadUploadRate = values['payload_upload_rate'] elif self.mode == "states":
overheadUploadRate = uploadRate - payloadUploadRate log.debug("Calling get_session_state")
client.core.get_session_state().addCallbacks(
print "{0}.value {1}".format(namesForMunin["payloadDownloadRate"], payloadDownloadRate) self.on_session_state,
print "{0}.value {1}".format(namesForMunin["overheadDownloadRate"], overheadDownloadRate) self.end_session,
print "{0}.value {1}".format(namesForMunin["payloadUploadRate"], payloadUploadRate) errbackArgs=("get_session_state failed"))
print "{0}.value {1}".format(namesForMunin["overheadUploadRate"], overheadUploadRate)
def on_num_connections(self, num_connections):
self.endSession("Done") log.debug("Got num_connections from the daemon : {0}".format(
str(num_connections)))
def onSessionState(self, torrentIds): print "{0}.value {1}".format(
log.debug("Got session state from the daemon") names_for_munin["numConnections"], num_connections)
self.end_session("Done")
self.states = { }
for stateName in torrentStates : def on_bandwidth(self, values):
self.states[stateName] = 0 log.debug(
#self.states={'Seeding': 0, 'Downloading': 0, 'Paused': 0, 'Error': 0, 'Queued': 0, 'Checking': 0, 'Other' : 0} "Got bandwidth info from the daemon : {0}".format(str(values)))
deferredList = [] download_rate = values['download_rate']
for torrentId in torrentIds: payload_download_rate = values['payload_download_rate']
log.debug(" - TorrentId : {0}".format(torrentId)) overhead_download_rate = download_rate - payload_download_rate
d = client.core.get_torrent_status(torrentId, ['state']) upload_rate = values['upload_rate']
d.addCallback(self.onOneTorrentInfo, torrentId) payload_upload_rate = values['payload_upload_rate']
d.addErrback(self.onOneTorrentInfoFailed, torrentId) overhead_upload_rate = upload_rate - payload_upload_rate
deferredList.append(d)
print "{0}.value {1}".format(
defer.DeferredList(deferredList).addCallback(self.onAllTorrentInfoFetched) names_for_munin["payloadDownloadRate"], payload_download_rate)
print "{0}.value {1}".format(
def onOneTorrentInfoFailed(self, torrentId): names_for_munin["overheadDownloadRate"], overhead_download_rate)
log.debug("Failed fetching torrent info {0}".format(torrentId)) print "{0}.value {1}".format(
self.state["Error"] = self.state["Error"] + 1; names_for_munin["payloadUploadRate"], payload_upload_rate)
print "{0}.value {1}".format(
names_for_munin["overheadUploadRate"], overhead_upload_rate)
def onOneTorrentInfo(self, value, torrentId):
log.debug("Got torrent info : {0} -> {1}".format(torrentId, value)) self.end_session("Done")
if 'state' in value:
state = value['state'] def on_session_state(self, torrent_ids):
else: log.debug("Got session state from the daemon")
state = "Error"
self.states = {}
if not (state in self.states) : for state_name in torrent_states:
log.warn("State '{0}' is unknown !".format(state)) self.states[state_name] = 0
state = "Other"
deferred_list = []
self.states[state] = self.states[state] + 1 for torrent_id in torrent_ids:
log.debug(" - TorrentId : {0}".format(torrent_id))
def onAllTorrentInfoFetched(self, res): d = client.core.get_torrent_status(torrent_id, ['state'])
log.debug("onAllTorrentInfoFetched : {0}".format(str(self.states))) d.addCallback(self.on_one_torrent_info, torrent_id)
d.addErrback(self.on_one_torrent_info_failed, torrent_id)
for state in self.states: deferred_list.append(d)
print "{0}.value {1}".format(namesForMunin["state." + state], self.states[state])
defer.DeferredList(deferred_list).addCallback(
self.endSession("Done") self.on_all_torrent_info_fetched)
def on_one_torrent_info_failed(self, torrent_id):
log.debug("Failed fetching torrent info {0}".format(torrent_id))
self.state["Error"] = self.state["Error"] + 1
def on_one_torrent_info(self, value, torrent_id):
log.debug("Got torrent info : {0} -> {1}".format(torrent_id, value))
if 'state' in value:
state = value['state']
else:
state = "Error"
if not (state in self.states):
log.warn("State '{0}' is unknown !".format(state))
state = "Other"
self.states[state] = self.states[state] + 1
def on_all_torrent_info_fetched(self, res):
log.debug("on_all_torrent_info_fetched : {0}".format(str(self.states)))
for state in self.states:
print "{0}.value {1}".format(
names_for_munin["state." + state], self.states[state])
self.end_session("Done")
def getMode() : def get_mode():
scriptName = list(os.path.split(sys.argv[0]))[1] script_name = list(os.path.split(sys.argv[0]))[1]
mode = scriptName[string.rindex(scriptName,'_')+1:] mode = script_name[string.rindex(script_name, '_') + 1:]
log.debug("Mode : {0}".format(str(mode)))
if not mode in modes :
log.error("Unknown mode '{0}'".format(mode))
log.info("Available modes are : {0}".format(str(modes)))
sys.exit(1)
return mode
def printConfig(mode) : log.debug("Mode : {0}".format(str(mode)))
if mode == "connections" :
print("graph_title Number of connections") if not mode in modes:
print("graph_args --base 1000 -l 0") log.error("Unknown mode '{0}'".format(mode))
print("graph_vlabel connections") log.info("Available modes are : {0}".format(str(modes)))
print("graph_scale yes") sys.exit(1)
print("graph_category deluge")
print("graph_info This graph shows the number of connections used by Deluge Torrent") return mode
print(namesForMunin["numConnections"] + ".label connections")
print(namesForMunin["numConnections"] + ".min 0")
print(namesForMunin["numConnections"] + ".info The number of connections used by Deluge Torrent") def print_config(mode):
elif mode == "bandwidth" : if mode == "connections":
print("graph_title Bandwidth usage") print("graph_title Number of connections")
print("graph_order payloadUploadRate payloadDownloadRate overheadUploadRate overheadDownloadRate") print("graph_args --base 1000 -l 0")
print("graph_args --base 1024 -r") print("graph_vlabel connections")
print("graph_vlabel octet/s : down(+) and up(-)") print("graph_scale yes")
print("graph_scale yes") print("graph_category deluge")
print("graph_info This graph shows the bandwidth used by Deluge Torrent") print(
print("graph_category deluge") "graph_info This graph shows the number of connections used by Deluge Torrent")
print("graph_period second") print(names_for_munin["numConnections"] + ".label connections")
print(names_for_munin["numConnections"] + ".min 0")
print("payloadUploadRate.label payload") print(names_for_munin["numConnections"] +
print("payloadUploadRate.draw AREA") ".info The number of connections used by Deluge Torrent")
print("payloadUploadRate.min 0") elif mode == "bandwidth":
#print("payloadUploadRate.info Bandwidth used to upload torrents") print("graph_title Bandwidth usage")
print("graph_order payloadUploadRate payloadDownloadRate overheadUploadRate overheadDownloadRate")
print("payloadDownloadRate.label payload") print("graph_args --base 1024 -r")
print("payloadDownloadRate.draw AREA") print("graph_vlabel octet/s : down(+) and up(-)")
print("payloadDownloadRate.min 0") print("graph_scale yes")
print("payloadDownloadRate.negative payloadUploadRate") print("graph_info This graph shows the bandwidth used by Deluge Torrent")
print("payloadDownloadRate.info Bandwidth used to download / upload torrents") print("graph_category deluge")
print("graph_period second")
print("overheadUploadRate.label overhead")
print("overheadUploadRate.draw STACK") print("payloadUploadRate.label payload")
print("overheadUploadRate.min 0") print("payloadUploadRate.draw AREA")
#print("overheadUploadRate.info Bandwidth 'lost' due to overhead while downloading and uploading torrents") print("payloadUploadRate.min 0")
# print("payloadUploadRate.info Bandwidth used to upload torrents")
print("overheadDownloadRate.label overhead")
print("overheadDownloadRate.draw STACK") print("payloadDownloadRate.label payload")
print("overheadDownloadRate.min 0") print("payloadDownloadRate.draw AREA")
print("overheadDownloadRate.negative overheadUploadRate") print("payloadDownloadRate.min 0")
print("overheadDownloadRate.info Bandwidth 'lost' due to overhead while downloading and uploading torrents") print("payloadDownloadRate.negative payloadUploadRate")
elif mode == "states" : print("payloadDownloadRate.info Bandwidth used to download / upload torrents")
print("graph_title Torrents states")
print("overheadUploadRate.label overhead")
graphOrder = "" print("overheadUploadRate.draw STACK")
for stateName in torrentStates : print("overheadUploadRate.min 0")
graphOrder += namesForMunin["state." + stateName] + " " # print("overheadUploadRate.info Bandwidth 'lost' due to overhead while downloading and uploading torrents")
print("graph_order " + graphOrder) print("overheadDownloadRate.label overhead")
print("graph_args --base 1000 -r --lower-limit 0") print("overheadDownloadRate.draw STACK")
print("graph_vlabel number of torrents") print("overheadDownloadRate.min 0")
print("graph_scale yes") print("overheadDownloadRate.negative overheadUploadRate")
print("graph_info This graph shows the states of the torrents in Deluge Torrent") print("overheadDownloadRate.info Bandwidth 'lost' due to overhead while downloading and uploading torrents")
print("graph_category deluge") elif mode == "states":
print("graph_period second") print("graph_title Torrents states")
first = True graph_order = ""
for stateName in torrentStates : for state_name in torrent_states:
print(namesForMunin["state." + stateName ] + ".label " + stateName) graph_order += names_for_munin["state." + state_name] + " "
if first :
first = False print("graph_order " + graph_order)
print(namesForMunin["state." + stateName ] + ".draw AREA") print("graph_args --base 1000 -r --lower-limit 0")
else : print("graph_vlabel number of torrents")
print(namesForMunin["state." + stateName ] + ".draw STACK") print("graph_scale yes")
print(namesForMunin["state." + stateName ] + ".type GAUGE") print("graph_info This graph shows the states of the torrents in Deluge Torrent")
print(namesForMunin["state." + stateName ] + ".min 0") print("graph_category deluge")
print(namesForMunin["state." + stateName ] + ".info Number of torrents in the '" + stateName + "' state") print("graph_period second")
first = True
for state_name in torrent_states:
print(names_for_munin["state." +
state_name] + ".label " + state_name)
if first:
first = False
print(names_for_munin["state." + state_name] + ".draw AREA")
else:
print(names_for_munin["state." + state_name] + ".draw STACK")
print(names_for_munin["state." + state_name] + ".type GAUGE")
print(names_for_munin["state." + state_name] + ".min 0")
print(names_for_munin["state." + state_name] +
".info Number of torrents in the '" + state_name + "' state")
def fetch_info(mode):
log.debug("Launching tests")
c = StatClient(conf, mode)
c.fetch_info()
def fetchInfo(mode) :
log.debug("Launching tests")
c = StatClient(conf, mode)
c.fetchInfo()
# Parse arguments # Parse arguments
if len(sys.argv) > 1 : if len(sys.argv) > 1:
action = sys.argv[1] action = sys.argv[1]
if action == "config" : if action == "config":
printConfig(getMode()) print_config(get_mode())
sys.exit(0) sys.exit(0)
elif action == "autoconf" : elif action == "autoconf":
status, output = commands.getstatusoutput('which deluged') status, output = commands.getstatusoutput('which deluged')
if status == 0 : if status == 0:
print('yes') print('yes')
sys.exit(0) sys.exit(0)
else : else:
print('no (deluged not found)') print('no (deluged not found)')
sys.exit(1) sys.exit(1)
elif action == "suggest" : elif action == "suggest":
for mode in modes : for mode in modes:
print(mode) print(mode)
sys.exit(0) sys.exit(0)
elif action == "version" : elif action == "version":
print('Deluge Torrent Munin plugin, version {0}'.format(plugin_version)) print('Deluge Torrent Munin plugin, version {0}'.format(
sys.exit(0) plugin_version))
elif action != "" : sys.exit(0)
log.warn("Unknown argument '{0}'".format(action)) elif action != "":
sys.exit(1) log.warn("Unknown argument '{0}'".format(action))
else : sys.exit(1)
fetchInfo(getMode()) else:
else : fetch_info(get_mode())
fetchInfo(getMode()) else:
fetch_info(get_mode())