|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +AWS Batch job listing script for CodeClash. |
| 4 | +
|
| 5 | +This is a convenience script that lists all AWS Batch jobs sorted by creation time. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + python list_jobs.py |
| 9 | + python list_jobs.py --status RUNNING |
| 10 | + python list_jobs.py --queue my-queue --limit 20 |
| 11 | +""" |
| 12 | + |
| 13 | +import argparse |
| 14 | +from datetime import datetime |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +import boto3 |
| 18 | + |
| 19 | +from codeclash.utils.log import get_logger |
| 20 | + |
| 21 | +logger = get_logger("list_jobs", emoji="📋") |
| 22 | + |
| 23 | + |
| 24 | +class AWSBatchJobLister: |
| 25 | + def __init__(self, job_queue: str = "codeclash-queue"): |
| 26 | + self.batch_client = boto3.client("batch") |
| 27 | + self.job_queue = job_queue |
| 28 | + |
| 29 | + def list_jobs(self, *, status: str | None = None, limit: int | None = None) -> list[dict[str, Any]]: |
| 30 | + """List jobs from AWS Batch, optionally filtered by status.""" |
| 31 | + all_jobs = [] |
| 32 | + |
| 33 | + # If specific status is requested, only query that status |
| 34 | + if status: |
| 35 | + statuses = [status.upper()] |
| 36 | + else: |
| 37 | + # Query all active statuses |
| 38 | + statuses = ["SUBMITTED", "PENDING", "RUNNABLE", "STARTING", "RUNNING", "SUCCEEDED", "FAILED"] |
| 39 | + |
| 40 | + for job_status in statuses: |
| 41 | + try: |
| 42 | + # Use paginator to handle large number of jobs |
| 43 | + paginator = self.batch_client.get_paginator("list_jobs") |
| 44 | + page_iterator = paginator.paginate(jobQueue=self.job_queue, jobStatus=job_status) |
| 45 | + |
| 46 | + for page in page_iterator: |
| 47 | + jobs_in_page = page.get("jobSummaryList", []) |
| 48 | + all_jobs.extend(jobs_in_page) |
| 49 | + |
| 50 | + except Exception as e: |
| 51 | + logger.warning(f"Failed to list jobs with status {job_status}: {e}") |
| 52 | + continue |
| 53 | + |
| 54 | + # Sort by creation time (newest first) |
| 55 | + all_jobs.sort(key=lambda x: x["createdAt"], reverse=True) |
| 56 | + |
| 57 | + # Apply limit if specified |
| 58 | + if limit: |
| 59 | + all_jobs = all_jobs[:limit] |
| 60 | + |
| 61 | + return all_jobs |
| 62 | + |
| 63 | + def format_job_info(self, job: dict[str, Any]) -> str: |
| 64 | + """Format job information for display.""" |
| 65 | + job_id = job["jobId"] |
| 66 | + job_name = job["jobName"] |
| 67 | + status = job["status"] |
| 68 | + created_at = job["createdAt"] |
| 69 | + |
| 70 | + # Format creation time |
| 71 | + if isinstance(created_at, datetime): |
| 72 | + created_str = created_at.strftime("%Y-%m-%d %H:%M:%S") |
| 73 | + else: |
| 74 | + # Handle timestamp (milliseconds since epoch) |
| 75 | + created_str = datetime.fromtimestamp(created_at / 1000).strftime("%Y-%m-%d %H:%M:%S") |
| 76 | + |
| 77 | + # Get additional info if available |
| 78 | + started_at = job.get("startedAt") |
| 79 | + stopped_at = job.get("stoppedAt") |
| 80 | + |
| 81 | + duration = "" |
| 82 | + if started_at and stopped_at: |
| 83 | + if isinstance(started_at, datetime): |
| 84 | + start_time = started_at |
| 85 | + stop_time = stopped_at |
| 86 | + else: |
| 87 | + start_time = datetime.fromtimestamp(started_at / 1000) |
| 88 | + stop_time = datetime.fromtimestamp(stopped_at / 1000) |
| 89 | + duration_seconds = (stop_time - start_time).total_seconds() |
| 90 | + duration = f" ({duration_seconds:.0f}s)" |
| 91 | + elif started_at: |
| 92 | + if isinstance(started_at, datetime): |
| 93 | + start_time = started_at |
| 94 | + else: |
| 95 | + start_time = datetime.fromtimestamp(started_at / 1000) |
| 96 | + running_seconds = (datetime.now() - start_time).total_seconds() |
| 97 | + duration = f" (running {running_seconds:.0f}s)" |
| 98 | + |
| 99 | + return f"{job_id:<36} {status:<10} {created_str} {job_name}{duration}" |
| 100 | + |
| 101 | + def print_jobs(self, jobs: list[dict[str, Any]]) -> None: |
| 102 | + """Print jobs in a formatted table.""" |
| 103 | + if not jobs: |
| 104 | + logger.info("No jobs found") |
| 105 | + return |
| 106 | + |
| 107 | + # Print header |
| 108 | + header = f"{'Job ID':<36} {'Status':<10} {'Created':<19} {'Job Name'}" |
| 109 | + print(header) |
| 110 | + print("-" * len(header)) |
| 111 | + |
| 112 | + # Print jobs |
| 113 | + for job in jobs: |
| 114 | + print(self.format_job_info(job)) |
| 115 | + |
| 116 | + print(f"\nTotal: {len(jobs)} job(s)") |
| 117 | + |
| 118 | + |
| 119 | +def main(): |
| 120 | + parser = argparse.ArgumentParser( |
| 121 | + description="List AWS Batch jobs", |
| 122 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 123 | + ) |
| 124 | + parser.add_argument( |
| 125 | + "--status", |
| 126 | + choices=["SUBMITTED", "PENDING", "RUNNABLE", "STARTING", "RUNNING", "SUCCEEDED", "FAILED"], |
| 127 | + help="Filter jobs by status (default: show all statuses)", |
| 128 | + ) |
| 129 | + parser.add_argument("--queue", default="codeclash-queue", help="Job queue name (default: codeclash-queue)") |
| 130 | + parser.add_argument("--limit", type=int, help="Maximum number of jobs to display") |
| 131 | + |
| 132 | + args = parser.parse_args() |
| 133 | + |
| 134 | + lister = AWSBatchJobLister(job_queue=args.queue) |
| 135 | + |
| 136 | + # List jobs |
| 137 | + logger.info(f"Listing jobs from queue: {args.queue}") |
| 138 | + if args.status: |
| 139 | + logger.info(f"Filtering by status: {args.status}") |
| 140 | + |
| 141 | + jobs = lister.list_jobs(status=args.status, limit=args.limit) |
| 142 | + lister.print_jobs(jobs) |
| 143 | + |
| 144 | + |
| 145 | +if __name__ == "__main__": |
| 146 | + main() |
0 commit comments