coolify/app/Actions/Service/StopService.php

58 lines
2.1 KiB
PHP
Raw Normal View History

2023-09-21 19:30:13 +00:00
<?php
namespace App\Actions\Service;
use App\Models\Service;
2024-08-09 16:59:41 +00:00
use App\Actions\Server\CleanupDocker;
2024-06-10 20:43:34 +00:00
use Lorisleiva\Actions\Concerns\AsAction;
2023-09-21 19:30:13 +00:00
class StopService
{
use AsAction;
2024-06-10 20:43:34 +00:00
public function handle(Service $service, bool $isDeleteOperation = false)
2023-09-21 19:30:13 +00:00
{
try {
$server = $service->destination->server;
if (!$server->isFunctional()) {
return 'Server is not functional';
}
ray('Stopping service: ' . $service->name);
$applications = $service->applications()->get();
foreach ($applications as $application) {
2024-08-09 16:59:41 +00:00
$this->stopContainer("{$application->name}-{$service->uuid}", $server, 600);
$application->update(['status' => 'exited']);
}
$dbs = $service->databases()->get();
foreach ($dbs as $db) {
2024-08-09 16:59:41 +00:00
$this->stopContainer("{$db->name}-{$service->uuid}", $server, 600);
$db->update(['status' => 'exited']);
}
if (!$isDeleteOperation) {
2024-08-09 16:59:41 +00:00
// Only run if not a deletion operation as for deletion we can specify if we want to delete networks or not
$service->delete_connected_networks($service->uuid);
2024-08-09 16:59:41 +00:00
CleanupDocker::run($server, true);
}
} catch (\Exception $e) {
ray($e->getMessage());
return $e->getMessage();
2024-01-31 08:58:41 +00:00
}
2023-09-21 19:30:13 +00:00
}
2024-08-09 16:59:41 +00:00
private function stopContainer(string $containerName, $server, int $timeout = 600)
{
try {
instant_remote_process(command: ["docker stop --time=$timeout $containerName"], server: $server, throwError: false);
$isRunning = instant_remote_process(command: ["docker inspect -f '{{.State.Running}}' $containerName"], server: $server, throwError: false);
if (trim($isRunning) === 'true') {
instant_remote_process(command: ["docker kill $containerName"], server: $server, throwError: false);
}
} catch (\Exception $error) {
}
instant_remote_process(command: ["docker rm -f $containerName"], server: $server, throwError: false);
}
2023-09-21 19:30:13 +00:00
}