-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclass-command.php
631 lines (548 loc) · 18.6 KB
/
class-command.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
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
<?php
/**
* Local Server Composer Command.
*
* phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
*
* @package altis/local-server
*/
namespace Altis\Local_Server\Composer;
use Composer\Command\BaseCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Process\Process;
/**
* Altis Local Server Composer Command.
*
* @package altis/local-server
*/
class Command extends BaseCommand {
/**
* Command configuration.
*
* @return void
*/
protected function configure() {
$this
->setName( 'server' )
->setDescription( 'Altis Local Server' )
->setDefinition( [
new InputArgument( 'subcommand', null, 'start, stop, restart, cli, exec, shell, status, db, logs.' ),
new InputArgument( 'options', InputArgument::IS_ARRAY ),
] )
->setAliases( [ 'local-server' ] )
->setHelp(
<<<EOT
Run the local development server.
Default command - start the local development server:
start [--xdebug] passing --xdebug starts the server with xdebug enabled
Stop the local development server:
stop
Restart the local development server:
restart [--xdebug] passing --xdebug restarts the server with xdebug enabled
Destroy the local development server:
destroy
View status of the local development server:
status
Run WP CLI command:
cli -- <command> eg: cli -- post list --debug
Run any shell command from the PHP container:
exec -- <command> eg: exec -- vendor/bin/phpcs
Open a shell:
shell
Database commands:
db Log into MySQL on the Database server
db sequel Generates an SPF file for Sequel Pro
db info Prints out Database connection details
View the logs
logs <service> <service> can be php, nginx, db, s3, elasticsearch, xray
Import files from content/uploads directly to s3:
import-uploads Copies files from `content/uploads` to s3
EOT
)
->addOption( 'xdebug' );
}
/**
* Whether the command is proxied.
*
* @return boolean
*/
public function isProxyCommand() {
return true;
}
/**
* Get the common docker-composer command prefix.
*
* @return string
*/
private function get_base_command_prefix() : string {
return sprintf(
'cd %s; VOLUME=%s COMPOSE_PROJECT_NAME=%s',
'vendor/altis/local-server/docker',
escapeshellarg( getcwd() ),
$this->get_project_subdomain()
);
}
/**
* Execute the given command.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int|null
*/
protected function execute( InputInterface $input, OutputInterface $output ) {
$subcommand = $input->getArgument( 'subcommand' );
if ( $subcommand === 'start' ) {
return $this->start( $input, $output );
} elseif ( $subcommand === 'stop' ) {
return $this->stop( $input, $output );
} elseif ( $subcommand === 'restart' ) {
return $this->restart( $input, $output );
} elseif ( $subcommand === 'destroy' ) {
return $this->destroy( $input, $output );
} elseif ( $subcommand === 'cli' ) {
return $this->exec( $input, $output, 'wp' );
} elseif ( $subcommand === 'exec' ) {
return $this->exec( $input, $output );
} elseif ( $subcommand === 'db' ) {
return $this->db( $input, $output );
} elseif ( $subcommand === 'status' ) {
return $this->status( $input, $output );
} elseif ( $subcommand === 'logs' ) {
return $this->logs( $input, $output );
} elseif ( $subcommand === 'shell' ) {
return $this->shell( $input, $output );
} elseif ( $subcommand === 'import-uploads' ) {
return $this->import_uploads( $input, $output );
} elseif ( $subcommand === null ) {
// Default to start command.
return $this->start( $input, $output );
}
$output->writeln( '<error>' . $subcommand . ' command not found.</>' );
return 1;
}
/**
* Get environment variables to pass to docker-compose and other subcommands.
*
* @return array Map of var name => value.
*/
protected function get_env() : array {
return [
'VOLUME' => getcwd(),
'COMPOSE_PROJECT_NAME' => $this->get_project_subdomain(),
'PATH' => getenv( 'PATH' ),
'ES_MEM_LIMIT' => getenv( 'ES_MEM_LIMIT' ) ?: '1g',
];
}
/**
* Start the application.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int|null
*/
protected function start( InputInterface $input, OutputInterface $output ) {
$output->writeln( '<info>Starting...</>' );
$proxy = new Process( 'docker-compose -f proxy.yml up -d', 'vendor/altis/local-server/docker' );
$proxy->setTimeout( 0 );
$proxy->setTty( true );
$proxy_failed = $proxy->run( function ( $type, $buffer ) {
echo $buffer;
} );
if ( $proxy_failed ) {
$output->writeln( '<error>Could not start traefik proxy.</>' );
return $proxy_failed;
}
$env = $this->get_env();
if ( $input->getOption( 'xdebug' ) ) {
$env['PHP_IMAGE'] = 'humanmade/altis-local-server-php:3.2.0-dev';
if ( in_array( php_uname( 's' ), [ 'BSD', 'Linux', 'Solaris', 'Unknown' ], true ) ) {
$env['XDEBUG_REMOTE_HOST'] = '172.17.0.1';
}
}
$compose = new Process( 'docker-compose up -d', 'vendor/altis/local-server/docker', $env );
$compose->setTty( true );
$compose->setTimeout( 0 );
$failed = $compose->run( function ( $type, $buffer ) {
echo $buffer;
} );
if ( $failed ) {
$output->writeln( '<error>Services failed to start successfully.</>' );
return $failed;
}
$cli = $this->getApplication()->find( 'local-server' );
// Check if WP is already installed.
$is_installed = $cli->run( new ArrayInput( [
'subcommand' => 'cli',
'options' => [
'core',
'is-installed',
'--quiet',
],
] ), $output ) === 0;
if ( ! $is_installed ) {
$install_failed = $cli->run( new ArrayInput( [
'subcommand' => 'cli',
'options' => [
'core',
'multisite-install',
'--title=Altis',
'--admin_user=admin',
'--admin_password=password',
'--skip-email',
'--skip-config',
'--quiet',
],
] ), $output );
// Check install was successful.
if ( $install_failed ) {
$output->writeln( sprintf( '<error>WordPress install failed. Exited with error code %d</>', $install_failed ) );
return $install_failed;
}
$output->writeln( '<info>Installed database.</>' );
$output->writeln( '<info>WP Username:</> <comment>admin</>' );
$output->writeln( '<info>WP Password:</> <comment>password</>' );
}
$site_url = 'https://' . $this->get_project_subdomain() . '.altis.dev/';
$output->writeln( '<info>Startup completed.</>' );
$output->writeln( '<info>To access your site visit:</> <comment>' . $site_url . '</>' );
}
/**
* Stop the application.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int
*/
protected function stop( InputInterface $input, OutputInterface $output ) {
$output->writeln( '<info>Stopping...</>' );
$proxy = new Process( 'docker-compose stop', 'vendor/altis/local-server/docker', $this->get_env() );
$proxy->run();
$compose = new Process( 'docker-compose stop', 'vendor/altis/local-server/docker', $this->get_env() );
$return_val = $compose->run( function ( $type, $buffer ) {
echo $buffer;
} );
if ( $return_val === 0 ) {
$output->writeln( '<info>Stopped.</>' );
} else {
$output->writeln( '<error>Failed to stop services.</>' );
}
return $return_val;
}
/**
* Destroys the application.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int
*/
protected function destroy( InputInterface $input, OutputInterface $output ) {
$helper = $this->getHelper( 'question' );
$question = new ConfirmationQuestion( 'Are you sure you want to destroy the server?', false );
if ( ! $helper->ask( $input, $output, $question ) ) {
return false;
}
$output->writeln( '<error>Destroying...</>' );
$proxy = new Process( 'docker-compose down -v', 'vendor/altis/local-server/docker', $this->get_env() );
$proxy->run();
$compose = new Process( 'docker-compose down -v', 'vendor/altis/local-server/docker', $this->get_env() );
$return_val = $compose->run( function ( $type, $buffer ) {
echo $buffer;
} );
if ( $return_val === 0 ) {
$output->writeln( '<error>Destroyed.</>' );
} else {
$output->writeln( '<error>Failed to destroy services.</>' );
}
return $return_val;
}
/**
* Restart the application.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int
*/
protected function restart( InputInterface $input, OutputInterface $output ) {
$output->writeln( '<info>Restarting...</>' );
$proxy = new Process( 'docker-compose restart', 'vendor/altis/local-server/docker', $this->get_env() );
$proxy->run();
$options = $input->getArgument( 'options' );
if ( isset( $options[0] ) ) {
$service = $options[0];
} else {
$service = '';
}
$compose = new Process( "docker-compose restart $service", 'vendor/altis/local-server/docker', $this->get_env() );
$return_val = $compose->run( function ( $type, $buffer ) {
echo $buffer;
} );
if ( $return_val === 0 ) {
$output->writeln( '<info>Restarted.</>' );
} else {
$output->writeln( '<error>Failed to restart services.</>' );
}
return $return_val;
}
/**
* Execute a command on the PHP container.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @param string|null $program The default program to pass input to.
* @return int
*/
protected function exec( InputInterface $input, OutputInterface $output, ?string $program = null ) {
$site_url = 'https://' . $this->get_project_subdomain() . '.altis.dev/';
$options = $input->getArgument( 'options' );
$passed_url = false;
foreach ( $options as $option ) {
if ( strpos( $option, '--url=' ) === 0 ) {
$passed_url = true;
break;
}
}
if ( ! $passed_url && $program === 'wp' ) {
$options[] = '--url=' . $site_url;
}
// Escape all options. Because the shell is going to strip the
// initial escaping like "My string" => My String, then we need
// to reapply escaping.
foreach ( $options as &$option ) {
if ( ! strpos( $option, '=' ) ) {
if ( strpos( $option, '--' ) === 0 ) {
continue;
}
$option = escapeshellarg( $option );
} else {
$arg = strtok( $option, '=' );
$option = $arg . '=' . escapeshellarg( substr( $option, strlen( $arg ) + 1 ) );
}
}
$container_id = exec( sprintf( 'docker ps --filter name=%s_php_1 -q', $this->get_project_subdomain() ) );
if ( ! $container_id ) {
$output->writeln( '<error>PHP container not found to run command.</>' );
return 1;
}
$columns = exec( 'tput cols' );
$lines = exec( 'tput lines' );
$has_stdin = ! posix_isatty( STDIN );
$has_stdout = ! posix_isatty( STDOUT );
$command = sprintf(
'docker exec -e COLUMNS=%d -e LINES=%d -u www-data %s %s %s %s',
$columns,
$lines,
( ! $has_stdin && ! $has_stdout ) && $program === 'wp' ? '-ti' : '', // forward wp-cli's isPiped detection.
$container_id,
$program ?? '',
implode( ' ', $options )
);
passthru( $command, $return_val );
return $return_val;
}
/**
* Get the status of all application containers.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int
*/
protected function status( InputInterface $input, OutputInterface $output ) {
$compose = new Process( 'docker-compose ps', 'vendor/altis/local-server/docker', $this->get_env() );
return $compose->run( function ( $type, $buffer ) {
echo $buffer;
} );
}
/**
* Fetch the logs for a given container.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int
*/
protected function logs( InputInterface $input, OutputInterface $output ) {
$log = $input->getArgument( 'options' )[0];
$compose = new Process( 'docker-compose logs --tail=100 -f ' . $log, 'vendor/altis/local-server/docker', $this->get_env() );
$compose->setTimeout( 0 );
return $compose->run( function ( $type, $buffer ) {
echo $buffer;
} );
}
/**
* SSH into the PHP container.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int
*/
protected function shell( InputInterface $input, OutputInterface $output ) {
$columns = exec( 'tput cols' );
$lines = exec( 'tput lines' );
$command_prefix = $this->get_base_command_prefix();
passthru( sprintf(
"$command_prefix docker-compose exec -e COLUMNS=%d -e LINES=%d php /bin/bash",
$columns,
$lines
), $return_val );
return $return_val;
}
/**
* Access the database or database connection information.
*
* @param InputInterface $input Command input object.
* @param OutputInterface $output Command output object.
* @return int
*/
protected function db( InputInterface $input, OutputInterface $output ) {
$db = $input->getArgument( 'options' )[0] ?? null;
$columns = exec( 'tput cols' );
$lines = exec( 'tput lines' );
$base_command_prefix = $this->get_base_command_prefix();
$base_command = sprintf(
"$base_command_prefix docker-compose exec -e COLUMNS=%d -e LINES=%d db",
$columns,
$lines
);
$return_val = 0;
switch ( $db ) {
case 'info':
$connection_data = $this->get_db_connection_data();
$db_info = <<<EOT
<info>Root password</info>: ${connection_data['MYSQL_ROOT_PASSWORD']}
<info>Database</info>: ${connection_data['MYSQL_DATABASE']}
<info>User</info>: ${connection_data['MYSQL_USER']}
<info>Password</info>: ${connection_data['MYSQL_PASSWORD']}
<info>Host</info>: ${connection_data['HOST']}
<info>Port</info>: ${connection_data['PORT']}
<comment>Version</comment>: ${connection_data['MYSQL_VERSION']}
EOT;
$output->write( $db_info );
break;
case 'sequel':
if ( php_uname( 's' ) === 'Darwin' ) {
$output->writeln( '<error>This command is only supported on MacOS, use composer server db info to see the database connection details.</error>' );
return 1;
}
$connection_data = $this->get_db_connection_data();
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$spf_file_contents = file_get_contents( dirname( __DIR__, 2 ) . '/templates/sequel.xml' );
foreach ( $connection_data as $field_name => $field_value ) {
$spf_file_contents = preg_replace( "/(<%=\s)($field_name)(\s%>)/i", $field_value, $spf_file_contents );
}
$output_file_path = sprintf( '/tmp/%s.spf', $this->get_project_subdomain() );
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
file_put_contents( $output_file_path, $spf_file_contents );
exec( "open $output_file_path", $null, $return_val );
if ( $return_val !== 0 ) {
$output->writeln( '<error>You must have Sequel Pro (https://www.sequelpro.com) installed to use this command</error>' );
}
break;
case null:
// phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
passthru( "$base_command mysql --database=wordpress --user=root -pwordpress", $return_val );
break;
default:
$output->writeln( "<error>The subcommand $db is not recognized</error>" );
$return_val = 1;
}
return $return_val;
}
/**
* Return the Database connection details.
*
* @return array
*/
private function get_db_connection_data() {
$command_prefix = $this->get_base_command_prefix();
$columns = exec( 'tput cols' );
$lines = exec( 'tput lines' );
$base_command = sprintf(
"$command_prefix docker-compose exec -e COLUMNS=%d -e LINES=%d db",
$columns,
$lines
);
// Env variables.
$env_variables = preg_split( '/\r\n|\r|\n/', shell_exec( "$base_command printenv" ) );
$values = array_reduce( $env_variables, function( $values, $env_variable_text ) {
$env_variable = explode( '=', $env_variable_text );
$values[ $env_variable[0] ] = $env_variable[1] ?? '';
return $values;
}, [] );
$keys = [
'MYSQL_ROOT_PASSWORD',
'MYSQL_PASSWORD',
'MYSQL_USER',
'MYSQL_DATABASE',
'MYSQL_VERSION',
];
array_walk( $values, function ( $value, $key ) use ( $keys ) {
return in_array( $key, $keys, true ) ? $value : false;
} );
$db_container_id = shell_exec( "$command_prefix docker-compose ps -q db" );
// Retrieve the forwarded ports using Docker and the container ID.
$ports = shell_exec( sprintf( "$command_prefix docker ps --format '{{.Ports}}' --filter id=%s", $db_container_id ) );
preg_match( '/.*,\s([\d.]+):([\d]+)->.*/', $ports, $ports_matches );
return array_merge(
array_filter( $values ),
[
'HOST' => $ports_matches[1],
'PORT' => $ports_matches[2],
]
);
}
/**
* Import uploads from the host machine to the S3 container.
*
* @return int
*/
protected function import_uploads() {
return $this->minio_client( sprintf(
'mirror --exclude ".*" /content local/s3-%s',
$this->get_project_subdomain()
) );
}
/**
* Pass a command through to the minio client.
*
* @param string $command The command for minio client.
* @return int
*/
protected function minio_client( string $command ) {
$columns = exec( 'tput cols' );
$lines = exec( 'tput lines' );
$base_command = sprintf(
'docker run ' .
'-e COLUMNS=%1%d -e LINES=%2$d ' .
'--volume=%3$s/vendor/altis/local-server/docker/minio.json:/root/.mc/config.json ' .
'--volume=%3$s/content/uploads:/content/uploads:delegated ' .
'--network=%4$s_default ' .
'minio/mc:RELEASE.2020-03-14T01-23-37Z %5$s',
$columns,
$lines,
getcwd(),
$this->get_project_subdomain(),
escapeshellcmd( $command )
);
passthru( $base_command, $return_var );
return $return_var;
}
/**
* Get the name of the project for the local subdomain
*
* @return string
*/
protected function get_project_subdomain() : string {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$composer_json = json_decode( file_get_contents( getcwd() . '/composer.json' ), true );
if ( isset( $composer_json['extra']['altis']['modules']['local-server']['name'] ) ) {
$project_name = $composer_json['extra']['altis']['modules']['local-server']['name'];
} else {
$project_name = basename( getcwd() );
}
return preg_replace( '/[^A-Za-z0-9\-\_]/', '', $project_name );
}
}