使用英文字母、数字、点、下划线或连字符。
-
选择套餐后显示资源规格和一次性价格。
CPU、内存、硬盘、带宽、宿主机及公网地址由所选套餐确定,不能自行修改。
+
选择套餐后显示资源规格、每期价格、账期和每期流量额度。
CPU、内存、硬盘、带宽、账期、每期流量额度、宿主机及公网地址由所选套餐确定,不能自行修改。
镜像来自宿主机允许使用的 ISO 目录。
系统镜像 *点击系统图标下方的箭头展开版本,再选择已导入的镜像;模板需支持 cloud-init。
diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql
index 476086ec..7fc51432 100644
--- a/web/sql/cloud.sql
+++ b/web/sql/cloud.sql
@@ -14,15 +14,32 @@ CREATE TABLE IF NOT EXISTS cloud_instances (
host_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
order_id BIGINT UNSIGNED DEFAULT NULL,
+ plan_id BIGINT UNSIGNED DEFAULT NULL,
+ current_period_id BIGINT UNSIGNED DEFAULT NULL,
name VARCHAR(63) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'active',
+ service_status VARCHAR(32) NOT NULL DEFAULT 'exempt',
+ network_status VARCHAR(32) NOT NULL DEFAULT 'active',
+ expires_at BIGINT UNSIGNED DEFAULT NULL,
+ renewal_price DECIMAL(12,2) DEFAULT NULL,
+ renewal_days INT UNSIGNED NOT NULL DEFAULT 0,
+ renewal_traffic_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ traffic_quota_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ traffic_download_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ traffic_upload_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ lifetime_download_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ lifetime_upload_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ traffic_synced_at BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ suspended_at BIGINT UNSIGNED DEFAULT NULL,
+ network_suspended_at BIGINT UNSIGNED DEFAULT NULL,
spec_json LONGTEXT NOT NULL,
credential_cipher LONGTEXT DEFAULT NULL,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
UNIQUE KEY uniq_cloud_host_vm (host_id, uuid),
UNIQUE KEY uniq_cloud_instance_order (order_id),
- KEY cloud_instance_owner (user_id, status)
+ KEY cloud_instance_owner (user_id, status),
+ KEY cloud_instance_lifecycle (service_status, expires_at, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS cloud_orders (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
@@ -41,6 +58,46 @@ CREATE TABLE IF NOT EXISTS cloud_orders (
UNIQUE KEY uniq_cloud_order_request (user_id, idempotency_key),
KEY cloud_order_owner (user_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+CREATE TABLE IF NOT EXISTS cloud_service_periods (
+ id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
+ instance_id BIGINT UNSIGNED NOT NULL,
+ user_id BIGINT UNSIGNED NOT NULL,
+ plan_id BIGINT UNSIGNED DEFAULT NULL,
+ order_id BIGINT UNSIGNED DEFAULT NULL,
+ renewal_id BIGINT UNSIGNED DEFAULT NULL,
+ starts_at BIGINT UNSIGNED NOT NULL,
+ ends_at BIGINT UNSIGNED NOT NULL,
+ traffic_quota_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ download_base_bytes BIGINT UNSIGNED DEFAULT NULL,
+ upload_base_bytes BIGINT UNSIGNED DEFAULT NULL,
+ download_used_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ upload_used_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ status VARCHAR(16) NOT NULL DEFAULT 'scheduled',
+ activated_at BIGINT UNSIGNED DEFAULT NULL,
+ created_at BIGINT UNSIGNED NOT NULL,
+ updated_at BIGINT UNSIGNED NOT NULL,
+ UNIQUE KEY uniq_cloud_period_order (order_id),
+ UNIQUE KEY uniq_cloud_period_renewal (renewal_id),
+ KEY cloud_period_timeline (instance_id, starts_at, ends_at),
+ KEY cloud_period_activation (status, starts_at, id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+CREATE TABLE IF NOT EXISTS cloud_renewals (
+ id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
+ instance_id BIGINT UNSIGNED NOT NULL,
+ user_id BIGINT UNSIGNED NOT NULL,
+ plan_id BIGINT UNSIGNED DEFAULT NULL,
+ period_id BIGINT UNSIGNED DEFAULT NULL,
+ idempotency_key VARCHAR(128) NOT NULL,
+ request_hash CHAR(64) NOT NULL,
+ amount DECIMAL(12,2) NOT NULL,
+ validity_days INT UNSIGNED NOT NULL,
+ traffic_bytes_added BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ previous_expires_at BIGINT UNSIGNED NOT NULL,
+ new_expires_at BIGINT UNSIGNED NOT NULL,
+ created_at BIGINT UNSIGNED NOT NULL,
+ UNIQUE KEY uniq_cloud_renewal_request (user_id, idempotency_key),
+ KEY cloud_renewal_instance (instance_id, id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS cloud_jobs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
operation_id CHAR(32) NOT NULL,
@@ -63,6 +120,7 @@ CREATE TABLE IF NOT EXISTS cloud_jobs (
UNIQUE KEY uniq_cloud_operation (operation_id),
UNIQUE KEY uniq_cloud_provision_order (order_id),
KEY cloud_job_poll (status, available_at, lease_until),
+ KEY cloud_job_instance_state (instance_id, status, id),
KEY cloud_job_owner (user_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS cloud_ssh_keys (
diff --git a/web/sql/cloud_log.sql b/web/sql/cloud_log.sql
index 5096237c..216bbc5b 100644
--- a/web/sql/cloud_log.sql
+++ b/web/sql/cloud_log.sql
@@ -1,8 +1,10 @@
--- Same schema as engine database._METRIC_SCHEMA, not a separate PHP metric model.
+-- Same DDL as the engine-owned metric/traffic schemas and migrations.
-- Engine owns collection, retention and writes; PHP initializes the empty log database.
CREATE TABLE IF NOT EXISTS engine_vm_metric_samples (
host_scope CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
vm_uuid CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+ host_id VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+ user_id BIGINT UNSIGNED NULL,
sampled_at BIGINT UNSIGNED NOT NULL,
cpu_percent DOUBLE NULL,
memory_used_mib DOUBLE NULL,
@@ -11,6 +13,52 @@ CREATE TABLE IF NOT EXISTS engine_vm_metric_samples (
disk_write_bps DOUBLE NULL,
network_rx_bps DOUBLE NULL,
network_tx_bps DOUBLE NULL,
+ network_rx_bytes BIGINT UNSIGNED NULL,
+ network_tx_bytes BIGINT UNSIGNED NULL,
PRIMARY KEY (host_scope, vm_uuid, sampled_at),
- KEY vm_metric_retention (sampled_at)
+ KEY vm_metric_retention (sampled_at),
+ KEY vm_metric_owner (user_id, host_id, sampled_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+CREATE TABLE IF NOT EXISTS engine_vm_traffic_totals (
+ host_scope CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+ vm_uuid CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+ host_id VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+ user_id BIGINT UNSIGNED NULL,
+ last_observed_at BIGINT UNSIGNED NULL,
+ network_signature CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+ network_baseline_json JSON NOT NULL,
+ download_rx_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ upload_tx_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
+ updated_at BIGINT UNSIGNED NOT NULL,
+ PRIMARY KEY (host_scope, vm_uuid),
+ KEY vm_traffic_owner (user_id, host_id),
+ KEY vm_traffic_host (host_id, vm_uuid)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- Compact, durable billing ledger. Chart samples below are pruned after 30
+-- days; the first cumulative counter observed in every hour is not.
+CREATE TABLE IF NOT EXISTS engine_vm_traffic_checkpoints (
+ host_scope CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+ vm_uuid CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+ checkpoint_hour BIGINT UNSIGNED NOT NULL,
+ host_id VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+ user_id BIGINT UNSIGNED NULL,
+ first_observed_at BIGINT UNSIGNED NOT NULL,
+ download_rx_bytes BIGINT UNSIGNED NOT NULL,
+ upload_tx_bytes BIGINT UNSIGNED NOT NULL,
+ PRIMARY KEY (host_scope, vm_uuid, checkpoint_hour),
+ KEY vm_traffic_checkpoint_owner (user_id, host_id, first_observed_at)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- Idempotent MariaDB migration for installations created before byte accounting.
+ALTER TABLE engine_vm_metric_samples ADD COLUMN IF NOT EXISTS
+ host_id VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL AFTER vm_uuid;
+ALTER TABLE engine_vm_metric_samples ADD COLUMN IF NOT EXISTS
+ user_id BIGINT UNSIGNED NULL AFTER host_id;
+ALTER TABLE engine_vm_metric_samples ADD COLUMN IF NOT EXISTS
+ network_rx_bytes BIGINT UNSIGNED NULL AFTER network_tx_bps;
+ALTER TABLE engine_vm_metric_samples ADD COLUMN IF NOT EXISTS
+ network_tx_bytes BIGINT UNSIGNED NULL AFTER network_rx_bytes;
+ALTER TABLE engine_vm_metric_samples ADD INDEX IF NOT EXISTS
+ vm_metric_owner (user_id, host_id, sampled_at);
diff --git a/web/sql/ss.sql b/web/sql/ss.sql
index 6a0bb531..93ba68d1 100644
--- a/web/sql/ss.sql
+++ b/web/sql/ss.sql
@@ -230,6 +230,8 @@ CREATE TABLE `shop` (
`memory_mib` int(11) NOT NULL,
`bandwidth_mbps` int(11) NOT NULL,
`disk_gib` int(11) NOT NULL,
+ `validity_days` int(10) unsigned NOT NULL DEFAULT 30,
+ `traffic_quota_bytes` bigint(20) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 1,
`stock` int(11) NOT NULL DEFAULT -1,
`sort` int(11) NOT NULL DEFAULT 0
diff --git a/web/tests/CloudBillingLifecycleTest.php b/web/tests/CloudBillingLifecycleTest.php
new file mode 100644
index 00000000..e4a09b15
--- /dev/null
+++ b/web/tests/CloudBillingLifecycleTest.php
@@ -0,0 +1,781 @@
+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";
+}
diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php
index f9993299..c3cf6eff 100644
--- a/web/tests/CloudFinancialWorkflowTest.php
+++ b/web/tests/CloudFinancialWorkflowTest.php
@@ -45,16 +45,17 @@ namespace {
$capsule->setAsGlobal(); $capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->string('money'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('restrict_balance_purchase')->default(0); });
- $schema->create('shop', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->string('name'); $t->string('price'); foreach (['cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'status', 'stock', 'sort'] as $v) { $t->integer($v)->default(0); } });
+ $schema->create('shop', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->string('name'); $t->string('price'); foreach (['cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'validity_days', 'traffic_quota_bytes', 'status', 'stock', 'sort'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->integer('enabled'); $t->string('default_network'); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'host_id'] as $v) { $t->integer($v); } $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('status'); $t->text('spec_json'); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_jobs', function (Blueprint $t) { $t->increments('id'); $t->string('operation_id')->unique(); foreach (['order_id', 'instance_id'] as $v) { $t->integer($v)->nullable(); } foreach (['user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('kind'); $t->string('status'); $t->text('payload_cipher'); $t->integer('attempts')->default(0); $t->integer('dispatched_at')->nullable(); $t->string('lease_token')->nullable(); $t->integer('lease_until')->default(0); $t->integer('available_at'); $t->string('error_code')->nullable(); $t->text('result_json')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); });
- $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('order_id')->nullable(); $t->string('uuid'); $t->string('name'); $t->string('status'); $t->text('spec_json'); $t->text('credential_cipher')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); });
+ $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id'] as $v) { $t->integer($v); } foreach (['order_id', 'plan_id', 'current_period_id', 'expires_at', 'suspended_at', 'network_suspended_at'] as $v) { $t->integer($v)->nullable(); } foreach (['renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', 'lifetime_download_bytes', 'lifetime_upload_bytes', 'traffic_synced_at'] as $v) { $t->integer($v)->default(0); } $t->string('renewal_price')->nullable(); $t->string('uuid'); $t->string('name'); $t->string('status'); $t->string('service_status')->default('exempt'); $t->string('network_status')->default('active'); $t->text('spec_json'); $t->text('credential_cipher')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); });
+ $schema->create('cloud_service_periods', function (Blueprint $t) { $t->increments('id'); foreach (['instance_id', 'user_id'] as $v) { $t->integer($v); } foreach (['plan_id', 'order_id', 'renewal_id', 'download_base_bytes', 'upload_base_bytes', 'activated_at'] as $v) { $t->integer($v)->nullable(); } foreach (['starts_at', 'ends_at', 'traffic_quota_bytes', 'download_used_bytes', 'upload_used_bytes', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } $t->string('status'); $t->unique('order_id'); $t->unique('renewal_id'); });
$schema->create('cloud_ssh_keys', function (Blueprint $t) { $t->increments('id'); $t->integer('user_id'); $t->string('name'); $t->text('public_key'); $t->string('fingerprint'); $t->integer('created_at'); });
$user = new User(); $user->id = 1; $user->money = '100.00'; $user->enable = 1; $user->is_admin = false; $user->save(); $user->isLogin = true;
\App\Services\Auth::$user = $user;
$host = new CloudHost(); $host->name = 'host'; $host->enabled = true; $host->default_network = 'bridge:br0'; $host->save();
- $plan = new Shop(); $plan->host_id = $host->id; $plan->name = 'plan'; $plan->price = '9.99'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->status = 1; $plan->stock = 10; $plan->save();
+ $plan = new Shop(); $plan->host_id = $host->id; $plan->name = 'plan'; $plan->price = '9.99'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->validity_days = 30; $plan->traffic_quota_bytes = 1024 * 1024 * 1024; $plan->status = 1; $plan->stock = 10; $plan->save();
$actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false, 'session_id' => ''];
$wrongOperationClient = new CloudEngineClient(new Client(['handler' => HandlerStack::create(new MockHandler([
new Response(422, [], '{"operation_id":"another-operation","status":"failed","safe_to_refund":true}')
@@ -76,7 +77,8 @@ namespace {
$stack = HandlerStack::create($mock); $stack->push(Middleware::history($history));
$worker = new CloudWorkerService(new CloudEngineClient(new Client(['handler' => $stack])));
$worker->tick();
- $assert(CloudOrder::find($first->id)->status === 'succeeded' && CloudInstance::count() === 1, 'Successful provision not associated.');
+ $assert(CloudOrder::find($first->id)->status === 'succeeded' && CloudInstance::count() === 1
+ && \App\Models\CloudServicePeriod::count() === 1, 'Successful provision did not create its first service period.');
$posted = json_decode((string) $history[0]['request']->getBody(), true);
$signedActor = json_decode(base64_decode(strtr($history[0]['request']->getHeaderLine('X-Cloud-Actor'), '-_', '+/')), true);
$assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100 && $posted['network'] === 'bridge:br0'
@@ -122,6 +124,147 @@ namespace {
$mock->append(new Response(200, [], '{"status":"succeeded","uuid":"11111111-1111-4111-8111-111111111111","state":"running"}')); $worker->tick();
$last = end($history)['request']; $signedActor = json_decode(base64_decode(strtr($last->getHeaderLine('X-Cloud-Actor'), '-_', '+/')), true);
$assert(CloudJob::find($actionJob->id)->status === 'succeeded' && $signedActor['can_manage'] === true && !isset($signedActor['can_provision']), 'Power task delegated provision authority or did not complete.');
+
+ // A policy request whose first POST was lost before the engine operation
+ // record existed is safe to replay with the same operation ID. A stale
+ // suspend target must instead be skipped after the authoritative 404.
+ $instance->network_status = 'blocking';
+ $instance->save();
+ $policy = new CloudJob();
+ $policy->operation_id = bin2hex(random_bytes(16));
+ $policy->instance_id = $instance->id;
+ $policy->user_id = $instance->user_id;
+ $policy->host_id = $instance->host_id;
+ $policy->kind = 'network_suspend';
+ $policy->status = 'uncertain';
+ $policy->payload_cipher = \App\Services\Cloud\CloudSecrets::encrypt([
+ 'method' => 'POST', 'resource' => 'vms/' . $instance->uuid . '/network-suspend',
+ 'body' => [], 'owner_id' => (int) $instance->user_id, 'system_policy' => true,
+ ]);
+ $policy->attempts = 1;
+ $policy->dispatched_at = time() - 30;
+ $policy->lease_until = 0;
+ $policy->available_at = 0;
+ $policy->created_at = $policy->updated_at = time() - 30;
+ $policy->save();
+ $beforePolicyRequests = count($history);
+ $mock->append(new Response(404, [], '{}'));
+ $mock->append(new Response(200, [], '{"status":"succeeded","result":{}}'));
+ $worker->tick();
+ $policyRequests = array_slice($history, $beforePolicyRequests);
+ $assert(count($policyRequests) === 2
+ && $policyRequests[0]['request']->getMethod() === 'GET'
+ && $policyRequests[0]['request']->getUri()->getQuery() === 'reconcile=false'
+ && $policyRequests[1]['request']->getMethod() === 'POST'
+ && CloudJob::find($policy->id)->status === 'succeeded'
+ && $instance->fresh()->network_status === 'blocked_traffic',
+ 'Missing target-state operation was not replayed safely with the same desired state.');
+
+ $instance->network_status = 'active';
+ $instance->save();
+ $stalePolicy = $policy->replicate();
+ $stalePolicy->operation_id = bin2hex(random_bytes(16));
+ $stalePolicy->status = 'uncertain';
+ $stalePolicy->result_json = null;
+ $stalePolicy->error_code = null;
+ $stalePolicy->lease_token = null;
+ $stalePolicy->lease_until = 0;
+ $stalePolicy->available_at = 0;
+ $stalePolicy->created_at = $stalePolicy->updated_at = time() - 30;
+ $stalePolicy->save();
+ $beforeStaleRequests = count($history);
+ $mock->append(new Response(404, [], '{}'));
+ $worker->tick();
+ $assert(count($history) === $beforeStaleRequests + 1
+ && end($history)['request']->getUri()->getQuery() === 'reconcile=false'
+ && CloudJob::find($stalePolicy->id)->status === 'succeeded'
+ && $instance->fresh()->network_status === 'active',
+ 'A stale policy suspend was replayed after the desired state changed.');
+
+ // Desired state may reverse while the old engine request is still inside
+ // libvirt. The PHP job must remain nonterminal until that executor exits;
+ // otherwise lifecycle could dispatch the opposite request concurrently.
+ $instance->network_status = 'restore_pending';
+ $instance->save();
+ $activePolicy = $policy->replicate();
+ $activePolicy->operation_id = bin2hex(random_bytes(16));
+ $activePolicy->status = 'uncertain';
+ $activePolicy->result_json = null;
+ $activePolicy->error_code = null;
+ $activePolicy->lease_token = null;
+ $activePolicy->lease_until = 0;
+ $activePolicy->available_at = 0;
+ $activePolicy->created_at = $activePolicy->updated_at = time() - 30;
+ $activePolicy->save();
+ $beforeActiveRequests = count($history);
+ $mock->append(new Response(200, [], json_encode([
+ 'status' => 'uncertain', 'executor_active' => true,
+ ])));
+ $worker->tick();
+ $activePolicy->refresh();
+ $assert(count($history) === $beforeActiveRequests + 1
+ && end($history)['request']->getUri()->getQuery() === 'reconcile=false'
+ && $activePolicy->status === 'uncertain'
+ && $activePolicy->available_at > time()
+ && $instance->fresh()->network_status === 'restore_pending',
+ 'An active stale policy executor was closed before libvirt finished.');
+
+ $activePolicy->available_at = 0;
+ $activePolicy->save();
+ $mock->append(new Response(200, [], json_encode([
+ 'status' => 'succeeded', 'executor_active' => false,
+ 'result' => ['network_suspended' => true],
+ ])));
+ $worker->tick();
+ $assert(CloudJob::find($activePolicy->id)->status === 'succeeded'
+ && $instance->fresh()->network_status === 'restore_pending',
+ 'A completed stale policy did not preserve the newer desired state.');
+
+ // After an engine restart executor_active is false, but an existing
+ // nonterminal operation may have only partly changed libvirt. Reconcile
+ // that old target before the pending reverse target is allowed to run.
+ $crashedPolicy = $policy->replicate();
+ $crashedPolicy->operation_id = bin2hex(random_bytes(16));
+ $crashedPolicy->status = 'uncertain';
+ $crashedPolicy->result_json = null;
+ $crashedPolicy->error_code = null;
+ $crashedPolicy->lease_token = null;
+ $crashedPolicy->lease_until = 0;
+ $crashedPolicy->available_at = 0;
+ $crashedPolicy->created_at = $crashedPolicy->updated_at = time() - 30;
+ $crashedPolicy->save();
+ $beforeCrashRequests = count($history);
+ $mock->append(new Response(200, [], json_encode([
+ 'status' => 'uncertain', 'executor_active' => false,
+ ])));
+ $mock->append(new Response(200, [], json_encode([
+ 'status' => 'succeeded', 'executor_active' => false,
+ 'result' => ['network_suspended' => true],
+ ])));
+ $worker->tick();
+ $crashRequests = array_slice($history, $beforeCrashRequests);
+ $assert(count($crashRequests) === 2
+ && $crashRequests[0]['request']->getMethod() === 'GET'
+ && $crashRequests[0]['request']->getUri()->getQuery() === 'reconcile=false'
+ && $crashRequests[1]['request']->getMethod() === 'POST'
+ && CloudJob::find($crashedPolicy->id)->status === 'succeeded'
+ && $instance->fresh()->network_status === 'restore_pending',
+ 'A crash-interrupted stale target was skipped instead of converged before reversal.');
+
+ // A non-policy mutation whose authoritative engine operation has vanished
+ // cannot be replayed safely and must become terminal instead of blocking
+ // expiry enforcement forever.
+ $missingAction = CloudJobService::enqueue($instance, $actor, 'action', 'POST',
+ '/actions', ['action' => 'reboot']);
+ $missingAction->status = 'uncertain';
+ $missingAction->dispatched_at = time() - 30;
+ $missingAction->available_at = 0;
+ $missingAction->save();
+ $mock->append(new Response(404, [], '{}'));
+ $worker->tick();
+ $assert(CloudJob::find($missingAction->id)->status === 'failed',
+ 'A vanished non-policy engine operation remained permanently uncertain.');
+
$reinstall = CloudJobService::enqueue($instance, $actor, 'reinstall', 'POST', '/reinstall', ['template_id' => $input['template_id'], 'confirmation_name' => $instance->name, 'root_password' => 'NewStrongPassword!123'], ['password' => 'NewStrongPassword!123', 'login_name' => 'root']);
$oldCredential = $instance->credential_cipher;
$mock->append(new Response(202, [], '{"status":"pending","job_id":"remote-reinstall-id"}')); $worker->tick();
diff --git a/web/tests/CloudPlanDefinitionTest.php b/web/tests/CloudPlanDefinitionTest.php
index 784ac8fa..2e9c2da8 100644
--- a/web/tests/CloudPlanDefinitionTest.php
+++ b/web/tests/CloudPlanDefinitionTest.php
@@ -15,12 +15,17 @@ namespace {
}
};
$input = ['name' => 'Cloud starter', 'price' => '19.90', 'cpu_cores' => '2', 'memory_mib' => '2048',
- 'bandwidth_mbps' => '100', 'disk_gib' => '20', 'status' => '1', 'stock' => '-1', 'sort' => '0'];
+ 'bandwidth_mbps' => '100', 'disk_gib' => '20', 'validity_days' => '30', 'traffic_gib' => '1024',
+ 'status' => '1', 'stock' => '-1', 'sort' => '0'];
$data = Shop::validatePlan($input);
- $assert($data['cpu_cores'] === 2 && $data['disk_gib'] === 20 && $data['price'] === '19.90', 'Plan values were not normalized.');
- $assert(!array_key_exists('class', $data) && !array_key_exists('expire', $data), 'A cloud plan contains old entitlements.');
+ $assert($data['cpu_cores'] === 2 && $data['disk_gib'] === 20 && $data['price'] === '19.90'
+ && $data['validity_days'] === 30 && $data['traffic_quota_bytes'] === 1024 * Shop::GIB,
+ 'Plan values were not normalized.');
+ $assert(!array_key_exists('class', $data) && !array_key_exists('expire', $data)
+ && !array_key_exists('traffic_gib', $data), 'A cloud plan contains legacy or noncanonical entitlements.');
foreach (['cpu_cores' => 0, 'memory_mib' => 511, 'disk_gib' => 4097, 'bandwidth_mbps' => 0,
- 'price' => '1.999', 'status' => 2, 'stock' => -2, 'name' => ''] as $key => $invalid) {
+ 'validity_days' => 0, 'traffic_gib' => -1, 'price' => '1.999', 'status' => 2,
+ 'stock' => -2, 'name' => ''] as $key => $invalid) {
try {
Shop::validatePlan(array_replace($input, [$key => $invalid]));
throw new \RuntimeException('Invalid plan value accepted: ' . $key);
@@ -34,5 +39,15 @@ namespace {
$body = substr($source, $start, $end - $start);
$assert(strpos($body, '409') !== false && strpos($body, 'save(') === false && strpos($body, 'transaction(') === false,
'Purchase must not debit or create an order before virtualization integration.');
+ $controller = file_get_contents(dirname(__DIR__) . '/app/Controllers/CloudApiController.php');
+ $client = file_get_contents(dirname(__DIR__) . '/public/cloud/app.js');
+ $assert(str_contains($controller, '\'can_mutate\' => $owner || $global')
+ && str_contains($controller, '\'can_view_credential\' => $owner || $global')
+ && str_contains($client, '!vm.can_view_credential')
+ && str_contains($client, 'danger.closest(\'section\').hidden = !vm.can_mutate'),
+ 'Readonly administrators were offered another tenant\'s credentials or VM mutation controls.');
+ $assert(str_contains($controller, '$suffix === \'/rescue/exit\'')
+ && str_contains($controller, "['blocking', 'blocked_traffic', 'block_failed']"),
+ 'Rescue exit does not preserve the authoritative traffic suspension target.');
echo 'Cloud plan definition checks passed.' . PHP_EOL;
}
diff --git a/web/tests/CloudSessionSecurityTest.php b/web/tests/CloudSessionSecurityTest.php
index 35cfe08f..5d51b08a 100644
--- a/web/tests/CloudSessionSecurityTest.php
+++ b/web/tests/CloudSessionSecurityTest.php
@@ -46,9 +46,9 @@ namespace {
$schema = $capsule->schema('default');
$schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('login_session_version')->default(0); });
$schema->create('cloud_sessions', function (Blueprint $t) { $t->string('id')->primary(); $t->integer('user_id'); $t->integer('version'); $t->string('fingerprint')->unique(); $t->string('auth_driver'); $t->text('auth_reference')->nullable(); $t->integer('active'); $t->integer('expires_at'); $t->integer('created_at'); });
- $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('user_id'); $t->string('uuid'); $t->string('status'); });
- $capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111', 'status' => 'active']);
- $capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222', 'status' => 'active']);
+ $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('user_id'); $t->string('uuid'); $t->string('status'); $t->string('service_status')->default('active'); $t->integer('expires_at')->nullable(); });
+ $capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111', 'status' => 'active', 'expires_at' => time() + 3600]);
+ $capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222', 'status' => 'active', 'expires_at' => time() + 3600]);
$user = new User(); $user->id = 1; $user->enable = 1; $user->is_admin = false; $user->login_session_version = 0; $user->save(); $user->isLogin = true; \App\Services\Auth::$user = $user;
$_COOKIE = ['uid' => '1', 'key' => 'authenticated-cookie-reference', 'ip' => 'bound-cookie', 'expire_in' => (string) (time() + 300), 'login_session_version' => '0'];
$id = CloudSessionService::current($user);
@@ -56,6 +56,9 @@ namespace {
$assert(CloudSessionService::active($id, 9, '11111111-1111-4111-8111-111111111111'), 'Active owner console rejected.');
$assert(!CloudSessionService::active($id, 9, '22222222-2222-4222-8222-222222222222')
&& !CloudSessionService::active($id, 8, '11111111-1111-4111-8111-111111111111'), 'Console crossed tenant or host boundary.');
+ $capsule->getConnection('default')->table('cloud_instances')->where('user_id', 1)->update(['service_status' => 'suspended_expired']);
+ $assert(!CloudSessionService::active($id, 9, '11111111-1111-4111-8111-111111111111'), 'Expired service retained console access.');
+ $capsule->getConnection('default')->table('cloud_instances')->where('user_id', 1)->update(['service_status' => 'active']);
User::where('id', 1)->update(['enable' => 0]); $assert(!CloudSessionService::active($id), 'Disabled user retained console.'); User::where('id', 1)->update(['enable' => 1]);
CloudSession::where('id', $id)->update(['expires_at' => time() - 1]); $assert(!CloudSessionService::active($id), 'Expired session retained console.'); CloudSession::where('id', $id)->update(['expires_at' => time() + 300]);
LoginSessionRevocationService::revokeUser($user); $assert(!CloudSessionService::active($id), 'Password/version change retained console.');
diff --git a/web/tests/VirtualizationSchemaTest.php b/web/tests/VirtualizationSchemaTest.php
index 85d5676e..ff1e60d5 100644
--- a/web/tests/VirtualizationSchemaTest.php
+++ b/web/tests/VirtualizationSchemaTest.php
@@ -5,16 +5,37 @@ $python = file_get_contents(dirname($root) . '/engine/virsh_panel/database.py');
if (preg_match('/_METRIC_SCHEMA\s*=\s*"""(.*?)"""/s', $python, $match) !== 1) {
throw new RuntimeException('Engine metric schema missing');
}
+if (preg_match('/_TRAFFIC_SCHEMA\s*=\s*"""(.*?)"""/s', $python, $trafficMatch) !== 1) {
+ throw new RuntimeException('Engine traffic schema missing');
+}
+if (preg_match('/_TRAFFIC_CHECKPOINT_SCHEMA\s*=\s*"""(.*?)"""/s', $python, $checkpointMatch) !== 1) {
+ throw new RuntimeException('Engine traffic checkpoint schema missing');
+}
$sql = file_get_contents($root . '/sql/cloud_log.sql');
$normalize = static function ($value): string {
$value = preg_replace('/^\s*--[^\n]*$/m', '', $value);
return rtrim(trim(preg_replace('/\s+/', ' ', $value)), ';');
};
-$expected = str_replace('vm_metric_samples', 'engine_vm_metric_samples', $match[1]);
-if ($normalize($sql) !== $normalize($expected)) {
- throw new RuntimeException('Fresh-install metric SQL differs from engine-owned schema');
+$metric = $normalize(str_replace('vm_metric_samples', 'engine_vm_metric_samples', $match[1]));
+$traffic = $normalize(str_replace('vm_traffic_totals', 'engine_vm_traffic_totals', $trafficMatch[1]));
+$checkpoint = $normalize(str_replace('vm_traffic_checkpoints', 'engine_vm_traffic_checkpoints', $checkpointMatch[1]));
+$actual = $normalize($sql);
+if (!str_contains($actual, $metric) || !str_contains($actual, $traffic)
+ || !str_contains($actual, $checkpoint)) {
+ throw new RuntimeException('Fresh-install metric/traffic/checkpoint SQL differs from engine-owned schemas');
+}
+foreach ([
+ 'host_id VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL AFTER vm_uuid',
+ 'user_id BIGINT UNSIGNED NULL AFTER host_id',
+ 'network_rx_bytes BIGINT UNSIGNED NULL AFTER network_tx_bps',
+ 'network_tx_bytes BIGINT UNSIGNED NULL AFTER network_rx_bytes',
+ 'vm_metric_owner (user_id, host_id, sampled_at)',
+] as $migration) {
+ if (!str_contains($actual, $migration)) {
+ throw new RuntimeException('Log schema is missing an idempotent metric migration');
+ }
}
if (!str_contains($sql, 'CREATE TABLE IF NOT EXISTS engine_vm_metric_samples')) {
throw new RuntimeException('Metric initializer must execute DDL, not an empty/comment-only query');
}
-echo "Fresh-install log metric DDL matches the Python engine schema.\n";
+echo "Fresh-install metric and traffic DDL matches the Python engine schemas.\n";