PHP的Heroku内存错误和从S3读取大文件

bon*_*nez 6 php memory heroku amazon-s3 amazon-web-services

我正在使用适用于PHP的AWS 2.3.2 SDK尝试使用它们的流包装器从S3下载一个大文件(~4g),这应该允许我使用fopen/fwrite将文件写入磁盘而不是缓冲区记忆.

这是参考:

http://docs.aws.amazon.com/aws-sdk-php-2/guide/latest/service-s3.html#downloading-data

这是我的代码:

public function download()
    {

        $client = S3Client::factory(array(
                    'key'    => getenv('S3_KEY'),
                    'secret' => getenv('S3_SECRET')
                    ));

        $bucket = getenv('S3_BUCKET');
        $client->registerStreamWrapper();

        try {
            error_log("calling download");
            // Open a stream in read-only mode
            if ($stream = fopen('s3://'.$bucket.'/tmp/'.$this->getOwner()->filename, 'r')) {
                // While the stream is still open
                if (($fp = @fopen($this->getOwner()->path . '/' . $this->getOwner()->filename, 'w')) !== false){

                    while (!feof($stream)) {
                        // Read 1024 bytes from the stream
                        fwrite($fp, fread($stream, 1024));
                    }
                    fclose($fp);
                }
            // Be sure to close the stream resource when you're done with it
            fclose($stream);
        }
Run Code Online (Sandbox Code Playgroud)

文件下载但我不断从Heroku收到错误消息:

2013-08-22T19:57:59.537740 + 00:00 heroku [run.9336]:进程运行mem = 515M(100.6%)2013-08-22T19:57:59.537972 + 00:00 heroku [run.9336]:错误R14(超出内存配额)

这让我相信这仍然以某种方式缓冲到内存.我曾尝试使用https://github.com/arnaud-lb/php-memory-profiler,但遇到了Seg Fault.

我还尝试使用带有CURLOPT_FILE选项的cURL下载文件,直接写入磁盘,但我的内存仍然不足.奇怪的是根据top我的php实例使用223m的内存,所以甚至不允许512的一半.

有人有什么想法吗?我从php 5.4.17 cli运行它来测试.

Wim*_*ans 2

您是否已经尝试过使用 2x dyno(内存为 1GB)?

您还可以尝试通过在 PHP 中执行curl 命令来下载文件。这不是最干净的方式,但它会更快/更可靠并且内存友好。

exec("curl -O http://test.s3.amazonaws.com/file.zip", $output);
Run Code Online (Sandbox Code Playgroud)

此示例适用于公共 URL。如果您不想公开您的 S3 文件,您可以随时创建一个签名 URL 并将其与curl 命令结合使用。