From b8c3f153c49e61a54eac741352f7afbb1e548de7 Mon Sep 17 00:00:00 2001 From: Daniel Supernault Date: Sat, 17 Dec 2022 20:38:11 -0700 Subject: [PATCH] Add MediaS3GarbageCollector command to clear local media after uploaded to S3 disks after 12 hours --- .../Commands/MediaS3GarbageCollector.php | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 app/Console/Commands/MediaS3GarbageCollector.php diff --git a/app/Console/Commands/MediaS3GarbageCollector.php b/app/Console/Commands/MediaS3GarbageCollector.php new file mode 100644 index 00000000..6eed4fbd --- /dev/null +++ b/app/Console/Commands/MediaS3GarbageCollector.php @@ -0,0 +1,98 @@ +error('Cloud storage not enabled. Exiting...'); + return; + } + + $deleteEnabled = config('media.delete_local_after_cloud'); + if(!$deleteEnabled) { + $this->error('Delete local storage after cloud upload is not enabled'); + return; + } + + $limit = $this->option('limit'); + $minId = Media::orderByDesc('id')->where('created_at', '<', now()->subHours(12))->first()->id; + + $gc = Media::whereNotNull(['status_id', 'cdn_url', 'replicated_at']) + ->whereNot('version', '4') + ->where('id', '<', $minId) + ->inRandomOrder() + ->take($limit) + ->get(); + + $totalSize = 0; + $bar = $this->output->createProgressBar($gc->count()); + $bar->start(); + $cloudDisk = Storage::disk(config('filesystems.cloud')); + $localDisk = Storage::disk('local'); + + foreach($gc as $media) { + if( + $cloudDisk->exists($media->media_path) + ) { + if( $localDisk->exists($media->media_path)) { + $localDisk->delete($media->media_path); + $media->version = 4; + $media->save(); + $totalSize = $totalSize + $media->size; + } else { + $media->version = 4; + $media->save(); + } + } else { + Log::channel('media')->info('[GC] Local media not properly persisted to cloud storage', ['media_id' => $media->id]); + } + $bar->advance(); + } + $bar->finish(); + $this->line(' '); + $this->info('Finished!'); + if($totalSize) { + $this->info('Cleared ' . $totalSize . ' bytes of media from local disk!'); + } + return 0; + } +}