coolify/app/Livewire/Project/Database/BackupEdit.php

383 lines
14 KiB
PHP
Raw Permalink Normal View History

<?php
2023-12-07 18:06:32 +00:00
namespace App\Livewire\Project\Database;
use App\Jobs\DatabaseBackupJob;
use App\Models\S3Storage;
2024-05-24 15:20:20 +00:00
use App\Models\ScheduledDatabaseBackup;
use App\Models\ServiceDatabase;
2024-11-04 11:40:10 +00:00
use Exception;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
2024-11-04 11:40:10 +00:00
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
class BackupEdit extends Component
{
use AuthorizesRequests;
2024-11-04 11:40:10 +00:00
public ScheduledDatabaseBackup $backup;
2024-06-10 20:43:34 +00:00
public string $section = 'general';
2024-11-04 11:40:10 +00:00
#[Locked]
public $availableS3Storages;
2024-06-10 20:43:34 +00:00
2024-11-04 11:40:10 +00:00
#[Locked]
public $parameters;
#[Validate(['required', 'boolean'])]
2024-09-02 17:27:21 +00:00
public bool $delete_associated_backups_locally = false;
2024-09-23 17:51:31 +00:00
#[Validate(['required', 'boolean'])]
2024-09-02 17:27:21 +00:00
public bool $delete_associated_backups_s3 = false;
2024-09-23 17:51:31 +00:00
#[Validate(['required', 'boolean'])]
2024-09-02 17:27:21 +00:00
public bool $delete_associated_backups_sftp = false;
#[Validate(['nullable', 'string'])]
2023-10-10 11:10:43 +00:00
public ?string $status = null;
2024-06-10 20:43:34 +00:00
#[Validate(['required', 'boolean'])]
2024-11-04 11:40:10 +00:00
public bool $backupEnabled = false;
#[Validate(['required', 'string'])]
2024-11-04 11:40:10 +00:00
public string $frequency = '';
#[Validate(['string'])]
2025-01-03 19:39:27 +00:00
public string $timezone = '';
#[Validate(['required', 'integer'])]
public int $databaseBackupRetentionAmountLocally = 0;
#[Validate(['required', 'integer'])]
public ?int $databaseBackupRetentionDaysLocally = 0;
#[Validate(['required', 'numeric', 'min:0'])]
public ?float $databaseBackupRetentionMaxStorageLocally = 0;
#[Validate(['required', 'integer'])]
public ?int $databaseBackupRetentionAmountS3 = 0;
#[Validate(['required', 'integer'])]
public ?int $databaseBackupRetentionDaysS3 = 0;
#[Validate(['required', 'numeric', 'min:0'])]
public ?float $databaseBackupRetentionMaxStorageS3 = 0;
2024-11-04 11:40:10 +00:00
#[Validate(['required', 'boolean'])]
2024-11-04 11:40:10 +00:00
public bool $saveS3 = false;
#[Validate(['required', 'boolean'])]
public bool $disableLocalBackup = false;
2025-01-13 20:26:20 +00:00
#[Validate(['nullable', 'integer'])]
public ?int $s3StorageId = null;
2024-11-04 11:40:10 +00:00
2025-01-13 20:26:20 +00:00
#[Validate(['nullable', 'string'])]
2024-11-04 11:40:10 +00:00
public ?string $databasesToBackup = null;
#[Validate(['required', 'boolean'])]
2024-11-04 11:40:10 +00:00
public bool $dumpAll = false;
#[Validate(['required', 'int', 'min:60', 'max:36000'])]
public int|string $timeout = 3600;
public function getListeners(): array
{
// Keep "Backup Now" in sync when the database starts/stops without a full page refresh.
$listeners = ['databaseUpdated' => 'refreshStatus'];
$user = Auth::user();
if (! $user) {
return $listeners;
}
$listeners["echo-private:user.{$user->id},DatabaseStatusChanged"] = 'refreshStatus';
$team = $user->currentTeam();
if ($team) {
$listeners["echo-private:team.{$team->id},ServiceChecked"] = 'refreshStatus';
}
return $listeners;
}
2023-08-10 14:28:29 +00:00
public function mount()
{
2024-11-04 11:40:10 +00:00
try {
$this->authorize('view', $this->backup->database);
2024-11-04 11:40:10 +00:00
$this->parameters = get_route_parameters();
$this->syncData();
$this->refreshStatus();
2024-11-04 11:40:10 +00:00
} catch (Exception $e) {
return handleError($e, $this);
}
}
public function refreshStatus(): void
{
$database = $this->backup->database;
if (! $database) {
return;
}
$database->refresh();
$this->status = $database->status;
}
2024-11-04 11:40:10 +00:00
public function syncData(bool $toModel = false)
{
if ($toModel) {
$this->backup->enabled = $this->backupEnabled;
$this->backup->frequency = $this->frequency;
$this->backup->database_backup_retention_amount_locally = $this->databaseBackupRetentionAmountLocally;
$this->backup->database_backup_retention_days_locally = $this->databaseBackupRetentionDaysLocally;
$this->backup->database_backup_retention_max_storage_locally = $this->databaseBackupRetentionMaxStorageLocally;
$this->backup->database_backup_retention_amount_s3 = $this->databaseBackupRetentionAmountS3;
$this->backup->database_backup_retention_days_s3 = $this->databaseBackupRetentionDaysS3;
$this->backup->database_backup_retention_max_storage_s3 = $this->databaseBackupRetentionMaxStorageS3;
2024-11-04 11:40:10 +00:00
$this->backup->save_s3 = $this->saveS3;
$this->backup->disable_local_backup = $this->disableLocalBackup;
2024-11-04 11:40:10 +00:00
$this->backup->s3_storage_id = $this->s3StorageId;
// Validate databases_to_backup to prevent command injection
// Handles all formats including MongoDB's "db:col1,col2|db2:col3"
if (filled($this->databasesToBackup)) {
validateDatabasesBackupInput($this->databasesToBackup);
}
2024-11-04 11:40:10 +00:00
$this->backup->databases_to_backup = $this->databasesToBackup;
$this->backup->dump_all = $this->dumpAll;
$this->backup->timeout = $this->timeout;
$this->customValidate();
2024-11-04 11:40:10 +00:00
$this->backup->save();
} else {
$this->backupEnabled = $this->backup->enabled;
$this->frequency = $this->backup->frequency;
2025-01-03 19:39:27 +00:00
$this->timezone = data_get($this->backup->server(), 'settings.server_timezone', 'Instance timezone');
$this->databaseBackupRetentionAmountLocally = $this->backup->database_backup_retention_amount_locally;
$this->databaseBackupRetentionDaysLocally = $this->backup->database_backup_retention_days_locally;
$this->databaseBackupRetentionMaxStorageLocally = $this->backup->database_backup_retention_max_storage_locally;
$this->databaseBackupRetentionAmountS3 = $this->backup->database_backup_retention_amount_s3;
$this->databaseBackupRetentionDaysS3 = $this->backup->database_backup_retention_days_s3;
$this->databaseBackupRetentionMaxStorageS3 = $this->backup->database_backup_retention_max_storage_s3;
2024-11-04 11:40:10 +00:00
$this->saveS3 = $this->backup->save_s3;
$this->disableLocalBackup = $this->backup->disable_local_backup ?? false;
$this->s3StorageId = $this->backup->s3_storage_id ?? $this->availableS3StorageIds()->first();
2024-11-04 11:40:10 +00:00
$this->databasesToBackup = $this->backup->databases_to_backup;
$this->dumpAll = $this->backup->dump_all;
$this->timeout = $this->backup->timeout;
2023-08-11 14:13:53 +00:00
}
2023-08-10 14:28:29 +00:00
}
public function delete($password, $selectedActions = [])
2023-08-10 14:25:59 +00:00
{
$this->authorize('manageBackups', $this->backup->database);
if (! verifyPasswordConfirmation($password, $this)) {
return 'The provided password is incorrect.';
}
2024-03-21 11:44:32 +00:00
try {
$server = null;
if ($this->backup->database instanceof ServiceDatabase) {
$server = $this->backup->database->service->destination->server;
} elseif ($this->backup->database->destination && $this->backup->database->destination->server) {
$server = $this->backup->database->destination->server;
2024-09-02 17:27:21 +00:00
}
$filenames = $this->backup->executions()
->whereNotNull('filename')
->where('filename', '!=', '')
->where('scheduled_database_backup_id', $this->backup->id)
->pluck('filename')
->filter()
->all();
if (! empty($filenames)) {
if ($this->delete_associated_backups_locally && $server) {
deleteBackupsLocally($filenames, $server);
}
if ($this->delete_associated_backups_s3 && $this->backup->s3) {
deleteBackupsS3($filenames, $this->backup->s3);
}
}
2024-03-21 11:44:32 +00:00
$this->backup->delete();
if ($this->backup->database->getMorphClass() === ServiceDatabase::class) {
$serviceDatabase = $this->backup->database;
return redirect()->route('project.service.database.backups', [
'project_uuid' => $this->parameters['project_uuid'],
'environment_uuid' => $this->parameters['environment_uuid'],
'service_uuid' => $serviceDatabase->service->uuid,
'stack_service_uuid' => $serviceDatabase->uuid,
]);
} else {
return redirect()->route('project.database.backup.index', [
'project_uuid' => $this->parameters['project_uuid'],
'environment_uuid' => $this->parameters['environment_uuid'],
'database_uuid' => $this->parameters['database_uuid'],
]);
2024-03-21 11:44:32 +00:00
}
} catch (Exception $e) {
$this->dispatch('error', 'Failed to delete backup: '.$e->getMessage());
2024-03-21 11:44:32 +00:00
return handleError($e, $this);
2023-11-07 11:11:47 +00:00
}
2023-08-10 14:25:59 +00:00
}
public function backupNow()
{
try {
$this->authorize('manageBackups', $this->backup->database);
DatabaseBackupJob::dispatch($this->backup);
$this->dispatch('success', 'Backup queued. It will be available in a few minutes.');
$database = $this->backup->database;
if ($database instanceof ServiceDatabase) {
return redirect()->route('project.service.database.backup.executions', [
'project_uuid' => $database->service->project()->uuid,
'environment_uuid' => $database->service->environment->uuid,
'service_uuid' => $database->service->uuid,
'stack_service_uuid' => $database->uuid,
'backup_uuid' => $this->backup->uuid,
]);
}
return redirect()->route('project.database.backup.executions', [
'project_uuid' => $database->project()->uuid,
'environment_uuid' => $database->environment->uuid,
'database_uuid' => $database->uuid,
'backup_uuid' => $this->backup->uuid,
]);
} catch (\Throwable $e) {
return handleError($e, $this);
}
}
public function instantSave()
{
2023-08-11 14:13:53 +00:00
try {
$this->authorize('manageBackups', $this->backup->database);
2024-11-04 11:40:10 +00:00
$this->syncData(true);
2024-03-21 11:44:32 +00:00
$this->dispatch('success', 'Backup updated successfully.');
} catch (\Throwable $e) {
2023-12-07 18:06:32 +00:00
$this->dispatch('error', $e->getMessage());
2023-08-11 14:13:53 +00:00
}
}
public function toggleEnabled(): void
{
try {
$this->authorize('manageBackups', $this->backup->database);
$this->backupEnabled = ! $this->backupEnabled;
$this->backup->update(['enabled' => $this->backupEnabled]);
$this->dispatch('success', $this->backupEnabled ? 'Backup enabled.' : 'Backup disabled.');
} catch (\Throwable $e) {
$this->dispatch('error', $e->getMessage());
}
}
public function updatedS3StorageId(): void
{
$this->instantSave();
}
public function toggleS3(): void
{
if (! $this->saveS3 && $this->availableS3StorageIds()->isEmpty()) {
$this->dispatch('error', 'Select a usable S3 storage before enabling S3 backups.');
return;
}
$this->saveS3 = ! $this->saveS3;
$this->disableLocalBackup = $this->saveS3 && $this->disableLocalBackup;
$this->instantSave();
}
2024-11-04 11:40:10 +00:00
private function customValidate()
{
2024-06-10 20:43:34 +00:00
if (! is_numeric($this->backup->s3_storage_id)) {
2023-08-11 18:48:52 +00:00
$this->backup->s3_storage_id = null;
}
// S3 backup cannot be enabled without a valid S3 storage owned by the team
$availableS3Ids = $this->availableS3StorageIds();
if ($availableS3Ids->isEmpty()) {
$this->backup->s3_storage_id = $this->s3StorageId = null;
if ($this->backup->save_s3) {
$this->backup->save_s3 = $this->saveS3 = false;
}
} elseif (! $availableS3Ids->contains($this->backup->s3_storage_id)) {
$this->backup->s3_storage_id = $this->s3StorageId = $availableS3Ids->first();
}
// Validate that disable_local_backup can only be true when S3 backup is enabled
if ($this->backup->disable_local_backup && ! $this->backup->save_s3) {
$this->backup->disable_local_backup = $this->disableLocalBackup = false;
}
$isValid = validate_cron_expression($this->backup->frequency);
2024-06-10 20:43:34 +00:00
if (! $isValid) {
throw new Exception('Invalid Cron / Human expression');
}
$this->validate();
2023-08-11 14:13:53 +00:00
}
private function availableS3StorageIds(): Collection
{
$storages = collect($this->availableS3Storages);
$storageIds = $storages->pluck('id')->filter()->all();
if (empty($storageIds)) {
return collect();
}
$teamIds = $storages->pluck('team_id')->reject(fn ($teamId) => $teamId === null)->unique()->values()->all();
if (empty($teamIds)) {
return collect();
}
return S3Storage::query()
->whereKey($storageIds)
->whereIn('team_id', $teamIds)
->where('is_usable', true)
->pluck('id');
}
2023-08-11 14:13:53 +00:00
public function submit()
{
try {
$this->authorize('manageBackups', $this->backup->database);
2024-11-04 11:40:10 +00:00
$this->syncData(true);
$this->dispatch('success', 'Backup updated successfully.');
} catch (\Throwable $e) {
2023-12-07 18:06:32 +00:00
$this->dispatch('error', $e->getMessage());
2023-08-11 14:13:53 +00:00
}
}
public function render()
{
return view('livewire.project.database.backup-edit', [
'checkboxes' => [
['id' => 'delete_associated_backups_locally', 'label' => __('database.delete_backups_locally')],
2025-01-14 08:22:15 +00:00
['id' => 'delete_associated_backups_s3', 'label' => 'All backups will be permanently deleted (associated with this backup job) from the selected S3 Storage.'],
2024-09-02 17:27:21 +00:00
// ['id' => 'delete_associated_backups_sftp', 'label' => 'All backups associated with this backup job from this database will be permanently deleted from the selected SFTP Storage.']
2024-09-23 17:51:31 +00:00
],
]);
}
}