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

207 lines
10 KiB
PHTML

<?php
use App\Services\Cloud\CloudAdminResourceService;
use App\Services\Cloud\CloudError;
use App\Models\CloudHostAgent;
require dirname(__DIR__) . '/vendor/autoload.php';
$root = dirname(__DIR__);
$source = file_get_contents(
$root . '/app/Services/Cloud/CloudAdminResourceService.php'
);
if (!is_string($source)) {
throw new RuntimeException('Unable to read CloudAdminResourceService.php');
}
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$assert(str_contains(
$source,
"private const VIEWS = ['topology', 'capacity', 'reservations', 'traffic']"
)
&& str_contains($source, "'topology' => self::topology(")
&& str_contains($source, "'effective_state' => \$effective['state']")
&& str_contains($source, "'effective_state_label' => self::effectiveStateLabel(")
&& str_contains($source, "'blockers' => \$effective['blockers']")
&& str_contains($source, "'placement_capacity' => \$placementCapacity")
&& str_contains($source, "'default_line_id' =>"),
'Resource projection must expose the new topology, health and human-state contract.');
$assert(str_contains($source, 'CloudHostAgent::whereIn(')
&& str_contains($source, 'CloudHostStorageConfiguration::whereIn(')
&& str_contains($source, '$agent !== null && $agent->isReady()')
&& str_contains($source, '$storage !== null && $storage->isApplied()')
&& str_contains($source, '$networkReadyByHostLine')
&& str_contains($source,
"->where('network_attachment.verification_state', 'verified')")
&& str_contains($source, 'CloudAgentSettingsService::testedNetworkSelectors(')
&& str_contains($source, '$row->verified_agent_revision')
&& !str_contains($source, 'CloudNetworkSelector::isValid(')
&& !str_contains($source,
"->whereColumn('network_attachment.network_selector',")
&& !str_contains($source,
"->where('network_attachment.sync_state', 'applied')")
&& str_contains($source, "'placement_ready_host_count'"),
'Placement readiness must include Agent, storage, exact-line network and capacity gates without default-network authority.');
$assert(str_contains($source, 'foreach ($memberships as $membership)')
&& str_contains($source,
'$poolHosts[(int) $membership->resource_pool_id][]')
&& str_contains($source, "'membership_id' => (int) \$membership->id")
&& str_contains($source, "'capacity_scope' => 'shared_host'")
&& str_contains($source, 'self::platformHostSummary('),
'Each membership must map to its exact pool while platform capacity uses a physical-host summary.');
$assert(str_contains($source, "'regions_total' =>")
&& str_contains($source, "'lines_total' =>")
&& str_contains($source, "'pools_total' =>")
&& str_contains($source, "'placement_ready_pools' =>")
&& str_contains($source, "'placement_ready_hosts' =>")
&& str_contains($source, "'uncertain_reservations' =>")
&& !str_contains($source, "'active_pools' =>")
&& !str_contains($source, "'schedulable_hosts' =>")
&& !str_contains($source, "'schedulable_host_count' =>")
&& !str_contains($source, "'sync_state' =>")
&& !str_contains($source, 'locked_reservation'),
'The clean-install projection must not retain misleading or retired field names.');
$settingsLockPosition = strpos($source,
'CloudNetworkLineFeature::lockedEnabled();');
$settingsRegionLockPosition = strpos($source,
"\$regions = CloudRegion::orderBy('id')->lockForUpdate()",
$settingsLockPosition === false ? 0 : $settingsLockPosition);
$assert(str_contains($source, '$isNew = !$region->exists;')
&& str_contains($source,
'$createDefaultLine = !CloudNetworkLineFeature::lockedEnabled();')
&& str_contains($source, '$region->getConnection()->transaction(')
&& str_contains($source, "\$line->code = 'default';")
&& str_contains($source, "\$line->name = '默认线路';")
&& str_contains($source, '$line->is_default = true;')
&& str_contains($source, "\$line->status = 'active';")
&& str_contains($source, 'if (!$enabled && $activeDefaults->count() === 0)')
&& str_contains($source, "\$default->code = 'default';")
&& str_contains($source, 'CloudNetworkLineFeature::save($enabled);')
&& $settingsLockPosition !== false
&& $settingsRegionLockPosition !== false
&& $settingsLockPosition < $settingsRegionLockPosition,
'Hidden-line mode must serialize on the feature row, then atomically create or backfill an active default line for every region.');
$reflection = new ReflectionClass(CloudAdminResourceService::class);
$selection = $reflection->getMethod('capacitySelection');
$catalog = ['pools' => [
['id' => 1, 'effective_state' => 'ready',
'placement_capacity' => ['cpu' => ['free' => 4], 'ip' => ['free' => 0]]],
['id' => 2, 'effective_state' => 'blocked',
'placement_capacity' => ['cpu' => ['free' => 0], 'ip' => ['free' => 2]]],
], 'hosts' => [['id' => 10, 'placement_ready' => true],
['id' => 11, 'placement_ready' => false]]];
$assert(array_column($selection->invoke(null, $catalog, 'ready_pools')['capacity_pools'], 'id') === [1]
&& array_column($selection->invoke(null, $catalog, 'ready_hosts')['capacity_hosts'], 'id') === [10]
&& count($selection->invoke(null, $catalog, 'hosts')['capacity_hosts']) === 2
&& array_column($selection->invoke(null, $catalog, 'cpu')['capacity_pools'], 'id') === [1]
&& array_column($selection->invoke(null, $catalog, 'ip')['capacity_pools'], 'id') === [2],
'Summary shortcuts must use placement readiness and usable capacity, not generic online status.');
$entityCode = $reflection->getMethod('entityCode');
$newModel = (object) ['exists' => false, 'code' => ''];
$generated = $entityCode->invoke(null, [], $newModel, 'region', '东京', 32,
'地区系统标识');
$assert(preg_match('/^region-[a-f0-9]{8}$/D', $generated) === 1,
'Non-ASCII names must receive a safe server-generated system identifier.');
$custom = $entityCode->invoke(null, ['code' => 'Tokyo-Core'], $newModel,
'region', '东京', 32, '地区系统标识');
$assert($custom === 'tokyo-core',
'A custom create-time system identifier must be normalized once.');
$existingModel = (object) ['exists' => true, 'code' => 'tokyo-core'];
$assert($entityCode->invoke(null, [], $existingModel, 'region', '东京', 32,
'地区系统标识') === 'tokyo-core',
'Reading an existing immutable system identifier must preserve it.');
$immutableRejected = false;
try {
$entityCode->invoke(null, ['code' => 'replacement'], $existingModel,
'region', '东京', 32, '地区系统标识');
} catch (CloudError $error) {
$immutableRejected = $error->httpStatus === 409;
}
$assert($immutableRejected,
'PATCH-style writes must reject system identifier replacement.');
$health = [
'host_count' => 1,
'enabled_host_count' => 1,
'scheduler_active_host_count' => 1,
'agent_ready_host_count' => 1,
'storage_ready_host_count' => 1,
'network_ready_host_count' => 1,
'capacity_ready_host_count' => 1,
'placement_ready_host_count' => 1,
];
$poolState = $reflection->getMethod('poolEffectiveState');
$line = (object) ['status' => 'active', 'is_default' => true];
$region = (object) ['status' => 'active'];
$ready = $poolState->invoke(null, 'active', $line, $region, false, $health);
$assert($ready['state'] === 'ready' && $ready['blockers'] === [],
'A pool is ready only when one host passes every base placement gate.');
$effectiveStateLabel = $reflection->getMethod('effectiveStateLabel');
$assert($effectiveStateLabel->invoke(null, 'ready') === '基础就绪',
'Base health must not claim request-specific offer and template readiness.');
$health['agent_ready_host_count'] = 0;
$health['placement_ready_host_count'] = 0;
$blocked = $poolState->invoke(null, 'active', $line, $region, false, $health);
$blockerCodes = array_column($blocked['blockers'], 'code');
$assert($blocked['state'] === 'blocked'
&& in_array('agent_not_ready', $blockerCodes, true)
&& in_array('no_placement_ready_hosts', $blockerCodes, true),
'A pool with an unavailable Agent must explain why it cannot place instances.');
$emptyCapacity = $reflection->getMethod('emptyCapacity');
$hostCapacity = $emptyCapacity->invoke(null);
foreach (['cpu' => 16, 'memory' => 32768, 'disk' => 800] as $key => $value) {
foreach (['configured', 'allocatable', 'free'] as $field) {
$hostCapacity[$key][$field] = $value;
}
$hostCapacity['max_host_free'][$key] = $value;
}
$hostCapacity['ip']['total'] = 4;
$hostCapacity['ip']['free'] = 4;
$hostCapacity['max_host_free']['ip'] = 4;
$platformSummary = $reflection->getMethod('platformHostSummary')->invoke(
null,
[7 => $hostCapacity],
[7 => [10 => ['total' => 2, 'allocated' => 0, 'reserved' => 0,
'disabled' => 0, 'free' => 2], 11 => ['total' => 2,
'allocated' => 0, 'reserved' => 0, 'disabled' => 0, 'free' => 2]]],
[7 => true],
[7 => [10 => true, 11 => true]],
[7 => true]
);
$assert($platformSummary['hosts_total'] === 1
&& $platformSummary['placement_ready_hosts'] === 1
&& $platformSummary['capacity']['cpu']['configured'] === 16
&& $platformSummary['placement_capacity']['cpu']['configured'] === 16
&& $platformSummary['placement_capacity']['ip']['free'] === 4,
'A host exposed through several memberships must contribute physical capacity exactly once.');
$agent = new CloudHostAgent();
$agent->enabled = true;
$agent->revision = 4;
$agent->tested_revision = 4;
$agent->last_test_status = 'healthy';
$agent->network_selectors_json = '["bridge:br-premium"]';
$selectorEvidence = $reflection->getMethod('agentSelectorEvidenceReady');
$assert($selectorEvidence->invoke(
null, $agent, 'bridge:br-premium', 4
) === true
&& $selectorEvidence->invoke(
null, $agent, 'bridge:br-missing', 4
) === false
&& $selectorEvidence->invoke(
null, $agent, 'bridge:br-premium', 3
) === false,
'Network readiness must require current Agent revision and selector evidence.');
echo "Administrator resource projection contracts passed.\n";