【问题标题】:Download script using php-fpm/Nginx Causes High Load CPU使用 php-fpm/Nginx 下载脚本导致 CPU 负载过高
【发布时间】:2013-11-30 03:18:54
【问题描述】:

我有一个用于文件共享的良好服务器,但下载脚本有问题。 我使用在 nginx 上运行的 PHP-FPM。

服务器规格:

2x Intel Xeon E5
CPU: 92GB RAM
10x2TB (RAID6)
And we use 1 SSD disk for CashCade

当我在 apache 服务器上运行这个脚本时,它工作正常,但我想在 nginx 服务器上运行它,因为 apache 占用大量内存。 (内存) 但是当我在 nginx 上运行这个脚本时,真正发生了一些事情——它占用了 30% 的 CPU,只下载一次! 请注意,在开始下载 3-4 分钟后,CPU 负载会恢复正常(但会继续下载)。

这是 LINUX 中的“TOP”当我下载时...

我不知道为什么,但是 PHP-FPM 脚本占用了大量 CPU 资源。脚本:

class ResumeDownload {
    private $file;
    private $name;
    private $boundary;
    private $delay = 0;
    private $size = 0;

    function __construct($file, $delay = 0) {
        if (! is_file($file)) {
            header("HTTP/1.1 400 Invalid Request");
            die("<h3>File Not Found</h3>");
        }

        $this->size = filesize($file);
        $this->file = fopen($file, "r");
        $this->boundary = md5($file);
        $this->delay = $delay;
        $this->name = basename($file);
    }

    public function process() {
        $ranges = NULL;
        $t = 0;
        if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_SERVER['HTTP_RANGE']) && $range = stristr(trim($_SERVER['HTTP_RANGE']), 'bytes=')) {
            $range = substr($range, 6);
            $ranges = explode(',', $range);
            $t = count($ranges);
        }

        header("Accept-Ranges: bytes");
        header("Content-Type: application/octet-stream");
        header("Content-Transfer-Encoding: binary");
        header(sprintf('Content-Disposition: attachment; filename="%s"', $this->name));

        if ($t > 0) {
            header("HTTP/1.1 206 Partial content");
            $t === 1 ? $this->pushSingle($range) : $this->pushMulti($ranges);
        } else {
            header("Content-Length: " . $this->size);
            $this->readFile();
        }

        flush();
    }

    private function pushSingle($range) {
        $start = $end = 0;
        $this->getRange($range, $start, $end);
        header("Content-Length: " . ($end - $start + 1));
        header(sprintf("Content-Range: bytes %d-%d/%d", $start, $end, $this->size));
        fseek($this->file, $start);
        $this->readBuffer($end - $start + 1);
        $this->readFile();
    }

    private function pushMulti($ranges) {
        $length = $start = $end = 0;
        $output = "";

        $tl = "Content-type: application/octet-stream\r\n";
        $formatRange = "Content-range: bytes %d-%d/%d\r\n\r\n";

        foreach ( $ranges as $range ) {
            $this->getRange($range, $start, $end);
            $length += strlen("\r\n--$this->boundary\r\n");
            $length += strlen($tl);
            $length += strlen(sprintf($formatRange, $start, $end, $this->size));
            $length += $end - $start + 1;
        }
        $length += strlen("\r\n--$this->boundary--\r\n");
        header("Content-Length: $length");
        header("Content-Type: multipart/x-byteranges; boundary=$this->boundary");
        foreach ( $ranges as $range ) {
            $this->getRange($range, $start, $end);
            echo "\r\n--$this->boundary\r\n";
            echo $tl;
            echo sprintf($formatRange, $start, $end, $this->size);
            fseek($this->file, $start);
            $this->readBuffer($end - $start + 1);
        }
        echo "\r\n--$this->boundary--\r\n";
    }

    private function getRange($range, &$start, &$end) {
        list($start, $end) = explode('-', $range);

        $fileSize = $this->size;
        if ($start == '') {
            $tmp = $end;
            $end = $fileSize - 1;
            $start = $fileSize - $tmp;
            if ($start < 0)
                $start = 0;
        } else {
            if ($end == '' || $end > $fileSize - 1)
                $end = $fileSize - 1;
        }

        if ($start > $end) {
            header("Status: 416 Requested range not satisfiable");
            header("Content-Range: */" . $fileSize);
            exit();
        }

        return array(
                $start,
                $end
        );
    }

    private function readFile() {
        while ( ! feof($this->file) ) {
            echo fgets($this->file);
            flush();
            usleep($this->delay);
        }
    }

    private function readBuffer($bytes, $size = 1024) {
        $bytesLeft = $bytes;
        while ( $bytesLeft > 0 && ! feof($this->file) ) {
            $bytesLeft > $size ? $bytesRead = $size : $bytesRead = $bytesLeft;
            $bytesLeft -= $bytesRead;
            echo fread($this->file, $bytesRead);
            flush();
            usleep($this->delay);
        }
    }
}

还有download.php(我运行脚本的地方)

// ... some code that get the file details from extrenal Database...

$fileArr = $query->fetch_assoc();
$file = 'uploads/' . $download['fileid'] . '/' . $fileArr['name'];

if(file_exists($file)) {
    $mysqli->close();
    require 'class.download.php';
    set_time_limit(0);
    $download = new ResumeDownload($file, 0); //delay about in microsecs 
    $download->process();
}

【问题讨论】:

标签: nginx download php


【解决方案1】:

我不知道为什么,但是 PHP-FPM 脚本占用了很多 CPU。

是什么让你认为这是个问题?当服务器不受 CPU 限制时,程序将使用尽可能多的 CPU 以尽可能快的速度运行。高 CPU 使用率真正重要的唯一情况是服务器无法足够快地处理请求,因为所有脚本都在竞争使用 CPU 资源,并相互阻止运行。

您的脚本正在尽可能快地运行(即使用尽可能多的 CPU),因为您已经告诉它:

$download = new ResumeDownload($file, 0); //delay about in microsecs

即您的下载脚本永远不会等待,因此它会尽可能快地循环将数据推送到网络连接中。

很明显,服务器将数据推送到网络连接的速度比通过 Internet 发送的速度要快,所以很多时候你的脚本只是循环并等待网络连接能够发送数据 - 正如所证明的那样通过“顶部”输出顶部的高空闲时间。

您可以设置延迟以使脚本真正进入睡眠状态,或者您可以使用 Nginx x-accel 完全消除 PHP 的负载。这里有一个配置:Serve large file with PHP and nginx X-Accel-Redirect 这在您实际上受 CPU 限制的情况下会更有效率。

【讨论】:

  • 我喜欢internal的方法,以前从来没有想过,它阻止直接访问,仍然保持nginx的负载,不错。
【解决方案2】:

增加这个方法的延迟:

 $download = new ResumeDownload($file, 500); //delay about in microsecs

或者使用 nginx x-accel-redirect 代替 ResumeDownload 类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-27
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2012-07-24
    • 2016-02-09
    • 2020-09-16
    相关资源
    最近更新 更多