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

315 lines
12 KiB
PHP

<?php
namespace App\Services {
final class Config
{
public static string $key = '';
public static function get($name, $default = null)
{
return $name === 'cloud_data_key' ? self::$key : $default;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudTemplate;
use App\Models\CloudTemplateArtifact;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudTemplateArtifactManager;
use App\Services\Config;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
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);
}
};
Config::$key = base64_encode(str_repeat('t', 32));
$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');
$table->string('state');
$table->integer('active_job_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$capsule->schema('default')->create('cloud_template_artifacts',
static function (Blueprint $table): void {
$table->string('template_id')->primary();
$table->integer('storage_revision');
$table->text('sealed_storage_runtime');
$table->string('object_key')->unique();
$table->string('object_version_id')->default('');
$table->string('object_etag');
$table->integer('size_bytes');
$table->string('sha256');
$table->string('state');
$table->string('error_code')->default('');
$table->string('delete_operation_id')->default('');
$table->integer('delete_generation')->default(0);
$table->integer('delete_cycle_attempts')->default(0);
$table->integer('delete_presence_confirmations')->default(0);
$table->integer('delete_last_checked_at')->default(0);
$table->integer('delete_next_check_at')->default(0);
$table->integer('delete_attention_at')->nullable();
$table->integer('verified_at');
$table->integer('created_at');
$table->integer('updated_at');
});
$path = tempnam(sys_get_temp_dir(), 'virt-template-artifact-');
if ($path === false) {
throw new RuntimeException('Cannot create temporary template fixture.');
}
register_shutdown_function(static function () use ($path): void {
@unlink($path);
});
file_put_contents($path, str_repeat('immutable-template-', 1024));
$bytes = filesize($path);
$sha256 = hash_file('sha256', $path);
$history = [];
$stack = HandlerStack::create(new MockHandler([
new Response(200, [
'ETag' => '"template-etag"',
'x-amz-version-id' => 'template-version-1',
]),
new Response(200, [
'Content-Length' => (string) $bytes,
'ETag' => '"template-etag"',
'x-amz-version-id' => 'template-version-1',
]),
]));
$stack->push(Middleware::history($history));
$client = new CloudObjectStorageS3Client(new Client([
'handler' => $stack,
]));
$runtime = [
'config' => [
'endpoint' => 'https://objects.example.com',
'region' => 'ewr',
'bucket' => 'template-bucket',
'prefix' => 'virt-cloud',
'path_style' => true,
],
'credentials' => [
'access_key_id' => 'TEMPLATEACCESSKEY',
'secret_access_key' => 'template-secret',
],
'revision' => 7,
];
$templateId = 'debian-13-immutable';
$generation = str_repeat('a', 32);
$template = new CloudTemplate();
foreach ([
'id' => $templateId,
'catalog_key' => 'debian-13',
'version_label' => '20261030-test',
'is_default' => 0,
'name' => 'Debian 13',
'os_family' => 'Debian',
'os_version' => '13',
'image_bytes' => $bytes,
'sha256' => $sha256,
'startup_script' => '',
'revision' => 1,
'generation_token' => $generation,
'state' => 'preparing',
'active_job_id' => null,
'created_at' => time(),
'updated_at' => time(),
] as $field => $value) {
$template->{$field} = $value;
}
$template->save();
CloudTemplateArtifactManager::reserveLocked($template, $runtime);
$artifact = CloudTemplateArtifactManager::publishReserved(
$template,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
$client
);
$request = $history[0]['request'];
$assert($request->getMethod() === 'PUT'
&& str_contains((string) $request->getUri(),
'/template-bucket/virt-cloud/cloud-templates/'
. $templateId . '/' . $generation . '/system.qcow2')
&& $request->getHeaderLine('If-None-Match') === '*'
&& $request->getHeaderLine('X-Amz-Content-Sha256') === $sha256
&& (string) $artifact->object_version_id === 'template-version-1'
&& (int) $artifact->storage_revision === 7,
'Immutable template publication lost its object identity or guard.');
$source = CloudTemplateArtifactManager::downloadSource($template, $client);
$assert($source['source_size_bytes'] === $bytes
&& $source['sha256'] === $sha256
&& str_contains($source['source_url'],
'versionId=template-version-1')
&& count($history) === 2
&& $history[1]['request']->getMethod() === 'HEAD',
'Template download capability did not bind the frozen provider version.');
$reserveTemplate = static function (
string $id,
string $generation
) use ($bytes, $sha256, $runtime): CloudTemplate {
$row = new CloudTemplate();
foreach ([
'id' => $id,
'catalog_key' => 'debian-13',
'version_label' => '20261030-' . substr($id, -8),
'is_default' => 0,
'name' => 'Debian 13 ' . $id,
'os_family' => 'Debian',
'os_version' => '13',
'image_bytes' => $bytes,
'sha256' => $sha256,
'startup_script' => '',
'revision' => 1,
'generation_token' => $generation,
'state' => 'preparing',
'active_job_id' => null,
'created_at' => time(),
'updated_at' => time(),
] as $field => $value) {
$row->{$field} = $value;
}
$row->save();
CloudTemplateArtifactManager::reserveLocked($row, $runtime);
return $row;
};
$uncertainTemplate = $reserveTemplate(
'debian-13-reconciled',
str_repeat('b', 32)
);
$uncertainHistory = [];
$uncertainStack = HandlerStack::create(new MockHandler([
new ConnectException(
'simulated lost PUT response',
new Request('PUT', 'https://objects.example.com')
),
new Response(200, [
'Content-Length' => (string) $bytes,
'ETag' => '"reconciled-etag"',
'x-amz-version-id' => 'reconciled-version-1',
]),
]));
$uncertainStack->push(Middleware::history($uncertainHistory));
$reconciled = CloudTemplateArtifactManager::publishReserved(
$uncertainTemplate,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
new CloudObjectStorageS3Client(new Client([
'handler' => $uncertainStack,
]))
);
$assert((string) $reconciled->state === 'ready'
&& (string) $reconciled->object_etag === '"reconciled-etag"'
&& (string) $reconciled->object_version_id
=== 'reconciled-version-1'
&& count($uncertainHistory) === 2
&& $uncertainHistory[0]['request']->getMethod() === 'PUT'
&& $uncertainHistory[1]['request']->getMethod() === 'HEAD',
'Unknown immutable PUT effect was not reconciled from exact object identity.');
$absentTemplate = $reserveTemplate(
'debian-13-absent',
str_repeat('c', 32)
);
$absentStack = HandlerStack::create(new MockHandler([
new ConnectException(
'simulated lost PUT response',
new Request('PUT', 'https://objects.example.com')
),
new Response(404),
]));
try {
CloudTemplateArtifactManager::publishReserved(
$absentTemplate,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
new CloudObjectStorageS3Client(new Client([
'handler' => $absentStack,
]))
);
throw new RuntimeException('Absent unknown PUT unexpectedly succeeded.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Proven absent PUT returned an unsafe status.');
}
$absentTemplate->refresh();
$absentArtifact = CloudTemplateArtifact::find(
(string) $absentTemplate->id
);
$assert((string) $absentTemplate->state === 'source_failed'
&& (string) $absentArtifact?->state === 'failed',
'Proven absent PUT remained permanently fenced.');
$unavailableTemplate = $reserveTemplate(
'debian-13-unavailable',
str_repeat('d', 32)
);
$unavailableStack = HandlerStack::create(new MockHandler([
new ConnectException(
'simulated lost PUT response',
new Request('PUT', 'https://objects.example.com')
),
new ConnectException(
'simulated unavailable HEAD',
new Request('HEAD', 'https://objects.example.com')
),
]));
try {
CloudTemplateArtifactManager::publishReserved(
$unavailableTemplate,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
new CloudObjectStorageS3Client(new Client([
'handler' => $unavailableStack,
]))
);
throw new RuntimeException(
'Unverifiable unknown PUT unexpectedly succeeded.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Unverifiable PUT returned an unsafe status.');
}
$unavailableTemplate->refresh();
$unavailableArtifact = CloudTemplateArtifact::find(
(string) $unavailableTemplate->id
);
$assert((string) $unavailableTemplate->state === 'source_unknown'
&& (string) $unavailableArtifact?->state === 'unknown'
&& (string) $unavailableArtifact?->error_code
=== 'template_source_reconcile_unavailable',
'Unavailable reconciliation did not retain the immutable object fence.');
echo "Immutable cloud-template artifact contract passed.\n";
}