-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdeploy.php
executable file
·421 lines (381 loc) · 15.6 KB
/
deploy.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
<?php
/**
* MagentoDeployer makes it easy to manage Magento deployments on Platform.sh
*/
class MagentoDeployer
{
public static array $FILE_PATHS = [
'installed' => 'app/etc/installed',
'env.php' => 'app/etc/env.php',
'config.php' => 'app/etc/config.php',
];
/**
* Fetch $PLATFORM_RELATIONSHIPS environment variable to array
*
* @return array
*/
public static function getRelationships(): array
{
return (array) json_decode(base64_decode($_ENV['PLATFORM_RELATIONSHIPS']), true);
}
/**
* Pluck Platform service details from $PLATFORM_RELATIONSHIPS as an array
*
* @param string $serviceName the name of the service as defined in .platform/services.yaml
* @return array
*/
public static function getRelationship(string $serviceName): array
{
return (array) static::getRelationships()[$serviceName][0];
}
/**
* Fetch $PLATFORM_ROUTES environment variable as an array
*
* @return array
*/
public static function getRoutes(): array
{
return (array) json_decode(base64_decode($_ENV['PLATFORM_ROUTES']), true);
}
/**
* Pluck route details with the ID "main" from $PLATFORM_ROUTES environment variable as an array
*
* @return array
*/
public static function getMainRouteInfo(): array
{
return array_filter(static::getRoutes(), function ($value) {
return array_key_exists('id', $value) && strtolower($value['id']) === 'magento_route';
});
}
/**
* Fetch the URL assigned to the route with ID of "magento_route" from $PLATFORM_ROUTES environment variable
*
* @return string
*/
public static function getMainRoute(): string
{
return (string) key(static::getMainRouteInfo());
}
/**
* Run a command and get its exit status. An abstraction of passthru() with built-in error handling.
*
* @param string $cmd The command to run in terminal
* @param bool $exitOnFailure
* @return int
*/
public static function run(string $cmd, bool $exitOnFailure = true): int
{
passthru($cmd, $exitStatus);
if ($exitOnFailure && $exitStatus !== 0) {
self::abortBuild("Build failed w/ command: {$cmd}", $exitStatus);
}
return (int) $exitStatus;
}
/**
* Validate that the environment has the expected main route and required services to install Magento.
* Exit if it does not.
*
* @return void
*/
public static function ValidateEnvironment(): void
{
if (! static::getMainRouteInfo()) {
self::abortBuild('Cannot find the main route for Magento. Please add `id: magento_route` to your routes.yaml.', 1);
}
if (! array_key_exists('database', static::getRelationships())) {
self::abortBuild('Cannot find the database service for Magento. Please update your .platform.app.yaml or .platform/applications.yaml to use the relationship name "database" or modify deploy.php to use the new name.', 1);
}
if (! array_key_exists('redis', static::getRelationships())) {
self::abortBuild('Cannot find the main redis service for Magento. Please update your .platform.app.yaml or .platform/applications.yaml to use the relationship name "redis" or modify deploy.php to use the new name.', 1);
}
}
/**
* Check to see if Magento has already been installed based on the existence of the install file.
*
* @return bool
*/
public static function isMagentoInstalled(): bool
{
return file_exists(self::$FILE_PATHS['installed']);
}
/**
* The inverse of self::isMagentoInstalled(). Check to see if Magento has not yet been installed
* based on the existence of the install file.
*
* @return bool
*/
public static function isFreshInstall(): bool
{
return ! static::isMagentoInstalled();
}
/**
* Check to see if Magento's env.php has been created.
*
* @return bool
*/
public static function isEnvConfigured(): bool
{
return file_exists(self::$FILE_PATHS['env.php']);
}
/**
* By default, Magento launches workers from cron jobs. This blocks Platform.sh deployments because the workers
* never stop running. We have a dedicated worker, so we are going to disable this cron feature.
* @return void
*/
public static function disableWorkersFromCrons(): void {
$magentoEnvConfig = include self::$FILE_PATHS['env.php'];
$magentoEnvConfig['cron_consumers_runner'] = [
'cron_run' => false,
];
$modifiedEnv = var_export($magentoEnvConfig, 1);
$newEnvContents = "<?php
return $modifiedEnv;";
self::resetFileFileContent(self::$FILE_PATHS['env.php'], $newEnvContents);
}
/**
* Defines a sequential list of commands to run and the conditions required to run them.
*
* @return array[]
*/
public static function installSteps(): array
{
$redis = self::getRelationship('redis');
$database = self::getRelationship('database');
$search = self::getRelationship('search');
$installFile = self::$FILE_PATHS['installed'];
return [
'Installing Magento 2.3' => [
'only_if' => static::isFreshInstall(),
'cmd' => 'php bin/magento setup:install',
'args' => [
'--ansi',
'--no-interaction',
'--skip-db-validation',
'--base-url='.self::getMainRoute(),
'--db-host='.$database['host'],
'--db-name='.$database['path'],
'--db-user='.$database['username'],
'--backend-frontname=admin',
'--language=en_US',
'--currency=USD',
'--timezone=Europe/Paris',
'--use-rewrites=1',
'--session-save=redis',
'--session-save-redis-host='.$redis['host'],
'--session-save-redis-port='.$redis['port'],
'--session-save-redis-db=0',
'--cache-backend=redis',
'--cache-backend-redis-server='.$redis['host'],
'--cache-backend-redis-port='.$redis['port'],
'--cache-backend-redis-db=1',
'--page-cache=redis',
'--page-cache-redis-server='.$redis['host'],
'--page-cache-redis-port='.$redis['port'],
'--page-cache-redis-db=2',
'--admin-firstname=admin',
'--admin-lastname=admin',
'--admin-user=admin',
'--admin-password=admin123',
],
],
'Requiring admin user to reset password by setting it to expired' => [
'only_if' => self::isFreshInstall(),
'cmd' => 'mysql',
'args' => [
"-h{$database['host']}",
"-u{$database['username']}",
$database['password'] ?? "-p{$database['password']}", // Password, but only if there is one
$database['path'],
"-e \"insert into admin_passwords (user_id, password_hash, expires, last_updated) values (1, '123456789:2', 1, 1435156243);\"",
],
'custom_fail_message' => 'WARNING! Failed to expire admin password. Please login to /admin and reset the password.',
],
'Ensuring latest deployed services are applied to app/etc/env.php' => [
'only_if' => static::isMagentoInstalled(),
'cmd' => 'php bin/magento setup:config:set',
'args' => [
'--ansi',
'--no-interaction',
'--db-host='.$database['host'],
'--db-name='.$database['path'],
'--db-user='.$database['username'],
'--session-save=redis',
'--session-save-redis-host='.$redis['host'],
'--session-save-redis-port='.$redis['port'],
'--session-save-redis-db=0',
'--cache-backend=redis',
'--page-cache-redis-server='.$redis['host'],
'--page-cache-redis-port='.$redis['port'],
'--cache-backend-redis-db=1',
'--page-cache=redis',
'--page-cache-redis-server='.$redis['host'],
'--page-cache-redis-port='.$redis['port'],
'--page-cache-redis-db=2',
],
],
'Purging cache to ensure the latest services are used' => [
'only_if' => static::isMagentoInstalled(),
'cmd' => 'php bin/magento cache:flush',
],
'Ensuring Magento deployment uses the latest configured main route' => [
'only_if' => self::isMagentoInstalled(),
'cmd' => 'php bin/magento config:set',
'args' => ['web/unsecure/base_url', self::getMainRoute()],
],
'Ensuring Magento deployment uses the latest configured Elasticsearch service' => [
'only_if' => true,
'cmd' => 'php bin/magento config:set catalog/search/engine elasticsearch7'
." && php bin/magento config:set catalog/search/elasticsearch7_server_hostname {$search['host']}"
." && php bin/magento config:set catalog/search/elasticsearch7_server_port {$search['port']}",
],
'Clearing Magento\'s cache to ensure we use the values that were just set' => [
'only_if' => true,
'cmd' => 'php bin/magento cache:flush',
],
'Ensuring Magento is in production mode' => [
'only_if' => true, // This will run every time.
'cmd' => 'php bin/magento deploy:mode:set production',
'args' => ['--skip-compilation'],
],
'Entering maintenance mode' => [
'only_if' => self::isMagentoInstalled(),
'cmd' => 'php bin/magento maintenance:enable',
],
'Installing & configuring Magento modules' => [
'only_if' => self::isMagentoInstalled(),
'cmd' => 'php bin/magento setup:upgrade',
],
'Compiling Magento\'s Di config' => [
'only_if' => self::isMagentoInstalled(),
'cmd' => 'php bin/magento setup:di:compile',
],
'Deploying Magento\'s static files' => [
'only_if' => true,
'cmd' => 'php bin/magento setup:static-content:deploy',
],
'Exiting maintenance mode' => [
'only_if' => self::isMagentoInstalled(),
'cmd' => 'php bin/magento maintenance:disable',
],
'Ensuring that Magento is marked as configured.' => [
'only_if' => true, // any time this setup runs successfully we should make sure this file is in place
'cmd' => "echo \"Welcome to Platform.sh! Your Magento site has been deployed!\" >> {$installFile}",
],
'Ensuring that the Magento does not block deployments by launching workers from the cron job' => [
'only_if' => true,
'cmd' => function () { self::disableWorkersFromCrons(); }
],
'Ensuring Magento search and catalog is up-to-date in case of search changes' => [
'only_if' => true,
'cmd' => 'bin/magento indexer:reindex'
],
'Clearing Magento\'s Full Page cache' => [
'only_if' => true,
'cmd' => 'php bin/magento cache:flush full_page block_html config',
],
];
}
/**
* Analyzes and runs a self::InstallStep() if conditions are met.
*
* @param string $summary Summary of the intall step being executed
* @param array $installStep Install step configuration
* @return void
*/
public static function executeInstallStep(string $summary, array $installStep): void
{
$shouldRun = $installStep['only_if'];
if (! $shouldRun) {
return;
}
echo "\n\n ================= \n > Install Step: {$summary}".PHP_EOL;
if (self::isPHPFunction($installStep['cmd'])) {
$installStep['cmd']();
return;
}
$hasCustomError = array_key_exists('custom_fail_message', $installStep);
$exitStatus = self::run(self::installCommand($installStep), ! $hasCustomError);
if ($exitStatus !== 0 && $hasCustomError) {
self::abortBuild($installStep['custom_fail_message'], $exitStatus);
}
}
/**
* Validates that the environment is ready to deploy and triggers the deployment if so.
*
* @return void
*/
public static function deploy(): void
{
static::ValidateEnvironment();
self::executeInstallSteps();
}
/**
* Determines if the $cmd argument is a PHP callable function.
*
* @param $cmd
* @return bool
*/
private static function isPHPFunction($cmd): bool
{
return is_callable($cmd);
}
/**
* Builds a terminal command from the provided $installStep configuration
*
* @param array $installStep Install step configuration as provided by self::InstallSteps()
* @return string
*/
private static function installCommand(array $installStep): string
{
$hasArgs = array_key_exists('args', $installStep) && is_array($installStep['args']);
$args = implode(' ', $hasArgs ? $installStep['args'] : []);
return "{$installStep['cmd']} {$args}";
}
/**
* Ends the PHP process that launched the Magento::Deploy() command with the provided message and exit status.
*
* @param string $message Message to output to PHP process launcher
* @param int $exitStatus Exit status to end the PHP process with
* @return void
*/
private static function abortBuild(string $message, int $exitStatus): void
{
$setBoldOutputCmd = 'echo "------ $(tput -T "xterm-256color" bold) \n"';
$resetOutputCmd = 'echo "\n------ $(tput -T "xterm-256color" sgr0)"';
passthru("figlet -f standard 'DEPLOYMENT ABORTED'");
passthru($setBoldOutputCmd);
echo $message . PHP_EOL;
passthru($resetOutputCmd);
exit($exitStatus);
}
/**
* Execute each of the install steps provided by self::InstallSteps()
*
* @return void
*/
private static function executeInstallSteps(): void
{
foreach (static::installSteps() as $summary => $installStep) {
static::executeInstallStep($summary, $installStep);
}
}
/**
* Replace file content with the provided content.
*
* @param mixed $filePath
* @param string $fileContent
* @return void
*/
private static function resetFileFileContent(string $filePath, string $fileContent): void
{
unlink($filePath);
file_put_contents($filePath, $fileContent);
}
}
MagentoDeployer::deploy();
if (MagentoDeployer::isFreshInstall()) {
echo "\t* You can login at ".MagentoDeployer::getMainRoute().'/admin using the username "admin" and the password "admin123".'.PHP_EOL;
echo "\t* This password will only work once. You will be prompted to update it once logged in.".PHP_EOL;
}