-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathsite-utils.php
More file actions
574 lines (480 loc) · 18.3 KB
/
site-utils.php
File metadata and controls
574 lines (480 loc) · 18.3 KB
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
<?php
namespace EE\Site\Utils;
use EE;
use EE\Model\Site;
use Symfony\Component\Filesystem\Filesystem;
use function EE\Utils\get_flag_value;
use function EE\Utils\get_config_value;
use function EE\Utils\sanitize_file_folder_name;
use function EE\Utils\remove_trailing_slash;
use function EE\Utils\trailingslashit;
/**
* Get the site-name from the path from where ee is running if it is a valid site path.
*
* @return bool|String Name of the site or false in failure.
*/
function get_site_name() {
$sites = Site::all( [ 'site_url' ] );
if ( ! empty( $sites ) ) {
if ( IS_DARWIN ) {
$cwd = getcwd();
} else {
$launch = EE::launch( 'pwd' );
$cwd = trim( $launch->stdout );
}
$name_in_path = explode( '/', $cwd );
$site_url = array_intersect( array_column( $sites, 'site_url' ), $name_in_path );
if ( 1 === count( $site_url ) ) {
$name = reset( $site_url );
$path = Site::find( $name );
if ( $path ) {
$site_path = $path->site_fs_path;
if ( substr( $cwd, 0, strlen( $site_path ) ) === $site_path ) {
return $name;
}
}
}
}
return false;
}
/**
* Function to set the site-name in the args when ee is running in a site folder and the site-name has not been passed
* in the args. If the site-name could not be found it will throw an error.
*
* @param array $args The passed arguments.
* @param String $command The command passing the arguments to auto-detect site-name.
* @param String $function The function passing the arguments to auto-detect site-name.
* @param integer $arg_pos Argument position where Site-name will be present.
*
* @return array Arguments with site-name set.
*/
function auto_site_name( $args, $command, $function, $arg_pos = 0 ) {
if ( isset( $args[ $arg_pos ] ) ) {
$possible_site_name = $args[ $arg_pos ];
if ( substr( $possible_site_name, 0, 4 ) === 'http' ) {
$possible_site_name = str_replace( [ 'https', 'http' ], '', $possible_site_name );
}
$url_path = parse_url( EE\Utils\remove_trailing_slash( $possible_site_name ), PHP_URL_PATH );
if ( Site::find( $url_path ) ) {
return $args;
}
}
$site_url = get_site_name();
if ( $site_url ) {
if ( isset( $args[ $arg_pos ] ) ) {
EE::error( $args[ $arg_pos ] . " is not a valid site-name. Did you mean `ee $command $function $site_url`?" );
}
array_splice( $args, $arg_pos, 0, $site_url );
} else {
EE::error( "Could not find the site you wish to run $command $function command on.\nEither pass it as an argument: `ee $command $function <site-name>` \nor run `ee $command $function` from inside the site folder." );
}
return $args;
}
/**
* Populate basic site info from db.
*
* @param bool $site_enabled_check Check if site is enabled. Throw error message if not enabled.
* @param bool $exit_if_not_found Check if site exists. Throw error message if not, else return false.
* @param bool $return_array Return array of data or object.
*
* @return mixed $site_data Site data from db.
*/
function get_site_info( $args, $site_enabled_check = true, $exit_if_not_found = true, $return_array = true ) {
$site_url = \EE\Utils\remove_trailing_slash( $args[0] );
$data = Site::find( $site_url );
$array_data = ( array ) $data;
$site_data = $return_array ? reset( $array_data ) : $data;
if ( ! $data ) {
if ( $exit_if_not_found ) {
\EE::error( sprintf( 'Site %s does not exist.', $site_url ) );
}
return false;
}
if ( ! $data->site_enabled && $site_enabled_check ) {
\EE::error( sprintf( 'Site %1$s is not enabled. Use `ee site enable %1$s` to enable it.', $data->site_url ) );
}
return $site_data;
}
/**
* Create user in remote or global db.
*
* @param string $db_host Database Hostname.
* @param string $db_name Database name to be created.
* @param string $db_user Database user to be created.
* @param string $db_pass Database password to be created.
*
* @return array|bool Finally created database name, user and password.
*/
function create_user_in_db( $db_host, $db_name = '', $db_user = '', $db_pass = '' ) {
$db_name = empty( $db_name ) ? \EE\Utils\random_password( 5 ) : $db_name;
$db_user = empty( $db_user ) ? \EE\Utils\random_password( 5 ) : $db_user;
$db_pass = empty( $db_pass ) ? \EE\Utils\random_password() : $db_pass;
$create_string = sprintf( "CREATE USER '%1\$s'@'%%' IDENTIFIED BY '%2\$s'; CREATE DATABASE %3\$s; GRANT ALL PRIVILEGES ON %3\$s.* TO '%1\$s'@'%%'; FLUSH PRIVILEGES;", $db_user, $db_pass, $db_name );
if ( GLOBAL_DB === $db_host ) {
$health_script = 'mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e"exit"';
$db_script_path = \EE\Utils\get_temp_dir() . 'db_exec';
file_put_contents( $db_script_path, $health_script );
$mysql_unhealthy = true;
EE::exec( sprintf( 'docker cp %s %s:/db_exec', $db_script_path, GLOBAL_DB_CONTAINER ) );
$count = 0;
while ( $mysql_unhealthy ) {
$mysql_unhealthy = ! EE::exec( sprintf( 'docker exec %s sh db_exec', GLOBAL_DB_CONTAINER ) );
if ( $count ++ > 60 ) {
break;
}
sleep( 1 );
}
$db_script_path = \EE\Utils\get_temp_dir() . 'db_exec';
file_put_contents( $db_script_path, sprintf( 'mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e"%s"', $create_string ) );
EE::exec( sprintf( 'docker cp %s %s:/db_exec', $db_script_path, GLOBAL_DB_CONTAINER ) );
if ( ! EE::exec( sprintf( 'docker exec %s sh db_exec', GLOBAL_DB_CONTAINER ) ) ) {
return false;
}
} else {
//TODO: Handle remote case.
}
return [
'db_name' => $db_name,
'db_user' => $db_user,
'db_pass' => $db_pass,
];
}
/**
* Function to cleanup database.
*
* @param string $db_host Database host from which database is to be removed.
* @param string $db_name Database name to be removed.
* @param string $db_user Database user to remove the host.
* @param string $db_pass Database password of the user.
*/
function cleanup_db( $db_host, $db_name, $db_user = '', $db_pass = '' ) {
$cleanup_string = sprintf( 'DROP DATABASE %s;', $db_name );
if ( GLOBAL_DB === $db_host ) {
$db_script_path = \EE\Utils\get_temp_dir() . 'db_exec';
file_put_contents( $db_script_path, sprintf( 'mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e"%s"', $cleanup_string ) );
EE::exec( sprintf( 'docker cp %s %s:/db_exec', $db_script_path, GLOBAL_DB_CONTAINER ) );
EE::exec( sprintf( 'docker exec %s sh db_exec', GLOBAL_DB_CONTAINER ) );
}
}
/**
* Function to cleanup database user.
*
* @param string $db_host Database host from which user is to be removed.
* @param string $db_user_to_be_cleaned Database user to be removed.
* @param string $db_privileged_pass User having sufficient privilege to delete the given user.
* @param string $db_privileged_user Password of that privileged user.
*/
function cleanup_db_user( $db_host, $db_user_to_be_cleaned, $db_privileged_pass = '', $db_privileged_user = 'root' ) {
$cleanup_string = sprintf( 'DROP USER \'%s\'@\'%%\';', $db_user_to_be_cleaned );
if ( GLOBAL_DB === $db_host ) {
$db_script_path = \EE\Utils\get_temp_dir() . 'db_exec';
file_put_contents( $db_script_path, sprintf( 'mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e"%s"', $cleanup_string ) );
EE::exec( sprintf( 'docker cp %s %s:/db_exec', $db_script_path, GLOBAL_DB_CONTAINER ) );
EE::exec( sprintf( 'docker exec %s sh db_exec', GLOBAL_DB_CONTAINER ) );
}
}
/**
* Creates site root directory if does not exist.
* Throws error if it does exist.
*
* @param string $site_fs_path Root directory of the site.
* @param string $site_url Name of the site.
*/
function create_site_root( $site_fs_path, $site_url ) {
$fs = new Filesystem();
if ( $fs->exists( $site_fs_path ) ) {
EE::error( "Webroot directory for site $site_url already exists." );
}
$whoami = EE::launch( 'whoami', false, true );
$terminal_username = rtrim( $whoami->stdout );
$fs->mkdir( $site_fs_path );
$fs->chown( $site_fs_path, $terminal_username );
}
/**
* Adds www to non-www redirection to site
*
* @param string $site_url name of the site.
* @param bool $ssl enable ssl or not.
* @param bool $inherit inherit cert or not.
*/
function add_site_redirects( string $site_url, bool $ssl, bool $inherit ) {
$fs = new Filesystem();
$confd_path = EE_ROOT_DIR . '/services/nginx-proxy/conf.d/';
$config_file_path = $confd_path . $site_url . '-redirect.conf';
$has_www = strpos( $site_url, 'www.' ) === 0;
$cert_site_name = $site_url;
$ssl_policy = get_ssl_policy();
$conf_ssl_policy = 'ssl_policy_' . str_replace( '-', '_', $ssl_policy );
if ( $inherit ) {
$cert_site_name = implode( '.', array_slice( explode( '.', $site_url ), 1 ) );
}
if ( $has_www ) {
$server_name = ltrim( $site_url, '.www' );
} else {
$server_name = 'www.' . $site_url;
}
$conf_data = [
'site_name' => $site_url,
'cert_site_name' => $cert_site_name,
'server_name' => $server_name,
'ssl' => $ssl,
$conf_ssl_policy => true,
];
$content = EE\Utils\mustache_render( SITE_TEMPLATE_ROOT . '/redirect.conf.mustache', $conf_data );
$fs->dumpFile( $config_file_path, ltrim( $content, PHP_EOL ) );
}
/**
* Function to check config and return a valid ssl-policy.
*
* @return string Valid ssl-policy.
*/
function get_ssl_policy() {
$ssl_policy = get_config_value( 'ssl-policy', 'Mozilla-Modern' );
$valid_configurations = [
'Mozilla-Old',
'Mozilla-Intermediate',
'Mozilla-Modern',
'AWS-TLS-1-2-2017-01',
'AWS-TLS-1-1-2017-01',
'AWS-2016-08',
'AWS-2015-05',
'AWS-2015-03',
'AWS-2015-02',
];
return in_array( $ssl_policy, $valid_configurations, true ) ? $ssl_policy : 'Mozilla-Modern';
}
/**
* Function to create entry in /etc/hosts.
*
* @param string $site_url Name of the site.
*/
function create_etc_hosts_entry( $site_url ) {
if ( IS_DARWIN ) {
// setup_dnsmasq_for_darwin only if domain ends with `.test`
$ends_with_string = '.test';
$diff = strlen( $site_url ) - strlen( $ends_with_string );
if ( $diff >= 0 && false !== strpos( $site_url, $ends_with_string, $diff ) ) {
setup_dnsmasq_for_darwin();
}
return;
}
$host_line = LOCALHOST_IP . "\t$site_url";
$etc_hosts = file_get_contents( '/etc/hosts' );
if ( ! preg_match( "/\s+$site_url\$/m", $etc_hosts ) ) {
if ( EE::exec( "/bin/bash -c 'echo \"$host_line\" >> /etc/hosts'" ) ) {
EE::success( 'Host entry successfully added.' );
} else {
EE::warning( "Failed to add $site_url in host entry, Please do it manually!" );
}
} else {
EE::log( 'Host entry already exists.' );
}
}
/**
* Setup dnsmasq for darwin to resolve `*.test` domain.
*
* @return bool success.
*/
function setup_dnsmasq_for_darwin() {
if ( ! IS_DARWIN ) {
return false;
}
// check if brew is installed.
if ( EE::exec( 'command -v brew' ) ) {
$fs = new Filesystem();
if ( $fs->exists( '/etc/resolver/test' ) ) {
return true;
}
} else {
return false;
}
// check if dnsmasq is installed.
if ( ! EE::exec( 'brew ls --versions dnsmasq' ) ) {
return false;
}
// create config directory.
EE::exec( 'mkdir -p $(brew --prefix)/etc/' );
// Setup `*.test` domain.
EE::exec( "echo 'address=/.test/127.0.0.1' > $(brew --prefix)/etc/dnsmasq.conf" );
EE::log( 'Setting up dnsmasq for *.test domain. You might need to enter password.' );
// Add to LaunchDaemons so that it works after reboot.
EE::exec( 'sudo cp -v $(brew --prefix dnsmasq)/homebrew.mxcl.dnsmasq.plist /Library/LaunchDaemons' );
// Create resolver directory.
EE::exec( 'sudo mkdir -v /etc/resolver' );
// Adding 127.0.0.1 nameserver to resolvers.
EE::exec( "sudo bash -c 'echo \"nameserver 127.0.0.1\" > /etc/resolver/test'" );
// start it.
if ( EE::exec( 'sudo launchctl load -w /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist' ) ) {
return true;
}
return false;
}
/**
* Checking site is running or not.
*
* @param string $site_url Name of the site.
*
* @throws \Exception when fails to connect to site.
*/
function site_status_check( $site_url ) {
EE::log( 'Checking and verifying site-up status. This may take some time.' );
$config_80_port = \EE\Utils\get_config_value( 'proxy_80_port', 80 );
$httpcode = \EE\Utils\get_curl_info( $site_url, $config_80_port );
$i = 0;
$auth = false;
while ( 200 !== $httpcode && 302 !== $httpcode && 301 !== $httpcode ) {
EE::debug( "$site_url status httpcode: $httpcode" );
if ( 401 === $httpcode ) {
$user_pass = get_global_auth();
$auth = $user_pass['username'] . ':' . $user_pass['password'];
}
$httpcode = \EE\Utils\get_curl_info( $site_url, $config_80_port, false, $auth, true );
echo '.';
sleep( 2 );
if ( $i ++ > 60 ) {
break;
}
}
EE::debug( "$site_url status httpcode: $httpcode" );
echo PHP_EOL;
if ( 200 !== $httpcode && 302 !== $httpcode && 301 !== $httpcode ) {
throw new \Exception( 'Problem connecting to site!' );
}
}
/**
* Function to pull the latest images and bring up the site containers and set EasyEngine header.
*
* @param string $site_fs_path Root directory of the site.
* @param array $containers The minimum required conatainers to start the site. Default null, leads to starting of all containers.
*
* @throws \Exception when docker-compose up fails.
*/
function start_site_containers( $site_fs_path, $containers = [] ) {
EE::log( 'Starting site\'s services.' );
if ( ! \EE_DOCKER::docker_compose_up( $site_fs_path, $containers ) ) {
throw new \Exception( 'There was some error in docker-compose up.' );
}
}
/**
* Function to restart given containers for a site and update EasyEngine header.
*
* @param string $site_fs_path Root directory of the site.
* @param string|array $containers Containers to restart.
*/
function restart_site_containers( $site_fs_path, $containers ) {
EE::log( 'Restarting site\'s services.' );
$all_containers = is_array( $containers ) ? implode( ' ', $containers ) : $containers;
if ( ! \EE_DOCKER::docker_compose_restart( $site_fs_path, $all_containers ) ) {
throw new \Exception( 'There was some error in docker-compose restart.' );
}
}
/**
* Function to stop given containers for a site.
*
* @param string $site_fs_path Root directory of the site.
* @param string|array $containers Containers to stop.
*/
function stop_site_containers( $site_fs_path, $containers ) {
EE::log( 'Stopping and removing site\'s services.' );
$all_containers = is_array( $containers ) ? implode( ' ', $containers ) : $containers;
$stopped = \EE_DOCKER::docker_compose_stop( $site_fs_path, $all_containers );
$forcermd = \EE_DOCKER::docker_compose_forcerm( $site_fs_path, $all_containers );
if ( ! (stopped && forcermd) ) {
throw new \Exception( 'There was some error in stopping and removing containers.' );
}
}
/**
* Function to copy and configure files needed for postfix.
*
* @param string $site_url Name of the site to configure postfix files for.
* @param string $site_service_dir Configuration directory of the site `site_root/services`.
*/
function set_postfix_files( $site_url, $site_service_dir ) {
$fs = new Filesystem();
$fs->mkdir( $site_service_dir . '/postfix/ssl' );
$ssl_dir = $site_service_dir . '/postfix/ssl';
if ( ! EE::exec( sprintf( "openssl req -new -x509 -nodes -days 365 -subj \"/CN=smtp.%s\" -out $ssl_dir/server.crt -keyout $ssl_dir/server.key", $site_url ) )
&& EE::exec( "chmod 0600 $ssl_dir/server.key" ) ) {
throw new \Exception( 'Unable to generate ssl key for postfix' );
}
}
/**
* Function to execute docker-compose exec calls to postfix to get it configured and running for the site.
*
* @param string $site_url Name of the for which postfix has to be configured.
* @param string $site_fs_path Site root.
*/
function configure_postfix( $site_url, $site_fs_path ) {
chdir( $site_fs_path );
EE::exec( 'docker-compose exec postfix postconf -e \'relayhost =\'' );
EE::exec( 'docker-compose exec postfix postconf -e \'smtpd_recipient_restrictions = permit_mynetworks\'' );
$launch = EE::launch( sprintf( 'docker inspect -f \'{{ with (index .IPAM.Config 0) }}{{ .Subnet }}{{ end }}\' %s', $site_url ) );
$subnet_cidr = trim( $launch->stdout );
EE::exec( sprintf( 'docker-compose exec postfix postconf -e \'mynetworks = %s 127.0.0.0/8\'', $subnet_cidr ) );
EE::exec( sprintf( 'docker-compose exec postfix postconf -e \'myhostname = %s\'', $site_url ) );
EE::exec( 'docker-compose exec postfix postconf -e \'syslog_name = $myhostname\'' );
EE::exec( 'docker-compose restart postfix' );
}
/**
* Reload the global nginx proxy.
*/
function reload_global_nginx_proxy() {
if ( \EE::launch( sprintf( 'docker exec %s sh -c "nginx -t"', EE_PROXY_TYPE ) ) ) {
return \EE::launch( sprintf( 'docker exec %s sh -c "/app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload"', EE_PROXY_TYPE ) );
}
return false;
}
/**
* Get global auth if it exists.
*/
function get_global_auth() {
if ( ! class_exists( '\EE\Model\Auth' ) ) {
return false;
}
$auth = \EE\Model\Auth::where( [
'site_url' => 'default',
] );
if ( empty( $auth ) ) {
return false;
}
return [
'username' => $auth[0]->username,
'password' => $auth[0]->password,
];
}
/**
* Clear site cache with specific key.
*
* @param string $key Cache key to clear.
*/
function clean_site_cache( $key ) {
EE::exec( sprintf( 'docker exec -it %s redis-cli --eval purge_all_cache.lua 0 , "%s*"', GLOBAL_REDIS_CONTAINER, $key ) );
}
/**
* Function to get the public-dir from assoc args with checks and sanitizations.
*
* @param $assoc_args
*
* @return string processed value for public-dir.
*/
function get_public_dir( $assoc_args ) {
// Create container fs path for site.
$public_root = get_flag_value( $assoc_args, 'public-dir' );
$public_root = str_replace( '/var/www/htdocs/', '', trailingslashit( $public_root ) );
$public_root = remove_trailing_slash( $public_root );
$sanitized_public_dir = sanitize_file_folder_name( $public_root );
$user_input_public_dir = sprintf( '/var/www/htdocs/%s', trim( $sanitized_public_dir, '/' ) );
return empty( $public_root ) ? '/var/www/htdocs' : $user_input_public_dir;
}
/**
* Get final source directory for site webroot.
*
* @param $original_src_dir Default source directory.
* @param $container_fs_path public directory set by user if any.
*
* @return string final webroot for site.
*/
function get_webroot( $original_src_dir, $container_fs_path ) {
$public_dir_path = str_replace( '/var/www/htdocs/', '', trailingslashit( $container_fs_path ) );
return empty( $public_dir_path ) ? $original_src_dir : $original_src_dir . '/' . rtrim( $public_dir_path, '/' );
}