Merge ~txiao/charm-logrotated:handle_unset into charm-logrotated:master

Proposed by Tianqi Xiao
Status: Merged
Approved by: Robert Gildein
Approved revision: 8746e270196d0464b2c4e230f34cec756da15f11
Merged at revision: a137eb7f109dca499ec59fe7bcc7c47ee93d4596
Proposed branch: ~txiao/charm-logrotated:handle_unset
Merge into: charm-logrotated:master
Diff against target: 130 lines (+43/-10)
3 files modified
src/lib/lib_cron.py (+20/-8)
src/reactive/logrotate.py (+14/-2)
src/tests/unit/test_logrotate.py (+9/-0)
Reviewer Review Type Date Requested Status
🤖 prod-jenkaas-bootstack (community) continuous-integration Approve
Robert Gildein Approve
Eric Chen Needs Fixing
Kamal Bhaskar Approve
Review via email: mp+441130@code.launchpad.net

Commit message

Handle "unset" value of update-cron-daily-schedule and fix workload status logic

Description of the change

Previously, validating "unset" value would result in silent error because:
1. the con_mapping in CronHelper.validate_cron_conf() doesn't contain "unset" key
which leads to an attemption of concatenating str with NoneType in later lines
2. wrongly checking index 0 of a str instead of list for self.cron_daily_schedule
in CronHelper.install_cronjob()
3. wrong logic for setting status in install and config_changed hook, which means
the workload always ends up in "active" even when exceptions are raised
4. didn't set workload status to blocked when executing cronjob.

This commit fixes the above mentioned issues and added related unit tests.
Additionally, more logs are added to provide extra information.

To post a comment you must log in.
Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote :

This merge proposal is being monitored by mergebot. Change the status to Approved to merge.

Revision history for this message
🤖 prod-jenkaas-bootstack (prod-jenkaas-bootstack) wrote :
review: Approve (continuous-integration)
Revision history for this message
Eric Chen (eric-chen) wrote :

Good catch. It's shame that we didn't aware this in the previous code review
https://code.launchpad.net/~llama-charmers/charm-logrotated/+git/charm-logrotated/+merge/435334

Furthermore, we should not skip Diko's suggest in the MR too. From the source code, I do not find the code to reset the value. ( set -> unset, or random -> unset ). This can be another feature request. I will let Kamal review the code and confirm my idea is correct.

review: Needs Information
Revision history for this message
Chi Wai CHAN (raychan96) wrote :

I left some inline comments for some nitpicks (non-blocking)

Revision history for this message
Kamal Bhaskar (kamalb) wrote :

> Good catch. It's shame that we didn't aware this in the previous code review
> https://code.launchpad.net/~llama-charmers/charm-logrotated/+git/charm-
> logrotated/+merge/435334
>
> Furthermore, we should not skip Diko's suggest in the MR too. From the source
> code, I do not find the code to reset the value. ( set -> unset, or random ->
> unset ). This can be another feature request. I will let Kamal review the code
> and confirm my idea is correct.

Yes, your idea is absolutely correct and make sense. Resetting the config back to 'unset' from 'set' or 'random' is missing here and that can be taken as a feature request definitely.

Revision history for this message
Kamal Bhaskar (kamalb) wrote :

The code commit here LGTM and take care of the reported bug/problem.

review: Approve
Revision history for this message
Eric Chen (eric-chen) wrote :

Please check Ray's inline comment, he forgot to leave a status for "Needs Fixing"

review: Needs Fixing
Revision history for this message
Robert Gildein (rgildein) :
Revision history for this message
🤖 prod-jenkaas-bootstack (prod-jenkaas-bootstack) wrote :
review: Approve (continuous-integration)
Revision history for this message
Tianqi Xiao (txiao) wrote :

Thanks @eric-chen @kamalb @raychan96 @rgildein for the reviews. The MP has been updated to include the suggested changes. For the resetting the cron value, since it's out of the current scope, I opened LP#2016659 to track it[1]

[1]: https://bugs.launchpad.net/charm-logrotated/+bug/2016659

Revision history for this message
Robert Gildein (rgildein) wrote :

LGTM, thanks

review: Approve
Revision history for this message
🤖 prod-jenkaas-bootstack (prod-jenkaas-bootstack) wrote :
review: Approve (continuous-integration)
Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote :

