coolify/app/Actions/Service/DeleteService.php

82 lines
2.8 KiB
PHP
Raw Normal View History

2023-12-08 17:32:08 +00:00
<?php
namespace App\Actions\Service;
use App\Models\Service;
use App\Actions\Server\CleanupDocker;
2024-06-10 20:43:34 +00:00
use Lorisleiva\Actions\Concerns\AsAction;
2023-12-08 17:32:08 +00:00
class DeleteService
{
use AsAction;
2024-06-10 20:43:34 +00:00
2024-08-08 22:30:11 +00:00
public function handle(Service $service, bool $deleteConfigurations, bool $deleteVolumes, bool $deleteImages, bool $deleteConnectedNetworks)
2023-12-08 17:32:08 +00:00
{
try {
$server = data_get($service, 'server');
2024-08-09 00:11:42 +00:00
if ($deleteVolumes && $server->isFunctional()) {
$storagesToDelete = collect([]);
$service->environment_variables()->delete();
$commands = [];
foreach ($service->applications()->get() as $application) {
$storages = $application->persistentStorages()->get();
foreach ($storages as $storage) {
$storagesToDelete->push($storage);
}
}
foreach ($service->databases()->get() as $database) {
$storages = $database->persistentStorages()->get();
foreach ($storages as $storage) {
$storagesToDelete->push($storage);
}
}
2024-08-09 00:11:42 +00:00
foreach ($storagesToDelete as $storage) {
$commands[] = "docker volume rm -f $storage->name";
}
2024-08-08 22:30:11 +00:00
2024-08-09 00:15:40 +00:00
// Execute volume deletion first, this must be done first otherwise volumes will not be deleted.
2024-08-09 00:11:42 +00:00
if (!empty($commands)) {
foreach ($commands as $command) {
$result = instant_remote_process([$command], $server, false);
if ($result !== 0) {
ray("Failed to execute: $command");
}
2024-08-08 22:30:11 +00:00
}
}
2024-08-09 00:11:42 +00:00
}
2024-08-09 00:11:42 +00:00
if ($deleteConnectedNetworks) {
2024-08-09 00:58:59 +00:00
$service->delete_connected_networks($service->uuid);
2024-08-09 00:11:42 +00:00
}
2024-08-09 00:11:42 +00:00
$commands[] = "docker rm -f $service->uuid";
2023-12-08 17:32:08 +00:00
2024-08-09 00:15:40 +00:00
// Executing remaining commands
2024-08-09 00:11:42 +00:00
instant_remote_process($commands, $server, false);
2024-08-09 00:58:59 +00:00
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
} finally {
2024-08-08 22:30:11 +00:00
if ($deleteConfigurations) {
$service->delete_configurations();
}
foreach ($service->applications()->get() as $application) {
$application->forceDelete();
2023-12-08 17:32:08 +00:00
}
foreach ($service->databases()->get() as $database) {
$database->forceDelete();
2024-01-29 15:03:45 +00:00
}
2024-02-14 14:14:06 +00:00
foreach ($service->scheduled_tasks as $task) {
$task->delete();
}
2024-02-02 10:50:28 +00:00
$service->tags()->detach();
$service->forceDelete();
2024-08-08 22:30:11 +00:00
if ($deleteImages) {
CleanupDocker::run($server, true);
}
2024-01-29 15:03:45 +00:00
}
2023-12-08 17:32:08 +00:00
}
2024-08-09 00:15:40 +00:00
}