Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

fix: prevent metric charts from freezing when navigating with wire:navigate

Andras Bacsaia8aa4524751d
diff --git a/app/Models/Application.php b/app/Models/Application.php
index 40e41c2a70..2eab8df209 100644
--- a/app/Models/Application.php
+++ b/app/Models/Application.php
@@ -6,6 +6,7 @@ use App\Enums\ApplicationDeploymentStatus;
use App\Services\ConfigurationGenerator;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasConfiguration;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -111,7 +112,7 @@ use Visus\Cuid2\Cuid2;
class Application extends BaseModel
{
- use ClearsGlobalSearchCache, HasConfiguration, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasConfiguration, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
private static $parserVersion = '5';
@@ -1977,54 +1978,6 @@ class Application extends BaseModel
return [];
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- if ($server->isMetricsEnabled()) {
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- if ($server->isMetricsEnabled()) {
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
- }
-
public function getLimits(): array
{
return [
diff --git a/app/Models/Server.php b/app/Models/Server.php
index fd1ce3e691..696b3529be 100644
--- a/app/Models/Server.php
+++ b/app/Models/Server.php
@@ -16,6 +16,7 @@ use App\Notifications\Server\Reachable;
use App\Notifications\Server\Unreachable;
use App\Services\ConfigurationRepository;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
@@ -103,7 +104,7 @@ use Visus\Cuid2\Cuid2;
class Server extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, SchemalessAttributesTrait, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, SchemalessAttributesTrait, SoftDeletes;
public static $batch_counter = 0;
@@ -667,141 +668,6 @@ $schema://$host {
CheckAndStartSentinelJob::dispatch($this);
}
- public function getCpuMetrics(int $mins = 5)
- {
- if ($this->isMetricsEnabled()) {
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $cpu = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$this->settings->sentinel_token}\" http://localhost:8888/api/cpu/history?from=$from'"], $this, false);
- if (str($cpu)->contains('error')) {
- $error = json_decode($cpu, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $cpu = json_decode($cpu, true);
-
- $metrics = collect($cpu)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- })->toArray();
-
- // Downsample for intervals > 60 minutes to prevent browser freeze
- if ($mins > 60 && count($metrics) > 1000) {
- $metrics = $this->downsampleLTTB($metrics, 1000);
- }
-
- return collect($metrics);
- }
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- if ($this->isMetricsEnabled()) {
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $memory = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$this->settings->sentinel_token}\" http://localhost:8888/api/memory/history?from=$from'"], $this, false);
- if (str($memory)->contains('error')) {
- $error = json_decode($memory, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $memory = json_decode($memory, true);
- $metrics = collect($memory)->map(function ($metric) {
- $usedPercent = $metric['usedPercent'] ?? 0.0;
-
- return [(int) $metric['time'], (float) $usedPercent];
- })->toArray();
-
- // Downsample for intervals > 60 minutes to prevent browser freeze
- if ($mins > 60 && count($metrics) > 1000) {
- $metrics = $this->downsampleLTTB($metrics, 1000);
- }
-
- return collect($metrics);
- }
- }
-
- /**
- * Downsample metrics using the Largest-Triangle-Three-Buckets (LTTB) algorithm.
- * This preserves the visual shape of the data better than simple averaging.
- *
- * @param array $data Array of [timestamp, value] pairs
- * @param int $threshold Target number of points
- * @return array Downsampled data
- */
- private function downsampleLTTB(array $data, int $threshold): array
- {
- $dataLength = count($data);
-
- // Return unchanged if threshold >= data length, or if threshold <= 2
- // (threshold <= 2 would cause division by zero in bucket calculation)
- if ($threshold >= $dataLength || $threshold <= 2) {
- return $data;
- }
-
- $sampled = [];
- $sampled[] = $data[0]; // Always keep first point
-
- $bucketSize = ($dataLength - 2) / ($threshold - 2);
-
- $a = 0; // Index of previous selected point
-
- for ($i = 0; $i < $threshold - 2; $i++) {
- // Calculate bucket range
- $bucketStart = (int) floor(($i + 1) * $bucketSize) + 1;
- $bucketEnd = (int) floor(($i + 2) * $bucketSize) + 1;
- $bucketEnd = min($bucketEnd, $dataLength - 1);
-
- // Calculate average point for next bucket (used as reference)
- $nextBucketStart = (int) floor(($i + 2) * $bucketSize) + 1;
- $nextBucketEnd = (int) floor(($i + 3) * $bucketSize) + 1;
- $nextBucketEnd = min($nextBucketEnd, $dataLength - 1);
-
- $avgX = 0;
- $avgY = 0;
- $nextBucketCount = $nextBucketEnd - $nextBucketStart + 1;
-
- if ($nextBucketCount > 0) {
- for ($j = $nextBucketStart; $j <= $nextBucketEnd; $j++) {
- $avgX += $data[$j][0];
- $avgY += $data[$j][1];
- }
- $avgX /= $nextBucketCount;
- $avgY /= $nextBucketCount;
- }
-
- // Find point in current bucket with largest triangle area
- $maxArea = -1;
- $maxAreaIndex = $bucketStart;
-
- $pointAX = $data[$a][0];
- $pointAY = $data[$a][1];
-
- for ($j = $bucketStart; $j <= $bucketEnd; $j++) {
- // Triangle area calculation
- $area = abs(
- ($pointAX - $avgX) * ($data[$j][1] - $pointAY) -
- ($pointAX - $data[$j][0]) * ($avgY - $pointAY)
- ) * 0.5;
-
- if ($area > $maxArea) {
- $maxArea = $area;
- $maxAreaIndex = $j;
- }
- }
-
- $sampled[] = $data[$maxAreaIndex];
- $a = $maxAreaIndex;
- }
-
- $sampled[] = $data[$dataLength - 1]; // Always keep last point
-
- return $sampled;
- }
-
public function getDiskUsage(): ?string
{
return instant_remote_process(['df / --output=pcent | tr -cd 0-9'], $this, false);
diff --git a/app/Models/StandaloneClickhouse.php b/app/Models/StandaloneClickhouse.php
index a76d55abbf..ee8a271621 100644
--- a/app/Models/StandaloneClickhouse.php
+++ b/app/Models/StandaloneClickhouse.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -10,7 +11,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneClickhouse extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -320,50 +321,6 @@ class StandaloneClickhouse extends BaseModel
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
-
public function isBackupSolutionAvailable()
{
return false;
diff --git a/app/Models/StandaloneDragonfly.php b/app/Models/StandaloneDragonfly.php
index f5337b1d51..051a95a806 100644
--- a/app/Models/StandaloneDragonfly.php
+++ b/app/Models/StandaloneDragonfly.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -10,7 +11,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneDragonfly extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -316,50 +317,6 @@ class StandaloneDragonfly extends BaseModel
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
-
public function isBackupSolutionAvailable()
{
return false;
diff --git a/app/Models/StandaloneKeydb.php b/app/Models/StandaloneKeydb.php
index ab24cae2c9..6cd51edce1 100644
--- a/app/Models/StandaloneKeydb.php
+++ b/app/Models/StandaloneKeydb.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -10,7 +11,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneKeydb extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -316,50 +317,6 @@ class StandaloneKeydb extends BaseModel
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
-
public function isBackupSolutionAvailable()
{
return false;
diff --git a/app/Models/StandaloneMariadb.php b/app/Models/StandaloneMariadb.php
index e48cfc1e60..f312473be5 100644
--- a/app/Models/StandaloneMariadb.php
+++ b/app/Models/StandaloneMariadb.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -11,7 +12,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneMariadb extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -319,50 +320,6 @@ class StandaloneMariadb extends BaseModel
return $this->morphMany(SslCertificate::class, 'resource');
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
-
public function isBackupSolutionAvailable()
{
return true;
diff --git a/app/Models/StandaloneMongodb.php b/app/Models/StandaloneMongodb.php
index 9e271b19a3..d2d8fef129 100644
--- a/app/Models/StandaloneMongodb.php
+++ b/app/Models/StandaloneMongodb.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -10,7 +11,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneMongodb extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -341,50 +342,6 @@ class StandaloneMongodb extends BaseModel
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
-
public function isBackupSolutionAvailable()
{
return true;
diff --git a/app/Models/StandaloneMysql.php b/app/Models/StandaloneMysql.php
index 377765697e..c27b2a6791 100644
--- a/app/Models/StandaloneMysql.php
+++ b/app/Models/StandaloneMysql.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -10,7 +11,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneMysql extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -320,50 +321,6 @@ class StandaloneMysql extends BaseModel
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
-
public function isBackupSolutionAvailable()
{
return true;
diff --git a/app/Models/StandalonePostgresql.php b/app/Models/StandalonePostgresql.php
index d9993426a7..73b00742ac 100644
--- a/app/Models/StandalonePostgresql.php
+++ b/app/Models/StandalonePostgresql.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -10,7 +11,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandalonePostgresql extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -337,51 +338,4 @@ class StandalonePostgresql extends BaseModel
{
return true;
}
-
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [
- (int) $metric['time'],
- (float) ($metric['percent'] ?? 0.0),
- ];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
}
diff --git a/app/Models/StandaloneRedis.php b/app/Models/StandaloneRedis.php
index 684bcaeb7b..46e8da4343 100644
--- a/app/Models/StandaloneRedis.php
+++ b/app/Models/StandaloneRedis.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
+use App\Traits\HasMetrics;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -10,7 +11,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneRedis extends BaseModel
{
- use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
+ use ClearsGlobalSearchCache, HasFactory, HasMetrics, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
@@ -332,50 +333,6 @@ class StandaloneRedis extends BaseModel
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
- public function getCpuMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['percent']];
- });
-
- return $parsedCollection->toArray();
- }
-
- public function getMemoryMetrics(int $mins = 5)
- {
- $server = $this->destination->server;
- $container_name = $this->uuid;
- $from = now()->subMinutes($mins)->toIso8601ZuluString();
- $metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
- if (str($metrics)->contains('error')) {
- $error = json_decode($metrics, true);
- $error = data_get($error, 'error', 'Something is not okay, are you okay?');
- if ($error === 'Unauthorized') {
- $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
- }
- throw new \Exception($error);
- }
- $metrics = json_decode($metrics, true);
- $parsedCollection = collect($metrics)->map(function ($metric) {
- return [(int) $metric['time'], (float) $metric['used']];
- });
-
- return $parsedCollection->toArray();
- }
-
public function isBackupSolutionAvailable()
{
return false;
diff --git a/app/Traits/HasMetrics.php b/app/Traits/HasMetrics.php
new file mode 100644
index 0000000000..667d584414
--- /dev/null
+++ b/app/Traits/HasMetrics.php
@@ -0,0 +1,74 @@
+<?php
+
+namespace App\Traits;
+
+trait HasMetrics
+{
+ public function getCpuMetrics(int $mins = 5): ?array
+ {
+ return $this->getMetrics('cpu', $mins, 'percent');
+ }
+
+ public function getMemoryMetrics(int $mins = 5): ?array
+ {
+ $field = $this->isServerMetrics() ? 'usedPercent' : 'used';
+
+ return $this->getMetrics('memory', $mins, $field);
+ }
+
+ private function getMetrics(string $type, int $mins, string $valueField): ?array
+ {
+ $server = $this->getMetricsServer();
+ if (! $server->isMetricsEnabled()) {
+ return null;
+ }
+
+ $from = now()->subMinutes($mins)->toIso8601ZuluString();
+ $endpoint = $this->getMetricsEndpoint($type, $from);
+
+ $response = instant_remote_process(
+ ["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" {$endpoint}'"],
+ $server,
+ false
+ );
+
+ if (str($response)->contains('error')) {
+ $error = json_decode($response, true);
+ $error = data_get($error, 'error', 'Something is not okay, are you okay?');
+ if ($error === 'Unauthorized') {
+ $error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
+ }
+ throw new \Exception($error);
+ }
+
+ $metrics = collect(json_decode($response, true))->map(function ($metric) use ($valueField) {
+ return [(int) $metric['time'], (float) ($metric[$valueField] ?? 0.0)];
+ })->toArray();
+
+ if ($mins > 60 && count($metrics) > 1000) {
+ $metrics = downsampleLTTB($metrics, 1000);
+ }
+
+ return $metrics;
+ }
+
+ private function isServerMetrics(): bool
+ {
+ return $this instanceof \App\Models\Server;
+ }
+
+ private function getMetricsServer(): \App\Models\Server
+ {
+ return $this->isServerMetrics() ? $this : $this->destination->server;
+ }
+
+ private function getMetricsEndpoint(string $type, string $from): string
+ {
+ $base = 'http://localhost:8888/api';
+ if ($this->isServerMetrics()) {
+ return "{$base}/{$type}/history?from={$from}";
+ }
+
+ return "{$base}/container/{$this->uuid}/{$type}/history?from={$from}";
+ }
+}
diff --git a/bootstrap/helpers/shared.php b/bootstrap/helpers/shared.php
index 9fc1e6f1ce..e26b7b6c7e 100644
--- a/bootstrap/helpers/shared.php
+++ b/bootstrap/helpers/shared.php
@@ -3416,3 +3416,81 @@ function verifyPasswordConfirmation(mixed $password, ?Livewire\Component $compon
return true;
}
+
+/**
+ * Downsample metrics using the Largest-Triangle-Three-Buckets (LTTB) algorithm.
+ * This preserves the visual shape of the data better than simple averaging.
+ *
+ * @param array $data Array of [timestamp, value] pairs
+ * @param int $threshold Target number of points
+ * @return array Downsampled data
+ */
+function downsampleLTTB(array $data, int $threshold): array
+{
+ $dataLength = count($data);
+
+ // Return unchanged if threshold >= data length, or if threshold <= 2
+ // (threshold <= 2 would cause division by zero in bucket calculation)
+ if ($threshold >= $dataLength || $threshold <= 2) {
+ return $data;
+ }
+
+ $sampled = [];
+ $sampled[] = $data[0]; // Always keep first point
+
+ $bucketSize = ($dataLength - 2) / ($threshold - 2);
+
+ $a = 0; // Index of previous selected point
+
+ for ($i = 0; $i < $threshold - 2; $i++) {
+ // Calculate bucket range
+ $bucketStart = (int) floor(($i + 1) * $bucketSize) + 1;
+ $bucketEnd = (int) floor(($i + 2) * $bucketSize) + 1;
+ $bucketEnd = min($bucketEnd, $dataLength - 1);
+
+ // Calculate average point for next bucket (used as reference)
+ $nextBucketStart = (int) floor(($i + 2) * $bucketSize) + 1;
+ $nextBucketEnd = (int) floor(($i + 3) * $bucketSize) + 1;
+ $nextBucketEnd = min($nextBucketEnd, $dataLength - 1);
+
+ $avgX = 0;
+ $avgY = 0;
+ $nextBucketCount = $nextBucketEnd - $nextBucketStart + 1;
+
+ if ($nextBucketCount > 0) {
+ for ($j = $nextBucketStart; $j <= $nextBucketEnd; $j++) {
+ $avgX += $data[$j][0];
+ $avgY += $data[$j][1];
+ }
+ $avgX /= $nextBucketCount;
+ $avgY /= $nextBucketCount;
+ }
+
+ // Find point in current bucket with largest triangle area
+ $maxArea = -1;
+ $maxAreaIndex = $bucketStart;
+
+ $pointAX = $data[$a][0];
+ $pointAY = $data[$a][1];
+
+ for ($j = $bucketStart; $j <= $bucketEnd; $j++) {
+ // Triangle area calculation
+ $area = abs(
+ ($pointAX - $avgX) * ($data[$j][1] - $pointAY) -
+ ($pointAX - $data[$j][0]) * ($avgY - $pointAY)
+ ) * 0.5;
+
+ if ($area > $maxArea) {
+ $maxArea = $area;
+ $maxAreaIndex = $j;
+ }
+ }
+
+ $sampled[] = $data[$maxAreaIndex];
+ $a = $maxAreaIndex;
+ }
+
+ $sampled[] = $data[$dataLength - 1]; // Always keep last point
+
+ return $sampled;
+}
diff --git a/resources/views/livewire/project/shared/metrics.blade.php b/resources/views/livewire/project/shared/metrics.blade.php
index 57e09af6da..728f7fef4f 100644
--- a/resources/views/livewire/project/shared/metrics.blade.php
+++ b/resources/views/livewire/project/shared/metrics.blade.php
@@ -29,230 +29,179 @@
<div wire:ignore id="{!! $chartId !!}-cpu"></div>
<script>
- checkTheme();
- const optionsServerCpu = {
- stroke: {
- curve: 'straight',
- width: 2,
- },
- chart: {
- height: '150px',
- id: '{!! $chartId !!}-cpu',
- type: 'area',
- toolbar: {
- show: true,
- tools: {
- download: false,
- selection: false,
- zoom: true,
- zoomin: false,
- zoomout: false,
- pan: false,
- reset: true
- },
+ (function() {
+ checkTheme();
+ const optionsServerCpu = {
+ stroke: {
+ curve: 'straight',
+ width: 2,
},
- animations: {
- enabled: true,
+ chart: {
+ height: '150px',
+ id: '{!! $chartId !!}-cpu',
+ type: 'area',
+ toolbar: {
+ show: true,
+ tools: {
+ download: false,
+ selection: false,
+ zoom: true,
+ zoomin: false,
+ zoomout: false,
+ pan: false,
+ reset: true
+ },
+ },
+ animations: {
+ enabled: true,
+ },
},
- },
- fill: {
- type: 'gradient',
- },
- dataLabels: {
- enabled: false,
- offsetY: -10,
- style: {
- colors: ['#FCD452'],
+ fill: {
+ type: 'gradient',
},
- background: {
+ dataLabels: {
enabled: false,
- }
- },
- grid: {
- show: true,
- borderColor: '',
- },
- colors: [cpuColor],
- xaxis: {
- type: 'datetime',
- },
- series: [{
- name: "CPU %",
- data: []
- }],
- noData: {
- text: 'Loading...',
- style: {
- color: textColor,
- }
- },
- tooltip: {
- enabled: true,
- marker: {
- show: false,
+ offsetY: -10,
+ style: {
+ colors: ['#FCD452'],
+ },
+ background: {
+ enabled: false,
+ }
+ },
+ grid: {
+ show: true,
+ borderColor: '',
},
- custom: function({ series, seriesIndex, dataPointIndex, w }) {
- const value = series[seriesIndex][dataPointIndex];
- const timestamp = w.globals.seriesX[seriesIndex][dataPointIndex];
- const date = new Date(timestamp);
- const timeString = String(date.getUTCHours()).padStart(2, '0') + ':' +
- String(date.getUTCMinutes()).padStart(2, '0') + ':' +
- String(date.getUTCSeconds()).padStart(2, '0') + ', ' +
- date.getUTCFullYear() + '-' +
- String(date.getUTCMonth() + 1).padStart(2, '0') + '-' +
- String(date.getUTCDate()).padStart(2, '0');
- return '<div class="apexcharts-tooltip-custom">' +
- '<div class="apexcharts-tooltip-custom-value">CPU: <span class="apexcharts-tooltip-value-bold">' + value + '%</span></div>' +
- '<div class="apexcharts-tooltip-custom-title">' + timeString + '</div>' +
- '</div>';
- }
- },
- legend: {
- show: false
- }
- }
- const serverCpuChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-cpu`), optionsServerCpu);
- serverCpuChart.render();
- Livewire.on('refreshChartData-{!! $chartId !!}-cpu', (chartData) => {
- checkTheme();
- serverCpuChart.updateOptions({
- series: [{
- data: chartData[0].seriesData,
- }],
- colors: [cpuColor],
+ colors: [cpuColor],
xaxis: {
type: 'datetime',
- labels: {
- show: true,
- style: {
- colors: textColor,
- }
- }
},
- yaxis: {
- show: true,
- labels: {
- show: true,
- style: {
- colors: textColor,
- },
- formatter: function(value) {
- return Math.round(value) + ' %';
- }
- }
- },
+ series: [{
+ name: "CPU %",
+ data: []
+ }],
noData: {
text: 'Loading...',
style: {
color: textColor,
}
+ },
+ tooltip: {
+ enabled: true,
+ marker: {
+ show: false,
+ },
+ custom: function({ series, seriesIndex, dataPointIndex, w }) {
+ const value = series[seriesIndex][dataPointIndex];
+ const timestamp = w.globals.seriesX[seriesIndex][dataPointIndex];
+ const date = new Date(timestamp);
+ const timeString = String(date.getUTCHours()).padStart(2, '0') + ':' +
+ String(date.getUTCMinutes()).padStart(2, '0') + ':' +
+ String(date.getUTCSeconds()).padStart(2, '0') + ', ' +
+ date.getUTCFullYear() + '-' +
+ String(date.getUTCMonth() + 1).padStart(2, '0') + '-' +
+ String(date.getUTCDate()).padStart(2, '0');
+ return '<div class="apexcharts-tooltip-custom">' +
+ '<div class="apexcharts-tooltip-custom-value">CPU: <span class="apexcharts-tooltip-value-bold">' + value + '%</span></div>' +
+ '<div class="apexcharts-tooltip-custom-title">' + timeString + '</div>' +
+ '</div>';
+ }
+ },
+ legend: {
+ show: false
}
+ }
+ const serverCpuChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-cpu`), optionsServerCpu);
+ serverCpuChart.render();
+ Livewire.on('refreshChartData-{!! $chartId !!}-cpu', (chartData) => {
+ checkTheme();
+ serverCpuChart.updateOptions({
+ series: [{
+ data: chartData[0].seriesData,
+ }],
+ colors: [cpuColor],
+ xaxis: {
+ type: 'datetime',
+ labels: {
+ show: true,
+ style: {
+ colors: textColor,
+ }
+ }
+ },
+ yaxis: {
+ show: true,
+ labels: {
+ show: true,
+ style: {
+ colors: textColor,
+ },
+ formatter: function(value) {
+ return Math.round(value) + ' %';
+ }
+ }
+ },
+ noData: {
+ text: 'Loading...',
+ style: {
+ color: textColor,
+ }
+ }
+ });
});
- });
+ })();
</script>
<h4>Memory Usage</h4>
<div wire:ignore id="{!! $chartId !!}-memory"></div>
<script>
- checkTheme();
- const optionsServerMemory = {
- stroke: {
- curve: 'straight',
- width: 2,
- },
- chart: {
- height: '150px',
- id: '{!! $chartId !!}-memory',
- type: 'area',
- toolbar: {
- show: true,
- tools: {
- download: false,
- selection: false,
- zoom: true,
- zoomin: false,
- zoomout: false,
- pan: false,
- reset: true
- },
+ (function() {
+ checkTheme();
+ const optionsServerMemory = {
+ stroke: {
+ curve: 'straight',
+ width: 2,
},
- animations: {
- enabled: true,
+ chart: {
+ height: '150px',
+ id: '{!! $chartId !!}-memory',
+ type: 'area',
+ toolbar: {
+ show: true,
+ tools: {
+ download: false,
+ selection: false,
+ zoom: true,
+ zoomin: false,
+ zoomout: false,
+ pan: false,
+ reset: true
+ },
+ },
+ animations: {
+ enabled: true,
+ },
},
- },
- fill: {
- type: 'gradient',
- },
- dataLabels: {
- enabled: false,
- offsetY: -10,
- style: {
- colors: ['#FCD452'],
+ fill: {
+ type: 'gradient',
},
- background: {
+ dataLabels: {
enabled: false,
- }
- },
- grid: {
- show: true,
- borderColor: '',
- },
- colors: [ramColor],
- xaxis: {
- type: 'datetime',
- labels: {
+ offsetY: -10,
+ style: {
+ colors: ['#FCD452'],
+ },
+ background: {
+ enabled: false,
+ }
+ },
+ grid: {
show: true,
- style: {
- colors: textColor,
- }
- }
- },
- series: [{
- name: "Memory (MB)",
- data: []
- }],
- noData: {
- text: 'Loading...',
- style: {
- color: textColor,
- }
- },
- tooltip: {
- enabled: true,
- marker: {
- show: false,
+ borderColor: '',
},
- custom: function({ series, seriesIndex, dataPointIndex, w }) {
- const value = series[seriesIndex][dataPointIndex];
- const timestamp = w.globals.seriesX[seriesIndex][dataPointIndex];
- const date = new Date(timestamp);
- const timeString = String(date.getUTCHours()).padStart(2, '0') + ':' +
- String(date.getUTCMinutes()).padStart(2, '0') + ':' +
- String(date.getUTCSeconds()).padStart(2, '0') + ', ' +
- date.getUTCFullYear() + '-' +
- String(date.getUTCMonth() + 1).padStart(2, '0') + '-' +
- String(date.getUTCDate()).padStart(2, '0');
- return '<div class="apexcharts-tooltip-custom">' +
- '<div class="apexcharts-tooltip-custom-value">Memory: <span class="apexcharts-tooltip-value-bold">' + value + ' MB</span></div>' +
- '<div class="apexcharts-tooltip-custom-title">' + timeString + '</div>' +
- '</div>';
- }
- },
- legend: {
- show: false
- }
- }
- const serverMemoryChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-memory`),
- optionsServerMemory);
- serverMemoryChart.render();
- Livewire.on('refreshChartData-{!! $chartId !!}-memory', (chartData) => {
- checkTheme();
- serverMemoryChart.updateOptions({
- series: [{
- data: chartData[0].seriesData,
- }],
- colors: [ramColor],
+ colors: [ramColor],
xaxis: {
type: 'datetime',
labels: {
@@ -262,27 +211,82 @@
}
}
},
- yaxis: {
- min: 0,
- show: true,
- labels: {
- show: true,
- style: {
- colors: textColor,
- },
- formatter: function(value) {
- return Math.round(value) + ' MB';
- }
- }
- },
+ series: [{
+ name: "Memory (MB)",
+ data: []
+ }],
noData: {
text: 'Loading...',
style: {
color: textColor,
}
+ },
+ tooltip: {
+ enabled: true,
+ marker: {
+ show: false,
+ },
+ custom: function({ series, seriesIndex, dataPointIndex, w }) {
+ const value = series[seriesIndex][dataPointIndex];
+ const timestamp = w.globals.seriesX[seriesIndex][dataPointIndex];
+ const date = new Date(timestamp);
+ const timeString = String(date.getUTCHours()).padStart(2, '0') + ':' +
+ String(date.getUTCMinutes()).padStart(2, '0') + ':' +
+ String(date.getUTCSeconds()).padStart(2, '0') + ', ' +
+ date.getUTCFullYear() + '-' +
+ String(date.getUTCMonth() + 1).padStart(2, '0') + '-' +
+ String(date.getUTCDate()).padStart(2, '0');
+ return '<div class="apexcharts-tooltip-custom">' +
+ '<div class="apexcharts-tooltip-custom-value">Memory: <span class="apexcharts-tooltip-value-bold">' + value + ' MB</span></div>' +
+ '<div class="apexcharts-tooltip-custom-title">' + timeString + '</div>' +
+ '</div>';
+ }
+ },
+ legend: {
+ show: false
}
+ }
+ const serverMemoryChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-memory`),
+ optionsServerMemory);
+ serverMemoryChart.render();
+ Livewire.on('refreshChartData-{!! $chartId !!}-memory', (chartData) => {
+ checkTheme();
+ serverMemoryChart.updateOptions({
+ series: [{
+ data: chartData[0].seriesData,
+ }],
+ colors: [ramColor],
+ xaxis: {
+ type: 'datetime',
+ labels: {
+ show: true,
+ style: {
+ colors: textColor,
+ }
+ }
+ },
+ yaxis: {
+ min: 0,
+ show: true,
+ labels: {
+ show: true,
+ style: {
+ colors: textColor,
+ },
+ formatter: function(value) {
+ return Math.round(value) + ' MB';
+ }
+ }
+ },
+ noData: {
+ text: 'Loading...',
+ style: {
+ color: textColor,
+ }
+ }
+ });
});
- });
+ })();
</script>
</div>
</div>
diff --git a/resources/views/livewire/server/charts.blade.php b/resources/views/livewire/server/charts.blade.php
index 876a4d23db..9aabf45dd8 100644
--- a/resources/views/livewire/server/charts.blade.php
+++ b/resources/views/livewire/server/charts.blade.php
@@ -23,145 +23,16 @@
<div wire:ignore id="{!! $chartId !!}-cpu"></div>
<script>
- checkTheme();
- const optionsServerCpu = {
- stroke: {
- curve: 'straight',
- width: 2,
- },
- chart: {
- height: '150px',
- id: '{!! $chartId !!}-cpu',
- type: 'area',
- toolbar: {
- show: true,
- tools: {
- download: false,
- selection: false,
- zoom: true,
- zoomin: false,
- zoomout: false,
- pan: false,
- reset: true
- },
- },
- animations: {
- enabled: true,
- },
- },
- fill: {
- type: 'gradient',
- },
- dataLabels: {
- enabled: false,
- offsetY: -10,
- style: {
- colors: ['#FCD452'],
- },
- background: {
- enabled: false,
- }
- },
- grid: {
- show: true,
- borderColor: '',
- },
- colors: [cpuColor],
- xaxis: {
- type: 'datetime',
- },
- series: [{
- name: 'CPU %',
- data: []
- }],
- noData: {
- text: 'Loading...',
- style: {
- color: textColor,
- }
- },
- tooltip: {
- enabled: true,
- marker: {
- show: false,
- },
- custom: function({ series, seriesIndex, dataPointIndex, w }) {
- const value = series[seriesIndex][dataPointIndex];
- const timestamp = w.globals.seriesX[seriesIndex][dataPointIndex];
- const date = new Date(timestamp);
- const timeString = String(date.getUTCHours()).padStart(2, '0') + ':' +
- String(date.getUTCMinutes()).padStart(2, '0') + ':' +
- String(date.getUTCSeconds()).padStart(2, '0') + ', ' +
- date.getUTCFullYear() + '-' +
- String(date.getUTCMonth() + 1).padStart(2, '0') + '-' +
- String(date.getUTCDate()).padStart(2, '0');
- return '<div class="apexcharts-tooltip-custom">' +
- '<div class="apexcharts-tooltip-custom-value">CPU: <span class="apexcharts-tooltip-value-bold">' + value + '%</span></div>' +
- '<div class="apexcharts-tooltip-custom-title">' + timeString + '</div>' +
- '</div>';
- }
- },
- legend: {
- show: false
- }
- }
- const serverCpuChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-cpu`),
- optionsServerCpu);
- serverCpuChart.render();
- document.addEventListener('livewire:init', () => {
- Livewire.on('refreshChartData-{!! $chartId !!}-cpu', (chartData) => {
- checkTheme();
- serverCpuChart.updateOptions({
- series: [{
- data: chartData[0].seriesData,
- }],
- colors: [cpuColor],
- xaxis: {
- type: 'datetime',
- labels: {
- show: true,
- style: {
- colors: textColor,
- }
- }
- },
- yaxis: {
- show: true,
- labels: {
- show: true,
- style: {
- colors: textColor,
- },
- formatter: function(value) {
- return Math.round(value) + ' %';
- }
- }
- },
- noData: {
- text: 'Loading...',
- style: {
- color: textColor,
- }
- }
- });
- });
- });
- </script>
-
- <div>
- <h4>Memory Usage</h4>
- <div wire:ignore id="{!! $chartId !!}-memory"></div>
-
- <script>
+ (function() {
checkTheme();
- const optionsServerMemory = {
+ const optionsServerCpu = {
stroke: {
curve: 'straight',
width: 2,
},
chart: {
height: '150px',
- id: '{!! $chartId !!}-memory',
+ id: '{!! $chartId !!}-cpu',
type: 'area',
toolbar: {
show: true,
@@ -196,18 +67,12 @@
show: true,
borderColor: '',
},
- colors: [ramColor],
+ colors: [cpuColor],
xaxis: {
type: 'datetime',
- labels: {
- show: true,
- style: {
- colors: textColor,
- }
- }
- },
- series: [{
- name: "Memory (%)",
+ },
+ series: [{
+ name: 'CPU %',
data: []
}],
noData: {
@@ -232,7 +97,7 @@
String(date.getUTCMonth() + 1).padStart(2, '0') + '-' +
String(date.getUTCDate()).padStart(2, '0');
return '<div class="apexcharts-tooltip-custom">' +
- '<div class="apexcharts-tooltip-custom-value">Memory: <span class="apexcharts-tooltip-value-bold">' + value + '%</span></div>' +
+ '<div class="apexcharts-tooltip-custom-value">CPU: <span class="apexcharts-tooltip-value-bold">' + value + '%</span></div>' +
'<div class="apexcharts-tooltip-custom-title">' + timeString + '</div>' +
'</div>';
}
@@ -241,17 +106,17 @@
show: false
}
}
- const serverMemoryChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-memory`),
- optionsServerMemory);
- serverMemoryChart.render();
+ const serverCpuChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-cpu`),
+ optionsServerCpu);
+ serverCpuChart.render();
document.addEventListener('livewire:init', () => {
- Livewire.on('refreshChartData-{!! $chartId !!}-memory', (chartData) => {
+ Livewire.on('refreshChartData-{!! $chartId !!}-cpu', (chartData) => {
checkTheme();
- serverMemoryChart.updateOptions({
+ serverCpuChart.updateOptions({
series: [{
data: chartData[0].seriesData,
}],
- colors: [ramColor],
+ colors: [cpuColor],
xaxis: {
type: 'datetime',
labels: {
@@ -262,16 +127,15 @@
}
},
yaxis: {
- min: 0,
show: true,
labels: {
show: true,
style: {
colors: textColor,
},
- formatter: function(value) {
- return Math.round(value) + ' %';
- }
+ formatter: function(value) {
+ return Math.round(value) + ' %';
+ }
}
},
noData: {
@@ -283,6 +147,146 @@
});
});
});
+ })();
+ </script>
+
+ <div>
+ <h4>Memory Usage</h4>
+ <div wire:ignore id="{!! $chartId !!}-memory"></div>
+
+ <script>
+ (function() {
+ checkTheme();
+ const optionsServerMemory = {
+ stroke: {
+ curve: 'straight',
+ width: 2,
+ },
+ chart: {
+ height: '150px',
+ id: '{!! $chartId !!}-memory',
+ type: 'area',
+ toolbar: {
+ show: true,
+ tools: {
+ download: false,
+ selection: false,
+ zoom: true,
+ zoomin: false,
+ zoomout: false,
+ pan: false,
+ reset: true
+ },
+ },
+ animations: {
+ enabled: true,
+ },
+ },
+ fill: {
+ type: 'gradient',
+ },
+ dataLabels: {
+ enabled: false,
+ offsetY: -10,
+ style: {
+ colors: ['#FCD452'],
+ },
+ background: {
+ enabled: false,
+ }
+ },
+ grid: {
+ show: true,
+ borderColor: '',
+ },
+ colors: [ramColor],
+ xaxis: {
+ type: 'datetime',
+ labels: {
+ show: true,
+ style: {
+ colors: textColor,
+ }
+ }
+ },
+ series: [{
+ name: "Memory (%)",
+ data: []
+ }],
+ noData: {
+ text: 'Loading...',
+ style: {
+ color: textColor,
+ }
+ },
+ tooltip: {
+ enabled: true,
+ marker: {
+ show: false,
+ },
+ custom: function({ series, seriesIndex, dataPointIndex, w }) {
+ const value = series[seriesIndex][dataPointIndex];
+ const timestamp = w.globals.seriesX[seriesIndex][dataPointIndex];
+ const date = new Date(timestamp);
+ const timeString = String(date.getUTCHours()).padStart(2, '0') + ':' +
+ String(date.getUTCMinutes()).padStart(2, '0') + ':' +
+ String(date.getUTCSeconds()).padStart(2, '0') + ', ' +
+ date.getUTCFullYear() + '-' +
+ String(date.getUTCMonth() + 1).padStart(2, '0') + '-' +
+ String(date.getUTCDate()).padStart(2, '0');
+ return '<div class="apexcharts-tooltip-custom">' +
+ '<div class="apexcharts-tooltip-custom-value">Memory: <span class="apexcharts-tooltip-value-bold">' + value + '%</span></div>' +
+ '<div class="apexcharts-tooltip-custom-title">' + timeString + '</div>' +
+ '</div>';
+ }
+ },
+ legend: {
+ show: false
+ }
+ }
+ const serverMemoryChart = new ApexCharts(document.getElementById(`{!! $chartId !!}-memory`),
+ optionsServerMemory);
+ serverMemoryChart.render();
+ document.addEventListener('livewire:init', () => {
+ Livewire.on('refreshChartData-{!! $chartId !!}-memory', (chartData) => {
+ checkTheme();
+ serverMemoryChart.updateOptions({
+ series: [{
+ data: chartData[0].seriesData,
+ }],
+ colors: [ramColor],
+ xaxis: {
+ type: 'datetime',
+ labels: {
+ show: true,
+ style: {
+ colors: textColor,
+ }
+ }
+ },
+ yaxis: {
+ min: 0,
+ show: true,
+ labels: {
+ show: true,
+ style: {
+ colors: textColor,
+ },
+ formatter: function(value) {
+ return Math.round(value) + ' %';
+ }
+ }
+ },
+ noData: {
+ text: 'Loading...',
+ style: {
+ color: textColor,
+ }
+ }
+ });
+ });
+ });
+ })();
</script>
</div>
diff --git a/tests/Unit/ClickhouseOfficialImageMigrationTest.php b/tests/Unit/ClickhouseOfficialImageMigrationTest.php
index 9edf5d09c9..054dc44237 100644
--- a/tests/Unit/ClickhouseOfficialImageMigrationTest.php
+++ b/tests/Unit/ClickhouseOfficialImageMigrationTest.php
@@ -3,7 +3,7 @@
use App\Models\StandaloneClickhouse;
test('clickhouse uses clickhouse_db field in internal connection string', function () {
- $clickhouse = new StandaloneClickhouse();
+ $clickhouse = new StandaloneClickhouse;
$clickhouse->clickhouse_admin_user = 'testuser';
$clickhouse->clickhouse_admin_password = 'testpass';
$clickhouse->clickhouse_db = 'mydb';
@@ -18,7 +18,7 @@ test('clickhouse uses clickhouse_db field in internal connection string', functi
});
test('clickhouse defaults to default database when clickhouse_db is null', function () {
- $clickhouse = new StandaloneClickhouse();
+ $clickhouse = new StandaloneClickhouse;
$clickhouse->clickhouse_admin_user = 'testuser';
$clickhouse->clickhouse_admin_password = 'testpass';
$clickhouse->clickhouse_db = null;
@@ -30,7 +30,7 @@ test('clickhouse defaults to default database when clickhouse_db is null', funct
});
test('clickhouse external url uses correct database', function () {
- $clickhouse = new StandaloneClickhouse();
+ $clickhouse = new StandaloneClickhouse;
$clickhouse->clickhouse_admin_user = 'admin';
$clickhouse->clickhouse_admin_password = 'secret';
$clickhouse->clickhouse_db = 'production';
@@ -38,12 +38,19 @@ test('clickhouse external url uses correct database', function () {
$clickhouse->is_public = true;
$clickhouse->public_port = 8123;
- $clickhouse->destination = new class {
+ $clickhouse->destination = new class
+ {
public $server;
- public function __construct() {
- $this->server = new class {
- public function __get($name) {
- if ($name === 'getIp') return '1.2.3.4';
+
+ public function __construct()
+ {
+ $this->server = new class
+ {
+ public function __get($name)
+ {
+ if ($name === 'getIp') {
+ return '1.2.3.4';
+ }
}
};
}
diff --git a/tests/Unit/ServerMetricsDownsamplingTest.php b/tests/Unit/MetricsDownsamplingTest.php
similarity index 78%
rename from tests/Unit/ServerMetricsDownsamplingTest.php
rename to tests/Unit/MetricsDownsamplingTest.php
index 819eecc4ce..67685896f0 100644
--- a/tests/Unit/ServerMetricsDownsamplingTest.php
+++ b/tests/Unit/MetricsDownsamplingTest.php
@@ -1,19 +1,9 @@
<?php
-use App\Models\Server;
-
/**
- * Helper to call the private downsampleLTTB method on Server model via reflection.
+ * Tests for the downsampleLTTB helper function used for metrics downsampling.
+ * This function implements the Largest-Triangle-Three-Buckets algorithm.
*/
-function callDownsampleLTTB(array $data, int $threshold): array
-{
- $server = new Server;
- $reflection = new ReflectionClass($server);
- $method = $reflection->getMethod('downsampleLTTB');
-
- return $method->invoke($server, $data, $threshold);
-}
-
it('returns data unchanged when below threshold', function () {
$data = [
[1000, 10.5],
@@ -21,7 +11,7 @@ it('returns data unchanged when below threshold', function () {
[3000, 15.7],
];
- $result = callDownsampleLTTB($data, 1000);
+ $result = downsampleLTTB($data, 1000);
expect($result)->toBe($data);
});
@@ -35,10 +25,10 @@ it('returns data unchanged when threshold is 2 or less', function () {
[5000, 12.0],
];
- $result = callDownsampleLTTB($data, 2);
+ $result = downsampleLTTB($data, 2);
expect($result)->toBe($data);
- $result = callDownsampleLTTB($data, 1);
+ $result = downsampleLTTB($data, 1);
expect($result)->toBe($data);
});
@@ -52,7 +42,7 @@ it('downsamples to target threshold count', function () {
$data[] = [$i * 1000, mt_rand(0, 100) / 10];
}
- $result = callDownsampleLTTB($data, 10);
+ $result = downsampleLTTB($data, 10);
expect(count($result))->toBe(10);
});
@@ -63,7 +53,7 @@ it('preserves first and last data points', function () {
$data[] = [$i * 1000, $i * 1.5];
}
- $result = callDownsampleLTTB($data, 20);
+ $result = downsampleLTTB($data, 20);
// First point should be preserved
expect($result[0])->toBe($data[0]);
@@ -78,7 +68,7 @@ it('maintains chronological order', function () {
$data[] = [$i * 60000, sin($i / 10) * 50 + 50]; // Sine wave pattern
}
- $result = callDownsampleLTTB($data, 50);
+ $result = downsampleLTTB($data, 50);
// Verify all timestamps are in non-decreasing order
$previousTimestamp = -1;
@@ -100,7 +90,7 @@ it('handles large datasets efficiently', function () {
}
$startTime = microtime(true);
- $result = callDownsampleLTTB($data, 1000);
+ $result = downsampleLTTB($data, 1000);
$executionTime = microtime(true) - $startTime;
expect(count($result))->toBe(1000);
@@ -121,7 +111,7 @@ it('preserves peaks and valleys in data', function () {
$data[] = [$i * 1000, $value];
}
- $result = callDownsampleLTTB($data, 20);
+ $result = downsampleLTTB($data, 20);
// The peak (100) and valley (0) should be preserved due to LTTB algorithm
$values = array_column($result, 1);