|
|
<?php
|
|
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
|
|
use App\Models\CloudHost;
|
|
|
use App\Models\CloudHostResourcePoolMembership;
|
|
|
use App\Models\CloudInstance;
|
|
|
use App\Models\CloudNetworkLine;
|
|
|
use App\Models\CloudPrivateCidrAllocatorConfig;
|
|
|
use App\Models\CloudRegion;
|
|
|
use App\Models\CloudRegionFabric;
|
|
|
use App\Models\CloudResourcePool;
|
|
|
use App\Models\CloudVpc;
|
|
|
use App\Models\CloudVpcHostDeployment;
|
|
|
|
|
|
/**
|
|
|
* Administrator projection and mutation boundary for the host WireGuard
|
|
|
* Fabric. Engine responses are treated as untrusted DTOs at this boundary:
|
|
|
* only the bounded status fields needed by the admin page are returned.
|
|
|
*/
|
|
|
final class CloudAdminFabricService
|
|
|
{
|
|
|
private const FABRIC_ID = '/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D';
|
|
|
private const HOST_ID = '/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/D';
|
|
|
private const KEY = '/^[A-Za-z0-9+\/]{42}==\z|^[A-Za-z0-9+\/]{43}=\z/D';
|
|
|
private const STATES = ['applying', 'active', 'degraded', 'uncertain'];
|
|
|
// One probe can consume the engine's 22-second SSH budget. The engine
|
|
|
// probes 16 hosts at a time, so even a full 64-host failed batch remains
|
|
|
// below this transport deadline with room for scheduling and readback.
|
|
|
private const FABRIC_WRITE_TIMEOUT_SECONDS = 180.0;
|
|
|
private const FABRIC_LISTEN_PORT = 51820;
|
|
|
private const MAX_FABRIC_NODES = 64;
|
|
|
// Detection may include one full desired set plus orphan/conflicting
|
|
|
// engine nodes. Two bounded engine batches still fit the browser budget.
|
|
|
private const MAX_READINESS_HOSTS = 128;
|
|
|
private const HOST_STATES = ['active', 'draining', 'disabled'];
|
|
|
private const ENDPOINT_SOURCES = ['configured', 'ssh_host_ipv4'];
|
|
|
private const ERROR_PHASES = ['identity', 'observe', 'apply'];
|
|
|
private const OPERATION_KINDS = ['apply', 'reconcile'];
|
|
|
private const OPERATION_STATES = [
|
|
|
'queued', 'running', 'succeeded', 'failed', 'uncertain', 'interrupted',
|
|
|
];
|
|
|
private const NODE_OPERATION_STATES = [
|
|
|
'pending', 'running', 'succeeded', 'failed', 'uncertain', 'skipped',
|
|
|
];
|
|
|
private const OPERATION_CHECKPOINTS = [
|
|
|
'dispatch', 'host_lock', 'identity', 'journal_recovery', 'journal_dispatch',
|
|
|
'journal_artifact_restore', 'journal_nft_restore',
|
|
|
'journal_runtime_restore', 'journal_finalize', 'preflight',
|
|
|
'preflight_sysctl', 'preflight_tools', 'preflight_artifacts',
|
|
|
'preflight_firewall', 'preflight_vpc', 'preflight_underlay',
|
|
|
'preflight_routes', 'preflight_persistence',
|
|
|
'transaction', 'nft_install', 'network_activate', 'persistence',
|
|
|
'final_readback', 'complete',
|
|
|
];
|
|
|
private const OPERATION_REASONS = [
|
|
|
'none', 'tool_missing', 'ownership_conflict', 'journal_conflict',
|
|
|
'sysctl_conflict', 'persistence_conflict',
|
|
|
'firewall_conflict', 'underlay_conflict', 'network_manager_failed',
|
|
|
'nft_failed', 'systemd_failed', 'readback_failed', 'command_failed',
|
|
|
'transport_failed', 'status_invalid',
|
|
|
];
|
|
|
private const ERROR_CODES = [
|
|
|
'fabric_apply_unconfirmed', 'fabric_host_capability_missing',
|
|
|
'fabric_host_capability_probe_failed', 'fabric_host_capability_probe_invalid',
|
|
|
'fabric_host_capability_probe_unsupported', 'fabric_host_connection_failed',
|
|
|
'fabric_endpoint_invalid', 'fabric_endpoint_missing',
|
|
|
'fabric_endpoint_mismatch', 'fabric_endpoint_not_local',
|
|
|
'fabric_endpoint_vpc_conflict', 'fabric_vpc_record_corrupt',
|
|
|
'firewalld_unsupported_requires_maintenance',
|
|
|
'legacy_firewalld_state_requires_cleanup',
|
|
|
'firewall_transaction_requires_recovery_or_cleanup',
|
|
|
'legacy_firewall_evidence_invalid',
|
|
|
'fabric_host_identity_mismatch', 'fabric_host_interface_conflict',
|
|
|
'fabric_host_firewall_mode_conflict', 'fabric_host_key_locked',
|
|
|
'fabric_host_network_manager_conflict',
|
|
|
'fabric_host_not_configured', 'fabric_host_unavailable',
|
|
|
'fabric_identity_conflict', 'fabric_identity_invalid', 'fabric_invalid',
|
|
|
'fabric_membership_conflict', 'fabric_not_found', 'fabric_overlay_conflict',
|
|
|
'fabric_readback_mismatch',
|
|
|
'fabric_region_conflict',
|
|
|
'fabric_plan_corrupt', 'fabric_readback_invalid', 'fabric_record_corrupt',
|
|
|
'fabric_operation_busy', 'fabric_operation_invalid',
|
|
|
'fabric_operation_limit', 'fabric_operation_not_found',
|
|
|
'fabric_operation_reconcile_required', 'fabric_operation_status_invalid',
|
|
|
'fabric_operation_status_timeout', 'fabric_operation_interrupted',
|
|
|
'fabric_remote_command_failed',
|
|
|
'fabric_revision_conflict', 'fabric_runner_unsupported',
|
|
|
];
|
|
|
|
|
|
public static function listing(array $actor, ?CloudEngineClient $engine = null): array
|
|
|
{
|
|
|
self::assertReadActor($actor);
|
|
|
$engine ??= new CloudEngineClient();
|
|
|
try {
|
|
|
$raw = $engine->fabricStatuses($actor);
|
|
|
} catch (CloudError $exception) {
|
|
|
// Keep the platform-owned region mapping visible when a host or
|
|
|
// engine is unavailable. This is a diagnostic snapshot, never a
|
|
|
// claim that the Fabric is active.
|
|
|
$mappings = self::mappings([]);
|
|
|
return [
|
|
|
'mappings' => $mappings,
|
|
|
'regions' => self::readinessRegions([], $mappings, [], false),
|
|
|
'generated_at' => time(),
|
|
|
'engine_available' => false,
|
|
|
'engine_error' => 'Fabric 引擎状态暂时无法读取,请稍后重试。',
|
|
|
];
|
|
|
}
|
|
|
if (!is_array($raw)) {
|
|
|
throw new CloudError('Fabric 状态响应无效,请稍后重试', 502);
|
|
|
}
|
|
|
$hostNames = self::hostNames($raw);
|
|
|
$fabrics = [];
|
|
|
foreach ($raw as $item) {
|
|
|
if (!is_array($item)) {
|
|
|
continue;
|
|
|
}
|
|
|
$fabrics[] = self::project($item, $hostNames);
|
|
|
}
|
|
|
usort($fabrics, static fn (array $a, array $b): int =>
|
|
|
strcmp((string) $a['fabric_id'], (string) $b['fabric_id']));
|
|
|
$mappings = self::mappings($fabrics);
|
|
|
return [
|
|
|
'mappings' => $mappings,
|
|
|
'regions' => self::readinessRegions($fabrics, $mappings),
|
|
|
'generated_at' => time(),
|
|
|
'engine_available' => true,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
public static function detail(string $fabricId, array $actor,
|
|
|
?CloudEngineClient $engine = null): array
|
|
|
{
|
|
|
self::assertReadActor($actor);
|
|
|
$fabricId = self::fabricId($fabricId);
|
|
|
$engine ??= new CloudEngineClient();
|
|
|
$raw = $engine->fabricStatus($fabricId, $actor);
|
|
|
if (!is_array($raw)) {
|
|
|
throw new CloudError('Fabric 状态响应无效,请稍后重试', 502);
|
|
|
}
|
|
|
$hostNames = self::hostNames([$raw]);
|
|
|
$fabric = self::project($raw, $hostNames);
|
|
|
return [
|
|
|
'fabric' => $fabric,
|
|
|
'mapping' => self::mappingForFabric($fabricId),
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/** Fresh, read-only host capability probe for one platform region. */
|
|
|
public static function probeRegion(string $regionId, array $actor,
|
|
|
?CloudEngineClient $engine = null): array
|
|
|
{
|
|
|
self::assertWriteActor($actor);
|
|
|
$region = self::regionById($regionId);
|
|
|
$engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS);
|
|
|
$fabrics = self::projectFabrics($engine->fabricStatuses($actor));
|
|
|
$mappings = self::mappings($fabrics);
|
|
|
// Start from the same inventory projection shown to the operator. It
|
|
|
// deliberately includes both canonical platform members and orphaned
|
|
|
// nodes that still exist in an engine Fabric, so drift cannot escape
|
|
|
// a fresh detection just because the scheduler relation changed.
|
|
|
$initial = self::findReadinessRegion(
|
|
|
self::readinessRegions($fabrics, $mappings), (int) $region->id
|
|
|
);
|
|
|
$hostIds = array_map(static fn (array $host): string =>
|
|
|
(string) $host['host_id'], $initial['hosts']);
|
|
|
if ($hostIds === []) {
|
|
|
throw new CloudError('该地区尚未分配宿主机', 409);
|
|
|
}
|
|
|
if (count($hostIds) > self::MAX_READINESS_HOSTS) {
|
|
|
throw new CloudError(
|
|
|
'该地区 readiness 清单超过 128 台,请先清理调度或未映射 Fabric 冲突', 409
|
|
|
);
|
|
|
}
|
|
|
$probes = [];
|
|
|
foreach (array_chunk($hostIds, self::MAX_FABRIC_NODES) as $batch) {
|
|
|
$probes = array_replace($probes,
|
|
|
self::probeRows($engine->fabricProbe($batch, $actor), $batch));
|
|
|
}
|
|
|
$rows = self::readinessRegions($fabrics, $mappings, $probes);
|
|
|
return [
|
|
|
'region' => self::findReadinessRegion($rows, (int) $region->id),
|
|
|
'generated_at' => time(),
|
|
|
'engine_available' => true,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/** Generate and apply a region Fabric without accepting a browser plan. */
|
|
|
public static function applyRegion(string $regionId, array $actor,
|
|
|
?CloudEngineClient $engine = null): array
|
|
|
{
|
|
|
self::assertWriteActor($actor);
|
|
|
$region = self::regionById($regionId);
|
|
|
if ((string) $region->status !== 'active') {
|
|
|
throw new CloudError('地区未启用,不能配置私网', 409);
|
|
|
}
|
|
|
$contexts = self::platformRegions();
|
|
|
$context = $contexts[(int) $region->id] ?? self::emptyRegionContext($region);
|
|
|
$candidates = array_values(array_filter(
|
|
|
$context['hosts'],
|
|
|
static fn (array $host): bool => ($host['required'] ?? false) === true
|
|
|
));
|
|
|
if (count($candidates) < 2 || count($candidates) > self::MAX_FABRIC_NODES) {
|
|
|
throw new CloudError('地区私网需要 2 至 64 台已启用且处于 active/draining 的宿主机', 409);
|
|
|
}
|
|
|
foreach ($context['hosts'] as $host) {
|
|
|
if (in_array('membership_conflict', $host['reasons'] ?? [], true)) {
|
|
|
throw new CloudError('地区存在冲突的宿主机资源池成员关系,请先修复调度配置', 409);
|
|
|
}
|
|
|
}
|
|
|
foreach ($candidates as $host) {
|
|
|
if (($host['platform_ready'] ?? false) !== true) {
|
|
|
throw new CloudError('地区仍有必须保留但未通过面板配置核验的宿主机', 409);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
$mapping = self::mappingModel((int) $region->id);
|
|
|
if ($mapping !== null) {
|
|
|
throw new CloudError(
|
|
|
'地区 Fabric 已固定,请使用重新核对恢复或激活', 409
|
|
|
);
|
|
|
}
|
|
|
$engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS);
|
|
|
$expectedFabricRegion = (string) $region->code;
|
|
|
$fabricId = self::automaticFabricId((string) $region->code);
|
|
|
self::assertFabricIdentityOwnedByRegion($fabricId, (int) $region->id);
|
|
|
self::assertLiveVpcFabricPinsCompatible(
|
|
|
(int) $region->id, false, $fabricId,
|
|
|
$expectedFabricRegion, 1
|
|
|
);
|
|
|
$candidateIds = array_map(static fn (array $host): string =>
|
|
|
(string) $host['host_id'], $candidates);
|
|
|
// Never trust a previous browser detection: configuration always
|
|
|
// repeats the fresh, generation-pinned, read-only probe first.
|
|
|
$probes = self::probeRows(
|
|
|
$engine->fabricProbe($candidateIds, $actor), $candidateIds
|
|
|
);
|
|
|
[$fabricRegion, $probeByHost] = self::assertConfigurableProbes(
|
|
|
$candidates, $probes, (string) $expectedFabricRegion
|
|
|
);
|
|
|
|
|
|
$rawStatuses = $engine->fabricStatuses($actor);
|
|
|
$fabrics = self::projectFabrics($rawStatuses);
|
|
|
self::assertNoRegionFabricConflicts(
|
|
|
$fabrics, $fabricRegion, $fabricId, $candidateIds
|
|
|
);
|
|
|
$current = self::fabricById($fabrics, $fabricId);
|
|
|
$expectedRevision = 1;
|
|
|
if ($current !== null) {
|
|
|
self::assertExistingFabricMatches(
|
|
|
$current, $fabricRegion, $candidateIds,
|
|
|
$expectedRevision
|
|
|
);
|
|
|
self::assertAutomaticFabricPlanMatches(
|
|
|
$current, (string) $region->code, $candidates,
|
|
|
$probeByHost, $fabrics
|
|
|
);
|
|
|
if (is_array($current['operation'] ?? null)
|
|
|
&& in_array($current['operation']['status'] ?? null,
|
|
|
['queued', 'running'], true)) {
|
|
|
return self::operationReceipt($current['operation']);
|
|
|
}
|
|
|
throw new CloudError(
|
|
|
'检测到未映射的部分成功 Fabric,请使用重新核对恢复',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
$revision = 1;
|
|
|
$overlay = self::automaticOverlay(
|
|
|
(string) $region->code, $fabrics, $fabricId,
|
|
|
array_column($probeByHost, 'endpoint_ip')
|
|
|
);
|
|
|
$nodes = self::automaticNodes($candidates, $probeByHost, $overlay);
|
|
|
$plan = [
|
|
|
'schema_version' => 1,
|
|
|
'fabric_id' => $fabricId,
|
|
|
'region' => $fabricRegion,
|
|
|
'overlay_cidr' => $overlay,
|
|
|
'revision' => $revision,
|
|
|
'listen_port' => self::FABRIC_LISTEN_PORT,
|
|
|
'nodes' => $nodes,
|
|
|
];
|
|
|
// Reuse the canonical engine-plan validator. A generated plan must
|
|
|
// not receive a looser contract than stored desired state.
|
|
|
self::assertFabricIdentityOwnedByRegion(
|
|
|
$fabricId, (int) $region->id
|
|
|
);
|
|
|
$raw = $engine->fabricApply(self::plan($plan), $actor);
|
|
|
if (!is_array($raw)) {
|
|
|
throw new CloudError('Fabric 应用响应无效,请使用重新核对', 502);
|
|
|
}
|
|
|
$fabric = self::project($raw, self::hostNames([$raw]));
|
|
|
self::assertExistingFabricMatches(
|
|
|
$fabric, $fabricRegion, $candidateIds,
|
|
|
$expectedRevision
|
|
|
);
|
|
|
self::assertAutomaticFabricPlanMatches(
|
|
|
$fabric, (string) $region->code, $candidates,
|
|
|
$probeByHost, $fabrics
|
|
|
);
|
|
|
$operation = self::mutationOperation(
|
|
|
$fabric['operation'] ?? null, ['apply']
|
|
|
);
|
|
|
// Apply only admits the host-owned asynchronous operation. Even if a
|
|
|
// very fast engine reports it terminal in this response, the region
|
|
|
// mapping is committed only by the later explicit reconcile path,
|
|
|
// after a fresh platform/host readback under the same operation ID.
|
|
|
return self::operationReceipt($operation);
|
|
|
}
|
|
|
|
|
|
/** Reconcile only the fixed desired Fabric; never generate a new plan. */
|
|
|
public static function reconcileRegion(string $regionId, array $actor,
|
|
|
?CloudEngineClient $engine = null): array
|
|
|
{
|
|
|
self::assertWriteActor($actor);
|
|
|
$region = self::regionById($regionId);
|
|
|
$mapping = self::mappingModel((int) $region->id);
|
|
|
$mappingExpectation = self::mappingExpectation($mapping);
|
|
|
$contexts = self::platformRegions();
|
|
|
$context = $contexts[(int) $region->id] ?? self::emptyRegionContext($region);
|
|
|
$candidates = array_values(array_filter(
|
|
|
$context['hosts'],
|
|
|
static fn (array $host): bool => ($host['required'] ?? false) === true
|
|
|
));
|
|
|
$requiredIds = array_map(static fn (array $host): string =>
|
|
|
(string) $host['host_id'], $candidates);
|
|
|
$fabricId = $mapping === null
|
|
|
? self::automaticFabricId((string) $region->code)
|
|
|
: (string) $mapping->fabric_id;
|
|
|
self::assertFabricIdentityOwnedByRegion($fabricId, (int) $region->id);
|
|
|
$engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS);
|
|
|
$expectedRegion = $mapping === null
|
|
|
? (string) $region->code : (string) $mapping->fabric_region;
|
|
|
$expectedRevision = $mapping === null
|
|
|
? 1 : (int) $mapping->fabric_revision;
|
|
|
if (count($candidates) < 2
|
|
|
|| count($candidates) > self::MAX_FABRIC_NODES) {
|
|
|
throw new CloudError(
|
|
|
'Fabric 重新核对要求 2 至 64 台规范宿主机', 409
|
|
|
);
|
|
|
}
|
|
|
// Reconcile writes every member host. Browser workflow flags are only
|
|
|
// presentation; enforce the platform gates again at the service
|
|
|
// boundary before any host-writing engine request can be issued.
|
|
|
self::assertPlatformContextUnchanged(
|
|
|
$region, $requiredIds
|
|
|
);
|
|
|
// Reconcile can execute host writes. Prove the stored engine desired
|
|
|
// identity before invoking it; a deterministic name alone is not
|
|
|
// enough to establish ownership after a partial or foreign restore.
|
|
|
$beforeRaw = $engine->fabricStatus($fabricId, $actor);
|
|
|
if (!is_array($beforeRaw)) {
|
|
|
throw new CloudError('Fabric 状态响应无效,已阻止重新核对', 502);
|
|
|
}
|
|
|
$before = self::project($beforeRaw, self::hostNames([$beforeRaw]));
|
|
|
self::assertExistingFabricMatches(
|
|
|
$before, $expectedRegion, $requiredIds,
|
|
|
$expectedRevision
|
|
|
);
|
|
|
$beforeOperation = is_array($before['operation'] ?? null)
|
|
|
? $before['operation'] : null;
|
|
|
if ($beforeOperation !== null) {
|
|
|
$beforeOperation = self::mutationOperation(
|
|
|
$beforeOperation, self::OPERATION_KINDS
|
|
|
);
|
|
|
}
|
|
|
$statusFabrics = self::projectFabrics(
|
|
|
$engine->fabricStatuses($actor)
|
|
|
);
|
|
|
self::assertNoRegionFabricConflicts(
|
|
|
$statusFabrics, $expectedRegion, $fabricId, $requiredIds
|
|
|
);
|
|
|
$probeRows = self::probeRows(
|
|
|
$engine->fabricProbe($requiredIds, $actor), $requiredIds
|
|
|
);
|
|
|
[, $verifiedProbes] = self::assertConfigurableProbes(
|
|
|
$candidates, $probeRows, $expectedRegion
|
|
|
);
|
|
|
$recoveryFabrics = [];
|
|
|
$recoveryProbes = $verifiedProbes;
|
|
|
if ($mapping === null) {
|
|
|
$recoveryFabrics = $statusFabrics;
|
|
|
$listed = self::fabricById($recoveryFabrics, $fabricId);
|
|
|
if ($listed === null) {
|
|
|
throw new CloudError(
|
|
|
'Fabric 状态列表与详情不一致,已阻止接管', 502
|
|
|
);
|
|
|
}
|
|
|
self::assertAutomaticFabricPlanMatches(
|
|
|
$listed, (string) $region->code, $candidates,
|
|
|
$recoveryProbes, $recoveryFabrics
|
|
|
);
|
|
|
self::assertAutomaticFabricPlanMatches(
|
|
|
$before, (string) $region->code, $candidates,
|
|
|
$recoveryProbes, $recoveryFabrics
|
|
|
);
|
|
|
}
|
|
|
// An existing tenant must never be reconciled against an absent or
|
|
|
// different region mapping. Enforce this for active and disabled
|
|
|
// mappings before the host-writing engine request.
|
|
|
self::assertLiveVpcFabricPinsCompatible(
|
|
|
(int) $region->id, $mapping !== null, $fabricId,
|
|
|
$expectedRegion, $expectedRevision
|
|
|
);
|
|
|
if (($mapping === null || (string) $mapping->state === 'disabled')
|
|
|
&& is_array($beforeOperation)
|
|
|
&& ($beforeOperation['status'] ?? null) === 'succeeded'
|
|
|
&& ($before['state'] ?? null) === 'active'
|
|
|
&& ($before['next_stage_allowed'] ?? false) === true) {
|
|
|
// Initial asynchronous apply has completed. This POST is the
|
|
|
// explicit control-plane confirmation: it commits the fixed
|
|
|
// mapping without replaying the already successful host write.
|
|
|
self::assertPlatformContextUnchanged($region, $requiredIds);
|
|
|
CloudAdminResourceService::saveRegionFabric((string) $region->id, [
|
|
|
'fabric_id' => $fabricId,
|
|
|
'fabric_region' => $expectedRegion,
|
|
|
'fabric_revision' => (int) $before['revision'],
|
|
|
'state' => 'active',
|
|
|
], $actor, false, $engine, $mappingExpectation,
|
|
|
static function () use ($region, $requiredIds): void {
|
|
|
self::assertPlatformContextUnchanged($region, $requiredIds);
|
|
|
}
|
|
|
);
|
|
|
return self::operationReceipt($beforeOperation);
|
|
|
}
|
|
|
// Close the inventory race opened by detail/list/probe network round
|
|
|
// trips. A host or region changed meanwhile must not be reconciled.
|
|
|
self::assertPlatformContextUnchanged(
|
|
|
$region, $requiredIds
|
|
|
);
|
|
|
self::assertFabricIdentityOwnedByRegion(
|
|
|
$fabricId, (int) $region->id
|
|
|
);
|
|
|
$raw = $engine->fabricReconcile($fabricId, $actor);
|
|
|
if (!is_array($raw)) {
|
|
|
throw new CloudError('Fabric 核对响应无效,请稍后刷新', 502);
|
|
|
}
|
|
|
$fabric = self::project($raw, self::hostNames([$raw]));
|
|
|
self::assertExistingFabricMatches(
|
|
|
$fabric, $expectedRegion, $requiredIds,
|
|
|
$expectedRevision
|
|
|
);
|
|
|
// A reconcile can either create a reconcile operation or resume the
|
|
|
// exact interrupted apply operation. Both are reviewed root kinds,
|
|
|
// but a missing/malformed receipt must never fall through to mapping.
|
|
|
$operation = self::mutationOperation(
|
|
|
$fabric['operation'] ?? null, self::OPERATION_KINDS
|
|
|
);
|
|
|
if (($operation['status'] ?? null) !== 'succeeded') {
|
|
|
return self::operationReceipt($operation);
|
|
|
}
|
|
|
if ($mapping === null) {
|
|
|
// Recover only the deterministic identity left by an earlier
|
|
|
// partial success. No plan, revision or membership is invented.
|
|
|
self::assertAutomaticFabricPlanMatches(
|
|
|
$fabric, (string) $region->code, $candidates,
|
|
|
$recoveryProbes, $recoveryFabrics
|
|
|
);
|
|
|
}
|
|
|
if ($mapping === null || (string) $mapping->state === 'disabled') {
|
|
|
// Reconcile may take minutes. Recheck generation after the host
|
|
|
// write and exact response before publishing a new/active pin.
|
|
|
self::assertPlatformContextUnchanged(
|
|
|
$region, $requiredIds
|
|
|
);
|
|
|
CloudAdminResourceService::saveRegionFabric((string) $region->id, [
|
|
|
'fabric_id' => $fabricId,
|
|
|
'fabric_region' => $expectedRegion,
|
|
|
'fabric_revision' => (int) $fabric['revision'],
|
|
|
'state' => 'active',
|
|
|
], $actor, false, $engine, $mappingExpectation,
|
|
|
static function () use (
|
|
|
$region, $requiredIds
|
|
|
): void {
|
|
|
self::assertPlatformContextUnchanged(
|
|
|
$region, $requiredIds
|
|
|
);
|
|
|
}
|
|
|
);
|
|
|
}
|
|
|
return self::listing($actor, $engine);
|
|
|
}
|
|
|
|
|
|
/** Return immediately without a second Engine round trip after accept. */
|
|
|
private static function operationReceipt(array $operation): array
|
|
|
{
|
|
|
return [
|
|
|
'operation' => self::mutationOperation(
|
|
|
$operation, self::OPERATION_KINDS
|
|
|
),
|
|
|
'engine_available' => true,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/** Require an auditable root receipt on every Fabric mutation path. */
|
|
|
private static function mutationOperation($value, array $expectedKinds): array
|
|
|
{
|
|
|
if (!is_array($value)
|
|
|
|| !is_string($value['id'] ?? null)
|
|
|
|| preg_match('/^[0-9a-f]{32}$/D', $value['id']) !== 1
|
|
|
|| !is_string($value['kind'] ?? null)
|
|
|
|| !in_array($value['kind'], $expectedKinds, true)
|
|
|
|| !is_string($value['status'] ?? null)
|
|
|
|| !in_array($value['status'], self::OPERATION_STATES, true)) {
|
|
|
throw new CloudError(
|
|
|
'Fabric operation 回执无效,已阻止发布地区映射', 502
|
|
|
);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function regionById(string $value): CloudRegion
|
|
|
{
|
|
|
if (preg_match('/^[1-9][0-9]*$/D', $value) !== 1) {
|
|
|
throw new CloudError('地区 ID 无效', 422);
|
|
|
}
|
|
|
$region = CloudRegion::find((int) $value);
|
|
|
if ($region === null) {
|
|
|
throw new CloudError('地区不存在', 404);
|
|
|
}
|
|
|
return $region;
|
|
|
}
|
|
|
|
|
|
private static function mappingModel(int $regionId): ?CloudRegionFabric
|
|
|
{
|
|
|
$connection = (new CloudRegionFabric())->getConnection();
|
|
|
if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
|
|
|
throw new CloudError('VPC Fabric 映射表尚未安装', 503);
|
|
|
}
|
|
|
return CloudRegionFabric::where('region_id', $regionId)->first();
|
|
|
}
|
|
|
|
|
|
/** Reject an absent or drifting VPC pin before a Fabric host write. */
|
|
|
private static function assertLiveVpcFabricPinsCompatible(int $regionId,
|
|
|
bool $mappingConfigured, string $fabricId, string $fabricRegion,
|
|
|
int $revision): void
|
|
|
{
|
|
|
$pins = self::liveVpcPinsByRegion($regionId)[$regionId] ?? [];
|
|
|
if ($pins === []) {
|
|
|
return;
|
|
|
}
|
|
|
if (!$mappingConfigured) {
|
|
|
throw new CloudError(
|
|
|
'地区现有 VPC 缺少 Fabric 映射,请先完成私网迁移',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
foreach ($pins as $pin) {
|
|
|
if ((string) $pin['fabric_id'] === $fabricId
|
|
|
&& (string) $pin['fabric_region'] === $fabricRegion
|
|
|
&& (int) $pin['fabric_revision'] === $revision) {
|
|
|
continue;
|
|
|
}
|
|
|
throw new CloudError(
|
|
|
'地区现有 VPC 的 Fabric 固定信息不一致,请先完成私网迁移',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/** @return array<int, array<int, array<string, int|string>>> */
|
|
|
private static function liveVpcPinsByRegion(?int $regionId = null): array
|
|
|
{
|
|
|
$connection = (new CloudVpc())->getConnection();
|
|
|
if (!$connection->getSchemaBuilder()->hasTable('cloud_vpcs')) {
|
|
|
return [];
|
|
|
}
|
|
|
$rows = CloudVpc::query()
|
|
|
->whereNotIn('state', ['deleted'])
|
|
|
->when($regionId !== null,
|
|
|
static function ($query) use ($regionId): void {
|
|
|
$query->where('region_id', $regionId);
|
|
|
})
|
|
|
->select([
|
|
|
'region_id', 'fabric_id', 'fabric_region', 'fabric_revision',
|
|
|
])->distinct()
|
|
|
->orderBy('region_id')
|
|
|
->orderBy('fabric_id')
|
|
|
->orderBy('fabric_region')
|
|
|
->orderBy('fabric_revision')
|
|
|
->get();
|
|
|
$result = [];
|
|
|
foreach ($rows as $row) {
|
|
|
$key = (int) $row->region_id;
|
|
|
$result[$key][] = [
|
|
|
'fabric_id' => (string) $row->fabric_id,
|
|
|
'fabric_region' => (string) $row->fabric_region,
|
|
|
'fabric_revision' => (int) $row->fabric_revision,
|
|
|
];
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
private static function mappingExpectation(?CloudRegionFabric $mapping): array
|
|
|
{
|
|
|
if ($mapping === null) {
|
|
|
return ['exists' => false];
|
|
|
}
|
|
|
return [
|
|
|
'exists' => true,
|
|
|
'fabric_id' => (string) $mapping->fabric_id,
|
|
|
'fabric_region' => (string) $mapping->fabric_region,
|
|
|
'fabric_revision' => (int) $mapping->fabric_revision,
|
|
|
'state' => (string) $mapping->state,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function assertFabricIdentityOwnedByRegion(string $fabricId,
|
|
|
int $regionId): void
|
|
|
{
|
|
|
$owner = CloudRegionFabric::where('fabric_id', $fabricId)->first();
|
|
|
if ($owner !== null && (int) $owner->region_id !== $regionId) {
|
|
|
throw new CloudError(
|
|
|
'自动 Fabric 标识已绑定其他地区,已阻止引擎操作', 409
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function conflictingRegionFabrics(array $fabrics,
|
|
|
string $region, string $allowedFabricId,
|
|
|
array $requiredHostIds = []): array
|
|
|
{
|
|
|
$required = array_fill_keys(array_map('strval', $requiredHostIds), true);
|
|
|
return array_values(array_filter($fabrics,
|
|
|
static function (array $fabric) use (
|
|
|
$region, $allowedFabricId, $required
|
|
|
): bool {
|
|
|
if ((string) ($fabric['fabric_id'] ?? '') === $allowedFabricId) {
|
|
|
return false;
|
|
|
}
|
|
|
if ((string) ($fabric['region'] ?? '') === $region) {
|
|
|
return true;
|
|
|
}
|
|
|
// wg-fabric0 is engine-global per host. A Fabric with a
|
|
|
// different/unmapped region string still blocks this region if
|
|
|
// it owns one of the platform-required hosts.
|
|
|
foreach (($fabric['nodes'] ?? []) as $node) {
|
|
|
if (is_array($node)
|
|
|
&& isset($required[(string) ($node['host_id'] ?? '')])) {
|
|
|
return true;
|
|
|
}
|
|
|
}
|
|
|
return false;
|
|
|
}
|
|
|
));
|
|
|
}
|
|
|
|
|
|
private static function assertNoRegionFabricConflicts(array $fabrics,
|
|
|
string $region, string $allowedFabricId,
|
|
|
array $requiredHostIds = []): void
|
|
|
{
|
|
|
if (self::conflictingRegionFabrics(
|
|
|
$fabrics, $region, $allowedFabricId, $requiredHostIds
|
|
|
) !== []) {
|
|
|
throw new CloudError(
|
|
|
'该地区存在冲突的未映射 Fabric 或宿主机归属,需先完成显式迁移', 409
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function projectFabrics($raw): array
|
|
|
{
|
|
|
if (!is_array($raw)) {
|
|
|
throw new CloudError('Fabric 状态响应无效,请稍后重试', 502);
|
|
|
}
|
|
|
$hostNames = self::hostNames($raw);
|
|
|
$fabrics = [];
|
|
|
foreach ($raw as $item) {
|
|
|
if (is_array($item)) {
|
|
|
$fabrics[] = self::project($item, $hostNames);
|
|
|
}
|
|
|
}
|
|
|
usort($fabrics, static fn (array $a, array $b): int =>
|
|
|
strcmp((string) $a['fabric_id'], (string) $b['fabric_id']));
|
|
|
return $fabrics;
|
|
|
}
|
|
|
|
|
|
private static function emptyRegionContext($region): array
|
|
|
{
|
|
|
return [
|
|
|
'region_id' => (int) $region->id,
|
|
|
'region_code' => (string) $region->code,
|
|
|
'region_name' => (string) $region->name,
|
|
|
'region_status' => (string) $region->status,
|
|
|
'hosts' => [],
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Resolve host geography exclusively through the canonical membership ->
|
|
|
* pool -> line -> region relation. CloudHost.region is an operator-facing
|
|
|
* display label, never the selector used to place a host in this inventory.
|
|
|
*/
|
|
|
private static function platformRegions(): array
|
|
|
{
|
|
|
$regions = CloudRegion::orderBy('sort')->orderBy('id')->get();
|
|
|
$contexts = [];
|
|
|
foreach ($regions as $region) {
|
|
|
$context = self::emptyRegionContext($region);
|
|
|
$context['hosts'] = [];
|
|
|
$contexts[(int) $region->id] = $context;
|
|
|
}
|
|
|
if ($contexts === []) {
|
|
|
return [];
|
|
|
}
|
|
|
$schema = (new CloudHost())->getConnection()->getSchemaBuilder();
|
|
|
foreach (['cloud_hosts', 'cloud_host_resource_pool_memberships',
|
|
|
'cloud_resource_pools', 'cloud_network_lines'] as $table) {
|
|
|
if (!$schema->hasTable($table)) {
|
|
|
return $contexts;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
$rows = CloudHostResourcePoolMembership::query()
|
|
|
->join('cloud_resource_pools as fabric_pool',
|
|
|
'fabric_pool.id', '=',
|
|
|
'cloud_host_resource_pool_memberships.resource_pool_id')
|
|
|
->join('cloud_network_lines as fabric_line',
|
|
|
'fabric_line.id', '=', 'fabric_pool.line_id')
|
|
|
->orderBy('cloud_host_resource_pool_memberships.host_id')
|
|
|
->orderBy('cloud_host_resource_pool_memberships.id')
|
|
|
->get([
|
|
|
'cloud_host_resource_pool_memberships.id as membership_id',
|
|
|
'cloud_host_resource_pool_memberships.host_id',
|
|
|
'cloud_host_resource_pool_memberships.scheduler_state',
|
|
|
'cloud_host_resource_pool_memberships.updated_at as membership_updated_at',
|
|
|
'fabric_pool.id as pool_id', 'fabric_pool.name as pool_name',
|
|
|
'fabric_pool.status as pool_status',
|
|
|
'fabric_line.id as line_id', 'fabric_line.name as line_name',
|
|
|
'fabric_line.status as line_status', 'fabric_line.region_id',
|
|
|
]);
|
|
|
$joinedMemberships = [];
|
|
|
foreach ($rows as $row) {
|
|
|
$joinedMemberships[(int) $row->membership_id] = true;
|
|
|
if (in_array((string) $row->scheduler_state,
|
|
|
['active', 'draining'], true)
|
|
|
&& !isset($contexts[(int) $row->region_id])) {
|
|
|
throw new CloudError(
|
|
|
'地区宿主机成员关系指向不存在的地区,已阻止 Fabric 操作', 503
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
// An inner join is useful for the canonical projection, but it must
|
|
|
// never make a required placement disappear when its pool/line chain
|
|
|
// is corrupt. Such a row has no trustworthy region to which we could
|
|
|
// attach a warning, so fail the whole inventory closed instead of
|
|
|
// guessing from CloudHost.region.
|
|
|
foreach (CloudHostResourcePoolMembership::whereIn(
|
|
|
'scheduler_state', ['active', 'draining']
|
|
|
)->get(['id']) as $membership) {
|
|
|
if (!isset($joinedMemberships[(int) $membership->id])) {
|
|
|
throw new CloudError(
|
|
|
'地区宿主机成员关系缺少资源池或线路,已阻止 Fabric 操作', 503
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
$byHost = [];
|
|
|
foreach ($rows as $row) {
|
|
|
$byHost[(int) $row->host_id][] = $row;
|
|
|
}
|
|
|
$hostIds = array_keys($byHost);
|
|
|
$hostModels = $hostIds === [] ? collect()
|
|
|
: CloudHost::whereIn('id', $hostIds)->get();
|
|
|
$hosts = [];
|
|
|
foreach ($hostModels as $host) {
|
|
|
$hosts[(int) $host->id] = $host;
|
|
|
}
|
|
|
|
|
|
$selectedByHost = [];
|
|
|
foreach ($byHost as $hostId => $memberships) {
|
|
|
$live = array_values(array_filter($memberships,
|
|
|
static fn ($row): bool => in_array(
|
|
|
(string) $row->scheduler_state,
|
|
|
['active', 'draining'], true
|
|
|
)));
|
|
|
$active = array_values(array_filter($memberships,
|
|
|
static fn ($row): bool => (string) $row->scheduler_state === 'active'));
|
|
|
$conflict = count($live) > 1;
|
|
|
if ($active !== []) {
|
|
|
$selected = $active;
|
|
|
} else {
|
|
|
$draining = array_values(array_filter($memberships,
|
|
|
static fn ($row): bool => (string) $row->scheduler_state === 'draining'));
|
|
|
$candidates = $draining !== [] ? $draining : $memberships;
|
|
|
usort($candidates, static function ($left, $right): int {
|
|
|
$updated = (int) $right->membership_updated_at
|
|
|
<=> (int) $left->membership_updated_at;
|
|
|
return $updated !== 0 ? $updated
|
|
|
: ((int) $right->membership_id <=> (int) $left->membership_id);
|
|
|
});
|
|
|
$selected = isset($candidates[0]) ? [$candidates[0]] : [];
|
|
|
}
|
|
|
$selectedByHost[$hostId] = $selected[0] ?? null;
|
|
|
foreach ($selected as $placement) {
|
|
|
$regionId = (int) $placement->region_id;
|
|
|
$host = $hosts[$hostId] ?? null;
|
|
|
if (!isset($contexts[$regionId])) {
|
|
|
continue;
|
|
|
}
|
|
|
$reasons = [];
|
|
|
if ($conflict) {
|
|
|
$reasons[] = 'membership_conflict';
|
|
|
}
|
|
|
$scheduler = in_array((string) $placement->scheduler_state,
|
|
|
self::HOST_STATES, true)
|
|
|
? (string) $placement->scheduler_state : 'disabled';
|
|
|
if ($host === null) {
|
|
|
$reasons[] = 'host_record_missing';
|
|
|
} elseif (!(bool) $host->enabled) {
|
|
|
$reasons[] = 'host_disabled';
|
|
|
}
|
|
|
if (!in_array($scheduler, ['active', 'draining'], true)) {
|
|
|
$reasons[] = 'scheduler_disabled';
|
|
|
}
|
|
|
if ((string) $placement->pool_status !== 'active') {
|
|
|
$reasons[] = 'resource_pool_disabled';
|
|
|
}
|
|
|
if ((string) $placement->line_status !== 'active') {
|
|
|
$reasons[] = 'network_line_disabled';
|
|
|
}
|
|
|
if ((string) $contexts[$regionId]['region_status'] !== 'active') {
|
|
|
$reasons[] = 'region_disabled';
|
|
|
}
|
|
|
$contexts[$regionId]['hosts'][(string) $hostId] = [
|
|
|
'host_id' => $hostId,
|
|
|
'host_name' => (string) ($host->name ?? ('宿主机 #' . $hostId)),
|
|
|
'host_enabled' => (bool) ($host->enabled ?? false),
|
|
|
'engine_region' => (string) ($host->region ?? ''),
|
|
|
'scheduler_state' => $scheduler,
|
|
|
'pool_id' => (int) $placement->pool_id,
|
|
|
'pool_name' => (string) $placement->pool_name,
|
|
|
'pool_status' => (string) $placement->pool_status,
|
|
|
'line_id' => (int) $placement->line_id,
|
|
|
'line_name' => (string) $placement->line_name,
|
|
|
'line_status' => (string) $placement->line_status,
|
|
|
'required' => in_array($scheduler, ['active', 'draining'], true),
|
|
|
'required_sources' => in_array($scheduler, ['active', 'draining'], true)
|
|
|
? ['membership'] : [],
|
|
|
'platform_ready' => $reasons === [],
|
|
|
'reasons' => array_values(array_unique($reasons)),
|
|
|
];
|
|
|
}
|
|
|
}
|
|
|
|
|
|
$poolRegions = [];
|
|
|
foreach (CloudResourcePool::query()
|
|
|
->join('cloud_network_lines as required_line',
|
|
|
'required_line.id', '=', 'cloud_resource_pools.line_id')
|
|
|
->get(['cloud_resource_pools.id as pool_id', 'required_line.region_id']) as $row) {
|
|
|
$poolRegions[(int) $row->pool_id] = (int) $row->region_id;
|
|
|
}
|
|
|
$required = [];
|
|
|
if ($schema->hasTable('cloud_instances')) {
|
|
|
foreach (CloudInstance::where('status', '<>', 'deleted')
|
|
|
->get(['host_id', 'resource_pool_id']) as $instance) {
|
|
|
$hostId = (int) $instance->host_id;
|
|
|
$poolId = (int) ($instance->resource_pool_id ?? 0);
|
|
|
if ($poolId > 0 && !isset($poolRegions[$poolId])) {
|
|
|
throw new CloudError(
|
|
|
'现有实例指向无效的资源池或线路,已阻止 Fabric 操作', 503
|
|
|
);
|
|
|
}
|
|
|
$regionId = $poolId > 0
|
|
|
? $poolRegions[$poolId]
|
|
|
: (int) ($selectedByHost[$hostId]->region_id ?? 0);
|
|
|
if ($regionId <= 0 || !isset($contexts[$regionId])) {
|
|
|
throw new CloudError(
|
|
|
'现有实例无法归属有效地区,已阻止 Fabric 操作', 503
|
|
|
);
|
|
|
}
|
|
|
$required[$regionId][$hostId]['instance'] = true;
|
|
|
}
|
|
|
}
|
|
|
if ($schema->hasTable('cloud_vpcs')
|
|
|
&& $schema->hasTable('cloud_vpc_host_deployments')) {
|
|
|
$deployments = CloudVpcHostDeployment::query()
|
|
|
->join('cloud_vpcs as required_vpc',
|
|
|
'required_vpc.id', '=', 'cloud_vpc_host_deployments.vpc_id')
|
|
|
->where('required_vpc.state', '<>', 'deleted')
|
|
|
->where('cloud_vpc_host_deployments.state', '<>', 'deleted')
|
|
|
->get(['cloud_vpc_host_deployments.id as deployment_id',
|
|
|
'cloud_vpc_host_deployments.host_id',
|
|
|
'required_vpc.region_id']);
|
|
|
$joinedDeploymentIds = [];
|
|
|
foreach ($deployments as $deployment) {
|
|
|
$joinedDeploymentIds[(int) $deployment->deployment_id] = true;
|
|
|
$regionId = (int) $deployment->region_id;
|
|
|
if (!isset($contexts[$regionId])) {
|
|
|
throw new CloudError(
|
|
|
'现有 VPC 部署无法归属有效地区,已阻止 Fabric 操作', 503
|
|
|
);
|
|
|
}
|
|
|
$required[$regionId][(int) $deployment->host_id]
|
|
|
['vpc_deployment'] = true;
|
|
|
}
|
|
|
foreach (CloudVpcHostDeployment::where('state', '<>', 'deleted')
|
|
|
->get(['id']) as $deployment) {
|
|
|
if (!isset($joinedDeploymentIds[(int) $deployment->id])) {
|
|
|
throw new CloudError(
|
|
|
'现有 VPC 部署缺少有效的 VPC 归属,已阻止 Fabric 操作', 503
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
$requiredHostIds = [];
|
|
|
foreach ($required as $regionHosts) {
|
|
|
foreach ($regionHosts as $hostId => $_sources) {
|
|
|
$requiredHostIds[$hostId] = true;
|
|
|
}
|
|
|
}
|
|
|
foreach (array_keys($requiredHostIds) as $hostId) {
|
|
|
if (!isset($hosts[$hostId])) {
|
|
|
$host = CloudHost::find($hostId);
|
|
|
if ($host !== null) {
|
|
|
$hosts[$hostId] = $host;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
foreach ($required as $regionId => $regionHosts) {
|
|
|
if (!isset($contexts[$regionId])) {
|
|
|
throw new CloudError(
|
|
|
'现有工作负载无法归属有效地区,已阻止 Fabric 操作', 503
|
|
|
);
|
|
|
}
|
|
|
foreach ($regionHosts as $hostId => $sources) {
|
|
|
$key = (string) $hostId;
|
|
|
if (!isset($contexts[$regionId]['hosts'][$key])) {
|
|
|
$host = $hosts[$hostId] ?? null;
|
|
|
$placement = $selectedByHost[$hostId] ?? null;
|
|
|
$fallbackReasons = ['workload_membership_mismatch'];
|
|
|
if ($host === null) {
|
|
|
$fallbackReasons[] = 'host_record_missing';
|
|
|
}
|
|
|
$contexts[$regionId]['hosts'][$key] = [
|
|
|
'host_id' => $hostId,
|
|
|
'host_name' => (string) ($host->name
|
|
|
?? ('宿主机 #' . $hostId)),
|
|
|
'host_enabled' => (bool) ($host->enabled ?? false),
|
|
|
'engine_region' => (string) ($host->region ?? ''),
|
|
|
'scheduler_state' => (string) ($placement->scheduler_state
|
|
|
?? $host->scheduler_state ?? 'disabled'),
|
|
|
'pool_id' => null, 'pool_name' => '',
|
|
|
'pool_status' => 'missing', 'line_id' => null,
|
|
|
'line_name' => '', 'line_status' => 'missing',
|
|
|
'required' => true,
|
|
|
'required_sources' => array_keys($sources),
|
|
|
'platform_ready' => false,
|
|
|
'reasons' => $fallbackReasons,
|
|
|
];
|
|
|
} else {
|
|
|
$contexts[$regionId]['hosts'][$key]['required'] = true;
|
|
|
$contexts[$regionId]['hosts'][$key]['required_sources'] =
|
|
|
array_values(array_unique(array_merge(
|
|
|
$contexts[$regionId]['hosts'][$key]['required_sources'],
|
|
|
array_keys($sources)
|
|
|
)));
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
foreach ($contexts as &$context) {
|
|
|
// A region readiness inventory is the exact set that must remain
|
|
|
// network-capable: active/draining placements plus hosts retained
|
|
|
// by a workload/deployment. A purely disabled, unused membership
|
|
|
// is intentionally omitted so detection never reconnects to a
|
|
|
// retired host. Existing Fabric-only nodes are added separately
|
|
|
// below as visible drift.
|
|
|
$context['hosts'] = array_values(array_filter(
|
|
|
$context['hosts'],
|
|
|
static fn (array $host): bool => ($host['required'] ?? false) === true
|
|
|
));
|
|
|
usort($context['hosts'], static fn (array $left, array $right): int =>
|
|
|
(int) $left['host_id'] <=> (int) $right['host_id']);
|
|
|
}
|
|
|
unset($context);
|
|
|
return $contexts;
|
|
|
}
|
|
|
|
|
|
/** Re-read the database gates after a long-running engine operation. */
|
|
|
private static function assertPlatformContextUnchanged(CloudRegion $region,
|
|
|
array $expectedHostIds): void
|
|
|
{
|
|
|
$freshRegion = CloudRegion::find((int) $region->id);
|
|
|
if ($freshRegion === null || (string) $freshRegion->status !== 'active') {
|
|
|
throw new CloudError('地区在配置期间已停用,已阻止写入 Fabric 映射', 409);
|
|
|
}
|
|
|
$contexts = self::platformRegions();
|
|
|
$context = $contexts[(int) $region->id]
|
|
|
?? self::emptyRegionContext($freshRegion);
|
|
|
$actual = [];
|
|
|
foreach ($context['hosts'] as $host) {
|
|
|
if (($host['required'] ?? false) !== true) {
|
|
|
continue;
|
|
|
}
|
|
|
if (($host['platform_ready'] ?? false) !== true) {
|
|
|
throw new CloudError('地区宿主机平台门禁在配置期间已变更', 409);
|
|
|
}
|
|
|
$actual[] = (string) $host['host_id'];
|
|
|
}
|
|
|
$expected = array_map('strval', $expectedHostIds);
|
|
|
sort($expected, SORT_STRING);
|
|
|
sort($actual, SORT_STRING);
|
|
|
if ($expected !== $actual) {
|
|
|
throw new CloudError('地区宿主机集合在配置期间已变更,请重新检测', 409);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function readinessRegions(array $fabrics, array $mappings,
|
|
|
array $probes = [], bool $engineAvailable = true): array
|
|
|
{
|
|
|
$contexts = self::platformRegions();
|
|
|
$liveVpcPinsByRegion = self::liveVpcPinsByRegion();
|
|
|
$fabricById = [];
|
|
|
foreach ($fabrics as $fabric) {
|
|
|
$fabricById[(string) $fabric['fabric_id']] = $fabric;
|
|
|
}
|
|
|
$mappingByRegion = [];
|
|
|
foreach ($mappings as $mapping) {
|
|
|
$mappingByRegion[(int) $mapping['region_id']] = $mapping;
|
|
|
}
|
|
|
$rows = [];
|
|
|
foreach ($contexts as $regionId => $context) {
|
|
|
$mapping = $mappingByRegion[$regionId] ?? null;
|
|
|
$automaticId = self::automaticFabricId((string) $context['region_code']);
|
|
|
$fabricId = is_array($mapping) && is_string($mapping['fabric_id'] ?? null)
|
|
|
&& $mapping['fabric_id'] !== '' ? (string) $mapping['fabric_id']
|
|
|
: $automaticId;
|
|
|
$expectedRegion = is_array($mapping)
|
|
|
&& is_string($mapping['fabric_region'] ?? null)
|
|
|
&& $mapping['fabric_region'] !== ''
|
|
|
? (string) $mapping['fabric_region']
|
|
|
: (string) $context['region_code'];
|
|
|
$hosts = [];
|
|
|
foreach ($context['hosts'] as $host) {
|
|
|
$hosts[(string) $host['host_id']] = $host;
|
|
|
}
|
|
|
// Freeze the platform-owned desired set before merging engine
|
|
|
// observations. Otherwise an orphan Fabric node would add itself
|
|
|
// to both sides of the comparison and hide membership drift.
|
|
|
$requiredIds = array_map('strval', array_keys($hosts));
|
|
|
sort($requiredIds, SORT_STRING);
|
|
|
$conflictFabrics = self::conflictingRegionFabrics(
|
|
|
$fabrics, $expectedRegion, $fabricId, $requiredIds
|
|
|
);
|
|
|
$desiredFabric = $fabricById[$fabricId] ?? null;
|
|
|
$fabric = $desiredFabric;
|
|
|
if ($fabric === null && $conflictFabrics !== []) {
|
|
|
// Show one historical/conflicting record as the readback
|
|
|
// summary while retaining every conflicting identity below.
|
|
|
// It remains ineligible for mapping or reconciliation.
|
|
|
$fabric = $conflictFabrics[0];
|
|
|
}
|
|
|
$nodes = [];
|
|
|
foreach (($fabric['nodes'] ?? []) as $node) {
|
|
|
$hostId = (string) ($node['host_id'] ?? '');
|
|
|
if ($hostId === '') {
|
|
|
continue;
|
|
|
}
|
|
|
$nodes[$hostId] = $node;
|
|
|
if (!isset($hosts[$hostId])) {
|
|
|
$model = ctype_digit($hostId) ? CloudHost::find((int) $hostId) : null;
|
|
|
$hosts[$hostId] = [
|
|
|
'host_id' => ctype_digit($hostId) ? (int) $hostId : $hostId,
|
|
|
'host_name' => (string) ($model->name ?? ('宿主机 #' . $hostId)),
|
|
|
'host_enabled' => (bool) ($model->enabled ?? false),
|
|
|
'engine_region' => (string) ($model->region ?? ''),
|
|
|
'scheduler_state' => (string) ($model->scheduler_state ?? 'disabled'),
|
|
|
'pool_id' => null, 'pool_name' => '', 'pool_status' => 'missing',
|
|
|
'line_id' => null, 'line_name' => '', 'line_status' => 'missing',
|
|
|
'required' => false, 'required_sources' => ['fabric'],
|
|
|
'platform_ready' => false,
|
|
|
'reasons' => ['fabric_membership_drift'],
|
|
|
];
|
|
|
} else {
|
|
|
$hosts[$hostId]['required'] = true;
|
|
|
$hosts[$hostId]['required_sources'][] = 'fabric';
|
|
|
$hosts[$hostId]['required_sources'] = array_values(array_unique(
|
|
|
$hosts[$hostId]['required_sources']));
|
|
|
}
|
|
|
}
|
|
|
$conflictNodes = [];
|
|
|
foreach ($conflictFabrics as $conflictFabric) {
|
|
|
foreach (($conflictFabric['nodes'] ?? []) as $conflictNode) {
|
|
|
$hostId = (string) ($conflictNode['host_id'] ?? '');
|
|
|
if ($hostId === '') {
|
|
|
continue;
|
|
|
}
|
|
|
$conflictNodes[$hostId] = $conflictNode;
|
|
|
if (!isset($hosts[$hostId])) {
|
|
|
$model = ctype_digit($hostId)
|
|
|
? CloudHost::find((int) $hostId) : null;
|
|
|
$hosts[$hostId] = [
|
|
|
'host_id' => ctype_digit($hostId)
|
|
|
? (int) $hostId : $hostId,
|
|
|
'host_name' => (string) ($model->name
|
|
|
?? ('宿主机 #' . $hostId)),
|
|
|
'host_enabled' => (bool) ($model->enabled ?? false),
|
|
|
'engine_region' => (string) ($model->region ?? ''),
|
|
|
'scheduler_state' => (string) ($model->scheduler_state
|
|
|
?? 'disabled'),
|
|
|
'pool_id' => null, 'pool_name' => '',
|
|
|
'pool_status' => 'missing', 'line_id' => null,
|
|
|
'line_name' => '', 'line_status' => 'missing',
|
|
|
'required' => false,
|
|
|
'required_sources' => ['fabric_conflict'],
|
|
|
'platform_ready' => false,
|
|
|
'reasons' => ['fabric_identity_conflict'],
|
|
|
];
|
|
|
} else {
|
|
|
$hosts[$hostId]['required_sources'][] = 'fabric_conflict';
|
|
|
$hosts[$hostId]['required_sources'] = array_values(
|
|
|
array_unique($hosts[$hostId]['required_sources'])
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
// PHP coerces numeric-string array keys to integers. Normalize
|
|
|
// both sides before the strict identity comparison so ordinary
|
|
|
// database host IDs can converge to an exact active set.
|
|
|
$nodeIds = array_map('strval', array_keys($nodes));
|
|
|
sort($nodeIds, SORT_STRING);
|
|
|
$hostSetMatches = $fabric !== null && $conflictFabrics === []
|
|
|
&& $requiredIds === $nodeIds;
|
|
|
$mappingReady = is_array($mapping) && $fabric !== null
|
|
|
&& ($mapping['state'] ?? null) === 'active'
|
|
|
&& (string) ($mapping['fabric_region'] ?? '') === (string) $fabric['region']
|
|
|
&& (int) ($mapping['fabric_revision'] ?? 0) === (int) $fabric['revision']
|
|
|
&& (string) ($fabric['state'] ?? '') === 'active'
|
|
|
&& ($fabric['next_stage_allowed'] ?? false) === true;
|
|
|
$hostRows = [];
|
|
|
$readyHosts = 0;
|
|
|
$blockedHosts = 0;
|
|
|
$probeEndpointCounts = [];
|
|
|
foreach ($hosts as $hostId => $host) {
|
|
|
$probeEndpoint = $probes[(string) $hostId]['endpoint_ip'] ?? null;
|
|
|
if (($host['required'] ?? false) === true
|
|
|
&& is_string($probeEndpoint) && $probeEndpoint !== '') {
|
|
|
$key = $probeEndpoint . ':' . self::FABRIC_LISTEN_PORT;
|
|
|
$probeEndpointCounts[$key] = ($probeEndpointCounts[$key] ?? 0) + 1;
|
|
|
}
|
|
|
}
|
|
|
foreach ($hosts as $hostId => $host) {
|
|
|
$probe = $probes[(string) $hostId] ?? null;
|
|
|
$node = $nodes[(string) $hostId] ?? null;
|
|
|
$conflictNode = $conflictNodes[(string) $hostId] ?? null;
|
|
|
$observedNode = $node ?? $conflictNode;
|
|
|
$reasons = array_values($host['reasons'] ?? []);
|
|
|
if (is_array($conflictNode)) {
|
|
|
$reasons[] = 'fabric_identity_conflict';
|
|
|
}
|
|
|
$platformReady = ($host['platform_ready'] ?? false) === true;
|
|
|
if (is_array($probe)) {
|
|
|
$reasons = array_merge($reasons, $probe['reasons']);
|
|
|
if (($probe['endpoint_ip'] ?? null) === null) {
|
|
|
$reasons[] = 'fabric_endpoint_unavailable';
|
|
|
} elseif (($probeEndpointCounts[
|
|
|
$probe['endpoint_ip'] . ':' . self::FABRIC_LISTEN_PORT
|
|
|
] ?? 0) > 1) {
|
|
|
$reasons[] = 'fabric_endpoint_duplicate';
|
|
|
}
|
|
|
}
|
|
|
if (is_array($probe) && is_array($node)
|
|
|
&& is_string($probe['endpoint_ip'] ?? null)
|
|
|
&& ($node['endpoint'] ?? null)
|
|
|
!== $probe['endpoint_ip'] . ':' . self::FABRIC_LISTEN_PORT) {
|
|
|
// A saved Fabric revision owns one exact endpoint per
|
|
|
// host. A new host-profile endpoint must never be shown
|
|
|
// as active while the Engine is still running the old
|
|
|
// plan; switching underlays needs a versioned migration.
|
|
|
$reasons[] = 'fabric_endpoint_mismatch';
|
|
|
}
|
|
|
if (($host['required'] ?? false) === true && $fabric !== null
|
|
|
&& $node === null) {
|
|
|
$reasons[] = 'fabric_membership_drift';
|
|
|
}
|
|
|
if (is_array($observedNode)
|
|
|
&& !empty($observedNode['last_error_code'])) {
|
|
|
$reasons[] = (string) $observedNode['last_error_code'];
|
|
|
}
|
|
|
$reasons = array_values(array_unique(array_filter($reasons,
|
|
|
static fn ($reason): bool => is_string($reason) && $reason !== '')));
|
|
|
$freshReady = is_array($probe)
|
|
|
&& $platformReady
|
|
|
&& ($probe['configured'] ?? false) === true
|
|
|
&& ($probe['reachable'] ?? false) === true
|
|
|
&& ($probe['vpc_ready'] ?? false) === true
|
|
|
&& ($probe['endpoint_ip'] ?? null) !== null
|
|
|
&& in_array($probe['endpoint_source'] ?? null,
|
|
|
self::ENDPOINT_SOURCES, true)
|
|
|
&& $reasons === [];
|
|
|
$active = $mappingReady && $hostSetMatches
|
|
|
&& ($host['required'] ?? false) === true
|
|
|
&& $platformReady
|
|
|
&& (!is_array($probe) || $freshReady)
|
|
|
&& $reasons === [] && is_array($node)
|
|
|
&& ($node['state'] ?? null) === 'active'
|
|
|
&& ($node['transport_verified'] ?? false) === true;
|
|
|
if ($active) {
|
|
|
$state = 'active';
|
|
|
} elseif (is_array($probe)) {
|
|
|
$state = $freshReady ? 'ready' : 'blocked';
|
|
|
} elseif ($reasons !== [] && is_array($node)) {
|
|
|
$state = 'uncertain';
|
|
|
} elseif (!$platformReady) {
|
|
|
$state = 'blocked';
|
|
|
} else {
|
|
|
$state = 'not_checked';
|
|
|
}
|
|
|
if (in_array($state, ['active', 'ready'], true)) {
|
|
|
$readyHosts++;
|
|
|
} elseif (in_array($state, ['blocked', 'uncertain'], true)) {
|
|
|
$blockedHosts++;
|
|
|
}
|
|
|
$hostRows[] = array_merge($host, [
|
|
|
'platform_ready' => $platformReady,
|
|
|
'configured' => $probe['configured'] ?? null,
|
|
|
'reachable' => $probe['reachable'] ?? null,
|
|
|
'endpoint_ip' => $probe['endpoint_ip'] ?? null,
|
|
|
'endpoint_source' => $probe['endpoint_source'] ?? null,
|
|
|
'probe_checked' => is_array($probe),
|
|
|
'probed_at' => $probe['probed_at'] ?? null,
|
|
|
'vpc_ready' => $probe['vpc_ready'] ?? null,
|
|
|
'capabilities' => $probe['capabilities'] ?? [],
|
|
|
'fabric_member' => is_array($observedNode),
|
|
|
'fabric_state' => $observedNode['state'] ?? null,
|
|
|
'transport_verified' => $observedNode['transport_verified'] ?? false,
|
|
|
'observed_revision' => $observedNode['observed_revision'] ?? null,
|
|
|
'last_error_code' => $observedNode['last_error_code'] ?? null,
|
|
|
'last_error_phase' => $observedNode['last_error_phase'] ?? null,
|
|
|
'operation' => $observedNode['operation'] ?? null,
|
|
|
'readiness_state' => $state,
|
|
|
'reasons' => $reasons,
|
|
|
]);
|
|
|
}
|
|
|
usort($hostRows, static fn (array $left, array $right): int =>
|
|
|
(int) $left['host_id'] <=> (int) $right['host_id']);
|
|
|
$requiredCount = count(array_filter($hostRows,
|
|
|
static fn (array $host): bool => ($host['required'] ?? false) === true));
|
|
|
$ready = $mappingReady && $hostSetMatches && $requiredCount >= 2
|
|
|
&& count(array_filter($hostRows,
|
|
|
static fn (array $host): bool => ($host['required'] ?? false) === true
|
|
|
&& ($host['readiness_state'] ?? '') !== 'active')) === 0;
|
|
|
[$workflow, $planPreview] = self::workflowProjection(
|
|
|
$context, $mapping, $desiredFabric, $fabrics,
|
|
|
$conflictFabrics, $hostRows, $probes, $hostSetMatches,
|
|
|
$ready, $engineAvailable,
|
|
|
$liveVpcPinsByRegion[(int) $regionId] ?? []
|
|
|
);
|
|
|
$rows[] = array_merge($context, [
|
|
|
'fabric_id' => $mapping['fabric_id'] ?? ($fabric['fabric_id'] ?? null),
|
|
|
'fabric_region' => $mapping['fabric_region'] ?? ($fabric['region'] ?? null),
|
|
|
'fabric_revision' => $mapping['fabric_revision'] ?? ($fabric['revision'] ?? null),
|
|
|
'mapping_state' => $mapping['state'] ?? 'unconfigured',
|
|
|
'fabric_state' => $fabric['state'] ?? null,
|
|
|
'operation' => $fabric['operation'] ?? null,
|
|
|
'next_stage_allowed' => $conflictFabrics === []
|
|
|
&& ($fabric['next_stage_allowed'] ?? false) === true,
|
|
|
'fabric_conflicts' => array_map(
|
|
|
static fn (array $item): array => [
|
|
|
'fabric_id' => (string) $item['fabric_id'],
|
|
|
'region' => (string) $item['region'],
|
|
|
'revision' => (int) $item['revision'],
|
|
|
'state' => (string) $item['state'],
|
|
|
], $conflictFabrics
|
|
|
),
|
|
|
'ready' => $ready,
|
|
|
'host_set_matches' => $hostSetMatches,
|
|
|
'host_count' => count($hostRows),
|
|
|
'required_host_count' => $requiredCount,
|
|
|
'ready_host_count' => $readyHosts,
|
|
|
'blocked_host_count' => $blockedHosts,
|
|
|
'hosts' => $hostRows,
|
|
|
'workflow' => $workflow,
|
|
|
'plan_preview' => $planPreview,
|
|
|
]);
|
|
|
}
|
|
|
usort($rows, static function (array $left, array $right): int {
|
|
|
$status = (($left['region_status'] ?? '') === 'active' ? 0 : 1)
|
|
|
<=> (($right['region_status'] ?? '') === 'active' ? 0 : 1);
|
|
|
return $status !== 0 ? $status
|
|
|
: strcmp((string) $left['region_name'], (string) $right['region_name']);
|
|
|
});
|
|
|
return $rows;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Derive the administrator wizard from authoritative platform and engine
|
|
|
* state. The browser receives only bounded action gates and a read-only
|
|
|
* summary; it never receives the generated node/endpoint plan.
|
|
|
*/
|
|
|
private static function workflowProjection(array $context, ?array $mapping,
|
|
|
?array $desiredFabric, array $fabrics, array $conflictFabrics,
|
|
|
array $hostRows, array $probes, bool $hostSetMatches, bool $ready,
|
|
|
bool $engineAvailable, array $liveVpcPins): array
|
|
|
{
|
|
|
$requiredHosts = array_values(array_filter($hostRows,
|
|
|
static fn (array $host): bool => ($host['required'] ?? false) === true));
|
|
|
$requiredCount = count($requiredHosts);
|
|
|
$hostCount = count($hostRows);
|
|
|
$mappingConfigured = is_array($mapping)
|
|
|
&& is_string($mapping['fabric_id'] ?? null)
|
|
|
&& $mapping['fabric_id'] !== '';
|
|
|
$mappingState = $mappingConfigured
|
|
|
? (string) ($mapping['state'] ?? '') : 'unconfigured';
|
|
|
$canProbe = $engineAvailable && $hostCount >= 1
|
|
|
&& $hostCount <= self::MAX_READINESS_HOSTS;
|
|
|
|
|
|
$reasons = [];
|
|
|
$addReason = static function (array &$values, string $reason): void {
|
|
|
if (preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $reason) === 1
|
|
|
&& !in_array($reason, $values, true) && count($values) < 32) {
|
|
|
$values[] = $reason;
|
|
|
}
|
|
|
};
|
|
|
$addHostReasons = static function () use (
|
|
|
&$reasons, $hostRows, $addReason
|
|
|
): void {
|
|
|
foreach ($hostRows as $host) {
|
|
|
foreach (is_array($host['reasons'] ?? null)
|
|
|
? $host['reasons'] : [] as $reason) {
|
|
|
if (is_string($reason)) {
|
|
|
$addReason($reasons, $reason);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
};
|
|
|
$result = static function (string $stage, bool $canApply,
|
|
|
bool $canReconcile) use (&$reasons, $canProbe): array {
|
|
|
$probeAllowed = $stage !== 'operation_running' && $canProbe;
|
|
|
$action = 'none';
|
|
|
if ($stage === 'ready_to_apply' && $canApply) {
|
|
|
$action = 'apply';
|
|
|
} elseif (in_array($stage,
|
|
|
['needs_reconcile', 'operation_running'], true)
|
|
|
&& $canReconcile) {
|
|
|
$action = 'reconcile';
|
|
|
} elseif (in_array($stage, ['needs_probe', 'blocked'], true)
|
|
|
&& $probeAllowed) {
|
|
|
$action = 'probe';
|
|
|
}
|
|
|
return [[
|
|
|
'stage' => $stage,
|
|
|
'can_probe' => $probeAllowed,
|
|
|
'can_apply' => $canApply,
|
|
|
'can_reconcile' => $canReconcile,
|
|
|
'blocking_reasons' => array_values($reasons),
|
|
|
'action_mode' => $action,
|
|
|
], null];
|
|
|
};
|
|
|
$existingPreview = static function (?array $fabric): ?array {
|
|
|
if (!is_array($fabric)) {
|
|
|
return null;
|
|
|
}
|
|
|
return [
|
|
|
'mode' => 'existing',
|
|
|
'fabric_id' => (string) $fabric['fabric_id'],
|
|
|
'fabric_region' => (string) $fabric['region'],
|
|
|
'revision' => (int) $fabric['revision'],
|
|
|
'listen_port' => (int) $fabric['listen_port'],
|
|
|
'overlay_cidr' => (string) $fabric['overlay_cidr'],
|
|
|
'host_count' => count($fabric['nodes'] ?? []),
|
|
|
];
|
|
|
};
|
|
|
$withPreview = static function (array $workflow, ?array $preview): array {
|
|
|
return [$workflow[0], $preview];
|
|
|
};
|
|
|
|
|
|
if ($liveVpcPins !== [] && !$mappingConfigured) {
|
|
|
$addReason($reasons, 'vpc_fabric_mapping_missing');
|
|
|
return $withPreview(
|
|
|
$result('migration_required', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
foreach ($liveVpcPins as $pin) {
|
|
|
if ((string) ($pin['fabric_id'] ?? '')
|
|
|
=== (string) ($mapping['fabric_id'] ?? '')
|
|
|
&& (string) ($pin['fabric_region'] ?? '')
|
|
|
=== (string) ($mapping['fabric_region'] ?? '')
|
|
|
&& (int) ($pin['fabric_revision'] ?? 0)
|
|
|
=== (int) ($mapping['fabric_revision'] ?? 0)) {
|
|
|
continue;
|
|
|
}
|
|
|
$addReason($reasons, 'vpc_fabric_pin_mismatch');
|
|
|
return $withPreview(
|
|
|
$result('migration_required', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if (!$engineAvailable) {
|
|
|
$addReason($reasons, 'engine_unavailable');
|
|
|
return $result('engine_unavailable', false, false);
|
|
|
}
|
|
|
$currentOperation = is_array($desiredFabric['operation'] ?? null)
|
|
|
? $desiredFabric['operation'] : null;
|
|
|
if (is_array($currentOperation)
|
|
|
&& in_array($currentOperation['status'] ?? null,
|
|
|
['queued', 'running'], true)) {
|
|
|
$addReason($reasons, 'fabric_operation_running');
|
|
|
return $withPreview(
|
|
|
$result('operation_running', false, true),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if ($mappingConfigured && $desiredFabric === null) {
|
|
|
// A database mapping pins one exact desired identity. A different
|
|
|
// same-region Fabric is a second problem, not a replacement plan
|
|
|
// that the wizard may adopt or preview.
|
|
|
$addReason($reasons, 'fabric_desired_missing');
|
|
|
if ($conflictFabrics !== []) {
|
|
|
$addReason($reasons, 'fabric_identity_conflict');
|
|
|
}
|
|
|
return $result('recovery_required', false, false);
|
|
|
}
|
|
|
if ($conflictFabrics !== []) {
|
|
|
$addReason($reasons, 'fabric_identity_conflict');
|
|
|
$addHostReasons();
|
|
|
return $withPreview(
|
|
|
$result('migration_required', false, false),
|
|
|
$existingPreview($desiredFabric ?? $conflictFabrics[0])
|
|
|
);
|
|
|
}
|
|
|
if ($desiredFabric !== null && !$hostSetMatches) {
|
|
|
$addReason($reasons, 'fabric_membership_drift');
|
|
|
$addHostReasons();
|
|
|
return $withPreview(
|
|
|
$result('migration_required', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
|
|
|
$mappedExact = $mappingConfigured && $desiredFabric !== null
|
|
|
&& (string) ($mapping['fabric_region'] ?? '')
|
|
|
=== (string) $desiredFabric['region']
|
|
|
&& (int) ($mapping['fabric_revision'] ?? 0)
|
|
|
=== (int) $desiredFabric['revision']
|
|
|
&& $hostSetMatches;
|
|
|
if ($mappingConfigured && !$mappedExact) {
|
|
|
$addReason($reasons, 'fabric_plan_mismatch');
|
|
|
return $withPreview(
|
|
|
$result('migration_required', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
$endpointDrift = count(array_filter(
|
|
|
$requiredHosts,
|
|
|
static fn (array $host): bool => in_array(
|
|
|
'fabric_endpoint_mismatch',
|
|
|
is_array($host['reasons'] ?? null) ? $host['reasons'] : [],
|
|
|
true
|
|
|
)
|
|
|
)) > 0;
|
|
|
if ($desiredFabric !== null && $endpointDrift) {
|
|
|
$addHostReasons();
|
|
|
return $withPreview(
|
|
|
$result('migration_required', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if ($requiredCount === 0) {
|
|
|
$addReason($reasons, 'no_required_hosts');
|
|
|
return $withPreview(
|
|
|
$result('no_hosts', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if ($hostCount > self::MAX_READINESS_HOSTS) {
|
|
|
$addReason($reasons, 'readiness_host_limit_exceeded');
|
|
|
return $withPreview(
|
|
|
$result('blocked', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if ($requiredCount > self::MAX_FABRIC_NODES) {
|
|
|
$addReason($reasons, 'fabric_node_limit_exceeded');
|
|
|
return $withPreview(
|
|
|
$result('blocked', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
|
|
|
$platformReady = (string) ($context['region_status'] ?? '') === 'active'
|
|
|
&& $requiredCount >= 2
|
|
|
&& count(array_filter($requiredHosts,
|
|
|
static fn (array $host): bool =>
|
|
|
($host['platform_ready'] ?? false) !== true)) === 0;
|
|
|
if (!$platformReady) {
|
|
|
$addHostReasons();
|
|
|
if ($reasons === []) {
|
|
|
$addReason($reasons, 'platform_gate_failed');
|
|
|
}
|
|
|
return $withPreview(
|
|
|
$result('blocked', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
|
|
|
$freshProbeCount = count(array_filter($requiredHosts,
|
|
|
static fn (array $host): bool => isset(
|
|
|
$probes[(string) ($host['host_id'] ?? '')]
|
|
|
)));
|
|
|
$freshProbeComplete = $freshProbeCount === $requiredCount;
|
|
|
if ($freshProbeCount > 0 && !$freshProbeComplete) {
|
|
|
$addReason($reasons, 'probe_required');
|
|
|
$addHostReasons();
|
|
|
return $withPreview(
|
|
|
$result('needs_probe', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if ($freshProbeComplete) {
|
|
|
$freshEndpoints = [];
|
|
|
$freshReadyCount = 0;
|
|
|
foreach ($requiredHosts as $host) {
|
|
|
$probe = $probes[(string) ($host['host_id'] ?? '')] ?? null;
|
|
|
$endpoint = is_array($probe)
|
|
|
? ($probe['endpoint_ip'] ?? null) : null;
|
|
|
if (!is_array($probe)
|
|
|
|| ($probe['configured'] ?? false) !== true
|
|
|
|| ($probe['reachable'] ?? false) !== true
|
|
|
|| ($probe['vpc_ready'] ?? false) !== true
|
|
|
|| !is_string($endpoint) || $endpoint === ''
|
|
|
|| !in_array($probe['endpoint_source'] ?? null,
|
|
|
self::ENDPOINT_SOURCES, true)
|
|
|
|| ($probe['reasons'] ?? []) !== []) {
|
|
|
continue;
|
|
|
}
|
|
|
$endpointKey = $endpoint . ':' . self::FABRIC_LISTEN_PORT;
|
|
|
if (isset($freshEndpoints[$endpointKey])) {
|
|
|
continue;
|
|
|
}
|
|
|
$freshEndpoints[$endpointKey] = true;
|
|
|
$freshReadyCount++;
|
|
|
}
|
|
|
if ($freshReadyCount !== $requiredCount) {
|
|
|
$addHostReasons();
|
|
|
if ($reasons === []) {
|
|
|
$addReason($reasons, 'fresh_probe_failed');
|
|
|
}
|
|
|
return $withPreview(
|
|
|
$result('blocked', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// Without an explicit probe in this response, an exact active mapping
|
|
|
// may rely on bounded engine readback. Once a complete fresh probe is
|
|
|
// present, its failure has already failed closed above.
|
|
|
if ($mappedExact && $mappingState === 'active' && $ready) {
|
|
|
return $withPreview(
|
|
|
$result('active', false, true),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if ($mappedExact && $mappingState === 'active') {
|
|
|
$addReason($reasons, 'fabric_reconcile_required');
|
|
|
$addHostReasons();
|
|
|
return $withPreview(
|
|
|
$result('needs_reconcile', false, true),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
$terminalIdentityMatches = $mappedExact
|
|
|
|| (!$mappingConfigured && $desiredFabric !== null
|
|
|
&& (string) ($desiredFabric['region'] ?? '')
|
|
|
=== (string) ($context['region_code'] ?? '')
|
|
|
&& (int) ($desiredFabric['revision'] ?? 0) === 1);
|
|
|
$terminalDesiredReady = $freshProbeCount === 0
|
|
|
&& $desiredFabric !== null
|
|
|
&& ($desiredFabric['state'] ?? null) === 'active'
|
|
|
&& ($desiredFabric['next_stage_allowed'] ?? false) === true
|
|
|
&& $hostSetMatches
|
|
|
&& $terminalIdentityMatches
|
|
|
&& is_array($currentOperation)
|
|
|
&& is_string($currentOperation['id'] ?? null)
|
|
|
&& preg_match('/^[0-9a-f]{32}$/D', $currentOperation['id']) === 1
|
|
|
&& in_array($currentOperation['kind'] ?? null,
|
|
|
self::OPERATION_KINDS, true)
|
|
|
&& ($currentOperation['status'] ?? null) === 'succeeded';
|
|
|
$mappingNeedsConfirmation = !$mappingConfigured
|
|
|
|| ($mappedExact && $mappingState === 'disabled');
|
|
|
if ($terminalDesiredReady && $mappingNeedsConfirmation) {
|
|
|
// A read-only listing must not require a second browser probe
|
|
|
// after the asynchronous host write has already converged. The
|
|
|
// reconcile POST still performs its own fresh probe and exact
|
|
|
// plan validation before publishing the missing/disabled pin.
|
|
|
$addReason($reasons, 'fabric_reconcile_required');
|
|
|
return $withPreview(
|
|
|
$result('needs_reconcile', false, true),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if (!$freshProbeComplete) {
|
|
|
$addReason($reasons, 'probe_required');
|
|
|
return $withPreview(
|
|
|
$result('needs_probe', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
|
|
|
if ($desiredFabric !== null && !$mappingConfigured) {
|
|
|
try {
|
|
|
self::assertAutomaticFabricPlanMatches(
|
|
|
$desiredFabric, (string) $context['region_code'],
|
|
|
$context['hosts'], $probes, $fabrics
|
|
|
);
|
|
|
} catch (CloudError $exception) {
|
|
|
$addReason($reasons, 'fabric_plan_mismatch');
|
|
|
return $withPreview(
|
|
|
$result('migration_required', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
$addReason($reasons, 'fabric_reconcile_required');
|
|
|
return $withPreview(
|
|
|
$result('needs_reconcile', false, true),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
|
|
|
if ($mappedExact && $mappingState === 'disabled') {
|
|
|
$addReason($reasons, 'fabric_reconcile_required');
|
|
|
return $withPreview(
|
|
|
$result('needs_reconcile', false, true),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
if ($mappingConfigured) {
|
|
|
$addReason($reasons, 'fabric_plan_mismatch');
|
|
|
return $withPreview(
|
|
|
$result('recovery_required', false, false),
|
|
|
$existingPreview($desiredFabric)
|
|
|
);
|
|
|
}
|
|
|
|
|
|
try {
|
|
|
$overlay = self::automaticOverlay(
|
|
|
(string) $context['region_code'], $fabrics,
|
|
|
self::automaticFabricId((string) $context['region_code']),
|
|
|
array_values(array_filter(array_column($probes, 'endpoint_ip'),
|
|
|
static fn ($value): bool => is_string($value) && $value !== ''))
|
|
|
);
|
|
|
} catch (CloudError $exception) {
|
|
|
$addReason($reasons, 'fabric_plan_mismatch');
|
|
|
return $result('blocked', false, false);
|
|
|
}
|
|
|
return [[
|
|
|
'stage' => 'ready_to_apply',
|
|
|
'can_probe' => $canProbe,
|
|
|
'can_apply' => true,
|
|
|
'can_reconcile' => false,
|
|
|
'blocking_reasons' => [],
|
|
|
'action_mode' => 'apply',
|
|
|
], [
|
|
|
'mode' => 'automatic',
|
|
|
'fabric_id' => self::automaticFabricId(
|
|
|
(string) $context['region_code']),
|
|
|
'fabric_region' => (string) $context['region_code'],
|
|
|
'revision' => 1,
|
|
|
'listen_port' => self::FABRIC_LISTEN_PORT,
|
|
|
'overlay_cidr' => $overlay,
|
|
|
'host_count' => $requiredCount,
|
|
|
]];
|
|
|
}
|
|
|
|
|
|
private static function probeRows(array $payload, array $expectedHostIds): array
|
|
|
{
|
|
|
$items = $payload['hosts'] ?? null;
|
|
|
if (!is_array($items) || array_is_list($items) !== true
|
|
|
|| count($items) > self::MAX_FABRIC_NODES) {
|
|
|
throw new CloudError('宿主机检测响应无效,请稍后重试', 502);
|
|
|
}
|
|
|
$tenantPool = self::tenantPoolCidr();
|
|
|
$expected = array_fill_keys(array_map('strval', $expectedHostIds), true);
|
|
|
$result = [];
|
|
|
foreach ($items as $item) {
|
|
|
if (!is_array($item)) {
|
|
|
continue;
|
|
|
}
|
|
|
$hostId = (string) ($item['host_id'] ?? '');
|
|
|
if (!isset($expected[$hostId]) || isset($result[$hostId])) {
|
|
|
continue;
|
|
|
}
|
|
|
$reasons = [];
|
|
|
foreach (is_array($item['reasons'] ?? null)
|
|
|
? $item['reasons'] : [] as $reason) {
|
|
|
if (is_string($reason)
|
|
|
&& preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $reason) === 1) {
|
|
|
$reasons[] = $reason;
|
|
|
}
|
|
|
}
|
|
|
$error = $item['error_code'] ?? null;
|
|
|
if (is_string($error)
|
|
|
&& preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $error) === 1) {
|
|
|
$reasons[] = $error;
|
|
|
}
|
|
|
$region = $item['region'] ?? null;
|
|
|
if (!is_string($region) || strlen($region) > 64
|
|
|
|| preg_match('/[\x00-\x1f\x7f]/', $region) === 1) {
|
|
|
$region = '';
|
|
|
}
|
|
|
$endpoint = $item['endpoint_ip'] ?? null;
|
|
|
if (!is_string($endpoint)
|
|
|
|| filter_var($endpoint, FILTER_VALIDATE_IP,
|
|
|
FILTER_FLAG_IPV4) === false
|
|
|
|| !self::endpointAddressUsable($endpoint)) {
|
|
|
$endpoint = null;
|
|
|
}
|
|
|
$endpointSource = $item['endpoint_source'] ?? null;
|
|
|
if (!is_string($endpointSource)
|
|
|
|| !in_array($endpointSource, self::ENDPOINT_SOURCES, true)) {
|
|
|
$endpoint = null;
|
|
|
$endpointSource = null;
|
|
|
$reasons[] = 'fabric_endpoint_source_invalid';
|
|
|
} elseif ($endpoint === null) {
|
|
|
$endpointSource = null;
|
|
|
}
|
|
|
if ($endpoint !== null
|
|
|
&& self::containsAddress($tenantPool, $endpoint)) {
|
|
|
$reasons[] = 'fabric_endpoint_vpc_pool_conflict';
|
|
|
}
|
|
|
$capabilities = [];
|
|
|
$rawCapabilities = is_array($item['capabilities'] ?? null)
|
|
|
? $item['capabilities'] : [];
|
|
|
foreach (['os_id', 'os_version', 'network_manager',
|
|
|
'network_manager_expected', 'deployment_mode', 'firewall_manager',
|
|
|
'firewall_mode', 'underlay_interface', 'public_selector'] as $key) {
|
|
|
if (is_string($rawCapabilities[$key] ?? null)
|
|
|
&& strlen($rawCapabilities[$key]) <= 128
|
|
|
&& preg_match('/[\x00-\x1f\x7f]/', $rawCapabilities[$key]) !== 1) {
|
|
|
$capabilities[$key] = $rawCapabilities[$key];
|
|
|
}
|
|
|
}
|
|
|
foreach (['network_manager_supported', 'wireguard_ready',
|
|
|
'wireguard_owned', 'nftables_ready', 'nftables_active',
|
|
|
'nftables_persistent', 'public_verified'] as $key) {
|
|
|
if (is_bool($rawCapabilities[$key] ?? null)) {
|
|
|
$capabilities[$key] = $rawCapabilities[$key];
|
|
|
}
|
|
|
}
|
|
|
foreach (['ip_forward', 'rp_filter', 'rp_filter_all',
|
|
|
'rp_filter_default', 'rp_filter_default_effective',
|
|
|
'rp_filter_underlay_raw', 'rp_filter_underlay_effective',
|
|
|
'rp_filter_fabric_raw', 'rp_filter_fabric_effective'] as $key) {
|
|
|
if (is_int($rawCapabilities[$key] ?? null)
|
|
|
&& in_array($rawCapabilities[$key], [0, 1, 2], true)) {
|
|
|
$capabilities[$key] = $rawCapabilities[$key];
|
|
|
} elseif ($key !== 'ip_forward' && $key !== 'rp_filter'
|
|
|
&& array_key_exists($key, $rawCapabilities)
|
|
|
&& $rawCapabilities[$key] === null) {
|
|
|
// Explicit null means that the engine checked this bounded
|
|
|
// field but the interface/value does not exist yet. Keep
|
|
|
// that distinct from an older engine which omitted it.
|
|
|
$capabilities[$key] = null;
|
|
|
}
|
|
|
}
|
|
|
$nativeNftables = ($rawCapabilities['firewall_manager'] ?? null)
|
|
|
=== 'nftables'
|
|
|
&& ($rawCapabilities['firewall_mode'] ?? null)
|
|
|
=== 'native_nftables';
|
|
|
if (!$nativeNftables) {
|
|
|
$reasons[] = (($rawCapabilities['firewall_manager'] ?? null)
|
|
|
=== 'firewalld'
|
|
|
|| ($rawCapabilities['firewall_mode'] ?? null)
|
|
|
=== 'firewalld_nft')
|
|
|
? 'firewalld_unsupported_requires_maintenance'
|
|
|
: 'firewall_mode_unsupported';
|
|
|
}
|
|
|
$result[$hostId] = [
|
|
|
'configured' => ($item['configured'] ?? false) === true,
|
|
|
'reachable' => ($item['reachable'] ?? false) === true,
|
|
|
'region' => $region,
|
|
|
'endpoint_ip' => $endpoint,
|
|
|
'endpoint_source' => $endpointSource,
|
|
|
'probed_at' => max(0, (int) ($item['probed_at'] ?? time())),
|
|
|
'vpc_ready' => $nativeNftables
|
|
|
&& ($item['vpc_ready'] ?? false) === true,
|
|
|
'reasons' => array_values(array_unique($reasons)),
|
|
|
'capabilities' => $capabilities,
|
|
|
];
|
|
|
}
|
|
|
foreach (array_keys($expected) as $hostId) {
|
|
|
$result[$hostId] ??= [
|
|
|
'configured' => false, 'reachable' => false, 'region' => '',
|
|
|
'endpoint_ip' => null, 'endpoint_source' => null,
|
|
|
'probed_at' => time(),
|
|
|
'vpc_ready' => false,
|
|
|
'reasons' => ['host_capability_probe_missing'],
|
|
|
'capabilities' => [],
|
|
|
];
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
/** Return the immutable global tenant pool used by automatic VPC CIDRs. */
|
|
|
private static function tenantPoolCidr(): string
|
|
|
{
|
|
|
$model = new CloudPrivateCidrAllocatorConfig();
|
|
|
$schema = $model->getConnection()->getSchemaBuilder();
|
|
|
if (!$schema->hasTable($model->getTable())) {
|
|
|
throw new CloudError('私网 CIDR 分配器尚未初始化', 503);
|
|
|
}
|
|
|
$config = CloudPrivateCidrAllocatorConfig::where(
|
|
|
'id', CloudPrivateCidrAllocator::CONFIG_ID
|
|
|
)->first();
|
|
|
if ($config === null) {
|
|
|
throw new CloudError('私网 CIDR 分配器尚未初始化', 503);
|
|
|
}
|
|
|
$pool = CloudPrivateCidrAllocator::normalize(
|
|
|
(string) $config->pool_cidr
|
|
|
);
|
|
|
return (string) $pool['cidr'];
|
|
|
}
|
|
|
|
|
|
private static function assertConfigurableProbes(array $candidates,
|
|
|
array $probes, string $expectedRegion): array
|
|
|
{
|
|
|
$byHost = [];
|
|
|
$seenEndpoints = [];
|
|
|
foreach ($candidates as $candidate) {
|
|
|
$hostId = (string) $candidate['host_id'];
|
|
|
$probe = $probes[$hostId] ?? null;
|
|
|
if (!is_array($probe)
|
|
|
|| ($probe['configured'] ?? false) !== true
|
|
|
|| ($probe['reachable'] ?? false) !== true
|
|
|
|| ($probe['vpc_ready'] ?? false) !== true
|
|
|
|| ($probe['endpoint_ip'] ?? null) === null
|
|
|
|| !in_array($probe['endpoint_source'] ?? null,
|
|
|
self::ENDPOINT_SOURCES, true)
|
|
|
|| ($probe['reasons'] ?? []) !== []) {
|
|
|
throw new CloudError('地区仍有宿主机未通过 fresh readiness 检测', 409);
|
|
|
}
|
|
|
// Reuse the endpoint validator before a value reaches the plan.
|
|
|
$endpoint = self::endpoint(
|
|
|
$probe['endpoint_ip'] . ':' . self::FABRIC_LISTEN_PORT
|
|
|
);
|
|
|
if (isset($seenEndpoints[$endpoint])) {
|
|
|
throw new CloudError(
|
|
|
'地区宿主机的 WireGuard endpoint 重复,无法自动组网', 409
|
|
|
);
|
|
|
}
|
|
|
$seenEndpoints[$endpoint] = true;
|
|
|
$byHost[$hostId] = $probe;
|
|
|
}
|
|
|
return [$expectedRegion, $byHost];
|
|
|
}
|
|
|
|
|
|
private static function automaticFabricId(string $regionCode): string
|
|
|
{
|
|
|
$value = 'fabric-' . strtolower($regionCode);
|
|
|
return self::fabricId($value);
|
|
|
}
|
|
|
|
|
|
private static function automaticOverlay(string $regionCode,
|
|
|
array $fabrics, string $fabricId, array $excludedAddresses = []): string
|
|
|
{
|
|
|
$start = hexdec(substr(hash('sha256', $regionCode), 0, 8)) % 16384;
|
|
|
for ($offset = 0; $offset < 16384; $offset++) {
|
|
|
$slot = ($start + $offset) % 16384;
|
|
|
$candidate = '100.' . (64 + intdiv($slot, 256)) . '.'
|
|
|
. ($slot % 256) . '.0/24';
|
|
|
$conflict = false;
|
|
|
foreach ($excludedAddresses as $address) {
|
|
|
if (is_string($address)
|
|
|
&& filter_var($address, FILTER_VALIDATE_IP,
|
|
|
FILTER_FLAG_IPV4) !== false
|
|
|
&& self::containsAddress($candidate, $address)) {
|
|
|
$conflict = true;
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
foreach ($fabrics as $fabric) {
|
|
|
if ($conflict) {
|
|
|
break;
|
|
|
}
|
|
|
if ((string) ($fabric['fabric_id'] ?? '') === $fabricId) {
|
|
|
continue;
|
|
|
}
|
|
|
$other = (string) ($fabric['overlay_cidr'] ?? '');
|
|
|
if ($other !== '' && (self::containsAddress($other,
|
|
|
substr($candidate, 0, -3))
|
|
|
|| self::containsAddress($candidate,
|
|
|
explode('/', $other, 2)[0]))) {
|
|
|
$conflict = true;
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
if (!$conflict) {
|
|
|
return $candidate;
|
|
|
}
|
|
|
}
|
|
|
throw new CloudError('没有可用的 Fabric overlay /24 网段', 409);
|
|
|
}
|
|
|
|
|
|
private static function automaticNodes(array $candidates, array $probes,
|
|
|
string $overlay): array
|
|
|
{
|
|
|
usort($candidates, static fn (array $left, array $right): int =>
|
|
|
(int) $left['host_id'] <=> (int) $right['host_id']);
|
|
|
[$network] = explode('/', $overlay, 2);
|
|
|
$base = (int) sprintf('%u', ip2long($network));
|
|
|
$nodes = [];
|
|
|
foreach ($candidates as $index => $candidate) {
|
|
|
$hostId = (string) $candidate['host_id'];
|
|
|
$probe = $probes[$hostId];
|
|
|
$nodes[] = [
|
|
|
'host_id' => $hostId,
|
|
|
'overlay_ip' => long2ip($base + $index + 1),
|
|
|
'endpoint' => $probe['endpoint_ip'] . ':' . self::FABRIC_LISTEN_PORT,
|
|
|
'listen_port' => self::FABRIC_LISTEN_PORT,
|
|
|
];
|
|
|
}
|
|
|
return $nodes;
|
|
|
}
|
|
|
|
|
|
private static function assertFabricPlanEquals(array $fabric, array $plan,
|
|
|
string $message): void
|
|
|
{
|
|
|
$normalizeNodes = static function (array $nodes): array {
|
|
|
$result = [];
|
|
|
foreach ($nodes as $node) {
|
|
|
if (!is_array($node)) {
|
|
|
continue;
|
|
|
}
|
|
|
$result[] = [
|
|
|
'host_id' => (string) ($node['host_id'] ?? ''),
|
|
|
'overlay_ip' => (string) ($node['overlay_ip'] ?? ''),
|
|
|
'endpoint' => (string) ($node['endpoint'] ?? ''),
|
|
|
'listen_port' => (int) ($node['listen_port'] ?? 0),
|
|
|
];
|
|
|
}
|
|
|
usort($result, static fn (array $left, array $right): int =>
|
|
|
strcmp($left['host_id'], $right['host_id']));
|
|
|
return $result;
|
|
|
};
|
|
|
if ((string) ($fabric['fabric_id'] ?? '')
|
|
|
!== (string) ($plan['fabric_id'] ?? '')
|
|
|
|| (string) ($fabric['region'] ?? '')
|
|
|
!== (string) ($plan['region'] ?? '')
|
|
|
|| (string) ($fabric['overlay_cidr'] ?? '')
|
|
|
!== (string) ($plan['overlay_cidr'] ?? '')
|
|
|
|| (int) ($fabric['revision'] ?? 0)
|
|
|
!== (int) ($plan['revision'] ?? 0)
|
|
|
|| (int) ($fabric['listen_port'] ?? 0)
|
|
|
!== (int) ($plan['listen_port'] ?? 0)
|
|
|
|| $normalizeNodes($fabric['nodes'] ?? [])
|
|
|
!== $normalizeNodes($plan['nodes'] ?? [])) {
|
|
|
throw new CloudError($message, 409);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Prove that an unmapped deterministic record is exactly the plan this
|
|
|
* workflow would have generated. This is the ownership evidence used to
|
|
|
* recover a lost HTTP/DB response; matching only its friendly ID would be
|
|
|
* insufficient.
|
|
|
*/
|
|
|
private static function assertAutomaticFabricPlanMatches(array $fabric,
|
|
|
string $regionCode, array $candidates, array $probes,
|
|
|
array $fabrics): void
|
|
|
{
|
|
|
$fabricId = self::automaticFabricId($regionCode);
|
|
|
$overlay = self::automaticOverlay(
|
|
|
$regionCode, $fabrics, $fabricId,
|
|
|
array_column($probes, 'endpoint_ip')
|
|
|
);
|
|
|
self::assertFabricPlanEquals($fabric, [
|
|
|
'fabric_id' => $fabricId,
|
|
|
'region' => $regionCode,
|
|
|
'overlay_cidr' => $overlay,
|
|
|
'revision' => 1,
|
|
|
'listen_port' => self::FABRIC_LISTEN_PORT,
|
|
|
'nodes' => self::automaticNodes($candidates, $probes, $overlay),
|
|
|
], '未映射的 Fabric 与平台自动计划不一致,已阻止接管');
|
|
|
}
|
|
|
|
|
|
private static function fabricById(array $fabrics, string $fabricId): ?array
|
|
|
{
|
|
|
foreach ($fabrics as $fabric) {
|
|
|
if ((string) ($fabric['fabric_id'] ?? '') === $fabricId) {
|
|
|
return $fabric;
|
|
|
}
|
|
|
}
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
private static function assertExistingFabricMatches(array $fabric,
|
|
|
string $region, array $hostIds, ?int $revision): void
|
|
|
{
|
|
|
if ((string) ($fabric['region'] ?? '') !== $region
|
|
|
|| ($revision !== null
|
|
|
&& (int) ($fabric['revision'] ?? 0) !== $revision)) {
|
|
|
throw new CloudError('既有 Fabric 的地区或版本与平台固定值不一致', 409);
|
|
|
}
|
|
|
$expected = array_map('strval', $hostIds);
|
|
|
sort($expected, SORT_STRING);
|
|
|
$actual = [];
|
|
|
foreach (($fabric['nodes'] ?? []) as $node) {
|
|
|
$actual[] = (string) ($node['host_id'] ?? '');
|
|
|
}
|
|
|
sort($actual, SORT_STRING);
|
|
|
if ($expected !== $actual) {
|
|
|
throw new CloudError('地区宿主机集合已变化,需要显式迁移,不能自动覆盖', 409);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function findReadinessRegion(array $rows, int $regionId): array
|
|
|
{
|
|
|
foreach ($rows as $row) {
|
|
|
if ((int) ($row['region_id'] ?? 0) === $regionId) {
|
|
|
return $row;
|
|
|
}
|
|
|
}
|
|
|
throw new CloudError('地区 readiness 投影不可用', 503);
|
|
|
}
|
|
|
|
|
|
private static function assertReadActor(array $actor): void
|
|
|
{
|
|
|
if (!($actor['is_admin'] ?? false)) {
|
|
|
throw new CloudError('需要管理员权限', 403);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function assertWriteActor(array $actor): void
|
|
|
{
|
|
|
if (!($actor['is_admin'] ?? false)
|
|
|
|| !($actor['is_super_admin'] ?? false)
|
|
|
|| !($actor['can_manage'] ?? false)) {
|
|
|
throw new CloudError('仅超级管理员可以修改 Fabric', 403);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function fabricId($value): string
|
|
|
{
|
|
|
if (!is_string($value) || preg_match(self::FABRIC_ID, $value) !== 1) {
|
|
|
throw new CloudError('Fabric 标识无效', 422);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
/** Validate the exact engine plan vocabulary before forwarding it. */
|
|
|
private static function plan(array $body): array
|
|
|
{
|
|
|
CloudInput::only($body, [
|
|
|
'schema_version', 'fabric_id', 'region', 'overlay_cidr',
|
|
|
'revision', 'listen_port', 'nodes',
|
|
|
]);
|
|
|
if (($body['schema_version'] ?? 1) !== 1) {
|
|
|
throw new CloudError('Fabric 计划版本不支持', 422);
|
|
|
}
|
|
|
$fabricId = self::fabricId($body['fabric_id'] ?? null);
|
|
|
$region = self::safeText($body['region'] ?? null, 'Fabric 地区', 64);
|
|
|
$network = self::network($body['overlay_cidr'] ?? null);
|
|
|
$revision = self::positiveInt($body['revision'] ?? null, 'Fabric 版本');
|
|
|
$listenPort = self::port($body['listen_port'] ?? 51820);
|
|
|
$nodes = $body['nodes'] ?? null;
|
|
|
if (!is_array($nodes) || array_is_list($nodes) !== true
|
|
|
|| count($nodes) < 2 || count($nodes) > 64) {
|
|
|
throw new CloudError('Fabric 至少需要两个且最多支持 64 个宿主机', 422);
|
|
|
}
|
|
|
$seenHosts = [];
|
|
|
$seenIps = [];
|
|
|
$seenEndpoints = [];
|
|
|
$normalized = [];
|
|
|
foreach ($nodes as $node) {
|
|
|
if (!is_array($node)) {
|
|
|
throw new CloudError('Fabric 节点字段无效', 422);
|
|
|
}
|
|
|
CloudInput::only($node, ['host_id', 'overlay_ip', 'endpoint', 'listen_port']);
|
|
|
$hostId = $node['host_id'] ?? null;
|
|
|
if (!is_string($hostId) || preg_match(self::HOST_ID, $hostId) !== 1
|
|
|
|| isset($seenHosts[$hostId])) {
|
|
|
throw new CloudError('Fabric 宿主机标识无效或重复', 422);
|
|
|
}
|
|
|
$overlayIp = self::ipv4($node['overlay_ip'] ?? null, 'Fabric overlay 地址');
|
|
|
if (isset($seenIps[$overlayIp])) {
|
|
|
throw new CloudError('Fabric overlay 地址不能重复', 422);
|
|
|
}
|
|
|
if (!self::containsHost($network, $overlayIp)) {
|
|
|
throw new CloudError('Fabric overlay 地址必须位于 overlay CIDR 内', 422);
|
|
|
}
|
|
|
$endpoint = self::endpoint($node['endpoint'] ?? null);
|
|
|
if (isset($seenEndpoints[$endpoint])) {
|
|
|
throw new CloudError('WireGuard endpoint 不能重复', 422);
|
|
|
}
|
|
|
[$endpointIp] = explode(':', $endpoint, 2);
|
|
|
if (self::containsAddress($network, $endpointIp)) {
|
|
|
throw new CloudError('WireGuard endpoint 不能位于 Fabric overlay 网段', 422);
|
|
|
}
|
|
|
$nodePort = self::port($node['listen_port'] ?? $listenPort);
|
|
|
$seenHosts[$hostId] = true;
|
|
|
$seenIps[$overlayIp] = true;
|
|
|
$seenEndpoints[$endpoint] = true;
|
|
|
$normalized[] = [
|
|
|
'host_id' => $hostId,
|
|
|
'overlay_ip' => $overlayIp,
|
|
|
'endpoint' => $endpoint,
|
|
|
'listen_port' => $nodePort,
|
|
|
];
|
|
|
}
|
|
|
usort($normalized, static fn (array $a, array $b): int =>
|
|
|
strcmp($a['host_id'], $b['host_id']));
|
|
|
return [
|
|
|
'schema_version' => 1,
|
|
|
'fabric_id' => $fabricId,
|
|
|
'region' => $region,
|
|
|
'overlay_cidr' => $network,
|
|
|
'revision' => $revision,
|
|
|
'listen_port' => $listenPort,
|
|
|
'nodes' => $normalized,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function project(array $value, array $hostNames): array
|
|
|
{
|
|
|
$fabricId = self::fabricId($value['fabric_id'] ?? null);
|
|
|
$region = self::safeText($value['region'] ?? null, 'Fabric 地区', 64);
|
|
|
$overlay = self::network($value['overlay_cidr'] ?? null);
|
|
|
$revision = self::positiveInt($value['revision'] ?? null, 'Fabric 版本');
|
|
|
$state = self::choice($value['state'] ?? null, self::STATES, 'Fabric 状态');
|
|
|
$result = [
|
|
|
'fabric_id' => $fabricId,
|
|
|
'region' => $region,
|
|
|
'overlay_cidr' => $overlay,
|
|
|
'revision' => $revision,
|
|
|
'listen_port' => self::port($value['listen_port'] ?? 51820),
|
|
|
'plan_digest' => self::digest($value['plan_digest'] ?? null),
|
|
|
'interface' => self::safeText($value['interface'] ?? 'wg-fabric0', 'Fabric 网卡', 32),
|
|
|
'state' => $state,
|
|
|
'next_stage_allowed' => ($value['next_stage_allowed'] ?? false) === true,
|
|
|
'updated_at' => max(0, (int) ($value['updated_at'] ?? 0)),
|
|
|
'operation' => self::operation($value['operation'] ?? null, false),
|
|
|
'nodes' => [],
|
|
|
];
|
|
|
$nodes = $value['nodes'] ?? [];
|
|
|
if (!is_array($nodes) || count($nodes) > 64) {
|
|
|
throw new CloudError('Fabric 节点状态无效', 502);
|
|
|
}
|
|
|
foreach ($nodes as $node) {
|
|
|
if (!is_array($node)) {
|
|
|
continue;
|
|
|
}
|
|
|
$hostId = self::safeText($node['host_id'] ?? null, '宿主机标识', 64);
|
|
|
$lastErrorCode = self::errorCode($node['last_error_code'] ?? null);
|
|
|
$lastErrorPhase = self::errorPhase($node['last_error_phase'] ?? null);
|
|
|
if ($lastErrorPhase !== null && $lastErrorCode === null) {
|
|
|
throw new CloudError('Fabric 失败阶段缺少对应错误代码', 502);
|
|
|
}
|
|
|
$row = [
|
|
|
'host_id' => $hostId,
|
|
|
'host_name' => $hostNames[$hostId]['name'] ?? null,
|
|
|
'host_region' => $hostNames[$hostId]['region'] ?? null,
|
|
|
'overlay_ip' => self::ipv4($node['overlay_ip'] ?? null, 'Fabric overlay 地址'),
|
|
|
'endpoint' => self::endpoint($node['endpoint'] ?? null),
|
|
|
'listen_port' => self::port($node['listen_port'] ?? 51820),
|
|
|
'public_key' => self::key($node['public_key'] ?? null),
|
|
|
'state' => self::choice($node['state'] ?? null, self::STATES, 'Fabric 节点状态'),
|
|
|
'transport_verified' => ($node['transport_verified'] ?? false) === true,
|
|
|
'observed_revision' => max(0, (int) ($node['observed_revision'] ?? 0)),
|
|
|
'observed_plan_digest' => self::nullableDigest($node['observed_plan_digest'] ?? null),
|
|
|
'last_error_code' => $lastErrorCode,
|
|
|
'last_error_phase' => $lastErrorPhase,
|
|
|
'operation' => self::operation(
|
|
|
$node['operation'] ?? null, true
|
|
|
),
|
|
|
'observed' => self::observed($node['observed'] ?? []),
|
|
|
];
|
|
|
$result['nodes'][] = $row;
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
private static function observed($value): array
|
|
|
{
|
|
|
if (!is_array($value)) {
|
|
|
return [];
|
|
|
}
|
|
|
$result = [];
|
|
|
foreach ([
|
|
|
'owner', 'config_fabric', 'config_revision', 'config_digest',
|
|
|
'config_network', 'config_overlay', 'config_ok', 'interface',
|
|
|
'listen_port', 'enabled', 'service_active', 'timer_enabled',
|
|
|
'timer_active', 'nft_guard', 'key_secure', 'nft_persistence',
|
|
|
'config_secure', 'helper_marker', 'unit_marker', 'repair_marker',
|
|
|
'timer_marker', 'manager_mode', 'manager_owner', 'manager_active',
|
|
|
'admin_state', 'vpc_state', 'peer_allowed_exact', 'vpc_nft_state',
|
|
|
'vpc_nft_exact',
|
|
|
] as $key) {
|
|
|
if (array_key_exists($key, $value)) {
|
|
|
$item = $value[$key];
|
|
|
$result[$key] = is_string($item)
|
|
|
? substr($item, 0, 128)
|
|
|
: (is_scalar($item) ? $item : null);
|
|
|
}
|
|
|
}
|
|
|
foreach ([
|
|
|
'addresses', 'routes', 'paths', 'pings', 'endpoint_paths',
|
|
|
'config_routes', 'route_overlaps', 'vpc_tenants', 'vpc_nft_ips',
|
|
|
] as $key) {
|
|
|
if (!is_array($value[$key] ?? null)) {
|
|
|
continue;
|
|
|
}
|
|
|
$result[$key] = array_values(array_filter(
|
|
|
array_map(static fn ($item): ?string => is_string($item)
|
|
|
? substr($item, 0, 128) : null, $value[$key]),
|
|
|
static fn ($item): bool => $item !== null
|
|
|
));
|
|
|
}
|
|
|
foreach (['sysctls', 'rp_filters'] as $key) {
|
|
|
if (!is_array($value[$key] ?? null)) {
|
|
|
continue;
|
|
|
}
|
|
|
$result[$key] = [];
|
|
|
foreach ($value[$key] as $name => $item) {
|
|
|
if (is_string($name) && strlen($name) <= 64
|
|
|
&& in_array((string) $item, ['0', '1', '2', 'unknown'], true)) {
|
|
|
$result[$key][$name] = (string) $item;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
foreach (['config_peers', 'peers', 'overlay_peers'] as $key) {
|
|
|
if (!is_array($value[$key] ?? null)) {
|
|
|
continue;
|
|
|
}
|
|
|
$result[$key] = [];
|
|
|
foreach ($value[$key] as $item) {
|
|
|
if (!is_array($item) || count($item) !== 3) {
|
|
|
continue;
|
|
|
}
|
|
|
$result[$key][] = array_map(static fn ($part): string =>
|
|
|
substr((string) $part, 0, 128), array_values($item));
|
|
|
}
|
|
|
}
|
|
|
if (is_array($value['handshakes'] ?? null)) {
|
|
|
$result['handshakes'] = [];
|
|
|
foreach ($value['handshakes'] as $key => $stamp) {
|
|
|
if (is_string($key) && strlen($key) <= 128 && is_numeric($stamp)) {
|
|
|
$result['handshakes'][$key] = (int) $stamp;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
private static function mappings(array $fabrics): array
|
|
|
{
|
|
|
$connection = (new CloudRegionFabric())->getConnection();
|
|
|
if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
|
|
|
return [];
|
|
|
}
|
|
|
$regions = CloudRegion::orderBy('id')->get();
|
|
|
$byFabric = [];
|
|
|
foreach ($fabrics as $fabric) {
|
|
|
$byFabric[(string) $fabric['fabric_id']] = $fabric;
|
|
|
}
|
|
|
$fabricRows = CloudRegionFabric::get()->keyBy('region_id');
|
|
|
$rows = [];
|
|
|
foreach ($regions as $region) {
|
|
|
$row = $fabricRows[(int) $region->id] ?? null;
|
|
|
if ($row === null) {
|
|
|
$rows[] = self::unconfiguredMapping($region);
|
|
|
continue;
|
|
|
}
|
|
|
$fabric = $byFabric[(string) $row->fabric_id] ?? null;
|
|
|
$rows[] = self::mappingRow($row, $region, $fabric);
|
|
|
}
|
|
|
return $rows;
|
|
|
}
|
|
|
|
|
|
private static function mappingForFabric(string $fabricId): ?array
|
|
|
{
|
|
|
$connection = (new CloudRegionFabric())->getConnection();
|
|
|
if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
|
|
|
return null;
|
|
|
}
|
|
|
$row = CloudRegionFabric::where('fabric_id', $fabricId)->first();
|
|
|
if ($row === null) {
|
|
|
return null;
|
|
|
}
|
|
|
$region = CloudRegion::find((int) $row->region_id);
|
|
|
return self::mappingRow($row, $region, null);
|
|
|
}
|
|
|
|
|
|
private static function mappingRow($row, $region, ?array $fabric): array
|
|
|
{
|
|
|
return [
|
|
|
'region_id' => (int) $row->region_id,
|
|
|
'region_code' => (string) ($region->code ?? ''),
|
|
|
'region_name' => (string) ($region->name ?? ''),
|
|
|
'region_status' => (string) ($region->status ?? 'disabled'),
|
|
|
'fabric_id' => (string) $row->fabric_id,
|
|
|
'fabric_region' => (string) $row->fabric_region,
|
|
|
'fabric_revision' => (int) $row->fabric_revision,
|
|
|
'state' => (string) $row->state,
|
|
|
'engine_state' => is_array($fabric) ? ($fabric['state'] ?? null) : null,
|
|
|
'engine_revision' => is_array($fabric) ? ($fabric['revision'] ?? null) : null,
|
|
|
'next_stage_allowed' => is_array($fabric)
|
|
|
? ($fabric['next_stage_allowed'] ?? false) : false,
|
|
|
'updated_at' => (int) $row->updated_at,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function unconfiguredMapping($region): array
|
|
|
{
|
|
|
return [
|
|
|
'region_id' => (int) ($region->id ?? 0),
|
|
|
'region_code' => (string) ($region->code ?? ''),
|
|
|
'region_name' => (string) ($region->name ?? ''),
|
|
|
'region_status' => (string) ($region->status ?? 'disabled'),
|
|
|
'fabric_id' => null,
|
|
|
'fabric_region' => null,
|
|
|
'fabric_revision' => null,
|
|
|
'state' => 'unconfigured',
|
|
|
'engine_state' => null,
|
|
|
'engine_revision' => null,
|
|
|
'next_stage_allowed' => false,
|
|
|
'updated_at' => null,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function hostNames(array $fabrics): array
|
|
|
{
|
|
|
$ids = [];
|
|
|
foreach ($fabrics as $fabric) {
|
|
|
foreach (($fabric['nodes'] ?? []) as $node) {
|
|
|
$id = is_array($node) ? (string) ($node['host_id'] ?? '') : '';
|
|
|
if (ctype_digit($id) && (int) $id > 0) {
|
|
|
$ids[(int) $id] = true;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
if ($ids === []) {
|
|
|
return [];
|
|
|
}
|
|
|
$result = [];
|
|
|
foreach (CloudHost::whereIn('id', array_keys($ids))->get() as $host) {
|
|
|
$result[(string) $host->id] = [
|
|
|
'name' => (string) $host->name,
|
|
|
'region' => (string) $host->region,
|
|
|
];
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
private static function network($value): string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
throw new CloudError('Fabric overlay CIDR 无效', 422);
|
|
|
}
|
|
|
[$ip, $prefix] = array_pad(explode('/', trim($value), 2), 2, null);
|
|
|
$prefix = filter_var($prefix, FILTER_VALIDATE_INT);
|
|
|
if ($prefix === false || $prefix < 10 || $prefix > 24
|
|
|
|| self::ipv4($ip, 'Fabric overlay CIDR') !== $ip) {
|
|
|
throw new CloudError('Fabric overlay CIDR 无效', 422);
|
|
|
}
|
|
|
$parts = array_map('intval', explode('.', $ip));
|
|
|
if ($parts[0] !== 100 || $parts[1] < 64 || $parts[1] > 127) {
|
|
|
throw new CloudError('Fabric overlay 必须位于 100.64.0.0/10 内', 422);
|
|
|
}
|
|
|
$mask = $prefix === 0 ? 0 : (0xffffffff << (32 - $prefix)) & 0xffffffff;
|
|
|
$number = (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
|
|
|
if (($number & $mask) !== $number) {
|
|
|
throw new CloudError('Fabric overlay CIDR 必须使用规范网络地址', 422);
|
|
|
}
|
|
|
return $ip . '/' . $prefix;
|
|
|
}
|
|
|
|
|
|
private static function containsHost(string $network, string $ip): bool
|
|
|
{
|
|
|
if (!self::containsAddress($network, $ip)) {
|
|
|
return false;
|
|
|
}
|
|
|
[$base, $prefix] = explode('/', $network);
|
|
|
$toInt = static function (string $value): int {
|
|
|
$parts = array_map('intval', explode('.', $value));
|
|
|
return (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
|
|
|
};
|
|
|
$mask = (0xffffffff << (32 - (int) $prefix)) & 0xffffffff;
|
|
|
$value = $toInt($ip);
|
|
|
$baseValue = $toInt($base);
|
|
|
return (($value & $mask) === $baseValue) && $value !== $baseValue
|
|
|
&& $value !== ($baseValue | ((1 << (32 - (int) $prefix)) - 1));
|
|
|
}
|
|
|
|
|
|
private static function containsAddress(string $network, string $ip): bool
|
|
|
{
|
|
|
[$base, $prefix] = explode('/', $network);
|
|
|
$toInt = static function (string $value): int {
|
|
|
$parts = array_map('intval', explode('.', $value));
|
|
|
return (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
|
|
|
};
|
|
|
$mask = (0xffffffff << (32 - (int) $prefix)) & 0xffffffff;
|
|
|
return (($toInt($ip) & $mask) === $toInt($base));
|
|
|
}
|
|
|
|
|
|
private static function ipv4($value, string $label): string
|
|
|
{
|
|
|
if (!is_string($value) || filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
|
|
|
throw new CloudError($label . '无效', 422);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function endpoint($value): string
|
|
|
{
|
|
|
if (!is_string($value) || substr_count($value, ':') !== 1) {
|
|
|
throw new CloudError('WireGuard endpoint 无效', 422);
|
|
|
}
|
|
|
[$ip, $port] = explode(':', $value, 2);
|
|
|
$ip = self::ipv4($ip, 'WireGuard endpoint 地址');
|
|
|
if (!self::endpointAddressUsable($ip)) {
|
|
|
throw new CloudError('WireGuard endpoint 地址不可路由', 422);
|
|
|
}
|
|
|
$port = self::port($port);
|
|
|
return $ip . ':' . $port;
|
|
|
}
|
|
|
|
|
|
private static function endpointAddressUsable(string $ip): bool
|
|
|
{
|
|
|
$parts = array_map('intval', explode('.', $ip));
|
|
|
return count($parts) === 4
|
|
|
&& $parts[0] !== 0
|
|
|
&& $parts[0] !== 127
|
|
|
&& $parts[0] < 224
|
|
|
&& !($parts[0] === 169 && $parts[1] === 254);
|
|
|
}
|
|
|
|
|
|
private static function port($value): int
|
|
|
{
|
|
|
if (is_string($value) && ctype_digit($value)) {
|
|
|
$value = (int) $value;
|
|
|
}
|
|
|
if (is_bool($value) || !is_int($value) || $value < 1 || $value > 65535) {
|
|
|
throw new CloudError('WireGuard 端口无效', 422);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function positiveInt($value, string $label): int
|
|
|
{
|
|
|
if (is_string($value) && ctype_digit($value)) {
|
|
|
$value = (int) $value;
|
|
|
}
|
|
|
if (is_bool($value) || !is_int($value) || $value < 1 || $value > 9223372036854775807) {
|
|
|
throw new CloudError($label . '无效', 422);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function safeText($value, string $label, int $maximum): string
|
|
|
{
|
|
|
if (!is_string($value) || $value === '' || strlen($value) > $maximum
|
|
|
|| trim($value) !== $value || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) {
|
|
|
throw new CloudError($label . '无效', 422);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function choice($value, array $choices, string $label): string
|
|
|
{
|
|
|
if (!is_string($value) || !in_array($value, $choices, true)) {
|
|
|
throw new CloudError($label . '无效', 502);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function key($value): ?string
|
|
|
{
|
|
|
if ($value === null) {
|
|
|
return null;
|
|
|
}
|
|
|
if (!is_string($value) || preg_match(self::KEY, $value) !== 1) {
|
|
|
throw new CloudError('Fabric 公钥回读无效', 502);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function digest($value): ?string
|
|
|
{
|
|
|
if ($value === null || $value === '') {
|
|
|
return null;
|
|
|
}
|
|
|
if (!is_string($value) || preg_match('/^[0-9a-f]{64}$/D', $value) !== 1) {
|
|
|
throw new CloudError('Fabric 摘要回读无效', 502);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function nullableDigest($value): ?string
|
|
|
{
|
|
|
return $value === null || $value === '' ? null : self::digest($value);
|
|
|
}
|
|
|
|
|
|
private static function errorCode($value): ?string
|
|
|
{
|
|
|
if ($value === null || $value === '') {
|
|
|
return null;
|
|
|
}
|
|
|
if (!is_string($value) || !in_array($value, self::ERROR_CODES, true)) {
|
|
|
return 'fabric_readback_invalid';
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function errorPhase($value): ?string
|
|
|
{
|
|
|
if ($value === null || $value === '') {
|
|
|
return null;
|
|
|
}
|
|
|
if (!is_string($value) || !in_array($value, self::ERROR_PHASES, true)) {
|
|
|
throw new CloudError('Fabric 失败阶段回读无效', 502);
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Project only the fixed, credential-free operation receipt contract.
|
|
|
* Unknown enum values become the literal "unknown" marker; arbitrary
|
|
|
* Engine strings never cross into the administrator response.
|
|
|
*/
|
|
|
private static function operation($value, bool $node): ?array
|
|
|
{
|
|
|
if ($value === null || $value === '') {
|
|
|
return null;
|
|
|
}
|
|
|
if (!is_array($value)) {
|
|
|
$result = [
|
|
|
'id' => null,
|
|
|
'status' => 'unknown',
|
|
|
'started_at' => null, 'updated_at' => null,
|
|
|
'finished_at' => null,
|
|
|
];
|
|
|
if ($node) {
|
|
|
$result += [
|
|
|
'phase' => 'unknown', 'checkpoint' => 'unknown',
|
|
|
'reason' => 'unknown',
|
|
|
];
|
|
|
} else {
|
|
|
$result['kind'] = 'unknown';
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
$id = $value['id'] ?? null;
|
|
|
if (!is_string($id)
|
|
|
|| preg_match('/^[0-9a-f]{32}$/D', $id) !== 1) {
|
|
|
$id = null;
|
|
|
}
|
|
|
$statuses = $node
|
|
|
? self::NODE_OPERATION_STATES : self::OPERATION_STATES;
|
|
|
$status = is_string($value['status'] ?? null)
|
|
|
&& in_array($value['status'], $statuses, true)
|
|
|
? $value['status'] : 'unknown';
|
|
|
$result = [
|
|
|
'id' => $id,
|
|
|
'status' => $status,
|
|
|
'started_at' => self::operationTime($value['started_at'] ?? null),
|
|
|
'updated_at' => self::operationTime($value['updated_at'] ?? null),
|
|
|
'finished_at' => self::operationTime($value['finished_at'] ?? null),
|
|
|
];
|
|
|
if (!$node) {
|
|
|
$result['kind'] = is_string($value['kind'] ?? null)
|
|
|
&& in_array($value['kind'], self::OPERATION_KINDS, true)
|
|
|
? $value['kind'] : 'unknown';
|
|
|
return $result;
|
|
|
}
|
|
|
$result['phase'] = is_string($value['phase'] ?? null)
|
|
|
&& in_array($value['phase'], self::ERROR_PHASES, true)
|
|
|
? $value['phase'] : 'unknown';
|
|
|
$result['checkpoint'] = is_string($value['checkpoint'] ?? null)
|
|
|
&& in_array($value['checkpoint'], self::OPERATION_CHECKPOINTS, true)
|
|
|
? $value['checkpoint'] : 'unknown';
|
|
|
$result['reason'] = is_string($value['reason'] ?? null)
|
|
|
&& in_array($value['reason'], self::OPERATION_REASONS, true)
|
|
|
? $value['reason'] : 'unknown';
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
private static function operationTime($value): ?int
|
|
|
{
|
|
|
return is_int($value) && $value > 0 ? $value : null;
|
|
|
}
|
|
|
}
|