From 4db48d142a3ba507de375acb557def4fcdf36e6a Mon Sep 17 00:00:00 2001 From: "Ifeanyi O." Date: Thu, 3 Dec 2026 16:58:31 -0600 Subject: [PATCH] New serverless pattern - eventbridge-scheduler-cron-migration Adds eventbridge-scheduler-cron-migration/python/sam: migrating cron on a VM to Amazon EventBridge Scheduler. An import script converts a crontab into one schedule per entry targeting a Lambda dispatcher, each run is recorded in DynamoDB keyed on the scheduled window, a CloudWatch alarm treats a missing completion as breaching, and a catch-up function idempotently replays windows missed during a deployment. --- .../python/sam/.gitignore | 4 + .../python/sam/README.md | 222 +++++++++++ .../python/sam/example-pattern.json | 71 ++++ .../python/sam/src/catchup/app.py | 178 +++++++++ .../python/sam/src/catchup/cron_match.py | 137 +++++++ .../python/sam/src/catchup/requirements.txt | 3 + .../python/sam/src/dispatcher/app.py | 242 ++++++++++++ .../sam/src/dispatcher/requirements.txt | 3 + .../python/sam/template.yaml | 283 ++++++++++++++ .../python/sam/tools/cron_to_scheduler.py | 188 ++++++++++ .../python/sam/tools/examples/crontab | 16 + .../sam/tools/examples/crontab-unsupported | 23 ++ .../python/sam/tools/examples/schedule.json | 15 + .../python/sam/tools/import_crontab.py | 345 ++++++++++++++++++ .../sam/tools/test_cron_to_scheduler.py | 135 +++++++ 15 files changed, 1865 insertions(+) create mode 100644 eventbridge-scheduler-cron-migration/python/sam/.gitignore create mode 100644 eventbridge-scheduler-cron-migration/python/sam/README.md create mode 100644 eventbridge-scheduler-cron-migration/python/sam/example-pattern.json create mode 100644 eventbridge-scheduler-cron-migration/python/sam/src/catchup/app.py create mode 100644 eventbridge-scheduler-cron-migration/python/sam/src/catchup/cron_match.py create mode 100644 eventbridge-scheduler-cron-migration/python/sam/src/catchup/requirements.txt create mode 100644 eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/app.py create mode 100644 eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/requirements.txt create mode 100644 eventbridge-scheduler-cron-migration/python/sam/template.yaml create mode 100644 eventbridge-scheduler-cron-migration/python/sam/tools/cron_to_scheduler.py create mode 100644 eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab create mode 100644 eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab-unsupported create mode 100644 eventbridge-scheduler-cron-migration/python/sam/tools/examples/schedule.json create mode 100644 eventbridge-scheduler-cron-migration/python/sam/tools/import_crontab.py create mode 100644 eventbridge-scheduler-cron-migration/python/sam/tools/test_cron_to_scheduler.py diff --git a/eventbridge-scheduler-cron-migration/python/sam/.gitignore b/eventbridge-scheduler-cron-migration/python/sam/.gitignore new file mode 100644 index 0000000000..cdd831584c --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/.gitignore @@ -0,0 +1,4 @@ +.aws-sam/ +samconfig.toml +__pycache__/ +*.pyc diff --git a/eventbridge-scheduler-cron-migration/python/sam/README.md b/eventbridge-scheduler-cron-migration/python/sam/README.md new file mode 100644 index 0000000000..72fd834a5e --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/README.md @@ -0,0 +1,222 @@ +# Migrate cron to Amazon EventBridge Scheduler with AWS Lambda and Amazon DynamoDB + +This pattern helps you **replace cron on a VM** with Amazon EventBridge Scheduler. It reads an existing crontab, creates one schedule per entry, keeps an **execution record** of every run in Amazon DynamoDB, alarms when a job does not report completion, and replays a **missed schedule** after a deployment. + +A schedule **survives reboots**, because there is no instance to reboot and no `crontab -l` to lose with the host. You can **migrate one job at a time**, and **roll back by disabling the schedule** without touching the rest. + +Learn more about this pattern at Serverless Land Patterns: << Add the live URL here >> + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +## Requirements + +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed +* Python installed, to run the import script. The script needs `boto3` to create schedules; `--dry-run` converts and checks a crontab with no dependencies at all. + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ``` + git clone https://github.com/aws-samples/serverless-patterns + ``` +1. Change directory to the pattern directory: + ``` + cd serverless-patterns/eventbridge-scheduler-cron-migration/python/sam + ``` +1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yaml file: + ``` + sam deploy --guided + ``` +1. During the prompts: + * Enter a stack name + * Enter the desired AWS Region + * Enter a `ScheduleTimezone`, for example `America/New_York`. A crontab inherits the time zone of the host it runs on; a schedule has to state it. + * Allow SAM CLI to create IAM roles with the required permissions. + + Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults. +1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. The `ImportCommand` output is a ready-made import command with every ARN filled in. + +### Import the crontab + +The stack deploys the machinery; the import script creates the schedules. Convert first and look at the result before anything is created: + +```bash +python3 tools/import_crontab.py --crontab tools/examples/crontab \ + --dispatcher-arn \ + --role-arn \ + --group \ + --dlq-arn \ + --timezone America/New_York \ + --dry-run +``` + +``` +Time zone: America/New_York +2 schedule(s) to import: + nightly-report cron(0 2 * * ? *) <- 0 2 * * * /usr/local/bin/nightly-report.sh --full + hourly-sync cron(0 * * * ? *) <- 0 * * * * /usr/local/bin/sync-inventory.sh +``` + +Drop `--dry-run` to create them. Re-running the import updates the existing schedules in place, so it is safe to run again as you work through a crontab. + +To migrate one job at a time, import a single job with `--only`, or create everything in the `DISABLED` state with `--disabled` and enable each schedule once you have compared a run against the old crontab: + +```bash +python3 tools/import_crontab.py --crontab /etc/crontab --only nightly-report --disabled ... +aws scheduler update-schedule --name nightly-report --group-name --state ENABLED ... +``` + +## How it works + +An import script, a dispatcher, a table and an alarm replace what a crontab and a mail alias used to do between them. + +**One schedule per crontab line.** `tools/import_crontab.py` parses a crontab, converts each entry, and calls `CreateSchedule` once per line with an explicit time zone, a retry policy and a dead-letter queue. Every schedule targets the same Lambda dispatcher and names its job in the payload, so the schedule count matches the crontab line count without one function per job. Schedules live in their own schedule group, so you can list and remove the migration as a unit. + +**The conversion is not a copy and paste.** A crontab line and a cron expression look alike, which is what makes the differences expensive: + +| | crontab | EventBridge Scheduler | +| --- | --- | --- | +| Fields | 5 | 6, the extra one is `year` | +| Day of week | `0`-`6` from Sunday, `7` also Sunday | `1`-`7` from Sunday, so every number shifts | +| Both day fields | `*` in both is normal | not allowed; one must be `?` | +| Day-of-month **and** day-of-week | ORed together | cannot be expressed | +| `@reboot` | runs at boot | no equivalent | + +Copying `0 0 * * 1` across unchanged moves a Monday job to Sunday and produces an expression Scheduler rejects. The importer handles the shift, and refuses what Scheduler cannot express faithfully rather than quietly creating a schedule that fires on the wrong days. Run it against `tools/examples/crontab-unsupported` to see each refusal and its reason. + +**Every run leaves an execution record.** The dispatcher writes an item to DynamoDB when a run starts and updates it when the run finishes, keyed on `job#` and `run#`. The scheduled time comes from the schedule itself, through the `` context attribute, not from the clock inside the function. That is what makes a retry address the same record instead of creating a second one, and it is what lets the catch-up function tell a missed window from a completed one. A `marker` item per job holds the last completed window and only ever moves forward. + +**The alarm watches for silence.** On completion the dispatcher publishes a `JobCompleted` metric for the job, and a CloudWatch alarm with `TreatMissingData: breaching` fires when that metric does not arrive inside the expected window. This is deliberately the opposite of alarming on errors: the failure a crontab hides is the run that never started, which produces no output, no exit code and no mail, so nothing fires. Set `MonitoredJobDeadlineSeconds` to the business deadline for the job, not to its runtime. + +**Catch-up closes the deployment gap.** A schedule missed during a deployment is the case cron has no answer for: if the host was replaced at 02:03 and a job was due at 02:00, that run is simply gone and nothing notices. The catch-up function reads each job's marker, lists the windows that should have fired since, and invokes the dispatcher once per window with that window's scheduled time. The dispatcher's conditional write makes each replay idempotent, so running catch-up twice does not run a job twice. + +Catch-up is bounded on purpose. It replays at most `MAX_REPLAYS_PER_JOB` windows per job, and a job with no marker at all looks back `lookbackHours` rather than to the beginning of time, so a first run against an empty table cannot replay a year of windows. Raise either in `src/catchup/app.py` if a longer gap is genuinely possible; a job whose marker is months old will otherwise stop at the cap. + +The one-time schedule that triggers catch-up is created by the import script rather than declared in `template.yaml`, for a reason worth knowing: `AWS::Scheduler::Schedule` has no `ActionAfterCompletion` property, and a completed one-time schedule keeps counting against the Region's schedule quota until something deletes it. The API accepts `ActionAfterCompletion=DELETE`, so a schedule created that way removes itself after it fires. + +**Rollback** is one call. `update-schedule --state DISABLED` stops a job without deleting its history or touching any other job, which is the property that makes migrating one job at a time safe. + +A few limits worth stating plainly. Schedules invoke their targets with 60 second precision, so a run due at 02:00 starts somewhere in that minute. Scheduler adjusts cron schedules for daylight saving time in the time zone you give it: when the clock springs forward onto a time that does not exist the run is skipped, and when it falls back the run happens once rather than twice. Neither is something a crontab on a VM handles better, but both are worth knowing before you move a job that cares. + +## Testing + +The commands below use the stack outputs. Set `STACK` to your stack name first. + +```bash +STACK= +GROUP=$(aws cloudformation describe-stacks --stack-name $STACK \ + --query "Stacks[0].Outputs[?OutputKey=='ScheduleGroupName'].OutputValue" --output text) +TABLE=$(aws cloudformation describe-stacks --stack-name $STACK \ + --query "Stacks[0].Outputs[?OutputKey=='RunHistoryTableName'].OutputValue" --output text) +DISPATCHER=$(aws cloudformation describe-stacks --stack-name $STACK \ + --query "Stacks[0].Outputs[?OutputKey=='DispatcherFunctionArn'].OutputValue" --output text) +``` + +**1. Confirm the conversion.** Run the importer against the unsupported examples and check that each line is refused with a reason: + +```bash +python3 tools/import_crontab.py --crontab tools/examples/crontab-unsupported \ + --dispatcher-arn $DISPATCHER --role-arn x --group $GROUP --dry-run +``` + +**2. Confirm the schedules exist**, with the time zone and dead-letter queue attached: + +```bash +aws scheduler list-schedules --group-name $GROUP \ + --query "Schedules[].{Name:Name,State:State}" --output table +aws scheduler get-schedule --group-name $GROUP --name nightly-report \ + --query "{Expression:ScheduleExpression,Timezone:ScheduleExpressionTimezone,DLQ:Target.DeadLetterConfig.Arn}" +``` + +**3. Run a job without waiting for its window.** Invoke the dispatcher with a scheduled time of your choosing. This is also the CLI test case for the function: + +```bash +aws lambda invoke --function-name $DISPATCHER --cli-binary-format raw-in-base64-out \ + --payload '{"job":"nightly-report","scheduledTime":"2026-01-01T02:00:00Z","executionId":"manual-1","attempt":1,"scheduleArn":"manual"}' \ + response.json && cat response.json +``` + +Expected: `{"job": "nightly-report", "scheduledTime": "2026-01-01T02:00:00Z", "status": "COMPLETED", "durationMs": ...}` + +**4. Confirm the execution record**, which should hold one `run#` item and one `marker`: + +```bash +aws dynamodb query --table-name $TABLE \ + --key-condition-expression "pk = :pk" \ + --expression-attribute-values '{":pk":{"S":"job#nightly-report"}}' \ + --query "Items[].{sk:sk.S,status:status.S,scheduled:scheduledTime.S}" --output table +``` + +**5. Confirm a replay does not run the job twice.** Invoke the same payload again: + +```bash +aws lambda invoke --function-name $DISPATCHER --cli-binary-format raw-in-base64-out \ + --payload '{"job":"nightly-report","scheduledTime":"2026-01-01T02:00:00Z","executionId":"manual-2","attempt":1,"scheduleArn":"manual"}' \ + response.json && cat response.json +``` + +Expected: `"status": "SKIPPED"`. The window already completed, so the conditional write refused it. + +**6. Confirm catch-up finds a missed schedule.** Ask the catch-up function what it would replay, without replaying it: + +```bash +CATCHUP=$(aws cloudformation describe-stacks --stack-name $STACK \ + --query "Stacks[0].Outputs[?OutputKey=='CatchUpFunctionArn'].OutputValue" --output text) +aws lambda invoke --function-name $CATCHUP --cli-binary-format raw-in-base64-out \ + --payload '{"dryRun":true,"lookbackHours":48}' response.json && cat response.json +``` + +Expected: a `wouldReplay` list of the windows between each job's marker and now. Drop `dryRun` to replay them; every window already recorded comes back `SKIPPED`. + +**7. Confirm the alarm treats silence as a failure.** A job that has never completed has no metric at all, so the alarm should settle in `ALARM` rather than `INSUFFICIENT_DATA`: + +```bash +aws cloudwatch describe-alarms --alarm-names "$STACK-nightly-report-no-completion" \ + --query "MetricAlarms[].{State:StateValue,Reason:StateReason}" --output table +``` + +### Lambda test event + +```json +{ + "job": "nightly-report", + "scheduledTime": "2026-01-01T02:00:00Z", + "executionId": "manual-1", + "attempt": 1, + "scheduleArn": "manual" +} +``` + +### Unit tests + +The crontab conversion has a known-answer test suite covering the field count, the day-of-week shift, the `?` rule, the macros and every refusal: + +```bash +cd tools && python3 -m unittest -v test_cron_to_scheduler +``` + +## Cleanup + +1. Delete the schedules the importer created. They are not part of the stack, so CloudFormation does not remove them, and a schedule group cannot be deleted while it still holds schedules: + ```bash + for name in $(aws scheduler list-schedules --group-name $GROUP --query "Schedules[].Name" --output text); do + aws scheduler delete-schedule --name $name --group-name $GROUP + done + ``` +1. Delete the stack + ```bash + aws cloudformation delete-stack --stack-name STACK_NAME + ``` +1. Confirm the stack has been deleted + ```bash + aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus" + ``` + +---- + +Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/eventbridge-scheduler-cron-migration/python/sam/example-pattern.json b/eventbridge-scheduler-cron-migration/python/sam/example-pattern.json new file mode 100644 index 0000000000..a79ff49181 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/example-pattern.json @@ -0,0 +1,71 @@ +{ + "title": "Migrate cron to Amazon EventBridge Scheduler with AWS Lambda and Amazon DynamoDB", + "description": "Replace cron on a VM: import a crontab as one schedule per job, keep an execution record, alarm on a missing completion, and catch up a missed schedule.", + "language": "Python", + "level": "300", + "framework": "AWS SAM", + "tags": ["cron", "scheduler", "migration", "catch-up"], + "introBox": { + "headline": "How it works", + "text": [ + "This pattern replaces cron on a VM with Amazon EventBridge Scheduler. An import script reads an existing crontab, converts each line into a Scheduler cron expression, and creates one schedule per entry targeting a single AWS Lambda dispatcher. Nothing has to be rewritten job by job, because the crontab is the input. The dispatcher routes on the job name carried in the schedule payload, so the number of schedules matches the number of crontab lines without deploying one Lambda function per job. Every schedule is created in its own schedule group, so the migration can be listed, disabled or removed as a unit.", + "Converting a crontab is not a copy and paste. A Scheduler cron expression has six fields rather than five, numbers the days of the week from Sunday as 1 rather than 0, and cannot use the asterisk wildcard in both day fields at once, so a line carried across unchanged can move a Monday job to Sunday or be rejected outright. The importer handles all three conversions, and refuses the lines Scheduler cannot express faithfully rather than creating a schedule that fires on the wrong days. Those include @reboot, which has no equivalent because there is no instance to boot, and a crontab that restricts both the day of the month and the day of the week, which cron treats as a logical OR. A dry run prints the converted expressions, and every refusal with its reason, before anything is created.", + "The dispatcher writes an execution record to an Amazon DynamoDB table when a run starts and updates it when the run finishes, keyed on the scheduled window taken from the schedule's own context attributes rather than from the clock inside the function. Keying on the window is what lets a retry update the same record instead of creating a second one, and what lets the catch-up function tell a missed schedule apart from a completed one. A marker item per job holds the last completed window and only ever moves forward.", + "On completion the dispatcher publishes a metric, and a CloudWatch alarm that treats missing data as breaching fires when that metric does not arrive inside the expected window. The alarm watches for absence rather than for errors, because the failure a crontab hides is the run that never started: it produces no output, no exit code and no mail, so nothing fires. A catch-up function reads each job's marker, lists the windows that should have fired while no schedule was running, and replays them idempotently, which closes the gap a deployment leaves behind.", + "A schedule survives reboots because there is no host to reboot and no crontab to lose along with it. Jobs can be migrated one at a time by importing a single entry or by creating every schedule disabled and enabling them individually, and a rollback is one call to disable one schedule." + ] + }, + "gitHub": { + "template": { + "templateFile": "template.yaml" + } + }, + "resources": { + "bullets": [ + { + "text": "Schedule types on EventBridge Scheduler, including the six cron fields and the day-of-week numbering", + "link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html" + }, + { + "text": "Adding context attributes, used here to pass the scheduled time into the run record", + "link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule-context-attributes.html" + }, + { + "text": "Managing a schedule: time zones, flexible time windows, retries and dead-letter queues", + "link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule.html" + }, + { + "text": "Configuring how CloudWatch alarms treat missing data", + "link": "https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarms-and-missing-data" + }, + { + "text": "Quotas for EventBridge Scheduler, including the schedule count that completed one-time schedules consume", + "link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/scheduler-quotas.html" + } + ] + }, + "deploy": { + "text": [ + "sam deploy --guided" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the schedules the importer created, then delete the stack: sam delete." + ] + }, + "authors": [ + { + "name": "Ifeanyi O.", + "bio": "Developer Experience Engineer at AWS", + "linkedin": "ifeanyi-otuonye", + "twitter": "ifeanyi_otuonye", + "github": "rextheking" + } + ] +} diff --git a/eventbridge-scheduler-cron-migration/python/sam/src/catchup/app.py b/eventbridge-scheduler-cron-migration/python/sam/src/catchup/app.py new file mode 100644 index 0000000000..4e46f9b3dd --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/src/catchup/app.py @@ -0,0 +1,178 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Replay scheduled windows that elapsed while no schedule was running. + +A crontab on a VM has no memory: if the host was down, or the schedule was +disabled during a rollback, or a deployment replaced the stack between 02:00 and +02:05, the 02:00 run is simply gone and nothing notices. This function closes +that gap. + +For every schedule in the group it reads the last completed window from the +run-history marker, lists the windows that should have fired since, and invokes +the dispatcher once per window with that window's scheduled time. The +dispatcher's conditional write makes each replay idempotent, so running this +twice does not run a job twice. + +Invoked by the one-time schedule that tools/import_crontab.py --schedule-catchup +creates after a deploy, or by hand with an empty payload. +""" + +import datetime as dt +import json +import logging +import os +from zoneinfo import ZoneInfo + +import boto3 + +import cron_match + +logger = logging.getLogger() +logger.setLevel(os.environ.get("LOG_LEVEL", "INFO")) + +TABLE_NAME = os.environ["RUN_HISTORY_TABLE"] +DISPATCHER = os.environ["DISPATCHER_FUNCTION_NAME"] +GROUP_NAME = os.environ["SCHEDULE_GROUP_NAME"] +DEFAULT_TIMEZONE = os.environ.get("SCHEDULE_TIMEZONE", "UTC") + +# A deployment gap is hours, not months. Capping the lookback stops a first run +# against an empty table from replaying a year of windows. +DEFAULT_LOOKBACK_HOURS = 24 +MAX_REPLAYS_PER_JOB = 50 + +# The format EventBridge Scheduler uses for , e.g. +# 2022-03-22T18:59:43Z. Replays must use the same spelling so they address the +# same run-history item a live invocation would. +SCHEDULED_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + +_table = boto3.resource("dynamodb").Table(TABLE_NAME) +_scheduler = boto3.client("scheduler") +_lambda = boto3.client("lambda") + + +def _list_group_schedules() -> list: + schedules, token = [], None + while True: + kwargs = {"GroupName": GROUP_NAME, "MaxResults": 100} + if token: + kwargs["NextToken"] = token + page = _scheduler.list_schedules(**kwargs) + schedules.extend(page.get("Schedules", [])) + token = page.get("NextToken") + if not token: + return schedules + + +def _job_name_from_target(schedule: dict) -> str: + """Read the job name out of the schedule's own payload.""" + raw_input = (schedule.get("Target") or {}).get("Input") or "{}" + try: + return json.loads(raw_input).get("job") or "" + except json.JSONDecodeError: + return "" + + +def _last_completed(job: str) -> str: + item = _table.get_item( + Key={"pk": f"job#{job}", "sk": "marker"} + ).get("Item") or {} + return item.get("lastCompletedScheduledTime") or "" + + +def _replay(job: str, scheduled_time: str) -> str: + """Invoke the dispatcher for one window. Returns its reported status.""" + response = _lambda.invoke( + FunctionName=DISPATCHER, + InvocationType="RequestResponse", + Payload=json.dumps({ + "job": job, + "scheduledTime": scheduled_time, + "executionId": f"catchup-{scheduled_time}", + "attempt": 1, + "scheduleArn": "catch-up", + }).encode(), + ) + payload = json.loads(response["Payload"].read() or b"{}") + if response.get("FunctionError"): + logger.error("replay of %s %s failed: %s", job, scheduled_time, payload) + return "FAILED" + return payload.get("status", "UNKNOWN") + + +def lambda_handler(event, context): + event = event or {} + dry_run = bool(event.get("dryRun")) + lookback_hours = int(event.get("lookbackHours") or DEFAULT_LOOKBACK_HOURS) + only_jobs = set(event.get("jobs") or []) + + now_utc = dt.datetime.now(dt.timezone.utc) + report = [] + + for schedule in _list_group_schedules(): + name = schedule["Name"] + detail = _scheduler.get_schedule(Name=name, GroupName=GROUP_NAME) + + job = _job_name_from_target(detail) + if not job or (only_jobs and job not in only_jobs): + continue + + expression = detail.get("ScheduleExpression", "") + zone_name = detail.get("ScheduleExpressionTimezone") or DEFAULT_TIMEZONE + try: + zone = ZoneInfo(zone_name) + except Exception: # noqa: BLE001 + logger.warning("schedule %s has unknown time zone %s", name, zone_name) + zone = ZoneInfo("UTC") + + # Windows are evaluated in the schedule's own time zone, the same way + # EventBridge Scheduler evaluates the expression. + marker = _last_completed(job) + if marker: + start_utc = dt.datetime.strptime( + marker, SCHEDULED_TIME_FORMAT + ).replace(tzinfo=dt.timezone.utc) + else: + start_utc = now_utc - dt.timedelta(hours=lookback_hours) + logger.info( + "no marker for %s; looking back %sh", job, lookback_hours + ) + + try: + missed = cron_match.occurrences( + expression, + start_utc.astimezone(zone), + now_utc.astimezone(zone), + limit=MAX_REPLAYS_PER_JOB, + ) + except cron_match.UnsupportedExpression as error: + logger.warning("skipping %s: %s", name, error) + report.append({"job": job, "skipped": str(error)}) + continue + + windows = [ + window.astimezone(dt.timezone.utc).strftime(SCHEDULED_TIME_FORMAT) + for window in missed + ] + + if dry_run: + report.append({"job": job, "wouldReplay": windows}) + continue + + statuses = {} + for window in windows: + statuses[window] = _replay(job, window) + + if windows: + logger.info("replayed %s windows for %s", len(windows), job) + report.append({ + "job": job, + "timezone": zone_name, + "expression": expression, + "replayed": statuses, + }) + + return { + "ranAt": now_utc.strftime(SCHEDULED_TIME_FORMAT), + "dryRun": dry_run, + "jobs": report, + } diff --git a/eventbridge-scheduler-cron-migration/python/sam/src/catchup/cron_match.py b/eventbridge-scheduler-cron-migration/python/sam/src/catchup/cron_match.py new file mode 100644 index 0000000000..a3606c5d18 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/src/catchup/cron_match.py @@ -0,0 +1,137 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Decide whether a six-field EventBridge Scheduler cron expression fires at a +given minute, and list the minutes it fired between two instants. + +This exists so the catch-up function can answer "which windows did this job +miss?" without a third-party cron library. It walks candidate minutes and tests +each one, which is fast enough for the lookback a deployment gap needs and keeps +the pattern's dependencies to what the Lambda runtime already ships. + +Day-of-week follows EventBridge Scheduler, not cron: 1 is Sunday and 7 is +Saturday. The L, W and # wildcards are not supported here; a schedule using one +is reported rather than guessed at. +""" + +import datetime as dt +import re + +DAY_NAMES = {name: index + 1 for index, name in enumerate( + ("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"))} +MONTH_NAMES = {name: index + 1 for index, name in enumerate( + ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", + "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"))} + +CRON_RE = re.compile(r"^cron\((.+)\)$", re.IGNORECASE) + +# Wildcards this matcher deliberately does not implement. +UNSUPPORTED_RE = re.compile(r"[LW#]", re.IGNORECASE) + + +class UnsupportedExpression(ValueError): + """The expression uses syntax this matcher will not guess at.""" + + +def _to_number(token: str, names: dict) -> int: + token = token.strip().upper() + if token in names: + return names[token] + if not token.lstrip("-").isdigit(): + raise UnsupportedExpression(f"cannot read {token!r} as a number") + return int(token) + + +def _field_matches(field: str, value: int, bounds: tuple, names: dict) -> bool: + """True if `value` satisfies one cron field.""" + field = field.strip() + if field in ("*", "?"): + return True + + low_bound, high_bound = bounds + for token in field.split(","): + base, separator, step_text = token.partition("/") + step = int(step_text) if separator and step_text else 1 + base = base.strip() + + if base in ("*", "?", ""): + low, high = low_bound, high_bound + elif "-" in base.lstrip("-"): + start_text, _, end_text = base.partition("-") + low = _to_number(start_text, names) + high = _to_number(end_text, names) + else: + low = high = _to_number(base, names) + + if not low <= value <= high: + continue + if step == 1 or (value - low) % step == 0: + return True + + return False + + +def _scheduler_day_of_week(moment: dt.datetime) -> int: + """Convert a datetime to Scheduler's day-of-week, where Sunday is 1.""" + # isoweekday(): Monday 1 .. Sunday 7. Scheduler: Sunday 1 .. Saturday 7. + return (moment.isoweekday() % 7) + 1 + + +def parse(expression: str) -> list: + """Split `cron(...)` into its six fields.""" + match = CRON_RE.match(expression.strip()) + if not match: + raise UnsupportedExpression( + f"{expression!r} is not a cron(...) expression; rate() and at() " + "schedules have no fixed windows to replay" + ) + if UNSUPPORTED_RE.search(match.group(1)): + raise UnsupportedExpression( + f"{expression!r} uses an L, W or # wildcard, which this matcher " + "does not evaluate. Replay this job's windows by hand." + ) + fields = match.group(1).split() + if len(fields) != 6: + raise UnsupportedExpression( + f"expected 6 fields in {expression!r}, found {len(fields)}" + ) + return fields + + +def matches(expression: str, moment: dt.datetime) -> bool: + """True if a schedule with this expression fires at `moment`. + + `moment` is interpreted in whatever time zone it carries, so pass a + datetime already localised to the schedule's ScheduleExpressionTimezone. + """ + minutes, hours, day_of_month, month, day_of_week, year = parse(expression) + + return ( + _field_matches(minutes, moment.minute, (0, 59), {}) + and _field_matches(hours, moment.hour, (0, 23), {}) + and _field_matches(day_of_month, moment.day, (1, 31), {}) + and _field_matches(month, moment.month, (1, 12), MONTH_NAMES) + and _field_matches( + day_of_week, _scheduler_day_of_week(moment), (1, 7), DAY_NAMES) + and _field_matches(year, moment.year, (1970, 2199), {}) + ) + + +def occurrences(expression: str, start: dt.datetime, end: dt.datetime, + limit: int = 500) -> list: + """Every minute in (start, end] at which the schedule fires. + + `start` is exclusive so the last completed window is not replayed, and `end` + is inclusive. Both must be timezone-aware and in the schedule's time zone. + Stops at `limit` to bound a long gap. + """ + if start.tzinfo is None or end.tzinfo is None: + raise ValueError("start and end must be timezone-aware") + + # Round up to the next whole minute after `start`. + cursor = (start + dt.timedelta(minutes=1)).replace(second=0, microsecond=0) + found = [] + while cursor <= end and len(found) < limit: + if matches(expression, cursor): + found.append(cursor) + cursor += dt.timedelta(minutes=1) + return found diff --git a/eventbridge-scheduler-cron-migration/python/sam/src/catchup/requirements.txt b/eventbridge-scheduler-cron-migration/python/sam/src/catchup/requirements.txt new file mode 100644 index 0000000000..7cff171140 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/src/catchup/requirements.txt @@ -0,0 +1,3 @@ +# boto3 and botocore ship with the Lambda Python runtime, so this pattern adds +# no dependencies. Pin boto3 here only if you need a newer version than the +# runtime provides. diff --git a/eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/app.py b/eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/app.py new file mode 100644 index 0000000000..08f9b50698 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/app.py @@ -0,0 +1,242 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Run one scheduled job and record the attempt. + +Every imported schedule targets this one function and names its job in the +payload, so the number of schedules matches the number of crontab lines without +one Lambda function per line. + +The payload is built by tools/import_crontab.py and looks like this, with the +angle-bracket keywords replaced by EventBridge Scheduler at invocation time: + + { + "job": "nightly-report", + "scheduledTime": "", + "executionId": "", + "attempt": "", + "scheduleArn": "" + } + +`scheduledTime` is the window the run belongs to, not the moment the function +started. Keying run history on it is what makes a retry, and a catch-up replay, +address the same record instead of creating a second one. +""" + +import datetime as dt +import json +import logging +import os +import time + +import boto3 +from botocore.exceptions import ClientError + +logger = logging.getLogger() +logger.setLevel(os.environ.get("LOG_LEVEL", "INFO")) + +TABLE_NAME = os.environ["RUN_HISTORY_TABLE"] +METRIC_NAMESPACE = os.environ["METRIC_NAMESPACE"] +RETENTION_DAYS = int(os.environ.get("RUN_HISTORY_RETENTION_DAYS", "90")) + +_dynamodb = boto3.resource("dynamodb") +_table = _dynamodb.Table(TABLE_NAME) +_cloudwatch = boto3.client("cloudwatch") + +STATUS_RUNNING = "RUNNING" +STATUS_COMPLETED = "COMPLETED" +STATUS_FAILED = "FAILED" + +MARKER_SK = "marker" + + +class AlreadyCompleted(Exception): + """This job already completed this window, so there is nothing to do.""" + + +# --------------------------------------------------------------------------- +# The jobs themselves. +# +# Two stand-ins for whatever the crontab used to call. Replace the bodies with +# real work, or have them invoke another function; the surrounding bookkeeping +# does not change. +# --------------------------------------------------------------------------- +def nightly_report(event: dict) -> dict: + logger.info("building nightly report for window %s", event["scheduledTime"]) + return {"rows": 42} + + +def hourly_sync(event: dict) -> dict: + logger.info("syncing for window %s", event["scheduledTime"]) + return {"synced": 7} + + +JOBS = { + "nightly-report": nightly_report, + "hourly-sync": hourly_sync, +} + + +def _expires_at() -> int: + return int(time.time()) + RETENTION_DAYS * 86400 + + +def _claim_window(job: str, scheduled_time: str, execution_id: str, + attempt: int, schedule_arn: str) -> None: + """Write the RUNNING record, refusing to re-run a completed window. + + The condition is the idempotency guarantee the catch-up function relies on: + replaying a window that already finished is a no-op rather than a second run. + A window left RUNNING by a timed-out invocation is allowed through, so a + genuine retry still works. + """ + now = dt.datetime.now(dt.timezone.utc).isoformat() + try: + _table.put_item( + Item={ + "pk": f"job#{job}", + "sk": f"run#{scheduled_time}", + "job": job, + "scheduledTime": scheduled_time, + "status": STATUS_RUNNING, + "startedAt": now, + "executionId": execution_id, + "attempt": attempt, + "scheduleArn": schedule_arn, + "expiresAt": _expires_at(), + }, + ConditionExpression="attribute_not_exists(sk) OR #s <> :completed", + ExpressionAttributeNames={"#s": "status"}, + ExpressionAttributeValues={":completed": STATUS_COMPLETED}, + ) + except ClientError as error: + if error.response["Error"]["Code"] == "ConditionalCheckFailedException": + raise AlreadyCompleted( + f"{job} already completed window {scheduled_time}" + ) from error + raise + + +def _record_completion(job: str, scheduled_time: str, result: dict, + duration_ms: int) -> None: + now = dt.datetime.now(dt.timezone.utc).isoformat() + _table.update_item( + Key={"pk": f"job#{job}", "sk": f"run#{scheduled_time}"}, + UpdateExpression=( + "SET #s = :status, completedAt = :now, durationMs = :ms, " + "#r = :result" + ), + ExpressionAttributeNames={"#s": "status", "#r": "result"}, + ExpressionAttributeValues={ + ":status": STATUS_COMPLETED, + ":now": now, + ":ms": duration_ms, + ":result": json.dumps(result)[:1024], + }, + ) + + # The marker is what catch-up reads to work out which windows it missed. + # Only move it forward, so replaying an older window cannot rewind it. A + # failed condition means the marker is already newer, which is the expected + # outcome of a catch-up replay and not an error. + try: + _table.update_item( + Key={"pk": f"job#{job}", "sk": MARKER_SK}, + UpdateExpression=( + "SET lastCompletedScheduledTime = :t, lastCompletedAt = :now, " + "#j = :job" + ), + ConditionExpression=( + "attribute_not_exists(lastCompletedScheduledTime) " + "OR lastCompletedScheduledTime < :t" + ), + ExpressionAttributeNames={"#j": "job"}, + ExpressionAttributeValues={ + ":t": scheduled_time, ":now": now, ":job": job, + }, + ) + except ClientError as error: + if error.response["Error"]["Code"] != "ConditionalCheckFailedException": + raise + logger.info( + "marker for %s already past %s; leaving it alone", job, scheduled_time + ) + + +def _record_failure(job: str, scheduled_time: str, message: str) -> None: + _table.update_item( + Key={"pk": f"job#{job}", "sk": f"run#{scheduled_time}"}, + UpdateExpression="SET #s = :status, failedAt = :now, #e = :error", + ExpressionAttributeNames={"#s": "status", "#e": "error"}, + ExpressionAttributeValues={ + ":status": STATUS_FAILED, + ":now": dt.datetime.now(dt.timezone.utc).isoformat(), + ":error": message[:1024], + }, + ) + + +def _emit_completion_metric(job: str) -> None: + """Publish the business-completion marker the alarm watches for. + + The alarm treats missing data as breaching, so this metric only ever needs + to say "it finished". Silence is the alarm condition. + """ + _cloudwatch.put_metric_data( + Namespace=METRIC_NAMESPACE, + MetricData=[{ + "MetricName": "JobCompleted", + "Dimensions": [{"Name": "JobName", "Value": job}], + "Value": 1, + "Unit": "Count", + }], + ) + + +def lambda_handler(event, context): + job = event.get("job") + if job not in JOBS: + # Not retryable: a bad job name will still be bad on the next attempt. + raise ValueError( + f"unknown job {job!r}; known jobs are {sorted(JOBS)}" + ) + + scheduled_time = event.get("scheduledTime") + if not scheduled_time or scheduled_time.startswith("', which EventBridge " + "Scheduler substitutes at invocation time." + ) + + execution_id = event.get("executionId", "manual") + attempt = int(event.get("attempt") or 1) + schedule_arn = event.get("scheduleArn", "") + + try: + _claim_window(job, scheduled_time, execution_id, attempt, schedule_arn) + except AlreadyCompleted as skip: + logger.info("%s", skip) + return {"job": job, "scheduledTime": scheduled_time, "status": "SKIPPED"} + + started = time.monotonic() + try: + result = JOBS[job](event) + except Exception as error: # noqa: BLE001 + logger.exception("job %s failed for window %s", job, scheduled_time) + _record_failure(job, scheduled_time, str(error)) + # Re-raised so Scheduler's retry policy applies and the DLQ sees it. + raise + + duration_ms = int((time.monotonic() - started) * 1000) + _record_completion(job, scheduled_time, result, duration_ms) + _emit_completion_metric(job) + + logger.info( + "job %s completed window %s in %sms", job, scheduled_time, duration_ms + ) + return { + "job": job, + "scheduledTime": scheduled_time, + "status": STATUS_COMPLETED, + "durationMs": duration_ms, + } diff --git a/eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/requirements.txt b/eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/requirements.txt new file mode 100644 index 0000000000..7cff171140 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/src/dispatcher/requirements.txt @@ -0,0 +1,3 @@ +# boto3 and botocore ship with the Lambda Python runtime, so this pattern adds +# no dependencies. Pin boto3 here only if you need a newer version than the +# runtime provides. diff --git a/eventbridge-scheduler-cron-migration/python/sam/template.yaml b/eventbridge-scheduler-cron-migration/python/sam/template.yaml new file mode 100644 index 0000000000..3a022f17a2 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/template.yaml @@ -0,0 +1,283 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + Replace cron on a VM with Amazon EventBridge Scheduler. Imports a crontab into one + schedule per job, records every run in Amazon DynamoDB, alarms when a job does not + report completion, and replays windows missed during a deployment. + +Parameters: + ScheduleTimezone: + Type: String + Default: UTC + Description: > + IANA time zone the cron expressions are evaluated in, e.g. America/New_York. + A crontab inherits the host time zone; a schedule has to say it out loud. + + MonitoredJobName: + Type: String + Default: nightly-report + Description: > + The job the completion alarm watches. One alarm is wired up as an example; + add one per job that has a business deadline. + + MonitoredJobDeadlineSeconds: + Type: Number + Default: 86400 + MinValue: 60 + MaxValue: 86400 + Description: > + How long after a run is due to wait for its completion marker before alarming, + in seconds. Must be a multiple of 60, which is what CloudWatch accepts for an + alarm period above one minute. Default is 86400, one day, matching the daily + example job. + + RunHistoryRetentionDays: + Type: Number + Default: 90 + Description: Days to keep run-history items before DynamoDB TTL removes them. + +Globals: + Function: + Runtime: python3.13 + MemorySize: 256 + Timeout: 60 + Tracing: Active + Environment: + Variables: + RUN_HISTORY_TABLE: !Ref RunHistoryTable + METRIC_NAMESPACE: !Sub '${AWS::StackName}/CronMigration' + RUN_HISTORY_RETENTION_DAYS: !Ref RunHistoryRetentionDays + +Resources: + # --------------------------------------------------------------------------- + # Execution record + # + # One item per job per scheduled window, written when a run starts and updated + # when it completes. The scheduled time comes from the schedule itself + # (), not from the clock inside the function, so + # a retry of a given window addresses the same item and the catch-up function + # can tell a missed window from a completed one. + # --------------------------------------------------------------------------- + RunHistoryTable: + Type: AWS::DynamoDB::Table + Properties: + BillingMode: PAY_PER_REQUEST + AttributeDefinitions: + - AttributeName: pk # job# + AttributeType: S + - AttributeName: sk # run# | marker + AttributeType: S + KeySchema: + - AttributeName: pk + KeyType: HASH + - AttributeName: sk + KeyType: RANGE + TimeToLiveSpecification: + AttributeName: expiresAt + Enabled: true + SSESpecification: + SSEEnabled: true + PointInTimeRecoverySpecification: + PointInTimeRecoveryEnabled: true + + # --------------------------------------------------------------------------- + # Dead-letter queue for invocations EventBridge Scheduler could not deliver. + # This catches failures before the function runs, which a crontab has no + # equivalent for: cron writes to mail or /dev/null and moves on. + # --------------------------------------------------------------------------- + ScheduleDeadLetterQueue: + Type: AWS::SQS::Queue + Properties: + MessageRetentionPeriod: 1209600 # 14 days + SqsManagedSseEnabled: true + + # --------------------------------------------------------------------------- + # Schedule group: one namespace for every schedule this stack owns, so the + # imported jobs are listable, and removable, as a unit. + # --------------------------------------------------------------------------- + JobScheduleGroup: + Type: AWS::Scheduler::ScheduleGroup + Properties: + Name: !Sub '${AWS::StackName}-jobs' + + # --------------------------------------------------------------------------- + # The dispatcher. One schedule per job, all pointing here; the handler routes + # on the job name in the payload. This keeps the schedule count equal to the + # crontab line count without one Lambda function per line. + # --------------------------------------------------------------------------- + DispatcherFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: src/dispatcher/ + Handler: app.lambda_handler + Description: Runs a scheduled job and records the attempt in run history. + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref RunHistoryTable + - Statement: + # PutMetricData has no resource-level permission, so it is scoped by + # namespace condition instead of Resource. + - Effect: Allow + Action: cloudwatch:PutMetricData + Resource: '*' + Condition: + StringEquals: + cloudwatch:namespace: !Sub '${AWS::StackName}/CronMigration' + + DispatcherLogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub '/aws/lambda/${DispatcherFunction}' + RetentionInDays: 14 + + # --------------------------------------------------------------------------- + # Catch-up. Reads the last-run marker for each job and re-runs the windows that + # elapsed while no schedule existed, for example during a deployment or while a + # schedule was disabled for a rollback. Invoked by a one-time schedule created + # by tools/import_crontab.py --schedule-catchup. + # + # The one-time schedule is created through the API rather than declared here on + # purpose: AWS::Scheduler::Schedule has no ActionAfterCompletion property, and a + # completed one-time schedule keeps counting against the account's schedule quota + # until it is deleted. The API accepts ActionAfterCompletion=DELETE, so the + # schedule removes itself once it has fired. + # --------------------------------------------------------------------------- + CatchUpFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: src/catchup/ + Handler: app.lambda_handler + Timeout: 300 + Description: Replays scheduled windows that were missed while no schedule ran. + Environment: + Variables: + DISPATCHER_FUNCTION_NAME: !Ref DispatcherFunction + SCHEDULE_GROUP_NAME: !Ref JobScheduleGroup + SCHEDULE_TIMEZONE: !Ref ScheduleTimezone + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref RunHistoryTable + - LambdaInvokePolicy: + FunctionName: !Ref DispatcherFunction + - Statement: + # GetSchedule is authorised against the individual schedule, so it + # is scoped to this stack's group. + - Effect: Allow + Action: scheduler:GetSchedule + Resource: + - !Sub 'arn:${AWS::Partition}:scheduler:${AWS::Region}:${AWS::AccountId}:schedule/${JobScheduleGroup}/*' + # ListSchedules is a list operation: it is authorised against + # schedule/*/* even when the call filters by GroupName, so it cannot + # be scoped to one group. Narrowed to this account and Region. + - Effect: Allow + Action: scheduler:ListSchedules + Resource: + - !Sub 'arn:${AWS::Partition}:scheduler:${AWS::Region}:${AWS::AccountId}:schedule/*/*' + + CatchUpLogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub '/aws/lambda/${CatchUpFunction}' + RetentionInDays: 14 + + # --------------------------------------------------------------------------- + # The role EventBridge Scheduler assumes to invoke the dispatcher. Scoped to + # this account and this schedule group so another account cannot borrow it, + # and so it cannot invoke anything but the dispatcher. + # + # aws:SourceArn must name the schedule *group*, not a schedule or a schedule + # name prefix. Scoping it to `schedule//*` makes CreateSchedule fail + # with "The execution role you provide must allow AWS EventBridge Scheduler to + # assume the role", because the role is validated against the group. + # See Confused deputy prevention in the EventBridge Scheduler User Guide. + # --------------------------------------------------------------------------- + SchedulerInvokeRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: scheduler.amazonaws.com + Action: sts:AssumeRole + Condition: + StringEquals: + aws:SourceAccount: !Ref AWS::AccountId + aws:SourceArn: !Sub 'arn:${AWS::Partition}:scheduler:${AWS::Region}:${AWS::AccountId}:schedule-group/${JobScheduleGroup}' + Policies: + - PolicyName: InvokeDispatcherAndCatchUp + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: lambda:InvokeFunction + Resource: + - !GetAtt DispatcherFunction.Arn + - !GetAtt CatchUpFunction.Arn + - Effect: Allow + Action: sqs:SendMessage + Resource: !GetAtt ScheduleDeadLetterQueue.Arn + + # --------------------------------------------------------------------------- + # Business-completion alarm. + # + # The alarm watches for the absence of a completion, which is the failure a + # crontab hides: the job did not run, so it wrote no output and sent no mail, + # so nothing fired. TreatMissingData: breaching is what makes "no data" an + # alarm rather than a gap, so a job that never started still pages someone. + # --------------------------------------------------------------------------- + JobCompletionAlarm: + Type: AWS::CloudWatch::Alarm + Properties: + AlarmName: !Sub '${AWS::StackName}-${MonitoredJobName}-no-completion' + AlarmDescription: !Sub > + ${MonitoredJobName} did not record a completion within + ${MonitoredJobDeadlineSeconds} seconds of its scheduled window. + Namespace: !Sub '${AWS::StackName}/CronMigration' + MetricName: JobCompleted + Dimensions: + - Name: JobName + Value: !Ref MonitoredJobName + Statistic: Sum + Period: !Ref MonitoredJobDeadlineSeconds + EvaluationPeriods: 1 + Threshold: 1 + ComparisonOperator: LessThanThreshold + TreatMissingData: breaching + +Outputs: + DispatcherFunctionArn: + Description: Target ARN for every imported schedule. + Value: !GetAtt DispatcherFunction.Arn + + CatchUpFunctionArn: + Description: Target ARN for the one-time catch-up schedule. + Value: !GetAtt CatchUpFunction.Arn + + SchedulerInvokeRoleArn: + Description: Role EventBridge Scheduler assumes to invoke the dispatcher. + Value: !GetAtt SchedulerInvokeRole.Arn + + ScheduleGroupName: + Description: Schedule group that holds the imported jobs. + Value: !Ref JobScheduleGroup + + ScheduleDeadLetterQueueArn: + Description: Dead-letter queue for undeliverable invocations. + Value: !GetAtt ScheduleDeadLetterQueue.Arn + + RunHistoryTableName: + Description: DynamoDB table holding the execution record. + Value: !Ref RunHistoryTable + + ImportCommand: + Description: Copy-paste command to import the example crontab. + Value: !Sub >- + python3 tools/import_crontab.py --crontab tools/examples/crontab + --dispatcher-arn ${DispatcherFunction.Arn} + --role-arn ${SchedulerInvokeRole.Arn} + --group ${JobScheduleGroup} + --dlq-arn ${ScheduleDeadLetterQueue.Arn} + --timezone ${ScheduleTimezone} + --region ${AWS::Region} diff --git a/eventbridge-scheduler-cron-migration/python/sam/tools/cron_to_scheduler.py b/eventbridge-scheduler-cron-migration/python/sam/tools/cron_to_scheduler.py new file mode 100644 index 0000000000..c0b6fdf416 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/tools/cron_to_scheduler.py @@ -0,0 +1,188 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Convert a 5-field crontab expression into an EventBridge Scheduler cron expression. + +A crontab line and an EventBridge Scheduler cron expression look alike, which is +exactly why a copy-and-paste migration goes wrong. The four differences that +matter, all from the EventBridge Scheduler User Guide "Schedule types" page: + +1. Field count. crontab has five fields; Scheduler has six and the extra one is + `year`: cron(minutes hours day-of-month month day-of-week year) + +2. Day-of-week numbering. crontab uses 0-6 for Sunday-Saturday and also accepts + 7 for Sunday. Scheduler uses 1-7 for SUN-SAT, so every numeric day-of-week + shifts by one. Copying `0 0 * * 1` across unchanged moves a Monday job to + Sunday. Three-letter names (MON, FRI) mean the same thing in both and are + passed through untouched. + +3. `*` cannot appear in both day-of-month and day-of-week. The guide: "You can't + use * in both the Day-of-month and Day-of-week fields. If you use it in one, + you must use ? in the other." Plain `* * * * *` is therefore not a valid + Scheduler expression. + +4. When a crontab restricts both day-of-month and day-of-week, the two are ORed + ("1 * 1" means the 1st of the month OR every Monday). Scheduler has no way to + express that, so this module refuses the line instead of silently shipping a + schedule that fires on the wrong days. + +`@reboot` has no Scheduler equivalent and is refused for the same reason. +""" + +# crontab shorthand, expanded to the equivalent 5-field line before conversion. +# `@reboot` is deliberately absent: see UnsupportedCronError below. +MACROS = { + "@yearly": "0 0 1 1 *", + "@annually": "0 0 1 1 *", + "@monthly": "0 0 1 * *", + "@weekly": "0 0 * * 0", + "@daily": "0 0 * * *", + "@midnight": "0 0 * * *", + "@hourly": "0 * * * *", +} + +DAY_NAMES = ("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT") +MONTH_NAMES = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", + "JUL", "AUG", "SEP", "OCT", "NOV", "DEC") + + +class UnsupportedCronError(ValueError): + """A crontab line that EventBridge Scheduler cannot express faithfully. + + Raised rather than returning an approximation: a schedule that fires on the + wrong days is worse than a migration that stops and tells you why. + """ + + +def _shift_day_of_week(value: int) -> int: + """Map a crontab day-of-week number onto Scheduler's 1-7 (SUN-SAT). + + crontab: 0=Sun .. 6=Sat, and 7 is also Sun. + Scheduler: 1=Sun .. 7=Sat. + The modulo collapses crontab's duplicate Sunday (0 and 7) onto 1. + """ + if not 0 <= value <= 7: + raise UnsupportedCronError( + f"day-of-week {value} is out of range; crontab allows 0-7" + ) + return (value % 7) + 1 + + +def _convert_day_of_week_token(token: str) -> str: + """Convert one day-of-week token, preserving ranges, steps and names.""" + # Steps: "*/2", "1/2". Scheduler counts from SUN just as crontab counts from + # day 0, so a `*` base needs no shift; an explicit base does. + if "/" in token: + base, _, step = token.partition("/") + return f"{_convert_day_of_week_token(base) if base != '*' else '*'}/{step}" + + # Ranges: "1-5" -> "2-6". Names ("MON-FRI") pass through. + if "-" in token and not token.startswith("-"): + start, _, end = token.partition("-") + return f"{_convert_day_of_week_token(start)}-{_convert_day_of_week_token(end)}" + + if token == "*": + return "*" + + # Names already agree between crontab and Scheduler. `L` and `#` are + # Scheduler-only and are passed through for hand-written schedule.json input. + if not token.lstrip("-").isdigit(): + return token.upper() if token.upper() in DAY_NAMES else token + + return str(_shift_day_of_week(int(token))) + + +def _convert_day_of_week(field: str) -> str: + return ",".join(_convert_day_of_week_token(t) for t in field.split(",")) + + +def _check_numeric_range(field: str, low: int, high: int, name: str, + names: tuple = ()) -> None: + """Reject out-of-range literals so a bad line fails here, not in the API call.""" + for token in field.split(","): + # Strip a step suffix, then check each end of any range. + base = token.partition("/")[0] + if base in ("*", "?", ""): + continue + for part in base.split("-"): + part = part.strip().upper() + if not part or part in names: + continue + # Scheduler-only wildcards in day-of-month (L, W, 3W). + if name == "day-of-month" and part.rstrip("W") in ("L", ""): + continue + if name == "day-of-month" and part.endswith("W"): + part = part[:-1] + if not part.isdigit(): + raise UnsupportedCronError( + f"{name} field {field!r} contains {part!r}, which is not a number" + ) + if not low <= int(part) <= high: + raise UnsupportedCronError( + f"{name} value {part} is out of range ({low}-{high})" + ) + + +def to_scheduler_expression(crontab_line: str) -> str: + """Return the `cron(...)` expression equivalent to a crontab line. + + >>> to_scheduler_expression("30 8 * * *") + 'cron(30 8 * * ? *)' + >>> to_scheduler_expression("0 0 * * 1") # Monday stays Monday + 'cron(0 0 ? * 2 *)' + + Raises UnsupportedCronError when Scheduler cannot express the line. + """ + line = crontab_line.strip() + if not line: + raise UnsupportedCronError("empty schedule expression") + + if line.startswith("@"): + macro = line.lower() + if macro == "@reboot": + raise UnsupportedCronError( + "@reboot has no EventBridge Scheduler equivalent: there is no " + "instance to boot. Trigger this work from the deployment itself, " + "or from the catch-up function if it must run once after a deploy." + ) + if macro not in MACROS: + raise UnsupportedCronError(f"unknown crontab macro {line!r}") + line = MACROS[macro] + + fields = line.split() + if len(fields) != 5: + raise UnsupportedCronError( + f"expected 5 crontab fields, got {len(fields)}: {crontab_line!r}. " + "Strip any user column or command before converting." + ) + + minutes, hours, day_of_month, month, day_of_week = fields + + _check_numeric_range(minutes, 0, 59, "minute") + _check_numeric_range(hours, 0, 23, "hour") + _check_numeric_range(day_of_month, 1, 31, "day-of-month") + _check_numeric_range(month, 1, 12, "month", MONTH_NAMES) + _check_numeric_range(day_of_week, 0, 7, "day-of-week", DAY_NAMES) + + dom_is_wildcard = day_of_month == "*" + dow_is_wildcard = day_of_week == "*" + + # Scheduler needs `?` in exactly one of the two day fields. + if dow_is_wildcard: + # Covers "* * * * *" and any day-of-month schedule: "0 0 1 * *". + day_of_week_out = "?" + day_of_month_out = day_of_month + elif dom_is_wildcard: + # A weekday schedule: "0 0 * * 1-5". + day_of_month_out = "?" + day_of_week_out = _convert_day_of_week(day_of_week) + else: + raise UnsupportedCronError( + f"crontab line {crontab_line!r} restricts both day-of-month " + f"({day_of_month}) and day-of-week ({day_of_week}). cron treats these " + "as OR (either may match); EventBridge Scheduler cannot express that. " + "Split it into two schedules, one per day field." + ) + + return ( + f"cron({minutes} {hours} {day_of_month_out} {month} {day_of_week_out} *)" + ) diff --git a/eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab b/eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab new file mode 100644 index 0000000000..1f995fd152 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab @@ -0,0 +1,16 @@ +# An ordinary crontab, the kind that accumulates on a VM over a few years. +# +# The "# job:" comment names the schedule that the next line becomes. Without it +# the importer derives a name from the command, which works but reads less well. +# +# MAILTO is how a crontab reports failure: it emails whoever still reads that +# mailbox. There is no schedule equivalent, so the importer skips the line. The +# stack replaces it with a run-history record and a completion alarm. +MAILTO="ops@example.com" +PATH=/usr/local/bin:/usr/bin:/bin + +# job: nightly-report +0 2 * * * /usr/local/bin/nightly-report.sh --full + +# job: hourly-sync +0 * * * * /usr/local/bin/sync-inventory.sh diff --git a/eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab-unsupported b/eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab-unsupported new file mode 100644 index 0000000000..307f49b212 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/tools/examples/crontab-unsupported @@ -0,0 +1,23 @@ +# Crontab lines that EventBridge Scheduler cannot express faithfully. +# +# Run the importer against this file to see each one refused with the reason. +# The importer prints them and exits non-zero rather than creating a schedule +# that fires on the wrong days: +# +# python3 tools/import_crontab.py --crontab tools/examples/crontab-unsupported \ +# --dispatcher-arn X --role-arn Y --group Z --dry-run + +# No instance boots, so there is no boot to run at. Move this work into the +# deployment, or into the catch-up function if it must run once afterwards. +# job: warm-cache +@reboot /usr/local/bin/warm-cache.sh + +# cron ORs the two day fields: this means "the 1st of the month OR any Monday". +# A cron expression cannot say that, because one of the two day fields has to be +# "?". Split it into two schedules. +# job: month-start-or-monday +0 3 1 * 1 /usr/local/bin/partial-reindex.sh + +# Out of range: minute 60 does not exist. +# job: typo-minute +60 1 * * * /usr/local/bin/typo.sh diff --git a/eventbridge-scheduler-cron-migration/python/sam/tools/examples/schedule.json b/eventbridge-scheduler-cron-migration/python/sam/tools/examples/schedule.json new file mode 100644 index 0000000000..bccb97dcf3 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/tools/examples/schedule.json @@ -0,0 +1,15 @@ +{ + "timezone": "America/New_York", + "jobs": [ + { + "name": "nightly-report", + "cron": "0 2 * * *", + "command": "/usr/local/bin/nightly-report.sh --full" + }, + { + "name": "hourly-sync", + "cron": "0 * * * *", + "command": "/usr/local/bin/sync-inventory.sh" + } + ] +} diff --git a/eventbridge-scheduler-cron-migration/python/sam/tools/import_crontab.py b/eventbridge-scheduler-cron-migration/python/sam/tools/import_crontab.py new file mode 100644 index 0000000000..848b1b80f1 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/tools/import_crontab.py @@ -0,0 +1,345 @@ +#!/usr/bin/env python3 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Create one EventBridge Scheduler schedule per crontab line. + +Reads a crontab (or an equivalent schedule.json), converts each entry to a +Scheduler cron expression, and creates a schedule that targets the dispatcher +Lambda function, with an explicit time zone, a retry policy and a dead-letter +queue. + +Run it with --dry-run first. It prints what it would create, including any line +it refuses, and touches nothing. + + python3 tools/import_crontab.py --crontab tools/examples/crontab \\ + --dispatcher-arn \\ + --role-arn \\ + --group \\ + --dlq-arn \\ + --timezone America/New_York \\ + --dry-run + +Migrating one job at a time: pass --only to import a single job, or --disabled +to create every schedule in the DISABLED state and enable them individually once +you have compared a run against the old crontab. +""" + +import argparse +import datetime as dt +import json +import re +import sys + +from cron_to_scheduler import UnsupportedCronError, to_scheduler_expression + +# boto3 is imported inside the functions that call AWS, so --dry-run works on a +# machine with nothing installed. Converting and checking a crontab is the part +# you want to run first, and it needs no credentials and no dependencies. + +# Schedule names accept [0-9a-zA-Z-_.] and are capped at 64 characters. +NAME_ALLOWED_RE = re.compile(r"[^0-9a-zA-Z._-]+") +NAME_MAX_LENGTH = 64 + +# A crontab environment assignment, e.g. MAILTO="ops@example.com". +ENV_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\s*=") + +# "# job: nightly-report" names the entry on the following line. +JOB_COMMENT_RE = re.compile(r"^#\s*job:\s*(\S+)", re.IGNORECASE) + +# The payload every schedule sends. The angle-bracket keywords are context +# attributes EventBridge Scheduler substitutes at invocation time; they must +# reach the API as literal text. +def _build_input(job: str, command: str) -> str: + return json.dumps({ + "job": job, + "scheduledTime": "", + "executionId": "", + "attempt": "", + "scheduleArn": "", + "command": command, + }) + + +def sanitise_name(raw: str) -> str: + """Turn a job label into a legal schedule name.""" + name = NAME_ALLOWED_RE.sub("-", raw).strip("-._") + return (name or "job")[:NAME_MAX_LENGTH] + + +def _job_name_from_command(command: str) -> str: + """Derive a job name from the command when no `# job:` comment is given.""" + first_word = command.split()[0] if command.split() else "job" + base = first_word.rsplit("/", 1)[-1] + return sanitise_name(base.rsplit(".", 1)[0] or base) + + +def parse_crontab(text: str) -> tuple: + """Return (entries, problems) for a crontab file. + + An entry is {"name", "cron", "command", "line"}. A problem is + {"line", "lineNumber", "reason"} for a line Scheduler cannot express; the + caller decides whether to continue. + """ + entries, problems = [], [] + pending_name = None + + for number, raw_line in enumerate(text.splitlines(), start=1): + line = raw_line.strip() + if not line: + continue + + if line.startswith("#"): + match = JOB_COMMENT_RE.match(line) + if match: + pending_name = match.group(1) + continue + + if ENV_ASSIGNMENT_RE.match(line): + # MAILTO, PATH, SHELL and friends have no schedule equivalent. + continue + + fields = line.split() + if line.startswith("@"): + schedule_text, command = fields[0], " ".join(fields[1:]) + elif len(fields) >= 6: + schedule_text, command = " ".join(fields[:5]), " ".join(fields[5:]) + else: + problems.append({ + "line": line, "lineNumber": number, + "reason": "not enough fields for a schedule and a command", + }) + pending_name = None + continue + + try: + expression = to_scheduler_expression(schedule_text) + except UnsupportedCronError as error: + problems.append({ + "line": line, "lineNumber": number, "reason": str(error), + }) + pending_name = None + continue + + entries.append({ + "name": sanitise_name(pending_name or _job_name_from_command(command)), + "cron": expression, + "command": command, + "line": line, + }) + pending_name = None + + return entries, problems + + +def parse_schedule_json(text: str) -> tuple: + """Read the same entries from a schedule.json file. + + {"timezone": "...", "jobs": [{"name": "...", "cron": "0 2 * * *", + "command": "..."}]} + """ + document = json.loads(text) + entries, problems = [], [] + + for index, job in enumerate(document.get("jobs", []), start=1): + raw = job.get("cron", "") + try: + expression = to_scheduler_expression(raw) + except UnsupportedCronError as error: + problems.append({ + "line": json.dumps(job), "lineNumber": index, + "reason": str(error), + }) + continue + entries.append({ + "name": sanitise_name(job.get("name") or f"job-{index}"), + "cron": expression, + "command": job.get("command", ""), + "line": json.dumps(job), + }) + + return entries, problems, document.get("timezone") + + +def put_schedule(client, entry: dict, args) -> str: + """Create or update one schedule. Returns "created" or "updated".""" + request = { + "Name": entry["name"], + "GroupName": args.group, + "ScheduleExpression": entry["cron"], + "ScheduleExpressionTimezone": args.timezone, + "Description": f"Imported from cron: {entry['line']}"[:512], + "State": "DISABLED" if args.disabled else "ENABLED", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": args.dispatcher_arn, + "RoleArn": args.role_arn, + "Input": _build_input(entry["name"], entry["command"]), + "RetryPolicy": { + "MaximumRetryAttempts": args.retry_attempts, + "MaximumEventAgeInSeconds": args.max_event_age, + }, + }, + } + if args.dlq_arn: + request["Target"]["DeadLetterConfig"] = {"Arn": args.dlq_arn} + + from botocore.exceptions import ClientError + + try: + client.create_schedule(**request) + return "created" + except ClientError as error: + if error.response["Error"]["Code"] != "ConflictException": + raise + # Re-running the import is expected during a migration, so an existing + # schedule is updated in place rather than treated as a failure. + client.update_schedule(**request) + return "updated" + + +def schedule_catchup(client, args) -> str: + """Create a one-time schedule that runs the catch-up function shortly. + + Created through the API, not CloudFormation: AWS::Scheduler::Schedule has no + ActionAfterCompletion property, and a finished one-time schedule keeps + counting against the region's schedule quota until something deletes it. + ActionAfterCompletion=DELETE makes the schedule clean itself up. + """ + run_at = dt.datetime.now(dt.timezone.utc) + dt.timedelta( + minutes=args.catchup_delay_minutes) + name = sanitise_name(f"catchup-{run_at.strftime('%Y%m%dT%H%M%S')}") + + client.create_schedule( + Name=name, + GroupName=args.group, + ScheduleExpression=f"at({run_at.strftime('%Y-%m-%dT%H:%M:%S')})", + ScheduleExpressionTimezone="UTC", + Description="One-time catch-up after a deployment. Deletes itself.", + State="ENABLED", + ActionAfterCompletion="DELETE", + FlexibleTimeWindow={"Mode": "OFF"}, + Target={ + "Arn": args.catchup_arn, + "RoleArn": args.role_arn, + "Input": json.dumps({"lookbackHours": args.catchup_lookback_hours}), + "RetryPolicy": {"MaximumRetryAttempts": 2}, + }, + ) + return name + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Import a crontab into Amazon EventBridge Scheduler.", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--crontab", help="path to a crontab file, or - for stdin") + source.add_argument("--schedule-json", help="path to a schedule.json file") + + parser.add_argument("--dispatcher-arn", required=True, + help="DispatcherFunctionArn stack output") + parser.add_argument("--role-arn", required=True, + help="SchedulerInvokeRoleArn stack output") + parser.add_argument("--group", required=True, + help="ScheduleGroupName stack output") + parser.add_argument("--dlq-arn", help="ScheduleDeadLetterQueueArn stack output") + parser.add_argument("--timezone", default="UTC", + help="IANA time zone the cron fields are read in " + "(default: UTC). A crontab inherits the host " + "time zone; a schedule must state it.") + parser.add_argument("--region", help="AWS Region (default: from profile)") + parser.add_argument("--profile", help="AWS profile") + parser.add_argument("--only", action="append", metavar="JOB", + help="import only this job; repeatable, for migrating " + "one job at a time") + parser.add_argument("--disabled", action="store_true", + help="create schedules DISABLED, to enable one by one") + parser.add_argument("--retry-attempts", type=int, default=3) + parser.add_argument("--max-event-age", type=int, default=3600) + parser.add_argument("--dry-run", action="store_true", + help="print the plan and exit without calling AWS") + + parser.add_argument("--schedule-catchup", action="store_true", + help="also create a one-time schedule that runs the " + "catch-up function (needs --catchup-arn)") + parser.add_argument("--catchup-arn", help="CatchUpFunctionArn stack output") + parser.add_argument("--catchup-delay-minutes", type=int, default=2) + parser.add_argument("--catchup-lookback-hours", type=int, default=24) + return parser + + +def main(argv=None) -> int: + args = build_parser().parse_args(argv) + + if args.schedule_catchup and not args.catchup_arn: + print("error: --schedule-catchup needs --catchup-arn", file=sys.stderr) + return 2 + + if args.crontab: + text = sys.stdin.read() if args.crontab == "-" else open( + args.crontab, encoding="utf-8").read() + entries, problems = parse_crontab(text) + else: + with open(args.schedule_json, encoding="utf-8") as handle: + entries, problems, file_timezone = parse_schedule_json(handle.read()) + # An explicit --timezone wins; otherwise the file may set it. + if file_timezone and args.timezone == "UTC": + args.timezone = file_timezone + + if args.only: + wanted = {sanitise_name(name) for name in args.only} + entries = [entry for entry in entries if entry["name"] in wanted] + + duplicates = { + entry["name"] for entry in entries + if [e["name"] for e in entries].count(entry["name"]) > 1 + } + if duplicates: + print(f"error: duplicate job names {sorted(duplicates)}. Schedule names " + f"must be unique; add a '# job: ' comment to separate them.", + file=sys.stderr) + return 1 + + print(f"Time zone: {args.timezone}") + print(f"{len(entries)} schedule(s) to import" + f"{' (DISABLED)' if args.disabled else ''}:\n") + for entry in entries: + print(f" {entry['name']:<32} {entry['cron']:<26} <- {entry['line']}") + + if problems: + print(f"\n{len(problems)} line(s) refused:\n", file=sys.stderr) + for problem in problems: + print(f" line {problem['lineNumber']}: {problem['line']}", + file=sys.stderr) + print(f" {problem['reason']}\n", file=sys.stderr) + + if args.dry_run: + print("\nDry run: nothing was created.") + return 1 if problems else 0 + + try: + import boto3 + except ImportError: + print("error: creating schedules needs boto3 (pip install boto3). " + "Re-run with --dry-run to check the conversion without it.", + file=sys.stderr) + return 2 + + session = boto3.Session(profile_name=args.profile, region_name=args.region) + client = session.client("scheduler") + + print() + for entry in entries: + action = put_schedule(client, entry, args) + print(f" {action}: {entry['name']}") + + if args.schedule_catchup: + name = schedule_catchup(client, args) + print(f" created one-time catch-up schedule: {name}") + + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/eventbridge-scheduler-cron-migration/python/sam/tools/test_cron_to_scheduler.py b/eventbridge-scheduler-cron-migration/python/sam/tools/test_cron_to_scheduler.py new file mode 100644 index 0000000000..927a9872c8 --- /dev/null +++ b/eventbridge-scheduler-cron-migration/python/sam/tools/test_cron_to_scheduler.py @@ -0,0 +1,135 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Known-answer tests for the crontab to EventBridge Scheduler converter. + +Run from this folder: python3 -m unittest -v test_cron_to_scheduler +""" + +import unittest + +from cron_to_scheduler import UnsupportedCronError, to_scheduler_expression + +# (crontab line, expected Scheduler expression, what it is testing) +CASES = [ + # --- the `*` in both day fields rule ------------------------------------- + ("* * * * *", "cron(* * * * ? *)", "every minute: day-of-week becomes ?"), + ("0 0 * * *", "cron(0 0 * * ? *)", "midnight daily"), + ("30 8 * * *", "cron(30 8 * * ? *)", "08:30 daily"), + + # --- day-of-week shift, the bug this module exists to prevent ------------ + ("0 0 * * 0", "cron(0 0 ? * 1 *)", "crontab Sunday 0 -> Scheduler 1"), + ("0 0 * * 7", "cron(0 0 ? * 1 *)", "crontab also allows 7 for Sunday"), + ("0 0 * * 1", "cron(0 0 ? * 2 *)", "Monday 1 -> 2"), + ("0 0 * * 6", "cron(0 0 ? * 7 *)", "Saturday 6 -> 7"), + ("15 10 * * 5", "cron(15 10 ? * 6 *)", "Friday 5 -> 6"), + ("0 0 * * 1-5", "cron(0 0 ? * 2-6 *)", "weekday range shifts both ends"), + ("0 0 * * 0,6", "cron(0 0 ? * 1,7 *)", "weekend list shifts each item"), + ("0 0 * * MON-FRI", "cron(0 0 ? * MON-FRI *)", "names mean the same in both"), + ("0 0 * * mon", "cron(0 0 ? * MON *)", "lowercase name is upper-cased"), + + # --- day-of-month schedules --------------------------------------------- + ("0 0 1 * *", "cron(0 0 1 * ? *)", "first of the month"), + ("0 0 1,15 * *", "cron(0 0 1,15 * ? *)", "two days of the month"), + ("0 0 1 1 *", "cron(0 0 1 1 ? *)", "1 January"), + ("0 0 * JAN *", "cron(0 0 * JAN ? *)", "month name passes through"), + + # --- steps and lists ---------------------------------------------------- + ("*/15 * * * *", "cron(*/15 * * * ? *)", "every 15 minutes"), + ("0 */4 * * *", "cron(0 */4 * * ? *)", "every 4 hours"), + ("0 9,17 * * *", "cron(0 9,17 * * ? *)", "twice a day"), + # Both count every Nth day starting at Sunday, so a `*` base needs no shift: + # crontab 0,2,4,6 and Scheduler 1,3,5,7 are the same four days. + ("0 0 * * */2", "cron(0 0 ? * */2 *)", "step on a * base is unshifted"), + + # --- macros ------------------------------------------------------------- + ("@hourly", "cron(0 * * * ? *)", "@hourly"), + ("@daily", "cron(0 0 * * ? *)", "@daily"), + ("@midnight", "cron(0 0 * * ? *)", "@midnight is @daily"), + ("@weekly", "cron(0 0 ? * 1 *)", "@weekly is Sunday, shifted to 1"), + ("@monthly", "cron(0 0 1 * ? *)", "@monthly"), + ("@yearly", "cron(0 0 1 1 ? *)", "@yearly"), + ("@annually", "cron(0 0 1 1 ? *)", "@annually is @yearly"), + + # --- whitespace --------------------------------------------------------- + (" 0 0 * * * ", "cron(0 0 * * ? *)", "extra whitespace is tolerated"), +] + +# (crontab line, substring expected in the error, why it is refused) +REJECTED = [ + ("@reboot", "no EventBridge Scheduler equivalent", "nothing boots"), + ("0 0 1 * 1", "OR", "cron ORs the two day fields; Scheduler cannot"), + ("0 0 15 * MON", "OR", "same OR problem with a day name"), + ("60 0 * * *", "minute value 60", "minute out of range"), + ("0 24 * * *", "hour value 24", "hour out of range"), + ("0 0 32 * *", "day-of-month value 32", "day-of-month out of range"), + ("0 0 * 13 *", "month value 13", "month out of range"), + ("0 0 * * 8", "day-of-week value 8", "day-of-week out of range"), + ("* * * *", "expected 5 crontab fields", "four fields"), + ("0 0 * * * extra", "expected 5 crontab fields", "command column left on"), + ("", "empty", "empty line"), + ("@hourlyish", "unknown crontab macro", "macro typo"), +] + + +class TestConversion(unittest.TestCase): + def test_known_answers(self): + for line, expected, reason in CASES: + with self.subTest(crontab=line, reason=reason): + self.assertEqual(to_scheduler_expression(line), expected) + + def test_always_six_fields(self): + """Scheduler requires six fields; crontab supplies five.""" + for line, _, reason in CASES: + with self.subTest(crontab=line, reason=reason): + inner = to_scheduler_expression(line)[len("cron("):-1] + self.assertEqual(len(inner.split()), 6, inner) + + def test_exactly_one_question_mark(self): + """`?` must appear in exactly one of the two day fields.""" + for line, _, reason in CASES: + with self.subTest(crontab=line, reason=reason): + inner = to_scheduler_expression(line)[len("cron("):-1] + _, _, dom, _, dow, _ = inner.split() + self.assertEqual( + [dom, dow].count("?"), 1, + f"day-of-month={dom} day-of-week={dow}", + ) + self.assertFalse( + dom == "*" and dow == "*", + "`*` is not allowed in both day fields", + ) + + +class TestRejections(unittest.TestCase): + def test_refused_with_a_useful_message(self): + for line, fragment, reason in REJECTED: + with self.subTest(crontab=line, reason=reason): + with self.assertRaises(UnsupportedCronError) as caught: + to_scheduler_expression(line) + self.assertIn(fragment, str(caught.exception)) + + +class TestDayOfWeekRoundTrip(unittest.TestCase): + """Every crontab day number must land on the same real weekday.""" + + def test_all_seven_days(self): + # crontab number -> the Scheduler number for the same weekday + expected = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 1} + for crontab_day, scheduler_day in expected.items(): + with self.subTest(crontab_day=crontab_day): + self.assertEqual( + to_scheduler_expression(f"0 0 * * {crontab_day}"), + f"cron(0 0 ? * {scheduler_day} *)", + ) + + def test_numeric_and_named_days_agree(self): + """`0 0 * * 3` and `0 0 * * WED` must select the same day.""" + numeric = to_scheduler_expression("0 0 * * 3") + named = to_scheduler_expression("0 0 * * WED") + self.assertEqual(numeric, "cron(0 0 ? * 4 *)") + self.assertEqual(named, "cron(0 0 ? * WED *)") + # Scheduler: 1=SUN, so 4=WED. Same day by two spellings. + + +if __name__ == "__main__": + unittest.main(verbosity=2)