1
0
Fork 0
mirror of https://github.com/munin-monitoring/contrib.git synced 2025-07-21 18:41:03 +00:00

Fix python style issues reported by flake8

Additionally some python2-only "print" statements are now compatible
with python3.
This commit is contained in:
Lars Kruse 2019-12-18 00:25:39 +01:00
parent 73f885e382
commit 7063330e03
17 changed files with 102 additions and 103 deletions

View file

@ -100,7 +100,7 @@ def parse(clients):
# Get the current bytes # Get the current bytes
if line.endswith(" is running."): if line.endswith(" is running."):
bytes_count_text = input_lines[pos+2].split()[1].split("=")[1].replace(",", "") bytes_count_text = input_lines[pos + 2].split()[1].split("=")[1].replace(",", "")
try: try:
# python2 # python2
bytes_count = long(bytes_count_text) bytes_count = long(bytes_count_text)
@ -126,8 +126,8 @@ def print_config():
print("graph_category backup") print("graph_category backup")
print("graph_order", " ".join(fd[1] for fd in clients)) print("graph_order", " ".join(fd[1] for fd in clients))
print() print()
if ((os.getenv("report_hostname") is not None) and if ((os.getenv("report_hostname") is not None)
(os.getenv("report_hostname").upper() in ["YES", "TRUE", "1", "Y"])): and (os.getenv("report_hostname").upper() in ["YES", "TRUE", "1", "Y"])):
print("host_name", hostname) print("host_name", hostname)
for client in clients: for client in clients:
print("%s.label %s" % (client[1], client[0])) print("%s.label %s" % (client[1], client[0]))

View file

@ -91,7 +91,7 @@ def parse():
# Get the current bytes # Get the current bytes
if input_lines[pos].endswith("is mounted with:"): if input_lines[pos].endswith("is mounted with:"):
bytes_count_text = input_lines[pos+5].split()[1].split("=")[1].replace(",", "") bytes_count_text = input_lines[pos + 5].split()[1].split("=")[1].replace(",", "")
try: try:
bytes_count = long(bytes_count_text) bytes_count = long(bytes_count_text)
except NameError: except NameError:

View file

@ -236,7 +236,7 @@ class Proxy:
'method': self.method, 'method': self.method,
'params': args, 'params': args,
'id': self.id, 'id': self.id,
} }
request = urllib.request.Request(self.service.url, json.dumps(data).encode()) request = urllib.request.Request(self.service.url, json.dumps(data).encode())
if self.service.username: if self.service.username:
auth_string = '%s:%s' % (self.service.username, self.service.password) auth_string = '%s:%s' % (self.service.username, self.service.password)

View file

@ -7,11 +7,11 @@ import urllib2
import json import json
URL = 'https://www.btcguild.com/api.php?api_key=' URL = 'https://www.btcguild.com/api.php?api_key='
API_KEY = sys.argv[0][(sys.argv[0].rfind('_')+1):] API_KEY = sys.argv[0][(sys.argv[0].rfind('_') + 1):]
STATS = URL + API_KEY STATS = URL + API_KEY
print STATS print(STATS)
command = '' command = ''
if len(sys.argv) > 1: if len(sys.argv) > 1:
@ -25,16 +25,16 @@ workers = mining_stats['workers']
if command == 'config': if command == 'config':
print "graph_title BTCGuild Hashrate" print("graph_title BTCGuild Hashrate")
print "graph_args --upper-limit 3000 -l 0" print("graph_args --upper-limit 3000 -l 0")
print "graph_vlabel MHash/s" print("graph_vlabel MHash/s")
print "graph_category htc" print("graph_category htc")
for worker in workers: for worker in workers:
label = workers[worker]['worker_name'] label = workers[worker]['worker_name']
print label + ".label " + label print(label + ".label " + label)
sys.exit(0) sys.exit(0)
for worker in workers: for worker in workers:
hash_rate = workers[worker]['hash_rate'] hash_rate = workers[worker]['hash_rate']
label = workers[worker]['worker_name'] label = workers[worker]['worker_name']
print label + ".value %d" % int(hash_rate) print(label + ".value %d" % int(hash_rate))

View file

