From aa408ed8bc1faf4452aeee79f5b5b74de20731d9 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 2 Nov 2026 20:20:55 +0800 Subject: [PATCH] feat: support multiple host pool memberships --- web/app/Command/CloudSetup.php | 6 +- web/app/Controllers/CloudAdminController.php | 37 +- web/app/Middleware/CloudApi.php | 2 +- .../CloudHostResourcePoolMembership.php | 1 + .../Cloud/CloudAdminHostProjectionService.php | 473 ++++++++++---- .../Cloud/CloudAdminHostSchedulingService.php | 603 +++++++++++++----- .../Cloud/CloudAdminResourceService.php | 172 +++-- .../Cloud/CloudHostPoolMembershipService.php | 231 ++++--- web/config/routes_cloud.php | 3 + web/public/cloud/admin-hosts.js | 165 ++++- .../views/venix/admin/hosts/index.tpl | 50 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/sql/cloud.sql | 10 +- web/tests/AdminHostSchedulingBehaviorTest.mjs | 187 ++++++ web/tests/AdminHostSchedulingContractTest.php | 172 ++--- .../AdminResourceProjectionContractTest.php | 69 +- .../AdminResourceProjectionWorkflowTest.php | 1 + .../CloudAdminHostListProjectionTest.php | 10 +- ...AdminHostMultiMembershipProjectionTest.php | 364 +++++++++++ ...oudAdminHostMultiMembershipServiceTest.php | 334 ++++++++++ .../CloudAdminHostNetworkServiceTest.php | 1 + web/tests/CloudAdminVpcControlServiceTest.php | 1 + .../CloudAggregateRecoveryConvergenceTest.php | 1 + web/tests/CloudFinancialWorkflowTest.php | 2 +- web/tests/CloudFreshSchemaContractTest.php | 2 +- .../CloudHostNetworkAttachmentServiceTest.php | 1 + .../CloudMultiHostSchemaDefinitionTest.php | 4 +- ...oudMultiPublicPoolSchemaDefinitionTest.php | 6 + web/tests/CloudPlanUpgradeServiceTest.php | 1 + ...CloudPortableBackupSameHostRestoreTest.php | 1 + .../CloudRescueCatalogSchemaContractTest.php | 2 +- web/tests/CloudTemplateCatalogTest.php | 1 + .../CloudTemplateImportIntentContractTest.php | 2 +- .../CloudTemplateRegionalAvailabilityTest.php | 1 + .../CloudTrafficPoolSchemaContractTest.php | 2 +- .../CloudVpcHostRetirementServiceTest.php | 1 + web/tests/CloudVpcSchemaContractTest.php | 2 +- web/tests/CloudVpcServiceTest.php | 1 + 38 files changed, 2373 insertions(+), 551 deletions(-) create mode 100644 web/tests/AdminHostSchedulingBehaviorTest.mjs create mode 100644 web/tests/CloudAdminHostMultiMembershipProjectionTest.php create mode 100644 web/tests/CloudAdminHostMultiMembershipServiceTest.php diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index 46942caf..0919d2c3 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v25-network-attachments'; + private const SCHEMA_VERSION = 'go-agent-wss-v26-multi-pool-memberships'; private const MAIN_TABLES = [ 'cloud_regions', 'cloud_traffic_pool_groups', 'cloud_network_lines', 'cloud_resource_pools', @@ -70,6 +70,10 @@ final class CloudSetup 'observed_revision', 'sync_state', 'last_error_code', 'created_at', 'updated_at', ], + 'cloud_host_resource_pool_memberships' => [ + 'id', 'host_id', 'resource_pool_id', 'scheduler_state', + 'priority', 'weight', 'revision', 'created_at', 'updated_at', + ], 'cloud_traffic_pool_groups' => [ 'id', 'code', 'name', 'mode', 'revision', 'created_at', 'updated_at', diff --git a/web/app/Controllers/CloudAdminController.php b/web/app/Controllers/CloudAdminController.php index d1b530dd..0cae7756 100644 --- a/web/app/Controllers/CloudAdminController.php +++ b/web/app/Controllers/CloudAdminController.php @@ -138,12 +138,45 @@ final class CloudAdminController } else { $body = CloudInput::object($request); CloudInput::only($body, [ - 'resource_pool_id', 'scheduler_state', 'configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', ]); - $result = CloudAdminHostSchedulingService::save($hostId, $body); + $result = CloudAdminHostSchedulingService::saveCapacity( + $hostId, $body + ); + } + return $response->withJson($result) + ->withHeader('Cache-Control', 'no-store'); + } + + public function hostSchedulingMembership($request, $response, $args) + { + $this->actor($request, true); + $hostId = (int) ($args['id'] ?? 0); + $poolId = (int) ($args['resource_pool_id'] ?? 0); + $body = CloudInput::object($request); + if ($request->getMethod() === 'DELETE') { + CloudInput::only($body, ['expected_revision']); + $expectedRevision = filter_var( + $body['expected_revision'] ?? null, + FILTER_VALIDATE_INT + ); + if ($expectedRevision === false || $expectedRevision < 1) { + throw new CloudError( + '资源池成员关系版本无效,请刷新后重试' + ); + } + $result = CloudAdminHostSchedulingService::deleteMembership( + $hostId, $poolId, (int) $expectedRevision + ); + } else { + CloudInput::only($body, [ + 'scheduler_state', 'priority', 'weight', 'expected_revision', + ]); + $result = CloudAdminHostSchedulingService::saveMembership( + $hostId, $poolId, $body + ); } return $response->withJson($result) ->withHeader('Cache-Control', 'no-store'); diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php index 5ad67aa0..ace81f1a 100644 --- a/web/app/Middleware/CloudApi.php +++ b/web/app/Middleware/CloudApi.php @@ -25,7 +25,7 @@ final class CloudApi || preg_match('#^/api/v1/admin/traffic-pool-groups(?:/[1-9][0-9]*(?:/(?:lines|readiness))?)?$#D', $path) === 1 || preg_match('#^/api/v1/admin/vpc-control(?:/vpcs(?:/[1-9][0-9]*)?)?$#D', $path) === 1 || preg_match('#^/api/v1/admin/vpc-cidr-pools(?:/[1-9][0-9]*)?$#D', $path) === 1 - || preg_match('#^/api/v1/admin/hosts/[0-9]+/scheduling$#D', $path) === 1 + || preg_match('#^/api/v1/admin/hosts/[0-9]+/scheduling(?:/memberships/[1-9][0-9]*)?$#D', $path) === 1 || preg_match('#^/api/v1/admin/hosts/[1-9][0-9]*/network-attachments(?:/discover|/[0-9a-f]{32}(?:/test)?)?$#D', $path) === 1 || preg_match('#^/api/v1/admin/hosts/[1-9][0-9]*/vpc-transport(?:/(?:discover|test))?$#D', $path) === 1 || preg_match('#^/api/v1/admin/agents(?:/[1-9][0-9]*(?:/test)?)?$#D', $path) === 1 diff --git a/web/app/Models/CloudHostResourcePoolMembership.php b/web/app/Models/CloudHostResourcePoolMembership.php index 457b1cc8..aa722464 100644 --- a/web/app/Models/CloudHostResourcePoolMembership.php +++ b/web/app/Models/CloudHostResourcePoolMembership.php @@ -13,6 +13,7 @@ final class CloudHostResourcePoolMembership extends Model 'resource_pool_id' => 'int', 'priority' => 'int', 'weight' => 'int', + 'revision' => 'int', 'created_at' => 'int', 'updated_at' => 'int', ]; diff --git a/web/app/Services/Cloud/CloudAdminHostProjectionService.php b/web/app/Services/Cloud/CloudAdminHostProjectionService.php index d5286ed6..fd19dd18 100644 --- a/web/app/Services/Cloud/CloudAdminHostProjectionService.php +++ b/web/app/Services/Cloud/CloudAdminHostProjectionService.php @@ -45,16 +45,9 @@ final class CloudAdminHostProjectionService foreach ($memberships as $membership) { $membershipsByHost[(int) $membership->host_id][] = $membership; } - $selectedByHost = []; $poolIds = []; - foreach ($hosts as $host) { - $selected = CloudHostPoolMembershipService::selected( - $membershipsByHost[(int) $host->id] ?? [] - ); - $selectedByHost[(int) $host->id] = $selected; - if ($selected !== null) { - $poolIds[] = (int) $selected->resource_pool_id; - } + foreach ($memberships as $membership) { + $poolIds[] = (int) $membership->resource_pool_id; } $pools = self::keyById($poolIds === [] ? [] @@ -87,38 +80,39 @@ final class CloudAdminHostProjectionService 'host_id', $hostIds )->get()); $usage = CloudPanelUsageService::forHosts($hostIds); - $ipStats = self::ipStats($hostIds); + $ipStats = self::ipStats($hostIds, $agents); $flat = []; $groups = []; foreach ($hosts as $host) { $hostId = (int) $host->id; - $membership = $selectedByHost[$hostId] ?? null; - $pool = $membership === null ? null - : ($pools[(int) $membership->resource_pool_id] ?? null); - $line = $pool === null ? null - : ($lines[(int) $pool->line_id] ?? null); - $region = $line === null ? null - : ($regions[(int) $line->region_id] ?? null); - $lineIp = $line === null ? self::emptyIpStats() - : ($ipStats[$hostId][(int) $line->id] - ?? self::emptyIpStats()); + $hostMemberships = $membershipsByHost[$hostId] ?? []; + $primary = CloudHostPoolMembershipService::primary( + $hostMemberships + ); + $primaryPool = $primary === null ? null + : ($pools[(int) $primary->resource_pool_id] ?? null); + $primaryLine = $primaryPool === null ? null + : ($lines[(int) $primaryPool->line_id] ?? null); + $primaryRegion = $primaryLine === null ? null + : ($regions[(int) $primaryLine->region_id] ?? null); $row = self::hostDto( $host, - $membership, - $pool, - $line, - $region, + $hostMemberships, + $pools, + $lines, + $regions, $policies[$hostId] ?? null, $agents[$hostId] ?? null, $storage[$hostId] ?? null, $usage[$hostId] ?? CloudPanelUsageService::emptyUsage(), - $lineIp + $ipStats[$hostId] ?? [] ); $flat[] = $row; - $key = $region === null ? 'unclassified' : 'region:' . $region->id; + $key = $primaryRegion === null + ? 'unclassified' : 'region:' . $primaryRegion->id; if (!isset($groups[$key])) { - $groups[$key] = self::regionDto($region, $host); + $groups[$key] = self::regionDto($primaryRegion, $host); } $groups[$key]['hosts'][] = $row; self::addHostToGroup($groups[$key], $row); @@ -155,39 +149,107 @@ final class CloudAdminHostProjectionService public static function one(CloudHost $host): array { - $memberships = CloudHostResourcePoolMembership::where( - 'host_id', (int) $host->id - )->orderBy('resource_pool_id')->orderBy('id')->get(); - return self::basicDto($host, $memberships); + foreach (self::listing()['hosts'] as $row) { + if ((int) $row['id'] === (int) $host->id) { + return $row; + } + } + return self::basicDto($host, []); } private static function basicDto(CloudHost $host, iterable $memberships): array { - $selected = CloudHostPoolMembershipService::selected($memberships); - $state = (string) ($selected?->scheduler_state ?? 'disabled'); + $rows = []; + foreach ($memberships as $membership) { + $rows[] = $membership; + } + $primary = CloudHostPoolMembershipService::primary($rows); + $state = (string) ($primary?->scheduler_state ?? 'disabled'); $dto = $host->toArray(); - $dto['resource_pool_id'] = $selected === null - ? null : (int) $selected->resource_pool_id; + // Compact compatibility fields are a deterministic summary only. + // Every scheduling decision must use one exact memberships[] row. + $dto['resource_pool_id'] = $primary === null + ? null : (int) $primary->resource_pool_id; $dto['scheduler_state'] = in_array($state, self::SCHEDULER_STATES, true) ? $state : 'disabled'; + $dto['active_memberships'] = count(array_filter( + $rows, + static fn ($row): bool => + (string) $row->scheduler_state === 'active' + )); + $dto['draining_memberships'] = count(array_filter( + $rows, + static fn ($row): bool => + (string) $row->scheduler_state === 'draining' + )); return $dto; } - private static function hostDto(CloudHost $host, $membership, $pool, - $line, $region, $policy, ?CloudHostAgent $agent, + private static function hostDto(CloudHost $host, iterable $memberships, + array $pools, array $lines, array $regions, $policy, + ?CloudHostAgent $agent, ?CloudHostStorageConfiguration $storage, array $usage, - array $ip): array + array $ipByLine): array { - $base = self::basicDto($host, $membership === null - ? [] : [$membership]); - $scheduler = (string) $base['scheduler_state']; - $selectorReady = CloudNetworkSelector::isValid( - (string) $host->default_network - ); + $membershipModels = []; + foreach ($memberships as $membership) { + $membershipModels[] = $membership; + } + $base = self::basicDto($host, $membershipModels); + $primary = CloudHostPoolMembershipService::primary($membershipModels); $storageReady = $storage !== null && $storage->isApplied(); $agentReady = $agent !== null && $agent->isReady(); - $capacity = self::capacity($policy, $usage, $ip); + $aggregateIp = self::emptyIpStats(); + $countedLines = []; + $membershipRows = []; + $lineRows = []; + foreach ($membershipModels as $membership) { + $pool = $pools[(int) $membership->resource_pool_id] ?? null; + $line = $pool === null ? null + : ($lines[(int) $pool->line_id] ?? null); + $region = $line === null ? null + : ($regions[(int) $line->region_id] ?? null); + $lineId = $line === null ? null : (int) $line->id; + $lineIp = $lineId === null ? self::emptyIpStats() + : ($ipByLine[$lineId] ?? self::emptyIpStats()); + if ($lineId !== null && !isset($countedLines[$lineId])) { + self::addIpStats($aggregateIp, $lineIp); + $countedLines[$lineId] = true; + } + $membershipRows[] = self::membershipDto( + $membership, $pool, $line, $region, $lineIp + ); + if ($lineId !== null && !isset($lineRows[$lineId])) { + $lineRows[$lineId] = [ + 'id' => $lineId, + 'code' => (string) $line->code, + 'name' => (string) $line->name, + 'status' => (string) $line->status, + 'region_id' => $region === null ? null : (int) $region->id, + 'region_code' => $region === null + ? '' : (string) $region->code, + 'region_name' => $region === null + ? '地区已缺失' : (string) $region->name, + 'network_ready' => (int) $lineIp['available'] > 0, + 'ip' => $lineIp, + 'membership_count' => 0, + 'active_memberships' => 0, + 'draining_memberships' => 0, + 'placement_ready_memberships' => 0, + ]; + } + if ($lineId !== null) { + $lineRows[$lineId]['membership_count']++; + $state = (string) $membership->scheduler_state; + if ($state === 'active') { + $lineRows[$lineId]['active_memberships']++; + } elseif ($state === 'draining') { + $lineRows[$lineId]['draining_memberships']++; + } + } + } + $capacity = self::capacity($policy, $usage, $aggregateIp); $capacityConfigured = $policy !== null && $capacity['cpu']['configured'] > 0 && $capacity['memory']['configured'] > 0 @@ -198,57 +260,69 @@ final class CloudAdminHostProjectionService $maxInstances = (int) $capacity['instances']['max']; $instanceCount = (int) $capacity['instances']['allocated'] + (int) $capacity['instances']['reserved']; - $poolPathReady = $pool !== null && (string) $pool->status === 'active' - && $line !== null && (string) $line->status === 'active' - && $region !== null && (string) $region->status === 'active'; - $placementReady = (bool) $host->enabled - && $scheduler === 'active' && $poolPathReady && $selectorReady - && $agentReady && $storageReady && $capacityConfigured + $hostCapacityReady = $capacityConfigured && (int) $capacity['unknown_instances'] === 0 && ($maxInstances <= 0 || $instanceCount < $maxInstances) && $capacity['cpu']['free'] > 0 && $capacity['memory']['free'] > 0 - && $capacity['disk']['free'] > 0 - && $capacity['ip']['available'] > 0; + && $capacity['disk']['free'] > 0; + $placementReady = false; + $networkReady = false; + $primaryPlacement = null; + foreach ($membershipRows as &$membershipRow) { + $membershipRow['placement_ready'] = (bool) $host->enabled + && $membershipRow['scheduler_state'] === 'active' + && $membershipRow['path_ready'] + && $membershipRow['network_ready'] + && $agentReady && $storageReady && $hostCapacityReady; + if ($membershipRow['scheduler_state'] === 'active' + && $membershipRow['network_ready']) { + $networkReady = true; + } + if ($membershipRow['placement_ready']) { + $placementReady = true; + $lineId = $membershipRow['line_id']; + if ($lineId !== null && isset($lineRows[$lineId])) { + $lineRows[$lineId]['placement_ready_memberships']++; + } + } + if ($primary !== null + && (int) $membershipRow['id'] === (int) $primary->id) { + $primaryPlacement = $membershipRow; + } + } + unset($membershipRow); + $lineRows = array_values($lineRows); + usort($lineRows, static fn (array $left, array $right): int => + [$left['name'], $left['id']] <=> [$right['name'], $right['id']] + ); + $placement = self::compactPlacement($primaryPlacement); $attention = self::attention( $host, - $membership, - $pool, - $line, - $region, - $scheduler, - $selectorReady, + $membershipRows, $agentReady, $storageReady, $capacityConfigured, - $capacity + $capacity, + $networkReady ); - $country = CloudCountryCatalog::option((string) ($region?->country_code - ?? $host->country_code)); + $primaryRegionId = $primaryPlacement['region_id'] ?? null; + $primaryRegion = $primaryRegionId === null + ? null : ($regions[(int) $primaryRegionId] ?? null); + $country = CloudCountryCatalog::option((string) ( + $primaryRegion?->country_code ?? $host->country_code + )); return $base + [ + 'memberships' => $membershipRows, + 'lines' => $lineRows, 'location' => [ 'physical_label' => (string) $host->region, 'country_code' => $country['code'], 'country_name' => $country['name'], 'country_flag' => $country['flag'], ], - 'placement' => [ - 'region_id' => $region === null ? null : (int) $region->id, - 'region_code' => $region === null ? '' : (string) $region->code, - 'region_name' => $region === null ? '未分类节点' - : (string) $region->name, - 'region_status' => $region === null ? 'missing' - : (string) $region->status, - 'line_id' => $line === null ? null : (int) $line->id, - 'line_name' => $line === null ? '' : (string) $line->name, - 'line_status' => $line === null ? 'missing' - : (string) $line->status, - 'pool_id' => $pool === null ? null : (int) $pool->id, - 'pool_name' => $pool === null ? '' : (string) $pool->name, - 'pool_status' => $pool === null ? 'missing' - : (string) $pool->status, - ], + 'placement' => $placement, 'agent' => [ 'state' => self::agentState($agent), 'ready' => $agentReady, @@ -270,7 +344,12 @@ final class CloudAdminHostProjectionService : (int) $agent->updated_at, ], 'readiness' => [ - 'network_selector_ready' => $selectorReady, + 'network_ready' => $networkReady, + // Compatibility alias: this now reflects the deterministic + // primary membership's verified line, never default_network. + 'network_selector_ready' => (bool) ( + $primaryPlacement['network_ready'] ?? false + ), 'storage_ready' => $storageReady, 'capacity_configured' => $capacityConfigured, 'placement_ready' => $placementReady, @@ -281,6 +360,91 @@ final class CloudAdminHostProjectionService ]; } + private static function membershipDto($membership, $pool, $line, + $region, array $ip): array + { + $state = (string) $membership->scheduler_state; + if (!in_array($state, self::SCHEDULER_STATES, true)) { + $state = 'disabled'; + } + $pathReady = $pool !== null && (string) $pool->status === 'active' + && $line !== null && (string) $line->status === 'active' + && $region !== null && (string) $region->status === 'active'; + return [ + 'id' => (int) $membership->id, + 'resource_pool_id' => (int) $membership->resource_pool_id, + 'scheduler_state' => $state, + 'priority' => (int) $membership->priority, + 'weight' => (int) $membership->weight, + 'revision' => max(1, (int) $membership->revision), + 'region_id' => $region === null ? null : (int) $region->id, + 'region_code' => $region === null ? '' : (string) $region->code, + 'region_name' => $region === null + ? '地区已缺失' : (string) $region->name, + 'region_status' => $region === null + ? 'missing' : (string) $region->status, + 'line_id' => $line === null ? null : (int) $line->id, + 'line_code' => $line === null ? '' : (string) $line->code, + 'line_name' => $line === null ? '' : (string) $line->name, + 'line_status' => $line === null + ? 'missing' : (string) $line->status, + 'pool_id' => $pool === null ? null : (int) $pool->id, + 'pool_code' => $pool === null ? '' : (string) $pool->code, + 'pool_name' => $pool === null ? '' : (string) $pool->name, + 'pool_status' => $pool === null + ? 'missing' : (string) $pool->status, + 'path_ready' => $pathReady, + 'network_ready' => (int) $ip['available'] > 0, + 'ip' => $ip, + 'placement_ready' => false, + ]; + } + + private static function compactPlacement(?array $membership): array + { + if ($membership === null) { + return [ + 'membership_id' => null, + 'scheduler_state' => 'disabled', + 'region_id' => null, + 'region_code' => '', + 'region_name' => '未分类节点', + 'region_status' => 'missing', + 'line_id' => null, + 'line_name' => '', + 'line_status' => 'missing', + 'pool_id' => null, + 'pool_name' => '', + 'pool_status' => 'missing', + 'network_ready' => false, + 'placement_ready' => false, + ]; + } + return [ + 'membership_id' => (int) $membership['id'], + 'scheduler_state' => (string) $membership['scheduler_state'], + 'region_id' => $membership['region_id'], + 'region_code' => (string) $membership['region_code'], + 'region_name' => (string) $membership['region_name'], + 'region_status' => (string) $membership['region_status'], + 'line_id' => $membership['line_id'], + 'line_name' => (string) $membership['line_name'], + 'line_status' => (string) $membership['line_status'], + 'pool_id' => $membership['pool_id'], + 'pool_name' => (string) $membership['pool_name'], + 'pool_status' => (string) $membership['pool_status'], + 'network_ready' => (bool) $membership['network_ready'], + 'placement_ready' => (bool) $membership['placement_ready'], + ]; + } + + private static function addIpStats(array &$target, array $source): void + { + foreach (array_keys(self::emptyIpStats()) as $field) { + $target[$field] += (int) ($source[$field] ?? 0); + } + } + private static function agentState(?CloudHostAgent $agent): string { if ($agent === null) { @@ -329,19 +493,14 @@ final class CloudAdminHostProjectionService return $result; } - private static function attention(CloudHost $host, $membership, $pool, - $line, $region, string $scheduler, bool $selectorReady, + private static function attention(CloudHost $host, array $memberships, bool $agentReady, bool $storageReady, bool $capacityConfigured, - array $capacity): array + array $capacity, bool $networkReady): array { $attention = []; - if ($membership === null || $pool === null || $line === null - || $region === null) { + if ($memberships === []) { $attention[] = 'placement_unclassified'; } - if (!$selectorReady) { - $attention[] = 'network_selector_invalid'; - } if (!$agentReady) { $attention[] = 'agent_not_ready'; } @@ -351,30 +510,50 @@ final class CloudAdminHostProjectionService if ((int) $capacity['unknown_instances'] > 0) { $attention[] = 'instance_capacity_unknown'; } - if ($scheduler === 'active') { + $active = array_values(array_filter( + $memberships, + static fn (array $row): bool => + $row['scheduler_state'] === 'active' + )); + if ($active !== []) { if (!(bool) $host->enabled) { $attention[] = 'host_service_disabled'; } - if ($pool !== null && (string) $pool->status !== 'active') { - $attention[] = 'pool_inactive'; - } - if ($line !== null && (string) $line->status !== 'active') { - $attention[] = 'line_inactive'; - } - if ($region !== null && (string) $region->status !== 'active') { - $attention[] = 'region_inactive'; - } if (!$capacityConfigured) { $attention[] = 'capacity_not_configured'; } - if ((int) $capacity['ip']['available'] <= 0) { + if (!$networkReady) { $attention[] = 'public_ip_unavailable'; } + foreach ($active as $row) { + if ($row['pool_id'] === null) { + $attention[] = 'placement_unclassified'; + } elseif ($row['pool_status'] !== 'active') { + $attention[] = 'pool_inactive'; + } + if ($row['line_id'] === null) { + $attention[] = 'placement_unclassified'; + } elseif ($row['line_status'] !== 'active') { + $attention[] = 'line_inactive'; + } + if ($row['region_id'] === null) { + $attention[] = 'placement_unclassified'; + } elseif ($row['region_status'] !== 'active') { + $attention[] = 'region_inactive'; + } + } + $regionIds = array_values(array_unique(array_filter(array_map( + static fn (array $row) => $row['region_id'], + $active + ), static fn ($id): bool => $id !== null))); + if (count($regionIds) > 1) { + $attention[] = 'membership_region_conflict'; + } } return array_values(array_unique($attention)); } - private static function ipStats(array $hostIds): array + private static function ipStats(array $hostIds, array $agents): array { $result = []; if ($hostIds === []) { @@ -385,50 +564,76 @@ final class CloudAdminHostProjectionService 'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id') ->join('cloud_host_network_attachments as network_attachment', 'network_attachment.id', '=', 'public_pool.network_attachment_id') - ->join('cloud_hosts as selected_host', - 'selected_host.id', '=', 'cloud_public_ips.host_id') ->whereIn('cloud_public_ips.host_id', $hostIds) ->whereColumn('public_pool.host_id', 'cloud_public_ips.host_id') ->whereColumn('network_attachment.host_id', 'cloud_public_ips.host_id') - ->whereColumn('network_attachment.network_selector', - 'selected_host.default_network') - ->groupBy('cloud_public_ips.host_id', 'network_attachment.line_id') - ->selectRaw( - 'cloud_public_ips.host_id, network_attachment.line_id, ' - . 'COUNT(*) AS total_count, ' - . "SUM(CASE WHEN cloud_public_ips.state = 'assigned' " - . 'THEN 1 ELSE 0 END) AS allocated_count, ' - . "SUM(CASE WHEN cloud_public_ips.state IN " - . "('reserved','changing','uncertain') THEN 1 ELSE 0 END) " - . 'AS reserved_count, ' - . "SUM(CASE WHEN cloud_public_ips.state = 'disabled' " - . 'THEN 1 ELSE 0 END) AS disabled_count, ' - . "SUM(CASE WHEN cloud_public_ips.state = 'available' " - . 'AND cloud_public_ips.reservation_id IS NULL ' - . 'AND cloud_public_ips.instance_id IS NULL ' - . 'AND cloud_public_ips.operation_id IS NULL ' - . "AND network_attachment.state = 'active' " - . "AND network_attachment.sync_state = 'applied' " - . 'AND network_attachment.observed_revision >= ' - . 'network_attachment.desired_revision ' - . "AND public_pool.state = 'active' " - . "AND public_pool.sync_state = 'applied' " - . 'AND public_pool.observed_revision >= public_pool.desired_revision ' - . 'THEN 1 ELSE 0 END) AS available_count' - )->get(); + ->get([ + 'cloud_public_ips.host_id', + 'network_attachment.line_id', + 'cloud_public_ips.state', + 'cloud_public_ips.reservation_id', + 'cloud_public_ips.instance_id', + 'cloud_public_ips.operation_id', + 'network_attachment.network_selector', + 'network_attachment.state as attachment_state', + 'network_attachment.verification_state', + 'network_attachment.verified_agent_revision', + 'public_pool.state as pool_state', + 'public_pool.sync_state as pool_sync_state', + 'public_pool.observed_revision as pool_observed_revision', + 'public_pool.desired_revision as pool_desired_revision', + ]); foreach ($rows as $row) { - $result[(int) $row->host_id][(int) $row->line_id] = [ - 'total' => (int) $row->total_count, - 'allocated' => (int) $row->allocated_count, - 'reserved' => (int) $row->reserved_count, - 'available' => (int) $row->available_count, - 'disabled' => (int) $row->disabled_count, - ]; + $hostId = (int) $row->host_id; + $lineId = (int) $row->line_id; + $result[$hostId][$lineId] ??= self::emptyIpStats(); + $result[$hostId][$lineId]['total']++; + $state = (string) $row->state; + if ($state === 'assigned') { + $result[$hostId][$lineId]['allocated']++; + } elseif (in_array($state, + ['reserved', 'changing', 'uncertain'], true)) { + $result[$hostId][$lineId]['reserved']++; + } elseif ($state === 'disabled') { + $result[$hostId][$lineId]['disabled']++; + } + $available = $state === 'available' + && $row->reservation_id === null + && $row->instance_id === null + && $row->operation_id === null + && (string) $row->attachment_state === 'active' + && (string) $row->verification_state === 'verified' + && (string) $row->pool_state === 'active' + && (string) $row->pool_sync_state === 'applied' + && (int) $row->pool_observed_revision + >= (int) $row->pool_desired_revision + && self::agentSelectorEvidenceReady( + $agents[$hostId] ?? null, + (string) $row->network_selector, + (int) $row->verified_agent_revision + ); + if ($available) { + $result[$hostId][$lineId]['available']++; + } } return $result; } + private static function agentSelectorEvidenceReady(?CloudHostAgent $agent, + string $selector, int $verifiedRevision): bool + { + return $agent !== null + && $agent->isReady() + && $verifiedRevision === (int) $agent->revision + && $verifiedRevision === (int) $agent->tested_revision + && in_array( + $selector, + CloudAgentSettingsService::testedNetworkSelectors($agent), + true + ); + } + private static function emptyIpStats(): array { return [ diff --git a/web/app/Services/Cloud/CloudAdminHostSchedulingService.php b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php index 936855c9..f51aa77e 100644 --- a/web/app/Services/Cloud/CloudAdminHostSchedulingService.php +++ b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php @@ -4,9 +4,7 @@ namespace App\Services\Cloud; use App\Models\CloudHost; use App\Models\CloudHostCapacityPolicy; -use App\Models\CloudHostNetworkAttachment; use App\Models\CloudNetworkLine; -use App\Models\CloudPublicIpPool; use App\Models\CloudPublicIp; use App\Models\CloudRegion; use App\Models\CloudResourcePool; @@ -19,87 +17,94 @@ final class CloudAdminHostSchedulingService public static function read(int $hostId): array { - [$host, $membership, $memberships] = (new CloudHost())->getConnection() + [$host, $memberships] = (new CloudHost())->getConnection() ->transaction(function () use ($hostId): array { $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); if ($host === null) { throw new CloudError('宿主机不存在', 404); } $rows = CloudHostPoolMembershipService::lockedRows($host); - $selected = CloudHostPoolMembershipService::selected($rows); - return [$host, $selected, $rows]; + return [$host, $rows]; }, 3); $policy = CloudHostCapacityPolicy::find($hostId); $pools = self::poolOptions(); - $selected = null; + $poolsById = []; foreach ($pools as $pool) { - if ((int) $pool['id'] === (int) ($membership?->resource_pool_id ?? 0)) { - $selected = $pool; - break; - } + $poolsById[(int) $pool['id']] = $pool; } - - $usage = self::hostUsage($hostId, (int) ($selected['line_id'] ?? 0)); + [$usage, $ipUsageByLine] = self::hostUsage($hostId); $capacity = self::capacityDto($policy, $usage); + $membershipDtos = []; + foreach ($memberships as $membership) { + $membershipDtos[] = self::membershipDto( + $membership, + $poolsById[(int) $membership->resource_pool_id] ?? null, + $host, + $policy, + $usage, + $capacity, + $ipUsageByLine + ); + } + $primary = CloudHostPoolMembershipService::primary($memberships); + $primaryDto = null; + if ($primary !== null) { + foreach ($membershipDtos as $membershipDto) { + if ((int) $membershipDto['resource_pool_id'] + === (int) $primary->resource_pool_id) { + $primaryDto = $membershipDto; + break; + } + } + } + $warnings = self::warnings($membershipDtos, $capacity); return [ 'host' => [ 'id' => (int) $host->id, 'name' => self::safeText((string) $host->name, 80), 'enabled' => (bool) $host->enabled, - 'resource_pool_id' => $membership === null - ? null : (int) $membership->resource_pool_id, - 'scheduler_state' => in_array((string) ($membership?->scheduler_state - ?? 'disabled'), - self::SCHEDULER_STATES, true) - ? (string) ($membership?->scheduler_state ?? 'disabled') : 'disabled', + // These two compact fields remain a deterministic summary for + // callers that do not yet render the complete relation list. + // They are not scheduling authority. + 'resource_pool_id' => $primary === null + ? null : (int) $primary->resource_pool_id, + 'scheduler_state' => $primary === null + ? 'disabled' : (string) $primary->scheduler_state, + 'active_memberships' => count(array_filter( + $membershipDtos, + static fn (array $row): bool => + $row['scheduler_state'] === 'active' + )), + 'draining_memberships' => count(array_filter( + $membershipDtos, + static fn (array $row): bool => + $row['scheduler_state'] === 'draining' + )), ], 'policy' => self::policyDto($policy), 'capacity' => $capacity, - 'placement' => $selected, - 'memberships' => $memberships->map(static fn ($row): array => [ - 'id' => (int) $row->id, - 'resource_pool_id' => (int) $row->resource_pool_id, - 'scheduler_state' => (string) $row->scheduler_state, - 'priority' => (int) $row->priority, - 'weight' => (int) $row->weight, - ])->values()->all(), + 'placement' => $primaryDto, + 'memberships' => $membershipDtos, 'pools' => $pools, 'network_lines_enabled' => CloudNetworkLineFeature::enabled(), - 'warnings' => self::warnings($membership, $selected, $capacity), + 'warnings' => $warnings, 'generated_at' => time(), ]; } - public static function save(int $hostId, array $body): array + /** Save only host-global capacity. Memberships are independent relations. */ + public static function saveCapacity(int $hostId, array $body): array { - $poolId = self::nullablePositiveId($body['resource_pool_id'] ?? null); - $schedulerState = $body['scheduler_state'] ?? null; - if (!is_string($schedulerState) - || !in_array($schedulerState, self::SCHEDULER_STATES, true)) { - throw new CloudError('调度状态无效'); - } - $values = [ - 'configured_cpu_cores' => self::integer($body, 'configured_cpu_cores', 0, 65535, '配置 CPU'), - 'configured_memory_mib' => self::integer($body, 'configured_memory_mib', 0, 2147483647, '配置内存'), - 'configured_disk_gib' => self::integer($body, 'configured_disk_gib', 0, 2147483647, '配置磁盘'), - 'safety_cpu_cores' => self::integer($body, 'safety_cpu_cores', 0, 65535, 'CPU 安全预留'), - 'safety_memory_mib' => self::integer($body, 'safety_memory_mib', 0, 2147483647, '内存安全预留'), - 'safety_disk_gib' => self::integer($body, 'safety_disk_gib', 0, 2147483647, '磁盘安全预留'), - 'max_instances' => self::integer($body, 'max_instances', 0, 2147483647, '最大实例数'), - ]; + $values = self::capacityValues($body); (new CloudHost())->getConnection()->transaction( - function () use ($hostId, $poolId, $schedulerState, $values): void { - // All capacity writers use host -> policy order. Keep this - // order aligned with placement and reservation reconciliation. + function () use ($hostId, $values): void { $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); if ($host === null) { throw new CloudError('宿主机不存在', 404); } - // Membership is the scheduling authority. Lock it directly - // after the host sentinel and before host-global capacity. - CloudHostPoolMembershipService::lockedRows($host); + $memberships = CloudHostPoolMembershipService::lockedRows($host); $policy = CloudHostCapacityPolicy::where('host_id', $hostId) ->lockForUpdate()->first(); if ($policy === null) { @@ -107,30 +112,11 @@ final class CloudAdminHostSchedulingService $policy->host_id = $hostId; $policy->created_at = time(); } - - $pool = $poolId === null ? null : CloudResourcePool::find($poolId); - $line = $pool === null ? null : CloudNetworkLine::find((int) $pool->line_id); - $region = $line === null ? null : CloudRegion::find((int) $line->region_id); - if ($poolId !== null && $pool === null) { - throw new CloudError('所选资源池不存在', 409); - } - if ($schedulerState === 'active') { - $usage = self::hostUsage($hostId); - if ((int) ($usage['unknown'] ?? 0) > 0) { - throw new CloudError( - '宿主机存在缺少 CPU、内存或磁盘规格的旧实例,补齐规格后才能启用调度', - 409 - ); - } - self::validateActive($host, $pool, $line, $region, $values); + if (CloudHostPoolMembershipService::activeRows($memberships) !== []) { + self::validateCapacity($values); } - self::assertReservationLine($host, $pool, $line); - self::assertNetworkLine($host, $line); $now = time(); - CloudHostPoolMembershipService::replaceLocked( - $host, $poolId, $schedulerState, $now - ); $host->updated_at = $now; $host->save(); foreach ($values as $field => $value) { @@ -144,6 +130,146 @@ final class CloudAdminHostSchedulingService return self::read($hostId); } + /** Insert or update exactly one independently revisioned membership. */ + public static function saveMembership(int $hostId, int $poolId, + array $body): array + { + if ($poolId < 1) { + throw new CloudError('资源池 ID 无效', 422); + } + $state = $body['scheduler_state'] ?? null; + if (!is_string($state) + || !CloudHostPoolMembershipService::isState($state)) { + throw new CloudError('调度状态无效', 422); + } + $priority = self::integer( + $body, 'priority', CloudHostPoolMembershipService::MIN_PRIORITY, + CloudHostPoolMembershipService::MAX_PRIORITY, '资源池成员优先级' + ); + $weight = self::integer( + $body, 'weight', CloudHostPoolMembershipService::MIN_WEIGHT, + CloudHostPoolMembershipService::MAX_WEIGHT, '资源池成员权重' + ); + $expectedRevision = self::integer( + $body, 'expected_revision', 0, PHP_INT_MAX, + '资源池成员关系版本' + ); + + (new CloudHost())->getConnection()->transaction(function () use ( + $hostId, $poolId, $state, $priority, $weight, $expectedRevision + ): void { + $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); + if ($host === null) { + throw new CloudError('宿主机不存在', 404); + } + $memberships = CloudHostPoolMembershipService::lockedRows($host); + $existingMembership = CloudHostPoolMembershipService::findForPool( + $memberships, $poolId + ); + $actualRevision = $existingMembership === null + ? 0 : max(1, (int) $existingMembership->revision); + if ($actualRevision !== $expectedRevision) { + throw new CloudError( + '资源池成员关系已被修改,请刷新后重试', + 409 + ); + } + $policy = CloudHostCapacityPolicy::where('host_id', $hostId) + ->lockForUpdate()->first(); + $pool = CloudResourcePool::find($poolId); + $line = $pool === null ? null + : CloudNetworkLine::find((int) $pool->line_id); + $region = $line === null ? null + : CloudRegion::find((int) $line->region_id); + if ($pool === null || $line === null || $region === null) { + throw new CloudError('所选资源池、线路或地区不存在', 409); + } + + if ($state !== 'disabled') { + self::assertMembershipRegion( + $memberships, $poolId, (int) $region->id + ); + } else { + self::assertNoReservationsForPool($hostId, $poolId); + } + if ($state === 'active') { + if ($policy === null) { + throw new CloudError( + '启用调度前必须先配置宿主机容量', 409 + ); + } + $usage = CloudPanelUsageService::forHost($hostId); + if ((int) ($usage['unknown'] ?? 0) > 0) { + throw new CloudError( + '宿主机存在缺少 CPU、内存或磁盘规格的旧实例,补齐规格后才能启用调度', + 409 + ); + } + self::validateActive( + $host, $pool, $line, $region, self::policyValues($policy) + ); + } + + $now = time(); + CloudHostPoolMembershipService::upsertLocked( + $host, + $memberships, + $poolId, + $state, + $priority, + $weight, + $expectedRevision, + $now + ); + $host->updated_at = $now; + $host->save(); + }, 3); + + return self::read($hostId); + } + + /** Remove exactly one empty membership without disturbing its siblings. */ + public static function deleteMembership(int $hostId, int $poolId, + int $expectedRevision): array + { + if ($hostId < 1 || $poolId < 1 || $expectedRevision < 1) { + throw new CloudError('资源池成员关系版本无效,请刷新后重试', 422); + } + (new CloudHost())->getConnection()->transaction(function () use ( + $hostId, $poolId, $expectedRevision + ): void { + $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); + if ($host === null) { + throw new CloudError('宿主机不存在', 404); + } + $memberships = CloudHostPoolMembershipService::lockedRows($host); + // Keep the host -> memberships -> policy -> reservations lock + // order aligned with the capacity and placement writers. + CloudHostCapacityPolicy::where('host_id', $hostId) + ->lockForUpdate()->first(); + $membership = CloudHostPoolMembershipService::findForPool( + $memberships, $poolId + ); + if ($membership === null) { + throw new CloudError('宿主机资源池成员关系不存在', 404); + } + if ((int) $membership->revision !== $expectedRevision) { + throw new CloudError( + '资源池成员关系已被修改,请刷新后重试', + 409 + ); + } + self::assertNoReservationsForPool($hostId, $poolId); + CloudHostPoolMembershipService::removeLocked( + $memberships, $poolId, $expectedRevision + ); + $host->updated_at = time(); + $host->save(); + }, 3); + + return self::read($hostId); + } + private static function validateActive(CloudHost $host, $pool, $line, $region, array $values): void { @@ -160,6 +286,11 @@ final class CloudAdminHostSchedulingService if (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default) { throw new CloudError('线路功能关闭时只能使用地区默认线路', 409); } + self::validateCapacity($values); + } + + private static function validateCapacity(array $values): void + { foreach (['cpu_cores' => 'CPU', 'memory_mib' => '内存', 'disk_gib' => '磁盘'] as $suffix => $label) { $configured = (int) $values['configured_' . $suffix]; $safety = (int) $values['safety_' . $suffix]; @@ -172,68 +303,60 @@ final class CloudAdminHostSchedulingService } } - /** Keep existing instances on the line captured by their sales pool. */ - private static function assertReservationLine(CloudHost $host, $pool, - $line): void + /** Every non-disabled membership on one physical host stays in one region. */ + private static function assertMembershipRegion($memberships, + int $targetPoolId, int $targetRegionId): void { - $reservations = CloudResourceReservation::where('host_id', (int) $host->id) - ->whereIn('state', ['held', 'uncertain', 'committed']) - ->orderBy('id')->lockForUpdate()->get(['id', 'resource_pool_id']); - if ($reservations->isEmpty()) { + $poolIds = []; + foreach ($memberships as $membership) { + if ((int) $membership->resource_pool_id === $targetPoolId + || (string) $membership->scheduler_state === 'disabled') { + continue; + } + $poolIds[] = (int) $membership->resource_pool_id; + } + $poolIds = array_values(array_unique($poolIds)); + if ($poolIds === []) { return; } - if ($pool === null || $line === null) { - throw new CloudError('宿主机仍有实例或资源预留,不能移除所属资源池', 409); + $pools = CloudResourcePool::whereIn('id', $poolIds) + ->orderBy('id')->get(['id', 'line_id'])->keyBy('id'); + if ($pools->count() !== count($poolIds)) { + throw new CloudError('宿主机现有资源池成员关系不完整', 409); } - $poolIds = $reservations->pluck('resource_pool_id')->map( + $lineIds = $pools->pluck('line_id')->map( static fn ($id): int => (int) $id )->unique()->values()->all(); - $reservationPools = CloudResourcePool::whereIn('id', $poolIds) - ->orderBy('id')->get(['id', 'line_id'])->keyBy('id'); - if ($reservationPools->count() !== count($poolIds)) { - throw new CloudError('宿主机现有资源预留的线路关系不完整', 409); + $lines = CloudNetworkLine::whereIn('id', $lineIds) + ->orderBy('id')->get(['id', 'region_id'])->keyBy('id'); + if ($lines->count() !== count($lineIds)) { + throw new CloudError('宿主机现有资源池线路关系不完整', 409); } foreach ($poolIds as $poolId) { - if ((int) $reservationPools->get($poolId)->line_id !== (int) $line->id) { - throw new CloudError('宿主机仍有其他线路的实例或资源预留,不能跨线路更换资源池', 409); + $line = $lines->get((int) $pools->get($poolId)->line_id); + if ($line === null || (int) $line->region_id !== $targetRegionId) { + throw new CloudError( + '同一宿主机的启用或排空资源池成员必须属于同一地区', + 409 + ); } } } - /** Do not relabel a configured network as another commercial line. */ - private static function assertNetworkLine(CloudHost $host, - $line): void + /** A disabled or deleted relation must not orphan an exact pool claim. */ + private static function assertNoReservationsForPool(int $hostId, + int $poolId): void { - $attachments = CloudHostNetworkAttachment::where( - 'host_id', (int) $host->id - )->orderBy('id')->lockForUpdate()->get(['id', 'line_id']); - $publicPools = CloudPublicIpPool::where('host_id', (int) $host->id) - ->orderBy('id')->lockForUpdate()->get(['id', 'network_attachment_id']); - if ($attachments->isEmpty() && $publicPools->isEmpty()) { - return; - } - if ($attachments->isEmpty() || $line === null) { + $reservations = CloudResourceReservation::where('host_id', $hostId) + ->where('resource_pool_id', $poolId) + ->whereIn('state', ['held', 'uncertain', 'committed']) + ->orderBy('id')->lockForUpdate()->get(['id']); + if ($reservations->isNotEmpty()) { throw new CloudError( - '宿主机已有公网网络接入,不能移除所属线路', 409 + '该资源池成员仍有实例或资源预留,不能停用或删除', + 409 ); } - $attachmentIds = $attachments->pluck('id')->map( - static fn ($id): int => (int) $id - )->all(); - foreach ($publicPools as $publicPool) { - if (!in_array((int) $publicPool->network_attachment_id, - $attachmentIds, true)) { - throw new CloudError('宿主机公网地址池的线路关系不完整', 409); - } - } - foreach ($attachments as $attachment) { - if ((int) $attachment->line_id !== (int) $line->id) { - throw new CloudError( - '宿主机已有其他线路的公网网络接入,不能静默跨线路更换资源池', - 409 - ); - } - } } private static function poolOptions(): array @@ -279,44 +402,42 @@ final class CloudAdminHostSchedulingService return $result; } - private static function hostUsage(int $hostId, ?int $lineId = null): array + /** + * Return host-global compute usage and IP usage grouped by commercial line. + * Public capacity follows attachment ownership and never host.default_network. + * + * @return array{0:array,1:array>} + */ + private static function hostUsage(int $hostId): array { $usage = CloudPanelUsageService::forHost($hostId); - $usage['ip'] = []; - $lineId = $lineId !== null && $lineId > 0 ? $lineId : null; - $host = $lineId === null ? null : CloudHost::find($hostId); - $ipQuery = CloudPublicIp::where('cloud_public_ips.host_id', $hostId); - if ($lineId !== null && $host !== null) { - $ipQuery->join( + $byLine = []; + $ipQuery = CloudPublicIp::where('cloud_public_ips.host_id', $hostId) + ->join( 'cloud_public_ip_pools as public_pool', 'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id' )->join( 'cloud_host_network_attachments as network_attachment', 'network_attachment.id', '=', 'public_pool.network_attachment_id' - )->where('network_attachment.line_id', $lineId) - ->whereColumn('public_pool.host_id', - 'cloud_public_ips.host_id') - ->whereColumn('network_attachment.host_id', - 'cloud_public_ips.host_id') - ->where('network_attachment.network_selector', - (string) $host->default_network) - ->select([ - 'cloud_public_ips.state', - 'cloud_public_ips.reservation_id', - 'cloud_public_ips.instance_id', - 'cloud_public_ips.operation_id', - 'network_attachment.state as attachment_state', - 'network_attachment.sync_state as attachment_sync_state', - 'network_attachment.observed_revision as attachment_observed_revision', - 'network_attachment.desired_revision as attachment_desired_revision', - 'public_pool.state as pool_state', - 'public_pool.sync_state as pool_sync_state', - 'public_pool.observed_revision as pool_observed_revision', - 'public_pool.desired_revision as pool_desired_revision', - ]); - } + )->whereColumn('public_pool.host_id', 'cloud_public_ips.host_id') + ->whereColumn('network_attachment.host_id', 'cloud_public_ips.host_id') + ->select([ + 'cloud_public_ips.state', + 'cloud_public_ips.reservation_id', + 'cloud_public_ips.instance_id', + 'cloud_public_ips.operation_id', + 'network_attachment.line_id', + 'network_attachment.state as attachment_state', + 'network_attachment.sync_state as attachment_sync_state', + 'network_attachment.observed_revision as attachment_observed_revision', + 'network_attachment.desired_revision as attachment_desired_revision', + 'public_pool.state as pool_state', + 'public_pool.sync_state as pool_sync_state', + 'public_pool.observed_revision as pool_observed_revision', + 'public_pool.desired_revision as pool_desired_revision', + ]); foreach ($ipQuery->get() as $row) { - if ($lineId !== null && (string) $row->state === 'available' + if ((string) $row->state === 'available' && ((int) ($row->reservation_id ?? 0) > 0 || (int) ($row->instance_id ?? 0) > 0 || (string) ($row->operation_id ?? '') !== '' @@ -330,10 +451,20 @@ final class CloudAdminHostSchedulingService < (int) ($row->pool_desired_revision ?? 0))) { continue; } + $lineId = (int) $row->line_id; + if ($lineId < 1) { + continue; + } $key = (string) $row->state; - $usage['ip'][$key] = ($usage['ip'][$key] ?? 0) + 1; + $byLine[$lineId][$key] = ($byLine[$lineId][$key] ?? 0) + 1; + } + $usage['ip'] = []; + foreach ($byLine as $states) { + foreach ($states as $state => $count) { + $usage['ip'][$state] = ($usage['ip'][$state] ?? 0) + $count; + } } - return $usage; + return [$usage, $byLine]; } private static function capacityDto($policy, array $usage): array @@ -375,26 +506,164 @@ final class CloudAdminHostSchedulingService return $result; } - private static function warnings($membership, ?array $placement, + private static function membershipDto($membership, ?array $pool, + CloudHost $host, $policy, array $usage, array $capacity, + array $ipUsageByLine): array + { + $warnings = []; + $state = (string) $membership->scheduler_state; + $lineId = (int) ($pool['line_id'] ?? 0); + $ipCapacity = self::ipCapacityDto($ipUsageByLine[$lineId] ?? []); + $instanceCount = (int) ($capacity['instances']['allocated'] ?? 0) + + (int) ($capacity['instances']['reserved'] ?? 0); + $maxInstances = (int) ($capacity['instances']['max'] ?? 0); + $capacityReady = self::capacityReady($policy) + && (int) ($usage['unknown'] ?? 0) === 0 + && (int) ($capacity['cpu']['free'] ?? 0) > 0 + && (int) ($capacity['memory']['free'] ?? 0) > 0 + && (int) ($capacity['disk']['free'] ?? 0) > 0 + && ($maxInstances < 1 || $instanceCount < $maxInstances); + $pathReady = $pool !== null + && (string) $pool['status'] === 'active' + && (string) $pool['line_status'] === 'active' + && (string) $pool['region_status'] === 'active' + && (CloudNetworkLineFeature::enabled() + || (bool) $pool['line_is_default']); + if ($pool === null) { + $warnings[] = '资源池、线路或地区关系已缺失。'; + } elseif ($state === 'active' && !$pathReady) { + $warnings[] = '资源池、线路或地区当前不满足调度条件。'; + } + if ($state === 'active' && !$capacityReady) { + $warnings[] = '宿主机容量尚未正确配置或存在规格未知的实例。'; + } + if ($state === 'active' && $ipCapacity['available'] < 1) { + $warnings[] = '该线路没有可调度的公网 IP。'; + } + + return [ + 'id' => (int) $membership->id, + 'resource_pool_id' => (int) $membership->resource_pool_id, + 'scheduler_state' => in_array( + $state, self::SCHEDULER_STATES, true + ) ? $state : 'disabled', + 'priority' => (int) $membership->priority, + 'weight' => (int) $membership->weight, + 'revision' => max(1, (int) ($membership->revision ?? 1)), + 'pool_name' => $pool === null ? '资源池已缺失' : $pool['name'], + 'pool_status' => $pool === null ? 'missing' : $pool['status'], + 'scheduling_policy' => $pool === null + ? '' : $pool['scheduling_policy'], + 'line_id' => $pool['line_id'] ?? null, + 'line_name' => $pool === null ? '线路已缺失' : $pool['line_name'], + 'line_status' => $pool === null ? 'missing' : $pool['line_status'], + 'line_is_default' => $pool !== null + && (bool) $pool['line_is_default'], + 'region_id' => $pool['region_id'] ?? null, + 'region_name' => $pool === null ? '地区已缺失' : $pool['region_name'], + 'region_status' => $pool === null ? 'missing' : $pool['region_status'], + 'ip_capacity' => $ipCapacity, + 'placement_ready' => (bool) $host->enabled + && $state === 'active' && $pathReady && $capacityReady + && $ipCapacity['available'] > 0, + 'warnings' => $warnings, + ]; + } + + private static function warnings(array $memberships, array $capacity): array { $warnings = []; - if ($placement === null - && (string) ($membership?->scheduler_state ?? '') === 'active') { - $warnings[] = '当前资源池已缺失,调度器不会选择此宿主机。'; - } elseif ($placement !== null - && (string) ($membership?->scheduler_state ?? '') === 'active' - && ((string) $placement['status'] !== 'active' - || (string) $placement['line_status'] !== 'active' - || (string) $placement['region_status'] !== 'active' - || (!CloudNetworkLineFeature::enabled() - && !$placement['line_is_default']))) { - $warnings[] = '当前资源池、线路或地区已不满足调度条件;保存的配置会保留,但不会接收新实例。'; + foreach ($memberships as $membership) { + foreach ($membership['warnings'] as $warning) { + $warnings[] = $membership['pool_name'] . ':' . $warning; + } } if ((int) ($capacity['unknown_instances'] ?? 0) > 0) { $warnings[] = '存在缺少 CPU、内存或磁盘规格的旧实例;补齐规格前不会接收新实例。'; } - return $warnings; + return array_values(array_unique($warnings)); + } + + private static function ipCapacityDto(array $states): array + { + return [ + 'total' => array_sum($states), + 'allocated' => (int) ($states['assigned'] ?? 0), + 'reserved' => (int) ($states['reserved'] ?? 0) + + (int) ($states['changing'] ?? 0) + + (int) ($states['uncertain'] ?? 0), + 'available' => (int) ($states['available'] ?? 0), + 'disabled' => (int) ($states['disabled'] ?? 0), + ]; + } + + private static function capacityReady($policy): bool + { + if ($policy === null) { + return false; + } + $values = self::policyValues($policy); + foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $suffix) { + if ((int) $values['configured_' . $suffix] < 1 + || (int) $values['safety_' . $suffix] + >= (int) $values['configured_' . $suffix]) { + return false; + } + } + return true; + } + + private static function policyValues($policy): array + { + return [ + 'configured_cpu_cores' => max( + 0, (int) ($policy?->configured_cpu_cores ?? 0) + ), + 'configured_memory_mib' => max( + 0, (int) ($policy?->configured_memory_mib ?? 0) + ), + 'configured_disk_gib' => max( + 0, (int) ($policy?->configured_disk_gib ?? 0) + ), + 'safety_cpu_cores' => max( + 0, (int) ($policy?->safety_cpu_cores ?? 0) + ), + 'safety_memory_mib' => max( + 0, (int) ($policy?->safety_memory_mib ?? 0) + ), + 'safety_disk_gib' => max( + 0, (int) ($policy?->safety_disk_gib ?? 0) + ), + 'max_instances' => max(0, (int) ($policy?->max_instances ?? 0)), + ]; + } + + private static function capacityValues(array $body): array + { + return [ + 'configured_cpu_cores' => self::integer( + $body, 'configured_cpu_cores', 0, 65535, '配置 CPU' + ), + 'configured_memory_mib' => self::integer( + $body, 'configured_memory_mib', 0, 2147483647, '配置内存' + ), + 'configured_disk_gib' => self::integer( + $body, 'configured_disk_gib', 0, 2147483647, '配置磁盘' + ), + 'safety_cpu_cores' => self::integer( + $body, 'safety_cpu_cores', 0, 65535, 'CPU 安全预留' + ), + 'safety_memory_mib' => self::integer( + $body, 'safety_memory_mib', 0, 2147483647, '内存安全预留' + ), + 'safety_disk_gib' => self::integer( + $body, 'safety_disk_gib', 0, 2147483647, '磁盘安全预留' + ), + 'max_instances' => self::integer( + $body, 'max_instances', 0, 2147483647, '最大实例数' + ), + ]; } private static function integer(array $body, string $key, int $minimum, @@ -410,18 +679,6 @@ final class CloudAdminHostSchedulingService return (int) $value; } - private static function nullablePositiveId($value): ?int - { - if ($value === null || $value === '') { - return null; - } - $id = filter_var($value, FILTER_VALIDATE_INT); - if ($id === false || $id < 1) { - throw new CloudError('资源池 ID 无效'); - } - return (int) $id; - } - private static function safeText(string $value, int $maximum): string { $value = preg_replace('/[\x00-\x1f\x7f]/u', '', $value) ?? ''; diff --git a/web/app/Services/Cloud/CloudAdminResourceService.php b/web/app/Services/Cloud/CloudAdminResourceService.php index eb85f475..92c31d9a 100644 --- a/web/app/Services/Cloud/CloudAdminResourceService.php +++ b/web/app/Services/Cloud/CloudAdminResourceService.php @@ -537,17 +537,12 @@ final class CloudAdminResourceService )->join( 'cloud_host_network_attachments as network_attachment', 'network_attachment.id', '=', 'public_pool.network_attachment_id' - )->join( - 'cloud_hosts as eligible_host', - 'eligible_host.id', '=', 'cloud_public_ips.host_id' )->whereIn('cloud_public_ips.host_id', $hostIds) ->whereColumn('public_pool.host_id', 'cloud_public_ips.host_id') ->whereColumn('network_attachment.host_id', 'cloud_public_ips.host_id') // Gateway, DNS and management addresses are disabled while // materializing the pool's reserved_ips ledger. - ->whereColumn('network_attachment.network_selector', - 'eligible_host.default_network') ->where(function ($query): void { $query->where('cloud_public_ips.state', '<>', 'available') ->orWhere(function ($available): void { @@ -577,9 +572,6 @@ final class CloudAdminResourceService )->join( 'cloud_host_network_attachments as network_attachment', 'network_attachment.id', '=', 'public_pool.network_attachment_id' - )->join( - 'cloud_hosts as eligible_host', - 'eligible_host.id', '=', 'cloud_public_ips.host_id' )->whereIn('cloud_public_ips.host_id', $hostIds) ->where('cloud_public_ips.state', 'available') ->whereNull('cloud_public_ips.reservation_id') @@ -590,12 +582,8 @@ final class CloudAdminResourceService 'public_pool.guest_prefix_length') ->whereColumn('network_attachment.host_id', 'cloud_public_ips.host_id') - ->whereColumn('network_attachment.network_selector', - 'eligible_host.default_network') ->where('network_attachment.state', 'active') - ->where('network_attachment.sync_state', 'applied') - ->whereColumn('network_attachment.observed_revision', '>=', - 'network_attachment.desired_revision') + ->where('network_attachment.verification_state', 'verified') ->where('public_pool.state', 'active') ->where('public_pool.sync_state', 'applied') ->whereColumn('public_pool.observed_revision', '>=', @@ -603,7 +591,10 @@ final class CloudAdminResourceService ->get([ 'cloud_public_ips.id as ip_id', 'cloud_public_ips.host_id', 'cloud_public_ips.address', - 'network_attachment.line_id', 'public_pool.pool_key', + 'network_attachment.line_id', + 'network_attachment.network_selector', + 'network_attachment.verified_agent_revision', + 'public_pool.pool_key', 'public_pool.cidr', ]); foreach ($networkRows as $row) { @@ -611,6 +602,10 @@ final class CloudAdminResourceService (string) $row->pool_key) !== 1 || !self::ipv4BelongsToCidr( (string) $row->address, (string) $row->cidr + ) || !self::agentSelectorEvidenceReady( + $agentByHost[(int) $row->host_id] ?? null, + (string) $row->network_selector, + (int) $row->verified_agent_revision )) { continue; } @@ -623,21 +618,23 @@ final class CloudAdminResourceService } $poolHosts = []; - foreach ($memberships->groupBy('host_id') as $hostId => $rows) { - $host = $hostById[(int) $hostId] ?? null; + foreach ($memberships as $membership) { + $host = $hostById[(int) $membership->host_id] ?? null; if ($host === null) { continue; } - $membership = CloudHostPoolMembershipService::selected($rows); - if ($membership !== null) { - $poolHosts[(int) $membership->resource_pool_id][] = [ - 'host' => $host, - 'membership' => $membership, - ]; - } + $poolHosts[(int) $membership->resource_pool_id][] = [ + 'host' => $host, + 'membership' => $membership, + ]; } $poolRows = []; $hostRows = []; + $platformCapacityByHost = []; + $platformLineCapacityByHost = []; + $platformPlacementEligibleByHost = []; + $platformPlacementLineByHost = []; + $platformReadyByHost = []; foreach ($pools as $pool) { $poolId = (int) $pool->id; $line = $lineById[(int) $pool->line_id] ?? null; @@ -704,10 +701,26 @@ final class CloudAdminResourceService $hostCapacity['max_host_free']['ip'] = $hostIpFree; self::addCapacity($capacity, $hostCapacity); + if (!isset($platformCapacityByHost[$hostId])) { + $platformCapacityByHost[$hostId] = $hostCapacity; + $platformCapacityByHost[$hostId]['ip'] = + self::emptyCapacity()['ip']; + $platformCapacityByHost[$hostId]['max_host_free']['ip'] = 0; + } + $lineId = (int) $pool->line_id; + if (!isset($platformLineCapacityByHost[$hostId][$lineId])) { + $platformLineCapacityByHost[$hostId][$lineId] = + $hostCapacity['ip']; + foreach (['total', 'allocated', 'reserved', 'disabled', + 'free'] as $field) { + $platformCapacityByHost[$hostId]['ip'][$field] += + (int) $hostCapacity['ip'][$field]; + } + $platformCapacityByHost[$hostId]['max_host_free']['ip'] += + $hostIpFree; + } + $hostEnabled = (bool) $host->enabled; - $selectorReady = CloudNetworkSelector::isValid( - (string) $host->default_network - ); $schedulerActive = (string) $membership->scheduler_state === 'active'; $agentReady = $agent !== null && $agent->isReady(); $storageReady = $storage !== null && $storage->isApplied(); @@ -724,7 +737,7 @@ final class CloudAdminResourceService && ($maxInstances <= 0 || $instanceCount < $maxInstances) && $hostResources['cpu'] > 0 && $hostResources['memory'] > 0 && $hostResources['disk'] > 0 && $hostIpFree > 0; - $hostBaseReady = $poolPathReady && $hostEnabled && $selectorReady + $hostBaseReady = $poolPathReady && $hostEnabled && $schedulerActive && $agentReady && $storageReady && $networkReady && $capacityConfigured && (int) ($hostUsage['unknown'] ?? 0) === 0 @@ -732,7 +745,10 @@ final class CloudAdminResourceService $health['host_count']++; $health['enabled_host_count'] += $hostEnabled ? 1 : 0; - $health['network_selector_ready_host_count'] += $selectorReady ? 1 : 0; + // Compatibility field: readiness now belongs to this exact + // host/line attachment, never the host default_network value. + $health['network_selector_ready_host_count'] += + $networkReady ? 1 : 0; $health['scheduler_active_host_count'] += $schedulerActive ? 1 : 0; $health['agent_ready_host_count'] += $agentReady ? 1 : 0; $health['storage_ready_host_count'] += $storageReady ? 1 : 0; @@ -740,15 +756,28 @@ final class CloudAdminResourceService $health['capacity_ready_host_count'] += $capacityReady ? 1 : 0; if ($hostBaseReady) { self::addCapacity($placementCapacity, $hostCapacity); + $platformPlacementEligibleByHost[$hostId] = true; + $platformPlacementLineByHost[$hostId][$lineId] = true; } if ($hostBaseReady && $capacityReady) { $health['placement_ready_host_count']++; + $platformReadyByHost[$hostId] = true; } $hostRows[] = [ 'id' => $hostId, 'name' => (string) $host->name, + 'membership_id' => (int) $membership->id, + 'resource_pool_id' => $poolId, + 'line_id' => (int) $pool->line_id, + 'scheduler_state' => (string) $membership->scheduler_state, + 'priority' => (int) $membership->priority, + 'weight' => (int) $membership->weight, + 'revision' => max(1, (int) $membership->revision), 'pool_name' => (string) $pool->name, + 'line_name' => (string) ($line->name ?? ''), 'region_name' => (string) ($region->name ?? ''), + 'network_ready' => $networkReady, + 'capacity_scope' => 'shared_host', 'placement_ready' => $hostBaseReady && $capacityReady, ]; } @@ -793,6 +822,9 @@ final class CloudAdminResourceService 'offer_count' => $offerCounts[$poolId] ?? 0, 'held_reservation_count' => $held, 'uncertain_reservation_count' => $uncertain, + 'capacity_scope' => 'shared_host', + 'capacity_shared' => true, + 'capacity_note' => '宿主机 CPU、内存和磁盘容量由该节点的全部资源池成员关系共享竞争', 'capacity' => $capacity, 'placement_capacity' => $placementCapacity, 'created_at' => (int) $pool->created_at, @@ -888,9 +920,18 @@ final class CloudAdminResourceService ]; } + $platformHosts = self::platformHostSummary( + $platformCapacityByHost, + $platformLineCapacityByHost, + $platformPlacementEligibleByHost, + $platformPlacementLineByHost, + $platformReadyByHost + ); return [ 'hosts' => $hostRows, - 'summary' => self::summary($regionRows, $lineRows, $poolRows), + 'summary' => self::summary( + $regionRows, $lineRows, $poolRows, $platformHosts + ), 'topology' => self::topology( $regionRows, $lineRows, $poolRows, $lineFeatureEnabled ), @@ -900,37 +941,69 @@ final class CloudAdminResourceService ]; } - private static function summary(array $regions, array $lines, array $pools): array + private static function summary(array $regions, array $lines, array $pools, + array $platformHosts): array { $summary = [ 'regions_total' => count($regions), 'lines_total' => count($lines), 'pools_total' => count($pools), 'placement_ready_pools' => 0, - 'hosts_total' => 0, - 'placement_ready_hosts' => 0, + 'hosts_total' => (int) $platformHosts['hosts_total'], + 'placement_ready_hosts' => + (int) $platformHosts['placement_ready_hosts'], 'held_reservations' => 0, 'uncertain_reservations' => 0, - 'capacity' => self::emptyCapacity(), - 'placement_capacity' => self::emptyCapacity(), + 'capacity' => $platformHosts['capacity'], + 'placement_capacity' => $platformHosts['placement_capacity'], ]; foreach ($pools as $pool) { if ($pool['effective_state'] === 'ready') { $summary['placement_ready_pools']++; } - $summary['hosts_total'] += $pool['health']['host_count']; - $summary['placement_ready_hosts'] += - $pool['health']['placement_ready_host_count']; $summary['held_reservations'] += $pool['held_reservation_count']; $summary['uncertain_reservations'] += $pool['uncertain_reservation_count']; - self::addCapacity($summary['capacity'], $pool['capacity']); - self::addCapacity( - $summary['placement_capacity'], $pool['placement_capacity'] - ); } return $summary; } + /** Physical host totals are counted once even when several pools share them. */ + private static function platformHostSummary(array $capacityByHost, + array $lineCapacityByHost, array $placementEligibleByHost, + array $placementLineByHost, array $readyByHost): array + { + $capacity = self::emptyCapacity(); + $placementCapacity = self::emptyCapacity(); + foreach ($capacityByHost as $hostId => $hostCapacity) { + self::addCapacity($capacity, $hostCapacity); + if (!isset($placementEligibleByHost[$hostId])) { + continue; + } + $eligible = $hostCapacity; + $eligible['ip'] = self::emptyCapacity()['ip']; + $eligible['max_host_free']['ip'] = 0; + foreach ($placementLineByHost[$hostId] ?? [] as $lineId => $_) { + $lineIp = $lineCapacityByHost[$hostId][$lineId] ?? null; + if (!is_array($lineIp)) { + continue; + } + foreach (['total', 'allocated', 'reserved', 'disabled', + 'free'] as $field) { + $eligible['ip'][$field] += (int) ($lineIp[$field] ?? 0); + } + $eligible['max_host_free']['ip'] += + (int) ($lineIp['free'] ?? 0); + } + self::addCapacity($placementCapacity, $eligible); + } + return [ + 'hosts_total' => count($capacityByHost), + 'placement_ready_hosts' => count($readyByHost), + 'capacity' => $capacity, + 'placement_capacity' => $placementCapacity, + ]; + } + private static function topology(array $regions, array $lines, array $pools, bool $lineFeatureEnabled): array { @@ -1018,9 +1091,6 @@ final class CloudAdminResourceService } else { $components = [ 'enabled_host_count' => ['hosts_disabled', '没有已启用的计算节点'], - 'network_selector_ready_host_count' => [ - 'network_selector_invalid', '没有网络选择器有效的计算节点', - ], 'scheduler_active_host_count' => [ 'scheduler_inactive', '没有启用自动调度的计算节点', ], @@ -1411,6 +1481,20 @@ final class CloudAdminResourceService return $address > $base && $address < $base + $block - 1; } + private static function agentSelectorEvidenceReady(?CloudHostAgent $agent, + string $selector, int $verifiedRevision): bool + { + return $agent !== null + && $agent->isReady() + && $verifiedRevision === (int) $agent->revision + && $verifiedRevision === (int) $agent->tested_revision + && in_array( + $selector, + CloudAgentSettingsService::testedNetworkSelectors($agent), + true + ); + } + private static function ipv4Number(string $value): ?int { if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { diff --git a/web/app/Services/Cloud/CloudHostPoolMembershipService.php b/web/app/Services/Cloud/CloudHostPoolMembershipService.php index 7c57d2f3..15e57224 100644 --- a/web/app/Services/Cloud/CloudHostPoolMembershipService.php +++ b/web/app/Services/Cloud/CloudHostPoolMembershipService.php @@ -5,114 +5,201 @@ namespace App\Services\Cloud; use App\Models\CloudHost; use App\Models\CloudHostResourcePoolMembership; -/** Authoritative host-to-resource-pool scheduling membership. */ +/** + * Host-to-resource-pool scheduling memberships. + * + * A compute host may expose capacity to several commercial lines in the same + * physical region. CPU, memory, disk and instance limits remain host-global; + * this service owns only the independently revisioned placement relations. + */ final class CloudHostPoolMembershipService { public const SAFE_PRIORITY = 0; public const SAFE_WEIGHT = 100; + public const MIN_PRIORITY = -1000000; + public const MAX_PRIORITY = 1000000; + public const MIN_WEIGHT = 1; + public const MAX_WEIGHT = 1000; + private const STATES = ['active', 'draining', 'disabled']; /** The caller must already hold a FOR UPDATE lock on the host row. */ public static function lockedRows(CloudHost $host) { - return CloudHostResourcePoolMembership::where('host_id', (int) $host->id) - ->orderBy('resource_pool_id')->orderBy('id')->lockForUpdate()->get(); + return CloudHostResourcePoolMembership::where( + 'host_id', (int) $host->id + )->orderBy('resource_pool_id')->orderBy('id')->lockForUpdate()->get(); } - /** Select the first-release placement relation deterministically. */ - public static function selected($rows): ?CloudHostResourcePoolMembership + public static function findForPool($rows, + int $resourcePoolId): ?CloudHostResourcePoolMembership { - $active = null; - $draining = null; - $latest = null; - $activeCount = 0; foreach ($rows as $row) { - if ((string) $row->scheduler_state === 'active') { - $activeCount++; - $active = $row; - } - if ((string) $row->scheduler_state === 'draining' - && ($draining === null || self::newer($row, $draining))) { - $draining = $row; - } - if ($latest === null || self::newer($row, $latest)) { - $latest = $row; + if ((int) $row->resource_pool_id === $resourcePoolId) { + return $row; } } - if ($activeCount > 1) { - throw new CloudError('宿主机存在多个启用中的资源池成员关系,请先修复调度配置', 409); + return null; + } + + /** @return array */ + public static function activeRows($rows): array + { + $active = []; + foreach ($rows as $row) { + if ((string) $row->scheduler_state === 'active') { + $active[] = $row; + } } - return $active ?? $draining ?? $latest; + usort($active, [self::class, 'compare']); + return $active; } /** - * Replace the first-release selected membership. Until the scheduler can - * express several memberships in its write API, one host has zero or one - * authoritative row; the relation schema itself remains ready for a later - * multi-pool rollout. + * A deterministic representative for compact legacy projections only. + * Placement must always select an exact resource_pool_id and must not use + * this method as scheduling authority. */ - public static function replaceLocked(CloudHost $host, ?int $poolId, - string $schedulerState, int $now): ?CloudHostResourcePoolMembership + public static function primary($rows): ?CloudHostResourcePoolMembership { - if (!in_array($schedulerState, self::STATES, true)) { - throw new CloudError('调度状态无效'); - } - if ($poolId === null && $schedulerState !== 'disabled') { - throw new CloudError('未选择资源池时只能停用调度', 409); - } - - $rows = self::lockedRows($host); - $target = null; + $rank = ['active' => 0, 'draining' => 1, 'disabled' => 2]; + $ordered = []; foreach ($rows as $row) { - if ($poolId !== null && (int) $row->resource_pool_id === $poolId) { - $target = $row; + $ordered[] = $row; + } + usort($ordered, static function ($left, $right) use ($rank): int { + $leftState = $rank[(string) $left->scheduler_state] ?? 3; + $rightState = $rank[(string) $right->scheduler_state] ?? 3; + if ($leftState !== $rightState) { + return $leftState <=> $rightState; } + return self::compare($left, $right); + }); + return $ordered[0] ?? null; + } + + /** @deprecated Use an exact resource-pool lookup for business decisions. */ + public static function selected($rows): ?CloudHostResourcePoolMembership + { + return self::primary($rows); + } + + /** + * Insert or update exactly one membership. Other memberships are never + * deleted or relabelled as a side effect. + * + * The caller holds the host row lock and passes the rows returned by + * lockedRows(), preserving the global host -> memberships lock order. + */ + public static function upsertLocked( + CloudHost $host, + $rows, + int $resourcePoolId, + string $schedulerState, + int $priority, + int $weight, + int $expectedRevision, + int $now + ): CloudHostResourcePoolMembership { + self::assertValues( + $resourcePoolId, + $schedulerState, + $priority, + $weight, + $expectedRevision + ); + + $membership = self::findForPool($rows, $resourcePoolId); + $actualRevision = $membership === null + ? 0 : max(1, (int) $membership->revision); + if ($actualRevision !== $expectedRevision) { + throw new CloudError( + '资源池成员关系已被修改,请刷新后重试', + 409 + ); } - if ($poolId !== null && $target === null) { - $target = new CloudHostResourcePoolMembership(); - $target->host_id = (int) $host->id; - $target->resource_pool_id = $poolId; - $target->created_at = $now; - $rows->push($target); + if ($actualRevision >= PHP_INT_MAX) { + throw new CloudError('资源池成员关系版本已达到上限', 409); } - foreach ($rows as $row) { - if ($target !== null - && (int) $row->resource_pool_id === (int) $target->resource_pool_id) { - continue; - } - $row->delete(); - } - if ($target !== null) { - $target->scheduler_state = $schedulerState; - $target->priority = self::SAFE_PRIORITY; - $target->weight = self::SAFE_WEIGHT; - $target->updated_at = $now; - $target->save(); - self::assertSingleActive([$target]); + if ($membership === null) { + $membership = new CloudHostResourcePoolMembership(); + $membership->host_id = (int) $host->id; + $membership->resource_pool_id = $resourcePoolId; + $membership->created_at = $now; } + $membership->scheduler_state = $schedulerState; + $membership->priority = $priority; + $membership->weight = $weight; + $membership->revision = $actualRevision + 1; + $membership->updated_at = $now; + $membership->save(); - return $target; + return $membership; + } + + /** Delete exactly one membership after its caller has checked references. */ + public static function removeLocked( + $rows, + int $resourcePoolId, + int $expectedRevision + ): void { + if ($resourcePoolId < 1 || $expectedRevision < 1) { + throw new CloudError('资源池成员关系版本无效,请刷新后重试', 422); + } + $membership = self::findForPool($rows, $resourcePoolId); + if ($membership === null) { + throw new CloudError('宿主机资源池成员关系不存在', 404); + } + if ((int) $membership->revision !== $expectedRevision) { + throw new CloudError( + '资源池成员关系已被修改,请刷新后重试', + 409 + ); + } + $membership->delete(); } - private static function assertSingleActive($rows): void + public static function isState(string $value): bool { - $active = 0; - foreach ($rows as $row) { - if ((string) $row->scheduler_state === 'active') { - $active++; - } + return in_array($value, self::STATES, true); + } + + private static function assertValues( + int $resourcePoolId, + string $schedulerState, + int $priority, + int $weight, + int $expectedRevision + ): void { + if ($resourcePoolId < 1) { + throw new CloudError('资源池 ID 无效', 422); + } + if (!self::isState($schedulerState)) { + throw new CloudError('调度状态无效', 422); + } + if ($priority < self::MIN_PRIORITY || $priority > self::MAX_PRIORITY) { + throw new CloudError('资源池成员优先级无效', 422); + } + if ($weight < self::MIN_WEIGHT || $weight > self::MAX_WEIGHT) { + throw new CloudError('资源池成员权重无效', 422); } - if ($active > 1) { - throw new CloudError('宿主机存在多个启用中的资源池成员关系,请先修复调度配置', 409); + if ($expectedRevision < 0) { + throw new CloudError('资源池成员关系版本无效,请刷新后重试', 422); } } - private static function newer($left, $right): bool + private static function compare($left, $right): int { - return (int) $left->updated_at > (int) $right->updated_at - || ((int) $left->updated_at === (int) $right->updated_at - && (int) $left->id > (int) $right->id); + return [ + (int) $left->priority, + (int) $left->resource_pool_id, + (int) $left->id, + ] <=> [ + (int) $right->priority, + (int) $right->resource_pool_id, + (int) $right->id, + ]; } } diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index 4198e667..a3d8689c 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -94,6 +94,9 @@ $app->group('/api/v1', function () { $this->delete('/ssh-keys/{id:[0-9]+}', 'App\Controllers\CloudApiController:deleteKey'); $this->map(['GET', 'PUT'], '/admin/hosts/{id:[0-9]+}/scheduling', 'App\Controllers\CloudAdminController:hostScheduling'); + $this->map(['PUT', 'DELETE'], + '/admin/hosts/{id:[0-9]+}/scheduling/memberships/{resource_pool_id:[1-9][0-9]*}', + 'App\Controllers\CloudAdminController:hostSchedulingMembership'); $this->map(['GET', 'POST'], '/admin/hosts/{id:[0-9]+}/network-pools', 'App\Controllers\CloudAdminHostNetworkController:index'); $this->put( diff --git a/web/public/cloud/admin-hosts.js b/web/public/cloud/admin-hosts.js index 472ebc1f..e8edd99b 100644 --- a/web/public/cloud/admin-hosts.js +++ b/web/public/cloud/admin-hosts.js @@ -479,11 +479,91 @@ async function saveHostStorage(event) { } } function schedulerLabel(value) { return ({ active: '调度启用', draining: '正在排空', disabled: '调度停用' })[value] || '调度未配置'; } +function schedulingPoolLabel(pool) { + const path = [pool?.region_name, pool?.line_name, pool?.name].filter(Boolean).join(' / ') || `资源池 #${pool?.id || '?'}`; + return `${path}${pool?.status === 'active' && pool?.line_status === 'active' && pool?.region_status === 'active' ? '' : '(不可调度)'}`; +} function setSchedulingWarnings(warnings) { const box = byId('host-scheduling-warnings'); box.replaceChildren(); const entries = Array.isArray(warnings) ? warnings.filter(Boolean) : []; box.hidden = entries.length === 0; if (!entries.length) return; const list = element('ul', 'mb-0'); for (const warning of entries) list.append(element('li', '', warning)); box.append(list); } +function schedulingInput(type, name, value, options = {}) { + const control = document.createElement(type === 'select' ? 'select' : 'input'); + control.className = type === 'select' ? 'form-select' : 'form-control'; + control.name = name; + if (type === 'select') { + for (const [optionValue, label] of [['active', '启用调度'], ['draining', '排空(不接收新实例)'], ['disabled', '停用调度']]) { + const option = element('option', '', label); option.value = optionValue; control.append(option); + } + } else { + control.type = 'number'; control.required = true; + control.min = String(options.min); control.max = String(options.max); + } + control.value = String(value ?? ''); control.disabled = !canManage; + return control; +} +function schedulingField(label, control) { + const wrapper = element('div'); wrapper.append(element('label', 'form-label', label), control); return wrapper; +} +function membershipPath(item) { + return [item?.region_name, item?.line_name, item?.pool_name].filter(Boolean).join(' / ') || `资源池 #${item?.resource_pool_id || '?'}`; +} +function renderHostMemberships(payload) { + const memberships = Array.isArray(payload?.memberships) ? payload.memberships : []; + const pools = Array.isArray(payload?.pools) ? payload.pools : []; + const assigned = new Set(memberships.map(item => Number(item.resource_pool_id))); + const poolSelect = byId('host-membership-pool'); poolSelect.replaceChildren(); + const placeholder = element('option', '', '选择要加入的资源池'); placeholder.value = ''; poolSelect.append(placeholder); + for (const pool of pools) { + if (assigned.has(Number(pool.id))) continue; + const option = element('option', '', schedulingPoolLabel(pool)); option.value = String(pool.id); poolSelect.append(option); + } + poolSelect.value = ''; poolSelect.disabled = !canManage || poolSelect.children.length < 2; + const addButton = byId('host-membership-add'); if (addButton) addButton.disabled = poolSelect.disabled; + byId('host-membership-new-state').value = 'disabled'; + byId('host-membership-new-priority').value = '0'; + byId('host-membership-new-weight').value = '100'; + byId('host-membership-pool-help').textContent = poolSelect.children.length < 2 + ? '当前没有可新增的资源池成员。' + : (payload?.network_lines_enabled ? '仅显示尚未加入的资源池;同一宿主机的启用或排空成员必须位于同一地区。' : '线路功能关闭时,只有地区默认线路可以启用调度。'); + + const list = byId('host-membership-list'); list.replaceChildren(); + if (!memberships.length) { + list.append(element('p', 'text-muted mb-0', '当前宿主机尚未加入任何资源池。')); + return; + } + for (const item of memberships) { + const card = element('article', 'card mb-3'); card.dataset.hostMembership = String(item.resource_pool_id); + const body = element('div', 'card-body'); + const header = element('div', 'd-flex justify-content-between align-items-start gap-3 flex-wrap'); + const identity = element('div'); identity.append( + element('h6', 'mb-1', membershipPath(item)), + element('p', 'text-muted fs-13 mb-0', `资源池 #${item.resource_pool_id} · revision ${item.revision}`) + ); + const badge = element('span', `badge ${item.scheduler_state === 'active' ? 'text-bg-success' : item.scheduler_state === 'draining' ? 'text-bg-warning' : 'text-bg-light'}`, schedulerLabel(item.scheduler_state)); + header.append(identity, badge); body.append(header); + + const form = element('form', 'cloud-admin-form-grid mt-3'); + form.dataset.hostMembershipForm = ''; form.dataset.poolId = String(item.resource_pool_id); form.dataset.revision = String(item.revision); + const stateControl = schedulingInput('select', 'scheduler_state', item.scheduler_state); + const priority = schedulingInput('number', 'priority', item.priority, { min: -1000000, max: 1000000 }); + const weight = schedulingInput('number', 'weight', item.weight, { min: 1, max: 1000 }); + form.append(schedulingField('调度状态', stateControl), schedulingField('优先级', priority), schedulingField('权重', weight)); + if (canManage) { + const actions = element('div', 'cloud-admin-full d-flex justify-content-end gap-2'); + const remove = element('button', 'btn btn-outline-danger', '删除成员'); remove.type = 'button'; remove.dataset.hostMembershipDelete = ''; + const save = element('button', 'btn btn-outline-primary', '保存此成员'); save.type = 'submit'; save.dataset.hostMembershipSave = ''; + remove.addEventListener('click', () => deleteHostMembership(item, remove)); + actions.append(remove, save); form.append(actions); + } + form.addEventListener('submit', saveHostMembership); + body.append(form); + const warnings = Array.isArray(item.warnings) ? item.warnings.filter(Boolean) : []; + if (warnings.length) body.append(element('p', 'alert alert-warning mt-3 mb-0', warnings.join(' '))); + card.append(body); list.append(card); + } +} function renderPanelCapacity(capacity) { const list = byId('host-panel-capacity'); list.replaceChildren(); const rows = capacity ? [ @@ -497,33 +577,90 @@ function renderPanelCapacity(capacity) { for (const [label, value] of rows) list.append(element('dt', '', label), element('dd', '', value)); } function renderHostScheduling(payload) { - const host = payload?.host || {}; const policy = payload?.policy || {}; const pools = Array.isArray(payload?.pools) ? payload.pools : []; - byId('host-scheduling-title').textContent = `${host.name || `宿主机 #${host.id}`} · 资源池与调度策略`; + const host = payload?.host || {}; const policy = payload?.policy || {}; const memberships = Array.isArray(payload?.memberships) ? payload.memberships : []; + byId('host-scheduling-title').textContent = `${host.name || `宿主机 #${host.id}`} · 资源池成员与调度容量`; byId('host-scheduling-host-id').value = host.id || ''; - const select = byId('host-resource-pool'); select.replaceChildren(); const empty = element('option', '', '不加入资源池'); empty.value = ''; select.append(empty); - for (const pool of pools) { const option = element('option', '', `${pool.region_name} / ${pool.line_name} / ${pool.name}${pool.status === 'active' && pool.line_status === 'active' && pool.region_status === 'active' ? '' : '(不可调度)'}`); option.value = String(pool.id); option.selected = Number(host.resource_pool_id) === Number(pool.id); select.append(option); } - byId('host-scheduler-state').value = ['active', 'draining', 'disabled'].includes(host.scheduler_state) ? host.scheduler_state : 'disabled'; const fields = { 'host-capacity-cpu': policy.configured_cpu_cores, 'host-capacity-memory': policy.configured_memory_mib, 'host-capacity-disk': policy.configured_disk_gib, 'host-safety-cpu': policy.safety_cpu_cores, 'host-safety-memory': policy.safety_memory_mib, 'host-safety-disk': policy.safety_disk_gib, 'host-max-instances': policy.max_instances }; for (const [id, value] of Object.entries(fields)) byId(id).value = Number(value || 0); - byId('host-resource-pool-help').textContent = payload?.network_lines_enabled ? '线路功能已开启,可选择任意启用线路下的资源池。' : '线路功能关闭,只允许启用地区的默认线路参与调度。'; - setSchedulingWarnings(payload?.warnings); renderPanelCapacity(payload?.capacity); - hostSchedulingNotice(`连接:${host.enabled ? '启用' : '停用'} · ${schedulerLabel(host.scheduler_state)}`); + renderHostMemberships(payload); setSchedulingWarnings(payload?.warnings); renderPanelCapacity(payload?.capacity); + const active = memberships.filter(item => item.scheduler_state === 'active').length; + const draining = memberships.filter(item => item.scheduler_state === 'draining').length; + hostSchedulingNotice(`连接:${host.enabled ? '启用' : '停用'} · 成员 ${memberships.length} 个 · 启用 ${active} 个 · 排空 ${draining} 个`); } function closeHostScheduling() { closeHostDrawer('host-scheduling-drawer', 'scheduling'); } async function openHostScheduling(hostId, opener) { - if (state.schedulingBusy) return; state.schedulingBusy = true; const dialog = byId('host-scheduling-drawer'); state.schedulingOpener = opener; hostSchedulingNotice('正在读取面板资源池和容量配置…'); setSchedulingWarnings([]); renderPanelCapacity(null); + if (state.schedulingBusy) return; state.schedulingBusy = true; const dialog = byId('host-scheduling-drawer'); state.schedulingOpener = opener; hostSchedulingNotice('正在读取资源池成员和容量配置…'); setSchedulingWarnings([]); renderPanelCapacity(null); byId('host-membership-list').replaceChildren(); if (!dialog.open) { lockHostDrawerScroll('scheduling'); window.VenixDrawerMotion.openDrawerWithMotion(dialog); } try { renderHostScheduling(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling`)); } catch (error) { hostSchedulingNotice(error.message, true); } finally { state.schedulingBusy = false; } } -function schedulingBody() { return { resource_pool_id: byId('host-resource-pool').value ? Number(byId('host-resource-pool').value) : null, scheduler_state: byId('host-scheduler-state').value, configured_cpu_cores: Number(byId('host-capacity-cpu').value), configured_memory_mib: Number(byId('host-capacity-memory').value), configured_disk_gib: Number(byId('host-capacity-disk').value), safety_cpu_cores: Number(byId('host-safety-cpu').value), safety_memory_mib: Number(byId('host-safety-memory').value), safety_disk_gib: Number(byId('host-safety-disk').value), max_instances: Number(byId('host-max-instances').value) }; } +function schedulingBody() { return { configured_cpu_cores: Number(byId('host-capacity-cpu').value), configured_memory_mib: Number(byId('host-capacity-memory').value), configured_disk_gib: Number(byId('host-capacity-disk').value), safety_cpu_cores: Number(byId('host-safety-cpu').value), safety_memory_mib: Number(byId('host-safety-memory').value), safety_disk_gib: Number(byId('host-safety-disk').value), max_instances: Number(byId('host-max-instances').value) }; } +function syncCachedHostScheduling(hostId, payload) { + if (!payload?.host) return; + const update = host => { + if (!host || Number(host.id) !== Number(hostId)) return; + host.resource_pool_id = payload.host.resource_pool_id; + host.scheduler_state = payload.host.scheduler_state; + host.placement = payload.placement || null; + host.memberships = Array.isArray(payload.memberships) ? payload.memberships : []; + if (payload.capacity) host.capacity = payload.capacity; + }; + state.hosts.forEach(update); + for (const region of state.hostRegions) collection(region, 'hosts').forEach(update); + renderHosts(); +} async function saveHostScheduling(event) { event.preventDefault(); if (!canManage || state.schedulingBusy) return; const hostId = byId('host-scheduling-host-id').value; if (!hostId) return; - state.schedulingBusy = true; const button = byId('host-scheduling-save'); if (button) button.disabled = true; hostSchedulingNotice('正在保存调度配置…'); - try { const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling`, { method: 'PUT', body: schedulingBody() }); renderHostScheduling(payload); const host = state.hosts.find(item => Number(item.id) === Number(hostId)); if (host) { host.resource_pool_id = payload.host.resource_pool_id; host.scheduler_state = payload.host.scheduler_state; renderHosts(); } hostSchedulingNotice('调度配置已保存,容量将按面板预留和 IP 账本实时计算。'); } + if (event.currentTarget?.reportValidity && !event.currentTarget.reportValidity()) return; + state.schedulingBusy = true; const button = byId('host-scheduling-save'); if (button) button.disabled = true; hostSchedulingNotice('正在保存宿主机全局容量…'); + try { const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling`, { method: 'PUT', body: schedulingBody() }); renderHostScheduling(payload); syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('全局容量已保存,资源池成员配置未被改动。'); } catch (error) { hostSchedulingNotice(error.message, true); } - finally { state.schedulingBusy = false; if (button) button.disabled = false; } + finally { state.schedulingBusy = false; if (button) button.disabled = !canManage; } +} +function membershipBody(form) { + return { + scheduler_state: form.elements.namedItem('scheduler_state').value, + priority: Number(form.elements.namedItem('priority').value), + weight: Number(form.elements.namedItem('weight').value), + expected_revision: Number(form.dataset.revision), + }; +} +async function createHostMembership(event) { + event.preventDefault(); if (!canManage || state.schedulingBusy) return; + const form = event.currentTarget; if (form.reportValidity && !form.reportValidity()) return; + const hostId = byId('host-scheduling-host-id').value; const poolId = byId('host-membership-pool').value; + if (!hostId || !poolId) return; + const button = byId('host-membership-add'); state.schedulingBusy = true; if (button) button.disabled = true; hostSchedulingNotice('正在新增资源池成员…'); + try { + const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling/memberships/${encodeURIComponent(poolId)}`, { method: 'PUT', body: { scheduler_state: byId('host-membership-new-state').value, priority: Number(byId('host-membership-new-priority').value), weight: Number(byId('host-membership-new-weight').value), expected_revision: 0 } }); + renderHostScheduling(payload); syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('资源池成员已新增。'); + } catch (error) { hostSchedulingNotice(error.message, true); } + finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = !canManage || byId('host-membership-pool').disabled; } +} +async function saveHostMembership(event) { + event.preventDefault(); if (!canManage || state.schedulingBusy) return; + const form = event.currentTarget; if (form.reportValidity && !form.reportValidity()) return; + const hostId = byId('host-scheduling-host-id').value; const poolId = form.dataset.poolId; + if (!hostId || !poolId) return; + const button = form.querySelector('[data-host-membership-save]'); state.schedulingBusy = true; if (button) button.disabled = true; hostSchedulingNotice(`正在保存资源池 #${poolId} 的成员配置…`); + try { + const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling/memberships/${encodeURIComponent(poolId)}`, { method: 'PUT', body: membershipBody(form) }); + renderHostScheduling(payload); syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('资源池成员配置已保存。'); + } catch (error) { hostSchedulingNotice(error.message, true); } + finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = false; } +} +async function deleteHostMembership(item, button) { + if (!canManage || state.schedulingBusy) return; + const confirmed = await window.VenixAdminDangerDialog.confirm({ tone: 'warning', title: '删除资源池成员', message: `将从宿主机移除“${membershipPath(item)}”成员关系。存在实例或资源预留时服务端会拒绝删除。`, confirmText: '删除成员' }); + if (!confirmed) return; + const hostId = byId('host-scheduling-host-id').value; if (!hostId) return; + state.schedulingBusy = true; if (button) button.disabled = true; hostSchedulingNotice(`正在删除资源池 #${item.resource_pool_id} 的成员关系…`); + try { + const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling/memberships/${encodeURIComponent(item.resource_pool_id)}`, { method: 'DELETE', body: { expected_revision: Number(item.revision) } }); + renderHostScheduling(payload); syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('资源池成员已删除。'); + } catch (error) { hostSchedulingNotice(error.message, true); } + finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = false; } } function networkPoolStateLabel(value) { return ({ active: '启用分配', draining: '排空', disabled: '停用' })[value] || '状态异常'; } function networkPoolInput(type, name, value, options = {}) { @@ -849,7 +986,7 @@ async function initialize() { byId('host-network-type').addEventListener('change', updateHostNetworkControls); byId('host-storage-form').addEventListener('submit', saveHostStorage); byId('host-storage-close').addEventListener('click', closeHostStorage); const storageDrawer = byId('host-storage-drawer'); storageDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostStorage(); }); storageDrawer.addEventListener('click', event => { if (event.target === storageDrawer) closeHostStorage(); }); - byId('host-scheduling-form').addEventListener('submit', saveHostScheduling); byId('host-scheduling-close').addEventListener('click', closeHostScheduling); + byId('host-scheduling-form').addEventListener('submit', saveHostScheduling); byId('host-membership-create-form').addEventListener('submit', createHostMembership); byId('host-scheduling-close').addEventListener('click', closeHostScheduling); const schedulingDrawer = byId('host-scheduling-drawer'); schedulingDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostScheduling(); }); schedulingDrawer.addEventListener('click', event => { if (event.target === schedulingDrawer) closeHostScheduling(); }); byId('host-network-pools-close').addEventListener('click', closeHostNetworkPools); byId('host-network-pool-add')?.addEventListener('click', showNetworkPoolCreate); byId('host-network-pool-create-cancel').addEventListener('click', hideNetworkPoolCreate); byId('host-network-pool-create-form').addEventListener('submit', createHostNetworkPool); const networkDrawer = byId('host-network-pools-drawer'); networkDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkPools(); }); networkDrawer.addEventListener('click', event => { if (event.target === networkDrawer) closeHostNetworkPools(); }); diff --git a/web/resources/views/venix/admin/hosts/index.tpl b/web/resources/views/venix/admin/hosts/index.tpl index 36ac80f4..49913947 100644 --- a/web/resources/views/venix/admin/hosts/index.tpl +++ b/web/resources/views/venix/admin/hosts/index.tpl @@ -134,29 +134,45 @@

