/
ProcessExecutor.php
470 lines (399 loc) · 12.8 KB
/
ProcessExecutor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Util;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\RuntimeException;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
/**
* @author Robert Schönthal <seroscho@googlemail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ProcessExecutor
{
const STATUS_QUEUED = 1;
const STATUS_STARTED = 2;
const STATUS_COMPLETED = 3;
const STATUS_FAILED = 4;
const STATUS_ABORTED = 5;
/** @var int */
protected static $timeout = 300;
/** @var bool */
protected $captureOutput = false;
/** @var string */
protected $errorOutput = '';
/** @var ?IOInterface */
protected $io;
/**
* @phpstan-var array<int, array<string, mixed>>
*/
private $jobs = array();
/** @var int */
private $runningJobs = 0;
/** @var int */
private $maxJobs = 10;
/** @var int */
private $idGen = 0;
/** @var bool */
private $allowAsync = false;
public function __construct(IOInterface $io = null)
{
$this->io = $io;
}
/**
* runs a process on the commandline
*
* @param string|list<string> $command the command to execute
* @param mixed $output the output will be written into this var if passed by ref
* if a callable is passed it will be used as output handler
* @param ?string $cwd the working directory
* @return int statuscode
*/
public function execute($command, &$output = null, $cwd = null)
{
if (func_num_args() > 1) {
return $this->doExecute($command, $cwd, false, $output);
}
return $this->doExecute($command, $cwd, false);
}
/**
* runs a process on the commandline in TTY mode
*
* @param string|list<string> $command the command to execute
* @param ?string $cwd the working directory
* @return int statuscode
*/
public function executeTty($command, $cwd = null)
{
if (Platform::isTty()) {
return $this->doExecute($command, $cwd, true);
}
return $this->doExecute($command, $cwd, false);
}
/**
* @param string|list<string> $command
* @param ?string $cwd
* @param bool $tty
* @param mixed $output
* @return int
*/
private function doExecute($command, $cwd, $tty, &$output = null)
{
$this->outputCommandRun($command, $cwd, false);
$this->captureOutput = func_num_args() > 3;
$this->errorOutput = '';
if (is_string($command)) {
$process = Process::fromShellCommandline($command, $cwd, null, null, static::getTimeout());
} else {
$process = new Process($command, $cwd, null, null, static::getTimeout());
}
if (!Platform::isWindows() && $tty) {
try {
$process->setTty(true);
} catch (RuntimeException $e) {
// ignore TTY enabling errors
}
}
$callback = is_callable($output) ? $output : array($this, 'outputHandler');
$process->run($callback);
if ($this->captureOutput && !is_callable($output)) {
$output = $process->getOutput();
}
$this->errorOutput = $process->getErrorOutput();
return $process->getExitCode();
}
/**
* starts a process on the commandline in async mode
*
* @param string|list<string> $command the command to execute
* @param string $cwd the working directory
* @return PromiseInterface
*/
public function executeAsync($command, $cwd = null)
{
if (!$this->allowAsync) {
throw new \LogicException('You must use the ProcessExecutor instance which is part of a Composer\Loop instance to be able to run async processes');
}
$job = array(
'id' => $this->idGen++,
'status' => self::STATUS_QUEUED,
'command' => $command,
'cwd' => $cwd,
);
$resolver = function ($resolve, $reject) use (&$job) {
$job['status'] = ProcessExecutor::STATUS_QUEUED;
$job['resolve'] = $resolve;
$job['reject'] = $reject;
};
$canceler = function () use (&$job) {
if ($job['status'] === ProcessExecutor::STATUS_QUEUED) {
$job['status'] = ProcessExecutor::STATUS_ABORTED;
}
if ($job['status'] !== ProcessExecutor::STATUS_STARTED) {
return;
}
$job['status'] = ProcessExecutor::STATUS_ABORTED;
try {
if (defined('SIGINT')) {
$job['process']->signal(SIGINT);
}
} catch (\Exception $e) {
// signal can throw in various conditions, but we don't care if it fails
}
$job['process']->stop(1);
throw new \RuntimeException('Aborted process');
};
$promise = new Promise($resolver, $canceler);
$promise = $promise->then(function () use (&$job) {
if ($job['process']->isSuccessful()) {
$job['status'] = ProcessExecutor::STATUS_COMPLETED;
} else {
$job['status'] = ProcessExecutor::STATUS_FAILED;
}
$this->markJobDone();
return $job['process'];
}, function ($e) use (&$job) {
$job['status'] = ProcessExecutor::STATUS_FAILED;
$this->markJobDone();
throw $e;
});
$this->jobs[$job['id']] = &$job;
if ($this->runningJobs < $this->maxJobs) {
$this->startJob($job['id']);
}
return $promise;
}
/**
* @param int $id
* @return void
*/
private function startJob($id)
{
$job = &$this->jobs[$id];
if ($job['status'] !== self::STATUS_QUEUED) {
return;
}
// start job
$job['status'] = self::STATUS_STARTED;
$this->runningJobs++;
$command = $job['command'];
$cwd = $job['cwd'];
$this->outputCommandRun($command, $cwd, true);
try {
if (is_string($command)) {
$process = Process::fromShellCommandline($command, $cwd, null, null, static::getTimeout());
} else {
$process = new Process($command, $cwd, null, null, static::getTimeout());
}
} catch (\Throwable $e) {
call_user_func($job['reject'], $e);
return;
}
$job['process'] = $process;
try {
$process->start();
} catch (\Throwable $e) {
call_user_func($job['reject'], $e);
return;
}
}
/**
* @param ?int $index job id
* @return void
*/
public function wait($index = null)
{
while (true) {
if (!$this->countActiveJobs($index)) {
return;
}
usleep(1000);
}
}
/**
* @internal
*
* @return void
*/
public function enableAsync()
{
$this->allowAsync = true;
}
/**
* @internal
*
* @param ?int $index job id
* @return int number of active (queued or started) jobs
*/
public function countActiveJobs($index = null)
{
// tick
foreach ($this->jobs as $job) {
if ($job['status'] === self::STATUS_STARTED) {
if (!$job['process']->isRunning()) {
call_user_func($job['resolve'], $job['process']);
}
}
if ($this->runningJobs < $this->maxJobs) {
if ($job['status'] === self::STATUS_QUEUED) {
$this->startJob($job['id']);
}
}
}
if (null !== $index) {
return $this->jobs[$index]['status'] < self::STATUS_COMPLETED ? 1 : 0;
}
$active = 0;
foreach ($this->jobs as $job) {
if ($job['status'] < self::STATUS_COMPLETED) {
$active++;
} else {
unset($this->jobs[$job['id']]);
}
}
return $active;
}
private function markJobDone(): void
{
$this->runningJobs--;
}
/**
* @param ?string $output
* @return string[]
*/
public function splitLines($output)
{
$output = trim((string) $output);
return $output === '' ? array() : Preg::split('{\r?\n}', $output);
}
/**
* Get any error output from the last command
*
* @return string
*/
public function getErrorOutput()
{
return $this->errorOutput;
}
/**
* @private
*
* @param Process::ERR|Process::OUT $type
* @param string $buffer
*
* @return void
*/
public function outputHandler($type, $buffer)
{
if ($this->captureOutput) {
return;
}
if (null === $this->io) {
echo $buffer;
return;
}
if (Process::ERR === $type) {
$this->io->writeErrorRaw($buffer, false);
} else {
$this->io->writeRaw($buffer, false);
}
}
/**
* @return int the timeout in seconds
*/
public static function getTimeout()
{
return static::$timeout;
}
/**
* @param int $timeout the timeout in seconds
* @return void
*/
public static function setTimeout($timeout)
{
static::$timeout = $timeout;
}
/**
* Escapes a string to be used as a shell argument.
*
* @param string|false|null $argument The argument that will be escaped
*
* @return string The escaped argument
*/
public static function escape($argument)
{
return self::escapeArgument($argument);
}
/**
* @param string|list<string> $command
*/
private function outputCommandRun($command, ?string $cwd, bool $async): void
{
if (null === $this->io || !$this->io->isDebug()) {
return;
}
$commandString = is_string($command) ? $command : implode(' ', array_map(self::class.'::escape', $command));
$safeCommand = Preg::replaceCallback('{://(?P<user>[^:/\s]+):(?P<password>[^@\s/]+)@}i', function ($m) {
// if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx) we obfuscate that
if (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) {
return '://***:***@';
}
if (Preg::isMatch('{^[a-f0-9]{12,}$}', $m['user'])) {
return '://***:***@';
}
return '://'.$m['user'].':***@';
}, $commandString);
$safeCommand = Preg::replace("{--password (.*[^\\\\]\') }", '--password \'***\' ', $safeCommand);
$this->io->writeError('Executing'.($async ? ' async' : '').' command ('.($cwd ?: 'CWD').'): '.$safeCommand);
}
/**
* Escapes a string to be used as a shell argument for Symfony Process.
*
* This method expects cmd.exe to be started with the /V:ON option, which
* enables delayed environment variable expansion using ! as the delimiter.
* If this is not the case, any escaped ^^!var^^! will be transformed to
* ^!var^! and introduce two unintended carets.
*
* Modified from https://github.com/johnstevenson/winbox-args
* MIT Licensed (c) John Stevenson <john-stevenson@blueyonder.co.uk>
*
* @param string|false|null $argument
*
* @return string
*/
private static function escapeArgument($argument)
{
if ('' === ($argument = (string) $argument)) {
return escapeshellarg($argument);
}
if (!Platform::isWindows()) {
return "'".str_replace("'", "'\\''", $argument)."'";
}
// New lines break cmd.exe command parsing
$argument = strtr($argument, "\n", ' ');
$quote = strpbrk($argument, " \t") !== false;
$argument = Preg::replace('/(\\\\*)"/', '$1$1\\"', $argument, -1, $dquotes);
$meta = $dquotes || Preg::isMatch('/%[^%]+%|![^!]+!/', $argument);
if (!$meta && !$quote) {
$quote = strpbrk($argument, '^&|<>()') !== false;
}
if ($quote) {
$argument = '"'.Preg::replace('/(\\\\*)$/', '$1$1', $argument).'"';
}
if ($meta) {
$argument = Preg::replace('/(["^&|<>()%])/', '^$1', $argument);
$argument = Preg::replace('/(!)/', '^^$1', $argument);
}
return $argument;
}
}