@ -53,7 +53,7 @@ import urllib2
program = sys.argv[0] program = sys.argv[0]
graph_type = program[program.rfind("_")+1:] graph_type = program[program.rfind("_") + 1:]
graph_types = { graph_types = {
"accesses": [ "accesses": [
{ {
@ -91,21 +91,21 @@ graph_types = {
if len(sys.argv) == 2 and sys.argv[1] == "autoconf": if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
print "yes" print("yes")
elif len(sys.argv) == 2 and sys.argv[1] == "config": elif len(sys.argv) == 2 and sys.argv[1] == "config":
if graph_type not in graph_types.keys(): if graph_type not in graph_types.keys():
raise Exception("Unknown graph type '%s'" % graph_type) raise Exception("Unknown graph type '%s'" % graph_type)
params = graph_types[graph_type] params = graph_types[graph_type]
for item in params: for item in params:
print "graph_title %s" % item["title"] print("graph_title %s" % item["title"])
print "graph_category webserver" print("graph_category webserver")
for field in item["fields"]: for field in item["fields"]:
print "%s.label %s" % (field, field) print("%s.label %s" % (field, field))
print "%s.type %s" % (field, item["type"]) print("%s.type %s" % (field, item["type"]))
print "graph_args %s" % item["args"] print("graph_args %s" % item["args"])
elif len(sys.argv) == 2 and sys.argv[1] == "suggest": elif len(sys.argv) == 2 and sys.argv[1] == "suggest":
for item in graph_types.keys(): for item in graph_types.keys():
print item print(item)
else: else:
status_url = os.environ.get('status_url', 'http://127.0.0.1/server-status') status_url = os.environ.get('status_url', 'http://127.0.0.1/server-status')
@ -129,11 +129,11 @@ else:
pass pass
if graph_type == "accesses": if graph_type == "accesses":
print "accesses.value %s" % data["Total Accesses"] print("accesses.value %s" % data["Total Accesses"])
elif graph_type == "kbytes": elif graph_type == "kbytes":
print "kbytes.value %s" % data["Total kBytes"] print("kbytes.value %s" % data["Total kBytes"])
elif graph_type == "uptime": elif graph_type == "uptime":
print "uptime.value %s" % str(float(data["Uptime"])/86400) print("uptime.value %s" % str(float(data["Uptime"]) / 86400))
elif graph_type == "status": elif graph_type == "status":
print "busy.value %s" % data["BusyServers"] print("busy.value %s" % data["BusyServers"])
print "idle.value %s" % data["IdleServers"] print("idle.value %s" % data["IdleServers"])

View file

@ -54,7 +54,7 @@ import time
# How we've been called # How we've been called
progName = sys.argv[0] progName = sys.argv[0]
progName = progName[progName.rfind("/")+1:] progName = progName[progName.rfind("/") + 1:]
# Where to store plugin state # Where to store plugin state

View file

@ -53,31 +53,31 @@ filterwarnings('ignore', category=MySQLdb.Warning)
program_name = os.path.basename(__file__) program_name = os.path.basename(__file__)
variables = { variables = {
'percona_queues': { 'percona_queues': {
'label': 'Queue sizes', 'label': 'Queue sizes',
'vlabel': 'size', 'vlabel': 'size',
'fields': ['wsrep_local_recv_queue', 'wsrep_local_send_queue'] 'fields': ['wsrep_local_recv_queue', 'wsrep_local_send_queue']
}, },
'percona_flow': { 'percona_flow': {
'label': 'Flow control', 'label': 'Flow control',
'vlabel': '', 'vlabel': '',
'fields': ['wsrep_flow_control_sent', 'wsrep_flow_control_recv'] 'fields': ['wsrep_flow_control_sent', 'wsrep_flow_control_recv']
}, },
'percona_transactions': { 'percona_transactions': {
'label': 'Transactions in and out', 'label': 'Transactions in and out',
'vlabel': 'transactions', 'vlabel': 'transactions',
'fields': ['wsrep_replicated', 'wsrep_received'] 'fields': ['wsrep_replicated', 'wsrep_received']
}, },
'percona_transactions_bytes': { 'percona_transactions_bytes': {
'label': 'Transactions in and out in bytes', 'label': 'Transactions in and out in bytes',
'vlabel': 'bytes', 'vlabel': 'bytes',
'fields': ['wsrep_replicated_bytes', 'wsrep_received_bytes'] 'fields': ['wsrep_replicated_bytes', 'wsrep_received_bytes']
}, },
'percona_replication': { 'percona_replication': {
'label': 'Replication conflicts', 'label': 'Replication conflicts',
'vlabel': 'conflicts', 'vlabel': 'conflicts',
'fields': ['wsrep_local_cert_failures', 'wsrep_local_bf_aborts'], 'fields': ['wsrep_local_cert_failures', 'wsrep_local_bf_aborts'],
} }
} }
# Parse environment variables # Parse environment variables

View file

@ -139,8 +139,8 @@ def main():
telnet.write("server:uptime()\n") telnet.write("server:uptime()\n")
telnet_response = telnet.read_until("minutes (", 5) telnet_response = telnet.read_until("minutes (", 5)
parsed_info = uptime_re.findall(telnet_response) parsed_info = uptime_re.findall(telnet_response)
uptime_value = (float(parsed_info[0]) + float(parsed_info[1])/24 uptime_value = (float(parsed_info[0]) + float(parsed_info[1]) / 24
+ float(parsed_info[2])/60/24) + float(parsed_info[2]) / 60 / 24)
print("uptime.value %s" % (uptime_value)) print("uptime.value %s" % (uptime_value))
telnet.write("quit\n") telnet.write("quit\n")

View file

@ -102,7 +102,7 @@ def login(session, url, username, password):
bytes(password.encode("ascii")), bytes(password.encode("ascii")),
salt, salt,
iterations=1000, iterations=1000,
dklen=128/8 dklen=128 / 8
) )
secret = {"Password": password, "Nonce": current_session_id} secret = {"Password": password, "Nonce": current_session_id}
plaintext = bytes(json.dumps(secret).encode("ascii")) plaintext = bytes(json.dumps(secret).encode("ascii"))

View file

@ -197,7 +197,7 @@ print(
"""multigraph technicolor_tc8715d_snr """multigraph technicolor_tc8715d_snr
graph_title Technicolor TC8715D Cable Modem SNR graph_title Technicolor TC8715D Cable Modem SNR
graph_vlabel Signal-to-Noise Ratio (dB) graph_vlabel Signal-to-Noise Ratio (dB)
graph_info This graph shows the downstream signal-to-noise ratio reported by a Technicolor TC8715D cable modem. graph_info Downstream signal-to-noise ratio reported by a Technicolor TC8715D cable modem.
graph_category network""" graph_category network"""
) )
@ -212,7 +212,7 @@ print(
"""multigraph technicolor_tc8715d_codewords """multigraph technicolor_tc8715d_codewords
graph_title Technicolor TC8715D Cable Modem Codewords graph_title Technicolor TC8715D Cable Modem Codewords
graph_vlabel Codewords/${graph_period} graph_vlabel Codewords/${graph_period}
graph_info This graph shows the downstream codeword rates reported by a Technicolor TC8715D cable modem. graph_info Downstream codeword rates reported by a Technicolor TC8715D cable modem.
graph_category network""" graph_category network"""
) )

View file

@ -77,7 +77,7 @@ def parse_params():
data = params['core'].rsplit('_', 1) data = params['core'].rsplit('_', 1)
handler = data.pop() handler = data.pop()
params['params'] = { params['params'] = {
'handler': os.environ.get('qpshandler_%s' % handler, 'standard') 'handler': os.environ.get('qpshandler_%s' % handler, 'standard'),
} }
if not data: if not data:
params['core'] = '' params['core'] = ''
@ -416,7 +416,7 @@ class SolrMuninGraph:
handler=self.params['params']['handler'], handler=self.params['params']['handler'],
core=self.params['core'], core=self.params['core'],
cores_qps_cdefs='%s,%s' % (','.join(map(lambda x: 'qps_%s' % x, cores)), cores_qps_cdefs='%s,%s' % (','.join(map(lambda x: 'qps_%s' % x, cores)),
','.join(['+'] * (len(cores)-1))), ','.join(['+'] * (len(cores) - 1))),
gorder=','.join(cores) gorder=','.join(cores)
) )
@ -512,4 +512,4 @@ if __name__ == '__main__':
SOLR_URL = '/' + SOLR_URL SOLR_URL = '/' + SOLR_URL
mb = SolrMuninGraph(SOLR_HOST_PORT, SOLR_URL, params) mb = SolrMuninGraph(SOLR_HOST_PORT, SOLR_URL, params)
if hasattr(mb, params['op']): if hasattr(mb, params['op']):
print(getattr(mb, params['op'])(params['type'])) print(getattr(mb, params['op'])(params['type']))

View file

@ -42,7 +42,7 @@ import sphinxsearch
prog_name = sys.argv[0] prog_name = sys.argv[0]
index_name = prog_name[prog_name.find("_")+1:] index_name = prog_name[prog_name.find("_") + 1:]
if len(sys.argv) == 2 and sys.argv[1] == "autoconf": if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
print("yes") print("yes")

View file

@ -91,7 +91,7 @@ class SynologySNMPClient(object):
if not oid.startswith(disk_table): if not oid.startswith(disk_table):
continue continue
disk_id = oid[oid.rindex('.')+1:] disk_id = oid[oid.rindex('.') + 1:]
values = devices.get(disk_id, [None, None, None]) values = devices.get(disk_id, [None, None, None])
if oid.startswith(disktable_id): if oid.startswith(disktable_id):
@ -119,21 +119,21 @@ class SynologySNMPClient(object):
return int(varBindTable[0][1]) return int(varBindTable[0][1])
def print_config(self): def print_config(self):
print """multigraph synology_hdd_temperatures print("""multigraph synology_hdd_temperatures
host_name {hostname} host_name {hostname}
graph_title HDD temperatures on {hostname} graph_title HDD temperatures on {hostname}
graph_vlabel Temperature in °C graph_vlabel Temperature in °C
graph_args --base 1000 graph_args --base 1000
graph_category sensors graph_category sensors
graph_info HDD temperatures on {hostname}""".format(hostname=self.hostname) graph_info HDD temperatures on {hostname}""".format(hostname=self.hostname))
for id, name, model, temp in self._get_disks(): for id, name, model, temp in self._get_disks():
print """disk{disk_id}.info Temperature of {name} ({model}) print("""disk{disk_id}.info Temperature of {name} ({model})
disk{disk_id}.label {name} ({model}) disk{disk_id}.label {name} ({model})
disk{disk_id}.type GAUGE disk{disk_id}.type GAUGE
disk{disk_id}.min 0""".format(disk_id=id, name=name, model=model) disk{disk_id}.min 0""".format(disk_id=id, name=name, model=model))
print """multigraph synology_sys_temperature print("""multigraph synology_sys_temperature
host_name {hostname} host_name {hostname}
graph_title System temperatures of {hostname} graph_title System temperatures of {hostname}
graph_vlabel Temperature in °C graph_vlabel Temperature in °C
@ -144,15 +144,15 @@ sys_temp.info System temperature
sys_temp.label Temperature sys_temp.label Temperature
sys_temp.type GAUGE sys_temp.type GAUGE
sys_temp.min 0 sys_temp.min 0
""".format(hostname=self.hostname) """.format(hostname=self.hostname))
def execute(self): def execute(self):
print """multigraph synology_hdd_temperatures""" print("""multigraph synology_hdd_temperatures""")
for id, name, model, temp in self._get_disks(): for id, name, model, temp in self._get_disks():
print """disk{disk_id}.value {temp}""".format(disk_id=id, temp=temp) print("""disk{disk_id}.value {temp}""".format(disk_id=id, temp=temp))
print """multigraph synology_sys_temperature""" print("""multigraph synology_sys_temperature""")
print "sys_temp.value {temp}".format(temp=self._get_sys_temperature()) print("sys_temp.value {temp}".format(temp=self._get_sys_temperature()))
host = None host = None
@ -175,7 +175,7 @@ except Exception as ex:
if "snmpconf" in sys.argv[1:]: if "snmpconf" in sys.argv[1:]:
print "require 1.3.6.1.4.1.6574.2.1.1" print("require 1.3.6.1.4.1.6574.2.1.1")
sys.exit(0) sys.exit(0)
else: else:
if not (host and port and community): if not (host and port and community):

