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/CloudHostStorageConfigurati...

250 lines
11 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Controllers\CloudAdminController;
use App\Models\CloudHostAgent;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudHostStorageConfigurationService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
use Slim\Http\Environment;
use Slim\Http\Request;
use Slim\Http\Response;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectError = static function (callable $action, int $status,
string $message) use ($assert): void {
try {
$action();
} catch (CloudError $error) {
$assert($error->httpStatus === $status, $message);
return;
}
throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->string('region');
$table->string('country_code', 2);
$table->boolean('enabled');
$table->string('default_network');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_host_agents', static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->text('sealed_api_secret');
$table->boolean('enabled')->default(false);
$table->integer('revision')->default(1);
$table->integer('tested_revision')->default(0);
$table->string('last_test_status')->default('never');
$table->string('last_error_code')->default('');
$table->string('last_agent_version')->default('');
$table->integer('last_tested_at')->default(0);
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_host_storage_configurations',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->integer('revision')->default(0);
foreach (['managed', 'template', 'seed', 'user_iso', 'rescue'] as $role) {
$table->text($role . '_directory');
}
$table->string('state')->default('applying');
$table->string('operation_id')->nullable()->unique();
$table->integer('created_at');
$table->integer('updated_at');
});
Capsule::table('cloud_hosts')->insert([
'id' => 1, 'name' => 'Host A', 'region' => 'HongKong',
'country_code' => 'HK', 'enabled' => 1, 'default_network' => 'bridge:br0',
'created_at' => 1, 'updated_at' => 1,
]);
$actor = [
'user_id' => 1, 'is_admin' => true, 'is_super_admin' => true,
'can_manage' => true, 'session_id' => 'test',
];
$first = [
'expected_revision' => 0,
'managed_directory' => '/srv/virt/disks',
'template_directory' => '/srv/virt/templates',
'seed_directory' => '/srv/virt/seeds',
'user_iso_directory' => '/srv/virt/user-isos',
'rescue_directory' => '/srv/virt/rescue-isos',
];
$empty = CloudHostStorageConfigurationService::read(1);
$assert($empty['state'] === 'unconfigured' && $empty['revision'] === 0,
'An unregistered host did not return the panel database state.');
foreach (['GET', 'PUT'] as $method) {
foreach (['is_admin', 'is_super_admin', 'can_manage'] as $permission) {
$request = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => $method,
'REQUEST_URI' => '/api/v1/admin/hosts/1/storage-configuration',
]))->withAttribute('cloud_actor', array_replace($actor,
[$permission => false]));
$expectError(fn () => (new CloudAdminController())
->hostStorageConfiguration($request, new Response(), ['id' => 1]),
403, "Storage $method accepted an actor without $permission.");
}
}
$expectError(fn () => CloudHostStorageConfigurationService::save(1, $first, $actor),
409, 'Storage paths were saved without an Agent.');
$assert(Capsule::table('cloud_host_storage_configurations')->count() === 0,
'A host without Agent enrollment persisted storage paths.');
Capsule::table('cloud_host_agents')->insert([
'host_id' => 1, 'sealed_api_secret' => 'invalid-test-secret',
'enabled' => 1, 'revision' => 1, 'tested_revision' => 1,
'last_test_status' => 'healthy', 'last_error_code' => '',
'last_agent_version' => 'test-1', 'last_tested_at' => 1,
'created_at' => 1, 'updated_at' => 1,
]);
$failed = CloudHostStorageConfigurationService::save(1, $first, $actor);
$assert($failed['state'] === 'failed' && $failed['revision'] === 1
&& preg_match('/^[a-f0-9]{32}$/D', $failed['operation_id']) === 1,
'A proven pre-dispatch failure did not retain editable paths.');
$setting = CloudHostAgent::find(1);
$assert($setting->revision === 2 && $setting->tested_revision === 0
&& $setting->last_test_status === 'never'
&& $setting->last_error_code === '' && $setting->last_agent_version === ''
&& $setting->last_tested_at === 0 && !$setting->isReady(),
'Storage registration did not revoke the prior Agent capability test.');
$expectError(fn () => CloudHostStorageConfigurationService::save(1, $first, $actor),
409, 'A stale storage revision was accepted.');
$second = $first;
$second['expected_revision'] = 1;
$second['managed_directory'] = '/srv/virt/vm-disks';
$changed = CloudHostStorageConfigurationService::save(1, $second, $actor);
$assert($changed['state'] === 'failed' && $changed['revision'] === 2,
'Pre-dispatch paths could not be corrected optimistically.');
$overlap = $second;
$overlap['expected_revision'] = 2;
$overlap['template_directory'] = '/srv/virt/vm-disks/templates';
$expectError(fn () => CloudHostStorageConfigurationService::save(1, $overlap, $actor),
422, 'Overlapping storage directories were accepted.');
$operationIdForDispatch = new ReflectionMethod(
CloudHostStorageConfigurationService::class, 'operationIdForDispatch'
);
$row = (object) [
'state' => 'uncertain', 'operation_id' => str_repeat('a', 32),
];
$assert($operationIdForDispatch->invoke(null, $row, true)
=== str_repeat('a', 32),
'An uncertain same-path dispatch lost its operation ID.');
$row->state = 'failed';
$assert($operationIdForDispatch->invoke(null, $row, true)
!== str_repeat('a', 32),
'A terminal failure did not receive a new operation ID.');
$safeOperationId = str_repeat('b', 32);
Capsule::table('cloud_host_storage_configurations')->where('host_id', 1)
->update(['state' => 'applying', 'operation_id' => $safeOperationId]);
$dispatchedChange = $second;
$dispatchedChange['template_directory'] = '/srv/virt/other-templates';
$expectError(fn () => CloudHostStorageConfigurationService::save(1, $dispatchedChange, $actor),
409, 'A dispatched storage layout was mutable.');
$applyOperation = new ReflectionMethod(
CloudHostStorageConfigurationService::class, 'applyOperation'
);
$safeFailure = $applyOperation->invoke(null, 1, $safeOperationId, 2, [
'operation_id' => $safeOperationId,
'status' => 'failed',
'cause_code' => 'storage_directory_invalid',
]);
$assert($safeFailure->state === 'failed'
&& $safeFailure->operation_id === $safeOperationId,
'A proven pre-libvirt failure did not unlock path correction.');
$result = ['configured' => true];
$successOperationId = str_repeat('c', 32);
Capsule::table('cloud_host_storage_configurations')->where('host_id', 1)
->update(['state' => 'applying', 'operation_id' => $successOperationId]);
$applied = $applyOperation->invoke(null, 1, $successOperationId, 2, [
'operation_id' => $successOperationId,
'status' => 'succeeded', 'result' => $result,
]);
$assert($applied->state === 'applied',
'An explicit Agent confirmation was not applied.');
$lateTimeout = $applyOperation->invoke(null, 1, $successOperationId, 2, [
'operation_id' => $successOperationId, 'status' => 'running',
]);
$assert($lateTimeout->state === 'applied',
'A late concurrent response downgraded an applied configuration.');
$invalidOperationId = str_repeat('d', 32);
Capsule::table('cloud_host_storage_configurations')->where('host_id', 1)
->update(['state' => 'applying', 'operation_id' => $invalidOperationId]);
$invalid = $applyOperation->invoke(null, 1, $invalidOperationId, 2, [
'operation_id' => $invalidOperationId, 'status' => 'succeeded',
'result' => ['configured' => false],
]);
$assert($invalid->state === 'uncertain'
&& $invalid->operation_id === $invalidOperationId,
'A success result without configured=true was trusted.');
$definitiveFailure = $applyOperation->invoke(null, 1, $invalidOperationId, 2, [
'operation_id' => $invalidOperationId, 'status' => 'failed',
'cause_code' => 'storage_pool_path_conflict',
]);
$assert($definitiveFailure->state === 'failed',
'A definitive Agent failure did not reach a terminal state.');
$corrected = $second;
$corrected['expected_revision'] = 2;
$corrected['template_directory'] = '/srv/virt/corrected-templates';
$correctedResult = CloudHostStorageConfigurationService::save(
1, $corrected, $actor
);
$assert($correctedResult['revision'] === 3
&& $correctedResult['template_directory']
=== '/srv/virt/corrected-templates',
'A definitively failed registration permanently locked its paths.');
Capsule::table('cloud_host_storage_configurations')->where('host_id', 1)
->update(['state' => 'applied', 'operation_id' => $successOperationId]);
$corrected['expected_revision'] = 3;
$same = CloudHostStorageConfigurationService::save(1, $corrected, $actor);
$assert($same['configured'] === true && !array_key_exists('pools', $same),
'An exact applied resubmission was not idempotent.');
$locked = $corrected;
$locked['managed_directory'] = '/srv/virt/other-disks';
$expectError(fn () => CloudHostStorageConfigurationService::save(1, $locked, $actor),
409, 'Applied storage directories were mutable.');
$assert(CloudHostStorageConfigurationService::read(1)['requires_agent_retest'],
'Applied storage with an untested Agent did not require a retest.');
$setting = CloudHostAgent::find(1);
$setting->tested_revision = $setting->revision;
$setting->last_test_status = 'healthy';
$setting->save();
foreach (['bridge:br0' => false, 'public' => true, 'network:default' => false] as $network => $retest) {
Capsule::table('cloud_hosts')->where('id', 1)->update(['default_network' => $network]);
$assert(CloudHostStorageConfigurationService::read(1)['requires_agent_retest'] === $retest,
'Storage retest hint disagrees with canonical network: ' . $network);
}
echo "Host storage configuration state and path validation passed.\n";