|
| 1 | +import logging |
| 2 | +import pathlib |
| 3 | +import typing |
| 4 | +from enum import Enum |
| 5 | +from tqdm import tqdm |
| 6 | +from hashlib import md5 |
| 7 | +import os |
| 8 | +from abc import ABC, abstractmethod |
| 9 | + |
| 10 | +from .. import config |
| 11 | + |
| 12 | +logging.getLogger("s3fs").setLevel(logging.CRITICAL) |
| 13 | + |
| 14 | +log = logging.getLogger(__name__) |
| 15 | + |
| 16 | +DatasetReader = typing.TypeVar("DatasetReader") |
| 17 | + |
| 18 | +class DatasetSource(Enum): |
| 19 | + S3 = "S3" |
| 20 | + AliyunOSS = "AliyunOSS" |
| 21 | + |
| 22 | + def reader(self) -> DatasetReader: |
| 23 | + if self == DatasetSource.S3: |
| 24 | + return AwsS3Reader() |
| 25 | + |
| 26 | + if self == DatasetSource.AliyunOSS: |
| 27 | + return AliyunOSSReader() |
| 28 | + |
| 29 | + |
| 30 | +class DatasetReader(ABC): |
| 31 | + source: DatasetSource |
| 32 | + remote_root: str |
| 33 | + |
| 34 | + @abstractmethod |
| 35 | + def read(self, dataset: str, files: list[str], local_ds_root: pathlib.Path, check_etag: bool = True): |
| 36 | + """read dataset files from remote_root to local_ds_root, |
| 37 | +
|
| 38 | + Args: |
| 39 | + dataset(str): for instance "sift_small_500k" |
| 40 | + files(list[str]): all filenames of the dataset |
| 41 | + local_ds_root(pathlib.Path): whether to write the remote data. |
| 42 | + check_etag(bool): whether to check the etag |
| 43 | + """ |
| 44 | + pass |
| 45 | + |
| 46 | + @abstractmethod |
| 47 | + def validate_file(self, remote: pathlib.Path, local: pathlib.Path) -> bool: |
| 48 | + pass |
| 49 | + |
| 50 | + |
| 51 | +class AliyunOSSReader(DatasetReader): |
| 52 | + source: DatasetSource = DatasetSource.AliyunOSS |
| 53 | + remote_root: str = config.ALIYUN_OSS_URL |
| 54 | + |
| 55 | + def __init__(self): |
| 56 | + import oss2 |
| 57 | + self.bucket = oss2.Bucket(oss2.AnonymousAuth(), self.remote_root, "benchmark", True) |
| 58 | + |
| 59 | + def validate_file(self, remote: pathlib.Path, local: pathlib.Path, check_etag: bool) -> bool: |
| 60 | + info = self.bucket.get_object_meta(remote.as_posix()) |
| 61 | + |
| 62 | + # check size equal |
| 63 | + remote_size, local_size = info.content_length, os.path.getsize(local) |
| 64 | + if remote_size != local_size: |
| 65 | + log.info(f"local file: {local} size[{local_size}] not match with remote size[{remote_size}]") |
| 66 | + return False |
| 67 | + |
| 68 | + # check etag equal |
| 69 | + if check_etag: |
| 70 | + return match_etag(info.etag.strip('"').lower(), local) |
| 71 | + |
| 72 | + |
| 73 | + return True |
| 74 | + |
| 75 | + def read(self, dataset: str, files: list[str], local_ds_root: pathlib.Path, check_etag: bool = False): |
| 76 | + downloads = [] |
| 77 | + if not local_ds_root.exists(): |
| 78 | + log.info(f"local dataset root path not exist, creating it: {local_ds_root}") |
| 79 | + local_ds_root.mkdir(parents=True) |
| 80 | + downloads = [(pathlib.Path("benchmark", dataset, f), local_ds_root.joinpath(f)) for f in files] |
| 81 | + |
| 82 | + else: |
| 83 | + for file in files: |
| 84 | + remote_file = pathlib.Path("benchmark", dataset, file) |
| 85 | + local_file = local_ds_root.joinpath(file) |
| 86 | + |
| 87 | + if (not local_file.exists()) or (not self.validate_file(remote_file, local_file, check_etag)): |
| 88 | + log.info(f"local file: {local_file} not match with remote: {remote_file}; add to downloading list") |
| 89 | + downloads.append((remote_file, local_file)) |
| 90 | + |
| 91 | + if len(downloads) == 0: |
| 92 | + return |
| 93 | + |
| 94 | + log.info(f"Start to downloading files, total count: {len(downloads)}") |
| 95 | + for remote_file, local_file in tqdm(downloads): |
| 96 | + log.debug(f"downloading file {remote_file} to {local_ds_root}") |
| 97 | + self.bucket.get_object_to_file(remote_file.as_posix(), local_file.as_posix()) |
| 98 | + |
| 99 | + log.info(f"Succeed to download all files, downloaded file count = {len(downloads)}") |
| 100 | + |
| 101 | + |
| 102 | + |
| 103 | +class AwsS3Reader(DatasetReader): |
| 104 | + source: DatasetSource = DatasetSource.S3 |
| 105 | + remote_root: str = config.AWS_S3_URL |
| 106 | + |
| 107 | + def __init__(self): |
| 108 | + import s3fs |
| 109 | + self.fs = s3fs.S3FileSystem( |
| 110 | + anon=True, |
| 111 | + client_kwargs={'region_name': 'us-west-2'} |
| 112 | + ) |
| 113 | + |
| 114 | + def ls_all(self, dataset: str): |
| 115 | + dataset_root_dir = pathlib.Path(self.remote_root, dataset) |
| 116 | + log.info(f"listing dataset: {dataset_root_dir}") |
| 117 | + names = self.fs.ls(dataset_root_dir) |
| 118 | + for n in names: |
| 119 | + log.info(n) |
| 120 | + return names |
| 121 | + |
| 122 | + |
| 123 | + def read(self, dataset: str, files: list[str], local_ds_root: pathlib.Path, check_etag: bool = True): |
| 124 | + downloads = [] |
| 125 | + if not local_ds_root.exists(): |
| 126 | + log.info(f"local dataset root path not exist, creating it: {local_ds_root}") |
| 127 | + local_ds_root.mkdir(parents=True) |
| 128 | + downloads = [pathlib.Path(self.remote_root, dataset, f) for f in files] |
| 129 | + |
| 130 | + else: |
| 131 | + for file in files: |
| 132 | + remote_file = pathlib.Path(self.remote_root, dataset, file) |
| 133 | + local_file = local_ds_root.joinpath(file) |
| 134 | + |
| 135 | + if (not local_file.exists()) or (not self.validate_file(remote_file, local_file, check_etag)): |
| 136 | + log.info(f"local file: {local_file} not match with remote: {remote_file}; add to downloading list") |
| 137 | + downloads.append(remote_file) |
| 138 | + |
| 139 | + if len(downloads) == 0: |
| 140 | + return |
| 141 | + |
| 142 | + log.info(f"Start to downloading files, total count: {len(downloads)}") |
| 143 | + for s3_file in tqdm(downloads): |
| 144 | + log.debug(f"downloading file {s3_file} to {local_ds_root}") |
| 145 | + self.fs.download(s3_file, local_ds_root.as_posix()) |
| 146 | + |
| 147 | + log.info(f"Succeed to download all files, downloaded file count = {len(downloads)}") |
| 148 | + |
| 149 | + |
| 150 | + def validate_file(self, remote: pathlib.Path, local: pathlib.Path, check_etag: bool) -> bool: |
| 151 | + # info() uses ls() inside, maybe we only need to ls once |
| 152 | + info = self.fs.info(remote) |
| 153 | + |
| 154 | + # check size equal |
| 155 | + remote_size, local_size = info.get("size"), os.path.getsize(local) |
| 156 | + if remote_size != local_size: |
| 157 | + log.info(f"local file: {local} size[{local_size}] not match with remote size[{remote_size}]") |
| 158 | + return False |
| 159 | + |
| 160 | + # check etag equal |
| 161 | + if check_etag: |
| 162 | + return match_etag(info.get('ETag', "").strip('"'), local) |
| 163 | + |
| 164 | + return True |
| 165 | + |
| 166 | + |
| 167 | +def match_etag(expected_etag: str, local_file) -> bool: |
| 168 | + """Check if local files' etag match with S3""" |
| 169 | + def factor_of_1MB(filesize, num_parts): |
| 170 | + x = filesize / int(num_parts) |
| 171 | + y = x % 1048576 |
| 172 | + return int(x + 1048576 - y) |
| 173 | + |
| 174 | + def calc_etag(inputfile, partsize): |
| 175 | + md5_digests = [] |
| 176 | + with open(inputfile, 'rb') as f: |
| 177 | + for chunk in iter(lambda: f.read(partsize), b''): |
| 178 | + md5_digests.append(md5(chunk).digest()) |
| 179 | + return md5(b''.join(md5_digests)).hexdigest() + '-' + str(len(md5_digests)) |
| 180 | + |
| 181 | + def possible_partsizes(filesize, num_parts): |
| 182 | + return lambda partsize: partsize < filesize and (float(filesize) / float(partsize)) <= num_parts |
| 183 | + |
| 184 | + filesize = os.path.getsize(local_file) |
| 185 | + le = "" |
| 186 | + if '-' not in expected_etag: # no spliting uploading |
| 187 | + with open(local_file, 'rb') as f: |
| 188 | + le = md5(f.read()).hexdigest() |
| 189 | + log.debug(f"calculated local etag {le}, expected etag: {expected_etag}") |
| 190 | + return expected_etag == le |
| 191 | + else: |
| 192 | + num_parts = int(expected_etag.split('-')[-1]) |
| 193 | + partsizes = [ ## Default Partsizes Map |
| 194 | + 8388608, # aws_cli/boto3 |
| 195 | + 15728640, # s3cmd |
| 196 | + factor_of_1MB(filesize, num_parts) # Used by many clients to upload large files |
| 197 | + ] |
| 198 | + |
| 199 | + for partsize in filter(possible_partsizes(filesize, num_parts), partsizes): |
| 200 | + le = calc_etag(local_file, partsize) |
| 201 | + log.debug(f"calculated local etag {le}, expected etag: {expected_etag}") |
| 202 | + if expected_etag == le: |
| 203 | + return True |
| 204 | + return False |
0 commit comments