View file

@ -121,25 +121,25 @@ log = logging.getLogger("delugeStats")
log.setLevel(logging.WARNING) log.setLevel(logging.WARNING)
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 = {
'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'
} }
torrent_states = ["Downloading", torrent_states = ["Downloading",
@ -300,8 +300,8 @@ def print_config(mode):
"graph_info This graph shows the number of connections used by Deluge Torrent") "graph_info This graph shows the number of connections used by Deluge Torrent")
print(names_for_munin["numConnections"] + ".label connections") print(names_for_munin["numConnections"] + ".label connections")
print(names_for_munin["numConnections"] + ".min 0") print(names_for_munin["numConnections"] + ".min 0")
print(names_for_munin["numConnections"] + print(names_for_munin["numConnections"]
".info The number of connections used by Deluge Torrent") + ".info The number of connections used by Deluge Torrent")
elif mode == "bandwidth": elif mode == "bandwidth":
print("graph_title Bandwidth usage") print("graph_title Bandwidth usage")
print("graph_order payloadDownloadRate overheadDownloadRate payloadUploadRate " print("graph_order payloadDownloadRate overheadDownloadRate payloadUploadRate "
@ -353,13 +353,12 @@ def print_config(mode):
print("graph_period second") print("graph_period second")
for state_name in torrent_states: for state_name in torrent_states:
print(names_for_munin["state." + print(names_for_munin["state." + state_name] + ".label " + state_name)
state_name] + ".label " + state_name)
print(names_for_munin["state." + state_name] + ".draw AREASTACK") print(names_for_munin["state." + state_name] + ".draw AREASTACK")
print(names_for_munin["state." + state_name] + ".type GAUGE") 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] + ".min 0")
print(names_for_munin["state." + state_name] + print(names_for_munin["state." + state_name]
".info Number of torrents in the '" + state_name + "' state") + ".info Number of torrents in the '" + state_name + "' state")
def fetch_info(mode): def fetch_info(mode):

