lasthourcloud/app/Jobs/DockerCleanupJob.php

71 lines
2.8 KiB
PHP
Raw Normal View History

2023-07-07 15:50:36 +02: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 15:50:36 +02:00
public $timeout = 500;
2023-07-07 15:50:36 +02:00
/**
* Create a new job instance.
*/
public function __construct()
{
//
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
$servers = Server::all();
foreach ($servers as $server) {
2023-08-27 21:36:11 +02:00
if (
!$server->settings->is_reachable && !$server->settings->is_usable
) {
continue;
}
if (isDev()) {
2023-07-07 15:50:36 +02: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 21:35:29 +02:00
$disk_percentage_before = $this->get_disk_usage($server, $docker_root_filesystem);
if ($disk_percentage_before >= $server->settings->cleanup_after_percentage) {
2023-07-07 21:07:42 +02: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 21:35:29 +02: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 15:50:36 +02:00
}
}
} catch (\Exception $e) {
2023-08-24 16:14:09 +02:00
send_internal_notification('DockerCleanupJob failed with: ' . $e->getMessage());
2023-07-26 13:33:48 +02:00
ray($e->getMessage());
2023-08-24 21:09:58 +02:00
throw $e;
2023-07-07 15:50:36 +02:00
}
}
2023-07-26 13:33:48 +02:00
private function get_disk_usage(Server $server, string $docker_root_filesystem)
{
2023-08-25 13:04:21 +02: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);
2023-07-07 21:35:29 +02:00
$mount_point = collect(data_get($disk_usage, 'disks'))->where('mount', $docker_root_filesystem)->first();
2023-08-25 13:04:21 +02:00
ray($mount_point);
2023-07-07 21:35:29 +02:00
return Str::of(data_get($mount_point, 'use%'))->trim()->replace('%', '')->value();
}
2023-07-26 13:33:48 +02:00
}