1 | <?php |
||
16 | class Client |
||
17 | { |
||
18 | /** |
||
19 | * @var OutputInterface |
||
20 | */ |
||
21 | private $output; |
||
22 | |||
23 | /** |
||
24 | * @var ProcessOutputPrinter |
||
25 | */ |
||
26 | private $pop; |
||
27 | |||
28 | /** |
||
29 | * @var bool |
||
30 | */ |
||
31 | private $multiplexing; |
||
32 | |||
33 | 6 | public function __construct(OutputInterface $output, ProcessOutputPrinter $pop, bool $multiplexing) |
|
34 | { |
||
35 | 6 | $this->output = $output; |
|
36 | 6 | $this->pop = $pop; |
|
37 | 6 | $this->multiplexing = $multiplexing; |
|
38 | 6 | } |
|
39 | |||
40 | /** |
||
41 | * @param Host $host |
||
42 | * @param string $command |
||
43 | * @param array $config |
||
44 | * @return string |
||
45 | * @throws RuntimeException |
||
46 | */ |
||
47 | public function run(Host $host, string $command, array $config = []) |
||
48 | { |
||
49 | $hostname = $host->getHostname(); |
||
50 | $defaults = [ |
||
51 | 'timeout' => 300, |
||
52 | 'tty' => false, |
||
53 | ]; |
||
54 | $config = array_merge($defaults, $config); |
||
55 | |||
56 | $this->pop->command($hostname, $command); |
||
57 | |||
58 | $sshArguments = $host->getSshArguments(); |
||
59 | $become = $host->has('become') ? 'sudo -u ' . $host->get('become') : ''; |
||
60 | |||
61 | // When tty need to be allocated, don't use multiplexing, |
||
62 | // and pass command without bash allocation on remote host. |
||
63 | if ($config['tty']) { |
||
64 | $this->output->write(''); // Notify OutputWatcher |
||
65 | $sshArguments = $sshArguments->withFlag('-tt'); |
||
66 | $command = escapeshellarg($command); |
||
67 | |||
68 | $ssh = "ssh $sshArguments $host $command"; |
||
69 | $process = new Process($ssh); |
||
70 | $process |
||
71 | ->setTimeout($config['timeout']) |
||
72 | ->setTty(true) |
||
73 | ->mustRun(); |
||
74 | |||
75 | return $process->getOutput(); |
||
76 | } |
||
77 | |||
78 | if ($host->isMultiplexing() === null ? $this->multiplexing : $host->isMultiplexing()) { |
||
79 | $sshArguments = $this->initMultiplexing($host); |
||
80 | } |
||
81 | |||
82 | $ssh = "ssh $sshArguments $host $become 'bash -s; printf \"[exit_code:%s]\" $?;'"; |
||
83 | |||
84 | $process = new Process($ssh); |
||
85 | $process |
||
86 | ->setInput($command) |
||
87 | ->setTimeout($config['timeout']); |
||
88 | |||
89 | $process->run($this->pop->callback($hostname)); |
||
90 | |||
91 | $output = $this->pop->filterOutput($process->getOutput()); |
||
92 | $exitCode = $this->parseExitStatus($process); |
||
93 | |||
94 | if ($exitCode !== 0) { |
||
95 | throw new RuntimeException( |
||
96 | $hostname, |
||
97 | $command, |
||
98 | $exitCode, |
||
99 | $output, |
||
100 | $process->getErrorOutput() |
||
101 | ); |
||
102 | } |
||
103 | |||
104 | return $output; |
||
105 | } |
||
106 | |||
107 | private function parseExitStatus(Process $process) |
||
119 | |||
120 | private function initMultiplexing(Host $host) |
||
121 | { |
||
142 | } |
||
143 |