繁体   English   中英

在 ec2 上使用 Boto3 将大文件流式传输到 S3 的问题

[英]Problem with Streaming large files with Boto3 to S3 on ec2

我正在尝试将 stream 大文件从 HTTP 直接转换为 S3。 我宁愿不下载文件,然后下载 stream 它,我正在尝试直接下载。 所以源是要从 http 服务器流式传输的大文件(60GB),目标是 s3 存储桶。

我已经在两个环境上进行了测试:在我的 WSL 环境中,当 memory 达到 100% 时,脚本被杀死,将 max_concurrency 设置为 2,没有任何帮助,为什么我仍然得到 memory 过载?

在我想要运行代码的 Ec2(微型)机器上,boto 代码甚至没有运行或显示任何错误? 也许我需要将机器的 memory 从 1GB 增加到 2-3? 但我仍然想保持它在免费层...

stream 这么大的文件有没有直接的? 当我 stream 小文件(如 1GB 或更少)时,它的工作没有问题..

i think the problem is with memory issues, that the code trys to read the http file into memory and upload, maybe the way is to read it into memory in chunks and stream in chunks? 我是怎么做的,我不是 python 专家.. 已经为此工作了好几天..


    def stream_to_s3(self, source_filename, remote_filename):
        error = 0
        self.log(f"====> Streaming {source_filename} to S3://{remote_filename}")

        s3 = boto3.resource('s3')
        bucket = s3.Bucket(self.params['UPLOAD_TO_S3']['S3_BUCKET'])
        destination = bucket.Object(remote_filename)

        with self.session.get(source_filename, stream=True) as response:
            GB = 1024 ** 3
            MB = 1024 * 1024
            max_threshold = 5 * GB
            # if int(response.headers['content-length']) > max_threshold:
            TC = TransferConfig(multipart_threshold=max_threshold, max_concurrency=2, multipart_chunksize=8 * MB, use_threads=True)
            try:
                destination.upload_fileobj(response.raw, Config=TC)
            except Exception as e:
                self.log(f"====> Failure streaming file to S3://{remote_filename}. Reason: {e}")
                return 1
        self.log(f"====> Succeeded streaming file to S3://{remote_filename}")

您可以使用智能打开package 获取输入源和 output 目标的文件对象。 这应该能够“有效地传输非常大的文件”。

from smart_open import open

remote_uri = f's3://{remote_filename}'

with open(remote_uri, 'w') as f_out:
    # Assuming requests library.
    for line in response.iter_lines(): 
        f_out.write(line)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM