-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDeployRunner.php
More file actions
412 lines (361 loc) · 15 KB
/
DeployRunner.php
File metadata and controls
412 lines (361 loc) · 15 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
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
<?php
namespace Hypernode\Deploy;
use Deployer\Deployer;
use Deployer\Exception\Exception;
use Deployer\Exception\GracefulShutdownException;
use Deployer\Host\Host;
use Deployer\Task\Task;
use Hypernode\Deploy\Brancher\BrancherHypernodeManager;
use Hypernode\Deploy\Deployer\RecipeLoader;
use Hypernode\Deploy\Deployer\Task\ConfigurableTaskInterface;
use Hypernode\Deploy\Deployer\Task\TaskFactory;
use Hypernode\Deploy\Exception\CreateBrancherHypernodeFailedException;
use Hypernode\Deploy\Exception\InvalidConfigurationException;
use Hypernode\Deploy\Exception\TimeoutException;
use Hypernode\Deploy\Exception\ValidationException;
use Hypernode\DeployConfiguration\Configurable\ServerRoleConfigurableInterface;
use Hypernode\DeployConfiguration\Configurable\StageConfigurableInterface;
use Hypernode\DeployConfiguration\Configuration;
use Hypernode\DeployConfiguration\Server;
use Hypernode\DeployConfiguration\Stage;
use Hypernode\DeployConfiguration\TaskConfigurationInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
use function Deployer\host;
use function Deployer\localhost;
use function Deployer\run;
class DeployRunner
{
public const TASK_BUILD = 'build';
public const TASK_DEPLOY = 'deploy';
public const DEFAULT_BRANCHER_TIMEOUT = 1500;
public const DEFAULT_BRANCHER_REACHABILITY_CHECK_COUNT = 6;
public const DEFAULT_BRANCHER_REACHABILITY_CHECK_INTERVAL = 10;
private TaskFactory $taskFactory;
private InputInterface $input;
private LoggerInterface $log;
private RecipeLoader $recipeLoader;
private DeployerLoader $deployerLoader;
private ConfigurationLoader $configurationLoader;
private BrancherHypernodeManager $brancherHypernodeManager;
/**
* Registered brancher Hypernodes to stop/cancel after running.
*
* @var string[]
*/
private array $brancherHypernodesRegistered = [];
private array $deployedHostnames = [];
private string $deployedStage = '';
public function __construct(
TaskFactory $taskFactory,
InputInterface $input,
LoggerInterface $log,
RecipeLoader $recipeLoader,
DeployerLoader $deployerLoader,
ConfigurationLoader $configurationLoader,
BrancherHypernodeManager $brancherHypernodeManager
) {
$this->taskFactory = $taskFactory;
$this->input = $input;
$this->log = $log;
$this->recipeLoader = $recipeLoader;
$this->deployerLoader = $deployerLoader;
$this->configurationLoader = $configurationLoader;
$this->brancherHypernodeManager = $brancherHypernodeManager;
}
/**
* @throws GracefulShutdownException
* @throws Throwable
* @throws Exception
*/
public function run(
OutputInterface $output,
string $stage,
string $task,
bool $configureBuildStage,
bool $configureServers,
bool $reuseBrancher
): int {
$deployer = $this->deployerLoader->getOrCreateInstance($output);
try {
$this->prepare($configureBuildStage, $configureServers, $stage, $reuseBrancher);
} catch (InvalidConfigurationException | ValidationException $e) {
$output->write($e->getMessage());
return 1;
}
return $this->runStage($deployer, $stage, $task);
}
/**
* Prepare deploy runner before running stage
*
* @throws Exception
* @throws GracefulShutdownException
* @throws InvalidConfigurationException
* @throws Throwable
*/
public function prepare(
bool $configureBuildStage,
bool $configureServers,
string $stage,
bool $reuseBrancher
): void {
$this->recipeLoader->load('common.php');
$tasks = $this->taskFactory->loadAll();
$config = $this->configurationLoader->load(
$this->input->getOption('file') ?: 'deploy.php'
);
$config->setLogger($this->log);
if ($configureBuildStage) {
$this->initializeBuildStage($config);
}
if ($configureServers) {
$this->configureServers($config, $stage, $reuseBrancher);
}
foreach ($tasks as $task) {
$task->configure($config);
$this->log->debug("Running configure for task " . get_class($task));
if ($task instanceof ConfigurableTaskInterface) {
$this->initializeConfigurableTask($task, $config);
}
}
foreach ($config->getPostInitializeCallbacks() as $callback) {
if (!is_callable($callback)) {
continue;
}
call_user_func($callback);
}
foreach ($tasks as $task) {
$task->register();
}
}
/**
* Configure deploy tasks based on specific configuration in Hypernode Deploy configuration
* @throws InvalidConfigurationException
*/
private function initializeConfigurableTask(ConfigurableTaskInterface $task, Configuration $mainConfig): void
{
$configurations = array_merge(
$mainConfig->getPlatformConfigurations(),
$mainConfig->getAfterDeployTasks()
);
foreach ($configurations as $taskConfig) {
if ($task->supports($taskConfig)) {
$deployerTask = $task->configureWithTaskConfig($taskConfig);
if ($deployerTask) {
$this->configureDeployerTask($deployerTask, $taskConfig);
}
}
}
}
private function configureDeployerTask(Task $deployerTask, TaskConfigurationInterface $taskConfig): void
{
$roles = $taskConfig instanceof ServerRoleConfigurableInterface
? $taskConfig->getServerRoles()
: [];
$stage = $taskConfig instanceof StageConfigurableInterface && $taskConfig->getStage()
? $taskConfig->getStage()->getName()
: null;
if ($roles) {
if ($stage) {
$deployerTask->select(
sprintf(
"stage={$stage}&roles=%s",
implode(",stage={$stage}&roles=", $roles)
)
);
} else {
$deployerTask->select('roles=' . implode(',roles=', $roles));
}
} elseif ($stage) {
$deployerTask->select("stage={$stage}");
}
}
private function configureServers(Configuration $config, string $stage, bool $reuseBrancher): void
{
foreach ($config->getStages() as $configStage) {
if ($configStage->getName() !== $stage) {
continue;
}
foreach ($configStage->getServers() as $server) {
$this->configureStageServer($configStage, $server, $config, $reuseBrancher);
}
}
}
private function configureStageServer(
Stage $stage,
Server $server,
Configuration $config,
bool $reuseBrancher
): void {
$this->maybeConfigureBrancherServer($server, $reuseBrancher);
$host = host($stage->getName() . ':' . $server->getHostname());
$host->setHostname($server->getHostname());
$host->setPort(22);
$host->set('labels', ['stage' => $stage->getName(), 'roles' => $server->getRoles()]);
$host->setRemoteUser('app');
$host->setForwardAgent(true);
$host->setSshMultiplexing(true);
$host->set('roles', $server->getRoles());
$host->set('domain', $stage->getDomain());
$host->set('stage', $stage->getName());
$host->set('deploy_path', function () {
// Ensure directory exists before returning it
run('mkdir -p ~/apps/{{domain}}/shared');
return run('realpath ~/apps/{{domain}}');
});
$host->set('current_path', '{{deploy_path}}/current');
$host->set('nginx_release_path', '{{release_path}}/.hypernode/nginx');
$host->set('nginx_current_path', '{{current_path}}/.hypernode/nginx');
$host->set('supervisor_release_path', '{{release_path}}/.hypernode/supervisor');
$host->set('supervisor_current_path', '{{current_path}}/.hypernode/supervisor');
$host->set('varnish_release_path', '{{release_path}}/.hypernode/varnish');
$host->set('varnish_current_path', '{{current_path}}/.hypernode/varnish');
$host->set('configuration_stage', $stage);
$host->set('writable_mode', 'chmod');
foreach ($server->getOptions() as $optionName => $optionValue) {
$host->set($optionName, $optionValue);
}
$sshOptions = [];
foreach ($server->getSshOptions() as $optionName => $optionValue) {
$sshOptions[] = "-o $optionName=$optionValue";
}
if ($sshOptions) {
$host->setSshArguments($sshOptions);
}
foreach ($config->getVariables() as $key => $value) {
$this->log->debug(
sprintf('Setting var "%s" to %s for stage "%s"', $key, json_encode($value), $stage->getName())
);
$host->set($key, $value);
}
foreach ($config->getVariables('deploy') as $key => $value) {
$this->log->debug(
sprintf('Setting var "%s" to %s for stage "%s"', $key, json_encode($value), $stage->getName())
);
$host->set($key, $value);
}
}
private function maybeConfigureBrancherServer(Server $server, bool $reuseBrancher): void
{
$serverOptions = $server->getOptions();
$isBrancher = $serverOptions[Server::OPTION_HN_BRANCHER] ?? false;
$parentApp = $serverOptions[Server::OPTION_HN_PARENT_APP] ?? null;
if ($isBrancher && $parentApp) {
$settings = $serverOptions[Server::OPTION_HN_BRANCHER_SETTINGS] ?? [];
$labels = $serverOptions[Server::OPTION_HN_BRANCHER_LABELS] ?? [];
$timeout = $serverOptions[Server::OPTION_HN_BRANCHER_TIMEOUT] ?? self::DEFAULT_BRANCHER_TIMEOUT;
$reachabilityCheckCount = $serverOptions[Server::OPTION_HN_BRANCHER_REACHABILITY_CHECK_COUNT] ?? self::DEFAULT_BRANCHER_REACHABILITY_CHECK_COUNT;
$reachabilityCheckInterval = $serverOptions[Server::OPTION_HN_BRANCHER_REACHABILITY_CHECK_INTERVAL] ?? self::DEFAULT_BRANCHER_REACHABILITY_CHECK_INTERVAL;
$this->log->info(sprintf('Creating an brancher Hypernode based on %s.', $parentApp));
if ($settings) {
$this->log->info(
sprintf('Settings to be applied: [%s].', implode(', ', $settings))
);
}
if ($labels) {
$this->log->info(
sprintf('Labels to be applied: [%s].', implode(', ', $labels))
);
}
$data = $settings;
$data['labels'] = $labels;
if ($reuseBrancher && $brancherApp = $this->brancherHypernodeManager->reuseExistingBrancherHypernode($parentApp, $labels)) {
$this->log->info(sprintf('Found existing brancher Hypernode, name is %s.', $brancherApp));
} else {
$brancherApp = $this->brancherHypernodeManager->createForHypernode($parentApp, $data);
$this->log->info(sprintf('Successfully requested brancher Hypernode, name is %s.', $brancherApp));
$this->brancherHypernodesRegistered[] = $brancherApp;
}
try {
$this->log->info('Waiting for brancher Hypernode to become available...');
$this->brancherHypernodeManager->waitForAvailability(
$brancherApp,
$timeout,
$reachabilityCheckCount,
$reachabilityCheckInterval
);
$this->log->info('Brancher Hypernode has become available!');
} catch (CreateBrancherHypernodeFailedException | TimeoutException $e) {
if (in_array($brancherApp, $this->brancherHypernodesRegistered)) {
$this->brancherHypernodeManager->cancel($brancherApp);
}
throw $e;
}
$server->setHostname(sprintf("%s.hypernode.io", $brancherApp));
}
}
/**
* Initialize build stage
*/
private function initializeBuildStage(Configuration $config): void
{
$host = localhost('build');
$host->set('labels', ['stage' => 'build']);
$host->set('bin/php', 'php');
$host->set('deploy_path', '.');
$host->set('release_or_current_path', '.');
foreach ($config->getVariables() as $key => $value) {
$this->log->debug(
sprintf('Setting var "%s" to %s for stage "build"', $key, json_encode($value))
);
$host->set($key, $value);
}
foreach ($config->getVariables('build') as $key => $value) {
$this->log->debug(
sprintf('Setting var "%s" to %s for stage "build"', $key, json_encode($value))
);
$host->set($key, $value);
}
}
/**
* @throws GracefulShutdownException
* @throws Throwable
* @throws Exception
*/
private function runStage(Deployer $deployer, string $stage, string $task = 'deploy'): int
{
$hosts = $deployer->selector->select("stage=$stage");
if (empty($hosts)) {
throw new \RuntimeException(sprintf('No host(s) found in stage %s', $stage));
}
$tasks = $deployer->scriptManager->getTasks($task);
$executor = $deployer->master;
pcntl_signal(SIGINT, function () {
$this->log->warning("Received signal SIGINT, running fail jobs");
// We don't have to do anything here. Underlying processes will receive the SIGINT signal as well
// and that will cause the $exitCode below to be 255, which will cause the fail tasks to be run.
});
/**
* Set the env variable to tell deployer to deploy the hosts sequentially instead of parallel.
* @see \Deployer\Executor\Master::runTask()
*/
putenv('DEPLOYER_LOCAL_WORKER=true');
$exitCode = $executor->run($tasks, $hosts);
if ($exitCode === 0) {
$this->deployedHostnames = array_map(fn(Host $host) => $host->getHostname(), $hosts);
$this->deployedStage = $stage;
return 0;
}
if ($exitCode === GracefulShutdownException::EXIT_CODE) {
return 1;
}
// Check if we have tasks to execute on failure
if ($deployer['fail']->has($task)) {
$taskName = $deployer['fail']->get($task);
$tasks = $deployer->scriptManager->getTasks($taskName);
$executor->run($tasks, $hosts);
}
$this->brancherHypernodeManager->cancel(...$this->brancherHypernodesRegistered);
return $exitCode;
}
public function getDeploymentReport()
{
return new Report\Report(
$this->deployedStage,
$this->deployedHostnames,
$this->brancherHypernodesRegistered
);
}
}