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

410 lines
17 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudTemplate;
use App\Models\CloudTemplateReplica;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudTemplateCatalogService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expect = static function (callable $callable, int $status,
string $message) use ($assert): void {
try {
$callable();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
$message . ' Unexpected status: ' . $error->httpStatus);
return;
}
throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('cloud_templates',
static function (Blueprint $table): void {
$table->string('id')->primary();
$table->string('catalog_key');
$table->string('version_label');
$table->boolean('is_default')->default(false);
$table->string('name');
$table->string('os_family');
$table->string('os_version');
$table->integer('image_bytes');
$table->string('sha256');
$table->text('startup_script');
$table->integer('revision');
$table->string('generation_token')->unique();
$table->string('state');
$table->integer('created_at');
$table->integer('updated_at');
});
$capsule->schema('default')->create('cloud_template_replicas',
static function (Blueprint $table): void {
$table->integer('host_id');
$table->string('template_id');
$table->integer('revision');
$table->string('generation_token');
$table->string('state')->default('pending');
$table->integer('image_bytes')->default(0);
$table->string('sha256')->default('');
$table->string('operation_id')->default('');
$table->integer('job_id')->nullable();
$table->string('error_code')->default('');
$table->integer('created_at');
$table->integer('updated_at');
$table->primary(['host_id', 'template_id']);
});
$capsule->schema('default')->create('cloud_template_artifacts',
static function (Blueprint $table): void {
$table->string('template_id')->primary();
$table->string('state')->default('ready');
$table->string('error_code')->default('');
$table->integer('delete_generation')->default(0);
$table->integer('delete_next_check_at')->default(0);
});
$capsule->schema('default')->create('configurations',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('name')->unique();
$table->text('value');
});
$capsule->schema('default')->create('shop',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('status');
});
$capsule->schema('default')->create('cloud_regions',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('status');
});
$capsule->schema('default')->create('cloud_network_lines',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('region_id');
$table->integer('is_default');
$table->string('status');
});
$capsule->schema('default')->create('cloud_resource_pools',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('line_id');
$table->string('status');
});
$capsule->schema('default')->create('cloud_hosts',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('enabled');
$table->string('default_network');
});
$capsule->schema('default')->create('cloud_host_agents',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->integer('enabled');
$table->integer('revision');
$table->integer('tested_revision');
$table->string('last_test_status');
$table->text('network_selectors_json');
});
$capsule->schema('default')->create('cloud_host_storage_configurations',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->string('state');
});
$capsule->schema('default')->create(
'cloud_host_resource_pool_memberships',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('resource_pool_id');
$table->string('scheduler_state');
$table->integer('revision')->default(1);
}
);
$capsule->schema('default')->create('cloud_host_capacity_policies',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->integer('configured_cpu_cores');
$table->integer('configured_memory_mib');
$table->integer('configured_disk_gib');
});
$capsule->schema('default')->create('cloud_host_network_attachments',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('line_id');
$table->string('network_selector');
$table->string('state');
$table->string('verification_state');
$table->integer('verified_agent_revision');
$table->integer('last_verified_at');
});
$capsule->schema('default')->create('cloud_public_ip_pools',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('pool_key');
$table->integer('host_id');
$table->integer('network_attachment_id');
$table->string('cidr');
$table->string('gateway');
$table->integer('guest_prefix_length');
$table->text('dns_servers_json');
$table->text('reserved_ips_json');
$table->string('state');
$table->string('sync_state');
$table->integer('desired_revision');
$table->integer('observed_revision');
});
$capsule->schema('default')->create('cloud_public_ips',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('public_ip_pool_id');
$table->string('address');
$table->integer('prefix_length');
$table->string('state');
$table->integer('reservation_id')->nullable();
$table->integer('instance_id')->nullable();
$table->string('operation_id')->nullable();
});
$capsule->schema('default')->create('cloud_offers',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('plan_id');
$table->integer('resource_pool_id');
$table->integer('status');
$table->string('currency');
});
Capsule::table('configurations')->insert([
'name' => 'cloud_network_lines_enabled', 'value' => 'false',
]);
Capsule::table('shop')->insert(['id' => 1, 'status' => 1]);
Capsule::table('cloud_regions')->insert(['id' => 1, 'status' => 'active']);
Capsule::table('cloud_network_lines')->insert([
'id' => 1, 'region_id' => 1, 'is_default' => 1, 'status' => 'active',
]);
Capsule::table('cloud_resource_pools')->insert([
'id' => 1, 'line_id' => 1, 'status' => 'active',
]);
Capsule::table('cloud_hosts')->insert([
'id' => 1, 'enabled' => 1, 'default_network' => 'bridge:br0',
]);
Capsule::table('cloud_host_agents')->insert([
'host_id' => 1, 'enabled' => 1, 'revision' => 1,
'tested_revision' => 1, 'last_test_status' => 'healthy',
'network_selectors_json' => '["bridge:br-public"]',
]);
Capsule::table('cloud_host_storage_configurations')->insert([
'host_id' => 1, 'state' => 'applied',
]);
Capsule::table('cloud_hosts')->insert([
'id' => 2, 'enabled' => 1, 'default_network' => 'bridge:br0',
]);
Capsule::table('cloud_host_agents')->insert([
'host_id' => 2, 'enabled' => 1, 'revision' => 1,
'tested_revision' => 0, 'last_test_status' => 'failed',
'network_selectors_json' => '[]',
]);
Capsule::table('cloud_host_storage_configurations')->insert([
'host_id' => 2, 'state' => 'applied',
]);
Capsule::table('cloud_host_resource_pool_memberships')->insert([
'host_id' => 1, 'resource_pool_id' => 1, 'scheduler_state' => 'active',
]);
Capsule::table('cloud_host_capacity_policies')->insert([
'host_id' => 1, 'configured_cpu_cores' => 32,
'configured_memory_mib' => 65536, 'configured_disk_gib' => 1024,
]);
Capsule::table('cloud_host_network_attachments')->insert([
'id' => 1, 'host_id' => 1, 'line_id' => 1,
'network_selector' => 'bridge:br-public', 'state' => 'active',
'verification_state' => 'verified', 'verified_agent_revision' => 1,
'last_verified_at' => time(),
]);
Capsule::table('cloud_public_ip_pools')->insert([
'id' => 1, 'pool_key' => str_repeat('1', 32), 'host_id' => 1,
'network_attachment_id' => 1, 'cidr' => '203.0.113.0/29',
'gateway' => '203.0.113.1',
'guest_prefix_length' => 29, 'state' => 'active',
'dns_servers_json' => '[]', 'reserved_ips_json' => '[]',
'sync_state' => 'applied', 'desired_revision' => 1,
'observed_revision' => 1,
]);
Capsule::table('cloud_public_ips')->insert([
'host_id' => 1, 'public_ip_pool_id' => 1,
'address' => '203.0.113.2', 'prefix_length' => 29,
'state' => 'available', 'reservation_id' => null,
'instance_id' => null, 'operation_id' => null,
]);
Capsule::table('cloud_offers')->insert([
'id' => 1, 'plan_id' => 1, 'resource_pool_id' => 1,
'status' => 1, 'currency' => 'USD',
]);
$generation = bin2hex(random_bytes(16));
$now = time();
$actor = ['user_id' => 1, 'is_admin' => true,
'is_super_admin' => true, 'can_manage' => true];
$template = new CloudTemplate();
foreach ([
'id' => 'debian-12-template',
'catalog_key' => 'debian-12',
'version_label' => '20261030-test',
'is_default' => 1,
'name' => 'Debian 12',
'os_family' => 'Debian',
'os_version' => '12',
'image_bytes' => 1024,
'sha256' => str_repeat('a', 64),
'startup_script' => '',
'revision' => 1,
'generation_token' => $generation,
'state' => 'active',
'created_at' => $now,
'updated_at' => $now,
] as $field => $value) {
$template->{$field} = $value;
}
$template->save();
$replica = new CloudTemplateReplica();
foreach ([
'host_id' => 1,
'template_id' => 'debian-12-template',
'revision' => 1,
'generation_token' => $generation,
'state' => 'active',
'image_bytes' => 1024,
'sha256' => str_repeat('a', 64),
'operation_id' => bin2hex(random_bytes(16)),
'error_code' => '',
'created_at' => $now,
'updated_at' => $now,
] as $field => $value) {
$replica->{$field} = $value;
}
$replica->save();
$registered = CloudTemplateCatalogService::adminCatalog()['templates'][0];
$assert(preg_match('/^[a-f0-9]{32}$/D', $generation) === 1
&& $registered['revision'] === 1
&& $registered['startup_script_configured'] === false,
'New PHP-owned template did not receive immutable CAS identity.');
$saved = CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', "#!/bin/bash\r\necho 中文\r\n", 1, $generation
);
$assert($saved['startup_script'] === "#!/bin/bash\necho 中文\n"
&& $saved['revision'] === 2
&& $saved['generation_token'] === $generation,
'Startup script did not normalize CRLF or preserve generation.');
$sealed = CloudTemplateCatalogService::applyProvisioningSnapshot([
'template_id' => 'debian-12-template',
'startup_script' => 'tenant supplied',
'template_revision' => 999,
'template_generation_token' => str_repeat('f', 32),
]);
$assert($sealed['startup_script'] === "#!/bin/bash\necho 中文\n"
&& $sealed['template_revision'] === 2
&& $sealed['template_generation_token'] === $generation,
'Provisioning did not replace untrusted template/script fields with the PHP snapshot.');
$reinstall = CloudTemplateCatalogService::applyProvisioningSnapshot([
'template_id' => 'debian-12-template', 'startup_script' => 'tenant supplied',
], false);
$assert(!array_key_exists('startup_script', $reinstall)
&& $reinstall['template_revision'] === 2
&& $reinstall['template_generation_token'] === $generation,
'Reinstall received a first-install script or lost immutable template identity.');
$expect(static fn () => CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', 'stale overwrite', 1, $generation
), 409, 'Stale startup-script revision was accepted.');
foreach (["echo\0bad", str_repeat('中', 10923), ["echo bad"]] as $invalid) {
$expect(static fn () => CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', $invalid, 2, $generation
), 422, 'Invalid startup-script content was accepted.');
}
$cleared = CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', '', 2, $generation
);
$assert($cleared['startup_script'] === '' && $cleared['revision'] === 3,
'An empty script did not disable first-boot execution.');
$operationBeforeBlockedMutation = (string) CloudTemplateReplica::query()
->where('host_id', 1)->where('template_id', 'debian-12-template')
->value('operation_id');
foreach (['importing', 'error'] as $blockedState) {
Capsule::table('cloud_templates')->where('id', 'debian-12-template')
->update(['state' => $blockedState]);
$expect(static fn () => CloudTemplateCatalogService::rename(
'debian-12-template', 'Blocked rename', 3, $generation, $actor
), 409, 'A non-active template was renamed.');
$expect(static fn () => CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', 'blocked script', 3, $generation
), 409, 'A non-active template startup script was changed.');
$blocked = CloudTemplate::find('debian-12-template');
$assert((int) $blocked->revision === 3
&& (string) $blocked->name === 'Debian 12'
&& (string) $blocked->startup_script === ''
&& (string) CloudTemplateReplica::query()->where('host_id', 1)
->where('template_id', 'debian-12-template')
->value('operation_id') === $operationBeforeBlockedMutation,
'A blocked metadata mutation changed template or replica identity.');
}
Capsule::table('cloud_templates')->where('id', 'debian-12-template')
->update(['state' => 'active']);
$public = CloudTemplateCatalogService::publicCatalog()['templates'][0];
$adminCatalog = CloudTemplateCatalogService::adminCatalog();
$admin = $adminCatalog['templates'][0];
$assert($public['offer_ids'] === [1] && $public['region_ids'] === [1],
'Tenant catalog did not expose its public offer and region availability.');
foreach (['startup_script', 'startup_script_configured', 'revision',
'generation_token', 'source_url', 'sealed_source_url', 'sha256', 'replicas']
as $privateField) {
$assert(!array_key_exists($privateField, $public),
'Tenant catalog exposed private template field: ' . $privateField);
}
$assert($admin['startup_script_configured'] === false
&& !array_key_exists('startup_script', $admin)
&& !array_key_exists('source_type', $admin)
&& !array_key_exists('sealed_source_url', $admin)
&& count($adminCatalog['hosts']) === 2
&& $adminCatalog['hosts'][0]['eligible'] === true
&& $adminCatalog['hosts'][1]['eligible'] === false
&& count($admin['replicas']) === 2
&& $admin['replicas'][0]['host_id'] === 1
&& $admin['replicas'][0]['state'] === 'active'
&& $admin['replicas'][0]['exact'] === true
&& $admin['replicas'][0]['repair_action'] === null
&& $admin['replicas'][0]['repair_reason'] === 'exact'
&& $admin['replicas'][1]['host_id'] === 2
&& $admin['replicas'][1]['state'] === 'missing'
&& $admin['replicas'][1]['host_eligible'] === false
&& $admin['replicas'][1]['repair_action'] === null
&& $admin['replicas'][1]['repair_reason'] === 'host_ineligible'
&& $admin['replica_summary'] === [
'hosts' => 2, 'eligible' => 1, 'ready' => 1,
'repairable' => 0, 'attention' => 0,
],
'Admin catalog must show script state without returning script content.');
$row = CloudTemplate::find('debian-12-template');
$replica = CloudTemplateReplica::query()->where('host_id', 1)
->where('template_id', 'debian-12-template')->first();
$assert((string) $row->generation_token === $generation,
'Template generation token changed after script mutations.');
$assert($replica !== null && (int) $replica->revision === 3
&& (string) $replica->generation_token === $generation
&& (string) $replica->state === 'active',
'Startup-script CAS did not keep the active Agent replica revision aligned.');
echo "PHP template catalog and startup-script CAS contract passed.\n";