请选择宿主机。

-
- -
-
- -
放置策略

排空会停止接收新实例;停用会完全退出自动调度。

-
+ +
+
+ +
资源池成员

同地区可加入多个线路资源池;每个成员独立控制调度状态、优先级与权重。

+
+
- - -
+ + +
-
- - + +
+
+ + +
+
+ + +
+
+ {if $admin_can_manage|default:false} + + {/if} +
-
+
+
+ +
@@ -185,7 +201,7 @@ 公网 IP 由面板地址池配置和账本维护,Agent 只应用宿主机网络配置。
{if $admin_can_manage|default:false} - + {/if}
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 3e69cae6..400ae57a 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110203' scope='global'} +{assign var=venix_asset_version value='2026110204' scope='global'} diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 86a3d953..9ae84a46 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -123,11 +123,10 @@ CREATE TABLE cloud_host_storage_configurations ( UNIQUE KEY cloud_host_storage_operation (operation_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; --- A physical host may eventually participate in more than one commercial --- resource pool. Compute capacity remains host-global; this relation only --- controls which pools may schedule work onto the host. The first multi-CIDR --- release keeps at most one active membership per host in application logic, --- while the schema is already safe for a later multi-line rollout. +-- A physical host may participate in several commercial resource pools in one +-- physical region. Compute capacity remains host-global; each independently +-- revisioned relation controls only whether and how its exact pool may place +-- work onto the host. CREATE TABLE cloud_host_resource_pool_memberships ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, host_id BIGINT UNSIGNED NOT NULL, @@ -135,6 +134,7 @@ CREATE TABLE cloud_host_resource_pool_memberships ( scheduler_state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'disabled', priority INT NOT NULL DEFAULT 0, weight SMALLINT UNSIGNED NOT NULL DEFAULT 100, + revision BIGINT UNSIGNED NOT NULL DEFAULT 1, created_at BIGINT UNSIGNED NOT NULL, updated_at BIGINT UNSIGNED NOT NULL, UNIQUE KEY cloud_host_pool_membership (host_id, resource_pool_id), diff --git a/web/tests/AdminHostSchedulingBehaviorTest.mjs b/web/tests/AdminHostSchedulingBehaviorTest.mjs new file mode 100644 index 00000000..1b669cd9 --- /dev/null +++ b/web/tests/AdminHostSchedulingBehaviorTest.mjs @@ -0,0 +1,187 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import vm from 'node:vm'; + +const adminSource = await readFile( + new URL('../public/cloud/admin-hosts.js', import.meta.url), 'utf8'); +const source = adminSource.slice(adminSource.indexOf('const root =')) + .replace('void initialize();', '') + + `\nglobalThis.hostSchedulingUI = { + renderHostScheduling, schedulingBody, saveHostScheduling, + createHostMembership, saveHostMembership, deleteHostMembership, state, + };`; + +const descendants = node => [node, ...(node?.children || []).flatMap(descendants)]; + +function fixture(canManage = true) { + const elements = new Map(); + const requests = []; + let response = null; + + class Element { + constructor(tag = 'input') { + this.tag = tag; this.value = ''; this.textContent = ''; this.className = ''; + this.name = ''; this.type = ''; this.dataset = {}; this.children = []; + this.disabled = false; this.hidden = false; this.isConnected = true; + this.listeners = new Map(); + this.classList = { add() {}, remove() {}, toggle() {} }; + } + get elements() { + return { namedItem: name => descendants(this).find(node => node.name === name) || null }; + } + append(...children) { this.children.push(...children); } + replaceChildren(...children) { + for (const child of this.children) for (const node of descendants(child)) node.isConnected = false; + this.children = children; + } + addEventListener(name, listener) { this.listeners.set(name, listener); } + querySelector(selector) { + if (selector === '[data-host-membership-save]') { + return descendants(this).find(node => Object.hasOwn(node.dataset, 'hostMembershipSave')) || null; + } + return null; + } + reportValidity() { return true; } + } + + const selectIds = new Set([ + 'host-membership-pool', 'host-membership-new-state', + ]); + const get = id => { + if (!elements.has(id)) elements.set(id, new Element(selectIds.has(id) ? 'select' : 'input')); + return elements.get(id); + }; + const root = { dataset: { cloudAdmin: 'hosts', canManage: canManage ? '1' : '0' } }; + const runtime = { + create: () => ({ + read: async path => ({ payload: response, path }), + mutate: async (path, options) => { + requests.push({ path, ...options }); + return { payload: response }; + }, + }), + }; + const context = { + document: { + querySelector: () => root, + getElementById: get, + createElement: tag => new Element(tag), + }, + ADMIN_CSRF_TOKEN: 'a'.repeat(64), + VenixAdminRequestRuntime: runtime, + VenixAdminDangerDialog: { confirm: async () => true }, + VenixDrawerMotion: {}, + taskUrl: () => '', + location: { assign() {} }, + Headers, AbortController, setTimeout, clearTimeout, + }; + context.window = context; + vm.runInNewContext(source, context, { filename: 'admin-hosts.js' }); + return { + ...context.hostSchedulingUI, + get, + requests, + descendants: id => descendants(get(id)), + respond(payload) { response = payload; }, + }; +} + +const capacity = { + cpu: { allocated: 1, reserved: 0, free: 7 }, + memory: { allocated: 1024, reserved: 0, free: 7168 }, + disk: { allocated: 20, reserved: 0, free: 180 }, + instances: { allocated: 1, reserved: 0 }, + ip: { available: 4, total: 8 }, +}; +const policy = { + configured_cpu_cores: 8, configured_memory_mib: 8192, + configured_disk_gib: 200, safety_cpu_cores: 0, + safety_memory_mib: 0, safety_disk_gib: 0, max_instances: 20, +}; +const pools = [ + { id: 11, name: 'Premium', status: 'active', line_name: 'CN2', line_status: 'active', region_name: 'Hong Kong', region_status: 'active' }, + { id: 12, name: 'Standard', status: 'active', line_name: 'Global', line_status: 'active', region_name: 'Hong Kong', region_status: 'active' }, +]; +const membership = { + resource_pool_id: 11, pool_name: 'Premium', line_name: 'CN2', + region_name: 'Hong Kong', scheduler_state: 'active', priority: 10, + weight: 200, revision: 4, warnings: [], +}; +const payload = { + host: { id: 7, name: 'HKG-A', enabled: true, resource_pool_id: 11, scheduler_state: 'active' }, + policy, capacity, pools, memberships: [membership], warnings: [], + network_lines_enabled: true, +}; + +const test = fixture(); +test.respond(payload); +test.renderHostScheduling(payload); + +assert.deepEqual(test.get('host-membership-pool').children.map(option => option.value), ['', '12'], + 'Assigned resource pools remained selectable as new memberships.'); +const cards = test.descendants('host-membership-list'); +assert.ok(cards.some(node => node.dataset.hostMembership === '11')); +assert.ok(cards.some(node => /Hong Kong \/ CN2 \/ Premium/.test(node.textContent))); +const memberForm = cards.find(node => node.dataset.hostMembershipForm === ''); +assert.equal(memberForm.dataset.revision, '4'); +assert.equal(memberForm.elements.namedItem('scheduler_state').value, 'active'); +assert.equal(memberForm.elements.namedItem('priority').value, '10'); +assert.equal(memberForm.elements.namedItem('weight').value, '200'); + +assert.deepEqual({ ...test.schedulingBody() }, policy, + 'The global capacity payload still contained membership fields.'); +await test.saveHostScheduling({ preventDefault() {}, currentTarget: test.get('host-scheduling-form') }); +assert.equal(test.requests.at(-1).path, '/api/v1/admin/hosts/7/scheduling'); +assert.equal(test.requests.at(-1).method, 'PUT'); +assert.deepEqual({ ...test.requests.at(-1).body }, policy); + +const withSecond = { + ...payload, + memberships: [membership, { ...membership, resource_pool_id: 12, pool_name: 'Standard', line_name: 'Global', scheduler_state: 'disabled', priority: 0, weight: 100, revision: 1 }], +}; +test.respond(withSecond); +test.get('host-membership-pool').value = '12'; +test.get('host-membership-new-state').value = 'disabled'; +test.get('host-membership-new-priority').value = '0'; +test.get('host-membership-new-weight').value = '100'; +await test.createHostMembership({ preventDefault() {}, currentTarget: test.get('host-membership-create-form') }); +assert.equal(test.requests.at(-1).path, '/api/v1/admin/hosts/7/scheduling/memberships/12'); +assert.equal(test.requests.at(-1).method, 'PUT'); +assert.deepEqual({ ...test.requests.at(-1).body }, { + scheduler_state: 'disabled', priority: 0, weight: 100, expected_revision: 0, +}); + +const updatedForms = test.descendants('host-membership-list'); +const firstForm = updatedForms.find(node => node.dataset.hostMembershipForm === '' && node.dataset.poolId === '11'); +firstForm.elements.namedItem('scheduler_state').value = 'draining'; +firstForm.elements.namedItem('priority').value = '30'; +firstForm.elements.namedItem('weight').value = '300'; +test.respond({ ...withSecond, memberships: [{ ...membership, scheduler_state: 'draining', priority: 30, weight: 300, revision: 5 }, withSecond.memberships[1]] }); +await test.saveHostMembership({ preventDefault() {}, currentTarget: firstForm }); +assert.equal(test.requests.at(-1).path, '/api/v1/admin/hosts/7/scheduling/memberships/11'); +assert.deepEqual({ ...test.requests.at(-1).body }, { + scheduler_state: 'draining', priority: 30, weight: 300, expected_revision: 4, +}); + +test.respond({ ...payload, memberships: [] }); +await test.deleteHostMembership({ ...membership, revision: 5 }, null); +assert.equal(test.requests.at(-1).method, 'DELETE'); +assert.equal(test.requests.at(-1).path, '/api/v1/admin/hosts/7/scheduling/memberships/11'); +assert.deepEqual({ ...test.requests.at(-1).body }, { expected_revision: 5 }); + +const viewer = fixture(false); +viewer.respond(payload); +viewer.renderHostScheduling(payload); +const viewerForm = viewer.descendants('host-membership-list') + .find(node => node.dataset.hostMembershipForm === ''); +assert.equal(viewerForm.elements.namedItem('scheduler_state').disabled, true); +assert.equal(viewerForm.elements.namedItem('priority').disabled, true); +assert.equal(viewerForm.elements.namedItem('weight').disabled, true); +assert.equal(viewer.descendants('host-membership-list') + .some(node => Object.hasOwn(node.dataset, 'hostMembershipSave')), false); +await viewer.saveHostScheduling({ preventDefault() {}, currentTarget: viewer.get('host-scheduling-form') }); +await viewer.createHostMembership({ preventDefault() {}, currentTarget: viewer.get('host-membership-create-form') }); +assert.equal(viewer.requests.length, 0, + 'Read-only administrators could submit host scheduling mutations.'); + +console.log('Administrator host capacity, independent membership and read-only UI behavior passed.'); diff --git a/web/tests/AdminHostSchedulingContractTest.php b/web/tests/AdminHostSchedulingContractTest.php index dd78bb41..d10a6655 100644 --- a/web/tests/AdminHostSchedulingContractTest.php +++ b/web/tests/AdminHostSchedulingContractTest.php @@ -29,95 +29,117 @@ $script = $read('public/cloud/admin-hosts.js'); $assets = $read('resources/views/venix/layout_assets.tpl'); $assert(str_contains($routes, "'/admin/hosts/{id:[0-9]+}/scheduling'") + && str_contains($routes, + "'/admin/hosts/{id:[0-9]+}/scheduling/memberships/{resource_pool_id:[1-9][0-9]*}'") && !str_contains($routes, '/capacity-sync'), - 'Host scheduling must be registered without the retired inventory sync route.'); -$assert(str_contains($middleware, '/scheduling$#D') + 'Host capacity and independent membership routes are incomplete.'); +$assert(str_contains($middleware, '/scheduling') + && str_contains($middleware, 'memberships') && !str_contains($middleware, 'capacity-sync') && str_contains($controller, '$this->actor($request, $write)') && str_contains($controller, '$this->actor($request, true)'), - 'Scheduling reads must allow administrators while writes stay super-admin only.'); -$assert(str_contains($controller, "'resource_pool_id', 'scheduler_state'") - && !str_contains(substr($controller, - strpos($controller, 'public function hostScheduling'), - strpos($controller, 'public function userIsoSettings') - - strpos($controller, 'public function hostScheduling')), 'public_ip'), - 'The scheduling allowlist must not accept manual public IP fields.'); -$assert(str_contains($controller, 'CloudAdminHostProjectionService::listing()') - && str_contains($controller, 'CloudAdminHostProjectionService::one(') - && str_contains($projectionService, - 'CloudHostPoolMembershipService::selected($memberships)') + 'Scheduling reads and writes lost their database-only authorization boundary.'); +$hostSchedulingStart = strpos($controller, + 'public function hostScheduling'); +$hostSchedulingEnd = strpos($controller, + 'public function hostStorageConfiguration', $hostSchedulingStart); +$hostScheduling = $hostSchedulingStart === false + || $hostSchedulingEnd === false ? '' : substr( + $controller, + $hostSchedulingStart, + $hostSchedulingEnd - $hostSchedulingStart + ); +$assert(str_contains($controller, + 'CloudAdminHostSchedulingService::saveCapacity') + && str_contains($controller, + 'CloudAdminHostSchedulingService::saveMembership') + && str_contains($controller, + 'CloudAdminHostSchedulingService::deleteMembership') + && str_contains($controller, "'expected_revision'") + && $hostScheduling !== '' + && !str_contains($hostScheduling, 'public_ip'), + 'Controller dispatch does not keep capacity and membership mutations separate.'); + +$assert(str_contains($projectionService, + 'CloudHostPoolMembershipService::primary(') && !str_contains($projectionService, '$host->resource_pool_id') && !str_contains($projectionService, '$host->scheduler_state'), - 'Host API projection must use the selected membership authority.'); - -$saveStart = strpos($service, 'public static function save'); -$saveEnd = strpos($service, 'private static function validateActive', $saveStart); -$save = $saveStart === false || $saveEnd === false ? '' - : substr($service, $saveStart, $saveEnd - $saveStart); -$hostLock = strpos($save, "CloudHost::where('id', \$hostId)->lockForUpdate()"); -$membershipLock = strpos($save, 'CloudHostPoolMembershipService::lockedRows'); -$policyLock = strpos($save, "CloudHostCapacityPolicy::where('host_id', \$hostId)"); -$attachmentLock = strpos($save, 'assertNetworkLine($host, $line)'); -$assert($save !== '' && $hostLock !== false && $membershipLock !== false - && $policyLock !== false && $attachmentLock !== false - && $hostLock < $membershipLock && $membershipLock < $policyLock - && $policyLock < $attachmentLock - && str_contains($service, '->lockForUpdate()->first();'), - 'Scheduling writes must lock host, membership, policy and network guard in order.'); -$assert(str_contains($service, 'CloudHostPoolMembershipService::replaceLocked(') - && str_contains($service, "'memberships' => \$memberships->map") - && str_contains($membershipService, - 'CloudHostResourcePoolMembership::where(\'host_id\'') - && str_contains($membershipService, - 'public static function selected($rows)') - && !str_contains($membershipService, '$host->resource_pool_id') - && str_contains($membershipService, 'public const SAFE_PRIORITY = 0;') - && str_contains($membershipService, 'public const SAFE_WEIGHT = 100;') - && str_contains($membershipService, '$row->delete();') - && str_contains($membershipService, - '宿主机存在多个启用中的资源池成员关系'), - 'Fresh membership authority or first-release single-row policy is missing.'); -$assert(str_contains($service, "\$schedulerState === 'active'") - && str_contains($service, 'CloudNetworkLineFeature::enabled()') - && str_contains($service, "(string) \$pool->status !== 'active'") - && str_contains($service, "(string) \$region->status !== 'active'") - && str_contains($service, '$safety >= $configured'), - 'Active scheduling must validate the host, pool hierarchy and safety reserves.'); -$assert(str_contains($service, 'assertReservationLine($host, $pool, $line)') + 'Host projection must derive compact placement from membership authority.'); +$assert(str_contains($service, 'public static function saveCapacity(') + && str_contains($service, 'public static function saveMembership(') + && str_contains($service, 'public static function deleteMembership(') && str_contains($service, - "->whereIn('state', ['held', 'uncertain', 'committed'])") + 'CloudHostPoolMembershipService::upsertLocked(') && str_contains($service, - '宿主机仍有其他线路的实例或资源预留,不能跨线路更换资源池'), - 'Hosts with live reservations must not move their configured network line across sales lines.'); -$assert(str_contains($service, 'assertNetworkLine($host, $line)') - && str_contains($service, 'CloudHostNetworkAttachment::where(') - && str_contains($service, 'CloudPublicIpPool::where(') + 'CloudHostPoolMembershipService::removeLocked(') && str_contains($service, - '宿主机已有其他线路的公网网络接入,不能静默跨线路更换资源池'), - 'Configured network attachments must prevent silent cross-line relabeling.'); + '同一宿主机的启用或排空资源池成员必须属于同一地区') + && str_contains($service, + '该资源池成员仍有实例或资源预留,不能停用或删除'), + 'Scheduling service lost independent multi-membership CAS behavior.'); +$assert(str_contains($membershipService, 'public static function activeRows(') + && str_contains($membershipService, 'public static function primary(') + && str_contains($membershipService, 'public static function upsertLocked(') + && str_contains($membershipService, 'public static function removeLocked(') + && str_contains($membershipService, 'expectedRevision') + && !str_contains($membershipService, '$host->resource_pool_id'), + 'Membership authority does not expose independent revisioned rows.'); $assert(!str_contains($service, 'CloudHostInventorySyncService') && !str_contains($service, 'syncOne(') && str_contains($service, 'hostUsage(') - && str_contains($service, 'capacityDto('), - 'Scheduling capacity must come from panel policy and reservation/IP ledgers without inventory sync.'); + && str_contains($service, 'network_attachment.line_id'), + 'Scheduling capacity or IP ownership regressed to host inventory/default-network coupling.'); $assert(str_contains($template, 'data-admin-host-scheduling-drawer') + && str_contains($template, 'id="host-membership-create-form"') + && str_contains($template, 'id="host-membership-pool"') + && str_contains($template, 'id="host-membership-list"') + && str_contains($template, 'id="host-scheduling-form"') && str_contains($template, 'id="host-panel-capacity"') - && str_contains($template, '{if $admin_can_manage|default:false}') - && str_contains($template, '不扫描宿主机') - && str_contains($template, '公网 IP 由面板地址池配置和账本维护') - && !str_contains($template, 'host-capacity-sync') - && !str_contains($template, '宿主机盘点'), - 'The host drawer must expose panel-owned capacity and IP ledger controls.'); -$assert(str_contains($script, 'window.VenixDrawerMotion.openDrawerWithMotion') - && str_contains($script, 'window.VenixDrawerMotion.closeDrawerWithMotion') - && str_contains($script, '/scheduling') + && str_contains($template, '保存全局容量') + && !str_contains($template, 'id="host-resource-pool"') + && !str_contains($template, 'id="host-scheduler-state"') + && !str_contains($template, 'host-capacity-sync'), + 'Host drawer did not replace its single placement selector with membership rows.'); + +$capacityBodyStart = strpos($script, 'function schedulingBody()'); +$capacityBodyEnd = strpos($script, 'function syncCachedHostScheduling', + $capacityBodyStart); +$capacityBody = $capacityBodyStart === false || $capacityBodyEnd === false + ? '' : substr($script, $capacityBodyStart, + $capacityBodyEnd - $capacityBodyStart); +$assert($capacityBody !== '' + && str_contains($capacityBody, 'configured_cpu_cores') + && str_contains($capacityBody, 'max_instances') + && !str_contains($capacityBody, 'resource_pool_id') + && !str_contains($capacityBody, 'scheduler_state'), + 'Global capacity PUT still contains a membership mutation.'); +$assert(str_contains($script, 'function renderHostMemberships(') + && str_contains($script, 'dataset.hostMembershipForm') + && str_contains($script, 'item?.region_name') + && str_contains($script, 'item?.line_name') + && str_contains($script, 'item?.pool_name') + && str_contains($script, 'item.priority') + && str_contains($script, 'item.weight') + && str_contains($script, 'item.revision') + && str_contains($script, + '/scheduling/memberships/${encodeURIComponent(poolId)}') + && str_contains($script, "method: 'PUT'") + && str_contains($script, "method: 'DELETE'") + && str_contains($script, 'expected_revision: 0') + && str_contains($script, 'VenixAdminDangerDialog.confirm') + && str_contains($script, + 'window.VenixDrawerMotion.openDrawerWithMotion') + && str_contains($script, + 'window.VenixDrawerMotion.closeDrawerWithMotion') && !str_contains($script, '/capacity-sync'), - 'The host drawer must reuse shared motion and the panel scheduling endpoint.'); -$assert(preg_match("/venix_asset_version value='([0-9]+)'/", $assets, $match) === 1 - && (int) $match[1] >= 2026100313, - 'Shared asset version must be bumped for admin-hosts.js changes.'); -$assert(!file_exists($root . '/public/cloud/admin-host-scheduling.css'), - 'Host scheduling must not introduce a standalone CSS file.'); + 'Membership rendering or independent PUT/DELETE behavior is incomplete.'); +$assert(preg_match("/venix_asset_version value='([0-9]+)'/", $assets, + $match) === 1 + && (int) $match[1] >= 2026110204, + 'Shared asset version was not bumped for the scheduling UI change.'); +$assert(file_exists($root . '/tests/AdminHostSchedulingBehaviorTest.mjs') + && !file_exists($root . '/public/cloud/admin-host-scheduling.css'), + 'Scheduling UI must retain shared styling and have a DOM behavior test.'); -echo "Administrator host scheduling contract checks passed.\n"; +echo "Administrator host multi-membership scheduling contracts passed.\n"; diff --git a/web/tests/AdminResourceProjectionContractTest.php b/web/tests/AdminResourceProjectionContractTest.php index db96b2b9..278aec6d 100644 --- a/web/tests/AdminResourceProjectionContractTest.php +++ b/web/tests/AdminResourceProjectionContractTest.php @@ -2,6 +2,7 @@ use App\Services\Cloud\CloudAdminResourceService; use App\Services\Cloud\CloudError; +use App\Models\CloudHostAgent; require dirname(__DIR__) . '/vendor/autoload.php'; @@ -34,9 +35,26 @@ $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, 'CloudNetworkSelector::isValid(') + && 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, selector, network and capacity gates.'); + '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' =>") @@ -114,7 +132,6 @@ $assert($immutableRejected, $health = [ 'host_count' => 1, 'enabled_host_count' => 1, - 'network_selector_ready_host_count' => 1, 'scheduler_active_host_count' => 1, 'agent_ready_host_count' => 1, 'storage_ready_host_count' => 1, @@ -140,4 +157,50 @@ $assert($blocked['state'] === 'blocked' && 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"; diff --git a/web/tests/AdminResourceProjectionWorkflowTest.php b/web/tests/AdminResourceProjectionWorkflowTest.php index a6917451..09ada81a 100644 --- a/web/tests/AdminResourceProjectionWorkflowTest.php +++ b/web/tests/AdminResourceProjectionWorkflowTest.php @@ -69,6 +69,7 @@ $schema->create('cloud_host_resource_pool_memberships', $table->increments('id'); $table->integer('host_id'); $table->integer('resource_pool_id'); + $table->integer('revision')->default(1); }); $schema->create('cloud_resource_reservations', function (Blueprint $table): void { diff --git a/web/tests/CloudAdminHostListProjectionTest.php b/web/tests/CloudAdminHostListProjectionTest.php index f525a45c..4a65cf51 100644 --- a/web/tests/CloudAdminHostListProjectionTest.php +++ b/web/tests/CloudAdminHostListProjectionTest.php @@ -39,6 +39,7 @@ $schema->create('cloud_host_resource_pool_memberships', $table->string('scheduler_state'); $table->integer('priority'); $table->integer('weight'); + $table->integer('revision')->default(1); $table->integer('created_at'); $table->integer('updated_at'); $table->unique(['host_id', 'resource_pool_id']); @@ -97,6 +98,7 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->string('last_test_status'); $table->string('last_error_code'); $table->string('last_agent_version'); + $table->text('network_selectors_json'); $table->integer('last_tested_at'); $table->integer('created_at'); $table->integer('updated_at'); @@ -148,6 +150,8 @@ $schema->create('cloud_host_network_attachments', $table->string('network_selector'); $table->string('state'); $table->string('sync_state'); + $table->integer('verified_agent_revision'); + $table->string('verification_state'); $table->integer('observed_revision'); $table->integer('desired_revision'); }); @@ -180,7 +184,7 @@ Capsule::table('cloud_hosts')->insert([ 'default_network' => 'bridge:br0', 'enabled' => 0, 'created_at' => 20, 'updated_at' => 20], ['id' => 1, 'name' => 'Host A', 'region' => 'HongKong', 'country_code' => 'HK', - 'default_network' => 'bridge:br0', 'enabled' => 1, 'created_at' => 10, + 'default_network' => 'bridge:legacy', 'enabled' => 1, 'created_at' => 10, 'updated_at' => 10], ]); Capsule::table('cloud_host_resource_pool_memberships')->insert([ @@ -221,6 +225,7 @@ Capsule::table('cloud_host_agents')->insert([ 'revision' => 2, 'tested_revision' => 2, 'last_test_status' => 'healthy', 'last_error_code' => '', 'last_agent_version' => 'v3', 'last_tested_at' => 100, + 'network_selectors_json' => '["bridge:br0"]', 'created_at' => 1, 'updated_at' => 100, ]); Capsule::table('cloud_host_storage_configurations')->insert([ @@ -244,7 +249,8 @@ Capsule::table('cloud_instances')->insert([ Capsule::table('cloud_host_network_attachments')->insert([ 'id' => 1, 'host_id' => 1, 'line_id' => 1, 'network_selector' => 'bridge:br0', 'state' => 'active', - 'sync_state' => 'applied', 'observed_revision' => 1, + 'sync_state' => 'never', 'verified_agent_revision' => 2, + 'verification_state' => 'verified', 'observed_revision' => 0, 'desired_revision' => 1, ]); Capsule::table('cloud_public_ip_pools')->insert([ diff --git a/web/tests/CloudAdminHostMultiMembershipProjectionTest.php b/web/tests/CloudAdminHostMultiMembershipProjectionTest.php new file mode 100644 index 00000000..15737a6d --- /dev/null +++ b/web/tests/CloudAdminHostMultiMembershipProjectionTest.php @@ -0,0 +1,364 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('configurations', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name')->unique(); + $table->text('value'); +}); +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); + $table->string('region'); + $table->string('country_code', 2); + $table->string('default_network'); + $table->boolean('enabled'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->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('priority'); + $table->integer('weight'); + $table->integer('revision'); + $table->integer('created_at'); + $table->integer('updated_at'); + }); +$schema->create('cloud_regions', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('code'); + $table->string('name'); + $table->string('country_code', 2); + $table->string('status'); + $table->integer('sort'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_network_lines', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('region_id'); + $table->string('code'); + $table->string('name'); + $table->boolean('is_default'); + $table->string('status'); + $table->integer('sort'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_resource_pools', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('line_id'); + $table->string('code'); + $table->string('name'); + $table->string('status'); + $table->string('scheduling_policy'); + $table->integer('sort'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_offers', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('resource_pool_id'); +}); +$schema->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'); + $table->integer('safety_cpu_cores'); + $table->integer('safety_memory_mib'); + $table->integer('safety_disk_gib'); + $table->integer('max_instances'); + $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'); + $table->integer('revision'); + $table->integer('tested_revision'); + $table->string('last_test_status'); + $table->string('last_error_code'); + $table->string('last_agent_version'); + $table->text('network_selectors_json'); + $table->integer('last_tested_at'); + $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'); + $table->string('state'); + $table->integer('created_at'); + $table->integer('updated_at'); + }); +$schema->create('cloud_resource_reservations', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->string('state'); + $table->integer('instance_id')->nullable(); + $table->integer('cpu_cores'); + $table->integer('memory_mib'); + $table->integer('disk_gib'); + }); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->string('status'); + $table->text('spec_json'); +}); +$schema->create('cloud_instance_snapshots', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('host_id'); + $table->string('state'); + $table->integer('size_bytes')->nullable(); + }); +$schema->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('sync_state'); + $table->integer('verified_agent_revision'); + $table->string('verification_state'); + $table->integer('observed_revision'); + $table->integer('desired_revision'); + }); +$schema->create('cloud_public_ip_pools', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('network_attachment_id'); + $table->string('pool_key'); + $table->string('cidr'); + $table->integer('guest_prefix_length'); + $table->string('state'); + $table->string('sync_state'); + $table->integer('observed_revision'); + $table->integer('desired_revision'); + }); +$schema->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::table('configurations')->insert([ + 'name' => 'cloud_network_lines_enabled', + 'value' => 'true', +]); +Capsule::table('cloud_hosts')->insert([ + 'id' => 1, + 'name' => 'HKG-A', + 'region' => 'Hong Kong', + 'country_code' => 'HK', + 'default_network' => 'bridge:retired-default', + 'enabled' => 1, + 'created_at' => 1, + 'updated_at' => 1, +]); +Capsule::table('cloud_regions')->insert([ + 'id' => 1, 'code' => 'hkg', 'name' => 'Hong Kong', + 'country_code' => 'HK', 'status' => 'active', 'sort' => 1, + 'created_at' => 1, 'updated_at' => 1, +]); +Capsule::table('cloud_network_lines')->insert([ + ['id' => 10, 'region_id' => 1, 'code' => 'premium', + 'name' => 'Premium', 'is_default' => 0, 'status' => 'active', + 'sort' => 10, 'created_at' => 1, 'updated_at' => 1], + ['id' => 11, 'region_id' => 1, 'code' => 'standard', + 'name' => 'Standard', 'is_default' => 1, 'status' => 'active', + 'sort' => 20, 'created_at' => 1, 'updated_at' => 1], +]); +Capsule::table('cloud_resource_pools')->insert([ + ['id' => 20, 'line_id' => 10, 'code' => 'premium-pool', + 'name' => 'Premium Pool', 'status' => 'active', + 'scheduling_policy' => 'balanced', 'sort' => 10, + 'created_at' => 1, 'updated_at' => 1], + ['id' => 21, 'line_id' => 11, 'code' => 'standard-pool', + 'name' => 'Standard Pool', 'status' => 'active', + 'scheduling_policy' => 'balanced', 'sort' => 20, + 'created_at' => 1, 'updated_at' => 1], +]); +Capsule::table('cloud_host_resource_pool_memberships')->insert([ + ['id' => 30, 'host_id' => 1, 'resource_pool_id' => 20, + 'scheduler_state' => 'active', 'priority' => 20, 'weight' => 100, + 'revision' => 1, 'created_at' => 1, 'updated_at' => 1], + ['id' => 31, 'host_id' => 1, 'resource_pool_id' => 21, + 'scheduler_state' => 'active', 'priority' => 10, 'weight' => 100, + 'revision' => 2, 'created_at' => 1, 'updated_at' => 1], +]); +Capsule::table('cloud_host_capacity_policies')->insert([ + 'host_id' => 1, 'configured_cpu_cores' => 16, + 'configured_memory_mib' => 32768, 'configured_disk_gib' => 800, + 'safety_cpu_cores' => 2, 'safety_memory_mib' => 1024, + 'safety_disk_gib' => 50, 'max_instances' => 50, + 'created_at' => 1, 'updated_at' => 1, +]); +Capsule::table('cloud_host_agents')->insert([ + 'host_id' => 1, 'sealed_api_secret' => 'sealed', 'enabled' => 1, + 'revision' => 1, 'tested_revision' => 1, + 'last_test_status' => 'healthy', 'last_error_code' => '', + 'last_agent_version' => 'v3', 'last_tested_at' => 1, + 'network_selectors_json' => json_encode([ + 'bridge:br-premium', 'bridge:br-standard', + ], JSON_THROW_ON_ERROR), + 'created_at' => 1, 'updated_at' => 1, +]); +Capsule::table('cloud_host_storage_configurations')->insert([ + 'host_id' => 1, 'revision' => 1, 'state' => 'applied', + 'created_at' => 1, 'updated_at' => 1, +]); +Capsule::table('cloud_host_network_attachments')->insert([ + ['id' => 40, 'host_id' => 1, 'line_id' => 10, + 'network_selector' => 'bridge:br-premium', 'state' => 'active', + 'sync_state' => 'never', 'verified_agent_revision' => 1, + 'verification_state' => 'verified', 'observed_revision' => 0, + 'desired_revision' => 2], + ['id' => 41, 'host_id' => 1, 'line_id' => 11, + 'network_selector' => 'bridge:br-standard', 'state' => 'active', + 'sync_state' => 'never', 'verified_agent_revision' => 1, + 'verification_state' => 'verified', 'observed_revision' => 0, + 'desired_revision' => 3], +]); +Capsule::table('cloud_public_ip_pools')->insert([ + ['id' => 50, 'host_id' => 1, 'network_attachment_id' => 40, + 'pool_key' => str_repeat('a', 32), 'cidr' => '203.0.113.0/29', + 'guest_prefix_length' => 29, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 2, 'desired_revision' => 2], + ['id' => 51, 'host_id' => 1, 'network_attachment_id' => 41, + 'pool_key' => str_repeat('b', 32), 'cidr' => '198.51.100.0/29', + 'guest_prefix_length' => 29, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 3, 'desired_revision' => 3], +]); +Capsule::table('cloud_public_ips')->insert([ + ['id' => 60, 'host_id' => 1, 'public_ip_pool_id' => 50, + 'address' => '203.0.113.2', 'prefix_length' => 29, + 'state' => 'available', 'reservation_id' => null, + 'instance_id' => null, 'operation_id' => null], + ['id' => 61, 'host_id' => 1, 'public_ip_pool_id' => 51, + 'address' => '198.51.100.2', 'prefix_length' => 29, + 'state' => 'available', 'reservation_id' => null, + 'instance_id' => null, 'operation_id' => null], +]); + +$projection = CloudAdminHostProjectionService::listing(); +$assert(count($projection['hosts']) === 1, + 'Expected exactly one physical host projection.'); +$host = $projection['hosts'][0]; +$assert($host['resource_pool_id'] === 21 + && $host['scheduler_state'] === 'active' + && $host['active_memberships'] === 2 + && $host['draining_memberships'] === 0, + 'Compact fields were not a deterministic primary-membership summary.'); +$assert(array_column($host['memberships'], 'resource_pool_id') === [20, 21] + && count(array_filter($host['memberships'], + static fn (array $row): bool => $row['placement_ready'])) === 2 + && array_column($host['lines'], 'id') === [10, 11] + && $host['readiness']['network_ready'] === true + && $host['readiness']['placement_ready'] === true, + 'The host did not expose every exact membership and verified target line.'); +$assert($host['capacity']['cpu']['configured'] === 16 + && $host['capacity']['ip']['available'] === 2 + && $projection['summary']['capacity']['cpu']['configured'] === 16, + 'Physical capacity was duplicated across active memberships.'); + +$resources = CloudAdminResourceService::page(); +$pools = []; +foreach ($resources['pools'] as $pool) { + $pools[(int) $pool['id']] = $pool; +} +$assert(count($resources['hosts']) === 2 + && array_column($resources['hosts'], 'resource_pool_id') === [20, 21] + && $pools[20]['health']['host_count'] === 1 + && $pools[21]['health']['host_count'] === 1, + 'Resource catalog did not map each membership to its exact pool.'); +$assert($pools[20]['capacity_scope'] === 'shared_host' + && $pools[21]['capacity_shared'] === true + && $pools[20]['capacity']['cpu']['configured'] === 16 + && $pools[21]['capacity']['cpu']['configured'] === 16 + && $resources['summary']['hosts_total'] === 1 + && $resources['summary']['placement_ready_hosts'] === 1 + && $resources['summary']['capacity']['cpu']['configured'] === 16 + && $resources['summary']['placement_capacity']['cpu']['configured'] === 16, + 'Shared pool views or platform totals duplicated physical host capacity.'); + +$single = CloudAdminHostProjectionService::one(CloudHost::find(1)); +$assert(count($single['memberships']) === 2 && count($single['lines']) === 2, + 'Single-host projection drifted from the multi-membership list DTO.'); + +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'network_selectors_json' => '[]', +]); +$missingSelector = CloudAdminHostProjectionService::listing()['hosts'][0]; +$assert($missingSelector['readiness']['network_ready'] === false + && $missingSelector['readiness']['placement_ready'] === false + && $missingSelector['capacity']['ip']['available'] === 0, + 'A selector missing from current Agent evidence was advertised as ready.'); +$missingSelectorResources = CloudAdminResourceService::page(); +$assert(count(array_filter( + $missingSelectorResources['hosts'], + static fn (array $row): bool => $row['network_ready'] + )) === 0 + && $missingSelectorResources['summary']['placement_ready_hosts'] === 0 + && $missingSelectorResources['summary']['placement_capacity']['cpu'] + ['configured'] === 0, + 'Resource catalog accepted an attachment absent from Agent evidence.'); + +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'network_selectors_json' => json_encode([ + 'bridge:br-premium', 'bridge:br-standard', + ], JSON_THROW_ON_ERROR), +]); +Capsule::table('cloud_host_network_attachments')->update([ + 'verified_agent_revision' => 0, +]); +$staleRevision = CloudAdminHostProjectionService::listing()['hosts'][0]; +$assert($staleRevision['readiness']['network_ready'] === false + && $staleRevision['capacity']['ip']['available'] === 0, + 'Stale attachment verification was advertised as ready.'); + +echo "Administrator host multi-membership projection passed.\n"; diff --git a/web/tests/CloudAdminHostMultiMembershipServiceTest.php b/web/tests/CloudAdminHostMultiMembershipServiceTest.php new file mode 100644 index 00000000..e0d7fbfa --- /dev/null +++ b/web/tests/CloudAdminHostMultiMembershipServiceTest.php @@ -0,0 +1,334 @@ +httpStatus !== $status) { + throw new RuntimeException( + $message . ': expected HTTP ' . $status . ', got ' + . $error->httpStatus + ); + } + return; + } + throw new RuntimeException($message . ': expected CloudError'); +}; +$membership = static function (array $payload, int $poolId): array { + foreach ($payload['memberships'] as $row) { + if ((int) $row['resource_pool_id'] === $poolId) { + return $row; + } + } + throw new RuntimeException('Missing membership for pool ' . $poolId); +}; + +$capsule = new Capsule(); +$capsule->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('configurations', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name')->unique(); + $table->text('value'); +}); +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); + $table->boolean('enabled'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_regions', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('code'); + $table->string('name'); + $table->string('country_code', 2); + $table->string('status'); + $table->integer('sort'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_network_lines', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('region_id'); + $table->string('code'); + $table->string('name'); + $table->boolean('is_default'); + $table->string('status'); + $table->integer('sort'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_resource_pools', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('line_id'); + $table->string('code'); + $table->string('name'); + $table->string('status'); + $table->string('scheduling_policy'); + $table->integer('sort'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->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('priority'); + $table->integer('weight'); + $table->integer('revision')->default(1); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->unique(['host_id', 'resource_pool_id']); + }); +$schema->create('cloud_host_capacity_policies', + static function (Blueprint $table): void { + $table->integer('host_id')->primary(); + foreach (['configured_cpu_cores', 'configured_memory_mib', + 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', + 'safety_disk_gib', 'max_instances', 'created_at', + 'updated_at'] as $field) { + $table->integer($field); + } + }); +$schema->create('cloud_resource_reservations', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('resource_pool_id'); + $table->string('state'); + $table->integer('instance_id')->nullable(); + $table->integer('cpu_cores'); + $table->integer('memory_mib'); + $table->integer('disk_gib'); + }); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->string('status'); + $table->text('spec_json'); +}); +$schema->create('cloud_instance_snapshots', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('host_id'); + $table->string('state'); + $table->integer('size_bytes')->nullable(); + }); +$schema->create('cloud_host_network_attachments', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('line_id'); + $table->string('state'); + $table->string('sync_state'); + $table->integer('observed_revision'); + $table->integer('desired_revision'); + }); +$schema->create('cloud_public_ip_pools', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('network_attachment_id'); + $table->string('state'); + $table->string('sync_state'); + $table->integer('observed_revision'); + $table->integer('desired_revision'); + }); +$schema->create('cloud_public_ips', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('public_ip_pool_id'); + $table->string('state'); + $table->integer('reservation_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->string('operation_id')->nullable(); +}); + +$assert(!$schema->hasColumn('cloud_hosts', 'default_network'), + 'Test schema must prove scheduling no longer reads default_network.'); +Capsule::table('configurations')->insert([ + 'name' => 'cloud_network_lines_enabled', 'value' => 'true', +]); +Capsule::table('cloud_hosts')->insert([ + 'id' => 1, 'name' => 'HKG-A', 'enabled' => 1, + 'created_at' => 1, 'updated_at' => 1, +]); +Capsule::table('cloud_regions')->insert([ + ['id' => 1, 'code' => 'hkg', 'name' => 'Hong Kong', + 'country_code' => 'HK', 'status' => 'active', 'sort' => 10, + 'created_at' => 1, 'updated_at' => 1], + ['id' => 2, 'code' => 'nrt', 'name' => 'Tokyo', + 'country_code' => 'JP', 'status' => 'active', 'sort' => 20, + 'created_at' => 1, 'updated_at' => 1], +]); +Capsule::table('cloud_network_lines')->insert([ + ['id' => 10, 'region_id' => 1, 'code' => 'hkg-a', 'name' => 'HKG A', + 'is_default' => 1, 'status' => 'active', 'sort' => 10, + 'created_at' => 1, 'updated_at' => 1], + ['id' => 11, 'region_id' => 1, 'code' => 'hkg-b', 'name' => 'HKG B', + 'is_default' => 0, 'status' => 'active', 'sort' => 20, + 'created_at' => 1, 'updated_at' => 1], + ['id' => 20, 'region_id' => 2, 'code' => 'nrt-a', 'name' => 'NRT A', + 'is_default' => 1, 'status' => 'active', 'sort' => 30, + 'created_at' => 1, 'updated_at' => 1], +]); +Capsule::table('cloud_resource_pools')->insert([ + ['id' => 100, 'line_id' => 10, 'code' => 'hkg-a', 'name' => 'HKG A', + 'status' => 'active', 'scheduling_policy' => 'balanced', 'sort' => 10, + 'created_at' => 1, 'updated_at' => 1], + ['id' => 101, 'line_id' => 11, 'code' => 'hkg-b', 'name' => 'HKG B', + 'status' => 'active', 'scheduling_policy' => 'balanced', 'sort' => 20, + 'created_at' => 1, 'updated_at' => 1], + ['id' => 200, 'line_id' => 20, 'code' => 'nrt-a', 'name' => 'NRT A', + 'status' => 'active', 'scheduling_policy' => 'balanced', 'sort' => 30, + 'created_at' => 1, 'updated_at' => 1], +]); +Capsule::table('cloud_host_network_attachments')->insert([ + ['id' => 1, 'host_id' => 1, 'line_id' => 10, 'state' => 'active', + 'sync_state' => 'applied', 'observed_revision' => 1, + 'desired_revision' => 1], + ['id' => 2, 'host_id' => 1, 'line_id' => 11, 'state' => 'active', + 'sync_state' => 'applied', 'observed_revision' => 1, + 'desired_revision' => 1], +]); +Capsule::table('cloud_public_ip_pools')->insert([ + ['id' => 1, 'host_id' => 1, 'network_attachment_id' => 1, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], + ['id' => 2, 'host_id' => 1, 'network_attachment_id' => 2, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], +]); +Capsule::table('cloud_public_ips')->insert([ + ['id' => 1, 'host_id' => 1, 'public_ip_pool_id' => 1, + 'state' => 'available', 'reservation_id' => null, + 'instance_id' => null, 'operation_id' => null], + ['id' => 2, 'host_id' => 1, 'public_ip_pool_id' => 2, + 'state' => 'available', 'reservation_id' => null, + 'instance_id' => null, 'operation_id' => null], + ['id' => 3, 'host_id' => 1, 'public_ip_pool_id' => 2, + 'state' => 'available', 'reservation_id' => null, + 'instance_id' => null, 'operation_id' => null], +]); + +$capacityBody = [ + 'configured_cpu_cores' => 32, + 'configured_memory_mib' => 65536, + 'configured_disk_gib' => 1000, + 'safety_cpu_cores' => 2, + 'safety_memory_mib' => 2048, + 'safety_disk_gib' => 50, + 'max_instances' => 100, +]; +$initial = CloudAdminHostSchedulingService::saveCapacity(1, $capacityBody); +$assert($initial['memberships'] === [] + && Capsule::table('cloud_host_capacity_policies')->count() === 1, + 'Capacity save must not create or replace a membership.'); + +$first = CloudAdminHostSchedulingService::saveMembership(1, 100, [ + 'scheduler_state' => 'active', 'priority' => 10, 'weight' => 100, + 'expected_revision' => 0, +]); +$second = CloudAdminHostSchedulingService::saveMembership(1, 101, [ + 'scheduler_state' => 'active', 'priority' => 20, 'weight' => 200, + 'expected_revision' => 0, +]); +$poolA = $membership($second, 100); +$poolB = $membership($second, 101); +$assert(count($second['memberships']) === 2 + && $second['host']['active_memberships'] === 2 + && $poolA['revision'] === 1 && $poolB['revision'] === 1 + && $poolA['region_id'] === 1 && $poolB['region_id'] === 1 + && $poolA['line_id'] === 10 && $poolB['line_id'] === 11 + && $poolA['ip_capacity']['available'] === 1 + && $poolB['ip_capacity']['available'] === 2 + && $second['capacity']['ip']['available'] === 3, + 'Read did not expose complete enriched same-region memberships and IP capacity.'); + +$afterCapacity = CloudAdminHostSchedulingService::saveCapacity(1, + array_replace($capacityBody, ['configured_cpu_cores' => 64])); +$assert(count($afterCapacity['memberships']) === 2 + && $afterCapacity['policy']['configured_cpu_cores'] === 64 + && $membership($afterCapacity, 100)['revision'] === 1 + && $membership($afterCapacity, 101)['revision'] === 1 + && Capsule::table('cloud_host_capacity_policies')->count() === 1, + 'Host-global capacity save changed independently revisioned memberships.'); + +$draining = CloudAdminHostSchedulingService::saveMembership(1, 100, [ + 'scheduler_state' => 'draining', 'priority' => 10, 'weight' => 100, + 'expected_revision' => 1, +]); +$assert($membership($draining, 100)['scheduler_state'] === 'draining' + && $membership($draining, 100)['revision'] === 2 + && $membership($draining, 101)['scheduler_state'] === 'active' + && $membership($draining, 101)['revision'] === 1, + 'Updating one membership changed its sibling.'); +$expectError(static function (): void { + CloudAdminHostSchedulingService::saveMembership(1, 100, [ + 'scheduler_state' => 'active', 'priority' => 10, 'weight' => 100, + 'expected_revision' => 1, + ]); +}, 409, 'Stale membership revision was accepted'); +$expectError(static function (): void { + CloudAdminHostSchedulingService::saveMembership(1, 200, [ + 'scheduler_state' => 'active', 'priority' => 30, 'weight' => 100, + 'expected_revision' => 0, + ]); +}, 409, 'Cross-region active membership was accepted'); + +Capsule::table('cloud_resource_reservations')->insert([ + 'id' => 1, 'host_id' => 1, 'resource_pool_id' => 100, + 'state' => 'committed', 'instance_id' => null, + 'cpu_cores' => 1, 'memory_mib' => 512, 'disk_gib' => 5, +]); +$expectError(static function (): void { + CloudAdminHostSchedulingService::saveMembership(1, 100, [ + 'scheduler_state' => 'disabled', 'priority' => 10, 'weight' => 100, + 'expected_revision' => 2, + ]); +}, 409, 'Exact-pool reservation did not block membership disable'); + +$disabledB = CloudAdminHostSchedulingService::saveMembership(1, 101, [ + 'scheduler_state' => 'disabled', 'priority' => 20, 'weight' => 200, + 'expected_revision' => 1, +]); +$assert($membership($disabledB, 101)['revision'] === 2 + && $membership($disabledB, 101)['scheduler_state'] === 'disabled', + 'Reservation in another pool incorrectly blocked disable.'); +$afterDelete = CloudAdminHostSchedulingService::deleteMembership(1, 101, 2); +$assert(count($afterDelete['memberships']) === 1 + && $membership($afterDelete, 100)['revision'] === 2, + 'Deleting one empty membership disturbed its sibling.'); +$expectError(static function (): void { + CloudAdminHostSchedulingService::deleteMembership(1, 100, 2); +}, 409, 'Exact-pool reservation did not block membership deletion'); +$expectError(static function (): void { + CloudAdminHostSchedulingService::deleteMembership(1, 101, 2); +}, 404, 'Deleting an absent membership did not return not found'); + +echo "Administrator host multi-membership behavior passed.\n"; diff --git a/web/tests/CloudAdminHostNetworkServiceTest.php b/web/tests/CloudAdminHostNetworkServiceTest.php index a03edb8b..1263b462 100644 --- a/web/tests/CloudAdminHostNetworkServiceTest.php +++ b/web/tests/CloudAdminHostNetworkServiceTest.php @@ -62,6 +62,7 @@ $schema->create('cloud_host_resource_pool_memberships', $table->string('scheduler_state'); $table->integer('priority')->default(0); $table->integer('weight')->default(100); + $table->integer('revision')->default(1); $table->integer('created_at'); $table->integer('updated_at'); }); diff --git a/web/tests/CloudAdminVpcControlServiceTest.php b/web/tests/CloudAdminVpcControlServiceTest.php index 41a7c125..4ee5d641 100644 --- a/web/tests/CloudAdminVpcControlServiceTest.php +++ b/web/tests/CloudAdminVpcControlServiceTest.php @@ -46,6 +46,7 @@ $schema->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); }); $schema->create('cloud_host_vpc_transports', static function (Blueprint $table): void { diff --git a/web/tests/CloudAggregateRecoveryConvergenceTest.php b/web/tests/CloudAggregateRecoveryConvergenceTest.php index 66d88037..f82b19e4 100644 --- a/web/tests/CloudAggregateRecoveryConvergenceTest.php +++ b/web/tests/CloudAggregateRecoveryConvergenceTest.php @@ -368,6 +368,7 @@ SQL); $table->integer('host_id'); $table->integer('resource_pool_id'); $table->string('scheduler_state'); + $table->integer('revision')->default(1); }); $schema->create('cloud_host_capacity_policies', static function ( Blueprint $table diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index d484b12f..1266fc27 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -243,7 +243,7 @@ namespace { $schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->string('country_code')->default(''); $t->integer('enabled'); $t->integer('resource_pool_id')->nullable(); $t->string('scheduler_state')->default('disabled'); $t->string('default_network'); $t->integer('created_at')->default(0); $t->integer('updated_at')->default(0); }); $schema->create('cloud_host_agents', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->text('sealed_api_secret'); $t->integer('enabled')->default(0); $t->integer('revision')->default(1); $t->integer('tested_revision')->default(0); $t->string('last_test_status')->default('never'); $t->string('last_error_code')->default(''); $t->string('last_agent_version')->default(''); $t->integer('last_tested_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_host_storage_configurations', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->integer('revision')->default(0); $t->string('state')->default('applying'); }); - $schema->create('cloud_host_resource_pool_memberships', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('resource_pool_id'); $t->string('scheduler_state')->default('disabled'); $t->integer('priority')->default(0); $t->integer('weight')->default(100); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['host_id', 'resource_pool_id']); }); + $schema->create('cloud_host_resource_pool_memberships', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('resource_pool_id'); $t->string('scheduler_state')->default('disabled'); $t->integer('priority')->default(0); $t->integer('weight')->default(100); $t->integer('revision')->default(1); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['host_id', 'resource_pool_id']); }); $schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('selector'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->string('cidr'); $t->string('gateway'); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } }); diff --git a/web/tests/CloudFreshSchemaContractTest.php b/web/tests/CloudFreshSchemaContractTest.php index b57fb895..742471ef 100644 --- a/web/tests/CloudFreshSchemaContractTest.php +++ b/web/tests/CloudFreshSchemaContractTest.php @@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false $assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema), 'cloud.sql retained an engine-prefixed identifier.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v25-network-attachments'") + "SCHEMA_VERSION = 'go-agent-wss-v26-multi-pool-memberships'") && !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"), 'Outbound Agent schema must reject the incompatible earlier Go database.'); $assert(str_contains($schema, diff --git a/web/tests/CloudHostNetworkAttachmentServiceTest.php b/web/tests/CloudHostNetworkAttachmentServiceTest.php index f2f2e178..8789e556 100644 --- a/web/tests/CloudHostNetworkAttachmentServiceTest.php +++ b/web/tests/CloudHostNetworkAttachmentServiceTest.php @@ -72,6 +72,7 @@ $schema->create('cloud_host_resource_pool_memberships', $table->string('scheduler_state'); $table->integer('priority'); $table->integer('weight'); + $table->integer('revision')->default(1); $table->integer('created_at'); $table->integer('updated_at'); }); diff --git a/web/tests/CloudMultiHostSchemaDefinitionTest.php b/web/tests/CloudMultiHostSchemaDefinitionTest.php index cc9bfad7..293c7732 100644 --- a/web/tests/CloudMultiHostSchemaDefinitionTest.php +++ b/web/tests/CloudMultiHostSchemaDefinitionTest.php @@ -43,11 +43,13 @@ $assert(str_contains($schema, 'UNIQUE KEY cloud_region_code (code)') $assert(str_contains($schema, "scheduler_state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'disabled'") + && str_contains($schema, + 'revision BIGINT UNSIGNED NOT NULL DEFAULT 1') && str_contains($schema, 'cloud_pool_membership_scheduler (resource_pool_id, scheduler_state, priority, host_id)') && str_contains($schema, 'cloud_host_membership_scheduler (host_id, scheduler_state, id)'), - 'Host scheduling intent is not indexed as the panel authority.'); + 'Host scheduling intent is not revisioned and indexed as panel authority.'); $assert(!str_contains($schema, 'CREATE TABLE cloud_host_capacity_snapshots') && !str_contains($schema, diff --git a/web/tests/CloudMultiPublicPoolSchemaDefinitionTest.php b/web/tests/CloudMultiPublicPoolSchemaDefinitionTest.php index 56129714..78bba1f0 100644 --- a/web/tests/CloudMultiPublicPoolSchemaDefinitionTest.php +++ b/web/tests/CloudMultiPublicPoolSchemaDefinitionTest.php @@ -2,6 +2,7 @@ $root = dirname(__DIR__); $schema = file_get_contents($root . '/sql/cloud.sql'); +$setup = file_get_contents($root . '/app/Command/CloudSetup.php'); $failures = []; $assert = static function (bool $condition, string $message) use (&$failures): void { if (!$condition) { @@ -21,6 +22,11 @@ foreach ([ $assert(str_contains($schema, 'UNIQUE KEY cloud_host_pool_membership (host_id, resource_pool_id)'), 'A physical host must not have duplicate memberships in one resource pool.'); +$assert(str_contains($schema, + 'revision BIGINT UNSIGNED NOT NULL DEFAULT 1') + && str_contains($setup, + "'priority', 'weight', 'revision', 'created_at', 'updated_at'"), + 'Resource-pool memberships must expose a required optimistic revision.'); $assert(str_contains($schema, 'UNIQUE KEY cloud_host_network_attachment_key (host_id, attachment_key)'), 'Network attachment keys must be stable and host-scoped.'); diff --git a/web/tests/CloudPlanUpgradeServiceTest.php b/web/tests/CloudPlanUpgradeServiceTest.php index 19655e73..9a49e42c 100644 --- a/web/tests/CloudPlanUpgradeServiceTest.php +++ b/web/tests/CloudPlanUpgradeServiceTest.php @@ -165,6 +165,7 @@ namespace { $table->string('scheduler_state'); $table->integer('priority')->default(0); $table->integer('weight')->default(100); + $table->integer('revision')->default(1); $table->integer('created_at'); $table->integer('updated_at'); }); diff --git a/web/tests/CloudPortableBackupSameHostRestoreTest.php b/web/tests/CloudPortableBackupSameHostRestoreTest.php index 497e0eae..fb0efe9a 100644 --- a/web/tests/CloudPortableBackupSameHostRestoreTest.php +++ b/web/tests/CloudPortableBackupSameHostRestoreTest.php @@ -51,6 +51,7 @@ $schema->create('cloud_host_resource_pool_memberships', $table->integer('host_id'); $table->integer('resource_pool_id'); $table->string('scheduler_state'); + $table->integer('revision')->default(1); }); $schema->create('cloud_host_capacity_policies', static function (Blueprint $table): void { diff --git a/web/tests/CloudRescueCatalogSchemaContractTest.php b/web/tests/CloudRescueCatalogSchemaContractTest.php index cb843d9a..01b89380 100644 --- a/web/tests/CloudRescueCatalogSchemaContractTest.php +++ b/web/tests/CloudRescueCatalogSchemaContractTest.php @@ -56,7 +56,7 @@ $assert($replica !== '' && str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'), 'Rescue replica cannot prove exact identity or retain cleanup debt.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v25-network-attachments'") + "SCHEMA_VERSION = 'go-agent-wss-v26-multi-pool-memberships'") && str_contains($setup, "'cloud_rescue_artifact_delete_due'") && str_contains($setup, "'cloud_rescue_replica_cleanup'"), 'CloudSetup version or rescue catalog indexes are incomplete.'); diff --git a/web/tests/CloudTemplateCatalogTest.php b/web/tests/CloudTemplateCatalogTest.php index 20290b37..920b42dc 100644 --- a/web/tests/CloudTemplateCatalogTest.php +++ b/web/tests/CloudTemplateCatalogTest.php @@ -127,6 +127,7 @@ $capsule->schema('default')->create( $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', diff --git a/web/tests/CloudTemplateImportIntentContractTest.php b/web/tests/CloudTemplateImportIntentContractTest.php index 7a3ec026..4b8595d0 100644 --- a/web/tests/CloudTemplateImportIntentContractTest.php +++ b/web/tests/CloudTemplateImportIntentContractTest.php @@ -63,7 +63,7 @@ $assert(str_contains($schema, && str_contains($schema, 'CONSTRAINT chk_cloud_template_import_completion CHECK (') && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v25-network-attachments'"), + "SCHEMA_VERSION = 'go-agent-wss-v26-multi-pool-memberships'"), 'Template imports are missing durable identity or terminal-state constraints.'); $assert(str_contains($routes, "'/admin/cloud-template-imports'") && str_contains($routes, "'/admin/cloud-template-imports/{id}'") diff --git a/web/tests/CloudTemplateRegionalAvailabilityTest.php b/web/tests/CloudTemplateRegionalAvailabilityTest.php index e5cb54d4..0d266ac9 100644 --- a/web/tests/CloudTemplateRegionalAvailabilityTest.php +++ b/web/tests/CloudTemplateRegionalAvailabilityTest.php @@ -82,6 +82,7 @@ $schema->create('cloud_host_resource_pool_memberships', static function ( $table->integer('host_id'); $table->integer('resource_pool_id'); $table->string('scheduler_state'); + $table->integer('revision')->default(1); }); $schema->create('cloud_host_capacity_policies', static function ( Blueprint $table diff --git a/web/tests/CloudTrafficPoolSchemaContractTest.php b/web/tests/CloudTrafficPoolSchemaContractTest.php index 58d258d4..a506a3cf 100644 --- a/web/tests/CloudTrafficPoolSchemaContractTest.php +++ b/web/tests/CloudTrafficPoolSchemaContractTest.php @@ -71,7 +71,7 @@ $assert(str_contains($schema, 'Service-period traffic-pool identity is not frozen or indexed.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v25-network-attachments'") + "SCHEMA_VERSION = 'go-agent-wss-v26-multi-pool-memberships'") && str_contains($setup, "'chk_cloud_traffic_entitlement_balance'") && str_contains($setup, "'cloud_traffic_ledger_sequence'"), 'CloudSetup schema version or named-object validation is incomplete.'); diff --git a/web/tests/CloudVpcHostRetirementServiceTest.php b/web/tests/CloudVpcHostRetirementServiceTest.php index 70e08012..4f8866b6 100644 --- a/web/tests/CloudVpcHostRetirementServiceTest.php +++ b/web/tests/CloudVpcHostRetirementServiceTest.php @@ -70,6 +70,7 @@ $schema->create('cloud_host_resource_pool_memberships', static function ( $table->string('scheduler_state'); $table->integer('priority')->default(0); $table->integer('weight')->default(100); + $table->integer('revision')->default(1); $table->integer('created_at'); $table->integer('updated_at'); }); diff --git a/web/tests/CloudVpcSchemaContractTest.php b/web/tests/CloudVpcSchemaContractTest.php index 8ce623cd..8e281b1d 100644 --- a/web/tests/CloudVpcSchemaContractTest.php +++ b/web/tests/CloudVpcSchemaContractTest.php @@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL') 'Cloud jobs cannot be correlated to VPC or VPC-port work.'); $assert(str_contains($setup, - "private const SCHEMA_VERSION = 'go-agent-wss-v25-network-attachments'") + "private const SCHEMA_VERSION = 'go-agent-wss-v26-multi-pool-memberships'") && str_contains($setup, "'name' => 'cloud_vpc_enabled'") && str_contains($setup, "'value' => 'false'") && str_contains($setup, diff --git a/web/tests/CloudVpcServiceTest.php b/web/tests/CloudVpcServiceTest.php index 0b688180..69b8a5f5 100644 --- a/web/tests/CloudVpcServiceTest.php +++ b/web/tests/CloudVpcServiceTest.php @@ -43,6 +43,7 @@ $schema->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); }); $schema->create('cloud_host_vpc_transports', static function (Blueprint $table): void {