Improve parsing of cron schedule

Improving the parsing of the cron schedule for /etc/cron/rabbitmq-stats.
The code makes assumptions that the user in the cron entry will be the
root user, which is generally safe as that's what the charm applied.
However, the parsing is brittle in that it depends on the 'root' string
in the entry. This changes the code so that the cron timer spec is
stripped out based on the column entries in the file.

Change-Id: I2d573e8942e840e0e5376f1537a2a3373fea3db8
Fixes-Bug: #1939702
This commit is contained in:
Billy Olsen 2021-08-17 11:27:04 -07:00
parent 54460a568a
commit 45ded8b0f9
2 changed files with 16 additions and 2 deletions

View File

@ -103,9 +103,23 @@ def get_cron_interval(cronspec, base):
def get_stats_cron_schedule():
"""Returns the cron schedule from the stats CRONJOB spec file.
:return: a string containing the cron schedule
:rtype: str
"""
# TODO(wolsen) in general, the layout of this code makes a lot of
# assumptions about the files that are written, etc and is somewhat
# brittle for anything not specifically laid out by the charm. This
# should be revisited in the future.
with open(CRONJOB) as f:
cronjob = f.read()
return cronjob.split("root")[0].strip()
# The first 5 columns make up the cron spec, but the output of this
# function should be a string. Split the line on whitespace and reform
# the spec string from the necessary columns
# See LP#1939702
cron_spec = ' '.join(cronjob.split()[:5])
return cron_spec
def check_stats_file_freshness(stats_file, asof=None):

View File

@ -27,7 +27,7 @@ class CheckRabbitTest(unittest.TestCase):
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 "
f.write("*/5 * * * * rabbitmq 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