Add prepaid lifecycle and traffic enforcement
parent
74b89051a7
commit
772fa83ae4
@ -0,0 +1,24 @@
|
||||
[Unit]
|
||||
Description=Virt Cloud service-period and traffic lifecycle worker
|
||||
After=network-online.target virt-cloud-engine.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=apache
|
||||
Group=apache
|
||||
WorkingDirectory=/home/virt-cloud/web
|
||||
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudLifecycle
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectHome=false
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=-/home/virt-cloud/runtime/php
|
||||
ReadWritePaths=-/home/virt-cloud/web/storage
|
||||
TimeoutStopSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@ -0,0 +1,24 @@
|
||||
[Unit]
|
||||
Description=Virt Cloud enforcement policy worker %i
|
||||
After=network-online.target virt-cloud-engine.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=apache
|
||||
Group=apache
|
||||
WorkingDirectory=/home/virt-cloud/web
|
||||
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudWorker --policy-only
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectHome=false
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=-/home/virt-cloud/runtime/php
|
||||
ReadWritePaths=-/home/virt-cloud/web/storage
|
||||
TimeoutStopSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@ -1,7 +1,7 @@
|
||||
# Virt Cloud PHP 开发副本
|
||||
|
||||
仅保留 venix 主题及通用账户、邮箱、工单、公告、充值和财务能力。
|
||||
用户侧节点列表已经删除;管理员 `/admin/hosts` 是未接入的宿主机准备页。
|
||||
商城套餐现在是 CPU、内存、带宽和硬盘规格,接入 Python 引擎前不允许购买或扣款。
|
||||
用户侧旧节点列表已经删除;管理员在 `/admin/hosts` 配置宿主机。
|
||||
商城套餐现在是 CPU、内存、带宽、硬盘、账期天数和每期流量额度,通过私有 Python/libvirt 引擎开通实例。支持手动续费、到期停机以及流量用尽仅断网;生产必须同时运行账期 worker 与独立策略 worker。
|
||||
|
||||
详见上层 `docs/PRUNING_REPORT.md`。这不是已集成的生产销售面板,不要对现有生产数据库执行此副本的 SQL。
|
||||
部署与安全边界见上层 `docs/DEPLOYMENT.md` 和 `docs/INTEGRATION_PLAN.md`。真实数据库、宿主机与支付通道仍必须在测试环境验收后再开放销售。
|
||||
|
||||
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
namespace App\Command;
|
||||
|
||||
use App\Services\Cloud\CloudLifecycleService;
|
||||
|
||||
final class CloudLifecycle
|
||||
{
|
||||
public static function run(array $argv = []): int
|
||||
{
|
||||
$once = in_array('--once', $argv, true);
|
||||
$service = new CloudLifecycleService();
|
||||
do {
|
||||
try {
|
||||
$service->tick();
|
||||
} catch (\Throwable $error) {
|
||||
fwrite(STDERR, 'cloud lifecycle temporarily unavailable: '
|
||||
. get_class($error) . PHP_EOL);
|
||||
if ($once) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (!$once) {
|
||||
usleep(15000000);
|
||||
}
|
||||
} while (!$once);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
<?php
|
||||
namespace App\Models;
|
||||
|
||||
final class CloudRenewal extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_renewals';
|
||||
protected $casts = ['amount' => 'decimal:2'];
|
||||
protected $hidden = ['request_hash'];
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
namespace App\Models;
|
||||
|
||||
final class CloudServicePeriod extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_service_periods';
|
||||
}
|
||||
@ -0,0 +1,274 @@
|
||||
<?php
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudJob;
|
||||
use App\Models\CloudServicePeriod;
|
||||
|
||||
final class CloudLifecycleService
|
||||
{
|
||||
public function tick(int $limit = 200): int
|
||||
{
|
||||
$batchSize = max(1, min(1000, $limit));
|
||||
try {
|
||||
CloudTrafficService::sync($batchSize);
|
||||
} catch (\Throwable $error) {
|
||||
// Unknown traffic is fail-open. Time expiry remains enforceable.
|
||||
error_log('cloud traffic sync unavailable: ' . get_class($error));
|
||||
}
|
||||
$queued = 0;
|
||||
CloudInstance::where('status', '<>', 'deleted')
|
||||
->where('service_status', '<>', 'exempt')
|
||||
->select('id')->chunkById($batchSize, function ($instances) use (&$queued) {
|
||||
foreach ($instances as $instance) {
|
||||
try {
|
||||
$queued += $this->reconcile((int) $instance->id) ? 1 : 0;
|
||||
} catch (\Throwable $error) {
|
||||
// One corrupt or temporarily contended record must not
|
||||
// starve every higher instance ID on every daemon pass.
|
||||
error_log('cloud lifecycle instance ' . (int) $instance->id
|
||||
. ' unavailable: ' . get_class($error));
|
||||
}
|
||||
}
|
||||
});
|
||||
return $queued;
|
||||
}
|
||||
|
||||
private function reconcile(int $instanceId): bool
|
||||
{
|
||||
return (new CloudInstance())->getConnection()->transaction(function () use ($instanceId) {
|
||||
$now = time();
|
||||
$instance = CloudInstance::where('id', $instanceId)->lockForUpdate()->first();
|
||||
if ($instance === null || $instance->status === 'deleted'
|
||||
|| $instance->service_status === 'exempt') {
|
||||
return false;
|
||||
}
|
||||
$period = $instance->current_period_id === null ? null
|
||||
: CloudServicePeriod::where('id', $instance->current_period_id)
|
||||
->where('instance_id', $instance->id)->lockForUpdate()->first();
|
||||
|
||||
if ($period !== null && in_array((string) $period->status, ['active', 'exhausted'], true)) {
|
||||
$this->updateUsage($instance, $period, $now);
|
||||
if ((int) $period->ends_at <= $now) {
|
||||
$period->status = 'finished';
|
||||
$period->updated_at = $now;
|
||||
$period->save();
|
||||
$period = null;
|
||||
$instance->current_period_id = null;
|
||||
}
|
||||
} else {
|
||||
$period = null;
|
||||
$instance->current_period_id = null;
|
||||
}
|
||||
|
||||
if ($period === null) {
|
||||
// The lifecycle daemon may be stopped for longer than one
|
||||
// prepaid period. Never briefly activate an already expired
|
||||
// historical period (which would also restore its network).
|
||||
CloudServicePeriod::where('instance_id', $instance->id)
|
||||
->where('status', 'scheduled')->where('ends_at', '<=', $now)
|
||||
->update(['status' => 'finished', 'updated_at' => $now]);
|
||||
$period = CloudServicePeriod::where('instance_id', $instance->id)
|
||||
->where('status', 'scheduled')->where('starts_at', '<=', $now)
|
||||
->where('ends_at', '>', $now)
|
||||
->orderBy('starts_at')->orderBy('id')->lockForUpdate()->first();
|
||||
if ($period !== null) {
|
||||
$period->status = 'active';
|
||||
$period->activated_at = $now;
|
||||
$baseline = CloudTrafficService::periodBaseline(
|
||||
$instance, (int) $period->starts_at);
|
||||
if ($baseline === null
|
||||
&& (int) $instance->traffic_synced_at >= (int) $period->starts_at) {
|
||||
$baseline = [
|
||||
'download' => max(0, (int) $instance->lifetime_download_bytes),
|
||||
'upload' => max(0, (int) $instance->lifetime_upload_bytes),
|
||||
];
|
||||
}
|
||||
$period->download_base_bytes = $baseline['download'] ?? null;
|
||||
$period->upload_base_bytes = $baseline['upload'] ?? null;
|
||||
$period->download_used_bytes = $baseline === null ? 0
|
||||
: max(0, (int) $instance->lifetime_download_bytes
|
||||
- (int) $baseline['download']);
|
||||
$period->upload_used_bytes = $baseline === null ? 0
|
||||
: max(0, (int) $instance->lifetime_upload_bytes
|
||||
- (int) $baseline['upload']);
|
||||
$period->updated_at = $now;
|
||||
$period->save();
|
||||
$instance->current_period_id = $period->id;
|
||||
$instance->traffic_quota_bytes = max(0, (int) $period->traffic_quota_bytes);
|
||||
$instance->traffic_download_bytes = (int) $period->download_used_bytes;
|
||||
$instance->traffic_upload_bytes = (int) $period->upload_used_bytes;
|
||||
if (!in_array((string) $instance->service_status, ['active', 'exempt'], true)) {
|
||||
$instance->service_status = 'resume_pending';
|
||||
}
|
||||
if ((string) $instance->network_status !== 'active') {
|
||||
$instance->network_status = 'restore_pending';
|
||||
$instance->network_suspended_at = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($period !== null) {
|
||||
$usageKnown = $this->updateUsage($instance, $period, $now);
|
||||
$used = (int) $period->download_used_bytes + (int) $period->upload_used_bytes;
|
||||
$quota = max(0, (int) $period->traffic_quota_bytes);
|
||||
if ($usageKnown && $quota > 0 && $used >= $quota) {
|
||||
if ((string) $period->status !== 'exhausted') {
|
||||
$period->status = 'exhausted';
|
||||
$period->updated_at = $now;
|
||||
$period->save();
|
||||
}
|
||||
if ((string) $instance->network_status === 'block_failed'
|
||||
&& $this->policyRetryReady($instance, 'network_suspend', $now)) {
|
||||
$instance->network_status = 'blocking';
|
||||
} elseif (!in_array((string) $instance->network_status,
|
||||
['blocking', 'blocked_traffic', 'block_failed'], true)) {
|
||||
$instance->network_status = 'blocking';
|
||||
}
|
||||
} elseif ($usageKnown) {
|
||||
if ((string) $instance->network_status === 'restore_failed'
|
||||
&& $this->policyRetryReady($instance, 'network_resume', $now)) {
|
||||
$instance->network_status = 'restore_pending';
|
||||
$instance->network_suspended_at = null;
|
||||
} elseif (!in_array((string) $instance->network_status,
|
||||
['active', 'restore_failed'], true)) {
|
||||
$instance->network_status = 'restore_pending';
|
||||
$instance->network_suspended_at = null;
|
||||
}
|
||||
}
|
||||
if ((string) $instance->service_status === 'resume_failed'
|
||||
&& $this->policyRetryReady($instance, 'service_resume', $now)) {
|
||||
$instance->service_status = 'resume_pending';
|
||||
}
|
||||
} elseif ($instance->expires_at !== null && (int) $instance->expires_at <= $now
|
||||
&& (string) $instance->service_status !== 'suspended_expired') {
|
||||
if ((string) $instance->service_status === 'suspend_failed') {
|
||||
if ($this->policyRetryReady($instance, 'service_suspend', $now)) {
|
||||
$instance->service_status = 'suspending_expired';
|
||||
}
|
||||
} elseif ((string) $instance->service_status !== 'suspending_expired') {
|
||||
$instance->service_status = 'suspending_expired';
|
||||
}
|
||||
}
|
||||
$instance->updated_at = $now;
|
||||
$instance->save();
|
||||
|
||||
if ($this->hasConflictingJob($instance)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$service = (string) $instance->service_status;
|
||||
$network = (string) $instance->network_status;
|
||||
if ($service === 'suspending_expired') {
|
||||
return $this->enqueue($instance, 'service_suspend', 'service-suspend', 'expired');
|
||||
}
|
||||
if (in_array($service, ['resume_pending', 'resuming'], true)) {
|
||||
$instance->service_status = 'resuming';
|
||||
$instance->save();
|
||||
return $this->enqueue($instance, 'service_resume', 'service-resume', null,
|
||||
['start_if_suspended' => $instance->suspended_at !== null]);
|
||||
}
|
||||
if ($network === 'blocking') {
|
||||
return $this->enqueue($instance, 'network_suspend', 'network-suspend', 'traffic');
|
||||
}
|
||||
if (in_array($network, ['restore_pending', 'restoring'], true)) {
|
||||
$instance->network_status = 'restoring';
|
||||
$instance->save();
|
||||
return $this->enqueue($instance, 'network_resume', 'network-resume');
|
||||
}
|
||||
return false;
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private function hasConflictingJob(CloudInstance $instance): bool
|
||||
{
|
||||
return CloudJob::where('instance_id', $instance->id)
|
||||
->where(function ($query) {
|
||||
$query->whereIn('status', ['queued', 'running'])
|
||||
->orWhere(function ($uncertain) {
|
||||
// Reset/shutdown/delete style mutations cannot be
|
||||
// replayed after a lost response and may legitimately
|
||||
// remain uncertain forever. They must not permanently
|
||||
// disable expiry and traffic policy. Reinstall,
|
||||
// rescue and target-state policy operations can still
|
||||
// converge, so their uncertainty remains a conflict.
|
||||
$uncertain->where('status', 'uncertain')
|
||||
->whereNotIn('kind', ['action', 'delete']);
|
||||
});
|
||||
})->exists();
|
||||
}
|
||||
|
||||
private function policyRetryReady(CloudInstance $instance, string $kind, int $now): bool
|
||||
{
|
||||
$failed = CloudJob::where('instance_id', $instance->id)
|
||||
->where('kind', $kind)->where('status', 'failed')
|
||||
->orderByDesc('updated_at')->orderByDesc('id')->first();
|
||||
if ($failed === null) {
|
||||
return true;
|
||||
}
|
||||
$recentFailures = CloudJob::where('instance_id', $instance->id)
|
||||
->where('kind', $kind)->where('status', 'failed')
|
||||
->where('updated_at', '>=', $now - 3600)->count();
|
||||
// Retry temporary host/SSH failures without creating a 15-second job
|
||||
// storm. Enforcement always converges again after an administrator
|
||||
// repairs the host; the delay is capped at five minutes.
|
||||
$exponent = min(5, max(0, $recentFailures - 1));
|
||||
$delay = min(300, 15 * (1 << $exponent));
|
||||
return (int) $failed->updated_at + $delay <= $now;
|
||||
}
|
||||
|
||||
private function updateUsage(CloudInstance $instance, CloudServicePeriod $period, int $now): bool
|
||||
{
|
||||
if ($period->download_base_bytes === null || $period->upload_base_bytes === null) {
|
||||
// At a period boundary, an old cached total would charge bytes
|
||||
// from the previous period to the new one. Wait for the first
|
||||
// successful sample at/after the boundary and fail open until it
|
||||
// establishes both baselines.
|
||||
if ((int) $instance->traffic_synced_at < (int) $period->starts_at) {
|
||||
$period->download_base_bytes = null;
|
||||
$period->upload_base_bytes = null;
|
||||
$period->download_used_bytes = 0;
|
||||
$period->upload_used_bytes = 0;
|
||||
$period->updated_at = $now;
|
||||
$period->save();
|
||||
$instance->traffic_quota_bytes = max(0, (int) $period->traffic_quota_bytes);
|
||||
$instance->traffic_download_bytes = 0;
|
||||
$instance->traffic_upload_bytes = 0;
|
||||
return false;
|
||||
}
|
||||
$period->download_base_bytes = max(0, (int) $instance->lifetime_download_bytes);
|
||||
$period->upload_base_bytes = max(0, (int) $instance->lifetime_upload_bytes);
|
||||
}
|
||||
$download = max(0, (int) $instance->lifetime_download_bytes - (int) $period->download_base_bytes);
|
||||
$upload = max(0, (int) $instance->lifetime_upload_bytes - (int) $period->upload_base_bytes);
|
||||
$period->download_used_bytes = $download;
|
||||
$period->upload_used_bytes = $upload;
|
||||
$period->updated_at = $now;
|
||||
$period->save();
|
||||
$instance->traffic_quota_bytes = max(0, (int) $period->traffic_quota_bytes);
|
||||
$instance->traffic_download_bytes = $download;
|
||||
$instance->traffic_upload_bytes = $upload;
|
||||
return true;
|
||||
}
|
||||
|
||||
private function enqueue(CloudInstance $instance, string $kind, string $suffix,
|
||||
?string $reason = null, array $body = []): bool
|
||||
{
|
||||
$job = new CloudJob();
|
||||
$job->operation_id = bin2hex(random_bytes(16));
|
||||
$job->instance_id = $instance->id;
|
||||
$job->user_id = $instance->user_id;
|
||||
$job->host_id = $instance->host_id;
|
||||
$job->kind = $kind;
|
||||
$job->status = 'queued';
|
||||
$job->payload_cipher = CloudSecrets::encrypt([
|
||||
'method' => 'POST',
|
||||
'resource' => 'vms/' . rawurlencode($instance->uuid) . '/' . $suffix,
|
||||
'body' => $body, 'owner_id' => (int) $instance->user_id,
|
||||
'system_policy' => true, 'suspend_reason' => $reason,
|
||||
]);
|
||||
$job->available_at = $job->created_at = $job->updated_at = time();
|
||||
$job->save();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,174 @@
|
||||
<?php
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudJob;
|
||||
use App\Models\CloudRenewal;
|
||||
use App\Models\CloudServicePeriod;
|
||||
use App\Models\User;
|
||||
|
||||
final class CloudRenewalService
|
||||
{
|
||||
public static function renew(CloudInstance $instance, array $input, array $actor): CloudRenewal
|
||||
{
|
||||
CloudInput::only($input, ['idempotency_key']);
|
||||
$idempotency = $input['idempotency_key'] ?? '';
|
||||
if (!is_string($idempotency) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
|
||||
throw new CloudError('请提供 16 至 128 字符的续费幂等标识');
|
||||
}
|
||||
if ((int) $instance->user_id !== (int) $actor['user_id']) {
|
||||
throw new CloudError('只能为自己持有的实例续费', 403);
|
||||
}
|
||||
$requestHash = hash_hmac('sha256', 'renew:' . (int) $instance->id,
|
||||
CloudSecrets::key('payload_key'));
|
||||
|
||||
return (new User())->getConnection()->transaction(function () use ($instance, $actor, $idempotency, $requestHash) {
|
||||
$user = User::where('id', (int) $actor['user_id'])->lockForUpdate()->first();
|
||||
if ($user === null || (int) $user->enable !== 1) {
|
||||
throw new CloudError('账户不可用', 403);
|
||||
}
|
||||
if ((int) $user->restrict_balance_purchase === 1) {
|
||||
throw new CloudError('账户套餐购买服务已被管理员停用', 403);
|
||||
}
|
||||
$existing = CloudRenewal::where('user_id', $user->id)
|
||||
->where('idempotency_key', $idempotency)->first();
|
||||
if ($existing !== null) {
|
||||
if (!hash_equals((string) $existing->request_hash, $requestHash)) {
|
||||
throw new CloudError('同一请求标识不能用于不同实例', 409);
|
||||
}
|
||||
return $existing;
|
||||
}
|
||||
$locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first();
|
||||
if ($locked === null || $locked->status === 'deleted'
|
||||
|| (int) $locked->user_id !== (int) $user->id) {
|
||||
throw new CloudError('实例不存在或无权续费', 404);
|
||||
}
|
||||
if (CloudJob::where('instance_id', $locked->id)->where('kind', 'delete')
|
||||
->whereIn('status', ['queued', 'running', 'uncertain'])->exists()) {
|
||||
throw new CloudError('实例正在删除或等待核对,不能续费', 409);
|
||||
}
|
||||
$days = (int) $locked->renewal_days;
|
||||
$price = $locked->renewal_price === null ? -1 : CloudMoney::cents((string) $locked->renewal_price);
|
||||
if ($days < 1 || $price < 0 || $locked->expires_at === null) {
|
||||
throw new CloudError('此实例没有可续费的套餐快照', 409);
|
||||
}
|
||||
$balance = CloudMoney::cents((string) $user->money);
|
||||
if ($balance < $price) {
|
||||
throw new CloudError('账户余额不足', 409);
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$currentPeriod = $locked->current_period_id === null ? null
|
||||
: CloudServicePeriod::where('id', $locked->current_period_id)
|
||||
->where('instance_id', $locked->id)->lockForUpdate()->first();
|
||||
if ($currentPeriod !== null
|
||||
&& in_array((string) $currentPeriod->status, ['active', 'exhausted'], true)
|
||||
&& (int) $currentPeriod->ends_at <= $now) {
|
||||
if ($currentPeriod->download_base_bytes !== null
|
||||
&& $currentPeriod->upload_base_bytes !== null) {
|
||||
$currentPeriod->download_used_bytes = max(0,
|
||||
(int) $locked->lifetime_download_bytes - (int) $currentPeriod->download_base_bytes);
|
||||
$currentPeriod->upload_used_bytes = max(0,
|
||||
(int) $locked->lifetime_upload_bytes - (int) $currentPeriod->upload_base_bytes);
|
||||
}
|
||||
$currentPeriod->status = 'finished';
|
||||
$currentPeriod->updated_at = $now;
|
||||
$currentPeriod->save();
|
||||
$locked->current_period_id = null;
|
||||
}
|
||||
CloudServicePeriod::where('instance_id', $locked->id)
|
||||
->where('status', 'scheduled')->where('ends_at', '<=', $now)
|
||||
->update(['status' => 'finished', 'updated_at' => $now]);
|
||||
$maximumScheduled = max(1, min(120,
|
||||
(int) \App\Services\Config::get('cloud_max_renewal_periods_ahead', 24)));
|
||||
if (CloudServicePeriod::where('instance_id', $locked->id)
|
||||
->where('status', 'scheduled')->count() >= $maximumScheduled) {
|
||||
throw new CloudError('提前续费周期已达到上限,请在后续账期开始后再续费', 409);
|
||||
}
|
||||
$lastPeriod = CloudServicePeriod::where('instance_id', $locked->id)
|
||||
->orderByDesc('ends_at')->orderByDesc('id')->lockForUpdate()->first();
|
||||
if ($lastPeriod === null) {
|
||||
throw new CloudError('实例缺少有效的服务周期,无法续费', 409);
|
||||
}
|
||||
$previousExpiry = max(0, (int) $locked->expires_at, (int) $lastPeriod->ends_at);
|
||||
$startsAt = max($now, $previousExpiry);
|
||||
$newExpiry = $startsAt + $days * 86400;
|
||||
if ($newExpiry < $startsAt) {
|
||||
throw new CloudError('续费时间超出系统范围', 409);
|
||||
}
|
||||
$addedTraffic = max(0, (int) $locked->renewal_traffic_bytes);
|
||||
|
||||
$renewal = new CloudRenewal();
|
||||
$renewal->instance_id = $locked->id;
|
||||
$renewal->user_id = $user->id;
|
||||
$renewal->plan_id = $locked->plan_id;
|
||||
$renewal->idempotency_key = $idempotency;
|
||||
$renewal->request_hash = $requestHash;
|
||||
$renewal->amount = CloudMoney::decimal($price);
|
||||
$renewal->validity_days = $days;
|
||||
$renewal->traffic_bytes_added = $addedTraffic;
|
||||
$renewal->previous_expires_at = $previousExpiry;
|
||||
$renewal->new_expires_at = $newExpiry;
|
||||
$renewal->created_at = $now;
|
||||
$renewal->save();
|
||||
|
||||
$period = new CloudServicePeriod();
|
||||
$period->instance_id = $locked->id;
|
||||
$period->user_id = $user->id;
|
||||
$period->plan_id = $locked->plan_id;
|
||||
$period->renewal_id = $renewal->id;
|
||||
$period->starts_at = $startsAt;
|
||||
$period->ends_at = $newExpiry;
|
||||
$period->traffic_quota_bytes = $addedTraffic;
|
||||
$period->status = $startsAt <= $now ? 'active' : 'scheduled';
|
||||
$period->activated_at = $startsAt <= $now ? $now : null;
|
||||
if ($period->status === 'active') {
|
||||
$baselineReady = (int) $locked->traffic_synced_at >= $startsAt;
|
||||
$period->download_base_bytes = $baselineReady
|
||||
? max(0, (int) $locked->lifetime_download_bytes) : null;
|
||||
$period->upload_base_bytes = $baselineReady
|
||||
? max(0, (int) $locked->lifetime_upload_bytes) : null;
|
||||
}
|
||||
$period->created_at = $period->updated_at = $now;
|
||||
$period->save();
|
||||
$renewal->period_id = $period->id;
|
||||
$renewal->save();
|
||||
|
||||
$user->money = CloudMoney::decimal($balance - $price);
|
||||
$user->save();
|
||||
$locked->expires_at = $newExpiry;
|
||||
if ($period->status === 'active') {
|
||||
$locked->current_period_id = $period->id;
|
||||
$locked->traffic_quota_bytes = $addedTraffic;
|
||||
$locked->traffic_download_bytes = 0;
|
||||
$locked->traffic_upload_bytes = 0;
|
||||
if (!in_array((string) $locked->service_status, ['active', 'exempt'], true)) {
|
||||
$locked->service_status = 'resume_pending';
|
||||
}
|
||||
if ((string) $locked->network_status !== 'active') {
|
||||
$locked->network_status = 'restore_pending';
|
||||
$locked->network_suspended_at = null;
|
||||
}
|
||||
}
|
||||
$locked->updated_at = $now;
|
||||
$locked->save();
|
||||
|
||||
return $renewal;
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public static function display(CloudRenewal $renewal): array
|
||||
{
|
||||
return [
|
||||
'id' => (string) $renewal->id,
|
||||
'instance_id' => (string) $renewal->instance_id,
|
||||
'amount' => (string) $renewal->amount,
|
||||
'validity_days' => (int) $renewal->validity_days,
|
||||
'traffic_bytes_added' => (int) $renewal->traffic_bytes_added,
|
||||
'period_id' => $renewal->period_id === null ? null : (string) $renewal->period_id,
|
||||
'previous_expires_at' => (int) $renewal->previous_expires_at,
|
||||
'new_expires_at' => (int) $renewal->new_expires_at,
|
||||
'created_at' => (int) $renewal->created_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,152 @@
|
||||
<?php
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\User;
|
||||
|
||||
final class CloudTrafficService
|
||||
{
|
||||
public static function sync(int $limit = 500): int
|
||||
{
|
||||
$batchSize = max(1, min(2000, $limit));
|
||||
$updated = 0;
|
||||
CloudInstance::where('status', '<>', 'deleted')
|
||||
->where('service_status', '<>', 'exempt')
|
||||
->select(['id', 'host_id', 'user_id', 'uuid'])
|
||||
->chunkById($batchSize, function ($instances) use (&$updated) {
|
||||
$updated += self::syncBatch($instances);
|
||||
});
|
||||
return $updated;
|
||||
}
|
||||
|
||||
private static function syncBatch($instances): int
|
||||
{
|
||||
if ($instances->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
$groups = [];
|
||||
foreach ($instances as $instance) {
|
||||
$groups[(int) $instance->host_id][] = $instance;
|
||||
}
|
||||
$updated = 0;
|
||||
$log = User::getConnectionResolver()->connection('log');
|
||||
foreach ($groups as $hostId => $owned) {
|
||||
$scope = hash('sha256', 'virt-cloud/host/' . $hostId);
|
||||
$uuids = array_map(static fn ($instance) => (string) $instance->uuid, $owned);
|
||||
$rows = $log->table('engine_vm_traffic_totals')
|
||||
->where('host_scope', $scope)->whereIn('vm_uuid', $uuids)->get();
|
||||
$byUuid = [];
|
||||
foreach ($rows as $row) {
|
||||
$byUuid[(string) $row->vm_uuid] = $row;
|
||||
}
|
||||
foreach ($owned as $instance) {
|
||||
$row = $byUuid[(string) $instance->uuid] ?? null;
|
||||
// An absent or changed owner is unknown usage, not grounds to
|
||||
// stop another tenant's VM. The next successful sample repairs it.
|
||||
if ($row === null || $row->user_id === null
|
||||
|| (int) $row->user_id !== (int) $instance->user_id
|
||||
|| ($row->host_id !== null && (string) $row->host_id !== (string) $hostId)) {
|
||||
continue;
|
||||
}
|
||||
$download = max(0, (int) $row->download_rx_bytes);
|
||||
$upload = max(0, (int) $row->upload_tx_bytes);
|
||||
$observed = max(0, (int) ($row->last_observed_at ?? $row->updated_at ?? 0));
|
||||
$changed = CloudInstance::where('id', $instance->id)
|
||||
->where('host_id', $hostId)->where('user_id', $instance->user_id)
|
||||
->where('uuid', $instance->uuid)
|
||||
->where('traffic_synced_at', '<=', $observed)
|
||||
// Engine totals are durable monotonic counters. A rebuilt,
|
||||
// restored or corrupt log database must never roll paid
|
||||
// usage backwards and accidentally restore a blocked NIC.
|
||||
->where('lifetime_download_bytes', '<=', $download)
|
||||
->where('lifetime_upload_bytes', '<=', $upload)
|
||||
->update(['lifetime_download_bytes' => $download,
|
||||
'lifetime_upload_bytes' => $upload, 'traffic_synced_at' => $observed]);
|
||||
$updated += $changed;
|
||||
}
|
||||
}
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstruct a conservative period boundary from durable cumulative
|
||||
* checkpoints. Chart samples are intentionally retained for only 30
|
||||
* days, while the engine keeps the first cumulative total in every hour
|
||||
* indefinitely. Using the first observation *after* the boundary excludes
|
||||
* the straddling interval and bounds uncharged traffic to less than one
|
||||
* checkpoint hour even after a long lifecycle-daemon outage.
|
||||
*/
|
||||
public static function periodBaseline(CloudInstance $instance,
|
||||
int $startsAt): ?array
|
||||
{
|
||||
if ((int) $instance->traffic_synced_at < $startsAt) {
|
||||
return null;
|
||||
}
|
||||
$log = User::getConnectionResolver()->connection('log');
|
||||
$scope = hash('sha256', 'virt-cloud/host/' . (int) $instance->host_id);
|
||||
if ($log->getSchemaBuilder()->hasTable('engine_vm_traffic_checkpoints')) {
|
||||
$checkpoint = $log->table('engine_vm_traffic_checkpoints')
|
||||
->where('host_scope', $scope)->where('vm_uuid', (string) $instance->uuid)
|
||||
->where('user_id', (int) $instance->user_id)
|
||||
->where('host_id', (string) (int) $instance->host_id)
|
||||
->where('first_observed_at', '>', $startsAt)
|
||||
->where('first_observed_at', '<=', (int) $instance->traffic_synced_at)
|
||||
->orderBy('first_observed_at')->first([
|
||||
'download_rx_bytes', 'upload_tx_bytes',
|
||||
]);
|
||||
if ($checkpoint !== null) {
|
||||
$download = max(0, (int) $checkpoint->download_rx_bytes);
|
||||
$upload = max(0, (int) $checkpoint->upload_tx_bytes);
|
||||
if ($download <= (int) $instance->lifetime_download_bytes
|
||||
&& $upload <= (int) $instance->lifetime_upload_bytes) {
|
||||
return ['download' => $download, 'upload' => $upload];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade compatibility for a boundary still covered by the old
|
||||
// 30-day sample table. Refuse partial retained history: otherwise a
|
||||
// long outage would subtract only the tail and silently undercount.
|
||||
if (!$log->getSchemaBuilder()->hasTable('engine_vm_metric_samples')) {
|
||||
return null;
|
||||
}
|
||||
$rows = $log->table('engine_vm_metric_samples')
|
||||
->where('host_scope', $scope)->where('vm_uuid', (string) $instance->uuid)
|
||||
->where('user_id', (int) $instance->user_id)
|
||||
->where('host_id', (string) (int) $instance->host_id)
|
||||
->where('sampled_at', '>', $startsAt)
|
||||
->where('sampled_at', '<=', (int) $instance->traffic_synced_at)
|
||||
->orderBy('sampled_at')->get([
|
||||
'sampled_at', 'network_rx_bytes', 'network_tx_bytes',
|
||||
]);
|
||||
$download = 0;
|
||||
$upload = 0;
|
||||
$skippedBoundaryInterval = false;
|
||||
foreach ($rows as $row) {
|
||||
if ($row->network_rx_bytes === null || $row->network_tx_bytes === null) {
|
||||
continue;
|
||||
}
|
||||
if (!$skippedBoundaryInterval) {
|
||||
// The legacy sample fallback is safe only when retention still
|
||||
// covers the boundary. Normal collection is every 60 seconds;
|
||||
// five minutes tolerates jitter without accepting a truncated
|
||||
// 30-day tail as complete history.
|
||||
if ((int) $row->sampled_at > $startsAt + 300) {
|
||||
return null;
|
||||
}
|
||||
$skippedBoundaryInterval = true;
|
||||
continue;
|
||||
}
|
||||
$download += max(0, (int) $row->network_rx_bytes);
|
||||
$upload += max(0, (int) $row->network_tx_bytes);
|
||||
}
|
||||
$lifetimeDownload = max(0, (int) $instance->lifetime_download_bytes);
|
||||
$lifetimeUpload = max(0, (int) $instance->lifetime_upload_bytes);
|
||||
if ($download > $lifetimeDownload || $upload > $lifetimeUpload) {
|
||||
return null;
|
||||
}
|
||||
return ['download' => $lifetimeDownload - $download,
|
||||
'upload' => $lifetimeUpload - $upload];
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
# Edit the PHP binary and project path for your deployment before installing.
|
||||
# No account expiry, entitlement reset, proxy-node or automatic record-deletion jobs.
|
||||
# VM service-period and traffic enforcement is the virt-cloud-lifecycle systemd service, not cron.
|
||||
# No account expiry, proxy-node or automatic record-deletion jobs.
|
||||
0 6 * * * /usr/bin/php /home/www/virt-cloud/web/xcat backupJob >> /home/www/virt-cloud/web/storage/logs/database_backup.log 2>&1
|
||||
* * * * * /usr/bin/php /home/www/virt-cloud/web/xcat usdtScanJob 50 >> /home/www/virt-cloud/web/storage/logs/usdt_scan.log 2>&1
|
||||
*/5 * * * * /usr/bin/php /home/www/virt-cloud/web/xcat siteAnalyticsJob 2 >> /home/www/virt-cloud/web/storage/logs/site_analytics.log 2>&1
|
||||
|
||||
@ -1,2 +1,2 @@
|
||||
{assign var=admin_title value='开通订单'}{assign var=admin_active value='cloud_orders'}{include file='admin/static_header.tpl'}
|
||||
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="orders"><h4>余额开通订单</h4><p class="text-muted">首版采用余额一次性购买,不包含自动到期续费。失败或不确定的开通任务需核查实际宿主机状态,不要重复创建或扣款。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>订单</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 任务</th><th>时间 / 错误</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}
|
||||
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="orders"><h4>余额开通订单</h4><p class="text-muted">开通套餐按设置的账期生效,用户可在实例详情手动续费,不自动扣款。失败或不确定的开通任务需核查实际宿主机状态,不要重复创建或扣款。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>订单</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 任务</th><th>时间 / 错误</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}
|
||||
|
||||
@ -0,0 +1,781 @@
|
||||
<?php
|
||||
|
||||
// Billing lifecycle tests only. The in-memory keyring is not encryption and
|
||||
// is never loaded by production.
|
||||
namespace App\Services {
|
||||
final class Config
|
||||
{
|
||||
public static array $values = [];
|
||||
|
||||
public static function get($name, $default = null)
|
||||
{
|
||||
return self::$values[$name] ?? $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
final class CloudSecrets
|
||||
{
|
||||
private static array $memory = [];
|
||||
|
||||
public static function key(string $purpose): string
|
||||
{
|
||||
return str_repeat('k', 32);
|
||||
}
|
||||
|
||||
public static function encrypt(array $payload): string
|
||||
{
|
||||
$id = bin2hex(random_bytes(16));
|
||||
self::$memory[$id] = $payload;
|
||||
return 'test-only:' . $id;
|
||||
}
|
||||
|
||||
public static function decrypt(string $cipher): array
|
||||
{
|
||||
return self::$memory[substr($cipher, 10)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudJob;
|
||||
use App\Models\CloudRenewal;
|
||||
use App\Models\CloudServicePeriod;
|
||||
use App\Models\User;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudLifecycleService;
|
||||
use App\Services\Cloud\CloudRenewalService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'log');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('user', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('money');
|
||||
$table->integer('enable')->default(1);
|
||||
$table->integer('restrict_balance_purchase')->default(0);
|
||||
});
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('host_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('current_period_id')->nullable();
|
||||
$table->string('uuid');
|
||||
$table->string('name');
|
||||
$table->string('status');
|
||||
$table->string('service_status');
|
||||
$table->string('network_status');
|
||||
$table->integer('expires_at')->nullable();
|
||||
$table->string('renewal_price')->nullable();
|
||||
$table->integer('renewal_days')->default(0);
|
||||
$table->integer('renewal_traffic_bytes')->default(0);
|
||||
$table->integer('traffic_quota_bytes')->default(0);
|
||||
$table->integer('traffic_download_bytes')->default(0);
|
||||
$table->integer('traffic_upload_bytes')->default(0);
|
||||
$table->integer('lifetime_download_bytes')->default(0);
|
||||
$table->integer('lifetime_upload_bytes')->default(0);
|
||||
$table->integer('traffic_synced_at')->default(0);
|
||||
$table->integer('suspended_at')->nullable();
|
||||
$table->integer('network_suspended_at')->nullable();
|
||||
$table->text('spec_json');
|
||||
$table->text('credential_cipher')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
$table->unique(['host_id', 'uuid']);
|
||||
});
|
||||
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('renewal_id')->nullable();
|
||||
$table->integer('starts_at');
|
||||
$table->integer('ends_at');
|
||||
$table->integer('traffic_quota_bytes')->default(0);
|
||||
$table->integer('download_base_bytes')->nullable();
|
||||
$table->integer('upload_base_bytes')->nullable();
|
||||
$table->integer('download_used_bytes')->default(0);
|
||||
$table->integer('upload_used_bytes')->default(0);
|
||||
$table->string('status');
|
||||
$table->integer('activated_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
$table->unique('order_id');
|
||||
$table->unique('renewal_id');
|
||||
});
|
||||
$schema->create('cloud_renewals', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('period_id')->nullable();
|
||||
$table->string('idempotency_key');
|
||||
$table->string('request_hash');
|
||||
$table->string('amount');
|
||||
$table->integer('validity_days');
|
||||
$table->integer('traffic_bytes_added');
|
||||
$table->integer('previous_expires_at');
|
||||
$table->integer('new_expires_at');
|
||||
$table->integer('created_at');
|
||||
$table->unique(['user_id', 'idempotency_key']);
|
||||
});
|
||||
$schema->create('cloud_jobs', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('operation_id')->unique();
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('user_id');
|
||||
$table->integer('host_id');
|
||||
$table->string('kind');
|
||||
$table->string('status');
|
||||
$table->text('payload_cipher');
|
||||
$table->integer('attempts')->default(0);
|
||||
$table->integer('dispatched_at')->nullable();
|
||||
$table->string('lease_token')->nullable();
|
||||
$table->integer('lease_until')->default(0);
|
||||
$table->integer('available_at');
|
||||
$table->string('error_code')->nullable();
|
||||
$table->text('result_json')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
|
||||
$logSchema = $capsule->schema('log');
|
||||
$logSchema->create('engine_vm_traffic_totals', static function (Blueprint $table): void {
|
||||
$table->string('host_scope');
|
||||
$table->string('vm_uuid');
|
||||
$table->string('host_id')->nullable();
|
||||
$table->integer('user_id')->nullable();
|
||||
$table->integer('last_observed_at')->nullable();
|
||||
$table->integer('download_rx_bytes')->default(0);
|
||||
$table->integer('upload_tx_bytes')->default(0);
|
||||
$table->integer('updated_at')->default(0);
|
||||
$table->primary(['host_scope', 'vm_uuid']);
|
||||
});
|
||||
$logSchema->create('engine_vm_traffic_checkpoints', static function (Blueprint $table): void {
|
||||
$table->string('host_scope');
|
||||
$table->string('vm_uuid');
|
||||
$table->integer('checkpoint_hour');
|
||||
$table->string('host_id')->nullable();
|
||||
$table->integer('user_id')->nullable();
|
||||
$table->integer('first_observed_at');
|
||||
$table->integer('download_rx_bytes');
|
||||
$table->integer('upload_tx_bytes');
|
||||
$table->primary(['host_scope', 'vm_uuid', 'checkpoint_hour']);
|
||||
});
|
||||
|
||||
$user = new User();
|
||||
$user->id = 1;
|
||||
$user->money = '100.00';
|
||||
$user->enable = 1;
|
||||
$user->restrict_balance_purchase = 0;
|
||||
$user->save();
|
||||
|
||||
$now = time();
|
||||
$instance = new CloudInstance();
|
||||
$instance->host_id = 1;
|
||||
$instance->user_id = 1;
|
||||
$instance->plan_id = 7;
|
||||
$instance->uuid = '11111111-1111-4111-8111-111111111111';
|
||||
$instance->name = 'billed-vm';
|
||||
$instance->status = 'active';
|
||||
$instance->service_status = 'active';
|
||||
$instance->network_status = 'active';
|
||||
$instance->expires_at = $now + 3600;
|
||||
$instance->renewal_price = '10.00';
|
||||
$instance->renewal_days = 30;
|
||||
$instance->renewal_traffic_bytes = 1000;
|
||||
$instance->traffic_quota_bytes = 1000;
|
||||
$instance->spec_json = '{}';
|
||||
$instance->created_at = $instance->updated_at = $now - 100;
|
||||
$instance->save();
|
||||
|
||||
$period = new CloudServicePeriod();
|
||||
$period->instance_id = $instance->id;
|
||||
$period->user_id = 1;
|
||||
$period->plan_id = 7;
|
||||
$period->starts_at = $now - 100;
|
||||
$period->ends_at = $now + 3600;
|
||||
$period->traffic_quota_bytes = 1000;
|
||||
$period->download_base_bytes = 0;
|
||||
$period->upload_base_bytes = 0;
|
||||
$period->download_used_bytes = 0;
|
||||
$period->upload_used_bytes = 0;
|
||||
$period->status = 'active';
|
||||
$period->activated_at = $now - 100;
|
||||
$period->created_at = $period->updated_at = $now - 100;
|
||||
$period->save();
|
||||
$instance->current_period_id = $period->id;
|
||||
$instance->save();
|
||||
|
||||
$scope = hash('sha256', 'virt-cloud/host/1');
|
||||
$capsule->connection('log')->table('engine_vm_traffic_totals')->insert([
|
||||
'host_scope' => $scope,
|
||||
'vm_uuid' => $instance->uuid,
|
||||
'host_id' => '1',
|
||||
'user_id' => 1,
|
||||
'last_observed_at' => $now,
|
||||
'download_rx_bytes' => 700,
|
||||
'upload_tx_bytes' => 400,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
$lifecycle = new CloudLifecycleService();
|
||||
$lifecycle->tick(100);
|
||||
$instance->refresh();
|
||||
$period->refresh();
|
||||
$networkSuspend = CloudJob::where('instance_id', $instance->id)
|
||||
->where('kind', 'network_suspend')->first();
|
||||
$assert($period->status === 'exhausted', 'Combined upload/download did not exhaust the period quota.');
|
||||
$assert((int) $period->download_used_bytes === 700 && (int) $period->upload_used_bytes === 400,
|
||||
'Current-period directional traffic was not synchronized exactly.');
|
||||
$assert($instance->service_status === 'active' && $instance->network_status === 'blocking',
|
||||
'Traffic exhaustion stopped service instead of requesting network-only suspension.');
|
||||
$assert($networkSuspend !== null
|
||||
&& !CloudJob::where('instance_id', $instance->id)->where('kind', 'service_suspend')->exists(),
|
||||
'Traffic exhaustion queued the wrong enforcement operation.');
|
||||
|
||||
$actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
|
||||
'can_manage' => false, 'session_id' => ''];
|
||||
$periodEndsAt = (int) $period->ends_at;
|
||||
$renewal = CloudRenewalService::renew($instance, [
|
||||
'idempotency_key' => 'renew-current-period-0001',
|
||||
], $actor);
|
||||
$sameRenewal = CloudRenewalService::renew($instance->fresh(), [
|
||||
'idempotency_key' => 'renew-current-period-0001',
|
||||
], $actor);
|
||||
$scheduled = CloudServicePeriod::find($renewal->period_id);
|
||||
$instance->refresh();
|
||||
$assert($renewal->id === $sameRenewal->id && CloudRenewal::count() === 1
|
||||
&& User::find(1)->money === '90.00', 'Renewal idempotency did not debit exactly once.');
|
||||
$assert($scheduled->status === 'scheduled' && (int) $scheduled->starts_at === $periodEndsAt,
|
||||
'Early renewal did not create a future independent period.');
|
||||
$assert((int) $instance->current_period_id === (int) $period->id
|
||||
&& (int) $instance->traffic_download_bytes === 700
|
||||
&& (int) $instance->traffic_upload_bytes === 400
|
||||
&& $instance->network_status === 'blocking',
|
||||
'Early renewal refreshed current traffic or restored networking before the paid period began.');
|
||||
|
||||
// Model a successfully applied link-down operation, then move the clock
|
||||
// boundary into the past. The next period must reset only its own usage
|
||||
// and request link restoration without starting another VM service.
|
||||
$networkSuspend->status = 'succeeded';
|
||||
$networkSuspend->save();
|
||||
$instance->network_status = 'blocked_traffic';
|
||||
$instance->save();
|
||||
$period->ends_at = $now - 1;
|
||||
$period->save();
|
||||
$scheduled->starts_at = $now - 1;
|
||||
$scheduled->save();
|
||||
$lifecycle->tick(100);
|
||||
$instance->refresh();
|
||||
$period->refresh();
|
||||
$scheduled->refresh();
|
||||
$networkResume = CloudJob::where('instance_id', $instance->id)
|
||||
->where('kind', 'network_resume')->first();
|
||||
$assert($period->status === 'finished' && $scheduled->status === 'active'
|
||||
&& (int) $instance->current_period_id === (int) $scheduled->id,
|
||||
'The next prepaid period was not activated at the period boundary.');
|
||||
$assert((int) $scheduled->download_base_bytes === 700
|
||||
&& (int) $scheduled->upload_base_bytes === 400
|
||||
&& (int) $scheduled->download_used_bytes === 0
|
||||
&& (int) $scheduled->upload_used_bytes === 0,
|
||||
'New-period traffic did not start from an independent baseline.');
|
||||
$assert($instance->service_status === 'active' && $instance->network_status === 'restoring'
|
||||
&& $networkResume !== null,
|
||||
'The new period did not request automatic network restoration.');
|
||||
|
||||
$networkResume->status = 'succeeded';
|
||||
$networkResume->save();
|
||||
$instance->network_status = 'active';
|
||||
$instance->save();
|
||||
$capsule->connection('log')->table('engine_vm_traffic_totals')
|
||||
->where('host_scope', $scope)->where('vm_uuid', $instance->uuid)->update([
|
||||
'last_observed_at' => $now + 1,
|
||||
'download_rx_bytes' => 800,
|
||||
'upload_tx_bytes' => 450,
|
||||
'updated_at' => $now + 1,
|
||||
]);
|
||||
$lifecycle->tick(100);
|
||||
$scheduled->refresh();
|
||||
$assert((int) $scheduled->download_used_bytes === 100
|
||||
&& (int) $scheduled->upload_used_bytes === 50,
|
||||
'New-period usage included traffic paid for in the previous period.');
|
||||
|
||||
$scheduled->ends_at = $now - 1;
|
||||
$scheduled->save();
|
||||
$instance->expires_at = $now - 1;
|
||||
$instance->save();
|
||||
$lifecycle->tick(100);
|
||||
$instance->refresh();
|
||||
$serviceSuspend = CloudJob::where('instance_id', $instance->id)
|
||||
->where('kind', 'service_suspend')->first();
|
||||
$assert($instance->service_status === 'suspending_expired' && $serviceSuspend !== null,
|
||||
'Final paid expiry did not request full service suspension.');
|
||||
|
||||
// A missing sample at the billing boundary must fail open. Otherwise the
|
||||
// first counter catch-up after an outage would charge previous-period
|
||||
// bytes to the new period and could immediately disconnect the tenant.
|
||||
$stale = new CloudInstance();
|
||||
$stale->host_id = 1;
|
||||
$stale->user_id = 1;
|
||||
$stale->plan_id = 7;
|
||||
$stale->uuid = '33333333-3333-4333-8333-333333333333';
|
||||
$stale->name = 'stale-boundary-vm';
|
||||
$stale->status = 'active';
|
||||
$stale->service_status = 'active';
|
||||
$stale->network_status = 'blocked_traffic';
|
||||
$stale->expires_at = $now + 3600;
|
||||
$stale->renewal_price = '10.00';
|
||||
$stale->renewal_days = 30;
|
||||
$stale->renewal_traffic_bytes = 100;
|
||||
$stale->traffic_quota_bytes = 100;
|
||||
$stale->lifetime_download_bytes = 5000;
|
||||
$stale->lifetime_upload_bytes = 2000;
|
||||
$stale->traffic_synced_at = $now - 300;
|
||||
$stale->spec_json = '{}';
|
||||
$stale->created_at = $stale->updated_at = $now - 7200;
|
||||
$stale->save();
|
||||
|
||||
$staleOld = new CloudServicePeriod();
|
||||
$staleOld->instance_id = $stale->id;
|
||||
$staleOld->user_id = 1;
|
||||
$staleOld->plan_id = 7;
|
||||
$staleOld->starts_at = $now - 7200;
|
||||
$staleOld->ends_at = $now - 1;
|
||||
$staleOld->traffic_quota_bytes = 100;
|
||||
$staleOld->download_base_bytes = 0;
|
||||
$staleOld->upload_base_bytes = 0;
|
||||
$staleOld->download_used_bytes = 5000;
|
||||
$staleOld->upload_used_bytes = 2000;
|
||||
$staleOld->status = 'exhausted';
|
||||
$staleOld->activated_at = $now - 7200;
|
||||
$staleOld->created_at = $staleOld->updated_at = $now - 7200;
|
||||
$staleOld->save();
|
||||
|
||||
$staleNew = new CloudServicePeriod();
|
||||
$staleNew->instance_id = $stale->id;
|
||||
$staleNew->user_id = 1;
|
||||
$staleNew->plan_id = 7;
|
||||
$staleNew->starts_at = $now - 1;
|
||||
$staleNew->ends_at = $now + 3600;
|
||||
$staleNew->traffic_quota_bytes = 100;
|
||||
$staleNew->download_used_bytes = 0;
|
||||
$staleNew->upload_used_bytes = 0;
|
||||
$staleNew->status = 'scheduled';
|
||||
$staleNew->created_at = $staleNew->updated_at = $now - 60;
|
||||
$staleNew->save();
|
||||
$stale->current_period_id = $staleOld->id;
|
||||
$stale->save();
|
||||
|
||||
$lifecycle->tick(100);
|
||||
$stale->refresh();
|
||||
$staleNew->refresh();
|
||||
$staleResume = CloudJob::where('instance_id', $stale->id)
|
||||
->where('kind', 'network_resume')->first();
|
||||
$assert($staleNew->status === 'active'
|
||||
&& $staleNew->download_base_bytes === null
|
||||
&& $staleNew->upload_base_bytes === null
|
||||
&& (int) $staleNew->download_used_bytes === 0
|
||||
&& (int) $staleNew->upload_used_bytes === 0,
|
||||
'A stale pre-boundary sample was used as the new period baseline.');
|
||||
$assert($stale->network_status === 'restoring' && $staleResume !== null
|
||||
&& !CloudJob::where('instance_id', $stale->id)->where('kind', 'network_suspend')->exists(),
|
||||
'Unknown boundary traffic failed closed or prevented the paid-period network restore.');
|
||||
|
||||
$staleResume->status = 'succeeded';
|
||||
$staleResume->save();
|
||||
$stale->network_status = 'active';
|
||||
$stale->save();
|
||||
$capsule->connection('log')->table('engine_vm_traffic_totals')->insert([
|
||||
'host_scope' => $scope,
|
||||
'vm_uuid' => $stale->uuid,
|
||||
'host_id' => '1',
|
||||
'user_id' => 1,
|
||||
'last_observed_at' => $now + 2,
|
||||
'download_rx_bytes' => 8000,
|
||||
'upload_tx_bytes' => 4000,
|
||||
'updated_at' => $now + 2,
|
||||
]);
|
||||
$lifecycle->tick(100);
|
||||
$staleNew->refresh();
|
||||
$assert((int) $staleNew->download_base_bytes === 8000
|
||||
&& (int) $staleNew->upload_base_bytes === 4000
|
||||
&& (int) $staleNew->download_used_bytes === 0
|
||||
&& (int) $staleNew->upload_used_bytes === 0,
|
||||
'The first post-boundary observation did not establish a fail-open baseline.');
|
||||
|
||||
$capsule->connection('log')->table('engine_vm_traffic_totals')
|
||||
->where('host_scope', $scope)->where('vm_uuid', $stale->uuid)->update([
|
||||
'last_observed_at' => $now + 3,
|
||||
'download_rx_bytes' => 8070,
|
||||
'upload_tx_bytes' => 4040,
|
||||
'updated_at' => $now + 3,
|
||||
]);
|
||||
$lifecycle->tick(100);
|
||||
$stale->refresh();
|
||||
$staleNew->refresh();
|
||||
$assert((int) $staleNew->download_used_bytes === 70
|
||||
&& (int) $staleNew->upload_used_bytes === 40
|
||||
&& $stale->network_status === 'blocking'
|
||||
&& CloudJob::where('instance_id', $stale->id)->where('kind', 'network_suspend')->exists(),
|
||||
'Known post-baseline usage did not enforce the combined period quota.');
|
||||
|
||||
// A renewal submitted just after an expired period, before the lifecycle
|
||||
// daemon has closed it, must not leave two periods marked active.
|
||||
$late = new CloudInstance();
|
||||
$late->host_id = 1;
|
||||
$late->user_id = 1;
|
||||
$late->plan_id = 7;
|
||||
$late->uuid = '22222222-2222-4222-8222-222222222222';
|
||||
$late->name = 'late-renewal-vm';
|
||||
$late->status = 'active';
|
||||
$late->service_status = 'active';
|
||||
$late->network_status = 'blocked_traffic';
|
||||
$late->expires_at = $now - 60;
|
||||
$late->renewal_price = '10.00';
|
||||
$late->renewal_days = 30;
|
||||
$late->renewal_traffic_bytes = 1000;
|
||||
$late->traffic_quota_bytes = 1000;
|
||||
$late->lifetime_download_bytes = 2000;
|
||||
$late->lifetime_upload_bytes = 1000;
|
||||
$late->spec_json = '{}';
|
||||
$late->created_at = $late->updated_at = $now - 7200;
|
||||
$late->save();
|
||||
$expiredPeriod = new CloudServicePeriod();
|
||||
$expiredPeriod->instance_id = $late->id;
|
||||
$expiredPeriod->user_id = 1;
|
||||
$expiredPeriod->plan_id = 7;
|
||||
$expiredPeriod->starts_at = $now - 7200;
|
||||
$expiredPeriod->ends_at = $now - 60;
|
||||
$expiredPeriod->traffic_quota_bytes = 1000;
|
||||
$expiredPeriod->download_base_bytes = 0;
|
||||
$expiredPeriod->upload_base_bytes = 0;
|
||||
$expiredPeriod->download_used_bytes = 2000;
|
||||
$expiredPeriod->upload_used_bytes = 1000;
|
||||
$expiredPeriod->status = 'active';
|
||||
$expiredPeriod->activated_at = $now - 7200;
|
||||
$expiredPeriod->created_at = $expiredPeriod->updated_at = $now - 7200;
|
||||
$expiredPeriod->save();
|
||||
$late->current_period_id = $expiredPeriod->id;
|
||||
$late->save();
|
||||
|
||||
$lateRenewal = CloudRenewalService::renew($late, [
|
||||
'idempotency_key' => 'late-renewal-period-0001',
|
||||
], $actor);
|
||||
$late->refresh();
|
||||
$expiredPeriod->refresh();
|
||||
$latePeriod = CloudServicePeriod::find($lateRenewal->period_id);
|
||||
$assert($expiredPeriod->status === 'finished' && $latePeriod->status === 'active'
|
||||
&& (int) $late->current_period_id === (int) $latePeriod->id,
|
||||
'Late renewal left an expired period active beside the new current period.');
|
||||
|
||||
// The tick argument is a database chunk size, not a permanent low-ID cap.
|
||||
// Both instances must be reconciled even when one row is fetched per chunk.
|
||||
$expiredIds = [];
|
||||
foreach ([
|
||||
'44444444-4444-4444-8444-444444444444',
|
||||
'55555555-5555-4555-8555-555555555555',
|
||||
] as $number => $uuid) {
|
||||
$candidate = new CloudInstance();
|
||||
$candidate->host_id = 1;
|
||||
$candidate->user_id = 1;
|
||||
$candidate->uuid = $uuid;
|
||||
$candidate->name = 'expired-' . $number;
|
||||
$candidate->status = 'active';
|
||||
$candidate->service_status = 'active';
|
||||
$candidate->network_status = 'active';
|
||||
$candidate->expires_at = $now - 1;
|
||||
$candidate->spec_json = '{}';
|
||||
$candidate->created_at = $candidate->updated_at = $now - 100;
|
||||
$candidate->save();
|
||||
$expiredIds[] = $candidate->id;
|
||||
}
|
||||
$lifecycle->tick(1);
|
||||
foreach ($expiredIds as $id) {
|
||||
$assert(CloudInstance::find($id)->service_status === 'suspending_expired'
|
||||
&& CloudJob::where('instance_id', $id)->where('kind', 'service_suspend')->exists(),
|
||||
'Lifecycle chunking permanently starved a higher instance ID.');
|
||||
}
|
||||
|
||||
$makeInstance = static function (string $uuid, string $name, int $expiresAt,
|
||||
string $serviceStatus = 'active', string $networkStatus = 'active') use ($now): CloudInstance {
|
||||
$value = new CloudInstance();
|
||||
$value->host_id = 1;
|
||||
$value->user_id = 1;
|
||||
$value->plan_id = 7;
|
||||
$value->uuid = $uuid;
|
||||
$value->name = $name;
|
||||
$value->status = 'active';
|
||||
$value->service_status = $serviceStatus;
|
||||
$value->network_status = $networkStatus;
|
||||
$value->expires_at = $expiresAt;
|
||||
$value->spec_json = '{}';
|
||||
$value->created_at = $value->updated_at = $now - 7200;
|
||||
$value->save();
|
||||
return $value;
|
||||
};
|
||||
$makePeriod = static function (CloudInstance $value, int $startsAt, int $endsAt,
|
||||
string $status = 'scheduled', int $quota = 1000) use ($now): CloudServicePeriod {
|
||||
$periodValue = new CloudServicePeriod();
|
||||
$periodValue->instance_id = $value->id;
|
||||
$periodValue->user_id = $value->user_id;
|
||||
$periodValue->plan_id = $value->plan_id;
|
||||
$periodValue->starts_at = $startsAt;
|
||||
$periodValue->ends_at = $endsAt;
|
||||
$periodValue->traffic_quota_bytes = $quota;
|
||||
$periodValue->download_used_bytes = 0;
|
||||
$periodValue->upload_used_bytes = 0;
|
||||
$periodValue->status = $status;
|
||||
$periodValue->created_at = $periodValue->updated_at = $now - 7200;
|
||||
$periodValue->save();
|
||||
return $periodValue;
|
||||
};
|
||||
$makeJob = static function (CloudInstance $value, string $kind,
|
||||
string $status = 'uncertain') use ($now): CloudJob {
|
||||
$jobValue = new CloudJob();
|
||||
$jobValue->operation_id = bin2hex(random_bytes(16));
|
||||
$jobValue->instance_id = $value->id;
|
||||
$jobValue->user_id = $value->user_id;
|
||||
$jobValue->host_id = $value->host_id;
|
||||
$jobValue->kind = $kind;
|
||||
$jobValue->status = $status;
|
||||
$jobValue->payload_cipher = \App\Services\Cloud\CloudSecrets::encrypt([
|
||||
'method' => 'POST', 'resource' => 'test', 'body' => [],
|
||||
]);
|
||||
$jobValue->attempts = 1;
|
||||
$jobValue->dispatched_at = $now - 60;
|
||||
$jobValue->lease_until = 0;
|
||||
$jobValue->available_at = $now;
|
||||
$jobValue->created_at = $jobValue->updated_at = $now - 60;
|
||||
$jobValue->save();
|
||||
return $jobValue;
|
||||
};
|
||||
|
||||
// If the lifecycle daemon misses multiple complete prepaid periods, it
|
||||
// must finish those historical rows without ever activating them. Only
|
||||
// the one period that contains "now" may restore networking.
|
||||
$backlog = $makeInstance('66666666-6666-4666-8666-666666666666',
|
||||
'period-backlog-vm', $now + 1800, 'active', 'blocked_traffic');
|
||||
$backlog->lifetime_download_bytes = 10000;
|
||||
$backlog->lifetime_upload_bytes = 5000;
|
||||
$backlog->traffic_synced_at = $now;
|
||||
$backlog->save();
|
||||
$missedOne = $makePeriod($backlog, $now - 4000, $now - 3000);
|
||||
$missedTwo = $makePeriod($backlog, $now - 3000, $now - 2000);
|
||||
$currentBacklog = $makePeriod($backlog, $now - 100, $now + 900);
|
||||
$futureBacklog = $makePeriod($backlog, $now + 900, $now + 1800);
|
||||
$lifecycle->tick(100);
|
||||
$backlog->refresh();
|
||||
$missedOne->refresh();
|
||||
$missedTwo->refresh();
|
||||
$currentBacklog->refresh();
|
||||
$futureBacklog->refresh();
|
||||
$assert($missedOne->status === 'finished' && $missedOne->activated_at === null
|
||||
&& $missedTwo->status === 'finished' && $missedTwo->activated_at === null,
|
||||
'Historical scheduled periods were briefly activated after daemon downtime.');
|
||||
$assert($currentBacklog->status === 'active'
|
||||
&& (int) $backlog->current_period_id === (int) $currentBacklog->id
|
||||
&& $futureBacklog->status === 'scheduled',
|
||||
'Lifecycle did not select exactly the currently valid prepaid period.');
|
||||
$assert($backlog->network_status === 'restoring'
|
||||
&& CloudJob::where('instance_id', $backlog->id)->where('kind', 'network_resume')->count() === 1,
|
||||
'Current-period activation did not produce exactly one network restore.');
|
||||
|
||||
// Lost-response action/delete jobs can remain uncertain forever because
|
||||
// they are not safely replayable. They must not grant free service by
|
||||
// blocking final-expiry enforcement. Replayable and target-state policy
|
||||
// uncertainty must still serialize against a duplicate operation.
|
||||
$nonReplayable = $makeInstance('77777777-7777-4777-8777-777777777777',
|
||||
'non-replayable-uncertain', $now - 1);
|
||||
$makeJob($nonReplayable, 'action');
|
||||
$makeJob($nonReplayable, 'delete');
|
||||
|
||||
$replayable = $makeInstance('88888888-8888-4888-8888-888888888888',
|
||||
'replayable-uncertain', $now - 1);
|
||||
$makeJob($replayable, 'reinstall');
|
||||
|
||||
$policyPending = $makeInstance('99999999-9999-4999-8999-999999999999',
|
||||
'policy-uncertain', $now - 1, 'suspending_expired');
|
||||
$makeJob($policyPending, 'service_suspend');
|
||||
|
||||
$lifecycle->tick(100);
|
||||
$nonReplayable->refresh();
|
||||
$replayable->refresh();
|
||||
$policyPending->refresh();
|
||||
$assert($nonReplayable->service_status === 'suspending_expired'
|
||||
&& CloudJob::where('instance_id', $nonReplayable->id)
|
||||
->where('kind', 'service_suspend')->count() === 1,
|
||||
'Permanent uncertain action/delete jobs blocked final service suspension.');
|
||||
$assert($replayable->service_status === 'suspending_expired'
|
||||
&& CloudJob::where('instance_id', $replayable->id)
|
||||
->where('kind', 'service_suspend')->count() === 0,
|
||||
'Replayable uncertain work did not serialize expiry policy.');
|
||||
$assert(CloudJob::where('instance_id', $policyPending->id)
|
||||
->where('kind', 'service_suspend')->count() === 1,
|
||||
'An uncertain policy target-state operation was duplicated.');
|
||||
|
||||
// Renewal prepayment is intentionally bounded. Rejection must happen in
|
||||
// the wallet transaction before either money or ledger rows are changed.
|
||||
\App\Services\Config::$values['cloud_max_renewal_periods_ahead'] = 2;
|
||||
$renewalLimited = $makeInstance('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
'renewal-limit-vm', $now + 3000);
|
||||
$renewalLimited->renewal_price = '7.25';
|
||||
$renewalLimited->renewal_days = 30;
|
||||
$renewalLimited->renewal_traffic_bytes = 2048;
|
||||
$renewalLimited->traffic_quota_bytes = 2048;
|
||||
$renewalLimited->save();
|
||||
$limitedCurrent = $makePeriod($renewalLimited, $now - 100, $now + 1000, 'active', 2048);
|
||||
$limitedCurrent->download_base_bytes = 0;
|
||||
$limitedCurrent->upload_base_bytes = 0;
|
||||
$limitedCurrent->activated_at = $now - 100;
|
||||
$limitedCurrent->save();
|
||||
$makePeriod($renewalLimited, $now + 1000, $now + 2000, 'scheduled', 2048);
|
||||
$makePeriod($renewalLimited, $now + 2000, $now + 3000, 'scheduled', 2048);
|
||||
$renewalLimited->current_period_id = $limitedCurrent->id;
|
||||
$renewalLimited->save();
|
||||
$balanceBeforeLimit = (string) User::find(1)->money;
|
||||
$periodCountBeforeLimit = CloudServicePeriod::where('instance_id', $renewalLimited->id)->count();
|
||||
$renewalCountBeforeLimit = CloudRenewal::where('instance_id', $renewalLimited->id)->count();
|
||||
$expiryBeforeLimit = (int) $renewalLimited->expires_at;
|
||||
try {
|
||||
CloudRenewalService::renew($renewalLimited, [
|
||||
'idempotency_key' => 'renewal-ahead-limit-0001',
|
||||
], $actor);
|
||||
throw new RuntimeException('Renewal ahead limit was not enforced.');
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409, 'Renewal ahead limit returned the wrong status.');
|
||||
}
|
||||
$renewalLimited->refresh();
|
||||
$assert((string) User::find(1)->money === $balanceBeforeLimit
|
||||
&& CloudServicePeriod::where('instance_id', $renewalLimited->id)->count() === $periodCountBeforeLimit
|
||||
&& CloudRenewal::where('instance_id', $renewalLimited->id)->count() === $renewalCountBeforeLimit
|
||||
&& (int) $renewalLimited->expires_at === $expiryBeforeLimit,
|
||||
'Rejected over-limit renewal changed money, expiry or ledger rows.');
|
||||
unset(\App\Services\Config::$values['cloud_max_renewal_periods_ahead']);
|
||||
|
||||
// A newer log timestamp with lower cumulative counters indicates a log
|
||||
// reset or corrupt observation. Billing totals and blocked networking are
|
||||
// monotonic and must not roll back with it.
|
||||
$rollback = $makeInstance('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
|
||||
'counter-rollback-vm', $now + 3600, 'active', 'blocked_traffic');
|
||||
$rollback->traffic_quota_bytes = 1000;
|
||||
$rollback->lifetime_download_bytes = 1000;
|
||||
$rollback->lifetime_upload_bytes = 500;
|
||||
$rollback->traffic_download_bytes = 1000;
|
||||
$rollback->traffic_upload_bytes = 500;
|
||||
$rollback->traffic_synced_at = $now - 10;
|
||||
$rollback->save();
|
||||
$rollbackPeriod = $makePeriod($rollback, $now - 100, $now + 3600, 'exhausted', 1000);
|
||||
$rollbackPeriod->download_base_bytes = 0;
|
||||
$rollbackPeriod->upload_base_bytes = 0;
|
||||
$rollbackPeriod->download_used_bytes = 1000;
|
||||
$rollbackPeriod->upload_used_bytes = 500;
|
||||
$rollbackPeriod->activated_at = $now - 100;
|
||||
$rollbackPeriod->save();
|
||||
$rollback->current_period_id = $rollbackPeriod->id;
|
||||
$rollback->save();
|
||||
$capsule->connection('log')->table('engine_vm_traffic_totals')->insert([
|
||||
'host_scope' => $scope,
|
||||
'vm_uuid' => $rollback->uuid,
|
||||
'host_id' => '1',
|
||||
'user_id' => 1,
|
||||
'last_observed_at' => $now + 100,
|
||||
'download_rx_bytes' => 100,
|
||||
'upload_tx_bytes' => 50,
|
||||
'updated_at' => $now + 100,
|
||||
]);
|
||||
$lifecycle->tick(100);
|
||||
$rollback->refresh();
|
||||
$rollbackPeriod->refresh();
|
||||
$assert((int) $rollback->lifetime_download_bytes === 1000
|
||||
&& (int) $rollback->lifetime_upload_bytes === 500
|
||||
&& (int) $rollback->traffic_synced_at === $now - 10
|
||||
&& (int) $rollbackPeriod->download_used_bytes === 1000
|
||||
&& (int) $rollbackPeriod->upload_used_bytes === 500,
|
||||
'A newer but lower log total rolled billing counters backward.');
|
||||
$assert($rollback->network_status === 'blocked_traffic'
|
||||
&& !CloudJob::where('instance_id', $rollback->id)->where('kind', 'network_resume')->exists(),
|
||||
'Counter rollback incorrectly restored an exhausted VM network.');
|
||||
|
||||
// Hourly cumulative checkpoints survive the 30-day chart retention and
|
||||
// keep an independent billing boundary reconstructable after a prolonged
|
||||
// lifecycle-daemon outage.
|
||||
$checkpointed = $makeInstance('cccccccc-cccc-4ccc-8ccc-cccccccccccc',
|
||||
'checkpoint-boundary-vm', $now + 3600);
|
||||
$checkpointed->lifetime_download_bytes = 1000;
|
||||
$checkpointed->lifetime_upload_bytes = 500;
|
||||
$checkpointed->traffic_synced_at = $now;
|
||||
$checkpointed->save();
|
||||
$checkpointPeriod = $makePeriod($checkpointed, $now - 3600, $now + 3600,
|
||||
'scheduled', 10000);
|
||||
$capsule->connection('log')->table('engine_vm_traffic_checkpoints')->insert([
|
||||
'host_scope' => $scope,
|
||||
'vm_uuid' => $checkpointed->uuid,
|
||||
'checkpoint_hour' => intdiv($now - 3540, 3600),
|
||||
'host_id' => '1',
|
||||
'user_id' => 1,
|
||||
'first_observed_at' => $now - 3540,
|
||||
'download_rx_bytes' => 400,
|
||||
'upload_tx_bytes' => 200,
|
||||
]);
|
||||
$lifecycle->tick(100);
|
||||
$checkpointed->refresh();
|
||||
$checkpointPeriod->refresh();
|
||||
$assert($checkpointPeriod->status === 'active'
|
||||
&& (int) $checkpointPeriod->download_base_bytes === 400
|
||||
&& (int) $checkpointPeriod->upload_base_bytes === 200
|
||||
&& (int) $checkpointPeriod->download_used_bytes === 600
|
||||
&& (int) $checkpointPeriod->upload_used_bytes === 300,
|
||||
'Durable checkpoint did not reconstruct the independent period boundary.');
|
||||
|
||||
// Restoring a paid period may auto-start only a VM that expiry policy
|
||||
// actually stopped. A tenant-stopped VM merely has autostart re-enabled.
|
||||
foreach ([true, false] as $policyStoppedRunningVm) {
|
||||
$suffix = $policyStoppedRunningVm ? 'd' : 'e';
|
||||
$resume = $makeInstance(str_repeat($suffix, 8) . '-' . str_repeat($suffix, 4)
|
||||
. '-4' . str_repeat($suffix, 3) . '-8' . str_repeat($suffix, 3)
|
||||
. '-' . str_repeat($suffix, 12), 'resume-marker-' . $suffix,
|
||||
$now + 3600, 'resume_pending');
|
||||
$resume->suspended_at = $policyStoppedRunningVm ? $now - 10 : null;
|
||||
$resume->traffic_synced_at = $now;
|
||||
$resume->save();
|
||||
$resumePeriod = $makePeriod($resume, $now - 100, $now + 3600,
|
||||
'active', 1000);
|
||||
$resumePeriod->download_base_bytes = 0;
|
||||
$resumePeriod->upload_base_bytes = 0;
|
||||
$resumePeriod->activated_at = $now - 100;
|
||||
$resumePeriod->save();
|
||||
$resume->current_period_id = $resumePeriod->id;
|
||||
$resume->save();
|
||||
$lifecycle->tick(100);
|
||||
$resumeJob = CloudJob::where('instance_id', $resume->id)
|
||||
->where('kind', 'service_resume')->first();
|
||||
$resumePayload = $resumeJob === null ? []
|
||||
: \App\Services\Cloud\CloudSecrets::decrypt($resumeJob->payload_cipher);
|
||||
$assert($resumeJob !== null
|
||||
&& ($resumePayload['body']['start_if_suspended'] ?? null) === $policyStoppedRunningVm,
|
||||
'Service resume did not preserve whether expiry policy stopped a running VM.');
|
||||
}
|
||||
|
||||
echo "Cloud independent-period renewal, traffic quota and lifecycle checks passed.\n";
|
||||
}
|
||||
Loading…
Reference in New Issue