-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
DeployHookCommands.php
268 lines (241 loc) · 9.82 KB
/
DeployHookCommands.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
<?php
namespace Drush\Drupal\Commands\core;
use Consolidation\Log\ConsoleLogLevel;
use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
use Consolidation\OutputFormatters\StructuredData\UnstructuredListData;
use Consolidation\SiteAlias\SiteAliasManagerAwareTrait;
use Consolidation\SiteAlias\SiteAliasManagerAwareInterface;
use Drupal\Core\Update\UpdateRegistry;
use Drupal\Core\Utility\Error;
use Drush\Commands\DrushCommands;
use Drush\Drush;
use DrushBatchContext;
use Drush\Exceptions\UserAbortException;
use Psr\Log\LogLevel;
class DeployHookCommands extends DrushCommands implements SiteAliasManagerAwareInterface
{
use SiteAliasManagerAwareTrait;
/**
* Get the deploy hook update registry.
*/
public static function getRegistry(): UpdateRegistry
{
$registry = new class (
\Drupal::getContainer()->getParameter('app.root'),
\Drupal::getContainer()->getParameter('site.path'),
array_keys(\Drupal::service('module_handler')->getModuleList()),
\Drupal::service('keyvalue')->get('deploy_hook')
) extends UpdateRegistry {
public function setUpdateType(string $type): void
{
$this->updateType = $type;
}
};
$registry->setUpdateType('deploy');
return $registry;
}
/**
* Prints information about pending deploy update hooks.
*
* @usage deploy:hook-status
* Prints information about pending deploy hooks.
*
* @field-labels
* module: Module
* hook: Hook
* description: Description
* @default-fields module,hook,description
*
* @command deploy:hook-status
* @topics docs:deploy
*
* @filter-default-field hook
*/
public function status(): RowsOfFields
{
$updates = self::getRegistry()->getPendingUpdateInformation();
$rows = [];
foreach ($updates as $module => $update) {
if (!empty($update['pending'])) {
foreach ($update['pending'] as $hook => $description) {
$rows[] = [
'module' => $module,
'hook' => $hook,
'description' => $description,
];
}
}
}
return new RowsOfFields($rows);
}
/**
* Run pending deploy update hooks.
*
* @usage deploy:hook
* Run pending deploy hooks.
*
* @command deploy:hook
* @topics docs:deploy
* @version 10.3
*/
public function run(): int
{
$pending = self::getRegistry()->getPendingUpdateFunctions();
if (empty($pending)) {
$this->logger()->success(dt('No pending deploy hooks.'));
return self::EXIT_SUCCESS;
}
$process = $this->processManager()->drush($this->siteAliasManager()->getSelf(), 'deploy:hook-status');
$process->mustRun();
$this->output()->writeln($process->getOutput());
if (!$this->io()->confirm(dt('Do you wish to run the specified pending deploy hooks?'))) {
throw new UserAbortException();
}
$success = true;
if (!$this->getConfig()->simulate()) {
$operations = [];
foreach ($pending as $function) {
$operations[] = ['\Drush\Drupal\Commands\core\DeployHookCommands::updateDoOneDeployHook', [$function]];
}
$batch = [
'operations' => $operations,
'title' => 'Updating',
'init_message' => 'Starting deploy hooks',
'error_message' => 'An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.',
'finished' => [$this, 'updateFinished'],
];
batch_set($batch);
$result = drush_backend_batch_process('deploy:batch-process');
$success = false;
if (!is_array($result)) {
$this->logger()->error(dt('Batch process did not return a result array. Returned: !type', ['!type' => gettype($result)]));
} elseif (!empty($result[0]['#abort'])) {
// Whenever an error occurs the batch process does not continue, so
// this array should only contain a single item, but we still output
// all available data for completeness.
$this->logger()->error(dt('Update aborted by: !process', [
'!process' => implode(', ', $result[0]['#abort']),
]));
} else {
$success = true;
}
}
$level = $success ? ConsoleLogLevel::SUCCESS : LogLevel::ERROR;
$this->logger()->log($level, dt('Finished performing deploy hooks.'));
return $success ? self::EXIT_SUCCESS : self::EXIT_FAILURE;
}
/**
* Process operations in the specified batch set.
*
* @command deploy:batch-process
* @param string $batch_id The batch id that will be processed.
* @bootstrap full
* @hidden
*/
public function process(string $batch_id, $options = ['format' => 'json']): UnstructuredListData
{
$result = drush_batch_command($batch_id);
return new UnstructuredListData($result);
}
/**
* Batch command that executes a single deploy hook.
*
* @param string $function
* The deploy-hook function to execute.
* The batch context object.
*/
public static function updateDoOneDeployHook(string $function, DrushBatchContext $context): void
{
$ret = [];
// If this update was aborted in a previous step, or has a dependency that was
// aborted in a previous step, go no further.
if (!empty($context['results']['#abort'])) {
return;
}
list($module, $name) = explode('_deploy_', $function, 2);
$filename = $module . '.deploy';
\Drupal::moduleHandler()->loadInclude($module, 'php', $filename);
if (function_exists($function)) {
if (empty($context['results'][$module][$name]['type'])) {
Drush::logger()->notice("Deploy hook started: $function");
}
try {
$ret['results']['query'] = $function($context['sandbox']);
$ret['results']['success'] = true;
$ret['type'] = 'deploy';
if (!isset($context['sandbox']['#finished']) || (isset($context['sandbox']['#finished']) && $context['sandbox']['#finished'] >= 1)) {
self::getRegistry()->registerInvokedUpdates([$function]);
}
} catch (\Exception $e) {
// @TODO We may want to do different error handling for different exception
// types, but for now we'll just log the exception and return the message
// for printing.
// @see https://www.drupal.org/node/2564311
Drush::logger()->error($e->getMessage());
$variables = Error::decodeException($e);
unset($variables['backtrace']);
// On windows there is a problem with json encoding a string with backslashes.
$variables['%file'] = strtr($variables['%file'], [DIRECTORY_SEPARATOR => '/']);
$ret['#abort'] = [
'success' => false,
'query' => strip_tags((string) t('%type: @message in %function (line %line of %file).', $variables)),
];
}
} else {
$ret['#abort'] = ['success' => false];
Drush::logger()->warning(dt('Deploy hook function @function not found in file @filename', [
'@function' => $function,
'@filename' => "$filename.php",
]));
}
if (isset($context['sandbox']['#finished'])) {
$context['finished'] = $context['sandbox']['#finished'];
unset($context['sandbox']['#finished']);
}
if (!isset($context['results'][$module][$name])) {
$context['results'][$module][$name] = [];
}
$context['results'][$module][$name] = array_merge($context['results'][$module][$name], $ret);
// Log the message that was returned.
if (!empty($ret['results']['query'])) {
Drush::logger()->notice(strip_tags((string) $ret['results']['query']));
}
if (!empty($ret['#abort'])) {
// Record this function in the list of updates that were aborted.
$context['results']['#abort'][] = $function;
// Setting this value will output an error message.
// @see \DrushBatchContext::offsetSet()
$context['error_message'] = "Deploy hook failed: $function";
} elseif ($context['finished'] == 1 && empty($ret['#abort'])) {
// Setting this value will output a success message.
// @see \DrushBatchContext::offsetSet()
$context['message'] = "Performed: $function";
}
}
/**
* Batch finished callback.
*
* @param boolean $success Whether the batch ended without a fatal error.
*/
public function updateFinished(bool $success, array $results, array $operations): void
{
// In theory there is nothing to do here.
}
/**
* Mark all deploy hooks as having run.
*
* @usage deploy:mark-complete
* Skip all pending deploy hooks and mark them as complete.
*
* @command deploy:mark-complete
* @topics docs:deploy
* @version 10.6.1
*/
public function markComplete(): int
{
$pending = self::getRegistry()->getPendingUpdateFunctions();
self::getRegistry()->registerInvokedUpdates($pending);
$this->logger()->success(dt('Marked %count pending deploy hooks as complete.', ['%count' => count($pending)]));
return self::EXIT_SUCCESS;
}
}