View file

@ -3,7 +3,7 @@
import os import os
import re import re
import sys import sys
import urllib from urllib.request import urlopen
url = 'http://www.weather.com/weather/today/%s' url = 'http://www.weather.com/weather/today/%s'
@ -19,7 +19,7 @@ if not code:
elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": elif len(sys.argv) == 2 and sys.argv[1] == "autoconf":
print("yes") print("yes")
elif len(sys.argv) == 2 and sys.argv[1] == "config": elif len(sys.argv) == 2 and sys.argv[1] == "config":
u = urllib.urlopen(url % code) u = urlopen(url % code)
txt = u.read() txt = u.read()
u.close() u.close()
@ -39,7 +39,7 @@ elif len(sys.argv) == 2 and sys.argv[1] == "config":
print('graph_args --base 1000 -l 0') print('graph_args --base 1000 -l 0')
else: else:
u = urllib.urlopen(url % code) u = urlopen(url % code)
txt = u.read() txt = u.read()
u.close() u.close()
@ -53,7 +53,7 @@ else:
if len(TMP_F_list): if len(TMP_F_list):
TMP_F = TMP_F_list[0] TMP_F = TMP_F_list[0]
TMP_C = (int(TMP_F) - 32) * 5/9 TMP_C = (int(TMP_F) - 32) * 5 / 9
else: else:
sys.exit(1) sys.exit(1)

