Merge "Fix: do not use charmhelpers in non-charm context"

This commit is contained in:
Zuul 2021-01-15 15:46:40 +00:00 committed by Gerrit Code Review
commit de11e7f0dd
2 changed files with 42 additions and 15 deletions

View File

@ -12,13 +12,20 @@ import argparse
import os import os
import sys import sys
from charmhelpers.core.hookenv import config
from charmhelpers.core.host import CompareHostReleases, get_distrib_codename
if CompareHostReleases(get_distrib_codename()) > 'trusty': lsb_dict = {}
with open("/etc/lsb-release") as f:
lsb = [s.split("=") for s in f.readlines()]
lsb_dict = dict([(k, v.strip()) for k, v in lsb])
if lsb_dict.get("DISTRIB_CODENAME") != "trusty":
# Trusty doesn't have croniter
from croniter import croniter from croniter import croniter
CRONJOB = "/etc/cron.d/rabbitmq-stats"
def gen_data_lines(filename): def gen_data_lines(filename):
with open(filename, "rt") as fin: with open(filename, "rt") as fin:
for line in fin: for line in fin:
@ -95,6 +102,12 @@ def get_cron_interval(cronspec, base):
return it.get_next(datetime) - it.get_prev(datetime) return it.get_next(datetime) - it.get_prev(datetime)
def get_stats_cron_schedule():
with open(CRONJOB) as f:
cronjob = f.read()
return cronjob.split("root")[0].strip()
def check_stats_file_freshness(stats_file, asof=None): def check_stats_file_freshness(stats_file, asof=None):
"""Check if a rabbitmq stats file is fresh """Check if a rabbitmq stats file is fresh
@ -107,7 +120,7 @@ def check_stats_file_freshness(stats_file, asof=None):
if asof is None: if asof is None:
asof = datetime.now() asof = datetime.now()
file_mtime = datetime.fromtimestamp(os.path.getmtime(stats_file)) file_mtime = datetime.fromtimestamp(os.path.getmtime(stats_file))
cronspec = config("stats_cron_schedule") cronspec = get_stats_cron_schedule()
interval = get_cron_interval(cronspec, asof) interval = get_cron_interval(cronspec, asof)
# We expect the file to be modified in the last 2 cron intervals # We expect the file to be modified in the last 2 cron intervals
cutoff_time = asof - (2 * interval) cutoff_time = asof - (2 * interval)
@ -168,7 +181,7 @@ if __name__ == "__main__":
if "croniter" in sys.modules.keys(): # not on trusty and imported croniter if "croniter" in sys.modules.keys(): # not on trusty and imported croniter
freshness_results = [check_stats_file_freshness(f) freshness_results = [check_stats_file_freshness(f)
for f in args.stats_file] for f in args.stats_file]
criticals.append( criticals.extend(
msg for status, msg in freshness_results if status == "CRIT" msg for status, msg in freshness_results if status == "CRIT"
) )

View File

@ -13,18 +13,32 @@
# limitations under the License. # limitations under the License.
from datetime import datetime, timedelta from datetime import datetime, timedelta
from tempfile import NamedTemporaryFile from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
import unittest import unittest
from mock import MagicMock, patch
import check_rabbitmq_queues import check_rabbitmq_queues
class CheckRabbitTest(unittest.TestCase): class CheckRabbitTest(unittest.TestCase):
@patch(
"check_rabbitmq_queues.config", @classmethod
MagicMock(return_value="*/5 * * * *"), def setUpClass(cls):
) cls.tmpdir = TemporaryDirectory()
cronjob = Path(cls.tmpdir.name) / "rabbitmq-stats"
with cronjob.open('w') as f:
f.write("*/5 * * * * root timeout -k 10s -s SIGINT 300 "
"/usr/local/bin/collect_rabbitmq_stats.sh 2>&1 | "
"logger -p local0.notice")
cls.old_cron = check_rabbitmq_queues.CRONJOB
check_rabbitmq_queues.CRONJOB = str(cronjob)
@classmethod
def tearDownClass(cls):
"""Tear down class fixture."""
cls.tmpdir.cleanup()
check_rabbitmq_queues.CRONJOB = cls.old_cron
def test_check_stats_file_freshness_fresh(self): def test_check_stats_file_freshness_fresh(self):
with NamedTemporaryFile() as stats_file: with NamedTemporaryFile() as stats_file:
results = check_rabbitmq_queues.check_stats_file_freshness( results = check_rabbitmq_queues.check_stats_file_freshness(
@ -32,10 +46,6 @@ class CheckRabbitTest(unittest.TestCase):
) )
self.assertEqual(results[0], "OK") self.assertEqual(results[0], "OK")
@patch(
"check_rabbitmq_queues.config",
MagicMock(return_value="*/5 * * * *"),
)
def test_check_stats_file_freshness_nonfresh(self): def test_check_stats_file_freshness_nonfresh(self):
with NamedTemporaryFile() as stats_file: with NamedTemporaryFile() as stats_file:
next_hour = datetime.now() + timedelta(hours=1) next_hour = datetime.now() + timedelta(hours=1)
@ -43,3 +53,7 @@ class CheckRabbitTest(unittest.TestCase):
stats_file.name, asof=next_hour stats_file.name, asof=next_hour
) )
self.assertEqual(results[0], "CRIT") self.assertEqual(results[0], "CRIT")
def test_get_stats_cron_schedule(self):
schedule = check_rabbitmq_queues.get_stats_cron_schedule()
self.assertEqual(schedule, "*/5 * * * *")