|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Read-only, fail-closed ECS retirement check for the Project column contract migration. |
| 3 | +
|
| 4 | +The expected digest acknowledges fully deployed #8830 transaction-barrier and durable-authority support |
| 5 | +and retirement of every incompatible server and relevant old worker job before switching. Every live and supported |
| 6 | +rollback application must tolerate project_workspace being absent. |
| 7 | +AWS checks below independently verify ECS retirement, not worker drainage. |
| 8 | +""" |
| 9 | +import argparse |
| 10 | +import datetime |
| 11 | +import json |
| 12 | +import re |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | + |
| 16 | + |
| 17 | +def aws(region, *args): |
| 18 | + result = subprocess.run( |
| 19 | + ['aws', '--region', region, '--no-cli-pager', '--cli-connect-timeout', '10', '--cli-read-timeout', '30', *args, '--output', 'json'], |
| 20 | + capture_output=True, text=True, timeout=90, check=False, |
| 21 | + ) |
| 22 | + if result.returncode: |
| 23 | + raise RuntimeError('AWS preflight read failed; check deployment-read permissions') |
| 24 | + return json.loads(result.stdout) |
| 25 | + |
| 26 | + |
| 27 | +def latest_execution(region, pipeline): |
| 28 | + executions = aws(region, 'codepipeline', 'list-pipeline-executions', '--pipeline-name', pipeline).get('pipelineExecutionSummaries', []) |
| 29 | + def epoch(execution): |
| 30 | + value = execution['startTime'] |
| 31 | + return value if isinstance(value, (int, float)) else datetime.datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp() |
| 32 | + if not executions: |
| 33 | + raise RuntimeError('No application deployment execution was found') |
| 34 | + return max(executions, key=epoch) |
| 35 | + |
| 36 | + |
| 37 | +def matches_release(execution, digest): |
| 38 | + return execution.get('status') == 'Succeeded' and any( |
| 39 | + revision.get('actionName') == 'ECR_Source' and revision.get('revisionId') == digest |
| 40 | + for revision in execution.get('sourceRevisions', []) |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +def verify(environment, region, digest): |
| 45 | + if not re.fullmatch(r'sha256:[0-9a-f]{64}', digest): |
| 46 | + raise RuntimeError('Set the environment-specific PROJECT_COLUMN_ENFORCEMENT_READY_IMAGE_DIGEST after verifying #8830 authority-aware readers/writers, transaction barriers and all incompatible server/worker drainage') |
| 47 | + pipeline = f'sim-{environment}-{region}-app-deployment' |
| 48 | + execution = latest_execution(region, pipeline) |
| 49 | + if not matches_release(execution, digest): |
| 50 | + raise RuntimeError('The latest app pipeline has not completed for the acknowledged image; traffic cutover alone is insufficient') |
| 51 | + execution_id = execution['pipelineExecutionId'] |
| 52 | + group = aws(region, 'deploy', 'get-deployment-group', '--application-name', f'sim-{environment}-{region}-ecs-app', |
| 53 | + '--deployment-group-name', f'sim-{environment}-{region}-app-dg')['deploymentGroupInfo'] |
| 54 | + services = group.get('ecsServices', []) |
| 55 | + if len(services) != 1: |
| 56 | + raise RuntimeError('Expected exactly one application ECS service') |
| 57 | + cluster, service = services[0]['clusterName'], services[0]['serviceName'] |
| 58 | + description = aws(region, 'ecs', 'describe-services', '--cluster', cluster, '--services', service) |
| 59 | + if description.get('failures') or len(description.get('services', [])) != 1: |
| 60 | + raise RuntimeError('Cannot inspect the application ECS service') |
| 61 | + record = description['services'][0] |
| 62 | + if record.get('desiredCount', 0) < 1 or record.get('runningCount') != record['desiredCount'] or record.get('pendingCount') != 0: |
| 63 | + raise RuntimeError('Application ECS service is not stable') |
| 64 | + arns = set() |
| 65 | + for status in ('RUNNING', 'STOPPED'): |
| 66 | + arns.update(aws(region, 'ecs', 'list-tasks', '--cluster', cluster, '--service-name', service, |
| 67 | + '--desired-status', status).get('taskArns', [])) |
| 68 | + live = [] |
| 69 | + ordered = sorted(arns) |
| 70 | + for start in range(0, len(ordered), 100): |
| 71 | + response = aws(region, 'ecs', 'describe-tasks', '--cluster', cluster, '--tasks', *ordered[start:start + 100]) |
| 72 | + if response.get('failures'): |
| 73 | + raise RuntimeError('Cannot account for every ECS task') |
| 74 | + if len(response.get('tasks', [])) != len(ordered[start:start + 100]): |
| 75 | + raise RuntimeError('Incomplete ECS task response') |
| 76 | + live.extend(task for task in response['tasks'] if task.get('lastStatus') != 'STOPPED') |
| 77 | + if len(live) != record['desiredCount']: |
| 78 | + raise RuntimeError('Old, stopping, or pending ECS tasks remain') |
| 79 | + for task in live: |
| 80 | + app = [container for container in task.get('containers', []) if container.get('name') == 'app'] |
| 81 | + if task.get('lastStatus') != 'RUNNING' or task.get('desiredStatus') != 'RUNNING' or len(app) != 1 or app[0].get('imageDigest') != digest: |
| 82 | + raise RuntimeError('A live ECS task does not match the acknowledged compatible release') |
| 83 | + latest = latest_execution(region, pipeline) |
| 84 | + if latest.get('pipelineExecutionId') != execution_id or not matches_release(latest, digest): |
| 85 | + raise RuntimeError('Application deployment changed during preflight') |
| 86 | + print(json.dumps({'ecsRetired': True, 'expectedImageDigest': digest, 'pipelineExecutionId': execution_id, |
| 87 | + 'operatorAcknowledgedColumnWritersAndWorkers': True})) |
| 88 | + |
| 89 | + |
| 90 | +if __name__ == '__main__': |
| 91 | + parser = argparse.ArgumentParser(description=__doc__) |
| 92 | + parser.add_argument('--environment', required=True, choices=['production', 'staging']) |
| 93 | + parser.add_argument('--region', required=True) |
| 94 | + parser.add_argument('--expected-image-digest', required=True) |
| 95 | + args = parser.parse_args() |
| 96 | + try: |
| 97 | + verify(args.environment, args.region, args.expected_image_digest) |
| 98 | + except (RuntimeError, ValueError, KeyError, TypeError, subprocess.TimeoutExpired) as error: |
| 99 | + print(f'Project column rollout preflight refused: {error}', file=sys.stderr) |
| 100 | + sys.exit(1) |
0 commit comments