Completed
Push — master ( 1f6bdc...410881 )
by Hiraku
02:16
created

ParallelDownloader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
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
        do {
77
            // prepare curl resources
78
            while (count($unused) > 0 && count($packages) > 0) {
79
                $package = array_pop($packages);
80
                $filepath = $cachedir . DIRECTORY_SEPARATOR . static::getCacheKey($package);
81
                if (file_exists($filepath)) {
82
                    ++$this->successCnt;
83
                    continue;
84
                }
85
                $ch = array_pop($unused);
86
87
                // make file resource
88
                $chFpMap[(int)$ch] = $outputFile = new OutputFile($filepath);
89
90
                // make url
91
                $url = $package->getDistUrl();
92
                $host = parse_url($url, PHP_URL_HOST) ?: '';
93
                $request = new Aspects\HttpGetRequest($host, $url, $this->io);
94
                $request->verbose = $pluginConfig['verbose'];
95
                if (in_array($package->getName(), $pluginConfig['privatePackages'])) {
96
                    $request->maybePublic = false;
97
                } else {
98
                    $request->maybePublic = (bool)preg_match('%^(?:https|git)://github\.com%', $package->getSourceUrl());
99
                }
100
                $onPreDownload = Factory::getPreEvent($request);
101
                $onPreDownload->notify();
102
103
                $opts = $request->getCurlOpts();
104
                if ($pluginConfig['insecure']) {
105
                    $opts[CURLOPT_SSL_VERIFYPEER] = false;
106
                }
107
                if (! empty($pluginConfig['userAgent'])) {
108
                    $opts[CURLOPT_USERAGENT] = $pluginConfig['userAgent'];
109
                }
110
                if (! empty($pluginConfig['capath'])) {
111
                    $opts[CURLOPT_CAPATH] = $pluginConfig['capath'];
112
                }
113
                unset($opts[CURLOPT_ENCODING]);
114
                unset($opts[CURLOPT_USERPWD]); // ParallelDownloader doesn't support private packages.
115
                curl_setopt_array($ch, $opts);
116
                curl_setopt($ch, CURLOPT_FILE, $outputFile->getPointer());
117
                curl_multi_add_handle($mh, $ch);
118
            }
119
120
            // wait for any event
121
            do {
122
                // start multi download
123
                while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
124
                $runningBefore = $running;
125
126
                $eventCount = curl_multi_select($mh, 5);
127
128
                if ($eventCount === -1) {
129
                    usleep(200 * 1000);
130
                    continue;
131
                }
132
133
                if ($eventCount === 0) {
134
                    continue;
135
                }
136
137
                while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
138
139
                if ($running === $runningBefore) {
140
                    continue;
141
                }
142
143
                do {
144
                    if ($raised = curl_multi_info_read($mh, $remains)) {
145
                        $ch = $raised['handle'];
146
                        $errno = curl_errno($ch);
147
                        $info = curl_getinfo($ch);
148
                        curl_setopt($ch, CURLOPT_FILE, STDOUT);
149
                        $index = (int)$ch;
150
                        $outputFile = $chFpMap[$index];
151
                        unset($chFpMap[$index]);
152
                        if (CURLE_OK === $errno && 200 === $info['http_code']) {
153
                            ++$this->successCnt;
154
                        } else {
155
                            ++$this->failureCnt;
156
                            $outputFile->setFailure();
157
                        }
158
                        unset($outputFile);
159
                        $this->io->write($this->makeDownloadingText($info['url']));
160
                        curl_multi_remove_handle($mh, $ch);
161
                        $unused[] = $ch;
162
                    }
163
                } while ($remains > 0);
164
165
                if (count($packages) > 0) {
166
                    break;
167
                }
168
            } while ($running);
169
        } while (count($packages) > 0);
170
        $this->io->write("    Finished: <comment>success: $this->successCnt, failure: $this->failureCnt, total: $this->totalCnt</comment>");
171
172
        foreach ($unused as $ch) {
173
            curl_close($ch);
174
        }
175
        curl_multi_close($mh);
176
    }
177
178
    /**
179
     * @param string $url
180
     * @return string
181
     */
182
    private function makeDownloadingText($url)
183
    {
184
        $request = new Aspects\HttpGetRequest('example.com', $url, $this->io);
185
        $request->query = array();
186
        return "    <comment>$this->successCnt/$this->totalCnt</comment>:    {$request->getURL()}";
187
    }
188
189
    public static function getCacheKey(Package\PackageInterface $p)
190
    {
191
        $distRef = $p->getDistReference();
192
        if (preg_match('{^[a-f0-9]{40}$}', $distRef)) {
193
            return "{$p->getName()}/$distRef.{$p->getDistType()}";
194
        }
195
196
        return "{$p->getName()}/{$p->getVersion()}-$distRef.{$p->getDistType()}";
197
    }
198
}
199