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
diff --git a/src/lib/lib_cron.py b/src/lib/lib_cron.py
index 1287524..0e1c9a9 100644
--- a/src/lib/lib_cron.py
+++ b/src/lib/lib_cron.py
@@ -76,7 +76,7 @@ class CronHelper:
76 if (76 if (
77 self.validate_cron_conf()77 self.validate_cron_conf()
78 and self.cronjob_frequency == 178 and self.cronjob_frequency == 1
79 and self.cron_daily_schedule[0] != "unset"79 and self.cron_daily_schedule.split(",")[0] != "unset"
80 ):80 ):
81 self.update_cron_daily_schedule()81 self.update_cron_daily_schedule()
8282
@@ -143,24 +143,33 @@ class CronHelper:
143 try:143 try:
144 conf = self.cron_daily_schedule144 conf = self.cron_daily_schedule
145 conf = conf.split(",")145 conf = conf.split(",")
146 if conf[0] not in ("unset", "set", "random") or len(conf) > 3:146 operation = conf[0]
147 if operation not in ("unset", "set", "random") or len(conf) > 3:
147 raise ValueError(148 raise ValueError(
148 "Invalid value for update-cron-daily-schedule: {}".format(conf)149 "Invalid value for update-cron-daily-schedule: {}".format(conf)
149 )150 )
150151
151 conf_mapping = {152 result = True
152 "set": "_validate_set_schedule",153 # run additional validation functions
153 "random": "_validate_random_schedule",154 if operation == "set":
154 }155 result = self._validate_set_schedule(conf)
156 elif operation == "random":
157 result = self._validate_random_schedule(conf)
155158
156 conf_handler = conf_mapping.get(conf[0])
157 result = eval("self." + conf_handler)(conf)
158 return result159 return result
159160
160 except ValueError as err:161 except ValueError as err:
162 hookenv.log(
163 "Cron config validation failed: {}".format(err),
164 level=hookenv.ERROR,
165 )
166 hookenv.status_set(
167 "blocked", "Cron config validation failed. Check log for more info."
168 )
161 raise self.InvalidCronConfig(err)169 raise self.InvalidCronConfig(err)
162170
163 def _validate_set_schedule(self, conf):171 def _validate_set_schedule(self, conf):
172 """Validate update-cron-daily-schedule when the "set" keyword exists."""
164 cron_daily_time = conf[1].split(":")173 cron_daily_time = conf[1].split(":")
165 if not self._valid_timestamp(cron_daily_time):174 if not self._valid_timestamp(cron_daily_time):
166 raise ValueError(175 raise ValueError(
@@ -173,6 +182,7 @@ class CronHelper:
173 return True182 return True
174183
175 def _validate_random_schedule(self, conf):184 def _validate_random_schedule(self, conf):
185 """Validate update-cron-daily-schedule when the "random" keyword exists."""
176 cron_daily_start_time = conf[1].split(":")186 cron_daily_start_time = conf[1].split(":")
177 cron_daily_end_time = conf[2].split(":")187 cron_daily_end_time = conf[2].split(":")
178 if not (188 if not (
@@ -197,11 +207,13 @@ class CronHelper:
197207
198def main():208def main():
199 """Ran by cron."""209 """Ran by cron."""
210 hookenv.log("Executing cron job.", level=hookenv.INFO)
200 hookenv.status_set("maintenance", "Executing cron job.")211 hookenv.status_set("maintenance", "Executing cron job.")
201 cronhelper = CronHelper()212 cronhelper = CronHelper()
202 cronhelper.read_config()213 cronhelper.read_config()
203 cronhelper.update_logrotate_etc()214 cronhelper.update_logrotate_etc()
204 cronhelper.install_cronjob()215 cronhelper.install_cronjob()
216 hookenv.log("Cron job completed.", level=hookenv.INFO)
205 hookenv.status_set("active", "Unit is ready.")217 hookenv.status_set("active", "Unit is ready.")
206218
207219
diff --git a/src/reactive/logrotate.py b/src/reactive/logrotate.py
index b699e8f..86620fa 100644
--- a/src/reactive/logrotate.py
+++ b/src/reactive/logrotate.py
@@ -23,7 +23,12 @@ def install_logrotate():
23 logrotate.modify_configs()23 logrotate.modify_configs()
24 cron.install_cronjob()24 cron.install_cronjob()
25 except Exception as ex:25 except Exception as ex:
26 hookenv.status_set("blocked", str(ex))26 hookenv.log(
27 "Error running install hook: {}".format(str(ex)),
28 level=hookenv.ERROR,
29 )
30 hookenv.status_set("blocked", "Install hook failed. Check logs for more info.")
31 return
27 hookenv.status_set("active", "Unit is ready.")32 hookenv.status_set("active", "Unit is ready.")
28 set_flag("logrotate.installed")33 set_flag("logrotate.installed")
2934
@@ -39,7 +44,14 @@ def config_changed():
39 logrotate.modify_configs()44 logrotate.modify_configs()
40 cron.install_cronjob()45 cron.install_cronjob()
41 except Exception as ex:46 except Exception as ex:
42 hookenv.status_set("blocked", str(ex))47 hookenv.log(
48 "Error running config-changed hook: {}".format(str(ex)),
49 level=hookenv.ERROR,
50 )
51 hookenv.status_set(
52 "blocked", "Config-changed hook failed. Check logs for more info."
53 )
54 return
43 hookenv.status_set("active", "Unit is ready.")55 hookenv.status_set("active", "Unit is ready.")
4456
4557
diff --git a/src/tests/unit/test_logrotate.py b/src/tests/unit/test_logrotate.py
index 4871183..c0c5cdb 100644
--- a/src/tests/unit/test_logrotate.py
+++ b/src/tests/unit/test_logrotate.py
@@ -142,6 +142,15 @@ class TestLogrotateHelper:
142class TestCronHelper:142class TestCronHelper:
143 """Main cron test class."""143 """Main cron test class."""
144144
145 def test_cron_daily_schedule_unset(self, cron):
146 """Test the validation of unset update-cron-daily-schedule config value."""
147 cron_config = cron()
148 cron_config.cronjob_enabled = True
149 cron_config.cronjob_frequency = 1
150 cron_config.cron_daily_schedule = "unset"
151
152 assert cron_config.validate_cron_conf()
153
145 @pytest.mark.parametrize(154 @pytest.mark.parametrize(
146 ("cron_schedule, exp_pattern"),155 ("cron_schedule, exp_pattern"),
147 [156 [

Subscribers

People subscribed via source and target branches

to all changes: