[modules/ping] Spawn thread on-the-fly

Instead of having a thread that runs in the background continuously,
spawn a new one for every update interval. That speeds up the tests
quite a lot.

see #23
This commit is contained in:
Tobi-wan Kenobi 2016-12-11 11:50:15 +01:00
parent 71582cbcd7
commit 17ee621a5a

View file

@ -20,35 +20,22 @@ import bumblebee.output
import bumblebee.engine import bumblebee.engine
def get_rtt(module, widget): def get_rtt(module, widget):
try:
widget.set("rtt-unreachable", False)
res = bumblebee.util.execute("ping -n -q -c {} -W {} {}".format(
widget.get("rtt-probes"), widget.get("rtt-timeout"), widget.get("address")
))
main = None for line in res.split("\n"):
for thread in threading.enumerate(): if not line.startswith("rtt"): continue
if thread.name == "MainThread": m = re.search(r'([0-9\.]+)/([0-9\.]+)/([0-9\.]+)/([0-9\.]+)\s+(\S+)', line)
main = thread
interval = widget.get("interval") widget.set("rtt-min", float(m.group(1)))
next_check = 0 widget.set("rtt-avg", float(m.group(2)))
while main.is_alive(): widget.set("rtt-max", float(m.group(3)))
try: widget.set("rtt-unit", m.group(5))
if int(time.time()) < next_check: except Exception as e:
time.sleep(1) widget.set("rtt-unreachable", True)
continue
widget.set("rtt-unreachable", False)
res = bumblebee.util.execute("ping -n -q -c {} -W {} {}".format(
widget.get("rtt-probes"), widget.get("rtt-timeout"), widget.get("address")
))
next_check = int(time.time()) + interval
for line in res.split("\n"):
if not line.startswith("rtt"): continue
m = re.search(r'([0-9\.]+)/([0-9\.]+)/([0-9\.]+)/([0-9\.]+)\s+(\S+)', line)
widget.set("rtt-min", float(m.group(1)))
widget.set("rtt-avg", float(m.group(2)))
widget.set("rtt-max", float(m.group(3)))
widget.set("rtt-unit", m.group(5))
except Exception as e:
widget.set("rtt-unreachable", True)
class Module(bumblebee.engine.Module): class Module(bumblebee.engine.Module):
def __init__(self, engine, config): def __init__(self, engine, config):
@ -62,8 +49,7 @@ class Module(bumblebee.engine.Module):
widget.set("rtt-avg", 0.0) widget.set("rtt-avg", 0.0)
widget.set("rtt-unit", "") widget.set("rtt-unit", "")
self._thread = threading.Thread(target=get_rtt, args=(self,widget,)) self._next_check = 0
self._thread.start()
def rtt(self, widget): def rtt(self, widget):
if widget.get("rtt-unreachable"): if widget.get("rtt-unreachable"):
@ -78,4 +64,11 @@ class Module(bumblebee.engine.Module):
if widget.get("rtt-unreachable"): return ["critical"] if widget.get("rtt-unreachable"): return ["critical"]
return self.threshold_state(widget.get("rtt-avg"), 1000.0, 2000.0) return self.threshold_state(widget.get("rtt-avg"), 1000.0, 2000.0)
def update(self, widgets):
if int(time.time()) < self._next_check:
return
thread = threading.Thread(target=get_rtt, args=(self,widgets[0],))
thread.start()
self._next_check = int(time.time()) + widgets[0].get("interval")
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4