You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudMetricHistoryStore.php

312 lines
11 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\User;
/**
* Bounded performance-history storage behind one stable chart interface.
*
* Billing totals and traffic checkpoints are deliberately outside this
* module. It owns only disposable chart samples and their compact rollups.
*/
final class CloudMetricHistoryStore
{
public const RAW_RETENTION_SECONDS = 24 * 3600;
public const FIVE_MINUTE_RETENTION_SECONDS = 7 * 86400;
public const HOURLY_RETENTION_SECONDS = 35 * 86400;
public const FIVE_MINUTES = 300;
public const ONE_HOUR = 3600;
public const MAX_PRUNE_ROWS = 2000;
private const FIELDS = [
'cpu_percent', 'memory_used_mib', 'memory_total_mib',
'disk_read_bps', 'disk_write_bps', 'network_rx_bps',
'network_tx_bps',
];
/** @param array<string,mixed> $sample */
public static function recordRollups(object $log, array $sample): void
{
$instanceId = (int) ($sample['instance_id'] ?? 0);
$sampledAt = (int) ($sample['sampled_at'] ?? 0);
if ($instanceId < 1 || $sampledAt < 1) {
throw new \InvalidArgumentException(
'Metric rollup sample identity is invalid'
);
}
foreach ([self::FIVE_MINUTES, self::ONE_HOUR] as $interval) {
self::recordInterval($log, $sample, $interval);
}
}
/**
* @return array{interval_seconds:int,points:list<array<string,mixed>>}
*/
public static function series(
object $log,
int $instanceId,
int $userId,
string $range,
int $now
): array {
$ranges = [
'1h' => [3600, 60, 'raw'],
'24h' => [86400, 300, self::FIVE_MINUTES],
'7d' => [7 * 86400, 1800, self::FIVE_MINUTES],
'30d' => [30 * 86400, 7200, self::ONE_HOUR],
];
if (!isset($ranges[$range])) {
throw new CloudError('指标时间范围无效');
}
[$seconds, $outputInterval, $source] = $ranges[$range];
if ($source === 'raw') {
$rows = self::rawSeries(
$log,
$instanceId,
$userId,
$now - $seconds - $outputInterval,
$outputInterval
);
} else {
$rows = self::rollupSeries(
$log,
$instanceId,
$userId,
$now - $seconds - $outputInterval,
$outputInterval,
(int) $source
);
}
$points = [];
foreach ($rows as $row) {
$point = ['timestamp' => max(0, (int) $row->timestamp)];
foreach (self::FIELDS as $field) {
$value = $row->{$field};
$point[$field] = $value === null
? null : max(0.0, (float) $value);
}
$points[] = $point;
}
return ['interval_seconds' => $outputInterval, 'points' => $points];
}
/**
* Prune one bounded batch from every history tier and delete chart data
* belonging to a logically deleted instance.
*
* @return array{raw:int,five_minute:int,hourly:int,deleted_instance:int}
*/
public static function prune(object $log, int $now): array
{
return [
'raw' => self::pruneRaw(
$log,
$now - self::RAW_RETENTION_SECONDS
),
'five_minute' => self::pruneRollup(
$log,
self::FIVE_MINUTES,
$now - self::FIVE_MINUTE_RETENTION_SECONDS
),
'hourly' => self::pruneRollup(
$log,
self::ONE_HOUR,
$now - self::HOURLY_RETENTION_SECONDS
),
'deleted_instance' => self::pruneDeletedInstances($log),
];
}
/** @param array<string,mixed> $sample */
private static function recordInterval(
object $log,
array $sample,
int $interval
): void {
$bucketStart = intdiv((int) $sample['sampled_at'], $interval)
* $interval;
$query = $log->table('cloud_vm_metric_rollups')
->where('instance_id', (int) $sample['instance_id'])
->where('interval_seconds', $interval)
->where('bucket_start', $bucketStart);
$existing = $query->lockForUpdate()->first();
if ($existing === null) {
$values = [
'instance_id' => (int) $sample['instance_id'],
'user_id' => (int) $sample['user_id'],
'interval_seconds' => $interval,
'bucket_start' => $bucketStart,
'sample_count' => 1,
'last_sampled_at' => (int) $sample['sampled_at'],
];
foreach (self::FIELDS as $field) {
$value = self::metric($sample[$field] ?? null);
$values[$field . '_sum'] = $value;
$values[$field . '_count'] = $value === null ? 0 : 1;
}
$log->table('cloud_vm_metric_rollups')->insert($values);
return;
}
if ((int) $existing->user_id !== (int) $sample['user_id']) {
throw new \RuntimeException(
'Metric rollup ownership changed inside one logical bucket'
);
}
$values = [
'sample_count' => (int) $existing->sample_count + 1,
'last_sampled_at' => max(
(int) $existing->last_sampled_at,
(int) $sample['sampled_at']
),
];
foreach (self::FIELDS as $field) {
$value = self::metric($sample[$field] ?? null);
$sumColumn = $field . '_sum';
$countColumn = $field . '_count';
$values[$sumColumn] = $value === null
? $existing->{$sumColumn}
: (float) ($existing->{$sumColumn} ?? 0.0) + $value;
$values[$countColumn] = (int) $existing->{$countColumn}
+ ($value === null ? 0 : 1);
}
$query->update($values);
}
/** @return iterable<object> */
private static function rawSeries(
object $log,
int $instanceId,
int $userId,
int $cutoff,
int $interval
): iterable {
$bucket = self::bucketSql($log, 'sampled_at', $interval);
$select = $bucket
. ' AS metric_bucket, MAX(sampled_at) AS timestamp';
foreach (self::FIELDS as $field) {
$select .= ', AVG(' . $field . ') AS ' . $field;
}
return $log->table('cloud_vm_metric_samples')
->where('instance_id', $instanceId)
->where('user_id', $userId)
->where('sampled_at', '>=', $cutoff)
->selectRaw($select)->groupByRaw($bucket)
->orderBy('metric_bucket')->limit(600)->get();
}
/** @return iterable<object> */
private static function rollupSeries(
object $log,
int $instanceId,
int $userId,
int $cutoff,
int $outputInterval,
int $sourceInterval
): iterable {
$bucket = self::bucketSql($log, 'bucket_start', $outputInterval);
$select = $bucket
. ' AS metric_bucket, MAX(last_sampled_at) AS timestamp';
foreach (self::FIELDS as $field) {
$sum = $field . '_sum';
$count = $field . '_count';
$select .= ', CASE WHEN SUM(' . $count . ') = 0 THEN NULL ELSE '
. 'SUM(' . $sum . ') / SUM(' . $count . ') END AS ' . $field;
}
return $log->table('cloud_vm_metric_rollups')
->where('instance_id', $instanceId)
->where('user_id', $userId)
->where('interval_seconds', $sourceInterval)
->where('bucket_start', '>=', $cutoff)
->selectRaw($select)->groupByRaw($bucket)
->orderBy('metric_bucket')->limit(600)->get();
}
private static function bucketSql(
object $log,
string $column,
int $interval
): string {
return $log->getDriverName() === 'sqlite'
? 'CAST(' . $column . ' / ' . $interval . ' AS INTEGER)'
: 'FLOOR(' . $column . ' / ' . $interval . ')';
}
private static function pruneRaw(object $log, int $cutoff): int
{
$rows = $log->table('cloud_vm_metric_samples')
->where('sampled_at', '<', $cutoff)
->orderBy('sampled_at')->limit(self::MAX_PRUNE_ROWS)
->get(['instance_id', 'sampled_at']);
$deleted = 0;
foreach ($rows as $row) {
$deleted += $log->table('cloud_vm_metric_samples')
->where('instance_id', (int) $row->instance_id)
->where('sampled_at', (int) $row->sampled_at)
->where('sampled_at', '<', $cutoff)->delete();
}
return $deleted;
}
private static function pruneRollup(
object $log,
int $interval,
int $cutoff
): int {
$rows = $log->table('cloud_vm_metric_rollups')
->where('interval_seconds', $interval)
->where('bucket_start', '<', $cutoff)
->orderBy('bucket_start')->limit(self::MAX_PRUNE_ROWS)
->get(['instance_id', 'bucket_start']);
$deleted = 0;
foreach ($rows as $row) {
$deleted += $log->table('cloud_vm_metric_rollups')
->where('instance_id', (int) $row->instance_id)
->where('interval_seconds', $interval)
->where('bucket_start', (int) $row->bucket_start)
->where('bucket_start', '<', $cutoff)->delete();
}
return $deleted;
}
private static function pruneDeletedInstances(object $log): int
{
$candidateIds = $log->table('cloud_vm_metric_rollups')
->select('instance_id')->distinct()->orderBy('instance_id')
->limit(200)->pluck('instance_id')
->map(static fn ($id): int => (int) $id)->all();
if ($candidateIds === []) {
return 0;
}
$main = User::getConnectionResolver()->connection();
$liveIds = $main->table('cloud_instances')
->whereIn('id', $candidateIds)
->where('status', '<>', 'deleted')
->pluck('id')->map(static fn ($id): int => (int) $id)->all();
$deletedIds = array_values(array_diff($candidateIds, $liveIds));
if ($deletedIds === []) {
return 0;
}
$deleted = $log->table('cloud_vm_metric_rollups')
->whereIn('instance_id', $deletedIds)->delete();
$deleted += $log->table('cloud_vm_metric_samples')
->whereIn('instance_id', $deletedIds)->delete();
return $deleted;
}
private static function metric(mixed $value): ?float
{
if ($value === null) {
return null;
}
if (!is_int($value) && !is_float($value)) {
throw new \RuntimeException('Metric rollup value is invalid');
}
$number = (float) $value;
if (!is_finite($number) || $number < 0) {
throw new \RuntimeException('Metric rollup value is invalid');
}
return $number;
}
}