View file

@ -21,7 +21,7 @@ url = 'http://tgftp.nws.noaa.gov/data/observations/metar/decoded/%s.TXT'
re_hpa = re.compile(r'Pressure.*\((\d+) hPa\)') re_hpa = re.compile(r'Pressure.*\((\d+) hPa\)')
code = sys.argv[0][(sys.argv[0].rfind('_')+1):] code = sys.argv[0][(sys.argv[0].rfind('_') + 1):]
if not code: if not code:
sys.exit(1) sys.exit(1)
elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": elif len(sys.argv) == 2 and sys.argv[1] == "autoconf":

View file

@ -21,7 +21,7 @@ url = 'http://tgftp.nws.noaa.gov/data/observations/metar/decoded/%s.TXT'
re_C = re.compile(r'Temperature:.*\((-?\d+\.?\d?) C\)') re_C = re.compile(r'Temperature:.*\((-?\d+\.?\d?) C\)')
re_DewC = re.compile(r'Dew.*\((-?\d+\.?\d?) C\)') re_DewC = re.compile(r'Dew.*\((-?\d+\.?\d?) C\)')
code = sys.argv[0][(sys.argv[0].rfind('_')+1):] code = sys.argv[0][(sys.argv[0].rfind('_') + 1):]
if not code: if not code: