/
Runtime.php
executable file
·559 lines (489 loc) · 13.8 KB
/
Runtime.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Runtime;
use Mage\Deploy\Strategy\ReleasesStrategy;
use Mage\Deploy\Strategy\RsyncStrategy;
use Mage\Deploy\Strategy\StrategyInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\Process\Process;
use Mage\Runtime\Exception\RuntimeException;
/**
* Runtime is a container of all run in time configuration, stages of progress, hosts being deployed, etc.
*
* @author Andrés Montañez <andresmontanez@gmail.com>
*/
class Runtime
{
const PRE_DEPLOY = 'pre-deploy';
const ON_DEPLOY = 'on-deploy';
const POST_DEPLOY = 'post-deploy';
const ON_RELEASE = 'on-release';
const POST_RELEASE = 'post-release';
/**
* @var array Magallanes configuration
*/
protected $configuration = [];
/**
* @var string|null Environment being deployed
*/
protected $environment;
/**
* @var string Stage of Deployment
*/
protected $stage;
/**
* @var string|null The host being deployed to
*/
protected $workingHost = null;
/**
* @var string|null The Release ID
*/
protected $releaseId = null;
/**
* @var array Hold a bag of variables for sharing information between tasks, if needed
*/
protected $vars = [];
/**
* @var LoggerInterface|null The logger instance
*/
protected $logger;
/**
* @var bool Indicates if a Rollback operation is in progress
*/
protected $rollback = false;
public function isWindows()
{
return stripos(PHP_OS, 'WIN') === 0;
}
/**
* Generate the Release ID
*
* @return Runtime
*/
public function generateReleaseId()
{
$this->setReleaseId(date('YmdHis'));
return $this;
}
/**
* Sets the Release ID
*
* @param string $releaseId Release ID
* @return Runtime
*/
public function setReleaseId($releaseId)
{
$this->releaseId = $releaseId;
return $this;
}
/**
* Retrieve the current Release ID
*
* @return null|string Release ID
*/
public function getReleaseId()
{
return $this->releaseId;
}
/**
* Sets the Runtime in Rollback mode On or Off
*
* @param bool $inRollback
* @return Runtime
*/
public function setRollback($inRollback)
{
$this->rollback = $inRollback;
return $this;
}
/**
* Indicates if Runtime is in rollback
*
* @return bool
*/
public function inRollback()
{
return $this->rollback;
}
/**
* Sets a value in the Vars bag
*
* @param string $key Variable name
* @param string $value Variable value
* @return Runtime
*/
public function setVar($key, $value)
{
$this->vars[$key] = $value;
return $this;
}
/**
* Retrieve a value from the Vars bag
*
* @param string $key Variable name
* @param mixed $default Variable default value, returned if not found
* @return string
*/
public function getVar($key, $default = null)
{
if (array_key_exists($key, $this->vars)) {
return $this->vars[$key];
}
return $default;
}
/**
* Sets the Logger instance
*
* @param LoggerInterface $logger Logger instance
* @return Runtime
*/
public function setLogger(LoggerInterface $logger = null)
{
$this->logger = $logger;
return $this;
}
/**
* Sets the Magallanes Configuration to the Runtime
*
* @param array $configuration Configuration
* @return Runtime
*/
public function setConfiguration($configuration)
{
$this->configuration = $configuration;
return $this;
}
/**
* Retrieve the Configuration
*
* @return array
*/
public function getConfiguration()
{
return $this->configuration;
}
/**
* Retrieves the Configuration Option for a specific section in the configuration
*
* @param string $key Section name
* @param mixed $default Default value
* @return mixed
*/
public function getConfigOption($key, $default = null)
{
if (array_key_exists($key, $this->configuration)) {
return $this->configuration[$key];
}
return $default;
}
/**
* Returns the Configuration Option for a specific section the current Environment
*
* @param string $key Section/Parameter name
* @param mixed $default Default value
* @return mixed
*/
public function getEnvOption($key, $default = null)
{
if (!array_key_exists('environments', $this->configuration) || !is_array($this->configuration['environments'])) {
return $default;
}
if (!array_key_exists($this->environment, $this->configuration['environments'])) {
return $default;
}
if (array_key_exists($key, $this->configuration['environments'][$this->environment])) {
return $this->configuration['environments'][$this->environment][$key];
}
return $default;
}
/**
* Shortcut to get the the configuration option for a specific environment and merge it with
* the global one (environment specific overrides the global one if present).
*
* @param $key
* @param array $defaultEnv
*
* @return array
*/
public function getMergedOption($key, $defaultEnv = [])
{
$userGlobalOptions = $this->getConfigOption($key, $defaultEnv);
$userEnvOptions = $this->getEnvOption($key, $defaultEnv);
return array_merge(
(is_array($userGlobalOptions) ? $userGlobalOptions : []),
(is_array($userEnvOptions) ? $userEnvOptions : [])
);
}
/**
* Overwrites an Environment Configuration Option
*
* @param string $key
* @param mixed $value
* @return Runtime
*/
public function setEnvOption($key, $value)
{
if (array_key_exists('environments', $this->configuration) && is_array($this->configuration['environments'])) {
if (array_key_exists($this->environment, $this->configuration['environments'])) {
$this->configuration['environments'][$this->environment][$key] = $value;
}
}
return $this;
}
/**
* Sets the working Environment
*
* @param string $environment Environment name
* @return Runtime
* @throws RuntimeException
*/
public function setEnvironment($environment)
{
if (array_key_exists('environments', $this->configuration) && array_key_exists($environment, $this->configuration['environments'])) {
$this->environment = $environment;
return $this;
}
throw new RuntimeException(sprintf('The environment "%s" does not exists.', $environment), 100);
}
/**
* Returns the current working Environment
*
* @return null|string
*/
public function getEnvironment()
{
return $this->environment;
}
/**
* Sets the working stage
*
* @param string $stage Stage code
* @return Runtime
*/
public function setStage($stage)
{
$this->stage = $stage;
return $this;
}
/**
* Retrieve the current working Stage
*
* @return string
*/
public function getStage()
{
return $this->stage;
}
/**
* Retrieve the defined Tasks for the current Environment and Stage
*
* @return array
*/
public function getTasks()
{
if (!array_key_exists('environments', $this->configuration) || !is_array($this->configuration['environments'])) {
return [];
}
if (!array_key_exists($this->environment, $this->configuration['environments'])) {
return [];
}
if (array_key_exists($this->stage, $this->configuration['environments'][$this->environment])) {
if (is_array($this->configuration['environments'][$this->environment][$this->stage])) {
return $this->configuration['environments'][$this->environment][$this->stage];
}
}
return [];
}
/**
* Sets the working Host
*
* @param string $host Host name
* @return Runtime
*/
public function setWorkingHost($host)
{
$this->workingHost = $host;
return $this;
}
/**
* Retrieve the working Host
*
* @return null|string
*/
public function getWorkingHost()
{
return $this->workingHost;
}
/**
* Logs a Message into the Logger
*
* @param string $message Log message
* @param string $level Log Level
*/
public function log($message, $level = LogLevel::DEBUG)
{
if ($this->logger instanceof LoggerInterface) {
$this->logger->log($level, $message);
}
}
/**
* Executes a command, it will be run Locally or Remotely based on the working Stage
*
* @param string $cmd Command to execute
* @param int $timeout Seconds to wait
* @return Process
*/
public function runCommand($cmd, $timeout = 120)
{
switch ($this->getStage()) {
case self::ON_DEPLOY:
case self::ON_RELEASE:
case self::POST_RELEASE:
return $this->runRemoteCommand($cmd, true, $timeout);
default:
return $this->runLocalCommand($cmd, $timeout);
}
}
/**
* Execute a command locally
*
* @param string $cmd Command to execute
* @param int $timeout Seconds to wait
* @return Process
*/
public function runLocalCommand($cmd, $timeout = 120)
{
$this->log($cmd, LogLevel::INFO);
$process = Process::fromShellCommandline($cmd);
$process->setTimeout($timeout);
$process->run();
$this->log($process->getOutput(), LogLevel::DEBUG);
if (!$process->isSuccessful()) {
$this->log($process->getErrorOutput(), LogLevel::ERROR);
}
return $process;
}
/**
* Executes a command remotely, if jail is true, it will run inside the Host Path and the Release (if available)
*
* @param string $cmd Command to execute
* @param bool $jail Jail the command
* @param int $timeout Seconds to wait
* @return Process
*/
public function runRemoteCommand($cmd, $jail, $timeout = 120)
{
$user = $this->getEnvOption('user', $this->getCurrentUser());
$sudo = $this->getEnvOption('sudo', false);
$host = $this->getHostName();
$sshConfig = $this->getSSHConfig();
$cmdDelegate = $cmd;
if ($sudo === true) {
$cmdDelegate = sprintf('sudo %s', $cmd);
}
$hostPath = rtrim($this->getEnvOption('host_path'), '/');
if ($jail && $this->getReleaseId() !== null) {
$cmdDelegate = sprintf('cd %s/releases/%s && %s', $hostPath, $this->getReleaseId(), $cmdDelegate);
} elseif ($jail) {
$cmdDelegate = sprintf('cd %s && %s', $hostPath, $cmdDelegate);
}
$cmdRemote = str_replace('"', '\"', $cmdDelegate);
$cmdLocal = sprintf('ssh -p %d %s %s@%s "%s"', $sshConfig['port'], $sshConfig['flags'], $user, $host, $cmdRemote);
return $this->runLocalCommand($cmdLocal, $timeout);
}
/**
* Get the SSH configuration based on the environment
*
* @return array
*/
public function getSSHConfig()
{
$sshConfig = $this->getEnvOption('ssh', ['port' => 22, 'flags' => '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no']);
if ($this->getHostPort() !== null) {
$sshConfig['port'] = $this->getHostPort();
}
if (!array_key_exists('port', $sshConfig)) {
$sshConfig['port'] = '22';
}
if (!array_key_exists('flags', $sshConfig)) {
$sshConfig['flags'] = '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no';
}
if (!array_key_exists('timeout', $sshConfig)) {
$sshConfig['timeout'] = 300;
}
return $sshConfig;
}
/**
* Get the current Host Port or default ssh port
*
* @return integer
*/
public function getHostPort()
{
$info = explode(':', $this->getWorkingHost());
return isset($info[1]) ? $info[1] : null;
}
/**
* Get the current Host Name
*
* @return string
*/
public function getHostName()
{
if (strpos($this->getWorkingHost(), ':') === false) {
return $this->getWorkingHost();
}
$info = explode(':', $this->getWorkingHost());
return $info[0];
}
/**
* Gets a Temporal File name
*
* @return string
*/
public function getTempFile()
{
return tempnam(sys_get_temp_dir(), 'mage');
}
/**
* Get the current user
*
* @return string
*/
public function getCurrentUser()
{
$userData = posix_getpwuid(posix_geteuid());
return $userData['name'];
}
/**
* Shortcut for getting Branch information
*
* @return boolean|string
*/
public function getBranch()
{
return $this->getEnvOption('branch', false);
}
/**
* Guesses the Deploy Strategy to use
*
* @return StrategyInterface
*/
public function guessStrategy()
{
$strategy = new RsyncStrategy();
if ($this->getEnvOption('releases', false)) {
$strategy = new ReleasesStrategy();
}
$strategy->setRuntime($this);
return $strategy;
}
}