coolify/app/Jobs/ContainerStatusJob.php

379 lines
18 KiB
PHP
Raw Normal View History

2023-09-14 12:45:50 +02:00
<?php
namespace App\Jobs;
use App\Actions\Database\StartDatabaseProxy;
2023-10-17 19:00:23 +02:00
use App\Actions\Proxy\CheckProxy;
2023-09-14 12:45:50 +02:00
use App\Actions\Proxy\StartProxy;
2024-02-07 14:55:06 +01:00
use App\Actions\Shared\ComplexStatusCheck;
2023-09-14 15:52:04 +02:00
use App\Models\ApplicationPreview;
2023-09-14 12:45:50 +02:00
use App\Models\Server;
2024-03-25 12:35:31 +01:00
use App\Models\ServiceDatabase;
2023-09-14 12:45:50 +02:00
use App\Notifications\Container\ContainerRestarted;
use App\Notifications\Container\ContainerStopped;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
2023-09-19 15:51:13 +02:00
use Illuminate\Support\Arr;
2023-09-14 12:45:50 +02:00
2023-09-14 17:22:21 +02:00
class ContainerStatusJob implements ShouldQueue, ShouldBeEncrypted
2023-09-14 12:45:50 +02:00
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
2023-12-20 12:25:14 +01:00
public $tries = 4;
2023-12-19 15:16:08 +01:00
public function backoff(): int
{
2023-12-20 11:59:53 +01:00
return isDev() ? 1 : 3;
2023-12-19 15:16:08 +01:00
}
public function __construct(public Server $server)
{
}
2023-10-18 15:43:14 +02:00
public function middleware(): array
2023-09-14 12:45:50 +02:00
{
2023-12-20 11:59:06 +01:00
return [(new WithoutOverlapping($this->server->uuid))];
2023-09-14 12:45:50 +02:00
}
2023-10-18 15:43:14 +02:00
public function uniqueId(): int
{
2023-12-19 15:16:08 +01:00
return $this->server->uuid;
}
public function handle()
2023-09-14 12:45:50 +02:00
{
2024-02-25 23:13:27 +01:00
if (!$this->server->isFunctional()) {
return 'Server is not ready.';
};
2024-02-07 14:55:06 +01:00
$applications = $this->server->applications();
$skip_these_applications = collect([]);
2024-02-07 14:55:06 +01:00
foreach ($applications as $application) {
if ($application->additional_servers->count() > 0) {
$skip_these_applications->push($application);
ComplexStatusCheck::run($application);
$applications = $applications->filter(function ($value, $key) use ($application) {
return $value->id !== $application->id;
});
2024-02-07 14:55:06 +01:00
}
}
$applications = $applications->filter(function ($value, $key) use ($skip_these_applications) {
return !$skip_these_applications->pluck('id')->contains($value->id);
});
2023-09-14 12:45:50 +02:00
try {
2023-11-29 10:06:52 +01:00
if ($this->server->isSwarm()) {
2023-11-29 14:59:06 +01:00
$containers = instant_remote_process(["docker service inspect $(docker service ls -q) --format '{{json .}}'"], $this->server, false);
2023-12-18 14:01:25 +01:00
$containerReplicates = instant_remote_process(["docker service ls --format '{{json .}}'"], $this->server, false);
2023-11-29 10:06:52 +01:00
} else {
2023-11-29 15:13:03 +01:00
// Precheck for containers
$containers = instant_remote_process(["docker container ls -q"], $this->server, false);
2023-11-29 15:13:03 +01:00
if (!$containers) {
return;
}
2023-11-29 14:59:06 +01:00
$containers = instant_remote_process(["docker container inspect $(docker container ls -q) --format '{{json .}}'"], $this->server, false);
2023-12-18 14:01:25 +01:00
$containerReplicates = null;
2023-11-29 10:06:52 +01:00
}
2023-11-28 14:26:35 +01:00
if (is_null($containers)) {
return;
}
2024-04-16 15:42:38 +02:00
2023-09-14 12:45:50 +02:00
$containers = format_docker_command_output_to_json($containers);
2023-12-18 14:01:25 +01:00
if ($containerReplicates) {
$containerReplicates = format_docker_command_output_to_json($containerReplicates);
foreach ($containerReplicates as $containerReplica) {
2023-11-29 14:59:06 +01:00
$name = data_get($containerReplica, 'Name');
$containers = $containers->map(function ($container) use ($name, $containerReplica) {
if (data_get($container, 'Spec.Name') === $name) {
$replicas = data_get($containerReplica, 'Replicas');
$running = str($replicas)->explode('/')[0];
$total = str($replicas)->explode('/')[1];
if ($running === $total) {
data_set($container, 'State.Status', 'running');
data_set($container, 'State.Health.Status', 'healthy');
} else {
data_set($container, 'State.Status', 'starting');
data_set($container, 'State.Health.Status', 'unhealthy');
}
}
return $container;
});
}
}
2023-09-14 12:45:50 +02:00
$databases = $this->server->databases();
2023-09-26 15:07:33 +02:00
$services = $this->server->services()->get();
2023-09-14 15:52:04 +02:00
$previews = $this->server->previews();
$foundApplications = [];
$foundApplicationPreviews = [];
$foundDatabases = [];
2023-09-21 17:48:31 +02:00
$foundServices = [];
2023-09-14 15:52:04 +02:00
foreach ($containers as $container) {
2023-11-29 14:59:06 +01:00
if ($this->server->isSwarm()) {
$labels = data_get($container, 'Spec.Labels');
$uuid = data_get($labels, 'coolify.name');
} else {
$labels = data_get($container, 'Config.Labels');
}
2023-09-14 15:52:04 +02:00
$containerStatus = data_get($container, 'State.Status');
2023-09-25 09:17:42 +02:00
$containerHealth = data_get($container, 'State.Health.Status', 'unhealthy');
2023-09-22 15:29:19 +02:00
$containerStatus = "$containerStatus ($containerHealth)";
2023-09-14 15:52:04 +02:00
$labels = Arr::undot(format_docker_labels_to_json($labels));
$applicationId = data_get($labels, 'coolify.applicationId');
if ($applicationId) {
$pullRequestId = data_get($labels, 'coolify.pullRequestId');
if ($pullRequestId) {
if (str($applicationId)->contains('-')) {
$applicationId = str($applicationId)->before('-');
}
$preview = ApplicationPreview::where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();
2023-09-14 15:52:04 +02:00
if ($preview) {
$foundApplicationPreviews[] = $preview->id;
$statusFromDb = $preview->status;
if ($statusFromDb !== $containerStatus) {
$preview->update(['status' => $containerStatus]);
}
} else {
//Notify user that this container should not be there.
}
} else {
$application = $applications->where('id', $applicationId)->first();
2023-09-14 15:52:04 +02:00
if ($application) {
$foundApplications[] = $application->id;
$statusFromDb = $application->status;
if ($statusFromDb !== $containerStatus) {
$application->update(['status' => $containerStatus]);
}
} else {
//Notify user that this container should not be there.
}
}
} else {
$uuid = data_get($labels, 'com.docker.compose.service');
2024-03-25 12:35:31 +01:00
$type = data_get($labels, 'coolify.type');
2023-09-14 15:52:04 +02:00
if ($uuid) {
2024-03-25 12:35:31 +01:00
if ($type === 'service') {
$database_id = data_get($labels, 'coolify.service.subId');
if ($database_id) {
$service_db = ServiceDatabase::where('id', $database_id)->first();
if ($service_db) {
$uuid = $service_db->service->uuid;
$isPublic = data_get($service_db, 'is_public');
if ($isPublic) {
$foundTcpProxy = $containers->filter(function ($value, $key) use ($uuid) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
} else {
return data_get($value, 'Name') === "/$uuid-proxy";
}
})->first();
if (!$foundTcpProxy) {
StartDatabaseProxy::run($service_db);
// $this->server->team?->notify(new ContainerRestarted("TCP Proxy for {$service_db->service->name}", $this->server));
2024-03-25 12:35:31 +01:00
}
}
}
}
2023-09-14 15:52:04 +02:00
} else {
2024-03-25 12:35:31 +01:00
$database = $databases->where('uuid', $uuid)->first();
if ($database) {
$isPublic = data_get($database, 'is_public');
$foundDatabases[] = $database->id;
$statusFromDb = $database->status;
if ($statusFromDb !== $containerStatus) {
$database->update(['status' => $containerStatus]);
}
if ($isPublic) {
$foundTcpProxy = $containers->filter(function ($value, $key) use ($uuid) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
} else {
return data_get($value, 'Name') === "/$uuid-proxy";
}
})->first();
if (!$foundTcpProxy) {
StartDatabaseProxy::run($database);
$this->server->team?->notify(new ContainerRestarted("TCP Proxy for {$database->name}", $this->server));
}
}
} else {
// Notify user that this container should not be there.
}
2023-09-14 15:52:04 +02:00
}
}
if (data_get($container, 'Name') === '/coolify-db') {
2024-01-07 16:23:41 +01:00
$foundDatabases[] = 0;
}
2023-09-14 15:52:04 +02:00
}
2023-09-21 17:48:31 +02:00
$serviceLabelId = data_get($labels, 'coolify.serviceId');
if ($serviceLabelId) {
2023-09-25 15:48:43 +02:00
$subType = data_get($labels, 'coolify.service.subType');
$subId = data_get($labels, 'coolify.service.subId');
$service = $services->where('id', $serviceLabelId)->first();
2023-09-26 14:45:52 +02:00
if (!$service) {
continue;
}
2023-09-25 15:48:43 +02:00
if ($subType === 'application') {
$service = $service->applications()->where('id', $subId)->first();
} else {
$service = $service->databases()->where('id', $subId)->first();
}
2023-09-21 17:48:31 +02:00
if ($service) {
2023-09-25 15:48:43 +02:00
$foundServices[] = "$service->id-$service->name";
$statusFromDb = $service->status;
if ($statusFromDb !== $containerStatus) {
// ray('Updating status: ' . $containerStatus);
$service->update(['status' => $containerStatus]);
2023-09-21 17:48:31 +02:00
}
}
}
2023-09-14 15:52:04 +02:00
}
2023-09-21 17:48:31 +02:00
$exitedServices = collect([]);
2023-09-26 15:07:33 +02:00
foreach ($services as $service) {
2023-09-21 17:48:31 +02:00
$apps = $service->applications()->get();
$dbs = $service->databases()->get();
foreach ($apps as $app) {
2023-09-22 20:39:56 +02:00
if (in_array("$app->id-$app->name", $foundServices)) {
2023-09-21 17:48:31 +02:00
continue;
} else {
2023-09-22 11:23:49 +02:00
$exitedServices->push($app);
2023-09-21 17:48:31 +02:00
}
}
foreach ($dbs as $db) {
2023-09-22 20:39:56 +02:00
if (in_array("$db->id-$db->name", $foundServices)) {
2023-09-21 17:48:31 +02:00
continue;
} else {
2023-09-22 11:23:49 +02:00
$exitedServices->push($db);
2023-09-21 17:48:31 +02:00
}
}
2023-09-22 11:23:49 +02:00
}
2023-09-21 17:48:31 +02:00
$exitedServices = $exitedServices->unique('id');
2023-09-22 11:23:49 +02:00
foreach ($exitedServices as $exitedService) {
2024-02-07 14:55:06 +01:00
if (str($exitedService->status)->startsWith('exited')) {
2023-09-22 11:23:49 +02:00
continue;
}
$name = data_get($exitedService, 'name');
$fqdn = data_get($exitedService, 'fqdn');
2024-01-07 16:23:41 +01:00
$containerName = $name ? "$name, available at $fqdn" : $fqdn;
$projectUuid = data_get($service, 'environment.project.uuid');
$serviceUuid = data_get($service, 'uuid');
$environmentName = data_get($service, 'environment.name');
2023-09-22 11:23:49 +02:00
if ($projectUuid && $serviceUuid && $environmentName) {
$url = base_url() . '/project/' . $projectUuid . "/" . $environmentName . "/service/" . $serviceUuid;
} else {
$url = null;
}
$this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
2023-09-22 11:23:49 +02:00
$exitedService->update(['status' => 'exited']);
}
2023-09-21 17:48:31 +02:00
2023-09-14 15:52:04 +02:00
$notRunningApplications = $applications->pluck('id')->diff($foundApplications);
2023-09-18 12:08:19 +02:00
foreach ($notRunningApplications as $applicationId) {
2023-09-14 15:52:04 +02:00
$application = $applications->where('id', $applicationId)->first();
2024-02-07 14:55:06 +01:00
if (str($application->status)->startsWith('exited')) {
2023-09-14 15:52:04 +02:00
continue;
}
$application->update(['status' => 'exited']);
$name = data_get($application, 'name');
$fqdn = data_get($application, 'fqdn');
$containerName = $name ? "$name ($fqdn)" : $fqdn;
$projectUuid = data_get($application, 'environment.project.uuid');
$applicationUuid = data_get($application, 'uuid');
$environment = data_get($application, 'environment.name');
2023-09-14 15:52:04 +02:00
if ($projectUuid && $applicationUuid && $environment) {
$url = base_url() . '/project/' . $projectUuid . "/" . $environment . "/application/" . $applicationUuid;
} else {
$url = null;
}
2023-09-14 15:52:04 +02:00
$this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
2023-09-14 15:52:04 +02:00
}
$notRunningApplicationPreviews = $previews->pluck('id')->diff($foundApplicationPreviews);
foreach ($notRunningApplicationPreviews as $previewId) {
$preview = $previews->where('id', $previewId)->first();
2024-02-07 14:55:06 +01:00
if (str($preview->status)->startsWith('exited')) {
2023-09-14 15:52:04 +02:00
continue;
}
$preview->update(['status' => 'exited']);
$name = data_get($preview, 'name');
$fqdn = data_get($preview, 'fqdn');
$containerName = $name ? "$name ($fqdn)" : $fqdn;
$projectUuid = data_get($preview, 'application.environment.project.uuid');
$environmentName = data_get($preview, 'application.environment.name');
$applicationUuid = data_get($preview, 'application.uuid');
if ($projectUuid && $applicationUuid && $environmentName) {
$url = base_url() . '/project/' . $projectUuid . "/" . $environmentName . "/application/" . $applicationUuid;
} else {
$url = null;
}
2023-09-14 15:52:04 +02:00
$this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
2023-09-14 15:52:04 +02:00
}
$notRunningDatabases = $databases->pluck('id')->diff($foundDatabases);
2023-09-18 12:08:19 +02:00
foreach ($notRunningDatabases as $database) {
2023-09-14 15:52:04 +02:00
$database = $databases->where('id', $database)->first();
2024-02-07 14:55:06 +01:00
if (str($database->status)->startsWith('exited')) {
2023-09-14 15:52:04 +02:00
continue;
}
$database->update(['status' => 'exited']);
2023-09-18 12:08:19 +02:00
$name = data_get($database, 'name');
2023-09-14 15:52:04 +02:00
$fqdn = data_get($database, 'fqdn');
$containerName = $name;
$projectUuid = data_get($database, 'environment.project.uuid');
$environmentName = data_get($database, 'environment.name');
$databaseUuid = data_get($database, 'uuid');
2023-09-14 15:52:04 +02:00
if ($projectUuid && $databaseUuid && $environmentName) {
$url = base_url() . '/project/' . $projectUuid . "/" . $environmentName . "/database/" . $databaseUuid;
} else {
$url = null;
}
$this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
2023-09-14 15:52:04 +02:00
}
2023-11-17 21:16:25 +01:00
// Check if proxy is running
$this->server->proxyType();
$foundProxyContainer = $containers->filter(function ($value, $key) {
2023-11-29 14:59:06 +01:00
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === 'coolify-proxy_traefik';
} else {
return data_get($value, 'Name') === '/coolify-proxy';
}
2023-11-17 21:16:25 +01:00
})->first();
if (!$foundProxyContainer) {
try {
$shouldStart = CheckProxy::run($this->server);
if ($shouldStart) {
StartProxy::run($this->server, false);
$this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server));
2023-11-17 21:16:25 +01:00
}
} catch (\Throwable $e) {
ray($e);
}
} else {
$this->server->proxy->status = data_get($foundProxyContainer, 'State.Status');
$this->server->save();
$connectProxyToDockerNetworks = connectProxyToNetworks($this->server);
instant_remote_process($connectProxyToDockerNetworks, $this->server, false);
}
2023-09-14 12:45:50 +02:00
} catch (\Throwable $e) {
2023-11-17 14:43:57 +01:00
send_internal_notification("ContainerStatusJob failed on ({$this->server->id}) with: " . $e->getMessage());
2023-09-14 12:45:50 +02:00
ray($e->getMessage());
return handleError($e);
2023-09-14 12:45:50 +02:00
}
}
}