Skip to content

Commit

Permalink
automatically backup database
Browse files Browse the repository at this point in the history
  • Loading branch information
jrmajor committed May 4, 2024
1 parent 043f99d commit e340c5e
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ S3_SECRET_ACCESS_KEY=
S3_DEFAULT_REGION=
S3_ENDPOINT=
S3_BUCKET_MEDIA=
S3_BUCKET_BACKUP=

FATHOM_SITE_ID=

Expand Down
48 changes: 48 additions & 0 deletions app/Console/Commands/MakeBackup.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Psl\Filesystem;

class MakeBackup extends Command
{
protected $signature = 'backup:run';

protected $description = 'Make a new backup.';

public function handle(): void
{
$databasePath = DB::getConfig()['database'];
$databaseSize = $this->humanReadableSizeOf($databasePath);
$backupName = date('Y-m-d-H-i-s') . '.sqlite';

$this->line("Backing up database to {$backupName} ({$databaseSize})...");

Storage::disk('backup')->putFileAs('database', $databasePath, $backupName);

$this->info('Backup successfull.');
}

/**
* @param non-empty-string $path
*/
private function humanReadableSizeOf(string $path): string
{
$sizeInBytes = Filesystem\file_size($path);

$units = ['B', 'KB', 'MB', 'GB', 'TB'];

if ($sizeInBytes === 0) {
return '0 ' . $units[1];
}

for ($i = 0; $sizeInBytes > 1024; $i++) {
$sizeInBytes /= 1024;
}

return round($sizeInBytes, 2) . ' ' . $units[$i];
}
}
11 changes: 11 additions & 0 deletions config/filesystems.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@
'throw' => false,
],

'backup' => [
'driver' => 's3',
'key' => env('S3_ACCESS_KEY_ID'),
'secret' => env('S3_SECRET_ACCESS_KEY'),
'region' => env('S3_DEFAULT_REGION'),
'bucket' => env('S3_BUCKET_BACKUP'),
'endpoint' => env('S3_ENDPOINT'),
'use_path_style_endpoint' => false,
'throw' => false,
],

],

];
3 changes: 3 additions & 0 deletions routes/console.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
use App\Console\Commands;
use Illuminate\Console\Scheduling\Schedule as RealSchedule;
use Illuminate\Support\Facades\Schedule;
use Laravel\Telescope\Console\PruneCommand as PruneTelescopeEntries;

Schedule::command(Commands\RefreshArtistsCache::class)
->days([RealSchedule::TUESDAY, RealSchedule::FRIDAY])
->at('03:00')
->graceTimeInMinutes(30);

Schedule::command(Commands\MakeBackup::class)->dailyAt('02:00');

0 comments on commit e340c5e

Please sign in to comment.