This repository has been archived by the owner on Jul 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
deployotron.actions.inc
executable file
·1353 lines (1212 loc) · 39.5 KB
/
deployotron.actions.inc
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Actions for Deployotron.
*/
namespace Deployotron {
define('COLOR_RED', "\033[1;31;40m\033[1m");
define('COLOR_YELLOW', "\033[1;33;40m\033[1m");
define('COLOR_GREEN', "\033[1;32;40m\033[1m");
define('COLOR_RESET', "\033[0m");
/**
* Creates actions to run.
*/
class ActionFactory {
static protected $actionMapping = array(
'deploy' => array(
'SanityCheck',
'SiteOffline',
'BackupDatabase',
'DeployCode',
'CreateVersionTxt',
'UpdateDatabase',
'ClearCache',
'SiteOnline',
'PurgeDatabaseBackups',
'FlowdockNotificaton',
'NewRelicNotificaton',
),
'omg' => array(
'SiteOffline',
'OMGPrepare',
'DeployCode',
'CreateVersionTxt',
'RestoreDatabase',
'SiteOnline',
'ClearCache',
),
);
/**
* Gathers an array of actions to run.
*/
static public function getActions($name, $site = NULL) {
$actions = array();
if (isset(static::$actionMapping[$name])) {
foreach (static::$actionMapping[$name] as $class_name) {
$class_name = '\\Deployotron\\Actions\\' . $class_name;
$action = new $class_name($site);
$actions = array_merge($actions,
static::getActionCommands('pre', $action, $site),
array($action),
static::getActionCommands('post', $action, $site));
}
return $actions;
}
}
/**
* Gets pre/post commands for an action.
*/
static protected function getActionCommands($type, $action, $site) {
$actions = array();
$switch = $type . '-' . $action->getSwitchSuffix();
if ($action->enabled() && !drush_get_option('no-' . $switch, FALSE)) {
// @todo drush_get_option_list() doesn't play well with commas.
if ($commands = drush_get_option_list($switch, FALSE)) {
foreach ($commands as $command) {
if (!empty($command)) {
$actions[] = new Actions\CommandAction($site, $command);
}
}
}
}
return $actions;
}
/**
* Output help on actions and options.
*/
static public function getHelp() {
$all_actions = array();
drush_print('Commands');
drush_print('--------');
foreach (static::$actionMapping as $name => $actions) {
drush_print(wordwrap(dt('@name runs the actions: @actions', array(
'@name' => $name,
'@actions' => implode(', ', $actions),
))));
drush_print();
$all_actions = array_merge($all_actions, $actions);
}
$all_actions = array_unique($all_actions);
sort($all_actions);
drush_print('Actions');
drush_print('-------');
foreach ($all_actions as $class_name) {
drush_print($class_name . ':');
$class_name = '\\Deployotron\\Actions\\' . $class_name;
$action = new $class_name('@self');
drush_print($action->getHelp());
drush_print();
// Print options.
$options = $action->getOptions();
if ($options) {
drush_print_table(drush_format_help_section($options, 'options'));
drush_print();
}
drush_print();
}
}
}
/**
* Base class for actions.
*/
abstract class Action {
/**
* Set a default short description.
*/
protected $short = "incompletely implemented";
/**
* Default run message.
*/
protected $runMessage = "Running action.";
/**
* Options for this action.
*/
protected $options = array();
/**
* The site this action works on.
*/
protected $site;
/**
* Result object of last drush command.
*/
protected $drushResult;
/**
* Array of the output of the last executed command.
*/
protected $shOutput;
/**
* Return code of the last executed command.
*/
protected $shRc;
/**
* Shas of checkouts of aliases.
*/
static protected $headShas = array();
/**
* Construct a new Action object.
*/
public function __construct($site) {
$this->site = $site;
if ($this->short == "incompletely implemented") {
drush_log(dt('Incomplete action, missing short description: @action', array('@action' => get_class($this))), 'warning');
}
if (!isset($this->runMessage)) {
$this->runMessage = 'Running ' . $this->short;
}
}
/**
* Get help description.
*/
public function getHelp() {
if (isset($this->help)) {
return $this->help;
}
if (isset($this->description)) {
return $this->description;
}
return "No description.";
}
/**
* Get the command line options for this action.
*
* If the command has an enable-switch, the kill-switch and command options
* are classed as sub-options for nice help output. If there's no
* enable-switch, all options are considered regular options.
*
* @return array
* Options and sub-options as defined on commands in hook_drush_command().
*/
public function getOptions() {
$options = array();
if (isset($this->killSwitch)) {
$options += array(
$this->killSwitch => "Don't " . $this->short . (isset($this->enableSwitch) ? ' (overrides --' . $this->enableSwitch . ')' : '') . '.',
);
}
$options += $this->options;
$prest_options = array(
'pre/post-*' => array(
'pre-' . $this->getSwitchSuffix() => "Before " . $this->short . ".",
'post-' . $this->getSwitchSuffix() => "After " . $this->short . ".",
),
);
if (isset($this->enableSwitch)) {
$sub_options = $options;
$options = array();
// If the action options defines the enable switch, use it so
// description and possible example-values propergate.
if (isset($sub_options[$this->enableSwitch])) {
$options[$this->enableSwitch] = $sub_options[$this->enableSwitch];
unset($sub_options[$this->enableSwitch]);
}
else {
$options[$this->enableSwitch] = ucfirst($this->short) . '.';
}
$options['pre/post-*'] = "Commands to run before/after action.";
return array(
'options' => $options,
'sub-options' => (!empty($sub_options) ? array($this->enableSwitch => $sub_options) : array()) + $prest_options,
);
}
$options['pre/post-*'] = "Commands to run before/after action.";
return array('options' => $options, 'sub-options' => $prest_options);
}
/**
* Get the switch suffix for --pre-/--post- switches.
*/
public function getSwitchSuffix() {
if (isset($this->switchSuffix)) {
return $this->switchSuffix;
}
elseif (isset($this->enableSwitch)) {
return $this->enableSwitch;
}
elseif (isset($this->killSwitch)) {
return preg_replace('/^no-/', '', $this->killSwitch);
}
else {
return preg_replace(array('/[^a-z0-9 ]/', '/ /'), array('', '-'), strtolower($this->short));
}
}
/**
* Get the short description of this action.
*
* If the action has a killswitch, it should work with "Don't " prepended.
*
* @return string
* Human readable short description of action taken.
*/
public function getShort() {
return $this->short;
}
/**
* Return the message to print when running this action.
*
* @return string
* The Message (by Grandmaster Flash).
*/
public function getRunMessage() {
return $this->runMessage;
}
/**
* Get a description of what the action would do.
*
* If the action subclass defines the $description property, use that, else
* returns a generic message.
*
* If more logic than a static string is needed, subclassesare encouraged to
* override this to provide a more specific description of the effect of the
* action.
*
* Used when the user provides the --confirm switch.
*
* @return string
* Description of the action.
*/
public function getDescription() {
if (isset($this->description)) {
return $this->description;
}
return dt("Run the @short action.", array('@short' => $this->short));
}
/**
* Validate that the action can be run.
*
* @return bool
* Whether it can.
*/
public function validate() {
return TRUE;
}
/**
* Run the task.
*
* @param array $state
* Persistent state array that actions can use to communicate with
* following actions.
*
* @return bool
* Success or failure.
*/
public function run(\ArrayObject $state) {
return FALSE;
}
/**
* Roll back the task.
*/
public function rollback() {
return 'no rollback';
}
/**
* Whether this action is enabled.
*/
public function enabled() {
// Incomplete actions are always disabled.
if ($this->short == "incompletely implemented") {
return FALSE;
}
// Disable if there is a killswitch and it is set.
if (isset($this->killSwitch) && drush_get_option($this->killSwitch, FALSE)) {
return FALSE;
}
// If there is an enable switch, let that decide.
if (isset($this->enableSwitch)) {
return drush_get_option($this->enableSwitch, FALSE);
}
// Else default to enabled.
return TRUE;
}
/**
* Execute a sh command.
*
* Is run on the site.
*
* @param string $command
* Command to run.
*
* @return bool
* Whether the command succeeded.
*/
protected function sh($command) {
$exec = $command;
// Check that there is a remote host before trying to construct a remote
// command.
$host = drush_remote_host($this->site);
if (!empty($host)) {
$exec = drush_shell_proc_build($this->site, $command, TRUE);
}
else {
// Else just cd to the root of the alias. This allows us to test the
// code without a remote host.
$exec = "cd " . drush_escapeshellarg($this->site['root']) . " && " . $exec;
}
return $this->shLocal($exec);
}
/**
* Get the output of the most recent command.
*
* @return string
* The output.
*/
protected function shOutput() {
return implode("\n", $this->shOutputArray());
}
/**
* Get the output of the most recent command as an array.
*
* @return array
* Lines of output.
*/
protected function shOutputArray() {
return $this->shOutput;
}
/**
* Get the return code of the most recent command.
*/
protected function shRc() {
return $this->shRc;
}
/**
* Execute a sh locally.
*
* Works much like drush_shell_exec, however it captures the command return
* code too, and doesn't support interactive mode.
*
* @param string $command
* Command to run.
*
* @return bool
* Whether the command succeeded.
*/
protected function shLocal($command) {
$this->shOutput = array();
$this->shRc = 0;
$args = func_get_args();
// Escape args, but not the command.
for ($x = 1; $x < count($args); $x++) {
$args[$x] = drush_escapeshellarg($args[$x]);
}
// Mimic drush_shell_exec(), which can take a single or multiple args.
if (count($args) == 1) {
$command = $args[0];
}
else {
$command = call_user_func_array('sprintf', $args);
}
if (drush_get_context('DRUSH_VERBOSE') || drush_get_context('DRUSH_SIMULATE')) {
drush_print('Executing: ' . $command, 0, STDERR);
}
if (!drush_get_context('DRUSH_SIMULATE')) {
exec($command . ' 2>&1', $this->shOutput, $this->shRc);
if (drush_get_context('DRUSH_DEBUG')) {
foreach ($this->shOutput as $line) {
drush_print($line, 2);
}
}
}
// Exit code 0 means success.
return ($this->shRc == 0);
}
/**
* Find the tag pointed to by a SHA.
*
* @param string $sha
* The SHA to lookup.
*
* @return bool
* Whether the command succeeded.
*/
protected function gitPointsAt ($sha) {
$success = $this->shLocal('git tag --points-at ' . $sha);
// If it failed we try a fallback command for older versions of
// git.
if (!$success) {
$success = $this->shLocal('git show-ref --tags -d | grep ^' . $sha . ' | sed -e \'s,.* refs/tags/,,\' -e \'s/\^{}//\'');
}
return $success;
}
/**
* Execute a drush command.
*
* Is run on the site.
*
* @param string $command
* Command to run.
* @param string $args
* Command arguments.
* @param string $options
* Command arguments.
*
* @return bool
* Whether the command succeeded.
*/
protected function drush($command, $args = array(), $options = array()) {
$this->drushResult = drush_invoke_process($this->site, $command, $args, $options, TRUE);
if (!$this->drushResult || $this->drushResult['error_status'] != 0) {
return FALSE;
}
return TRUE;
}
/**
* Get the SHA to deploy.
*
* This is based on options from configuration or command.
*
* @return string
* The SHA to deploy.
*/
protected function pickSha($options = array()) {
$options = array(
'branch' => drush_get_option('branch', NULL),
'tag' => drush_get_option('tag', NULL),
'sha' => drush_get_option('sha', NULL),
);
$branch = $options['branch'];
$tag = $options['tag'];
$sha = $options['sha'];
$posibilities = array_filter(array($branch, $tag, $sha));
if (count($posibilities) > 1) {
drush_log(dt('More than one of branch/tag/sha specified, using @selected.', array('@selected' => !empty($sha) ? 'sha' : 'tag')), 'warning');
}
elseif (count($posibilities) < 1) {
return drush_set_error(dt('You must provide at least one of --branch, --tag or --sha.'));
}
// Use rev-list to ensure we get a full SHA rather than branch/tag/partial
// SHA. Ensures the existence of the branch/tag/SHA, and transforms
// annotated tag SHAs to the commit they're based on (so the repo will
// actually have the SHA we asked for checked out).
if ($this->shLocal('git rev-list -1 ' . end($posibilities) . ' --')) {
$sha = trim($this->shOutput());
}
else {
if (!empty($sha)) {
return drush_set_error(dt('Unknown SHA.'));
}
else {
return drush_set_error(dt('Error finding SHA for ' . (!empty($branch) ? 'branch' : 'tag') . '.'));
}
}
return $sha;
}
/**
* Get the current git head revision.
*
* @param bool $no_cache
* Dont't use cache, but fetch anyway.
*/
protected function getHead($no_cache = FALSE) {
$name = $this->site['#name'];
if (!isset(self::$headShas[$name]) || $no_cache) {
self::$headShas[$name] = '';
if ($this->sh('git rev-parse HEAD')) {
$sha = trim($this->shOutput());
// Confirm that we can see the HEAD locally.
if ($this->shLocal('git show -s ' . $sha)) {
self::$headShas[$name] = $sha;
}
else {
drush_log(dt("Could not find the deployed HEAD (@sha) locally, you pulled recently?", array('@sha' => $sha)), 'warning');
}
}
}
return self::$headShas[$name];
}
}
}
/**
* Use a namespace to keep actions together.
*/
namespace Deployotron\Actions {
use Deployotron\Action;
/**
* Generic command action.
*
* Automatically instantiated from pre/post-* options.
*/
class CommandAction extends Action {
/**
* Create action.
*/
public function __construct($site, $command) {
$this->description = 'Run command: ' . $command;
$this->runMessage = 'Running command: ' . $command;
$this->short = 'run ' . $command;
$this->command = $command;
parent::__construct($site);
}
/**
* {@inheritdoc}
*/
public function run(\ArrayObject $state) {
$success = $this->sh($this->command);
drush_print($this->shOutput());
if (!$success) {
return drush_set_error(dt('Error running command "@command"', array('@command' => $this->command)));
}
return TRUE;
}
}
/**
* Sanity check.
*
* Check for locally modified files and do a dry-run checkout.
*/
class SanityCheck extends Action {
protected $runMessage = 'Fetching and sanity checking';
protected $short = 'sanity check';
protected $help = 'Fetches the new code and checks that the repository is clean.';
protected $options = array(
'insanity' => "Don't check that the server repository is clean. Might cause data loss.",
);
/**
* {@inheritdoc}
*/
public function getDescription() {
if (drush_get_option('insanity', FALSE)) {
return COLOR_YELLOW . dt('Skipping sanity check of deployed repo. Might cause data loss or Git failures.') . COLOR_RESET;
}
return dt('Run git fetch and check that the deployed git repository is clean.');
}
/**
* {@inheritdoc}
*/
public function validate() {
if ($this->sha = $this->pickSha()) {
return TRUE;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function run(\ArrayObject $state) {
// Fetch the latest changes from upstream.
if (!$this->sh('git fetch')) {
$message = $this->shOutput();
if (preg_match('/Permission denied \(publickey\)/', $message)) {
drush_log(dt('Access denied to repository URL.'), 'error');
drush_log(dt('Ensure that either that the user on the server has access to the repository, or use "ForwardAgent yes" in .ssh/config.'), 'error');
}
else {
drush_print($message);
}
return drush_set_error(dt("Could not fetch from remote repository."));
}
// Check that we can see the sha we want to deploy.
if (!$this->sh('git log -1 ' . $this->sha . ' --')) {
$message = $this->shOutput();
if (preg_match('/^fatal: bad object/', $message)) {
return drush_set_error(dt('Could not find SHA, did you forget to push?'));
}
drush_print($message);
return drush_set_error(dt('Could not find SHA remotely.'));
}
if (drush_get_option('insanity', FALSE)) {
drush_log(dt('Skipping sanity check of deployed repo.'), 'warning');
return TRUE;
}
$fallback = FALSE;
// http://stackoverflow.com/questions/3878624/how-do-i-programmatically-determine-if-there-are-uncommited-changes
// claims this is the proper way. I'm inclined to agree.
// However, these are newer additions to Git, so fallback to git status
// if they fail.
if (!$this->sh('git diff-files --quiet --ignore-submodules --')) {
if ($this->shRc() != 129) {
return drush_set_error(dt('Remote git checkout not clean.'));
}
$fallback = TRUE;
}
if (!$fallback) {
if (!$this->sh('git diff-index --cached --quiet HEAD --ignore-submodules --')) {
if ($this->shRc() != 129) {
return drush_set_error(dt('Uncommitted changes in the index.'));
}
$fallback = TRUE;
}
}
if ($fallback) {
if (!$this->sh('git status -s --untracked-files=no')) {
return drush_set_error(dt('Error running git status -s --untracked-files=no.'));
}
$output = trim($this->shOutput());
if (!empty($output)) {
return drush_set_error(dt('Remote git checkout not clean.'));
}
}
return TRUE;
}
}
/**
* Deploy code.
*/
class DeployCode extends Action {
protected $runMessage = 'Deploying';
protected $killSwitch = 'no-deploy';
protected $short = 'deploy code';
protected $help = 'Checks out a specified branch/tag/sha on the site.';
protected $options = array(
'branch' => 'Branch to check out.',
'tag' => 'Tag to check out.',
'sha' => 'SHA to check out.',
);
/**
* {@inheritdoc}
*/
public function getDescription() {
$head = $this->getHead();
if (!$head) {
return COLOR_YELLOW . dt("Cannot find the deployed HEAD.") . COLOR_RESET;
}
// Collect info and log entry for the commit we're deploying.
$this->shLocal('git log --pretty="format:%an <%ae> @ %ci (%cr)%n%n%B" --color --no-walk ' . $this->sha);
$commit_info = $this->shOutput();
// Collect info and log entry for the deployed head.
$this->shLocal('git log --pretty="format:%an <%ae> @ %ci (%cr)%n%n%B" --color --no-walk ' . $head);
$head_info = $this->shOutput();
// Create diffstat between the deployed commit and the one we're
// deploying.
$this->shLocal('git diff --color --stat ' . $head . ' ' . $this->sha);
$stat = $this->shOutput();
$stat = explode("\n", $stat);
if (count($stat) > 20) {
$stat = array_merge(array_slice($stat, 0, 8), array('', ' ...', ''), array_slice($stat, -8));
}
$desc = dt("Check out @sha:\n", array('@sha' => $this->sha));
$desc .= $commit_info . "\n\n";
$desc .= dt("Currently deployed: @sha\n", array('@sha' => $head));
$desc .= $head_info . "\n\n";
$desc .= dt("All changes:\n!changes", array('!changes' => implode("\n", $stat)));
return $desc;
}
/**
* {@inheritdoc}
*/
public function validate() {
if ($this->sha = $this->pickSha()) {
return TRUE;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function run(\ArrayObject $state) {
// Some useful information for other actions.
$state['requested_branch'] = drush_get_option('branch', NULL);
$state['requested_tag'] = drush_get_option('tag', NULL);
$state['requested_sha'] = drush_get_option('sha', NULL);
if (!$this->sh('git checkout ' . $this->sha)) {
drush_print($this->shOutput());
return drush_set_error(dt('Could not checkout code.'));
}
// An extra safety check to make sure that things are as we think.
$deployed_sha = $this->getHead(TRUE);
if ($deployed_sha) {
if ($deployed_sha != $this->sha) {
return drush_set_error(dt('Code not properly deployed, head is at @sha now.', array('@sha' => $deployed_sha)));
}
else {
drush_log(dt('HEAD now at @sha', array('@sha' => $deployed_sha)), 'status');
$state['deployed_sha'] = $deployed_sha;
}
}
else {
drush_print($this->shOutput());
return drush_set_error(dt('Error confirming that the code update succceded.'));
}
return TRUE;
}
}
/**
* Set site offline.
*/
class SiteOffline extends Action {
protected $description = 'Set the site offline.';
protected $runMessage = 'Setting site offline';
protected $killSwitch = 'no-offline';
protected $short = 'set site offline';
/**
* {@inheritdoc}
*/
public function run(\ArrayObject $state) {
if (!$this->drush('variable-set', array('maintenance_mode', 1))) {
return drush_set_error(dt('Error setting site offline.'));
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function rollback() {
// Use the online action as rollback.
$online = new SiteOnline($this->site);
$online->run(new \ArrayObject());
}
}
/**
* Set site online.
*/
class SiteOnline extends Action {
protected $description = 'Set the site online.';
protected $runMessage = 'Setting site online';
protected $killSwitch = 'no-offline';
protected $short = 'set site online';
protected $switchSuffix = 'online';
/**
* {@inheritdoc}
*/
public function run(\ArrayObject $state) {
if (!$this->drush('variable-set', array('maintenance_mode', 0))) {
return drush_set_error(dt('Error setting site online.'));
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function rollback() {
// Use the online action as rollback.
$online = new SiteOffline($this->site);
$online->run(new \ArrayObject());
}
}
/**
* Backup database.
*/
class BackupDatabase extends Action {
protected $runMessage = 'Dumping database';
protected $killSwitch = 'no-dump';
protected $short = 'dump database';
protected $help = 'Makes a SQL dump of the site database.';
protected $options = array(
'dump-dir' => array(
'description' => 'Directory for database dumps, defaults to /tmp.',
'example-value' => 'path',
),
);
/**
* Get the name of a dump.
*/
public static function filename($alias, $date_str, $sha) {
return sprintf("%s/deploy.%s.%s.%s.sql", drush_get_option('dump-dir', '/tmp'), $alias, $date_str, $sha);
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return dt("Dump database to @file.", array('@file' => $this->dumpFilename()));
}
/**
* {@inheritdoc}
*/
public function run(\ArrayObject $state) {
if (!$this->drush('sql-dump', array(), array('no-ordered-dump' => TRUE, 'result-file' => $this->dumpFilename()))) {
return drush_set_error('Error dumping database.');
}
$state['database_dump'] = $this->dumpFilename();
return TRUE;
}
/**
* Figure out dump filename.
*/
protected function dumpFilename() {
// Because there can pass time between this is called first and last
// (--confirm primarily).
static $date;
if (!$date) {
$date = date('Y-m-d\TH:i:s');
}
return static::filename($this->site['#name'], $date, $this->getHead());
}
}
/**
* Restore database.
*/
class RestoreDatabase extends Action {
protected $runMessage = 'Restoring database';
protected $short = 'restore database';
protected $options = array(
'file' => array(
'description' => 'Database dump file to restore.',
'example-value' => 'filename',
),
);
/**
* {@inheritdoc}
*/
public function validate() {
if (!drush_get_option('file', NULL)) {
return drush_set_error(dt('Missing file.'));
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return dt("Restore database from @file.", array('@file' => drush_get_option('file', NULL)));
}
/**
* {@inheritdoc}
*/
public function run(\ArrayObject $state) {
if (!$this->drush('sql-connect', array(), array('pipe' => TRUE))) {
return drush_set_error('Error getting database connection setup.');
}
if (!is_string($this->drushResult['object'])) {
return drush_set_error('Weird result from sql-connnect.');
}
$command = $this->drushResult['object'];
if (!$this->sh($command . " < " . drush_get_option('file', NULL))) {
drush_print($this->shOutput());
return drush_set_error('Error restoring database.');
}
return TRUE;
}
}
/**
* Purge old backups.
*/
class PurgeDatabaseBackups extends Action {
protected $runMessage = 'Purging old database dumps.';
protected $short = 'purge old dumps';
protected $options = array(
'num-dumps' => array(
'description' => 'Number of database dumps to keep. 0 for unlimited.',
'example-value' => '5',
),
);
protected $switchSuffix = 'purge';
/**
* Dumps to delete.
*/
protected $deleteDumps = array();
/**
* {@inheritdoc}
*/
public function validate() {
$dumping = TRUE;
if (drush_get_option('no-dump', FALSE)) {
$dumping = FALSE;
}
$max_dumps = drush_get_option('num-dumps', 5);
if ($max_dumps > 0) {
// If we're dumping a new dump, we need to keep one less than the max to
// make room for the new one.