forked from EasyEngine/site-command
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSite_Backup_Restore.php
More file actions
1713 lines (1372 loc) · 59.1 KB
/
Site_Backup_Restore.php
File metadata and controls
1713 lines (1372 loc) · 59.1 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
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
namespace EE\Site\Type;
use EE;
use Symfony\Component\Filesystem\Filesystem;
use function EE\Utils\get_config_value;
use function EE\Utils\delem_log;
use function EE\Site\Utils\auto_site_name;
use function EE\Site\Utils\get_site_info;
class Site_Backup_Restore {
// Error type constants for categorized error reporting
const ERROR_TYPE_VALIDATION = 'validation_error'; // Invalid input
const ERROR_TYPE_CONFIG = 'configuration_error'; // Missing config
const ERROR_TYPE_FILESYSTEM = 'filesystem_error'; // File/dir issues
const ERROR_TYPE_NETWORK = 'network_error'; // Upload/download
const ERROR_TYPE_DATABASE = 'database_error'; // DB operations
const ERROR_TYPE_DISK_SPACE = 'disk_space_error'; // Insufficient space
const ERROR_TYPE_LOCK = 'lock_error'; // Concurrent operation
const ERROR_TYPE_FATAL = 'fatal_error'; // PHP fatal
const ERROR_TYPE_INTERRUPTED = 'interrupted'; // Killed/stopped
const ERROR_TYPE_UNKNOWN = 'unknown_error'; // Unexpected
private $fs;
public $site_data;
private $rclone_config_path;
// Properties for EasyDash callback handling
private $dash_auth_enabled = false;
private $dash_backup_id;
private $dash_verify_token;
private $dash_api_url;
private $dash_backup_metadata;
private $dash_backup_completed = false;
private $dash_new_backup_path; // Track new backup path for potential rollback
// Error tracking for EasyDash failure callbacks
private $dash_error_message = '';
private $dash_error_type = 'unknown';
private $dash_error_code = 0;
// Global backup lock handle for serializing backups
private $global_backup_lock_handle = null;
public function __construct() {
$this->fs = new Filesystem();
}
public function backup( $args, $assoc_args = [] ) {
delem_log( 'site backup start' );
$args = auto_site_name( $args, 'site', __FUNCTION__ );
$list_backups = \EE\Utils\get_flag_value( $assoc_args, 'list' );
$dash_auth = \EE\Utils\get_flag_value( $assoc_args, 'dash-auth' );
// For --list or --dash-auth, we handle site disabled state specially
// --list is read-only and should work regardless of site state
// --dash-auth needs to send API callback instead of just exiting with error
if ( $list_backups || $dash_auth ) {
$this->site_data = get_site_info( $args, false, true, true );
} else {
$this->site_data = get_site_info( $args, true, true, true );
}
// Handle --list flag to display available backups
if ( $list_backups ) {
$this->list_remote_backups();
return; // Exit after listing backups
}
// Handle --dash-auth flag for EasyDash integration
if ( $dash_auth ) {
// Debug: Log the raw dash_auth value received
EE::debug( 'Received --dash-auth value: ' . $dash_auth );
// Parse backup-id:backup-verification-token format
$auth_parts = explode( ':', $dash_auth, 2 );
if ( count( $auth_parts ) !== 2 || empty( $auth_parts[0] ) || empty( $auth_parts[1] ) ) {
EE::error( 'Invalid --dash-auth format. Expected: backup-id:backup-verification-token' );
}
// Check for ed-api-url configuration
$ed_api_url = get_config_value( 'ed-api-url', '' );
if ( empty( $ed_api_url ) ) {
EE::error( 'ed-api-url is not configured. Please set it in /opt/easyengine/config/config.yml' );
}
// Store dash auth info in class properties for shutdown handler
// Must be set before any capture_error calls so API callbacks work
$this->dash_auth_enabled = true;
$this->dash_backup_id = $auth_parts[0];
$this->dash_verify_token = $auth_parts[1];
$this->dash_api_url = $ed_api_url;
// Debug: Log parsed values
EE::debug( 'Parsed backup_id: ' . $this->dash_backup_id );
EE::debug( 'Parsed verify_token: ' . $this->dash_verify_token );
EE::debug( 'API URL: ' . $this->dash_api_url );
// Register shutdown handler to send failure callback if backup doesn't complete
register_shutdown_function( [ $this, 'dash_shutdown_handler' ] );
// Check if site is disabled - send API callback with error
if ( ! $this->site_data['site_enabled'] ) {
$error_msg = sprintf( 'Site %s is disabled. Enable it with `ee site enable %s` to create backup.', $this->site_data['site_url'], $this->site_data['site_url'] );
$this->capture_error( $error_msg, self::ERROR_TYPE_VALIDATION, 1003 );
EE::error( $error_msg );
}
}
// Acquire global lock to serialize backups (prevents OOM from concurrent backups)
$this->acquire_global_backup_lock();
// Register shutdown handler to release lock on any exit (error, crash, etc.)
register_shutdown_function( [ $this, 'release_global_backup_lock' ] );
$this->pre_backup_check();
$backup_dir = EE_BACKUP_DIR . '/' . $this->site_data['site_url'];
$this->fs->remove( $backup_dir );
$this->fs->mkdir( $backup_dir );
$this->dash_backup_metadata = $this->backup_site_details( $backup_dir );
switch ( $this->site_data['site_type'] ) {
case 'html':
$this->backup_html( $backup_dir );
break;
case 'php':
case 'wp':
$this->backup_php_wp( $backup_dir );
break;
default:
$this->capture_error(
sprintf( 'Backup is not supported for site type: %s', $this->site_data['site_type'] ),
self::ERROR_TYPE_VALIDATION,
1002
);
EE::error( 'Backup is not supported for this site type.' );
}
$this->rclone_upload( $backup_dir );
$this->fs->remove( $backup_dir );
$this->fs->remove( EE_BACKUP_DIR . '/' . $this->site_data['site_url'] . '.lock' );
// Mark backup as completed and send success callback
$this->dash_backup_completed = true;
if ( $this->dash_auth_enabled ) {
$api_success = $this->send_dash_success_callback(
$this->dash_api_url,
$this->dash_backup_id,
$this->dash_verify_token,
$this->dash_backup_metadata
);
// Only cleanup old backups if API callback succeeded
// If API failed, rollback the newly uploaded backup
if ( $api_success ) {
$this->cleanup_old_backups();
} else {
$this->rollback_failed_backup();
}
}
// Release global backup lock (also released by shutdown handler as safety net)
$this->release_global_backup_lock();
EE::success( 'Backup created successfully.' );
delem_log( 'site backup end' );
}
/**
* Shutdown handler to send failure callback to EasyDash if backup didn't complete.
* This is called when script terminates (including via EE::error which calls exit).
*
* Automatically captures fatal errors and interrupted processes if no error was
* explicitly captured during backup execution.
*/
public function dash_shutdown_handler() {
// Only send failure callback if dash auth was enabled and backup didn't complete
if ( $this->dash_auth_enabled && ! $this->dash_backup_completed ) {
// If no error was captured yet, try to capture shutdown error
if ( empty( $this->dash_error_message ) ) {
$last_error = error_get_last();
// Check if this was a fatal PHP error
if ( $last_error && in_array( $last_error['type'], [
E_ERROR,
E_PARSE,
E_CORE_ERROR,
E_COMPILE_ERROR,
E_USER_ERROR
] ) ) {
$this->capture_error(
sprintf(
'PHP Fatal Error: %s in %s:%d',
$last_error['message'],
basename( $last_error['file'] ),
$last_error['line']
),
self::ERROR_TYPE_FATAL,
5001
);
} else {
// Script was killed, interrupted, or failed unexpectedly
$this->capture_error(
'Backup process was interrupted or killed unexpectedly',
self::ERROR_TYPE_INTERRUPTED,
6000
);
}
}
$this->send_dash_failure_callback(
$this->dash_api_url,
$this->dash_backup_id,
$this->dash_verify_token
);
}
}
/**
* Capture error details for EasyDash failure callback.
* Stores error information to be sent when backup fails.
*
* @param string $message Error message describing what went wrong.
* @param string $type Error type category (use ERROR_TYPE_* constants).
* @param int $code Error code for additional context (optional).
*/
private function capture_error( $message, $type = self::ERROR_TYPE_UNKNOWN, $code = 0 ) {
// Only capture the first error (root cause)
if ( empty( $this->dash_error_message ) ) {
$this->dash_error_message = $message;
$this->dash_error_type = $type;
$this->dash_error_code = $code;
EE::debug( sprintf(
'Captured error for EasyDash: [%s] %s (code: %d)',
$type,
$message,
$code
) );
}
}
public function restore( $args, $assoc_args = [] ) {
delem_log( 'site restore start' );
$args = auto_site_name( $args, 'site', __FUNCTION__ );
$this->site_data = get_site_info( $args, true, true, true );
$backup_id = \EE\Utils\get_flag_value( $assoc_args, 'id' );
$backup_dir = EE_BACKUP_DIR . '/' . $this->site_data['site_url'];
if ( ! $this->fs->exists( $backup_dir ) ) {
$this->fs->mkdir( $backup_dir );
}
if ( $backup_id ) {
if ( ! $this->verify_backup_id( $backup_id ) ) {
EE::error( "Invalid backup ID provided.\nPlease provide a valid ID from the list using 'ee site backup --list " . $this->site_data['site_url'] . "'." );
}
// Set the config path to specified backup ID.
$this->rclone_config_path = \EE\Utils\trailingslashit( $this->get_rclone_config_path() ) . $backup_id;
}
$this->pre_restore_check();
if ( 'wp' === $this->site_data['site_type'] ) {
$this->restore_wp( $backup_dir );
} else {
$this->restore_site( $backup_dir );
}
// restore custom compose files
$this->maybe_restore_custom_docker_compose( $backup_dir );
$this->fs->remove( $backup_dir );
EE::log( 'Reloading site.' );
EE::run_command( [ 'site', 'reload', $this->site_data['site_url'] ], [], [] );
$this->fs->remove( EE_BACKUP_DIR . '/' . $this->site_data['site_url'] . '.lock' );
EE::success( 'Site restored successfully.' );
delem_log( 'site restore end' );
}
private function verify_backup_id( $backup_id ) {
$backups = $this->list_remote_backups( true );
if ( empty( $backups ) ) {
return false;
}
return in_array( $backup_id, $backups, true );
}
private function run_wp_cli_command( $command, $skip_plugins_themes = false ) {
$shell_command = 'timeout -k 10 --preserve-status 120 wp ';
if ( $skip_plugins_themes ) {
$shell_command .= ' --skip-plugins --skip-themes ';
}
$shell_command .= $command;
$output = EE::launch( "ee shell " . $this->site_data['site_url'] . " --skip-tty --command=\"$shell_command\"" );
$clean_output = trim( $output->stdout );
return empty( $clean_output ) ? '-' : $clean_output;
}
private function backup_site_details( $backup_dir ) {
$backup_data = [];
if ( 'wp' === $this->site_data['site_type'] ) {
$post_count = $this->run_wp_cli_command( 'post list --format=count', true );
$page_count = $this->run_wp_cli_command( 'post list --post_type=page --format=count', true );
$comment_count = $this->run_wp_cli_command( 'comment list --format=count', true );
$table_prefix = $this->run_wp_cli_command( 'config get table_prefix', true );
$query = 'SELECT COUNT(*) FROM ' . $table_prefix . 'posts WHERE post_type = "attachment"';
$query_file = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/app/htdocs/query.sql';
$this->fs->dumpFile( $query_file, $query );
$upload_count = $this->run_wp_cli_command( 'db query < /var/www/htdocs/query.sql --skip-column-names | tr -d \'[:space:]\'', true );
$upload_count = empty( $upload_count ) ? 0 : $upload_count;
$this->fs->remove( $query_file );
$plugin_count = $this->run_wp_cli_command( 'plugin list --format=count' );
// if it is not a number, then make it -
$plugin_count = is_numeric( $plugin_count ) ? $plugin_count : '-';
$theme_count = $this->run_wp_cli_command( 'theme list --format=count' );
// if it is not a number, then make it -
$theme_count = is_numeric( $theme_count ) ? $theme_count : '-';
$user_count = $this->run_wp_cli_command( 'user list --format=count', true );
$wp_version = $this->run_wp_cli_command( 'core version', true );
$backup_data = array(
'site_url' => $this->site_data['site_url'],
'site_type' => $this->site_data['site_type'],
'post_count' => $post_count,
'page_count' => $page_count,
'comment_count' => $comment_count,
'upload_count' => $upload_count,
'plugin_count' => $plugin_count,
'theme_count' => $theme_count,
'user_count' => $user_count,
'wp_version' => $wp_version,
);
$plugin_list = "plugin list --format=json";
$plugins_output = $this->run_wp_cli_command( $plugin_list );
$plugins = [];
if ( '-' !== $plugins_output && ! empty( $plugins_output ) ) {
// Check if the output is a valid JSON
if ( ! json_decode( $plugins_output ) ) {
EE::warning( 'Failed to get plugin list.' );
} else {
$plugins = json_decode( $plugins_output, true );
$plugins = array_map(
function ( $plugin ) {
return [
'name' => $plugin['name'],
'status' => $plugin['status'],
'version' => $plugin['version'],
];
}, $plugins
);
}
}
$theme_list = "theme list --format=json";
$themes_output = $this->run_wp_cli_command( $theme_list );
$themes = [];
if ( '-' !== $themes_output && ! empty( $themes_output ) ) {
// Check if the output is a valid JSON
if ( ! json_decode( $themes_output ) ) {
EE::warning( 'Failed to get theme list.' );
} else {
$themes = json_decode( $themes_output, true );
$themes = array_map(
function ( $theme ) {
return [
'name' => $theme['name'],
'status' => $theme['status'],
'version' => $theme['version'],
];
}, $themes
);
}
}
$meta_data = [
'siteUrl' => $this->site_data['site_url'],
'phpVersion' => $this->site_data['php_version'],
'wordpressVersion' => $wp_version,
'plugins' => [ $plugins ],
'themes' => [ $themes ],
];
$meta_file = $backup_dir . '/meta.json';
$this->fs->dumpFile( $meta_file, json_encode( $meta_data, JSON_PRETTY_PRINT ) );
} else {
$backup_data = [
'site_url' => $this->site_data['site_url'],
'site_type' => $this->site_data['site_type'],
];
}
$remote_path = $this->get_remote_path();
$backup_data['remote_path'] = explode( ':', $remote_path )[1];
$backup_data = array_merge( $this->site_data, $backup_data );
$backup_data_file = $backup_dir . '/metadata.json';
$metadata_copy = EE_BACKUP_DIR . '/' . $this->site_data['site_url'] . '.metadata.json';
$this->fs->dumpFile( $backup_data_file, json_encode( $backup_data, JSON_PRETTY_PRINT ) );
$this->fs->copy( $backup_data_file, $metadata_copy );
return $backup_data;
}
private function maybe_backup_custom_docker_compose( $backup_dir ) {
$custom_docker_compose = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/docker-compose-custom.yml';
if ( $this->fs->exists( $custom_docker_compose ) ) {
$this->fs->copy( $custom_docker_compose, $backup_dir . '/docker-compose-custom.yml' );
}
$custom_docker_compose_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/user-docker-compose';
if ( $this->fs->exists( $custom_docker_compose_dir ) ) {
$custom_docker_compose_dir_archive = $backup_dir . '/user-docker-compose.zip';
$archive_command = sprintf( 'cd %s && 7z a -mx=1 %s .', $custom_docker_compose_dir, $custom_docker_compose_dir_archive );
$result = EE::launch( $archive_command );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
// This is optional, so we just log a warning instead of failing
if ( $result->return_code >= 2 ) {
EE::warning( 'Failed to backup custom docker-compose directory. Continuing with backup.' );
}
}
}
private function backup_site_dir( $backup_dir ) {
EE::log( 'Backing up site files.' );
EE::log( 'This may take some time.' );
$site_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/app';
$backup_file = $backup_dir . '/' . $this->site_data['site_url'] . '.zip';
$backup_command = sprintf( 'cd %s && 7z a -mx=1 %s .', $site_dir, $backup_file );
$result = EE::launch( $backup_command );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
// Exit code 1 means warnings (e.g., missing symlink targets) but archive is still created
if ( $result->return_code >= 2 || ! $this->fs->exists( $backup_file ) ) {
$this->capture_error(
'Failed to create site backup archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to create backup archive. Please check disk space and file permissions.' );
}
return $backup_file;
}
private function backup_wp_content_dir( $backup_dir ) {
EE::log( 'Backing up site files.' );
EE::log( 'This may take some time.' );
$container_fs_path = $this->site_data['site_container_fs_path'];
$container_fs_path = str_replace( '/var/www/', '', $container_fs_path );
$site_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/app/' . $container_fs_path;
$backup_file = $backup_dir . '/' . $this->site_data['site_url'] . '.zip';
if ( ! $this->fs->exists( $site_dir . '/wp-content' ) ) {
if ( $this->fs->exists( $site_dir . '/current/wp-content' ) ) {
if ( ! $this->fs->exists( $site_dir . '/wp-cli.yml' ) ) {
$this->fs->dumpFile( $site_dir . '/wp-cli.yml', "path: current/" );
}
$site_dir = $site_dir . '/current';
} else {
EE::warning( 'wp-content directory not found in the site.' );
EE::log( 'Backing up complete site directory.' );
return $this->backup_site_dir( $backup_dir ); // Backup all if wp-content not found
}
}
$backup_command = sprintf( 'cd %s && 7z a -mx=1 %s wp-config.php', $site_dir . '/../', $backup_file );
$result = EE::launch( $backup_command );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
if ( $result->return_code >= 2 || ! $this->fs->exists( $backup_file ) ) {
$this->capture_error(
'Failed to create WordPress content backup archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to create backup archive. Please check disk space and file permissions.' );
}
// meta.json path
$meta_file = $backup_dir . '/meta.json';
// Include meta.json in the zip archive (Corrected logic)
$backup_command = sprintf( 'cd %s && 7z u -snl -mx=1 %s %s wp-content', $site_dir, $backup_file, $meta_file );
$result = EE::launch( $backup_command );
// Remove the file
$this->fs->remove( $meta_file );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
if ( $result->return_code >= 2 || ! $this->fs->exists( $backup_file ) ) {
$this->capture_error(
'Failed to create WordPress content backup archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to create backup archive. Please check disk space and file permissions.' );
}
$uploads_dir = $site_dir . '/wp-content/uploads';
if ( is_link( $uploads_dir ) ) {
$backup_command = sprintf( 'cd %s && 7z u -mx=1 %s wp-content/uploads', $site_dir, $backup_file );
$result = EE::launch( $backup_command );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
if ( $result->return_code >= 2 ) {
$this->capture_error(
'Failed to create WordPress content backup archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to create backup archive. Please check disk space and file permissions.' );
}
}
// Final check that backup file was created successfully
if ( ! $this->fs->exists( $backup_file ) ) {
$this->capture_error(
'Failed to create WordPress content backup archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to create backup archive. Please check disk space and file permissions.' );
}
return $backup_file;
}
private function backup_nginx_conf( $backup_dir ) {
EE::log( 'Backing up nginx configuration.' );
$conf_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/config';
$backup_file = $backup_dir . '/conf.zip';
$backup_command = sprintf( 'cd %s && 7z a -mx=1 %s nginx', $conf_dir, $backup_file );
$result = EE::launch( $backup_command );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
if ( $result->return_code >= 2 || ! $this->fs->exists( $backup_file ) ) {
$this->capture_error(
'Failed to create nginx configuration backup archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to create nginx configuration backup archive. Please check disk space and file permissions.' );
}
}
private function backup_php_conf( $backup_dir ) {
EE::log( 'Backing up php configuration.' );
$conf_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/config';
$backup_file = $backup_dir . '/conf.zip';
$backup_command = sprintf( 'cd %s && 7z u -mx=1 %s php', $conf_dir, $backup_file );
$result = EE::launch( $backup_command );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
if ( $result->return_code >= 2 || ! $this->fs->exists( $backup_file ) ) {
$this->capture_error(
'Failed to create PHP configuration backup archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to create PHP configuration backup archive. Please check disk space and file permissions.' );
}
}
private function backup_html( $backup_dir ) {
$this->backup_site_dir( $backup_dir );
$this->maybe_backup_custom_docker_compose( $backup_dir );
$this->backup_nginx_conf( $backup_dir );
}
private function backup_php_wp( $backup_dir ) {
$this->maybe_backup_custom_docker_compose( $backup_dir );
$this->backup_nginx_conf( $backup_dir );
$this->backup_php_conf( $backup_dir );
if ( ! empty( $this->site_data['db_name'] ) ) {
$this->backup_db( $backup_dir );
}
if ( 'wp' === $this->site_data['site_type'] ) {
$this->backup_wp_content_dir( $backup_dir );
} else {
$this->backup_site_dir( $backup_dir );
}
}
private function backup_db( $backup_dir ) {
// Flush MySQL privileges before backup
if ( 'running' === \EE_DOCKER::container_status( GLOBAL_DB_CONTAINER ) ) {
EE::exec( 'docker exec -it ' . GLOBAL_DB_CONTAINER . " bash -c 'mysql --skip-ssl -uroot -p\$MYSQL_ROOT_PASSWORD -e\"FLUSH PRIVILEGES\"'" );
}
EE::log( 'Backing up database.' );
$db_name = $this->site_data['db_name'];
$db_user = $this->site_data['db_user'];
$db_password = $this->site_data['db_password'];
$db_host = $this->site_data['db_host'];
$backup_file = $backup_dir . '/' . $this->site_data['site_url'] . '.zip';
$sql_filename = $this->site_data['site_url'] . '.sql';
$sql_file = $backup_dir . '/sql/' . $sql_filename;
$this->fs->mkdir( $backup_dir . '/sql' );
$backup_command = sprintf( 'mysqldump --skip-ssl -u %s -p%s -h %s --single-transaction %s > /var/www/htdocs/%s', $db_user, $db_password, $db_host, $db_name, $sql_filename );
$args = [ 'shell', $this->site_data['site_url'] ];
$assoc_args = [ 'command' => $backup_command ];
$options = [ 'skip-tty' => true ];
EE::run_command( $args, $assoc_args, $options );
$sql_dump_path = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/app/htdocs/' . $sql_filename;
// Check if database dump was created successfully
if ( ! $this->fs->exists( $sql_dump_path ) ) {
$this->capture_error(
sprintf( 'Database backup failed for database: %s', $db_name ),
self::ERROR_TYPE_DATABASE,
4002
);
EE::error( 'Database backup failed. Please check database credentials and connectivity.' );
}
EE::exec( sprintf( 'mv %s %s', $sql_dump_path, $sql_file ) );
$backup_command = sprintf( 'cd %s && 7z u -mx=1 %s sql', $backup_dir, $backup_file );
$result = EE::launch( $backup_command );
// 7z exit codes: 0=success, 1=warning (non-fatal), 2+=fatal error
if ( $result->return_code >= 2 || ! $this->fs->exists( $backup_file ) ) {
$this->capture_error(
'Failed to compress database backup into archive',
self::ERROR_TYPE_FILESYSTEM,
3002
);
EE::error( 'Failed to compress database backup. Please check disk space.' );
}
$this->fs->remove( $backup_dir . '/sql' );
}
private function maybe_restore_wp_config( $backup_dir ) {
if ( 'wp' !== $this->site_data['site_type'] ) {
return false;
}
$backup_file = $backup_dir . '/' . $this->site_data['site_url'] . '.zip';
$container_fs_path = $this->site_data['site_container_fs_path'];
$container_fs_path = str_replace( '/var/www/', '', $container_fs_path );
$site_dir = $this->site_data['site_fs_path'] . '/app/' . $container_fs_path;
$wp_config_path = $site_dir . '/../';
$unzip_command = sprintf( 'unzip -o %s wp-config.php -d %s', $backup_file, $wp_config_path );
EE::exec( $unzip_command );
$chown_command = sprintf( 'chown -R www-data:www-data %s', $wp_config_path );
EE::exec( $chown_command );
$db_name = $this->site_data['db_name'];
$db_user = $this->site_data['db_user'];
$db_password = $this->site_data['db_password'];
$db_host = $this->site_data['db_host'];
$args = [ 'shell', $this->site_data['site_url'] ];
$options = [ 'skip-tty' => true ];
$command = sprintf( 'wp config set DB_NAME %s', $db_name );
EE::run_command( $args, [ 'command' => $command ], $options );
$command = sprintf( 'wp config set DB_USER %s', $db_user );
EE::run_command( $args, [ 'command' => $command ], $options );
$command = sprintf( 'wp config set DB_PASSWORD %s', $db_password );
EE::run_command( $args, [ 'command' => $command ], $options );
$command = sprintf( 'wp config set DB_HOST %s', $db_host );
EE::run_command( $args, [ 'command' => $command ], $options );
}
private function maybe_restore_custom_docker_compose( $backup_dir ) {
$custom_compose_update = false;
$custom_docker_compose = $backup_dir . '/docker-compose-custom.yml';
$custom_docker_compose_dir_archive = $backup_dir . '/user-docker-compose.zip';
if ( $this->fs->exists( $custom_docker_compose ) ) {
$custom_compose_update = true;
$this->fs->copy( $custom_docker_compose, EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/docker-compose-custom.yml', true );
}
if ( $this->fs->exists( $custom_docker_compose_dir_archive ) ) {
$custom_compose_update = true;
$custom_docker_compose_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/user-docker-compose';
if ( ! $this->fs->exists( $custom_docker_compose_dir ) ) {
$this->fs->mkdir( $custom_docker_compose_dir );
}
$unzip_command = sprintf( 'unzip -o %s -d %s', $custom_docker_compose_dir_archive, $custom_docker_compose_dir );
EE::exec( $unzip_command );
}
if ( $custom_compose_update ) {
EE::log( 'Custom docker-compose file(s) updated.' );
EE::run_command( [ 'site', 'enable', $this->site_data['site_url'] ], [ 'force' => true ] );
}
}
private function restore_db( $sql_file, $container_path ) {
EE::log( 'Restoring database.' );
$site_url = $this->site_data['site_url'];
$db_user = $this->site_data['db_user'];
$db_password = $this->site_data['db_password'];
$db_host = $this->site_data['db_host'];
$db_name = $this->site_data['db_name'];
$sql_path = "/var/www/$container_path/" . basename( $sql_file ); // Use basename for safety
// Corrected command with proper escaping and error suppression for password
$restore_command = sprintf( "mysql --skip-ssl -u '%s' -p'%s' -h '%s' '%s' < '%s' 2>/dev/null", $db_user, $db_password, $db_host, $db_name, $sql_path );
$args = [ 'shell', $site_url ];
$assoc_args = [ 'command' => $restore_command ];
$options = [ 'skip-tty' => true ];
EE::run_command( $args, $assoc_args, $options );
}
private function restore_site( $backup_dir ) {
$backup_app = $backup_dir . '/' . $this->site_data['site_url'] . '.zip';
if ( ! $this->fs->exists( $backup_app ) ) {
$this->rclone_download( $backup_dir );
}
EE::log( 'Restoring site files.' );
$site_app_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/app';
// Remote the existing content inside the app directory but not the app directory itself
$remove_command = sprintf( 'rm -rf %s/*', $site_app_dir );
EE::exec( $remove_command );
$restore_command = sprintf( 'unzip -o %s -d %s', $backup_app, $site_app_dir );
EE::exec( $restore_command );
$chown_command = sprintf( 'chown -R www-data:www-data %s', \EE\Utils\trailingslashit( $site_app_dir ) );
EE::exec( $chown_command );
$backup_db = $site_app_dir . '/sql/' . $this->site_data['site_url'] . '.sql';
if ( $this->fs->exists( $backup_db ) ) {
$this->restore_db( $backup_db, 'sql' );
$this->fs->remove( $site_app_dir . '/sql' );
}
$this->maybe_restore_custom_docker_compose( $backup_dir );
$this->restore_nginx_conf( $backup_dir );
if ( in_array( $this->site_data['site_type'], [ 'php', 'wp' ], true ) ) {
$this->restore_php_conf( $backup_dir );
}
}
private function restore_wp( $backup_dir ) {
$backup_app = $backup_dir . '/' . $this->site_data['site_url'] . '.zip';
if ( ! $this->fs->exists( $backup_app ) ) {
$this->rclone_download( $backup_dir );
}
EE::log( 'Restoring site files.' );
$container_fs_path = $this->site_data['site_container_fs_path'];
$container_fs_path = str_replace( '/var/www/', '', $container_fs_path );
$site_dir = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/app/' . $container_fs_path;
$unzip_meta_command = sprintf( 'unzip -o %s meta.json -d %s', $backup_app, $backup_dir );
EE::exec( $unzip_meta_command );
$meta_data = json_decode( file_get_contents( $backup_dir . '/meta.json' ), true );
$wp_version = $meta_data['wordpressVersion'];
$args = [ 'shell', $this->site_data['site_url'] ];
$assoc_args = [ 'command' => sprintf( 'wp core download --force --version=%s', $wp_version ) ];
$options = [ 'skip-tty' => true ];
EE::run_command( $args, $assoc_args, $options );
$this->maybe_restore_wp_config( $backup_dir );
$restore_command = sprintf( 'unzip -o %s sql/%s.sql -d %s/app/', $backup_app, $this->site_data['site_url'], $this->site_data['site_fs_path'] );
EE::exec( $restore_command );
$this->restore_db( $this->site_data['site_url'] . '.sql', 'sql' );
$this->fs->remove( $this->site_data['site_fs_path'] . '/app/sql' );
$uploads_moved = false;
// if wp-content/uploads is symlink, then move it one level up
if ( is_link( $site_dir . '/wp-content/uploads' ) ) {
// move the symlink one level up for time being
$mv_command = sprintf( 'mv %s/wp-content/uploads %s/uploads', $site_dir, $site_dir );
EE::exec( $mv_command );
$uploads_moved = true;
}
// Remove all files from wp-content except uploads
$this->fs->remove( $site_dir . '/wp-content' );
$wp_content_command = sprintf( "unzip -o %s 'wp-content/*' -x 'wp-content/uploads/*' -d %s", $backup_app, $site_dir );
EE::exec( $wp_content_command );
if ( $uploads_moved ) {
// move the uploads directory back to wp-content
$mv_command = sprintf( 'mv %s/uploads %s/wp-content/uploads', $site_dir, $site_dir );
EE::exec( $mv_command );
}
$uploads_command = sprintf( "unzip -o %s 'wp-content/uploads/*' -d %s", $backup_app, $site_dir );
EE::exec( $uploads_command );
$this->maybe_restore_custom_docker_compose( $backup_dir );
$chown_command = sprintf( 'chown -R www-data:www-data %s/app/', $this->site_data['site_fs_path'] );
EE::exec( $chown_command );
$this->restore_nginx_conf( $backup_dir );
$this->restore_php_conf( $backup_dir );
$args = [ 'shell', $this->site_data['site_url'] ];
$assoc_args = [ 'command' => 'wp cache flush --skip-plugins --skip-themes' ];
$options = [ 'skip-tty' => true ];
EE::run_command( $args, $assoc_args, $options );
}
private function pre_backup_restore_checks() {
$command = 'rclone --version';
$return_code = EE::exec( $command );
if ( ! $return_code ) {
$this->capture_error(
'rclone is not installed',
self::ERROR_TYPE_CONFIG,
2001
);
EE::error( 'rclone is not installed. Please install rclone for backup/restore: https://rclone.org/downloads/#script-download-and-install' );
}
$command = 'rclone listremotes';
$output = EE::launch( $command );
$rclone_path = get_config_value( 'rclone-path', 'easyengine:easyengine' );
$rclone_backend = explode( ':', $rclone_path )[0];
$rclone_path = $rclone_backend . ':';
if ( strpos( $output->stdout, $rclone_path ) === false ) {
$this->capture_error(
sprintf( 'rclone backend "%s" is not configured. Please create it using `rclone config`', $rclone_backend ),
self::ERROR_TYPE_CONFIG,
2002
);
EE::error( sprintf( 'rclone backend "%s" does not exist. Please create it using `rclone config`', $rclone_backend ) );
}
$this->check_and_install( 'zip', 'zip' );
$this->check_and_install( '7z', 'p7zip-full' );
$this->check_and_install( 'unzip', 'unzip' );
$this->check_and_install( 'rsync', 'rsync' );
if ( ! $this->fs->exists( EE_BACKUP_DIR ) ) {
$this->fs->mkdir( EE_BACKUP_DIR );
}
$lock_file = EE_BACKUP_DIR . '/' . $this->site_data['site_url'] . '.lock';
if ( $this->fs->exists( $lock_file ) ) {
$this->capture_error(
'Another backup/restore process is already running for this site',
self::ERROR_TYPE_LOCK,
2003
);
EE::error( 'Another backup/restore process is running. Please wait for it to complete.' );
} else {
$this->fs->dumpFile( $lock_file, 'lock' );
}
}
private function pre_backup_check() {
$this->pre_backup_restore_checks();
$site_path = EE_ROOT_DIR . '/sites/' . $this->site_data['site_url'] . '/app/htdocs';
$site_size = $this->dir_size( $site_path );
EE::debug( 'Site size: ' . $site_size );
if ( in_array( $this->site_data['site_type'], [ 'php', 'wp' ] ) && ! empty( $this->site_data['db_name'] ) ) {
$site_size += $this->get_db_size();
EE::debug( 'Site size with db: ' . $site_size );
}
$free_space = disk_free_space( EE_BACKUP_DIR );
EE::debug( 'Free space: ' . $free_space );
if ( $site_size > $free_space ) {
$error_message = $this->build_disk_space_error_message( 'backup', $site_size, $free_space );
$this->capture_error(
sprintf(
'Insufficient disk space for backup. Required: %s, Available: %s',
$this->format_bytes( $site_size ),
$this->format_bytes( $free_space )
),
self::ERROR_TYPE_DISK_SPACE,
3001
);
$this->fs->remove( EE_BACKUP_DIR . '/' . $this->site_data['site_url'] . '.lock' );
EE::error( $error_message );
}
}
/**
* Build a disk space error message for backup/restore operations.
*
* @param string $operation The operation name ('backup' or 'restore').
* @param int $required_space The required disk space in bytes.
* @param int $free_space The available free space in bytes.
*
* @return string The formatted error message.
*/
private function build_disk_space_error_message( $operation, $required_space, $free_space ) {
$additional_space = $required_space - $free_space;
$required_formatted = $this->format_bytes( $required_space );
$available_formatted = $this->format_bytes( $free_space );
$needed_formatted = $this->format_bytes( $additional_space );
return sprintf(
"Not enough disk space to take %s.\n" .
"Required: %s (%s bytes)\n" .
"Available: %s (%s bytes)\n" .
"Additional space needed: %s (%s bytes)\n" .
"Please free up some space and try again.",
$operation,
$required_formatted,
number_format( $required_space ),
$available_formatted,
number_format( $free_space ),
$needed_formatted,
number_format( $additional_space )
);
}
private function check_and_install( $command, $name ) {
$status = EE::exec( "command -v $command" );
if ( ! $status ) {
if ( IS_DARWIN ) {
$this->capture_error(
sprintf( '%s is not installed (required for backup/restore)', $name ),
self::ERROR_TYPE_CONFIG,
2010
);
EE::error( "$name is not installed. Please install $name for backup/restore. You can install it using `brew install $name`." );
} else {
$status = EE::exec( 'apt-get --version' );
if ( $status ) {
EE::exec( 'apt-get update' );