lasthourcloud/app/Jobs/DockerCleanupJob.php

63 lines
2.5 KiB
PHP
Raw Normal View History

2023-07-07 13:50:36 +00:00
<?php
namespace App\Jobs;
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;
class DockerCleanupJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
2023-07-07 13:50:36 +00:00
public $timeout = 500;
2023-07-07 13:50:36 +00:00
/**
* Create a new job instance.
*/
public function __construct()
{
//
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
$servers = Server::all();
foreach ($servers as $server) {
if (is_dev()) {
2023-07-07 13:50:36 +00:00
$docker_root_filesystem = "/";
} else {
$docker_root_filesystem = instant_remote_process(['stat --printf=%m $(docker info --format "{{json .DockerRootDir}}" |sed \'s/"//g\')'], $server);
}
2023-07-07 19:35:29 +00:00
$disk_percentage_before = $this->get_disk_usage($server, $docker_root_filesystem);
if ($disk_percentage_before >= $server->settings->cleanup_after_percentage) {
2023-07-07 19:07:42 +00:00
instant_remote_process(['docker image prune -af'], $server);
instant_remote_process(['docker container prune -f --filter "label=coolify.managed=true"'], $server);
instant_remote_process(['docker builder prune -af'], $server);
2023-07-07 19:35:29 +00:00
$disk_percentage_after = $this->get_disk_usage($server, $docker_root_filesystem);
if ($disk_percentage_after < $disk_percentage_before) {
ray('Saved ' . ($disk_percentage_before - $disk_percentage_after) . '% disk space on ' . $server->name);
}
2023-07-07 13:50:36 +00:00
}
}
} catch (\Exception $e) {
2023-07-26 11:33:48 +00:00
ray($e->getMessage());
2023-07-07 13:50:36 +00:00
}
}
2023-07-26 11:33:48 +00:00
private function get_disk_usage(Server $server, string $docker_root_filesystem)
{
2023-07-07 19:35:29 +00:00
$disk_usage = json_decode(instant_remote_process(['df -hP | awk \'BEGIN {printf"{\"disks\":["}{if($1=="Filesystem")next;if(a)printf",";printf"{\"mount\":\""$6"\",\"size\":\""$2"\",\"used\":\""$3"\",\"avail\":\""$4"\",\"use%\":\""$5"\"}";a++;}END{print"]}";}\''], $server), true);
$mount_point = collect(data_get($disk_usage, 'disks'))->where('mount', $docker_root_filesystem)->first();
return Str::of(data_get($mount_point, 'use%'))->trim()->replace('%', '')->value();
}
2023-07-26 11:33:48 +00:00
}