Completed
Pull Request — master (#42)
by Hiraku
02:14
created

ParallelDownloader   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 3.77%

Importance

Changes 22
Bugs 7 Features 1
Metric Value
wmc 32
c 22
b 7
f 1
lcom 1
cbo 7
dl 0
loc 189
ccs 4
cts 106
cp 0.0377
rs 9.6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A makeDownloadingText() 0 6 1
A getCacheKey() 0 9 2
A __construct() 0 5 1
F download() 0 142 28
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 as CConfig;
12
13
/**
14
 *
15
 */
16
class ParallelDownloader
17
{
18
    /** @var IO/IOInterface */
19
    protected $io;
20
21
    /** @var CConfig */
22
    protected $config;
23
24
    /** @var int */
25
    protected $totalCnt = 0;
26
    protected $successCnt = 0;
27
    protected $skippedCnt = 0;
28
    protected $failureCnt = 0;
29
30 1
    public function __construct(IO\IOInterface $io, CConfig $config)
31
    {
32 1
        $this->io = $io;
33 1
        $this->config = $config;
34 1
    }
35
36
    /**
37
     * @param Package\PackageInterface[] $packages
38
     * @param array $pluginConfig
39
     * @return void
40
     */
41
    public function download(array $packages, array $pluginConfig)
42
    {
43
        $mh = curl_multi_init();
44
        $unused = array();
45
        $maxConns = $pluginConfig['maxConnections'];
46
        for ($i = 0; $i < $maxConns; ++$i) {
47
            $unused[] = curl_init();
48
        }
49
50
        // @codeCoverageIgnoreStart
51
        if (function_exists('curl_share_init')) {
52
            $sh = curl_share_init();
53
            curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
54
55
            foreach ($unused as $ch) {
56
                curl_setopt($ch, CURLOPT_SHARE, $sh);
57
            }
58
        }
59
60
        if (function_exists('curl_multi_setopt')) {
61
            if ($pluginConfig['pipeline']) {
62
                curl_multi_setopt($mh, CURLMOPT_PIPELINING, true);
63
            }
64
        }
65
        // @codeCoverageIgnoreEnd
66
67
        $cachedir = rtrim($this->config->get('cache-files-dir'), '\/');
68
69
        $chFpMap = array();
70
        $running = 0; //ref type
71
        $remains = 0; //ref type
72
73
        $this->totalCnt = count($packages);
74
        $this->successCnt = 0;
75
        $this->skippedCnt = 0;
76
        $this->failureCnt = 0;
77
        $this->io->write("    Prefetch start: total: $this->totalCnt</comment>");
78
79
        EVENTLOOP:
80
        // prepare curl resources
81
        while (count($unused) > 0 && count($packages) > 0) {
82
            $package = array_pop($packages);
83
            $filepath = $cachedir . DIRECTORY_SEPARATOR . static::getCacheKey($package);
84
            if (file_exists($filepath)) {
85
                ++$this->skippedCnt;
86
                continue;
87
            }
88
            $ch = array_pop($unused);
89
90
            // make file resource
91
            $chFpMap[(int)$ch] = $outputFile = new OutputFile($filepath);
92
93
            // make url
94
            $url = $package->getDistUrl();
95
            if (! $url) {
96
                ++$this->skippedCnt;
97
                continue;
98
            }
99
            if ($package->getDistMirrors()) {
100
                $url = current($package->getDistUrls());
101
            }
102
            $host = parse_url($url, PHP_URL_HOST) ?: '';
103
            $request = new Aspects\HttpGetRequest($host, $url, $this->io);
104
            $request->verbose = $pluginConfig['verbose'];
105
            if (in_array($package->getName(), $pluginConfig['privatePackages'])) {
106
                $request->maybePublic = false;
107
            } else {
108
                $request->maybePublic = (bool)preg_match('%^(?:https|git)://github\.com%', $package->getSourceUrl());
109
            }
110
            $onPreDownload = Factory::getPreEvent($request);
111
            $onPreDownload->notify();
112
113
            $opts = $request->getCurlOpts();
114
            if ($pluginConfig['insecure']) {
115
                $opts[CURLOPT_SSL_VERIFYPEER] = false;
116
            }
117
            if (! empty($pluginConfig['userAgent'])) {
118
                $opts[CURLOPT_USERAGENT] = $pluginConfig['userAgent'];
119
            }
120
            if (! empty($pluginConfig['capath'])) {
121
                $opts[CURLOPT_CAPATH] = $pluginConfig['capath'];
122
            }
123
            unset($opts[CURLOPT_ENCODING]);
124
            unset($opts[CURLOPT_USERPWD]); // ParallelDownloader doesn't support private packages.
125
            curl_setopt_array($ch, $opts);
126
            curl_setopt($ch, CURLOPT_FILE, $outputFile->getPointer());
127
            curl_multi_add_handle($mh, $ch);
128
        }
129
130
        // wait for any event
131
        do {
132
            $runningBefore = $running;
133
            while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
134
135
            SELECT:
136
            $eventCount = curl_multi_select($mh, 5);
137
138
            if ($eventCount === -1) {
139
                usleep(200 * 1000);
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
                        $outputFile->setSuccess();
161
                    } else {
162
                        ++$this->failureCnt;
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, skipped: $this->skippedCnt, 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