Change successfully merged at revision a137eb7f109dca499ec59fe7bcc7c47ee93d4596

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/src/lib/lib_cron.py b/src/lib/lib_cron.py
2index 1287524..0e1c9a9 100644
3--- a/src/lib/lib_cron.py
4+++ b/src/lib/lib_cron.py
5@@ -76,7 +76,7 @@ class CronHelper:
6 if (
7 self.validate_cron_conf()
8 and self.cronjob_frequency == 1
9- and self.cron_daily_schedule[0] != "unset"
10+ and self.cron_daily_schedule.split(",")[0] != "unset"
11 ):
12 self.update_cron_daily_schedule()
13
14@@ -143,24 +143,33 @@ class CronHelper:
15 try:
16 conf = self.cron_daily_schedule
17 conf = conf.split(",")
18- if conf[0] not in ("unset", "set", "random") or len(conf) > 3:
19+ operation = conf[0]
20+ if operation not in ("unset", "set", "random") or len(conf) > 3:
21 raise ValueError(
22 "Invalid value for update-cron-daily-schedule: {}".format(conf)
23 )
24
25- conf_mapping = {
26- "set": "_validate_set_schedule",
27- "random": "_validate_random_schedule",
28- }
29+ result = True
30+ # run additional validation functions
31+ if operation == "set":
32+ result = self._validate_set_schedule(conf)
33+ elif operation == "random":
34+ result = self._validate_random_schedule(conf)
35
36- conf_handler = conf_mapping.get(conf[0])
37- result = eval("self." + conf_handler)(conf)
38 return result
39
40 except ValueError as err:
41+ hookenv.log(
42+ "Cron config validation failed: {}".format(err),
43+ level=hookenv.ERROR,
44+ )
45+ hookenv.status_set(
46+ "blocked", "Cron config validation failed. Check log for more info."
47+ )
48 raise self.InvalidCronConfig(err)
49
50 def _validate_set_schedule(self, conf):
51+ """Validate update-cron-daily-schedule when the "set" keyword exists."""
52 cron_daily_time = conf[1].split(":")
53 if not self._valid_timestamp(cron_daily_time):
54 raise ValueError(
55@@ -173,6 +182,7 @@ class CronHelper:
56 return True
57
58 def _validate_random_schedule(self, conf):
59+ """Validate update-cron-daily-schedule when the "random" keyword exists."""
60 cron_daily_start_time = conf[1].split(":")
61 cron_daily_end_time = conf[2].split(":")
62 if not (
63@@ -197,11 +207,13 @@ class CronHelper:
64
65 def main():
66 """Ran by cron."""
67+ hookenv.log("Executing cron job.", level=hookenv.INFO)
68 hookenv.status_set("maintenance", "Executing cron job.")
69 cronhelper = CronHelper()
70 cronhelper.read_config()
71 cronhelper.update_logrotate_etc()
72 cronhelper.install_cronjob()
73+ hookenv.log("Cron job completed.", level=hookenv.INFO)
74 hookenv.status_set("active", "Unit is ready.")
75
76
77diff --git a/src/reactive/logrotate.py b/src/reactive/logrotate.py
78index b699e8f..86620fa 100644
79--- a/src/reactive/logrotate.py
80+++ b/src/reactive/logrotate.py
81@@ -23,7 +23,12 @@ def install_logrotate():
82 logrotate.modify_configs()
83 cron.install_cronjob()
84 except Exception as ex:
85- hookenv.status_set("blocked", str(ex))
86+ hookenv.log(
87+ "Error running install hook: {}".format(str(ex)),
88+ level=hookenv.ERROR,
89+ )
90+ hookenv.status_set("blocked", "Install hook failed. Check logs for more info.")
91+ return
92 hookenv.status_set("active", "Unit is ready.")
93 set_flag("logrotate.installed")
94
95@@ -39,7 +44,14 @@ def config_changed():
96 logrotate.modify_configs()
97 cron.install_cronjob()
98 except Exception as ex:
99- hookenv.status_set("blocked", str(ex))
100+ hookenv.log(
101+ "Error running config-changed hook: {}".format(str(ex)),
102+ level=hookenv.ERROR,
103+ )
104+ hookenv.status_set(
105+ "blocked", "Config-changed hook failed. Check logs for more info."
106+ )
107+ return
108 hookenv.status_set("active", "Unit is ready.")
109
110
111diff --git a/src/tests/unit/test_logrotate.py b/src/tests/unit/test_logrotate.py
112index 4871183..c0c5cdb 100644
113--- a/src/tests/unit/test_logrotate.py
114+++ b/src/tests/unit/test_logrotate.py
115@@ -142,6 +142,15 @@ class TestLogrotateHelper:
116 class TestCronHelper:
117 """Main cron test class."""
118
119+ def test_cron_daily_schedule_unset(self, cron):
120+ """Test the validation of unset update-cron-daily-schedule config value."""
121+ cron_config = cron()
122+ cron_config.cronjob_enabled = True
123+ cron_config.cronjob_frequency = 1
124+ cron_config.cron_daily_schedule = "unset"
125+
126+ assert cron_config.validate_cron_conf()
127+
128 @pytest.mark.parametrize(
129 ("cron_schedule, exp_pattern"),
130 [

Subscribers

People subscribed via source and target branches

to all changes: