Completed
Push — master ( f3bb1e...e89e6e )
by Hiraku
03:06
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
            if (count($url) > 0) {
94
                $url = $url[0];
95
            } else {
96
                $url = $package->getDistUrl();
97
            }
98
            $host = parse_url($url, PHP_URL_HOST) ?: '';
99
            $request = new Aspects\HttpGetRequest($host, $url, $this->io);
100
            $request->verbose = $pluginConfig['verbose'];
101
            if (in_array($package->getName(), $pluginConfig['privatePackages'])) {
102
                $request->maybePublic = false;
103
            } else {
104
                $request->maybePublic = (bool)preg_match('%^(?:https|git)://github\.com%', $package->getSourceUrl());
105
            }
106
            $onPreDownload = Factory::getPreEvent($request);
107
            $onPreDownload->notify();
108
109
            $opts = $request->getCurlOpts();
110
            if ($pluginConfig['insecure']) {
111
                $opts[CURLOPT_SSL_VERIFYPEER] = false;
112
            }
113
            if (! empty($pluginConfig['userAgent'])) {
114
                $opts[CURLOPT_USERAGENT] = $pluginConfig['userAgent'];
115
            }
116
            if (! empty($pluginConfig['capath'])) {
117
                $opts[CURLOPT_CAPATH] = $pluginConfig['capath'];
118
            }
119
            unset($opts[CURLOPT_ENCODING]);
120
            unset($opts[CURLOPT_USERPWD]); // ParallelDownloader doesn't support private packages.
121
            curl_setopt_array($ch, $opts);
122
            curl_setopt($ch, CURLOPT_FILE, $outputFile->getPointer());
123
            curl_multi_add_handle($mh, $ch);
124
        }
125
126
        // wait for any event
127
        do {
128
            $runningBefore = $running;
129
            while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
130
131
            SELECT:
132
            $eventCount = curl_multi_select($mh, 5);
133
134
            if ($eventCount === -1) {
135
                usleep(200 * 1000);
136
                continue;
137
            }
138
139
            if ($eventCount === 0) {
140
                continue;
141
            }
142
143
            while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
144
145
            if ($running > 0 && $running === $runningBefore) {
146
                goto SELECT;
147
            }
148
149
            do {
150
                if ($raised = curl_multi_info_read($mh, $remains)) {
151
                    $ch = $raised['handle'];
152
                    $errno = curl_errno($ch);
153
                    $info = curl_getinfo($ch);
154
                    curl_setopt($ch, CURLOPT_FILE, STDOUT);
155
                    $index = (int)$ch;
156
                    $outputFile = $chFpMap[$index];
157
                    unset($chFpMap[$index]);
158
                    if (CURLE_OK === $errno && 200 === $info['http_code']) {
159
                        ++$this->successCnt;
160
                    } else {
161
                        ++$this->failureCnt;
162
                        $outputFile->setFailure();
163
                    }
164
                    unset($outputFile);
165
                    $this->io->write($this->makeDownloadingText($info['url']));
166
                    curl_multi_remove_handle($mh, $ch);
167
                    $unused[] = $ch;
168
                }
169
            } while ($remains > 0);
170
171
            if (count($packages) > 0) {
172
                goto EVENTLOOP;
173
            }
174
        } while ($running > 0);
175
176
        $this->io->write("    Finished: <comment>success: $this->successCnt, failure: $this->failureCnt, total: $this->totalCnt</comment>");
177
178
        foreach ($unused as $ch) {
179
            curl_close($ch);
180
        }
181
        curl_multi_close($mh);
182
    }
183
184
    /**
185
     * @param string $url
186
     * @return string
187
     */
188
    private function makeDownloadingText($url)
189
    {
190
        $request = new Aspects\HttpGetRequest('example.com', $url, $this->io);
191
        $request->query = array();
192
        return "    <comment>$this->successCnt/$this->totalCnt</comment>:    {$request->getURL()}";
193
    }
194
195
    public static function getCacheKey(Package\PackageInterface $p)
196
    {
197
        $distRef = $p->getDistReference();
198
        if (preg_match('{^[a-f0-9]{40}$}', $distRef)) {
199
            return "{$p->getName()}/$distRef.{$p->getDistType()}";
200
        }
201
202
        return "{$p->getName()}/{$p->getVersion()}-$distRef.{$p->getDistType()}";
203
    }
204
}
205