|
| 1 | +import logging |
| 2 | +import subprocess |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +import boto3 |
| 6 | +from botocore.exceptions import ClientError |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from mypy_boto3_s3.client import S3Client |
| 10 | + |
| 11 | +from abdiff.config import Config |
| 12 | + |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +CONFIG = Config() |
| 17 | + |
| 18 | + |
| 19 | +def download_input_files(input_files: str): |
| 20 | + s3_client = boto3.client("s3") |
| 21 | + |
| 22 | + for input_file in input_files: |
| 23 | + if check_object_exists(CONFIG.TIMDEX_BUCKET, input_file, s3_client): |
| 24 | + continue |
| 25 | + |
| 26 | + logger.info(f"Downloading input file from {CONFIG.TIMDEX_BUCKET}: {input_file}") |
| 27 | + copy_command = ["aws", "s3", "cp", input_file, "-"] |
| 28 | + upload_command = [ |
| 29 | + "aws", |
| 30 | + "s3", |
| 31 | + "cp", |
| 32 | + "--endpoint-url", |
| 33 | + CONFIG.aws_endpoint_url, |
| 34 | + "--profile", |
| 35 | + "minio", |
| 36 | + "-", |
| 37 | + input_file, |
| 38 | + ] |
| 39 | + |
| 40 | + try: |
| 41 | + copy_process = subprocess.run( |
| 42 | + args=copy_command, check=True, capture_output=True |
| 43 | + ) |
| 44 | + subprocess.run( |
| 45 | + args=upload_command, |
| 46 | + check=True, |
| 47 | + input=copy_process.stdout, |
| 48 | + ) |
| 49 | + except subprocess.CalledProcessError: |
| 50 | + logger.exception(f"Failed to download input file: {input_file}") |
| 51 | + |
| 52 | + |
| 53 | +def check_object_exists(bucket: str, input_file: str, s3_client: S3Client) -> bool: |
| 54 | + key = input_file.replace(f"s3://{bucket}/", "") |
| 55 | + try: |
| 56 | + s3_client.head_object(Bucket=bucket, Key=key) |
| 57 | + return True |
| 58 | + except ClientError as exception: |
| 59 | + if exception.response["Error"]["Code"] == "NoSuchKey": |
| 60 | + return False |
| 61 | + logger.exception(f"Cannot determine if object exists for key {key}.") |
| 62 | + return False |
0 commit comments