1
|
|
|
<?php |
2
|
|
|
/* (c) Anton Medvedev <[email protected]> |
3
|
|
|
* |
4
|
|
|
* For the full copyright and license information, please view the LICENSE |
5
|
|
|
* file that was distributed with this source code. |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace Deployer\Component\ProcessRunner; |
9
|
|
|
|
10
|
|
|
use Deployer\Deployer; |
11
|
|
|
use Deployer\Component\ProcessRunner\Printer; |
12
|
|
|
use Deployer\Exception\RunException; |
13
|
|
|
use Deployer\Host\Host; |
14
|
|
|
use Deployer\Logger\Logger; |
15
|
|
|
use Symfony\Component\Process\Exception\ProcessFailedException; |
16
|
|
|
use Symfony\Component\Process\Process; |
17
|
|
|
|
18
|
|
|
class ProcessRunner |
19
|
|
|
{ |
20
|
|
|
private $pop; |
21
|
|
|
private $logger; |
22
|
|
|
|
23
|
11 |
|
public function __construct(Printer $pop, Logger $logger) |
24
|
|
|
{ |
25
|
11 |
|
$this->pop = $pop; |
26
|
11 |
|
$this->logger = $logger; |
27
|
11 |
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Runs a command, consider deployer global configs (timeout,...) |
31
|
|
|
* |
32
|
|
|
* @param Host $host |
33
|
|
|
* @param string $command |
34
|
|
|
* @param array $config |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
* |
38
|
|
|
*/ |
39
|
11 |
|
public function run(Host $host, string $command, array $config = []): string |
40
|
|
|
{ |
41
|
|
|
$defaults = [ |
42
|
11 |
|
'timeout' => $host->get('default_timeout', 300), |
43
|
|
|
'idle_timeout' => null, |
44
|
11 |
|
'cwd' => defined('DEPLOYER_ROOT') ? DEPLOYER_ROOT : null, |
45
|
|
|
'tty' => false, |
46
|
|
|
]; |
47
|
11 |
|
$config = array_merge($defaults, $config); |
48
|
|
|
|
49
|
11 |
|
$this->pop->command($host, $command); |
50
|
|
|
|
51
|
11 |
|
$terminalOutput = $this->pop->callback($host); |
52
|
|
|
$callback = function ($type, $buffer) use ($host, $terminalOutput) { |
53
|
10 |
|
$this->logger->printBuffer($host, $type, $buffer); |
54
|
10 |
|
$terminalOutput($type, $buffer); |
55
|
11 |
|
}; |
56
|
|
|
|
57
|
11 |
|
$command = str_replace('%secret%', $config['secret'] ?? '', $command); |
58
|
11 |
|
$command = str_replace('%sudo_pass%', $config['sudo_pass'] ?? '', $command); |
59
|
|
|
|
60
|
11 |
|
$process = Process::fromShellCommandline($command) |
61
|
11 |
|
->setTimeout($config['timeout']) |
62
|
11 |
|
->setIdleTimeout($config['idle_timeout']) |
63
|
11 |
|
->setTty($config['tty']); |
64
|
|
|
|
65
|
11 |
|
if ($config['cwd'] !== null) { |
66
|
|
|
$process->setWorkingDirectory($config['cwd']); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
try { |
70
|
11 |
|
$process->mustRun($callback); |
71
|
11 |
|
return $process->getOutput(); |
72
|
2 |
|
} catch (ProcessFailedException $exception) { |
73
|
2 |
|
throw new RunException( |
74
|
2 |
|
$host, |
75
|
|
|
$command, |
76
|
2 |
|
$process->getExitCode(), |
77
|
2 |
|
$process->getOutput(), |
78
|
2 |
|
$process->getErrorOutput() |
79
|
|
|
); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|