Repository navigation
implement CloudWatchScheduler class #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ff52067
implement CloudWatchScheduler class
jaymccon f7c11a0
catch ClientError
jaymccon 5de0051
use uuid str instead of .hex
jaymccon d26c6cc
minor style cleanup
jaymccon a4ddc18
use dict comprehension for serialize
jaymccon c2ef719
more granular tests
jaymccon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import json | ||
| import logging | ||
| from datetime import datetime, timedelta | ||
| from uuid import uuid4 | ||
|
|
||
| # boto3 doesn't have stub files | ||
| from boto3 import Session # type: ignore | ||
|
|
||
| from botocore.exceptions import ClientError # type: ignore | ||
|
|
||
| from .utils import HandlerRequest, KitchenSinkEncoder | ||
|
|
||
| LOG = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class CloudWatchScheduler: | ||
| def __init__(self, boto3_session: Session): | ||
| self.client = boto3_session.client("events") | ||
|
|
||
| def reschedule_after_minutes( | ||
| self, function_arn: str, minutes_from_now: int, handler_request: HandlerRequest | ||
| ) -> None: | ||
| cron = self._min_to_cron(max(minutes_from_now, 1)) | ||
| uuid = str(uuid4()) | ||
| rule_name = f"reinvoke-handler-{uuid}" | ||
| target_id = f"reinvoke-target-{uuid}" | ||
| handler_request.requestContext["cloudWatchEventsRuleName"] = rule_name | ||
| handler_request.requestContext["cloudWatchEventsTargetId"] = target_id | ||
| json_request = json.dumps(handler_request.serialize(), cls=KitchenSinkEncoder) | ||
| LOG.info("Scheduling re-invoke at %s (%s)", cron, uuid) | ||
| self.client.put_rule(Name=rule_name, ScheduleExpression=cron, State="ENABLED") | ||
| self.client.put_targets( | ||
| Rule=rule_name, | ||
| Targets=[{"Id": target_id, "Arn": function_arn, "Input": json_request}], | ||
| ) | ||
|
|
||
| def cleanup_cloudwatch_events(self, rule_name: str, target_id: str) -> None: | ||
| try: | ||
| if target_id and rule_name: | ||
| self.client.remove_targets(Rule=rule_name, Ids=[target_id]) | ||
| except ClientError as e: | ||
| LOG.error( | ||
| "Error cleaning CloudWatchEvents Target (targetId=%s): %s", target_id, e | ||
| ) | ||
| try: | ||
| if rule_name: | ||
| self.client.delete_rule(Name=rule_name, Force=True) | ||
| except ClientError as e: | ||
| LOG.error( | ||
| "Error cleaning CloudWatchEvents (ruleName=%s): %s", rule_name, str(e) | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _min_to_cron(minutes: int) -> str: | ||
| schedule_time = datetime.now() + timedelta(minutes=minutes) | ||
| # add another minute, as per java implementation | ||
| schedule_time = schedule_time + timedelta(minutes=1) | ||
| return schedule_time.strftime("cron('%M %H %d %m ? %Y')") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| # pylint: disable=redefined-outer-name,protected-access | ||
| from datetime import datetime | ||
| from unittest.mock import Mock, patch | ||
| from uuid import uuid4 | ||
|
|
||
| import pytest | ||
| from cloudformation_cli_python_lib.scheduler import CloudWatchScheduler | ||
|
|
||
| from botocore.exceptions import ClientError | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_boto3_session(): | ||
| return Mock("cloudformation_cli_python_lib.scheduler.Session", autospec=True)() | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_handler_request(): | ||
| mock_request = Mock( | ||
| "cloudformation_cli_python_lib.utils.HandlerRequest", autospec=True | ||
| )() | ||
| mock_request.requestContext = {} | ||
| mock_request.serialize.return_value = {} | ||
| return mock_request | ||
|
|
||
|
|
||
| def test_instantiates_boto3_client(mock_boto3_session): | ||
|
tobywf marked this conversation as resolved.
|
||
| cw_scheduler = CloudWatchScheduler(boto3_session=mock_boto3_session) | ||
| mock_boto3_session.client.assert_called_once_with("events") | ||
| assert cw_scheduler.client == mock_boto3_session.client.return_value | ||
|
|
||
|
|
||
| @patch( | ||
| "cloudformation_cli_python_lib.scheduler.CloudWatchScheduler._min_to_cron", | ||
| return_value="cron('30 16 21 11 ? 2019')", | ||
| ) | ||
| def test_reschedule_after_minutes_zero( | ||
| mock_min_to_cron, mock_boto3_session, mock_handler_request | ||
| ): | ||
|
jaymccon marked this conversation as resolved.
|
||
| cw_scheduler = CloudWatchScheduler(boto3_session=mock_boto3_session) | ||
|
|
||
| # if called with zero, should call cron with a 1 | ||
| cw_scheduler.reschedule_after_minutes("arn:goes:here", 0, mock_handler_request) | ||
| mock_min_to_cron.assert_called_once_with(1) | ||
|
|
||
|
|
||
| @patch( | ||
| "cloudformation_cli_python_lib.scheduler.CloudWatchScheduler._min_to_cron", | ||
| return_value="cron('30 16 21 11 ? 2019')", | ||
| ) | ||
| def test_reschedule_after_minutes_not_zero( | ||
| mock_min_to_cron, mock_boto3_session, mock_handler_request | ||
| ): | ||
| cw_scheduler = CloudWatchScheduler(boto3_session=mock_boto3_session) | ||
| # if called with another number, should use that | ||
| cw_scheduler.reschedule_after_minutes("arn:goes:here", 2, mock_handler_request) | ||
| mock_min_to_cron.assert_called_once_with(2) | ||
|
|
||
|
|
||
| @patch( | ||
| "cloudformation_cli_python_lib.scheduler.uuid4", | ||
| autospec=True, | ||
| return_value=str(uuid4()), | ||
| ) | ||
| def test_reschedule_after_minutes_success( | ||
| mock_uuid4, mock_boto3_session, mock_handler_request | ||
| ): | ||
| cw_scheduler = CloudWatchScheduler(boto3_session=mock_boto3_session) | ||
| with patch( | ||
| "cloudformation_cli_python_lib.scheduler.CloudWatchScheduler._min_to_cron", | ||
| return_value="cron('30 16 21 11 ? 2019')", | ||
| ): | ||
| cw_scheduler.reschedule_after_minutes("arn:goes:here", 2, mock_handler_request) | ||
|
|
||
| # should have made appropriate calls to create the schedule | ||
| cw_scheduler.client.put_targets.assert_called_once_with( | ||
| Rule=f"reinvoke-handler-{mock_uuid4.return_value}", | ||
| Targets=[ | ||
| { | ||
| "Id": f"reinvoke-target-{mock_uuid4.return_value}", | ||
| "Arn": "arn:goes:here", | ||
| "Input": "{}", | ||
| } | ||
| ], | ||
| ) | ||
| cw_scheduler.client.put_rule.assert_called_once_with( | ||
| Name=f"reinvoke-handler-{mock_uuid4.return_value}", | ||
| ScheduleExpression="cron('30 16 21 11 ? 2019')", | ||
| State="ENABLED", | ||
| ) | ||
|
|
||
|
|
||
| @patch("cloudformation_cli_python_lib.scheduler.LOG", autospec=True) | ||
| def test_cleanup_cloudwatch_events_empty(mock_logger, mock_boto3_session): | ||
| cw_scheduler = CloudWatchScheduler(boto3_session=mock_boto3_session) | ||
|
|
||
| # cleanup should silently pass if rule/target are empty | ||
| cw_scheduler.cleanup_cloudwatch_events("", "") | ||
| assert cw_scheduler.client.remove_targets.called is False | ||
| assert cw_scheduler.client.delete_rule.called is False | ||
| assert mock_logger.error.called is False | ||
|
|
||
|
|
||
| @patch("cloudformation_cli_python_lib.scheduler.LOG", autospec=True) | ||
| def test_cleanup_cloudwatch_events_success(mock_logger, mock_boto3_session): | ||
| cw_scheduler = CloudWatchScheduler(boto3_session=mock_boto3_session) | ||
|
|
||
| # when rule_name and target_id are provided we should call events client and not | ||
| # log errors if the deletion succeeds | ||
| cw_scheduler.cleanup_cloudwatch_events("rulename", "targetid") | ||
| assert mock_logger.error.called is False | ||
| cw_scheduler.client.remove_targets.assert_called_once() | ||
| cw_scheduler.client.delete_rule.assert_called_once() | ||
|
|
||
|
|
||
| @patch("cloudformation_cli_python_lib.scheduler.LOG", autospec=True) | ||
| def test_cleanup_cloudwatch_events_boto_error(mock_logger, mock_boto3_session): | ||
| cw_scheduler = CloudWatchScheduler(boto3_session=mock_boto3_session) | ||
|
|
||
| # cleanup should catch and log boto failures | ||
| err = ClientError(error_response={"Error": {"Code": "1"}}, operation_name="mock") | ||
| cw_scheduler.client.remove_targets.side_effect = err | ||
| cw_scheduler.client.delete_rule.side_effect = err | ||
| cw_scheduler.cleanup_cloudwatch_events("rulename", "targetid") | ||
|
jaymccon marked this conversation as resolved.
|
||
| assert mock_logger.error.call_count == 2 | ||
| cw_scheduler.client.remove_targets.assert_called_once() | ||
| cw_scheduler.client.delete_rule.assert_called_once() | ||
|
|
||
|
|
||
| @patch("cloudformation_cli_python_lib.scheduler.datetime", autospec=True) | ||
| def test__min_to_cron(mock_datetime): | ||
| mock_datetime.now.return_value = datetime.fromisoformat("2019-01-01 01:01:01") | ||
| cron = CloudWatchScheduler._min_to_cron(1) | ||
| assert cron == "cron('03 01 01 01 ? 2019')" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.