Completed
Pull Request — master (#37)
by Boris
03:48 queued 01:31
created

ParallelDownloader::getCacheKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 5
cp 0
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
/*
3
 * hirak/prestissimo
4
 * @author Hiraku NAKANO
5
 * @license MIT https://github.com/hirak/prestissimo
6
 */
7
namespace Hirak\Prestissimo;
8
9
use Composer\Package;
10
use Composer\IO;
11
use Composer\Config;
12
13
/**
14
 *
15
 */
16
class ParallelDownloader
17
{
18
    /** @var IO/IOInterface */
19
    protected $io;
20
21
    /** @var Config */
22
    protected $config;
23
24
    /** @var int */
25
    protected $totalCnt = 0;
26
    protected $successCnt = 0;
27
    protected $failureCnt = 0;
28
29 1
    public function __construct(IO\IOInterface $io, Config $config)
30
    {
31 1
        $this->io = $io;
32 1
        $this->config = $config;
33 1
    }
34
35
    /**
36
     * @param Package\PackageInterface[] $packages
37
     * @param array $pluginConfig
38
     * @return void
39
     */
40
    public function download(array $packages, array $pluginConfig)
41
    {
42
        $mh = curl_multi_init();
43
        $unused = array();
44
        $maxConns = $pluginConfig['maxConnections'];
45
        for ($i = 0; $i < $maxConns; ++$i) {
46
            $unused[] = curl_init();
47
        }
48
49
        // @codeCoverageIgnoreStart
50
        if (function_exists('curl_share_init')) {
51
            $sh = curl_share_init();
52
            curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
53
54
            foreach ($unused as $ch) {
55
                curl_setopt($ch, CURLOPT_SHARE, $sh);
56
            }
57
        }
58
59
        if (function_exists('curl_multi_setopt')) {
60
            if ($pluginConfig['pipeline']) {
61
                curl_multi_setopt($mh, CURLMOPT_PIPELINING, true);
62
            }
63
        }
64
        // @codeCoverageIgnoreEnd
65
66
        $cachedir = rtrim($this->config->get('cache-files-dir'), '\/');
67
68
        $chFpMap = array();
69
        $running = 0; //ref type
70
        $remains = 0; //ref type
71
72
        $this->totalCnt = count($packages);
73
        $this->successCnt = 0;
74
        $this->failureCnt = 0;
75
        $this->io->write("    Prefetch start: <comment>success: $this->successCnt, failure: $this->failureCnt, total: $this->totalCnt</comment>");
76
77
        EVENTLOOP:
78
        // prepare curl resources
79
        while (count($unused) > 0 && count($packages) > 0) {
80
            $package = array_pop($packages);
81
            $filepath = $cachedir . DIRECTORY_SEPARATOR . static::getCacheKey($package);
82
            if (file_exists($filepath)) {
83
                ++$this->successCnt;
84
                continue;
85
            }
86
            $ch = array_pop($unused);
87
88
            // make file resource
89
            $chFpMap[(int)$ch] = $outputFile = new OutputFile($filepath);
90
91
            // make url
92
            $url = $package->getDistUrls();
93
            $url = $url[0];
94
            $host = parse_url($url, PHP_URL_HOST) ?: '';
95
            $request = new Aspects\HttpGetRequest($host, $url, $this->io);
96
            $request->verbose = $pluginConfig['verbose'];
97
            if (in_array($package->getName(), $pluginConfig['privatePackages'])) {
98
                $request->maybePublic = false;
99
            } else {
100
                $request->maybePublic = (bool)preg_match('%^(?:https|git)://github\.com%', $package->getSourceUrl());
101
            }
102
            $onPreDownload = Factory::getPreEvent($request);
103
            $onPreDownload->notify();
104
105
            $opts = $request->getCurlOpts();
106
            if ($pluginConfig['insecure']) {
107
                $opts[CURLOPT_SSL_VERIFYPEER] = false;
108
            }
109
            if (! empty($pluginConfig['userAgent'])) {
110
                $opts[CURLOPT_USERAGENT] = $pluginConfig['userAgent'];
111
            }
112
            if (! empty($pluginConfig['capath'])) {
113
                $opts[CURLOPT_CAPATH] = $pluginConfig['capath'];
114
            }
115
            unset($opts[CURLOPT_ENCODING]);
116
            unset($opts[CURLOPT_USERPWD]); // ParallelDownloader doesn't support private packages.
117
            curl_setopt_array($ch, $opts);
118
            curl_setopt($ch, CURLOPT_FILE, $outputFile->getPointer());
119
            curl_multi_add_handle($mh, $ch);
120
        }
121
122
        // wait for any event
123
        do {
124
            $runningBefore = $running;
125
            while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
126
127
            SELECT:
128
            $eventCount = curl_multi_select($mh, 5);
129
130
            if ($eventCount === -1) {
131
                usleep(200 * 1000);
132
                continue;
133
            }
134
135
            if ($eventCount === 0) {
136
                continue;
137
            }
138
139
            while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
140
141
            if ($running > 0 && $running === $runningBefore) {
142
                goto SELECT;
143
            }
144
145
            do {
146
                if ($raised = curl_multi_info_read($mh, $remains)) {
147
                    $ch = $raised['handle'];
148
                    $errno = curl_errno($ch);
149
                    $info = curl_getinfo($ch);
150
                    curl_setopt($ch, CURLOPT_FILE, STDOUT);
151
                    $index = (int)$ch;
152
                    $outputFile = $chFpMap[$index];
153
                    unset($chFpMap[$index]);
154
                    if (CURLE_OK === $errno && 200 === $info['http_code']) {
155
                        ++$this->successCnt;
156
                    } else {
157
                        ++$this->failureCnt;
158
                        $outputFile->setFailure();
159
                    }
160
                    unset($outputFile);
161
                    $this->io->write($this->makeDownloadingText($info['url']));
162
                    curl_multi_remove_handle($mh, $ch);
163
                    $unused[] = $ch;
164
                }
165
            } while ($remains > 0);
166
167
            if (count($packages) > 0) {
168
                goto EVENTLOOP;
169
            }
170
        } while ($running > 0);
171
172
        $this->io->write("    Finished: <comment>success: $this->successCnt, failure: $this->failureCnt, total: $this->totalCnt</comment>");
173
174
        foreach ($unused as $ch) {
175
            curl_close($ch);
176
        }
177
        curl_multi_close($mh);
178
    }
179
180
    /**
181
     * @param string $url
182
     * @return string
183
     */
184
    private function makeDownloadingText($url)
185
    {
186
        $request = new Aspects\HttpGetRequest('example.com', $url, $this->io);
187
        $request->query = array();
188
        return "    <comment>$this->successCnt/$this->totalCnt</comment>:    {$request->getURL()}";
189
    }
190
191
    public static function getCacheKey(Package\PackageInterface $p)
192
    {
193
        $distRef = $p->getDistReference();
194
        if (preg_match('{^[a-f0-9]{40}$}', $distRef)) {
195
            return "{$p->getName()}/$distRef.{$p->getDistType()}";
196
        }
197
198
        return "{$p->getName()}/{$p->getVersion()}-$distRef.{$p->getDistType()}";
199
    }
200
}
201