-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathDeployer.php
More file actions
executable file
·349 lines (309 loc) · 10.8 KB
/
Deployer.php
File metadata and controls
executable file
·349 lines (309 loc) · 10.8 KB
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
<?php
declare(strict_types=1);
/* (c) Anton Medvedev <anton@medv.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Deployer;
use Deployer\Collection\Collection;
use Deployer\Command\BlackjackCommand;
use Deployer\Command\ConfigCommand;
use Deployer\Command\InitCommand;
use Deployer\Command\MainCommand;
use Deployer\Command\RunCommand;
use Deployer\Command\SshCommand;
use Deployer\Command\TreeCommand;
use Deployer\Command\WorkerCommand;
use Deployer\Component\Pimple\Container;
use Deployer\Exception\SchemaException;
use Deployer\Executor\Master;
use Deployer\Host\Host;
use Deployer\Host\HostCollection;
use Deployer\Host\Localhost;
use Deployer\Import\Import;
use Deployer\Logger\Handler\FileHandler;
use Deployer\Logger\Handler\NullHandler;
use Deployer\Logger\Logger;
use Deployer\ProcessRunner\ProcessRunner;
use Deployer\Selector\Selector;
use Deployer\Ssh\SshClient;
use Deployer\Task\ScriptManager;
use Deployer\Task\TaskCollection;
use Deployer\Utility\Httpie;
use Deployer\Utility\Rsync;
use Symfony\Component\Console;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
/**
* @property Application $console
* @property InputInterface $input
* @property OutputInterface $output
* @property Task\TaskCollection|Task\Task[] $tasks
* @property HostCollection|Host[] $hosts
* @property Configuration $config
* @property Rsync $rsync
* @property SshClient $sshClient
* @property ProcessRunner $processRunner
* @property Task\ScriptManager $scriptManager
* @property Selector $selector
* @property Master $master
* @property Logger $logger
* @property Collection $fail
* @property InputDefinition $inputDefinition
* @property Import $importer
*/
class Deployer extends Container
{
private static ?self $instance = null;
public function __construct(Application $console)
{
parent::__construct();
/******************************
* Console *
******************************/
$console->getDefinition()->addOption(
new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'Recipe file path'),
);
$this['console'] = function () use ($console) {
return $console;
};
$this['input'] = function () {
throw new \RuntimeException('Uninitialized "input" in Deployer container.');
};
$this['output'] = function () {
throw new \RuntimeException('Uninitialized "output" in Deployer container.');
};
$this['inputDefinition'] = function () {
return new InputDefinition();
};
$this['questionHelper'] = function () {
return $this->getHelper('question');
};
/******************************
* Config *
******************************/
$this['config'] = function () {
return new Configuration();
};
// -l act as if it had been invoked as a login shell (i.e. source ~/.profile file)
// -s commands are read from the standard input (no arguments should remain after this option)
$this->config['shell'] = function () {
if (currentHost() instanceof Localhost) {
return 'bash -s'; // Non-login shell for localhost.
}
return 'bash -ls';
};
$this->config['forward_agent'] = true;
$this->config['ssh_multiplexing'] = true;
/******************************
* Core *
******************************/
$this['logHandler'] = function () {
return !empty($this['log'])
? new FileHandler($this['log'])
: new NullHandler();
};
$this['logger'] = function ($c) {
return new Logger($c['output'], $this['logHandler']);
};
$this['sshClient'] = function ($c) {
return new SshClient($c['output'], $c['logger']);
};
$this['rsync'] = function ($c) {
return new Rsync($c['output'], $c['logger']);
};
$this['processRunner'] = function ($c) {
return new ProcessRunner($c['logger']);
};
$this['tasks'] = function () {
return new TaskCollection();
};
$this['hosts'] = function () {
return new HostCollection();
};
$this['scriptManager'] = function ($c) {
return new ScriptManager($c['tasks']);
};
$this['selector'] = function ($c) {
return new Selector($c['hosts']);
};
$this['fail'] = function () {
return new Collection();
};
$this['master'] = function ($c) {
return new Master(
$c['hosts'],
$c['input'],
$c['output'],
$c['logger'],
);
};
$this['importer'] = function () {
return new Import();
};
self::$instance = $this;
}
public static function get(): self
{
if (self::$instance === null) {
throw new \RuntimeException('Deployer is not initialized.');
}
return self::$instance;
}
public static function hasInstance(): bool
{
return self::$instance !== null;
}
/**
* @internal For tests that need a clean Deployer singleton between cases.
*/
public static function resetInstance(): void
{
self::$instance = null;
}
public function init(): void
{
$this->addTaskCommands();
$this->getConsole()->addCommand(new BlackjackCommand());
$this->getConsole()->addCommand(new ConfigCommand($this));
$this->getConsole()->addCommand(new WorkerCommand($this));
$this->getConsole()->addCommand(new InitCommand());
$this->getConsole()->addCommand(new TreeCommand($this));
$this->getConsole()->addCommand(new SshCommand($this));
$this->getConsole()->addCommand(new RunCommand($this));
}
/**
* Transform tasks to console commands.
*/
public function addTaskCommands(): void
{
foreach ($this->tasks as $name => $task) {
$command = new MainCommand($name, $task->getDescription(), $this);
$command->setHidden($task->isHidden());
$this->getConsole()->addCommand($command);
}
}
public function __get(string $name): mixed
{
if (isset($this[$name])) {
return $this[$name];
} else {
throw new \InvalidArgumentException("Property \"$name\" does not exist.");
}
}
public function __set(string $name, mixed $value): void
{
$this[$name] = $value;
}
public function getConsole(): Application
{
return $this['console'];
}
public function getHelper(string $name): Console\Helper\HelperInterface
{
return $this->getConsole()->getHelperSet()->get($name);
}
public static function run(string $version, ?string $deployFile): void
{
if (str_contains($version, 'master')) {
// Get version from composer.lock
$lockFile = __DIR__ . '/../../../../composer.lock';
if (file_exists($lockFile)) {
$content = file_get_contents($lockFile);
$json = json_decode($content);
foreach ($json->packages as $package) {
if ($package->name === 'deployer/deployer') {
$version = $package->version;
}
}
}
}
// Version must be without "v" prefix.
// Incorrect: v7.0.0
// Correct: 7.0.0
// But deployphp/deployer uses tags with "v", and it gets passed to
// the composer.json file. Let's manually remove it from the version.
if (preg_match("/^v/", $version)) {
$version = substr($version, 1);
}
if (!defined('DEPLOYER_VERSION')) {
define('DEPLOYER_VERSION', $version);
}
$input = new ArgvInput();
$output = new ConsoleOutput();
try {
$console = new Application('Deployer', $version);
$deployer = new self($console);
// Import recipe file
if (is_readable($deployFile ?? '')) {
$deployer->importer->import($deployFile);
}
$deployer->init();
$console->run($input, $output);
} catch (Throwable $exception) {
if (str_contains("$input", "-vvv")) {
$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
}
self::printException($output, $exception);
exit(1);
}
}
public static function printException(OutputInterface $output, Throwable $exception): void
{
if ($exception instanceof SchemaException) {
$output->writeln([
"<fg=white;bg=red> Schema error </> {$exception->getMessage()}",
]);
} else {
$class = get_class($exception);
$file = basename($exception->getFile());
$output->writeln([
"<fg=white;bg=red> {$class} </> <comment>in {$file} on line {$exception->getLine()}:</>",
"",
implode("\n", array_map(function ($line) {
return " " . $line;
}, explode("\n", $exception->getMessage()))),
"",
]);
if ($output->isDebug()) {
$output->writeln($exception->getTraceAsString());
}
}
if ($exception->getPrevious()) {
self::printException($output, $exception->getPrevious());
}
}
public static function isWorker(): bool
{
return defined('MASTER_ENDPOINT');
}
/**
* @return array|bool|string
*/
public static function masterCall(Host $host, string $func, mixed ...$arguments): mixed
{
// As request to master will stop master permanently, wait a little bit
// in order for ticker gather worker outputs and print it to user.
usleep(100_000); // Sleep 100ms.
return Httpie::post(MASTER_ENDPOINT . '/proxy')
->noTimeout()
->bearerToken(MASTER_TOKEN)
->jsonBody([
'host' => $host->getAlias(),
'func' => $func,
'arguments' => $arguments,
])
->sendJson();
}
public static function isPharArchive(): bool
{
return str_starts_with(__FILE__, 'phar:');
}
}