From 9759634977d0c8ea64dbcc1bd21ba3d3dd809bec Mon Sep 17 00:00:00 2001 From: "Kim B. Heino" Date: Thu, 1 Apr 2021 15:28:16 +0300 Subject: [PATCH] knot: cache results, needed for first run after server reboot Sometimes after reboot munin-async + munin-node runs before knot is ready. This will result missing knot stats, as there is no static config in plugin. Cache results and use them instead if knot's output is empty. --- plugins/knot/knot | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/plugins/knot/knot b/plugins/knot/knot index df7f1723..d512adea 100755 --- a/plugins/knot/knot +++ b/plugins/knot/knot @@ -38,6 +38,7 @@ GPLv2 import os import subprocess import sys +import time from collections import defaultdict @@ -112,14 +113,26 @@ def get_stats(): """Get statistics.""" # Get status output try: - pipe = subprocess.Popen( - ['/usr/sbin/knotc', '--force', 'stats'], - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - output = pipe.communicate()[0].decode('utf-8', 'ignore') - except OSError: + output = subprocess.run(['knotc', '--force', 'stats'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, check=False, + encoding='utf-8', errors='ignore').stdout + except FileNotFoundError: return {} + # After server reboot output can be almost empty. Use cached results + # instead, needed for plugin config when using munin-async. + cachename = os.getenv('MUNIN_PLUGSTATE') + '/knot.state' + if len(output) > 2048: + with open(cachename, 'wt') as cache: + cache.write(output) + elif ( + os.path.exists(cachename) and + os.stat(cachename).st_mtime > time.time() - 900 + ): + with open(cachename, 'rt') as cache: + output = cache.read() + # Parse output. Keep graph labels in knotc-order. values = defaultdict(dict) for line in output.splitlines():