|
| 1 | +import re |
| 2 | +from abc import ABC, ABCMeta, abstractmethod |
| 3 | +from enum import Enum |
| 4 | +from tempfile import TemporaryFile |
| 5 | +from typing import List |
| 6 | +from urllib.parse import ParseResult, urlparse |
| 7 | + |
| 8 | +import boto3 |
| 9 | +from google.cloud import storage |
| 10 | + |
| 11 | + |
| 12 | +class PROTOCOL(Enum): |
| 13 | + GS = "gs" |
| 14 | + S3 = "s3" |
| 15 | + LOCAL_FILE = "file" |
| 16 | + |
| 17 | + |
| 18 | +class StagingStrategy: |
| 19 | + def __init__(self): |
| 20 | + self._protocol_dict = dict() |
| 21 | + |
| 22 | + def execute_file_download(self, file_uri: ParseResult) -> TemporaryFile: |
| 23 | + protocol = self._get_staging_protocol(file_uri.scheme) |
| 24 | + return protocol.download_file(file_uri) |
| 25 | + |
| 26 | + def execute_get_source_files(self, source: str) -> List[str]: |
| 27 | + uri = urlparse(source) |
| 28 | + if "*" in uri.path: |
| 29 | + protocol = self._get_staging_protocol(uri.scheme) |
| 30 | + return protocol.list_files(bucket=uri.hostname, uri=uri) |
| 31 | + elif PROTOCOL(uri.scheme) in [PROTOCOL.S3, PROTOCOL.GS]: |
| 32 | + return [source] |
| 33 | + else: |
| 34 | + raise Exception( |
| 35 | + f"Could not identify file protocol {uri.scheme}. Only gs:// and file:// and s3:// supported" |
| 36 | + ) |
| 37 | + |
| 38 | + def execute_file_upload( |
| 39 | + self, scheme: str, local_path: str, bucket: str, remote_path: str |
| 40 | + ): |
| 41 | + protocol = self._get_staging_protocol(scheme) |
| 42 | + return protocol.upload_file(local_path, bucket, remote_path) |
| 43 | + |
| 44 | + def _get_staging_protocol(self, protocol): |
| 45 | + if protocol in self._protocol_dict: |
| 46 | + return self._protocol_dict[protocol] |
| 47 | + else: |
| 48 | + if PROTOCOL(protocol) == PROTOCOL.GS: |
| 49 | + self._protocol_dict[protocol] = GCSProtocol() |
| 50 | + elif PROTOCOL(protocol) == PROTOCOL.S3: |
| 51 | + self._protocol_dict[protocol] = S3Protocol() |
| 52 | + elif PROTOCOL(protocol) == PROTOCOL.LOCAL_FILE: |
| 53 | + self._protocol_dict[protocol] = LocalFSProtocol() |
| 54 | + else: |
| 55 | + raise Exception( |
| 56 | + f"Could not identify file protocol {protocol}. Only gs:// and file:// and s3:// supported" |
| 57 | + ) |
| 58 | + return self._protocol_dict[protocol] |
| 59 | + |
| 60 | + |
| 61 | +class AbstractStagingProtocol(ABC): |
| 62 | + |
| 63 | + __metaclass__ = ABCMeta |
| 64 | + |
| 65 | + @abstractmethod |
| 66 | + def __init__(self): |
| 67 | + pass |
| 68 | + |
| 69 | + @abstractmethod |
| 70 | + def download_file(self, uri: ParseResult) -> TemporaryFile: |
| 71 | + pass |
| 72 | + |
| 73 | + @abstractmethod |
| 74 | + def list_files(self, bucket: str, uri: ParseResult) -> List[str]: |
| 75 | + pass |
| 76 | + |
| 77 | + @abstractmethod |
| 78 | + def upload_file(self, local_path: str, bucket: str, remote_path: str): |
| 79 | + pass |
| 80 | + |
| 81 | + |
| 82 | +class GCSProtocol(AbstractStagingProtocol): |
| 83 | + def __init__(self): |
| 84 | + self.gcs_client = storage.Client(project=None) |
| 85 | + |
| 86 | + def download_file(self, uri: ParseResult) -> TemporaryFile: |
| 87 | + url = uri.geturl() |
| 88 | + file_obj = TemporaryFile() |
| 89 | + self.gcs_client.download_blob_to_file(url, file_obj) |
| 90 | + return file_obj |
| 91 | + |
| 92 | + def list_files(self, bucket: str, uri: ParseResult) -> List[str]: |
| 93 | + bucket = self.gcs_client.get_bucket(bucket) |
| 94 | + path = uri.path |
| 95 | + |
| 96 | + if "*" in path: |
| 97 | + regex = re.compile(path.replace("*", ".*?").strip("/")) |
| 98 | + blob_list = bucket.list_blobs( |
| 99 | + prefix=path.strip("/").split("*")[0], delimiter="/" |
| 100 | + ) |
| 101 | + # File path should not be in path (file path must be longer than path) |
| 102 | + return [ |
| 103 | + f"{uri.scheme}://{uri.hostname}/{file}" |
| 104 | + for file in [x.name for x in blob_list] |
| 105 | + if re.match(regex, file) and file not in path |
| 106 | + ] |
| 107 | + else: |
| 108 | + raise Exception(f"{path} is not a wildcard path") |
| 109 | + |
| 110 | + def upload_file(self, local_path: str, bucket: str, remote_path: str): |
| 111 | + bucket = self.gcs_client.get_bucket(bucket) |
| 112 | + blob = bucket.blob(remote_path) |
| 113 | + blob.upload_from_filename(local_path) |
| 114 | + |
| 115 | + |
| 116 | +class S3Protocol(AbstractStagingProtocol): |
| 117 | + def __init__(self): |
| 118 | + self.s3_client = boto3.client("s3") |
| 119 | + |
| 120 | + def download_file(self, uri: ParseResult) -> TemporaryFile: |
| 121 | + url = uri.path[1:] # removing leading / from the path |
| 122 | + bucket = uri.hostname |
| 123 | + file_obj = TemporaryFile() |
| 124 | + self.s3_client.download_fileobj(bucket, url, file_obj) |
| 125 | + return file_obj |
| 126 | + |
| 127 | + def list_files(self, bucket: str, uri: ParseResult) -> List[str]: |
| 128 | + path = uri.path |
| 129 | + |
| 130 | + if "*" in path: |
| 131 | + regex = re.compile(path.replace("*", ".*?").strip("/")) |
| 132 | + blob_list = self.s3_client.list_objects( |
| 133 | + Bucket=bucket, Prefix=path.strip("/").split("*")[0], Delimiter="/" |
| 134 | + ) |
| 135 | + # File path should not be in path (file path must be longer than path) |
| 136 | + return [ |
| 137 | + f"{uri.scheme}://{uri.hostname}/{file}" |
| 138 | + for file in [x["Key"] for x in blob_list["Contents"]] |
| 139 | + if re.match(regex, file) and file not in path |
| 140 | + ] |
| 141 | + else: |
| 142 | + raise Exception(f"{path} is not a wildcard path") |
| 143 | + |
| 144 | + def upload_file(self, local_path: str, bucket: str, remote_path: str): |
| 145 | + with open(local_path, "rb") as file: |
| 146 | + self.s3_client.upload_fileobj(file, bucket, remote_path) |
| 147 | + |
| 148 | + |
| 149 | +class LocalFSProtocol(AbstractStagingProtocol): |
| 150 | + def __init__(self): |
| 151 | + pass |
| 152 | + |
| 153 | + def download_file(self, file_uri: ParseResult) -> TemporaryFile: |
| 154 | + url = file_uri.path |
| 155 | + file_obj = open(url, "rb") |
| 156 | + return file_obj |
| 157 | + |
| 158 | + def list_files(self, bucket: str, uri: ParseResult) -> List[str]: |
| 159 | + raise NotImplementedError("list file not implemented for Local file") |
| 160 | + |
| 161 | + def upload_file(self, local_path: str, bucket: str, remote_path: str): |
| 162 | + pass # For test cases |
0 commit comments