feat: provision dual-stack public networks

go
codex 3 weeks ago
parent cb8260ab56
commit c0ee66f369

@ -28,7 +28,10 @@ final class CloudResourceReservation extends Model
'updated_at' => 'int',
];
/** Every reservation carries a complete immutable network allocation. */
/**
* Address ownership lives in cloud_resource_reservation_ips. The legacy
* singular columns remain schema-only until the final clean-break cleanup.
*/
public function save(array $options = [])
{
if (!$this->exists) {
@ -41,15 +44,15 @@ final class CloudResourceReservation extends Model
'New reservations require exactly one order or backup restore source.'
);
}
foreach (['network_attachment_id', 'public_ip_pool_id',
'public_ip_id'] as $field) {
if ((int) ($this->{$field} ?? 0) < 1) {
throw new \LogicException(
'New reservations require complete network allocation references.'
);
}
}
}
return parent::save($options);
}
public function publicIpClaims()
{
return $this->hasMany(
CloudResourceReservationIp::class,
'reservation_id'
);
}
}

@ -16,6 +16,102 @@ use App\Models\CloudResourceReservation;
*/
final class CloudInstanceMigrationSettlement
{
/**
* Lock the exact maintenance-migration evidence that accounts for a
* stopped source duplicate on one host.
*
* The caller already owns the host and public-pool locks. Migration rows
* are locked before their restore reservations, matching every migration
* finalizer before the allocator later locks concrete IP rows.
*
* @param list<int> $candidatePoolIds
* @return array<int,array{migration_id:int,migration_state:string,
* reservation_id:int,host_id:int,network_attachment_id:int,
* public_ip_pool_id:int,public_ip_id:int,operation_id:string}>
*/
public static function lockRetainedSourcePublicIpEvidence(
int $hostId,
array $candidatePoolIds
): array {
$candidatePoolIds = array_values(array_unique(array_map(
static fn ($id): int => (int) $id,
$candidatePoolIds
)));
sort($candidatePoolIds, SORT_NUMERIC);
if ($hostId < 1 || $candidatePoolIds === []
|| $candidatePoolIds[0] < 1) {
throw new CloudError('保留源副本公网账本范围无效', 409);
}
$migrations = CloudInstanceMigration::where('source_host_id', $hostId)
->whereIn('state', ['source_retained', 'cleanup_running'])
->orderBy('id')->lockForUpdate()->get();
if ($migrations->isEmpty()) {
return [];
}
$reservationIds = $migrations->pluck('source_reservation_id')->map(
static fn ($id): int => (int) $id
)->unique()->sort()->values()->all();
if ($reservationIds === [] || $reservationIds[0] < 1) {
throw new CloudError('保留源副本缺少资源预留证据', 409);
}
$reservations = CloudResourceReservation::whereIn('id', $reservationIds)
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
if ($reservations->count() !== count($reservationIds)) {
throw new CloudError('保留源副本资源预留证据不完整', 409);
}
$candidatePools = array_fill_keys($candidatePoolIds, true);
$evidence = [];
foreach ($migrations as $migration) {
$reservationId = (int) $migration->source_reservation_id;
$reservation = $reservations->get($reservationId);
$operationId = (string) ($reservation?->operation_id ?? '');
if (!$reservation instanceof CloudResourceReservation
|| (int) $migration->instance_id < 1
|| (int) $migration->restore_id < 1
|| (int) $migration->source_host_id !== $hostId
|| (int) $migration->target_host_id < 1
|| (int) $migration->target_reservation_id < 1
|| (int) $reservation->host_id !== $hostId
|| (int) ($reservation->backup_restore_id ?? 0)
!== (int) $migration->restore_id
|| $reservation->order_id !== null
|| (string) $reservation->state !== 'committed'
|| $reservation->instance_id !== null
|| (int) ($reservation->network_attachment_id ?? 0) < 1
|| (int) ($reservation->public_ip_pool_id ?? 0) < 1
|| (int) ($reservation->public_ip_id ?? 0) < 1
|| preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) {
throw new CloudError(
'保留源副本迁移与资源预留证据不一致',
409
);
}
$poolId = (int) $reservation->public_ip_pool_id;
if (!isset($candidatePools[$poolId])) {
continue;
}
$publicIpId = (int) $reservation->public_ip_id;
if (isset($evidence[$publicIpId])) {
throw new CloudError('保留源副本公网地址证据重复', 409);
}
$evidence[$publicIpId] = [
'migration_id' => (int) $migration->id,
'migration_state' => (string) $migration->state,
'reservation_id' => $reservationId,
'host_id' => (int) $reservation->host_id,
'network_attachment_id' =>
(int) $reservation->network_attachment_id,
'public_ip_pool_id' => $poolId,
'public_ip_id' => $publicIpId,
'operation_id' => $operationId,
];
}
ksort($evidence, SORT_NUMERIC);
return $evidence;
}
/**
* Make the order-linked reservation authoritative on the target while a
* separate restore reservation accounts for the stopped source duplicate.

@ -657,8 +657,13 @@ final class CloudInvoiceService
} else {
$spec = json_decode((string) $instance->spec_json, true);
$spec = is_array($spec) && !array_is_list($spec) ? $spec : [];
$cidr = is_string($spec['public_ip_cidr'] ?? null)
? trim($spec['public_ip_cidr']) : '';
try {
$cidr = CloudPublicNetworkSnapshot::fromArray(
$spec['public_network'] ?? null
)->address(4);
} catch (\InvalidArgumentException) {
$cidr = '';
}
$ip = explode('/', $cidr, 2)[0];
if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
$ip = '—';

@ -860,13 +860,31 @@ final class CloudOperationRecoveryIdentity
self::expectRequest($method, $target, 'POST', '/v1/vms');
self::assertAllowedBody($body, [
'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu',
'memory_mib', 'disk_gib', 'bandwidth_mbps', 'network',
'memory_mib', 'disk_gib', 'bandwidth_mbps', 'public_network',
'template_id', 'template_revision', 'template_generation_token',
'startup_script', 'hostname', 'guest_ssh_public_key',
'root_password', 'public_pool_key', 'public_pool_cidr',
'public_ip_cidr', 'gateway', 'dns_servers',
'root_password',
'platform_network_policy_snapshot',
]);
$order = $job->order_id === null ? null
: CloudOrder::find((int) $job->order_id);
$orderSpec = $order === null ? null
: json_decode((string) $order->spec_json, true);
$reservation = $order === null || $order->reservation_id === null
? null : CloudResourceReservation::find(
(int) $order->reservation_id
);
try {
$frozenPublicNetwork = CloudPublicNetworkSnapshot::fromArray(
is_array($orderSpec)
? ($orderSpec['public_network'] ?? null) : null
);
$requestedPublicNetwork = CloudPublicNetworkSnapshot::fromArray(
$body['public_network'] ?? null
);
} catch (\InvalidArgumentException) {
self::invalidPayload('创建实例的双栈公网快照无效');
}
$resourceId = self::operationUuid((string) $job->operation_id);
$requestedUuid = $body['uuid'] ?? null;
$integers = ['vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps',
@ -892,17 +910,6 @@ final class CloudOperationRecoveryIdentity
|| !is_string($body['template_generation_token'] ?? null)
|| preg_match(self::CATALOG_ID_PATTERN,
$body['template_generation_token']) !== 1
|| !is_string($body['network'] ?? null)
|| trim($body['network']) === ''
|| !is_string($body['public_pool_key'] ?? null)
|| preg_match(self::CATALOG_ID_PATTERN,
$body['public_pool_key']) !== 1
|| !is_string($body['public_pool_cidr'] ?? null)
|| !is_string($body['public_ip_cidr'] ?? null)
|| !is_string($body['gateway'] ?? null)
|| !is_array($body['dns_servers'] ?? null)
|| !array_is_list($body['dns_servers'])
|| $body['dns_servers'] === []
|| !is_array($body['platform_network_policy_snapshot'] ?? null)
|| array_is_list($body['platform_network_policy_snapshot'])
|| ($requestedUuid !== null
@ -910,8 +917,30 @@ final class CloudOperationRecoveryIdentity
|| !hash_equals($resourceId,
strtolower($requestedUuid))))
|| (int) $job->user_id < 1
|| $job->order_id === null
|| (int) $job->order_id < 1
|| $order === null || !is_array($orderSpec)
|| array_is_list($orderSpec)
|| ($orderSpec['source'] ?? null) !== 'cloud'
|| (int) $order->user_id !== (int) $job->user_id
|| (int) ($order->host_id ?? 0) !== (int) $job->host_id
|| $reservation === null
|| (int) $reservation->id !== (int) $order->reservation_id
|| (int) ($reservation->order_id ?? 0) !== (int) $order->id
|| (int) ($reservation->user_id ?? 0) !== (int) $order->user_id
|| (int) ($reservation->host_id ?? 0) !== (int) $job->host_id
|| (int) ($reservation->offer_id ?? 0) !== (int) $order->offer_id
|| (int) ($reservation->resource_pool_id ?? 0)
!== (int) $order->resource_pool_id
|| (int) ($reservation->backup_restore_id ?? 0) !== 0
|| !hash_equals(
(string) $job->operation_id,
(string) ($reservation->operation_id ?? '')
)
|| !in_array((string) $reservation->state,
['held', 'uncertain', 'committed'], true)
|| !hash_equals(
$frozenPublicNetwork->fingerprint(),
$requestedPublicNetwork->fingerprint()
)
|| array_key_exists('owner_id', $payload)) {
self::invalidPayload('创建实例请求与任务账本不匹配');
}

@ -51,6 +51,16 @@ final class CloudOrderService
if (!in_array($source, ['cloud', 'deployment_snapshot'], true)) {
throw new CloudError('实例来源无效');
}
// The C7 provisioning contract is dual-stack end to end. Backup and
// cloud-snapshot restores keep their legacy identity contract until
// C11, so reject them before creating an order or invoice rather than
// accepting payment for work that cannot be recovered safely.
if ($source === 'deployment_snapshot') {
throw new CloudError(
'云快照创建实例正在升级双栈网络,暂不可用',
503
);
}
$template = '';
$snapshotKey = null;
if ($source === 'cloud') {
@ -152,7 +162,7 @@ final class CloudOrderService
$payload = ['source' => $source === 'cloud' ? 'cloud' : '',
'name' => $name, 'vcpu' => (int) $plan->cpu_cores,
'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'network' => ''];
'bandwidth_mbps' => (int) $plan->bandwidth_mbps];
$credential = null;
if ($source === 'cloud') {
$key = CloudSSHKeys::owned(
@ -166,9 +176,6 @@ final class CloudOrderService
'template_id' => $template,
'guest_ssh_public_key' => $key?->public_key ?? '',
'root_password' => $password,
'public_pool_key' => '', 'public_pool_cidr' => '',
'public_ip_cidr' => '', 'gateway' => '',
'dns_servers' => [],
];
$credential = [
'password' => $password,
@ -186,9 +193,6 @@ final class CloudOrderService
'hostname' => CloudInput::hostname($name),
'guest_ssh_public_key' => '',
'root_password' => '',
'public_pool_key' => '', 'public_pool_cidr' => '',
'public_ip_cidr' => '', 'gateway' => '',
'dns_servers' => [],
'debian_12_network_fix' =>
$backupSpec['debian_12_network_fix'],
'backup_key' => (string) $sourceBackup->backup_key,
@ -505,6 +509,16 @@ final class CloudOrderService
CloudPlatformTestNetworkPolicy::snapshotForProvisioning();
$payload['body']['platform_network_policy_snapshot'] = $platformPolicy;
$source = $orderSpec['source'] ?? null;
// Also fence orders created before this deployment. The surrounding
// payment transaction will roll back, so no wallet debit or provider
// payment can produce an order that the current recovery contract
// cannot reconcile safely.
if ($source === 'deployment_snapshot') {
throw new CloudError(
'云快照创建实例正在升级双栈网络,暂不可用',
503
);
}
$sourceBackup = null;
if ($source === 'cloud') {
if ($order->deployment_snapshot_id !== null
@ -623,6 +637,14 @@ final class CloudOrderService
$placement = CloudPlacementService::reserve(
$order, $offer, $plan, $payload
);
$orderSpec['public_network'] =
$placement['public_network']->toArray();
if ($orderSpec['public_network']
!== $placement['payload']['body']['public_network']) {
throw new CloudError('开通订单与任务的双栈公网快照不一致', 409);
}
$order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($sourceBackup !== null) {
$uuid = CloudOperationRecoveryIdentity::operationUuid(
(string) $placement['reservation']->operation_id

@ -39,6 +39,114 @@ final class CloudPlacementNetworkService
return $available;
}
/**
* New-instance catalog hint for one IPv4 + one sparse IPv6 pool on the
* same currently verified attachment. Exact admission is repeated by the
* bundle allocator under locks after payment.
*
* @return array<int,bool>
*/
public static function advisoryDualStackAvailableHosts(
$candidateRows
): array {
$hostLines = [];
foreach ($candidateRows as $candidate) {
$hostId = (int) ($candidate->id ?? 0);
$lineId = (int) ($candidate->resource_pool_line_id ?? 0);
if ($hostId > 0 && $lineId > 0) {
$hostLines[$hostId][$lineId] = true;
}
}
if ($hostLines === []) {
return [];
}
$agents = CloudHostAgent::whereIn('host_id', array_keys($hostLines))
->get()->keyBy('host_id');
$attachments = CloudHostNetworkAttachment::whereIn(
'host_id',
array_keys($hostLines)
)->where('state', 'active')->where('verification_state', 'verified')
->orderBy('id')->get();
if ($attachments->isEmpty()) {
return [];
}
$eligible = [];
foreach ($attachments as $attachment) {
$hostId = (int) $attachment->host_id;
$lineId = (int) $attachment->line_id;
$agent = $agents->get($hostId);
if ($agent instanceof CloudHostAgent
&& isset($hostLines[$hostId][$lineId])
&& self::attachmentReadyForAgent($attachment, $agent)
&& CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
)) {
$eligible[(int) $attachment->id] = $attachment;
}
}
if ($eligible === []) {
return [];
}
$pools = CloudPublicIpPool::whereIn(
'network_attachment_id',
array_keys($eligible)
)->where('state', 'active')->where('sync_state', 'applied')
->whereColumn('observed_revision', 'desired_revision')
->orderBy('id')->get();
$poolIds = $pools->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$ipsByPool = [];
if ($poolIds !== []) {
$ipRows = CloudPublicIp::whereIn('public_ip_pool_id', $poolIds)
->whereIn('state', [
'available', 'reserved', 'changing', 'uncertain',
'assigned',
])->orderBy('id')->get();
foreach ($ipRows as $ip) {
$ipsByPool[(int) $ip->public_ip_pool_id][] = $ip;
}
}
$hosts = CloudHost::whereIn('id', array_keys($hostLines))
->get()->keyBy('id');
$capacity = [];
foreach ($pools as $pool) {
$attachment = $eligible[(int) $pool->network_attachment_id]
?? null;
$family = (int) $pool->address_family;
if ($attachment === null
|| (int) $pool->host_id !== (int) $attachment->host_id
|| !in_array($family, [4, 6], true)
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $pool->pool_key) !== 1) {
continue;
}
$poolIps = $ipsByPool[(int) $pool->id] ?? [];
$hasCapacity = $family === 4
? self::advisoryIpv4PoolHasCapacity(
$pool,
$poolIps,
$hosts->get((int) $pool->host_id)
)
: self::advisoryIpv6PoolHasCapacity($pool, $poolIps);
if ($hasCapacity) {
$capacity[(int) $attachment->id][$family] = true;
}
}
$available = [];
foreach ($capacity as $attachmentId => $families) {
if (!isset($families[4], $families[6])) {
continue;
}
$attachment = $eligible[(int) $attachmentId];
$available[(int) $attachment->host_id] = true;
}
ksort($available, SORT_NUMERIC);
return $available;
}
/** @return array<int,array<int,bool>> keyed by host ID then line ID. */
public static function advisoryAvailableHostLines($candidateRows): array
{
@ -109,7 +217,6 @@ final class CloudPlacementNetworkService
->where('public_pool.sync_state', 'applied')
->whereColumn(
'public_pool.observed_revision',
'>=',
'public_pool.desired_revision'
)
->get([
@ -215,7 +322,7 @@ final class CloudPlacementNetworkService
->whereIn('network_attachment_id', array_keys($eligibleAttachments))
->where('state', 'active')
->where('sync_state', 'applied')
->whereColumn('observed_revision', '>=', 'desired_revision')
->whereColumn('observed_revision', 'desired_revision')
->orderBy('id')->lockForUpdate()->get();
$candidates = [];
foreach ($pools as $pool) {
@ -250,6 +357,42 @@ final class CloudPlacementNetworkService
return $candidates;
}
/**
* New-instance admission requires one IPv4 and one IPv6 pool on the exact
* same verified attachment. Address allocation remains owned by the
* atomic bundle allocator after the resource reservation row is created.
*/
public static function hasCompleteDualStackCandidate(array $candidates,
CloudHostAgent $agent): bool
{
$familiesByAttachment = [];
foreach ($candidates as $candidate) {
$attachment = $candidate['attachment'] ?? null;
$pool = $candidate['public_pool'] ?? null;
if (!$attachment instanceof CloudHostNetworkAttachment
|| !$pool instanceof CloudPublicIpPool
|| (int) $pool->network_attachment_id
!== (int) $attachment->id
|| !in_array((int) $pool->address_family, [4, 6], true)
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
)) {
continue;
}
$familiesByAttachment[(int) $attachment->id][
(int) $pool->address_family
] = true;
}
foreach ($familiesByAttachment as $families) {
if (isset($families[4], $families[6])) {
return true;
}
}
return false;
}
/** Current-revision Agent evidence for one already-loaded attachment. */
public static function attachmentReadyForAgent(
CloudHostNetworkAttachment $attachment,
@ -354,8 +497,86 @@ final class CloudPlacementNetworkService
->orderBy('id');
}
private static function advisoryIpv4PoolHasCapacity(
CloudPublicIpPool $pool,
array $ips,
?CloudHost $host
): bool {
try {
$network = CloudIpPrefix::network((string) $pool->cidr);
$gateway = CloudIpAddress::parse((string) $pool->gateway);
} catch (\InvalidArgumentException) {
return false;
}
if ($network->family() !== 4 || $network->prefixLength() > 30
|| (int) $pool->guest_prefix_length
!== $network->prefixLength()
|| !$gateway->isPublicUnicast()
|| !$network->contains($gateway)) {
return false;
}
$available = array_values(array_filter(
$ips,
static fn (CloudPublicIp $ip): bool =>
(string) $ip->state === 'available'
&& $ip->reservation_id === null
&& $ip->instance_id === null
&& $ip->operation_id === null
));
if (count($available) > self::MAX_PUBLIC_IPS_PER_POOL) {
return false;
}
foreach ($available as $ip) {
try {
$address = CloudIpAddress::parse((string) $ip->address);
} catch (\InvalidArgumentException) {
continue;
}
if ($address->isPublicUnicast()
&& self::publicIpBelongsToPool($ip, $pool, $host)) {
return true;
}
}
return false;
}
private static function advisoryIpv6PoolHasCapacity(
CloudPublicIpPool $pool,
array $ips
): bool {
try {
$network = CloudIpPrefix::network((string) $pool->cidr);
$gateway = CloudIpAddress::parse((string) $pool->gateway);
$start = CloudIpAddress::parse((string) $pool->allocation_start);
$end = CloudIpAddress::parse((string) $pool->allocation_end);
} catch (\InvalidArgumentException) {
return false;
}
if ($network->family() !== 6 || $network->prefixLength() > 120
|| (int) $pool->guest_prefix_length
!== $network->prefixLength()
|| !$gateway->isPublicUnicast()
|| (!$network->contains($gateway)
&& !(bool) $pool->gateway_on_link)
|| $start->family() !== 6 || $end->family() !== 6
|| !$start->isPublicUnicast() || !$end->isPublicUnicast()
|| !$network->contains($start) || !$network->contains($end)
|| $start->compare($end) > 0
|| (int) $pool->max_allocations < 1) {
return false;
}
$active = count(array_filter(
$ips,
static fn (CloudPublicIp $ip): bool =>
(int) $ip->address_family === 6
&& in_array((string) $ip->state,
['reserved', 'changing', 'uncertain', 'assigned'], true)
));
return $active < (int) $pool->max_allocations;
}
private static function publicIpBelongsToPool(CloudPublicIp $ip,
CloudPublicIpPool $pool): bool
CloudPublicIpPool $pool, ?CloudHost $host = null): bool
{
return (int) $ip->host_id === (int) $pool->host_id
&& (int) $ip->public_ip_pool_id === (int) $pool->id
@ -366,7 +587,7 @@ final class CloudPlacementNetworkService
) && self::addressAllowedByPool(
(string) $ip->address,
$pool,
CloudHost::find((int) $pool->host_id)
$host ?? CloudHost::find((int) $pool->host_id)
);
}

@ -17,6 +17,7 @@ use App\Models\CloudPublicIpPool;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
use App\Models\CloudResourceReservationIp;
use App\Models\CloudOrder;
use App\Models\CloudTemplate;
use App\Models\CloudTemplateReplica;
@ -239,10 +240,10 @@ final class CloudPlacementService
}
/**
* Select a host and reserve one concrete public IP exactly once.
* Select a host and atomically reserve one IPv4+IPv6 public network.
*
* @return array{host: CloudHost, reservation: CloudResourceReservation,
* public_ip: CloudPublicIp, payload: array}
* public_network: CloudPublicNetworkSnapshot, payload: array}
*/
public static function reserve(CloudOrder $order, CloudOffer $offer,
Shop $plan, array $payload): array
@ -313,51 +314,55 @@ final class CloudPlacementService
}
public static function commit(CloudOrder $order, int $instanceId,
string $confirmedPublicIpCidr): void
array $confirmedPublicNetwork): void
{
[, $reservation] = self::lockedHostAndReservation($order);
if ($reservation === null || (string) $reservation->state === 'released') {
throw new CloudError('开通任务缺少有效的资源预留', 409);
if ($instanceId < 1) {
throw new CloudError('开通任务实例归属无效', 409);
}
$ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id)
->lockForUpdate()->first();
if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id
|| !self::reservationNetworkMatches($reservation, $ip)
|| (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($ip->operation_id ?? ''))
|| !hash_equals(
(string) $ip->address . '/' . (int) $ip->prefix_length,
$confirmedPublicIpCidr
)
|| !in_array((string) $reservation->state,
['held', 'uncertain', 'committed'], true)
|| ((string) $reservation->state === 'held'
&& (string) $ip->state !== 'reserved')
|| ((string) $reservation->state === 'uncertain'
&& (string) $ip->state !== 'uncertain')
|| ((string) $reservation->state === 'committed'
&& (string) $ip->state !== 'assigned')) {
throw new CloudError('开通任务的公网 IP 预留不一致', 409);
}
if ((string) $reservation->state === 'committed') {
if ((string) $ip->state !== 'assigned'
|| (int) ($reservation->instance_id ?? 0) !== $instanceId
|| (int) ($ip->instance_id ?? 0) !== $instanceId) {
throw new CloudError('已交付实例的公网 IP 账本不一致', 409);
}
return;
}
$now = time();
$reservation->state = 'committed';
$reservation->instance_id = $instanceId;
$reservation->expires_at = null;
$reservation->updated_at = $now;
$reservation->save();
$ip->state = 'assigned';
$ip->instance_id = $instanceId;
$ip->updated_at = $now;
$ip->save();
$confirmed = CloudPublicNetworkSnapshot::fromArray(
$confirmedPublicNetwork
);
(new CloudResourceReservation())->getConnection()->transaction(
static function () use ($order, $instanceId, $confirmed): void {
$hint = CloudResourceReservation::where(
'order_id',
(int) $order->id
)->first();
if ($hint === null) {
throw new CloudError('开通任务缺少有效的资源预留', 409);
}
$allocated = CloudPublicNetworkAllocationService::commitBundle(
(int) $hint->id,
$instanceId,
(string) $hint->operation_id
);
if (!hash_equals(
$confirmed->fingerprint(),
$allocated->fingerprint()
)) {
throw new CloudError('开通回执与双栈公网预留不一致', 409);
}
$reservation = CloudResourceReservation::where(
'id',
(int) $hint->id
)->lockForUpdate()->first();
self::assertOrderReservation($order, $reservation, [
'held', 'uncertain', 'committed',
]);
if ((string) $reservation->state === 'committed') {
if ((int) ($reservation->instance_id ?? 0) !== $instanceId) {
throw new CloudError('已交付实例的资源账本不一致', 409);
}
return;
}
$reservation->state = 'committed';
$reservation->instance_id = $instanceId;
$reservation->expires_at = null;
$reservation->updated_at = time();
$reservation->save();
},
3
);
}
/**
@ -805,58 +810,102 @@ final class CloudPlacementService
$ip->save();
}
/** Keep an ambiguous create and its address unavailable for reconciliation. */
/** Keep an ambiguous create and both addresses unavailable for reconciliation. */
public static function markUncertain(CloudOrder $order): void
{
[, $reservation] = self::lockedHostAndReservation($order);
if ($reservation === null || (string) $reservation->state === 'released') {
return;
}
$ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id)
->lockForUpdate()->first();
if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id
|| !self::reservationNetworkMatches($reservation, $ip)
|| (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($ip->operation_id ?? ''))) {
throw new CloudError('开通任务的公网 IP 预留不一致', 409);
}
// A late exception after a successful commit must never roll a live
// instance and its address back to an ambiguous creation state.
if ((string) $reservation->state === 'committed') {
if ((string) $ip->state !== 'assigned'
|| (int) ($reservation->instance_id ?? 0) < 1
|| (int) ($ip->instance_id ?? 0) !== (int) $reservation->instance_id) {
throw new CloudError('已交付实例的公网 IP 账本不一致', 409);
}
return;
}
if (!in_array((string) $reservation->state, ['held', 'uncertain'], true)
|| !in_array((string) $ip->state, ['reserved', 'uncertain'], true)) {
throw new CloudError('开通任务的资源预留状态无效', 409);
}
$now = time();
$reservation->state = 'uncertain';
$reservation->expires_at = null;
$reservation->updated_at = $now;
$reservation->save();
$ip->state = 'uncertain';
$ip->updated_at = $now;
$ip->save();
(new CloudResourceReservation())->getConnection()->transaction(
static function () use ($order): void {
$hint = CloudResourceReservation::where(
'order_id',
(int) $order->id
)->first();
if ($hint === null || (string) $hint->state === 'released') {
return;
}
if ((string) $hint->state === 'committed') {
$instanceId = (int) ($hint->instance_id ?? 0);
if ($instanceId < 1) {
throw new CloudError('已交付实例的资源账本不一致', 409);
}
CloudPublicNetworkAllocationService::commitBundle(
(int) $hint->id,
$instanceId,
(string) $hint->operation_id
);
$reservation = CloudResourceReservation::where(
'id',
(int) $hint->id
)->lockForUpdate()->first();
self::assertOrderReservation(
$order,
$reservation,
['committed']
);
if ((int) ($reservation->instance_id ?? 0)
!== $instanceId) {
throw new CloudError(
'已交付实例的资源账本不一致',
409
);
}
return;
}
CloudPublicNetworkAllocationService::fenceBundle(
(int) $hint->id,
(string) $hint->operation_id
);
$reservation = CloudResourceReservation::where(
'id',
(int) $hint->id
)->lockForUpdate()->first();
self::assertOrderReservation(
$order,
$reservation,
['held', 'uncertain']
);
$reservation->state = 'uncertain';
$reservation->expires_at = null;
$reservation->updated_at = time();
$reservation->save();
},
3
);
}
/** Release only when the Agent outcome proves that no guest owns the IP. */
public static function release(CloudOrder $order, string $reason,
bool $includeCommitted = false): void
/** Release only when the Agent proves that no guest owns either address. */
public static function release(CloudOrder $order, string $reason): void
{
[, $reservation] = self::lockedHostAndReservation($order);
if ($reservation === null || (string) $reservation->state === 'released') {
return;
}
self::releaseLockedReservation(
$reservation,
$reason,
$includeCommitted
(new CloudResourceReservation())->getConnection()->transaction(
static function () use ($order, $reason): void {
$hint = CloudResourceReservation::where(
'order_id',
(int) $order->id
)->first();
if ($hint === null || (string) $hint->state === 'released') {
return;
}
if ((string) $hint->state === 'committed') {
throw new CloudError('已交付实例的资源不能按失败任务释放', 409);
}
$releaseReason = self::releaseReason($reason);
CloudPublicNetworkAllocationService::releaseBundle(
(int) $hint->id,
(string) $hint->operation_id,
$releaseReason,
true
);
$reservation = CloudResourceReservation::where(
'id',
(int) $hint->id
)->lockForUpdate()->first();
self::assertOrderReservation(
$order,
$reservation,
['held', 'uncertain']
);
self::markReservationReleased($reservation, $releaseReason);
},
3
);
}
@ -872,60 +921,115 @@ final class CloudPlacementService
if ($instance->order_id === null) {
return;
}
$order = CloudOrder::where('id', (int) $instance->order_id)
->lockForUpdate()->first();
if ($order === null) {
throw new CloudError('已删除实例的开通订单不存在', 409);
}
self::release($order, $reason, true);
return;
}
$host = CloudHost::where('id', (int) $instance->host_id)
->lockForUpdate()->first();
$reservation = CloudResourceReservation::where('id', $reservationId)
->lockForUpdate()->first();
if ($host === null || $reservation === null
|| (int) $reservation->host_id !== (int) $host->id
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) ($instance->resource_pool_id ?? 0)) {
throw new CloudError('已删除实例的资源预留账本不一致', 409);
}
$orderId = (int) ($reservation->order_id ?? 0);
$restoreId = (int) ($reservation->backup_restore_id ?? 0);
if ($orderId > 0 && $restoreId === 0
&& (int) ($reservation->offer_id ?? 0) > 0) {
$order = CloudOrder::where('id', $orderId)
->lockForUpdate()->first();
if ($order === null
|| (int) ($instance->order_id ?? 0) !== (int) $order->id
|| (int) ($order->reservation_id ?? 0)
!== (int) $reservation->id
|| (int) ($order->host_id ?? 0) !== (int) $instance->host_id) {
throw new CloudError('已删除实例的订单资源账本不一致', 409);
}
} elseif ($orderId === 0 && $restoreId > 0
&& (int) ($reservation->offer_id ?? 0) === 0) {
$restore = CloudBackupRestore::where('id', $restoreId)
->lockForUpdate()->first();
if ($restore === null || $instance->order_id !== null
|| (int) $restore->target_host_id !== (int) $instance->host_id
|| (int) $restore->target_instance_id !== (int) $instance->id
|| (int) $restore->reservation_id !== (int) $reservation->id
|| (string) $restore->state !== 'ready'
|| !hash_equals(
(string) $restore->operation_id,
(string) $reservation->operation_id
)) {
throw new CloudError('已删除恢复实例的资源账本不一致', 409);
}
} else {
throw new CloudError('已删除实例的资源来源无效', 409);
}
throw new CloudError('已删除实例缺少资源预留账本', 409);
}
(new CloudResourceReservation())->getConnection()->transaction(
static function () use ($instance, $reservationId, $reason): void {
// Read only enough source identity to choose the writer. The
// dual-stack allocator then acquires host -> attachment/pool
// -> reservation -> claims/IP in its canonical lock order.
$hint = CloudResourceReservation::where(
'id',
$reservationId
)->first();
if ($hint === null) {
throw new CloudError('已删除实例的资源预留账本不存在', 409);
}
$orderId = (int) ($hint->order_id ?? 0);
$restoreId = (int) ($hint->backup_restore_id ?? 0);
if ($orderId > 0 && $restoreId === 0
&& (int) ($hint->offer_id ?? 0) > 0) {
$order = CloudOrder::where('id', $orderId)->first();
if ($order === null
|| (int) ($instance->order_id ?? 0) !== $orderId
|| (int) ($order->reservation_id ?? 0)
!== $reservationId
|| (int) ($order->host_id ?? 0)
!== (int) $instance->host_id
|| (int) $hint->host_id !== (int) $instance->host_id
|| (int) ($hint->instance_id ?? 0)
!== (int) $instance->id
|| (int) $hint->resource_pool_id
!== (int) ($instance->resource_pool_id ?? 0)) {
throw new CloudError(
'已删除实例的订单资源账本不一致',
409
);
}
if ((string) $hint->state === 'released') {
return;
}
$releaseReason = self::releaseReason($reason);
CloudPublicNetworkAllocationService::
releaseCommittedBundle(
$reservationId,
(int) $instance->id,
(string) $hint->operation_id,
$releaseReason,
true
);
$reservation = CloudResourceReservation::where(
'id',
$reservationId
)->lockForUpdate()->first();
self::assertOrderReservation(
$order,
$reservation,
['committed']
);
if ((int) ($reservation->instance_id ?? 0)
!== (int) $instance->id) {
throw new CloudError(
'已删除实例的资源归属不一致',
409
);
}
self::markReservationReleased(
$reservation,
$releaseReason
);
return;
}
self::releaseLockedReservation($reservation, $reason, true);
// Backup restores retain their pre-C11 single-address ledger.
if ($orderId !== 0 || $restoreId < 1
|| (int) ($hint->offer_id ?? 0) !== 0) {
throw new CloudError('已删除实例的资源来源无效', 409);
}
$host = CloudHost::where('id', (int) $instance->host_id)
->lockForUpdate()->first();
$reservation = CloudResourceReservation::where(
'id',
$reservationId
)->lockForUpdate()->first();
$restore = CloudBackupRestore::where('id', $restoreId)
->lockForUpdate()->first();
if ($host === null || $reservation === null
|| (int) $reservation->host_id !== (int) $host->id
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) ($instance->resource_pool_id ?? 0)
|| $restore === null || $instance->order_id !== null
|| (int) $restore->target_host_id
!== (int) $instance->host_id
|| (int) $restore->target_instance_id
!== (int) $instance->id
|| (int) $restore->reservation_id
!== (int) $reservation->id
|| (string) $restore->state !== 'ready'
|| !hash_equals(
(string) $restore->operation_id,
(string) $reservation->operation_id
)) {
throw new CloudError(
'已删除恢复实例的资源账本不一致',
409
);
}
self::releaseLockedReservation($reservation, $reason, true);
},
3
);
}
private static function releaseLockedReservation(
@ -1179,15 +1283,6 @@ final class CloudPlacementService
return null;
}
$networkCandidates = CloudPlacementNetworkService::lockedCandidates(
$hostId,
(int) $pool->line_id,
$agent
);
if ($networkCandidates === []) {
return null;
}
// This must be a current locking read, not an aggregate consistent
// read. Every reservation writer locks the host first, so after this
// host lock is acquired the row set is stable and the locking read
@ -1203,16 +1298,6 @@ final class CloudPlacementService
return null;
}
$network = CloudPlacementNetworkService::lockAvailableSelection(
$hostId,
$networkCandidates
);
if ($network === null) {
return null;
}
$selectedAttachment = $network['attachment'];
$selectedPool = $network['public_pool'];
$ip = $network['public_ip'];
$operationId = bin2hex(random_bytes(16));
$reservation = new CloudResourceReservation();
$reservation->reservation_key = bin2hex(random_bytes(16));
@ -1223,9 +1308,9 @@ final class CloudPlacementService
$reservation->host_id = $hostId;
$reservation->user_id = $order->user_id;
$reservation->instance_id = null;
$reservation->network_attachment_id = $selectedAttachment->id;
$reservation->public_ip_pool_id = $selectedPool->id;
$reservation->public_ip_id = $ip->id;
$reservation->network_attachment_id = null;
$reservation->public_ip_pool_id = null;
$reservation->public_ip_id = null;
$reservation->cpu_cores = $resources['cpu_cores'];
$reservation->memory_mib = $resources['memory_mib'];
$reservation->disk_gib = $resources['disk_gib'];
@ -1235,13 +1320,33 @@ final class CloudPlacementService
$reservation->release_reason = '';
$reservation->created_at = $reservation->updated_at = time();
$reservation->save();
$ip->state = 'reserved';
$ip->reservation_id = $reservation->id;
$ip->instance_id = null;
$ip->operation_id = $operationId;
$ip->updated_at = time();
$ip->save();
try {
$publicNetwork = CloudPublicNetworkAllocationService::reserveBundle(
$hostId,
(int) $pool->line_id,
(int) $reservation->id,
$operationId
);
} catch (CloudPublicNetworkCapacityUnavailable) {
// This is the only allocation outcome that means "try another
// host". The allocator selected and locked the complete network
// context before returning it, so a capacity miss must not have
// created either family claim. Any residue is a ledger fault and
// must abort the payment transaction instead of being hidden as
// ordinary scheduler exhaustion.
$claims = CloudResourceReservationIp::where(
'reservation_id',
(int) $reservation->id
)->orderBy('id')->lockForUpdate()->get();
if (!$claims->isEmpty()) {
throw new CloudError(
'公网地址容量回退存在残留账本,必须人工核查',
409
);
}
$reservation->delete();
return null;
}
$order->resource_pool_id = $pool->id;
$order->host_id = $hostId;
@ -1252,29 +1357,24 @@ final class CloudPlacementService
return [
'host' => $host,
'reservation' => $reservation,
'public_ip' => $ip,
'payload' => self::placementPayload(
$payload, $selectedAttachment, $selectedPool, $ip
),
'public_network' => $publicNetwork,
'payload' => self::placementPayload($payload, $publicNetwork),
];
}
private static function placementPayload(array $payload,
CloudHostNetworkAttachment $attachment, CloudPublicIpPool $publicPool,
CloudPublicIp $ip): array
CloudPublicNetworkSnapshot $publicNetwork): array
{
if (($payload['method'] ?? null) !== 'POST'
|| ($payload['request_target'] ?? null) !== '/v1/vms'
|| !is_array($payload['body'] ?? null)) {
throw new CloudError('开通订单的加密请求无效', 409);
}
$payload['body']['network'] = (string) $attachment->network_selector;
$payload['body']['public_pool_key'] = (string) $publicPool->pool_key;
$payload['body']['public_pool_cidr'] = (string) $publicPool->cidr;
$payload['body']['public_ip_cidr'] = (string) $ip->address . '/'
. (int) $ip->prefix_length;
$payload['body']['gateway'] = (string) $publicPool->gateway;
$payload['body']['dns_servers'] = self::poolDnsServers($publicPool);
foreach (['network', 'public_pool_key', 'public_pool_cidr',
'public_ip_cidr', 'gateway', 'dns_servers'] as $retired) {
unset($payload['body'][$retired]);
}
$payload['body']['public_network'] = $publicNetwork->toArray();
return $payload;
}
@ -1317,6 +1417,60 @@ final class CloudPlacementService
}
}
private static function assertOrderReservation(CloudOrder $order,
?CloudResourceReservation $reservation, array $allowedStates): void
{
if ($reservation === null
|| (int) ($reservation->order_id ?? 0) !== (int) $order->id
|| (int) ($reservation->user_id ?? 0) !== (int) $order->user_id
|| (int) ($reservation->offer_id ?? 0) !== (int) $order->offer_id
|| (int) ($reservation->resource_pool_id ?? 0)
!== (int) $order->resource_pool_id
|| (int) ($reservation->host_id ?? 0)
!== (int) $order->host_id
|| (int) ($order->reservation_id ?? 0)
!== (int) ($reservation->id ?? 0)
|| (int) ($reservation->backup_restore_id ?? 0) !== 0
|| preg_match(
'/^[a-f0-9]{32}$/D',
(string) ($reservation->operation_id ?? '')
) !== 1
|| !in_array(
(string) ($reservation->state ?? ''),
$allowedStates,
true
)) {
throw new CloudError('开通订单的资源预留账本不一致', 409);
}
}
private static function releaseReason(string $reason): string
{
$reason = strtolower(trim($reason));
$reason = preg_replace('/[^a-z0-9_]+/', '_', $reason) ?? '';
$reason = trim($reason, '_');
if ($reason === '' || preg_match('/^[a-z]/D', $reason) !== 1) {
$reason = 'released' . ($reason === '' ? '' : '_' . $reason);
}
if (strlen($reason) < 3) {
$reason = 'released';
}
return substr($reason, 0, 64);
}
private static function markReservationReleased(
CloudResourceReservation $reservation,
string $reason
): void {
$now = time();
$reservation->state = 'released';
$reservation->released_at = $now;
$reservation->release_reason = $reason;
$reservation->expires_at = null;
$reservation->updated_at = $now;
$reservation->save();
}
/**
* Capacity must follow the immutable order snapshot, never the mutable
* current plan. The sealed Agent request is checked against the same
@ -1372,20 +1526,6 @@ final class CloudPlacementService
return $resources;
}
/** @return array{0: ?CloudHost, 1: ?CloudResourceReservation} */
private static function lockedHostAndReservation(CloudOrder $order): array
{
$host = $order->host_id === null ? null
: CloudHost::where('id', (int) $order->host_id)->lockForUpdate()->first();
$reservation = CloudResourceReservation::where('order_id', (int) $order->id)
->lockForUpdate()->first();
if ($reservation !== null
&& ($host === null || (int) $reservation->host_id !== (int) $host->id)) {
throw new CloudError('订单的宿主机与资源预留不一致', 409);
}
return [$host, $reservation];
}
private static function candidateHostRows(int $poolId)
{
return CloudHost::query()->join(
@ -1450,7 +1590,7 @@ final class CloudPlacementService
*/
private static function availableIpHosts($candidateRows): array
{
return CloudPlacementNetworkService::advisoryAvailableHosts(
return CloudPlacementNetworkService::advisoryDualStackAvailableHosts(
$candidateRows
);
}

@ -2,6 +2,7 @@
namespace App\Services\Cloud;
use App\Models\CloudHostAgent;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Connection;
@ -28,11 +29,19 @@ final class CloudPublicNetworkAllocationService
$reservationId,
$operationId
): CloudPublicNetworkSnapshot {
$claimHints = self::unlockedClaims($reservationId);
self::lockHost($hostId);
$selection = $claimHints === []
? self::lockPoolPair($hostId, $lineId)
: self::lockClaimNetworkContext($claimHints, $hostId, $lineId);
$claimHints = self::unlockedClaims($reservationId);
$catalog = null;
$selection = null;
if ($claimHints === []) {
$catalog = self::lockPoolCatalog($hostId, $lineId);
} else {
$selection = self::lockClaimNetworkContext(
$claimHints,
$hostId,
$lineId
);
}
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'committed', 'uncertain']);
@ -41,9 +50,12 @@ final class CloudPublicNetworkAllocationService
self::assertClaimSet($existing, $operationId, [
'reserved', 'committed', 'uncertain',
]);
if ($selection === null) {
throw new CloudError('公网网络资源预留状态不明确', 409);
}
self::assertClaimsUseSelection($existing, $selection);
$addresses = self::lockClaimAddresses($existing);
self::assertClaimAddresses($existing, $addresses,
self::assertClaimAddresses($existing, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'committed' => ['assigned'],
@ -54,6 +66,10 @@ final class CloudPublicNetworkAllocationService
if ($claimHints !== [] || (string) $reservation->state !== 'held') {
throw new CloudError('公网网络资源预留状态不明确', 409);
}
if ($catalog === null) {
throw new CloudError('公网网络候选目录不完整', 409);
}
$selection = self::selectAvailablePoolPair($catalog);
$now = time();
$claims = [];
foreach (self::FAMILIES as $family) {
@ -96,12 +112,15 @@ final class CloudPublicNetworkAllocationService
$operationId
): CloudPublicNetworkSnapshot {
$reservationHint = self::unlockedReservation($reservationId);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
@ -111,7 +130,8 @@ final class CloudPublicNetworkAllocationService
['reserved', 'uncertain', 'committed']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
self::assertClaimAddresses($claims, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
'committed' => ['assigned'],
@ -146,12 +166,15 @@ final class CloudPublicNetworkAllocationService
$operationId
): void {
$reservationHint = self::unlockedReservation($reservationId);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
@ -161,7 +184,8 @@ final class CloudPublicNetworkAllocationService
['reserved', 'uncertain']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
self::assertClaimAddresses($claims, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
]);
@ -196,12 +220,15 @@ final class CloudPublicNetworkAllocationService
$reason
): void {
$reservationHint = self::unlockedReservation($reservationId);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
@ -211,7 +238,8 @@ final class CloudPublicNetworkAllocationService
['reserved', 'uncertain']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
self::assertClaimAddresses($claims, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
]);
@ -240,12 +268,15 @@ final class CloudPublicNetworkAllocationService
$reason
): void {
$reservationHint = self::unlockedReservation($reservationId);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
@ -254,7 +285,8 @@ final class CloudPublicNetworkAllocationService
self::assertClaimSet($claims, $operationId, ['committed']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
self::assertClaimAddresses($claims, $addresses, $selection,
$operationId, [
'committed' => ['assigned'],
], $instanceId);
self::releaseLockedClaims($claims, $operationId, $reason);
@ -385,15 +417,136 @@ final class CloudPublicNetworkAllocationService
return $result;
}
private static function assertPoolLedger(object $pool, array $rows,
array $retainedSourceEvidence): void
{
foreach ($rows as $row) {
self::assertConcreteAddress($row, $pool);
self::assertAddressOwnership(
$row,
$pool,
$retainedSourceEvidence
);
}
}
private static function assertConcreteAddress(object $row,
object $pool): CloudIpAddress
{
try {
$address = CloudIpAddress::parse((string) $row->address);
if ((int) $row->host_id !== (int) $pool->host_id
|| (int) $row->public_ip_pool_id !== (int) $pool->id
|| (int) $row->address_family
!== (int) $pool->address_family
|| (int) $row->prefix_length
!== (int) $pool->guest_prefix_length
|| !hash_equals($address->text(), (string) $row->address)
|| !is_string($row->address_binary)
|| !hash_equals($address->binary(), $row->address_binary)
|| !self::rawAddressBelongsToPool($address, $pool)
|| ((string) $row->state !== 'disabled'
&& !self::rawAddressAllowedByPool($address, $pool))) {
throw new \InvalidArgumentException();
}
if ($address->family() === 6
&& (string) $row->state !== 'disabled') {
$start = CloudIpAddress::parse($pool->allocation_start ?? null);
$end = CloudIpAddress::parse($pool->allocation_end ?? null);
if ($address->compare($start) < 0
|| $address->compare($end) > 0) {
throw new \InvalidArgumentException();
}
}
return $address;
} catch (\Throwable) {
throw new CloudError('公网地址具体身份与地址池不一致', 409);
}
}
private static function assertAddressOwnership(object $row,
?object $pool = null, array $retainedSourceEvidence = []): void
{
$reservationId = $row->reservation_id === null
? null : (int) $row->reservation_id;
$instanceId = $row->instance_id === null
? null : (int) $row->instance_id;
$operationId = $row->operation_id;
$validOperation = is_string($operationId)
&& preg_match('/^[a-f0-9]{32}$/D', $operationId) === 1;
$state = (string) $row->state;
$valid = match ($state) {
'available', 'disabled' => $reservationId === null
&& $instanceId === null && $operationId === null,
'reserved' => $reservationId !== null && $reservationId > 0
&& $instanceId === null && $validOperation,
'assigned' => $reservationId !== null && $reservationId > 0
&& $validOperation && (
($instanceId !== null && $instanceId > 0)
|| self::matchesRetainedSourceEvidence(
$row,
$pool,
$retainedSourceEvidence
)
),
'changing' => $reservationId === null
&& $instanceId !== null && $instanceId > 0
&& $validOperation,
'uncertain' => $validOperation && (
($reservationId !== null && $reservationId > 0
&& $instanceId === null)
|| ($reservationId === null
&& $instanceId !== null && $instanceId > 0)
),
default => false,
};
if (!$valid) {
throw new CloudError('公网地址占用账本形态不一致', 409);
}
}
private static function matchesRetainedSourceEvidence(object $row,
?object $pool, array $evidenceByPublicIpId): bool
{
if ($pool === null || $row->instance_id !== null) {
return false;
}
$evidence = $evidenceByPublicIpId[(int) ($row->id ?? 0)] ?? null;
return is_array($evidence)
&& in_array(
$evidence['migration_state'] ?? null,
['source_retained', 'cleanup_running'],
true
)
&& (int) ($evidence['reservation_id'] ?? 0)
=== (int) ($row->reservation_id ?? 0)
&& (int) ($evidence['host_id'] ?? 0) === (int) $row->host_id
&& (int) ($evidence['host_id'] ?? 0) === (int) $pool->host_id
&& (int) ($evidence['network_attachment_id'] ?? 0)
=== (int) $pool->network_attachment_id
&& (int) ($evidence['public_ip_pool_id'] ?? 0)
=== (int) $row->public_ip_pool_id
&& (int) ($evidence['public_ip_pool_id'] ?? 0)
=== (int) $pool->id
&& (int) ($evidence['public_ip_id'] ?? 0) === (int) $row->id
&& is_string($evidence['operation_id'] ?? null)
&& hash_equals(
(string) $evidence['operation_id'],
(string) ($row->operation_id ?? '')
);
}
private static function assertClaimAddresses(array $claims,
array $addresses, string $operationId, array $allowedPairs,
?int $instanceId = null): void
array $addresses, array $selection, string $operationId,
array $allowedPairs, ?int $instanceId = null): void
{
foreach ($claims as $claim) {
$ip = $addresses[(int) $claim->public_ip_id] ?? null;
$claimState = (string) $claim->state;
$allowedIpStates = $allowedPairs[$claimState] ?? [];
if ($ip === null || $allowedIpStates === []
$family = (int) $claim->address_family;
$pool = $selection['pools'][$family] ?? null;
if ($ip === null || $pool === null || $allowedIpStates === []
|| !in_array((string) $ip->state, $allowedIpStates, true)
|| (int) $ip->reservation_id !== (int) $claim->reservation_id
|| (int) $ip->address_family !== (int) $claim->address_family
@ -403,6 +556,8 @@ final class CloudPublicNetworkAllocationService
(string) ($ip->operation_id ?? ''))) {
throw new CloudError('公网地址与预留账本不一致', 409);
}
self::assertConcreteAddress($ip, $pool);
self::assertAddressOwnership($ip);
if ((string) $ip->state === 'assigned') {
$actualInstanceId = (int) ($ip->instance_id ?? 0);
if ($actualInstanceId < 1
@ -447,44 +602,165 @@ final class CloudPublicNetworkAllocationService
}
}
private static function lockPoolPair(int $hostId, int $lineId): array
/**
* Lock the exact current Agent proof and every configured pool candidate.
* Concrete address rows are deliberately not locked here: the reservation
* row must come before claims/IPs in the canonical hierarchy.
*/
private static function lockPoolCatalog(int $hostId, int $lineId): array
{
$agent = CloudHostAgent::where('host_id', $hostId)
->lockForUpdate()->first();
if (!$agent instanceof CloudHostAgent || !$agent->isReady()) {
throw new CloudError('宿主机 Agent 双栈网络验证证据无效', 409);
}
$attachments = DB::table('cloud_host_network_attachments')
->where('host_id', $hostId)->where('line_id', $lineId)
->where('state', 'active')->orderBy('priority')->orderBy('id')
->lockForUpdate()->get();
->where('state', 'active')->orderBy('id')
->lockForUpdate()->get()->all();
$eligible = [];
foreach ($attachments as $attachment) {
$rows = DB::table('cloud_public_ip_pools')
->where('host_id', $hostId)
->where('network_attachment_id', (int) $attachment->id)
->where('state', 'active')->where('sync_state', 'applied')
->whereColumn('desired_revision', 'observed_revision')
->whereIn('address_family', self::FAMILIES)
->orderBy('address_family')->orderBy('priority')->orderBy('id')
->lockForUpdate()->get();
$pools = [];
if ((string) $attachment->verification_state !== 'verified'
|| (int) $attachment->last_verified_at < 1
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
)) {
continue;
}
$eligible[(int) $attachment->id] = $attachment;
}
if ($eligible === []) {
throw new CloudError('宿主机缺少当前双栈公网网络验证证据', 409);
}
uasort($eligible, static fn (object $left, object $right): int => [
(int) $left->priority,
(int) $left->id,
] <=> [
(int) $right->priority,
(int) $right->id,
]);
$poolRows = DB::table('cloud_public_ip_pools')
->where('host_id', $hostId)
->whereIn('network_attachment_id', array_keys($eligible))
->where('state', 'active')
->whereIn('address_family', self::FAMILIES)
->orderBy('id')->lockForUpdate()->get()->all();
$pools = [];
foreach ($poolRows as $pool) {
$attachmentId = (int) $pool->network_attachment_id;
$family = (int) $pool->address_family;
if (!isset($eligible[$attachmentId])
|| (int) $pool->host_id !== $hostId
|| !in_array($family, self::FAMILIES, true)
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $pool->pool_key) !== 1
|| (string) $pool->sync_state !== 'applied'
|| (int) $pool->observed_revision
!== (int) $pool->desired_revision) {
throw new CloudError('公网地址池目录尚未精确收敛', 409);
}
self::validatePool($pool, $family);
$pools[$attachmentId][] = $pool;
}
foreach ($pools as &$attachmentPools) {
usort($attachmentPools,
static fn (object $left, object $right): int => [
(int) $left->priority,
(int) $left->id,
] <=> [
(int) $right->priority,
(int) $right->id,
]);
}
unset($attachmentPools);
$complete = false;
foreach (array_keys($eligible) as $attachmentId) {
$families = [];
foreach ($pools[$attachmentId] ?? [] as $pool) {
$families[(int) $pool->address_family] = true;
}
if (isset($families[4], $families[6])) {
$complete = true;
break;
}
}
if (!$complete) {
throw new CloudError('宿主机双栈公网地址池目录不完整', 409);
}
$poolIds = array_map(
static fn (object $pool): int => (int) $pool->id,
$poolRows
);
$retainedSourceEvidence = CloudInstanceMigrationSettlement::
lockRetainedSourcePublicIpEvidence($hostId, $poolIds);
return [
'attachments' => $eligible,
'pools' => $pools,
'retained_source_evidence' => $retainedSourceEvidence,
];
}
/** Called only after the reservation row is locked. */
private static function selectAvailablePoolPair(array $catalog): array
{
$allPools = [];
foreach ($catalog['pools'] as $attachmentPools) {
foreach ($attachmentPools as $pool) {
$allPools[(int) $pool->id] = $pool;
}
}
ksort($allPools, SORT_NUMERIC);
$rowsByPool = array_fill_keys(array_keys($allPools), []);
$lockedRows = DB::table('cloud_public_ips')
->whereIn('public_ip_pool_id', array_keys($allPools))
->orderBy('id')->lockForUpdate()->get()->all();
foreach ($lockedRows as $row) {
$poolId = (int) $row->public_ip_pool_id;
if (!isset($rowsByPool[$poolId])) {
throw new CloudError('公网地址引用了候选目录之外的地址池', 409);
}
$rowsByPool[$poolId][] = $row;
}
foreach ($allPools as $poolId => $pool) {
self::assertPoolLedger(
$pool,
$rowsByPool[$poolId],
$catalog['retained_source_evidence'] ?? []
);
}
foreach ($catalog['attachments'] as $attachmentId => $attachment) {
$selectedPools = [];
$addressCandidates = [];
foreach ($rows as $row) {
$family = (int) $row->address_family;
self::validatePool($row, $family);
if (isset($pools[$family])) {
foreach ($catalog['pools'][$attachmentId] ?? [] as $pool) {
$family = (int) $pool->address_family;
if (isset($selectedPools[$family])) {
continue;
}
$candidate = self::lockReservableAddressCandidate($row);
$candidate = self::lockReservableAddressCandidate(
$pool,
$rowsByPool[(int) $pool->id] ?? []
);
if ($candidate !== null) {
$pools[$family] = $row;
$selectedPools[$family] = $pool;
$addressCandidates[$family] = $candidate;
}
}
if (isset($pools[4], $pools[6])) {
if (isset($selectedPools[4], $selectedPools[6])) {
return [
'attachment' => $attachment,
'pools' => $pools,
'pools' => $selectedPools,
'address_candidates' => $addressCandidates,
];
}
}
throw new CloudError('宿主机没有完整可用的双栈公网地址池', 409);
throw new CloudPublicNetworkCapacityUnavailable(
'宿主机没有完整可用的双栈公网地址池',
409
);
}
/**
@ -496,28 +772,26 @@ final class CloudPublicNetworkAllocationService
* range_start:?CloudIpAddress,range_end:?CloudIpAddress}
*/
private static function lockReservableAddressCandidate(
object $pool
object $pool,
array $rows
): ?array {
$family = (int) $pool->address_family;
if ($family === 6) {
$activeCount = DB::table('cloud_public_ips')
->where('public_ip_pool_id', (int) $pool->id)
->whereIn('state', [
'reserved', 'assigned', 'changing', 'uncertain',
])->count();
$activeCount = count(array_filter(
$rows,
static fn (object $row): bool => in_array(
(string) $row->state,
['reserved', 'assigned', 'changing', 'uncertain'],
true
)
));
if ((int) $pool->max_allocations < 1
|| $activeCount >= (int) $pool->max_allocations) {
return null;
}
}
$available = DB::table('cloud_public_ips')
->where('host_id', (int) $pool->host_id)
->where('public_ip_pool_id', (int) $pool->id)
->where('address_family', $family)->where('state', 'available')
->whereNull('reservation_id')->whereNull('instance_id')
->whereNull('operation_id')->orderBy('id')->lockForUpdate()->get();
foreach ($available as $row) {
if (self::addressAllowedByPool($row, $pool)) {
foreach ($rows as $row) {
if ((string) $row->state === 'available') {
return [
'row' => $row,
'candidate' => null,
@ -537,8 +811,7 @@ final class CloudPublicNetworkAllocationService
|| $candidate->compare($rangeEnd) > 0) {
$candidate = $rangeStart;
}
$materializedCount = DB::table('cloud_public_ips')
->where('public_ip_pool_id', (int) $pool->id)->count();
$materializedCount = count($rows);
$attempts = max(1, $materializedCount
+ (int) $pool->max_allocations
+ count(self::decodedAddresses(
@ -695,33 +968,10 @@ final class CloudPublicNetworkAllocationService
}
}
private static function addressAllowedByPool(object $row,
object $pool): bool
{
try {
if ((int) $row->address_family !== (int) $pool->address_family
|| (int) $row->prefix_length
!== (int) $pool->guest_prefix_length) {
return false;
}
return self::rawAddressAllowedByPool(
CloudIpAddress::parse((string) $row->address),
$pool
);
} catch (\Throwable) {
return false;
}
}
private static function rawAddressAllowedByPool(CloudIpAddress $address,
object $pool): bool
{
$prefix = CloudIpPrefix::network((string) $pool->cidr);
if ($address->family() !== (int) $pool->address_family
|| !$address->isPublicUnicast() || !$prefix->contains($address)
|| $address->equals($prefix->networkAddress())
|| ($address->family() === 4
&& $address->equals($prefix->lastAddress()))) {
if (!self::rawAddressBelongsToPool($address, $pool)) {
return false;
}
$blocked = self::decodedAddresses(
@ -740,6 +990,18 @@ final class CloudPublicNetworkAllocationService
return !isset($blocked[$address->text()]);
}
private static function rawAddressBelongsToPool(CloudIpAddress $address,
object $pool): bool
{
$prefix = CloudIpPrefix::network((string) $pool->cidr);
return $address->family() === (int) $pool->address_family
&& $address->isPublicUnicast()
&& $prefix->contains($address)
&& !$address->equals($prefix->networkAddress())
&& ($address->family() !== 4
|| !$address->equals($prefix->lastAddress()));
}
private static function decodedAddresses(string $json,
bool $allowEmpty, int $maximum = 256): array
{

@ -0,0 +1,14 @@
<?php
namespace App\Services\Cloud;
/**
* The selected host has no complete allocatable IPv4 + IPv6 pair.
*
* Placement may continue with the next host only for this exact outcome.
* Invalid pool configuration and inconsistent address ledgers remain hard
* failures and must never be converted into scheduler fallback.
*/
final class CloudPublicNetworkCapacityUnavailable extends CloudError
{
}

@ -2665,45 +2665,47 @@ final class CloudWorkerService
|| preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $uuid) !== 1) {
throw new CloudError('Agent 成功结果缺少虚拟机标识', 502);
}
$requestedPublicIpCidr = is_array($payload['body'] ?? null)
? ($payload['body']['public_ip_cidr'] ?? null) : null;
$requestedPublicPoolKey = is_array($payload['body'] ?? null)
? ($payload['body']['public_pool_key'] ?? null) : null;
$confirmedPublicIpCidr = $vm['public_ip_cidr'] ?? null;
$confirmedPublicPoolKey = $vm['public_pool_key'] ?? null;
if (!is_string($requestedPublicIpCidr)
|| !is_string($confirmedPublicIpCidr)
|| !hash_equals($requestedPublicIpCidr,
$confirmedPublicIpCidr)
|| !is_string($requestedPublicPoolKey)
|| !is_string($confirmedPublicPoolKey)
|| preg_match('/^[a-f0-9]{32}$/D',
$requestedPublicPoolKey) !== 1
|| !hash_equals($requestedPublicPoolKey,
$confirmedPublicPoolKey)) {
$orderSpec = json_decode((string) $order->spec_json, true);
try {
$frozenPublicNetwork = CloudPublicNetworkSnapshot::fromArray(
is_array($orderSpec)
? ($orderSpec['public_network'] ?? null) : null
);
$requestedPublicNetwork =
CloudPublicNetworkSnapshot::fromArray(
is_array($payload['body'] ?? null)
? ($payload['body']['public_network'] ?? null)
: null
);
$confirmedPublicNetwork =
CloudPublicNetworkSnapshot::fromArray(
$vm['public_network'] ?? null
);
} catch (\InvalidArgumentException) {
throw new CloudError(
'Agent 成功结果缺少有效的双栈公网快照,必须人工核查',
502
);
}
if (!hash_equals(
$frozenPublicNetwork->fingerprint(),
$requestedPublicNetwork->fingerprint()
) || !hash_equals(
$requestedPublicNetwork->fingerprint(),
$confirmedPublicNetwork->fingerprint()
)) {
// A completion result may describe a VM whose network was
// changed out of band after dispatch. Never commit the
// original address in that case. Finalization converts the
// task to a terminal failure and retains the resource lock.
// changed out of band after dispatch. Never commit either
// original address in that case; retain the whole bundle.
throw new CloudError(
'Agent 成功结果与预留公网 IP 不一致,必须人工核查', 502
'Agent 成功结果与预留双栈公网不一致,必须人工核查',
502
);
}
$provisionInvoice = CloudInvoice::where(
'order_id',
(int) $order->id
)->lockForUpdate()->first();
$reservation = $order->reservation_id === null ? null
: \App\Models\CloudResourceReservation::where(
'id',
(int) $order->reservation_id
)->lockForUpdate()->first();
$publicIp = $reservation === null
|| $reservation->public_ip_id === null ? null
: \App\Models\CloudPublicIp::where(
'id',
(int) $reservation->public_ip_id
)->lockForUpdate()->first();
if (!in_array((string) $order->status,
['queued', 'failed', 'uncertain'], true)
|| $order->refunded_at !== null
@ -2720,36 +2722,7 @@ final class CloudWorkerService
|| strtoupper((string) $provisionInvoice->currency)
!== strtoupper((string) $order->currency)
|| CloudMoney::cents((string) $provisionInvoice->amount)
!== CloudMoney::cents((string) $order->amount)
|| $reservation === null
|| (int) $reservation->order_id !== (int) $order->id
|| (int) $reservation->user_id !== (int) $order->user_id
|| (int) $reservation->offer_id !== (int) $order->offer_id
|| (int) $reservation->resource_pool_id
!== (int) $order->resource_pool_id
|| (int) $reservation->host_id !== (int) $order->host_id
|| !hash_equals(
(string) $job->operation_id,
(string) $reservation->operation_id
)
|| !in_array((string) $reservation->state,
['held', 'uncertain'], true)
|| $reservation->instance_id !== null
|| $publicIp === null
|| (int) $publicIp->host_id !== (int) $reservation->host_id
|| (int) ($publicIp->reservation_id ?? 0)
!== (int) $reservation->id
|| !hash_equals(
(string) $reservation->operation_id,
(string) ($publicIp->operation_id ?? '')
)
|| !in_array((string) $publicIp->state,
['reserved', 'uncertain'], true)
|| !hash_equals(
(string) $publicIp->address . '/'
. (int) $publicIp->prefix_length,
$confirmedPublicIpCidr
)) {
!== CloudMoney::cents((string) $order->amount)) {
throw new CloudRecoveryInstanceStateConflict(
'开通成功回执与资金、库存或资源预留账本不一致',
409
@ -2765,7 +2738,7 @@ final class CloudWorkerService
$instance->offer_id = $order->offer_id;
$instance->resource_pool_id = $order->resource_pool_id;
$instance->reservation_id = $order->reservation_id;
$spec = json_decode((string) $order->spec_json, true) ?: [];
$spec = $orderSpec;
$templateMetadata = self::trustedTemplateMetadata($payload);
$spec = array_replace($spec, $templateMetadata);
$now = time();
@ -2825,6 +2798,8 @@ final class CloudWorkerService
}
// A VM is panel-managed only after the Agent's exact create
// operation has returned the validated success above.
$instanceSpec['public_network'] =
$confirmedPublicNetwork->toArray();
$instanceSpec['managed'] = true;
$instance->spec_json = json_encode(
$instanceSpec,
@ -2852,7 +2827,9 @@ final class CloudWorkerService
$instance->updated_at = time();
$instance->save();
CloudPlacementService::commit(
$order, (int) $instance->id, $confirmedPublicIpCidr
$order,
(int) $instance->id,
$confirmedPublicNetwork->toArray()
);
// Seed the independent runtime observation immediately after
// provisioning. If the Agent returned a trusted power

@ -83,13 +83,16 @@ $assert(str_contains($placement,
"CloudResourceReservation::where('order_id', (int) \$order->id)->exists()")
&& !str_contains($placement, 'restoreExisting('),
'Final placement capacity must use a current locking read after the host sentinel, not a repeatable-read aggregate snapshot.');
$assert(str_contains($worker, '$requestedPublicIpCidr')
&& str_contains($worker, '$confirmedPublicIpCidr')
&& str_contains($worker, "'Agent 成功结果与预留公网 IP 不一致,必须人工核查'")
$assert(str_contains($worker, '$frozenPublicNetwork')
&& str_contains($worker, '$requestedPublicNetwork')
&& str_contains($worker, '$confirmedPublicNetwork')
&& str_contains($worker,
"'Agent 成功结果与预留双栈公网不一致,必须人工核查'")
&& str_contains($placement,
'(string) $ip->address . \'/\' . (int) $ip->prefix_length')
&& str_contains($placement, '$confirmedPublicIpCidr'),
'Create reconciliation must match requested, confirmed, and reserved public IPs before committing the ledger.');
'CloudPublicNetworkAllocationService::commitBundle(')
&& str_contains($placement, '$confirmed->fingerprint()')
&& str_contains($placement, '$allocated->fingerprint()'),
'Create reconciliation must match frozen, requested, confirmed, and reserved dual-stack networks before committing the ledger.');
$refundStart = strpos($createFinalizer,
'public static function refundAndReleaseLocked(');
$refundEnd = $refundStart === false ? false

@ -184,6 +184,29 @@ namespace {
$table->integer('user_id');
$table->string('status');
});
$capsule->schema('default')->create('cloud_orders',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('offer_id');
$table->integer('resource_pool_id');
$table->integer('host_id');
$table->integer('reservation_id');
$table->text('spec_json');
});
$capsule->schema('default')->create('cloud_resource_reservations',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('order_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('resource_pool_id');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('instance_id')->nullable();
$table->string('operation_id');
$table->string('state');
});
$now = time();
foreach ([
41 => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
@ -191,11 +214,58 @@ namespace {
43 => 'cccccccccccccccccccccccccccccccc',
44 => 'dddddddddddddddddddddddddddddddd',
] as $id => $operationId) {
$publicNetwork = [
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('1', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => '8.8.8.' . $id . '/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('2', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => '2404:c140:156:3a::' . $id . '/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => true,
],
'dns_servers' => [
'1.1.1.1',
'2606:4700:4700::1111',
],
];
$reservationId = 1000 + $id;
Capsule::table('cloud_orders')->insert([
'id' => $id,
'user_id' => 99,
'offer_id' => 1,
'resource_pool_id' => 1,
'host_id' => 7,
'reservation_id' => $reservationId,
'spec_json' => json_encode([
'source' => 'cloud',
'public_network' => $publicNetwork,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES),
]);
Capsule::table('cloud_resource_reservations')->insert([
'id' => $reservationId,
'order_id' => $id,
'backup_restore_id' => null,
'offer_id' => 1,
'resource_pool_id' => 1,
'host_id' => 7,
'user_id' => 99,
'instance_id' => null,
'operation_id' => $operationId,
'state' => 'uncertain',
]);
Capsule::table('cloud_jobs')->insert([
'id' => $id, 'operation_id' => $operationId, 'host_id' => 7,
'request_idempotency_key' => $operationId,
'request_fingerprint' => hash('sha256', $operationId),
'kind' => 'create', 'order_id' => 100,
'kind' => 'create', 'order_id' => $id,
'phase' => 'terminal', 'outcome' => 'failed',
'status' => 'failed', 'dispatched_at' => $now - 90,
'dispatch_started_at' => $now - 100,
@ -215,16 +285,11 @@ namespace {
'memory_mib' => 2048,
'disk_gib' => 40,
'bandwidth_mbps' => 100,
'network' => 'bridge:br0',
'public_network' => $publicNetwork,
'template_id' => 'debian-13',
'template_revision' => 1,
'template_generation_token' => str_repeat('1', 32),
'root_password' => 'StrongPassword!123',
'public_pool_key' => str_repeat('2', 32),
'public_pool_cidr' => '203.0.113.0/24',
'public_ip_cidr' => '203.0.113.41/24',
'gateway' => '203.0.113.1',
'dns_servers' => ['1.1.1.1'],
'platform_network_policy_snapshot' => [
'schema_version' => 1,
],

@ -128,6 +128,29 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_orders',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('offer_id');
$table->integer('resource_pool_id');
$table->integer('host_id');
$table->integer('reservation_id');
$table->text('spec_json');
});
$schema->create('cloud_resource_reservations',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('order_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('resource_pool_id');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('instance_id')->nullable();
$table->string('operation_id');
$table->string('state');
});
$now = time();
$createBody = static function (string $operationId, int $suffix): array {
@ -139,16 +162,33 @@ namespace {
'memory_mib' => 2048,
'disk_gib' => 40,
'bandwidth_mbps' => 100,
'network' => 'bridge:br0',
'public_network' => [
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('2', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => '8.8.8.' . $suffix . '/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('3', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => '2404:c140:156:3a::'
. $suffix . '/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => true,
],
'dns_servers' => [
'1.1.1.1',
'2606:4700:4700::1111',
],
],
'template_id' => 'debian-13',
'template_revision' => 1,
'template_generation_token' => str_repeat('1', 32),
'root_password' => 'Identity-test9!Pass',
'public_pool_key' => str_repeat('2', 32),
'public_pool_cidr' => '203.0.113.0/24',
'public_ip_cidr' => '203.0.113.' . $suffix . '/24',
'gateway' => '203.0.113.1',
'dns_servers' => ['1.1.1.1'],
'platform_network_policy_snapshot' => ['schema_version' => 1],
];
};
@ -156,11 +196,38 @@ namespace {
int $id,
string $operationId
) use ($createBody, $now): void {
$orderId = 1000 + $id;
$reservationId = 2000 + $id;
$body = $createBody($operationId, 20 + $id);
Capsule::table('cloud_orders')->insert([
'id' => $orderId,
'user_id' => 11,
'offer_id' => 1,
'resource_pool_id' => 1,
'host_id' => 7,
'reservation_id' => $reservationId,
'spec_json' => json_encode([
'source' => 'cloud',
'public_network' => $body['public_network'],
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES),
]);
Capsule::table('cloud_resource_reservations')->insert([
'id' => $reservationId,
'order_id' => $orderId,
'backup_restore_id' => null,
'offer_id' => 1,
'resource_pool_id' => 1,
'host_id' => 7,
'user_id' => 11,
'instance_id' => null,
'operation_id' => $operationId,
'state' => 'held',
]);
Capsule::table('cloud_jobs')->insert([
'id' => $id,
'host_id' => 7,
'user_id' => 11,
'order_id' => 1000 + $id,
'order_id' => $orderId,
'operation_id' => $operationId,
'execution_mode' => 'agent',
'kind' => 'create',
@ -172,7 +239,7 @@ namespace {
'sealed_payload' => CloudSecrets::encrypt([
'method' => 'POST',
'request_target' => '/v1/vms',
'body' => $createBody($operationId, 20 + $id),
'body' => $body,
'credential' => [
'password' => 'Identity-test9!Pass',
'login_name' => 'root',

@ -18,6 +18,9 @@ $storage = $read(
$console = $read('app/Services/Cloud/CloudConsoleTicketService.php');
$hostController = $read('app/Controllers/CloudAdminController.php');
$placement = $read('app/Services/Cloud/CloudPlacementService.php');
$publicNetwork = $read(
'app/Services/Cloud/CloudPublicNetworkAllocationService.php'
);
$restore = $read('app/Services/Cloud/CloudBackupService.php');
$migration = $read(
'app/Services/Cloud/CloudInstanceMigrationService.php'
@ -44,7 +47,9 @@ $assert(str_contains($hostController, "'default_network'")
'Compatibility host metadata is missing or still invalidates Agent state.');
$assert(str_contains($placement,
'$payload[\'body\'][\'network\'] = (string) $attachment->network_selector;')
"\$payload['body']['public_network'] = \$publicNetwork->toArray();")
&& str_contains($publicNetwork,
"'network_selector' => (string) \$attachment->network_selector")
&& str_contains($restore,
"'network' => (string) \$network['network']")
&& str_contains($migration,

@ -0,0 +1,251 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudPlacementNetworkService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('default_network')->default('bridge:br0');
$table->string('endpoint')->default('https://host.invalid');
});
$schema->create('cloud_host_agents', static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->boolean('enabled');
$table->integer('revision');
$table->integer('tested_revision');
$table->string('last_test_status');
$table->text('network_selectors_json');
$table->text('public_network_capabilities_json');
});
$schema->create('cloud_host_network_attachments', static function (
Blueprint $table
): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('line_id');
$table->string('network_selector');
$table->string('state');
$table->integer('priority');
$table->string('verification_state');
$table->integer('verified_agent_revision');
$table->integer('last_verified_at');
});
$schema->create('cloud_public_ip_pools', static function (
Blueprint $table
): void {
$table->increments('id');
$table->string('pool_key');
$table->integer('host_id');
$table->integer('network_attachment_id');
$table->integer('address_family');
$table->string('cidr');
$table->string('gateway');
$table->boolean('gateway_on_link');
$table->integer('guest_prefix_length');
$table->text('dns_servers_json');
$table->text('reserved_ips_json');
$table->string('allocation_start')->nullable();
$table->string('allocation_end')->nullable();
$table->integer('max_allocations');
$table->string('state');
$table->integer('priority');
$table->integer('desired_revision');
$table->integer('observed_revision');
$table->string('sync_state');
});
$schema->create('cloud_public_ips', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('public_ip_pool_id');
$table->integer('address_family');
$table->string('address');
$table->integer('prefix_length');
$table->string('state');
$table->integer('reservation_id')->nullable();
$table->integer('instance_id')->nullable();
$table->string('operation_id')->nullable();
});
Capsule::table('cloud_hosts')->insert(['id' => 1]);
Capsule::table('cloud_host_agents')->insert([
'host_id' => 1,
'enabled' => 1,
'revision' => 5,
'tested_revision' => 5,
'last_test_status' => 'healthy',
'network_selectors_json' => '["bridge:br0","bridge:br1"]',
'public_network_capabilities_json' => json_encode([
'contract' => 1,
'dual_stack_required' => true,
'project_owned_filter' => true,
'ndp_guard' => true,
], JSON_THROW_ON_ERROR),
]);
Capsule::table('cloud_host_network_attachments')->insert([
[
'id' => 10,
'host_id' => 1,
'line_id' => 7,
'network_selector' => 'bridge:br0',
'state' => 'active',
'priority' => 0,
'verification_state' => 'verified',
'verified_agent_revision' => 5,
'last_verified_at' => time(),
],
[
'id' => 11,
'host_id' => 1,
'line_id' => 7,
'network_selector' => 'bridge:br1',
'state' => 'active',
'priority' => 1,
'verification_state' => 'verified',
'verified_agent_revision' => 5,
'last_verified_at' => time(),
],
]);
$common = [
'host_id' => 1,
'state' => 'active',
'priority' => 0,
'desired_revision' => 1,
'observed_revision' => 1,
'sync_state' => 'applied',
'reserved_ips_json' => '[]',
];
Capsule::table('cloud_public_ip_pools')->insert([
array_merge($common, [
'id' => 100,
'pool_key' => str_repeat('a', 32),
'network_attachment_id' => 10,
'address_family' => 4,
'cidr' => '8.8.8.0/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => 0,
'guest_prefix_length' => 24,
'dns_servers_json' => '["1.1.1.1"]',
'allocation_start' => null,
'allocation_end' => null,
'max_allocations' => 0,
]),
array_merge($common, [
'id' => 200,
'pool_key' => str_repeat('b', 32),
'network_attachment_id' => 11,
'address_family' => 6,
'cidr' => '2404:c140:156:3a::/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => 1,
'guest_prefix_length' => 64,
'dns_servers_json' => '["2606:4700:4700::1111"]',
'allocation_start' => '2404:c140:156:3a::10',
'allocation_end' => '2404:c140:156:3a::ff',
'max_allocations' => 2,
]),
]);
Capsule::table('cloud_public_ips')->insert([
'id' => 1,
'host_id' => 1,
'public_ip_pool_id' => 100,
'address_family' => 4,
'address' => '8.8.8.10',
'prefix_length' => 24,
'state' => 'available',
]);
$candidate = collect([
(object) ['id' => 1, 'resource_pool_line_id' => 7],
]);
$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts(
$candidate
) === [],
'Pools split across two attachments were advertised as one dual-stack path.');
Capsule::table('cloud_public_ip_pools')->where('id', 200)->update([
'network_attachment_id' => 10,
]);
$connection = Capsule::connection('default');
$connection->flushQueryLog();
$connection->enableQueryLog();
$available = CloudPlacementNetworkService::advisoryDualStackAvailableHosts(
$candidate
);
$queryCount = count($connection->getQueryLog());
$connection->disableQueryLog();
$assert($available === [1 => true] && $queryCount <= 5,
'A sparse IPv6 pool with capacity was not paired with available IPv4.');
Capsule::table('cloud_host_agents')->where('host_id', 1)->update([
'public_network_capabilities_json' => '{}',
]);
$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts(
$candidate
) === [],
'A host without current guarded-network capability remained sellable.');
Capsule::table('cloud_host_agents')->where('host_id', 1)->update([
'public_network_capabilities_json' => json_encode([
'contract' => 1,
'dual_stack_required' => true,
'project_owned_filter' => true,
'ndp_guard' => true,
], JSON_THROW_ON_ERROR),
]);
Capsule::table('cloud_public_ip_pools')->where('id', 100)->update([
'observed_revision' => 2,
]);
$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts(
$candidate
) === [],
'A pool ahead of its desired revision remained visible as sellable.');
Capsule::table('cloud_public_ip_pools')->where('id', 100)->update([
'observed_revision' => 1,
]);
Capsule::table('cloud_public_ips')->insert([
[
'id' => 2,
'host_id' => 1,
'public_ip_pool_id' => 200,
'address_family' => 6,
'address' => '2404:c140:156:3a::10',
'prefix_length' => 64,
'state' => 'assigned',
'reservation_id' => null,
'instance_id' => 90,
'operation_id' => null,
],
[
'id' => 3,
'host_id' => 1,
'public_ip_pool_id' => 200,
'address_family' => 6,
'address' => '2404:c140:156:3a::11',
'prefix_length' => 64,
'state' => 'changing',
'reservation_id' => 91,
'instance_id' => null,
'operation_id' => str_repeat('c', 32),
],
]);
$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts(
$candidate
) === [],
'A changing sparse IPv6 address was omitted from provisioning capacity.');
echo "Dual-stack placement advisory tests passed.\n";

File diff suppressed because it is too large Load Diff

@ -136,7 +136,28 @@ namespace {
$instance->expires_at = $now + 30 * 86400;
$instance->spec_json = json_encode([
'region' => 'HongKong',
'public_ip_cidr' => $ip . '/24',
'public_network' => [
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('1', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => $ip . '/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('2', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => '2404:c140:156:3a::11/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => true,
],
'dns_servers' => [
'1.1.1.1',
'2606:4700:4700::1111',
],
],
'os_name' => 'AlmaLinux 10',
'login_name' => 'root',
// Secrets in old snapshots must never be forwarded to a template.
@ -178,7 +199,7 @@ namespace {
return $mail;
};
$renewalInstance = $newInstance(1, 'renewal-vm', '203.0.113.10');
$renewalInstance = $newInstance(1, 'renewal-vm', '8.8.8.10');
$renewal = $newInvoice('VC-MAIL-RENEWAL', 'renewal', 1, $renewalInstance);
$renewalMail = $newMail($renewal, 'renewal_due');
$assert(CloudInvoiceService::deliverReminders(1) === 1
@ -191,7 +212,7 @@ namespace {
'实例续费账单已生成'),
'An open automatic renewal bill was not delivered and marked sent.');
$provisionedInstance = $newInstance(1, 'ready-vm', '203.0.113.11');
$provisionedInstance = $newInstance(1, 'ready-vm', '8.8.8.11');
$order = new CloudOrder();
$order->user_id = 1;
$order->instance_id = $provisionedInstance->id;
@ -217,13 +238,13 @@ namespace {
&& ($provisionMessage['emailType'] ?? null) === 'cloud_provision_success'
&& str_contains((string) ($provisionMessage['subject'] ?? ''), '实例开通成功')
&& ($provisionMessage['data']['instance_name'] ?? null) === 'ready-vm'
&& ($provisionMessage['data']['public_ip'] ?? null) === '203.0.113.11'
&& ($provisionMessage['data']['public_ip'] ?? null) === '8.8.8.11'
&& !array_key_exists('root_password', $provisionMessage['data'] ?? [])
&& !array_key_exists('private_key', $provisionMessage['data'] ?? []),
'The provision-success message is incomplete or contains credentials.');
Mail::$accepted = false;
$retryInstance = $newInstance(1, 'retry-vm', '203.0.113.12');
$retryInstance = $newInstance(1, 'retry-vm', '8.8.8.12');
$retryInvoice = $newInvoice('VC-MAIL-RETRY', 'renewal', 1, $retryInstance);
$retryMail = $newMail($retryInvoice, 'renewal_due');
$assert(CloudInvoiceService::deliverReminders(1) === 0
@ -239,7 +260,7 @@ namespace {
&& count(Mail::$messages) === $sentBeforeRetryProbe,
'A terminal failed SMTP message was retried.');
$otherInstance = $newInstance(2, 'other-tenant-vm', '203.0.113.13');
$otherInstance = $newInstance(2, 'other-tenant-vm', '8.8.8.13');
$corruptInvoice = $newInvoice('VC-MAIL-CROSS-TENANT', 'renewal', 1,
$otherInstance);
$corruptMail = $newMail($corruptInvoice, 'renewal_due');

@ -97,7 +97,6 @@ $assert(is_string($jobs)
'Network-change enqueue no longer locks and persists the attachment/pool/address ledger identity.');
$assert(is_string($worker)
&& str_contains($worker, 'CloudPlacementService::finishNetworkChange')
&& str_contains($worker, '$confirmedPublicPoolKey')
&& str_contains($worker, '$confirmedPoolKey')
&& str_contains($worker, '$sourceAttachmentId')
&& str_contains($worker, '$targetAttachmentId')
@ -111,9 +110,10 @@ $assert(is_string($placement)
&& str_contains($placement, 'cloud_host_resource_pool_memberships as pool_membership')
&& !str_contains($placement, 'eligible_host.host')
&& !str_contains($placement, "->where('cloud_hosts.resource_pool_id', \$poolId)")
&& str_contains($placement, '$reservation->network_attachment_id = $selectedAttachment->id')
&& str_contains($placement, '$reservation->public_ip_pool_id = $selectedPool->id')
&& str_contains($placement, '$payload[\'body\'][\'public_pool_key\']')
&& str_contains($placement,
'CloudPublicNetworkAllocationService::reserveBundle(')
&& str_contains($placement,
"\$payload['body']['public_network'] = \$publicNetwork->toArray()")
&& str_contains($placement, '$reservation->public_ip_id = $targetIpId')
&& str_contains($placement,
'$reservation->network_attachment_id = $targetAttachmentId')
@ -129,7 +129,11 @@ $assert(is_string($placement)
&& str_contains($placement, '$target->state = \'assigned\'')
&& str_contains($placement, '$target->state = \'uncertain\'')
&& str_contains($placement, '$source->state = \'available\'')
&& str_contains($placement, 'lockedHostAndReservation')
&& str_contains($finishMethod,
"CloudHost::where('id', (int) \$instance->host_id)")
&& str_contains($finishMethod,
"CloudResourceReservation::where('id',")
&& substr_count($finishMethod, 'lockForUpdate()') >= 4
&& str_contains($placement, '(string) $reservation->state === \'committed\'')
&& str_contains($placement, '$ip->instance_id ?? 0'),
'Placement no longer uses membership/pool-scoped allocation or enforce atomic multi-pool ledger swaps.');

@ -379,14 +379,16 @@ namespace {
$schema->create('cloud_resource_reservations',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_restore_id');
$table->integer('order_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('host_id');
$table->integer('user_id');
$table->integer('resource_pool_id')->nullable();
$table->integer('network_attachment_id')->nullable();
$table->integer('public_ip_pool_id')->nullable();
$table->string('operation_id');
$table->integer('public_ip_id');
$table->integer('public_ip_id')->nullable();
$table->integer('instance_id')->nullable();
$table->integer('cpu_cores');
$table->integer('memory_mib');
@ -398,6 +400,16 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_orders',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('offer_id');
$table->integer('resource_pool_id');
$table->integer('host_id');
$table->integer('reservation_id');
$table->text('spec_json');
});
$schema->create('cloud_public_ips',
static function (Blueprint $table): void {
$table->increments('id');
@ -2657,6 +2669,25 @@ namespace {
'expected_action' => 'restore-backup:' . $restoreBackupKey,
'expected_resource' => $restoreUuid,
];
$createPublicNetwork = [
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('5', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => '8.8.8.30/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('6', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => '2404:c140:156:3a::30/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => true,
],
'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'],
];
$createRecord = $insertJob(
'create',
static fn (int $jobId, string $operationId): array => [
@ -2670,16 +2701,11 @@ namespace {
'memory_mib' => 2048,
'disk_gib' => 40,
'bandwidth_mbps' => 100,
'network' => 'bridge:br0',
'template_id' => 'debian-13',
'template_revision' => 1,
'template_generation_token' => str_repeat('4', 32),
'root_password' => 'MatrixPassword!123',
'public_pool_key' => str_repeat('5', 32),
'public_pool_cidr' => '203.0.113.0/24',
'public_ip_cidr' => '203.0.113.30/24',
'gateway' => '203.0.113.1',
'dns_servers' => ['1.1.1.1'],
'public_network' => $createPublicNetwork,
'platform_network_policy_snapshot' => [
'schema_version' => 1,
],
@ -2702,6 +2728,39 @@ namespace {
null,
9001
);
$createReservationId = 9101;
Capsule::table('cloud_orders')->insert([
'id' => 9001,
'user_id' => $ownerId,
'offer_id' => 1,
'resource_pool_id' => 1,
'host_id' => $hostId,
'reservation_id' => $createReservationId,
'spec_json' => json_encode([
'source' => 'cloud',
'public_network' => $createPublicNetwork,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES),
]);
Capsule::table('cloud_resource_reservations')->insert([
'id' => $createReservationId,
'order_id' => 9001,
'backup_restore_id' => null,
'offer_id' => 1,
'host_id' => $hostId,
'user_id' => $ownerId,
'resource_pool_id' => 1,
'network_attachment_id' => null,
'public_ip_pool_id' => null,
'operation_id' => $createRecord['operation_id'],
'public_ip_id' => null,
'instance_id' => null,
'cpu_cores' => 2,
'memory_mib' => 2048,
'disk_gib' => 40,
'state' => 'uncertain',
'created_at' => $now - 180,
'updated_at' => $now - 20,
]);
$dedicatedFixtures['create'] = $createRecord + [
'expected_action' => 'create-vm',
];
@ -3156,6 +3215,21 @@ namespace {
$identity['resource_id']
) === 1,
'Create identity lost its deterministic UUID scope.');
$tamperedCreate = $fixture['payload'];
$tamperedCreate['body']['public_network']['ipv6'][
'address_cidr'
] = '2404:c140:156:3a::31/64';
$tamperRejected = false;
try {
CloudOperationRecoveryIdentity::expectedFromPayload(
$fixture['job'],
$tamperedCreate
);
} catch (CloudError $error) {
$tamperRejected = $error->httpStatus === 409;
}
$assert($tamperRejected,
'Create recovery accepted a different dual-stack snapshot.');
$projection = $projectionMethod->invoke(null, [
'creation_absent' => true,
'managed_artifacts_absent' => true,

@ -0,0 +1,121 @@
<?php
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$contents = file_get_contents($root . '/' . $path);
if (!is_string($contents)) {
throw new RuntimeException('Unreadable contract source: ' . $path);
}
return $contents;
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$order = $read('app/Services/Cloud/CloudOrderService.php');
$placement = $read('app/Services/Cloud/CloudPlacementService.php');
$worker = $read('app/Services/Cloud/CloudWorkerService.php');
$invoice = $read('app/Services/Cloud/CloudInvoiceService.php');
$recovery = $read('app/Services/Cloud/CloudOperationRecoveryIdentity.php');
$reservation = $read('app/Models/CloudResourceReservation.php');
$assert(!str_contains($order, "'public_pool_key' => ''")
&& !str_contains($order, "'public_pool_cidr' => ''")
&& !str_contains($order, "'public_ip_cidr' => ''")
&& !str_contains($order, "'gateway' => ''"),
'Unpaid orders still define the retired scalar public-network contract.');
$snapshotGate = strpos($order,
"if (\$source === 'deployment_snapshot') {");
$purchaseTransaction = strpos($order,
"return (new User())->getConnection()->transaction(");
$assert($snapshotGate !== false && $purchaseTransaction !== false
&& $snapshotGate < $purchaseTransaction
&& str_contains(substr($order, $snapshotGate,
$purchaseTransaction - $snapshotGate),
'云快照创建实例正在升级双栈网络,暂不可用'),
'Deferred cloud-snapshot provisioning is not blocked before billing state is created.');
$paymentStart = strpos($order,
'public static function queuePaidProvision(');
$paymentPlacement = strpos($order,
'CloudPlacementService::reserve(',
$paymentStart === false ? 0 : $paymentStart);
$paymentGate = $paymentStart === false || $paymentPlacement === false
? '' : substr($order, $paymentStart,
$paymentPlacement - $paymentStart);
$assert(str_contains($paymentGate,
"if (\$source === 'deployment_snapshot')")
&& str_contains($paymentGate,
'云快照创建实例正在升级双栈网络,暂不可用'),
'A pre-existing unpaid cloud-snapshot order can cross the payment boundary.');
$compactOrder = preg_replace('/\s+/', ' ', $order) ?? $order;
$assert(str_contains($compactOrder,
"\$orderSpec['public_network'] = \$placement['public_network']->toArray();")
&& str_contains($order,
"\$placement['payload']['body']['public_network']"),
'Paid order and dispatched job do not freeze the same public-network snapshot.');
foreach (['reserveBundle(', 'commitBundle(', 'fenceBundle(',
'releaseBundle(', 'releaseCommittedBundle('] as $call) {
$assert(preg_match(
'/CloudPublicNetworkAllocationService::\s*'
. preg_quote($call, '/') . '/',
$placement
) === 1,
'Provisioning placement does not use bundle operation: ' . $call);
}
$assert(str_contains($placement,
"\$payload['body']['public_network'] = \$publicNetwork->toArray();")
&& str_contains($placement,
"'public_network' => \$publicNetwork"),
'Placement does not return and dispatch one immutable dual-stack snapshot.');
$assert(!str_contains($reservation,
"foreach (['network_attachment_id', 'public_ip_pool_id',")
&& str_contains($reservation, 'cloud_resource_reservation_ips'),
'Resource reservations still treat one public_ip_id as network authority.');
$compactWorker = preg_replace('/\s+/', ' ', $worker) ?? $worker;
$workerFinalizationStart = strpos($worker,
'$provisionInvoice = CloudInvoice::where(');
$workerCommit = strpos($worker, 'CloudPlacementService::commit(',
$workerFinalizationStart === false ? 0 : $workerFinalizationStart);
$workerPreCommit = $workerFinalizationStart === false || $workerCommit === false
? '' : substr($worker, $workerFinalizationStart,
$workerCommit - $workerFinalizationStart);
$assert($workerPreCommit !== ''
&& !str_contains($workerPreCommit, 'CloudResourceReservation::where('),
'Create success locks the reservation before canonical placement commit.');
$tryHostStart = strpos($placement, 'private static function tryHost(');
$allocatorCall = strpos(
$placement,
'CloudPublicNetworkAllocationService::reserveBundle(',
$tryHostStart === false ? 0 : $tryHostStart
);
$preAllocator = $tryHostStart === false || $allocatorCall === false
? '' : substr($placement, $tryHostStart,
$allocatorCall - $tryHostStart);
$assert($preAllocator !== ''
&& !str_contains($preAllocator, 'lockedCandidates(')
&& !str_contains($preAllocator, 'hasCompleteDualStackCandidate('),
'tryHost can bypass the canonical allocator through a stale precheck.');
$assert(substr_count($worker,
'CloudPublicNetworkSnapshot::fromArray(') >= 2
&& str_contains($compactWorker,
"\$instanceSpec['public_network'] = \$confirmedPublicNetwork->toArray();")
&& str_contains($worker,
"\$requestedPublicNetwork->fingerprint()")
&& str_contains($worker,
"\$confirmedPublicNetwork->fingerprint()"),
'Create finalization does not compare and persist the exact dual-stack identity.');
$assert(str_contains($invoice, 'CloudPublicNetworkSnapshot::fromArray(')
&& str_contains($invoice, "\$spec['public_network']")
&& !str_contains($invoice, "\$spec['public_ip_cidr']"),
'Provision-success mail still treats scalar public_ip_cidr as authoritative.');
$assert(substr_count($recovery,
'CloudPublicNetworkSnapshot::fromArray(') >= 2
&& str_contains($recovery, "\$orderSpec['public_network']")
&& str_contains($recovery, "\$body['public_network']"),
'Create recovery identity is not bound to the frozen dual-stack snapshot.');
echo "Dual-stack provisioning call-chain contract passed.\n";

@ -0,0 +1,379 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudInstance;
use App\Models\CloudOrder;
use App\Services\Cloud\CloudPlacementService;
use App\Services\Cloud\CloudPublicNetworkAllocationService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$rejects = static function (callable $callback, string $message): void {
try {
$callback();
} catch (Throwable) {
return;
}
throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
});
$schema->create('cloud_host_agents', static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->boolean('enabled');
$table->integer('revision');
$table->integer('tested_revision');
$table->string('last_test_status');
$table->text('network_selectors_json');
$table->text('public_network_capabilities_json');
});
$schema->create('cloud_host_network_attachments', static function (
Blueprint $table
): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('line_id');
$table->string('network_selector');
$table->string('state');
$table->integer('priority')->default(0);
$table->string('verification_state');
$table->integer('verified_agent_revision');
$table->integer('last_verified_at');
});
$schema->create('cloud_public_ip_pools', static function (
Blueprint $table
): void {
$table->increments('id');
$table->string('pool_key');
$table->integer('host_id');
$table->integer('network_attachment_id');
$table->integer('address_family');
$table->string('cidr');
$table->string('gateway');
$table->boolean('gateway_on_link');
$table->integer('guest_prefix_length');
$table->text('dns_servers_json');
$table->text('reserved_ips_json');
$table->string('allocation_start')->nullable();
$table->string('allocation_end')->nullable();
$table->string('allocation_cursor')->nullable();
$table->integer('max_allocations');
$table->string('state');
$table->integer('priority')->default(0);
$table->integer('desired_revision');
$table->integer('observed_revision');
$table->string('sync_state');
});
$schema->create('cloud_public_ips', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('public_ip_pool_id');
$table->integer('address_family');
$table->string('address');
$table->binary('address_binary');
$table->integer('prefix_length');
$table->string('state');
$table->integer('reservation_id')->nullable();
$table->integer('instance_id')->nullable();
$table->string('operation_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['address_family', 'address_binary']);
});
$schema->create('cloud_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('offer_id');
$table->integer('resource_pool_id');
$table->integer('host_id');
$table->integer('reservation_id');
});
$schema->create('cloud_resource_reservations', static function (
Blueprint $table
): void {
$table->increments('id');
$table->string('reservation_key');
$table->string('operation_id');
$table->integer('order_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('resource_pool_id');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('instance_id')->nullable();
$table->integer('network_attachment_id')->nullable();
$table->integer('public_ip_pool_id')->nullable();
$table->integer('public_ip_id')->nullable();
$table->integer('cpu_cores');
$table->integer('memory_mib');
$table->integer('disk_gib');
$table->string('state');
$table->integer('expires_at')->nullable();
$table->integer('released_at')->nullable();
$table->string('release_reason')->default('');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_instance_migrations', static function (
Blueprint $table
): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('restore_id');
$table->integer('source_host_id');
$table->integer('source_reservation_id');
$table->integer('target_host_id');
$table->integer('target_reservation_id');
$table->string('state');
});
$schema->create('cloud_resource_reservation_ips', static function (
Blueprint $table
): void {
$table->increments('id');
$table->integer('reservation_id');
$table->integer('address_family');
$table->integer('network_attachment_id');
$table->integer('public_ip_pool_id');
$table->integer('public_ip_id');
$table->string('operation_id');
$table->string('state');
$table->integer('created_at');
$table->integer('updated_at');
$table->integer('released_at')->nullable();
$table->string('release_reason')->default('');
$table->unique(['reservation_id', 'address_family']);
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('order_id')->nullable();
$table->integer('resource_pool_id');
$table->integer('reservation_id');
$table->string('status');
});
Capsule::table('cloud_hosts')->insert(['id' => 1]);
Capsule::table('cloud_host_agents')->insert([
'host_id' => 1,
'enabled' => 1,
'revision' => 1,
'tested_revision' => 1,
'last_test_status' => 'healthy',
'network_selectors_json' => '["bridge:br0"]',
'public_network_capabilities_json' => json_encode([
'contract' => 1,
'dual_stack_required' => true,
'project_owned_filter' => true,
'ndp_guard' => true,
], JSON_THROW_ON_ERROR),
]);
Capsule::table('cloud_host_network_attachments')->insert([
'id' => 10,
'host_id' => 1,
'line_id' => 7,
'network_selector' => 'bridge:br0',
'state' => 'active',
'priority' => 0,
'verification_state' => 'verified',
'verified_agent_revision' => 1,
'last_verified_at' => time(),
]);
$poolCommon = [
'host_id' => 1,
'network_attachment_id' => 10,
'state' => 'active',
'priority' => 0,
'desired_revision' => 1,
'observed_revision' => 1,
'sync_state' => 'applied',
'reserved_ips_json' => '[]',
];
Capsule::table('cloud_public_ip_pools')->insert([
array_merge($poolCommon, [
'id' => 100,
'pool_key' => str_repeat('a', 32),
'address_family' => 4,
'cidr' => '8.8.8.0/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => 0,
'guest_prefix_length' => 24,
'dns_servers_json' => '["1.1.1.1"]',
'allocation_start' => null,
'allocation_end' => null,
'allocation_cursor' => null,
'max_allocations' => 0,
]),
array_merge($poolCommon, [
'id' => 200,
'pool_key' => str_repeat('b', 32),
'address_family' => 6,
'cidr' => '2404:c140:156:3a::/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => 1,
'guest_prefix_length' => 64,
'dns_servers_json' => '["2606:4700:4700::1111"]',
'allocation_start' => '2404:c140:156:3a::10',
'allocation_end' => '2404:c140:156:3a::ff',
'allocation_cursor' => null,
'max_allocations' => 8,
]),
]);
$now = time();
foreach (range(10, 13) as $suffix) {
$address = '8.8.8.' . $suffix;
Capsule::table('cloud_public_ips')->insert([
'host_id' => 1,
'public_ip_pool_id' => 100,
'address_family' => 4,
'address' => $address,
'address_binary' => inet_pton($address),
'prefix_length' => 24,
'state' => 'available',
'created_at' => $now,
'updated_at' => $now,
]);
}
$reserve = static function (int $id, string $operationId): array {
Capsule::table('cloud_orders')->insert([
'id' => $id,
'user_id' => 40,
'offer_id' => 50,
'resource_pool_id' => 60,
'host_id' => 1,
'reservation_id' => 1000 + $id,
]);
Capsule::table('cloud_resource_reservations')->insert([
'id' => 1000 + $id,
'reservation_key' => str_repeat((string) ($id % 10), 32),
'operation_id' => $operationId,
'order_id' => $id,
'backup_restore_id' => null,
'offer_id' => 50,
'resource_pool_id' => 60,
'host_id' => 1,
'user_id' => 40,
'instance_id' => null,
'network_attachment_id' => null,
'public_ip_pool_id' => null,
'public_ip_id' => null,
'cpu_cores' => 2,
'memory_mib' => 2048,
'disk_gib' => 20,
'state' => 'held',
'expires_at' => null,
'released_at' => null,
'release_reason' => '',
'created_at' => time(),
'updated_at' => time(),
]);
return [
CloudOrder::findOrFail($id),
CloudPublicNetworkAllocationService::reserveBundle(
1,
7,
1000 + $id,
$operationId
),
];
};
[$committedOrder, $committedSnapshot] = $reserve(1, str_repeat('1', 32));
CloudPlacementService::commit(
$committedOrder,
900,
$committedSnapshot->toArray()
);
$assert(Capsule::table('cloud_resource_reservations')->where('id', 1001)
->value('state') === 'committed'
&& Capsule::table('cloud_public_ips')->where('instance_id', 900)
->where('state', 'assigned')->count() === 2,
'Provisioning commit did not bind the complete public-network bundle.');
CloudPlacementService::markUncertain($committedOrder->fresh());
$assert(Capsule::table('cloud_resource_reservations')->where('id', 1001)
->value('state') === 'committed'
&& Capsule::table('cloud_public_ips')->where('instance_id', 900)
->where('state', 'assigned')->count() === 2,
'A late uncertainty marker rolled back a committed network bundle.');
[$failedOrder] = $reserve(2, str_repeat('2', 32));
CloudPlacementService::markUncertain($failedOrder);
$assert(Capsule::table('cloud_resource_reservations')->where('id', 1002)
->value('state') === 'uncertain'
&& Capsule::table('cloud_public_ips')->where('reservation_id', 1002)
->where('state', 'uncertain')->count() === 2,
'Unknown effect did not fence the complete provisioning bundle.');
CloudPlacementService::release($failedOrder, 'confirmed-not-applied');
$assert(Capsule::table('cloud_resource_reservations')->where('id', 1002)
->value('state') === 'released'
&& Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 1002)->where('state', 'released')->count() === 2
&& Capsule::table('cloud_public_ips')->where('reservation_id', 1002)
->count() === 0,
'Confirmed non-application did not release both address families.');
[$recoveredOrder, $recoveredSnapshot] = $reserve(3, str_repeat('3', 32));
CloudPlacementService::markUncertain($recoveredOrder);
CloudPlacementService::commit(
$recoveredOrder,
901,
$recoveredSnapshot->toArray()
);
$assert(Capsule::table('cloud_resource_reservations')->where('id', 1003)
->value('state') === 'committed'
&& Capsule::table('cloud_public_ips')->where('instance_id', 901)
->where('state', 'assigned')->count() === 2,
'A recovered success did not commit its previously fenced bundle.');
[$mismatchOrder, $mismatchSnapshot] = $reserve(4, str_repeat('4', 32));
$wrongSnapshot = $mismatchSnapshot->toArray();
$wrongSnapshot['ipv4']['address_cidr'] = '8.8.8.99/24';
$rejects(static fn () => CloudPlacementService::commit(
$mismatchOrder,
902,
$wrongSnapshot
), 'A create receipt committed a different dual-stack identity.');
$assert(Capsule::table('cloud_resource_reservations')->where('id', 1004)
->value('state') === 'held'
&& Capsule::table('cloud_public_ips')->where('reservation_id', 1004)
->where('state', 'reserved')->count() === 2,
'Rejecting a mismatched receipt partially committed the bundle.');
Capsule::table('cloud_instances')->insert([
'id' => 900,
'host_id' => 1,
'order_id' => 1,
'resource_pool_id' => 60,
'reservation_id' => 1001,
'status' => 'deleted',
]);
CloudPlacementService::releaseDeletedInstance(
CloudInstance::findOrFail(900),
'instance_deleted'
);
$assert(Capsule::table('cloud_resource_reservations')->where('id', 1001)
->value('state') === 'released'
&& Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 1001)->where('state', 'released')->count() === 2
&& Capsule::table('cloud_public_ips')->where('instance_id', 900)
->count() === 0,
'Confirmed instance deletion did not release its committed network bundle.');
echo "Provisioning dual-stack public-network ledger tests passed.\n";

@ -3,6 +3,8 @@
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudPublicNetworkAllocationService;
use App\Services\Cloud\CloudPublicNetworkCapacityUnavailable;
use App\Services\Cloud\CloudError;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
@ -32,6 +34,15 @@ $schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
});
$schema->create('cloud_host_agents', static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->boolean('enabled');
$table->integer('revision');
$table->integer('tested_revision');
$table->string('last_test_status');
$table->text('network_selectors_json');
$table->text('public_network_capabilities_json');
});
$schema->create('cloud_host_network_attachments', static function (
Blueprint $table
): void {
@ -41,6 +52,9 @@ $schema->create('cloud_host_network_attachments', static function (
$table->string('network_selector');
$table->string('state');
$table->integer('priority')->default(0);
$table->string('verification_state');
$table->integer('verified_agent_revision');
$table->integer('last_verified_at');
});
$schema->create('cloud_public_ip_pools', static function (
Blueprint $table
@ -89,6 +103,24 @@ $schema->create('cloud_resource_reservations', static function (
$table->integer('host_id');
$table->string('operation_id');
$table->string('state');
$table->integer('order_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->integer('instance_id')->nullable();
$table->integer('network_attachment_id')->nullable();
$table->integer('public_ip_pool_id')->nullable();
$table->integer('public_ip_id')->nullable();
});
$schema->create('cloud_instance_migrations', static function (
Blueprint $table
): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('restore_id');
$table->integer('source_host_id');
$table->integer('source_reservation_id');
$table->integer('target_host_id');
$table->integer('target_reservation_id');
$table->string('state');
});
$schema->create('cloud_resource_reservation_ips', static function (
Blueprint $table
@ -115,8 +147,25 @@ Capsule::table('cloud_host_network_attachments')->insert([
'network_selector' => 'bridge:br0',
'state' => 'active',
'priority' => 0,
'verification_state' => 'verified',
'verified_agent_revision' => 1,
'last_verified_at' => time(),
]);
Capsule::table('cloud_hosts')->insert(['id' => 1]);
Capsule::table('cloud_host_agents')->insert([
'host_id' => 1,
'enabled' => 1,
'revision' => 1,
'tested_revision' => 1,
'last_test_status' => 'healthy',
'network_selectors_json' => '["bridge:br0"]',
'public_network_capabilities_json' => json_encode([
'contract' => 1,
'dual_stack_required' => true,
'project_owned_filter' => true,
'ndp_guard' => true,
], JSON_THROW_ON_ERROR),
]);
$common = [
'host_id' => 1,
'network_attachment_id' => 10,
@ -369,26 +418,57 @@ Capsule::table('cloud_public_ip_pools')->where('id', 100)->update([
'cidr' => '198.51.100.0/24',
'gateway' => '198.51.100.1',
]);
$rejects(static fn () => CloudPublicNetworkAllocationService::reserveBundle(
1,
7,
503,
$operations[503]
), 'A special-use range crossed the public-network allocator.');
$invalidPoolError = null;
try {
CloudPublicNetworkAllocationService::reserveBundle(
1,
7,
503,
$operations[503]
);
} catch (CloudError $error) {
$invalidPoolError = $error;
}
$assert($invalidPoolError instanceof CloudError
&& !$invalidPoolError instanceof CloudPublicNetworkCapacityUnavailable,
'Invalid pool configuration was downgraded to scheduler exhaustion.');
$assert(Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 503)->count() === 0,
'Rejecting a non-public pool retained a partial address claim.');
$addAgent = static function (int $hostId, array $selectors,
array $overrides = []): void {
Capsule::table('cloud_host_agents')->insert(array_replace([
'host_id' => $hostId,
'enabled' => 1,
'revision' => 1,
'tested_revision' => 1,
'last_test_status' => 'healthy',
'network_selectors_json' => json_encode(
$selectors,
JSON_THROW_ON_ERROR
),
'public_network_capabilities_json' => json_encode([
'contract' => 1,
'dual_stack_required' => true,
'project_owned_filter' => true,
'ndp_guard' => true,
], JSON_THROW_ON_ERROR),
], $overrides));
};
$addAttachment = static function (int $id, int $hostId, int $lineId,
int $priority): void {
Capsule::table('cloud_host_network_attachments')->insert([
int $priority, array $overrides = []): void {
Capsule::table('cloud_host_network_attachments')->insert(array_replace([
'id' => $id,
'host_id' => $hostId,
'line_id' => $lineId,
'network_selector' => 'bridge:br' . $id,
'state' => 'active',
'priority' => $priority,
]);
'verification_state' => 'verified',
'verified_agent_revision' => 1,
'last_verified_at' => time(),
], $overrides));
};
$addPool = static function (int $id, int $hostId, int $attachmentId,
int $family, int $priority, string $cidr, string $gateway,
@ -444,16 +524,78 @@ $addReservation = static function (int $id, int $hostId,
'state' => 'held',
]);
};
$assertHardFailure = static function (callable $callback,
string $message) use ($assert): void {
$failure = null;
try {
$callback();
} catch (CloudError $error) {
$failure = $error;
}
$assert($failure instanceof CloudError
&& !$failure instanceof CloudPublicNetworkCapacityUnavailable,
$message);
};
$addPairHost = static function (int $hostId, int $lineId,
int $attachmentId, int $ipv4PoolId, int $ipv6PoolId,
string $ipv4Cidr, string $ipv6Cidr, array $agentOverrides = [],
array $attachmentOverrides = []) use (
$addAgent,
$addAttachment,
$addPool,
$addIp
): void {
$ipv4Prefix = substr($ipv4Cidr, 0, strrpos($ipv4Cidr, '.'));
$ipv6Network = substr($ipv6Cidr, 0, -3);
$selector = 'bridge:br' . $attachmentId;
Capsule::table('cloud_hosts')->insert(['id' => $hostId]);
$addAgent($hostId, [$selector], $agentOverrides);
$addAttachment(
$attachmentId,
$hostId,
$lineId,
0,
$attachmentOverrides
);
$addPool(
$ipv4PoolId,
$hostId,
$attachmentId,
4,
0,
$ipv4Cidr,
$ipv4Prefix . '.1'
);
$addIp(
$hostId,
$ipv4PoolId,
4,
$ipv4Prefix . '.10',
24
);
$addPool(
$ipv6PoolId,
$hostId,
$attachmentId,
6,
0,
$ipv6Cidr,
'2404:c140:156::1',
$ipv6Network . '10',
$ipv6Network . '20',
4
);
};
// A complete attachment may have more than one pool per family. Exhaustion
// of a higher-priority pool must not hide capacity in its next sibling.
Capsule::table('cloud_hosts')->insert(['id' => 2]);
$addAgent(2, ['bridge:br20', 'bridge:br30', 'bridge:br31']);
$addAttachment(20, 2, 8, 0);
$addPool(110, 2, 20, 4, 0, '9.9.9.0/24', '9.9.9.1');
Capsule::table('cloud_public_ip_pools')->where('id', 110)->update([
'reserved_ips_json' => '["9.9.9.10"]',
]);
$addIp(2, 110, 4, '9.9.9.10', 24);
$addPool(111, 2, 20, 4, 1, '11.0.0.0/24', '11.0.0.1');
$addIp(2, 111, 4, '11.0.0.10', 24);
$addPool(210, 2, 20, 6, 0, '2404:c140:156:3b::/64',
@ -504,6 +646,7 @@ $assert($attachmentFallback->address(4) === '13.0.0.10/24'
// An unavailable IPv6 leg must reject the whole bundle before the available
// IPv4 leg is claimed.
Capsule::table('cloud_hosts')->insert(['id' => 3]);
$addAgent(3, ['bridge:br40']);
$addAttachment(40, 3, 10, 0);
$addPool(130, 3, 40, 4, 0, '14.0.0.0/24', '14.0.0.1');
$addIp(3, 130, 4, '14.0.0.10', 24);
@ -513,13 +656,583 @@ $addPool(230, 3, 40, 6, 0, '2404:c140:156:3f::/64',
$addIp(3, 230, 6, '2404:c140:156:3f::10', 64, 'assigned');
$exhaustedOperation = str_repeat('4', 32);
$addReservation(602, 3, $exhaustedOperation);
$rejects(static fn () => CloudPublicNetworkAllocationService::reserveBundle(
3, 10, 602, $exhaustedOperation
), 'A host without a complete usable pool pair was accepted.');
$capacityUnavailable = false;
try {
CloudPublicNetworkAllocationService::reserveBundle(
3, 10, 602, $exhaustedOperation
);
} catch (CloudPublicNetworkCapacityUnavailable) {
$capacityUnavailable = true;
}
$assert($capacityUnavailable,
'Pair exhaustion did not produce the dedicated capacity result.');
$assert(Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 602)->count() === 0
&& Capsule::table('cloud_public_ips')->where('public_ip_pool_id', 130)
->where('state', 'available')->whereNull('reservation_id')->count() === 1,
'A failed pair selection left a partial IPv4 claim.');
// Exact allocation must ignore an unverified high-priority attachment and
// continue with a lower-priority attachment backed by the same locked current
// Agent evidence.
Capsule::table('cloud_hosts')->insert(['id' => 4]);
$addAgent(4, ['bridge:br51']);
$addAttachment(50, 4, 11, 0, [
'verification_state' => 'pending',
'verified_agent_revision' => 0,
]);
$addPool(140, 4, 50, 4, 0, '15.0.0.0/24', '15.0.0.1');
$addIp(4, 140, 4, '15.0.0.10', 24);
$addPool(240, 4, 50, 6, 0, '2404:c140:156:40::/64',
'2404:c140:156::1', '2404:c140:156:40::10',
'2404:c140:156:40::20', 4);
$addAttachment(51, 4, 11, 1);
$addPool(141, 4, 51, 4, 0, '16.0.0.0/24', '16.0.0.1');
$addIp(4, 141, 4, '16.0.0.10', 24);
$addPool(241, 4, 51, 6, 0, '2404:c140:156:41::/64',
'2404:c140:156::1', '2404:c140:156:41::10',
'2404:c140:156:41::20', 4);
$verifiedFallbackOperation = str_repeat('3', 32);
$addReservation(603, 4, $verifiedFallbackOperation);
$verifiedFallback = CloudPublicNetworkAllocationService::reserveBundle(
4, 11, 603, $verifiedFallbackOperation
);
$verifiedFallbackClaims = Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 603)->get();
$assert($verifiedFallback->address(4) === '16.0.0.10/24'
&& $verifiedFallbackClaims->count() === 2
&& $verifiedFallbackClaims->every(
static fn ($claim): bool =>
(int) $claim->network_attachment_id === 51
), 'Allocator selected an unverified higher-priority attachment.');
// Missing capabilities, an untested selector and stale revision evidence are
// configuration/evidence failures. They must never be downgraded to ordinary
// address exhaustion and silently sent to the next host.
$addPairHost(
5,
12,
60,
150,
250,
'17.0.0.0/24',
'2404:c140:156:50::/64'
);
$evidenceCases = [
'capabilities' => static function (): void {
Capsule::table('cloud_host_agents')->where('host_id', 5)->update([
'public_network_capabilities_json' => '{}',
]);
},
'selector' => static function (): void {
Capsule::table('cloud_host_agents')->where('host_id', 5)->update([
'network_selectors_json' => '[]',
]);
},
'agent revision' => static function (): void {
Capsule::table('cloud_host_agents')->where('host_id', 5)->update([
'tested_revision' => 0,
]);
},
'attachment revision' => static function (): void {
Capsule::table('cloud_host_network_attachments')->where('id', 60)
->update(['verified_agent_revision' => 2]);
},
];
$validCapabilities = json_encode([
'contract' => 1,
'dual_stack_required' => true,
'project_owned_filter' => true,
'ndp_guard' => true,
], JSON_THROW_ON_ERROR);
$evidenceReservationId = 604;
foreach ($evidenceCases as $label => $mutateEvidence) {
Capsule::table('cloud_host_agents')->where('host_id', 5)->update([
'enabled' => 1,
'revision' => 1,
'tested_revision' => 1,
'last_test_status' => 'healthy',
'network_selectors_json' => '["bridge:br60"]',
'public_network_capabilities_json' => $validCapabilities,
]);
Capsule::table('cloud_host_network_attachments')->where('id', 60)
->update([
'verification_state' => 'verified',
'verified_agent_revision' => 1,
'last_verified_at' => time(),
]);
$mutateEvidence();
$operation = str_pad(dechex($evidenceReservationId), 32, 'a');
$addReservation($evidenceReservationId, 5, $operation);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::reserveBundle(
5,
12,
$evidenceReservationId,
$operation
),
'Stale ' . $label . ' evidence was treated as address exhaustion.'
);
$assert(Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', $evidenceReservationId)->count() === 0,
'Stale ' . $label . ' evidence retained an address claim.');
$evidenceReservationId++;
}
// An active pool whose observed revision is ahead of the desired catalog is
// not a capacity miss; it is a non-converged configuration that must stop the
// paid placement transaction.
Capsule::table('cloud_host_agents')->where('host_id', 5)->update([
'tested_revision' => 1,
'network_selectors_json' => '["bridge:br60"]',
'public_network_capabilities_json' => $validCapabilities,
]);
Capsule::table('cloud_host_network_attachments')->where('id', 60)->update([
'verification_state' => 'verified',
'verified_agent_revision' => 1,
]);
Capsule::table('cloud_public_ip_pools')->where('id', 150)->update([
'observed_revision' => 2,
]);
$revisionOperation = str_repeat('2', 32);
$addReservation(608, 5, $revisionOperation);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::reserveBundle(
5,
12,
608,
$revisionOperation
),
'A pool ahead of desired revision was treated as address exhaustion.'
);
$assert(Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 608)->count() === 0,
'A non-converged pool retained an address claim.');
// Every materialized row is validated before capacity is evaluated. Shape,
// topology and concrete address corruption must therefore hard-fail rather
// than make a host look merely full.
$addPairHost(
6,
13,
70,
160,
260,
'18.0.0.0/24',
'2404:c140:156:60::/64'
);
$ledgerIpv4 = Capsule::table('cloud_public_ips')
->where('public_ip_pool_id', 160)->first();
$assert($ledgerIpv4 !== null, 'Ledger corruption fixture is missing IPv4.');
$ledgerBaseline = [
'host_id' => 6,
'public_ip_pool_id' => 160,
'address_family' => 4,
'address' => '18.0.0.10',
'address_binary' => inet_pton('18.0.0.10'),
'prefix_length' => 24,
'state' => 'available',
'reservation_id' => null,
'instance_id' => null,
'operation_id' => null,
];
$ledgerCases = [
'dirty available ownership' => [
'reservation_id' => 9999,
],
'active row without ownership' => [
'state' => 'reserved',
],
'wrong host' => [
'host_id' => 999,
],
'wrong family' => [
'address_family' => 6,
],
'wrong pool' => [
'public_ip_pool_id' => 260,
],
'invalid prefix' => [
'prefix_length' => 23,
],
'address outside pool' => [
'address' => '19.0.0.10',
'address_binary' => inet_pton('19.0.0.10'),
],
'same text with different binary' => [
'address_binary' => inet_pton('18.0.0.11'),
],
];
$ledgerReservationId = 609;
foreach ($ledgerCases as $label => $mutation) {
Capsule::table('cloud_public_ips')->where('id', (int) $ledgerIpv4->id)
->update(array_replace($ledgerBaseline, $mutation));
$operation = str_pad(dechex($ledgerReservationId), 32, 'b');
$addReservation($ledgerReservationId, 6, $operation);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::reserveBundle(
6,
13,
$ledgerReservationId,
$operation
),
'Corrupt ' . $label . ' ledger was treated as address exhaustion.'
);
$assert(Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', $ledgerReservationId)->count() === 0,
'Corrupt ' . $label . ' ledger retained a partial claim.');
$ledgerReservationId++;
}
// Canonical text is part of the concrete identity just like the packed bytes.
Capsule::table('cloud_public_ips')->where('id', (int) $ledgerIpv4->id)
->update($ledgerBaseline);
$nonCanonicalIpv6Id = Capsule::table('cloud_public_ips')->insertGetId([
'host_id' => 6,
'public_ip_pool_id' => 260,
'address_family' => 6,
'address' => '2404:C140:156:60::10',
'address_binary' => inet_pton('2404:c140:156:60::10'),
'prefix_length' => 64,
'state' => 'available',
'reservation_id' => null,
'instance_id' => null,
'operation_id' => null,
'created_at' => time(),
'updated_at' => time(),
]);
$canonicalOperation = str_repeat('1', 32);
$addReservation(617, 6, $canonicalOperation);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::reserveBundle(
6,
13,
617,
$canonicalOperation
),
'Non-canonical concrete address text was treated as address exhaustion.'
);
$assert(Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 617)->count() === 0,
'Rejecting non-canonical text retained a partial claim.');
Capsule::table('cloud_public_ips')->where('id', $nonCanonicalIpv6Id)->delete();
// A retained maintenance-migration source is a deliberate capacity debt, not
// a corrupt assigned address. Accept only the exact migration + restore
// reservation evidence, and keep that address unavailable to new placement.
$addPairHost(
8,
15,
90,
180,
280,
'21.0.0.0/24',
'2404:c140:156:80::/64'
);
foreach ([
['21.0.0.14', 'changing', null, 8000, str_repeat('6', 32)],
['21.0.0.15', 'uncertain', null, 8001, str_repeat('7', 32)],
['21.0.0.16', 'disabled', null, null, null],
] as [$address, $state, $reservationId, $instanceId, $operationId]) {
Capsule::table('cloud_public_ips')->insert([
'host_id' => 8,
'public_ip_pool_id' => 180,
'address_family' => 4,
'address' => $address,
'address_binary' => inet_pton($address),
'prefix_length' => 24,
'state' => $state,
'reservation_id' => $reservationId,
'instance_id' => $instanceId,
'operation_id' => $operationId,
'created_at' => time(),
'updated_at' => time(),
]);
}
$retainedOperation = str_repeat('8', 32);
$retainedIpId = Capsule::table('cloud_public_ips')->insertGetId([
'host_id' => 8,
'public_ip_pool_id' => 180,
'address_family' => 4,
'address' => '21.0.0.11',
'address_binary' => inet_pton('21.0.0.11'),
'prefix_length' => 24,
'state' => 'assigned',
'reservation_id' => 700,
'instance_id' => null,
'operation_id' => $retainedOperation,
'created_at' => time(),
'updated_at' => time(),
]);
Capsule::table('cloud_resource_reservations')->insert([
'id' => 700,
'host_id' => 8,
'operation_id' => $retainedOperation,
'state' => 'committed',
'order_id' => null,
'backup_restore_id' => 800,
'instance_id' => null,
'network_attachment_id' => 90,
'public_ip_pool_id' => 180,
'public_ip_id' => $retainedIpId,
]);
Capsule::table('cloud_instance_migrations')->insert([
'id' => 800,
'instance_id' => 8000,
'restore_id' => 800,
'source_host_id' => 8,
'source_reservation_id' => 700,
'target_host_id' => 9,
'target_reservation_id' => 701,
'state' => 'source_retained',
]);
$sourceRetainedOperation = str_repeat('9', 32);
$addReservation(621, 8, $sourceRetainedOperation);
$sourceRetainedBundle = CloudPublicNetworkAllocationService::reserveBundle(
8,
15,
621,
$sourceRetainedOperation
);
$assert($sourceRetainedBundle->address(4) === '21.0.0.10/24'
&& Capsule::table('cloud_public_ips')->where('id', $retainedIpId)
->where('state', 'assigned')->whereNull('instance_id')
->where('reservation_id', 700)->count() === 1,
'Exact source-retained debt blocked placement or was reallocated.');
// The same debt remains valid while its cleanup mutation is in flight.
Capsule::table('cloud_instance_migrations')->where('id', 800)->update([
'state' => 'cleanup_running',
]);
$addIp(8, 180, 4, '21.0.0.12', 24);
$cleanupRunningOperation = str_repeat('a', 32);
$addReservation(622, 8, $cleanupRunningOperation);
$cleanupRunningBundle = CloudPublicNetworkAllocationService::reserveBundle(
8,
15,
622,
$cleanupRunningOperation
);
$assert($cleanupRunningBundle->address(4) === '21.0.0.12/24'
&& Capsule::table('cloud_public_ips')->where('id', $retainedIpId)
->where('state', 'assigned')->whereNull('instance_id')
->where('reservation_id', 700)->count() === 1,
'Cleanup-running retained debt blocked placement or was reallocated.');
// An orphan or any material identity mismatch must remain a hard ledger
// failure. It must not become ordinary capacity exhaustion or claim a spare.
$addIp(8, 180, 4, '21.0.0.13', 24);
$retainedMigrationBaseline = (array) Capsule::table(
'cloud_instance_migrations'
)->where('id', 800)->first();
$retainedReservationBaseline = (array) Capsule::table(
'cloud_resource_reservations'
)->where('id', 700)->first();
$evidenceFailureReservationId = 623;
$assertRetainedEvidenceFailure = static function (
string $label
) use (
&$evidenceFailureReservationId,
$addReservation,
$assertHardFailure,
$assert
): void {
$operation = str_pad(
dechex($evidenceFailureReservationId),
32,
'b'
);
$addReservation($evidenceFailureReservationId, 8, $operation);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::reserveBundle(
8,
15,
$evidenceFailureReservationId,
$operation
),
$label . ' was downgraded to ordinary capacity exhaustion.'
);
$assert(Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', $evidenceFailureReservationId)
->count() === 0,
$label . ' retained a partial public-network claim.');
$evidenceFailureReservationId++;
};
Capsule::table('cloud_instance_migrations')->where('id', 800)->delete();
$assertRetainedEvidenceFailure('Orphan retained-source address');
Capsule::table('cloud_instance_migrations')->insert(
$retainedMigrationBaseline
);
$retainedEvidenceMutations = [
'Unsupported retained-source state' => static function (): void {
Capsule::table('cloud_instance_migrations')->where('id', 800)
->update(['state' => 'completed']);
},
'Migration restore identity mismatch' => static function (): void {
Capsule::table('cloud_instance_migrations')->where('id', 800)
->update(['restore_id' => 801]);
},
'Reservation host identity mismatch' => static function (): void {
Capsule::table('cloud_resource_reservations')->where('id', 700)
->update(['host_id' => 999]);
},
'Reservation pool identity mismatch' => static function (): void {
Capsule::table('cloud_resource_reservations')->where('id', 700)
->update(['public_ip_pool_id' => 280]);
},
'Reservation IP identity mismatch' => static function (): void {
Capsule::table('cloud_resource_reservations')->where('id', 700)
->update(['public_ip_id' => 999999]);
},
'Reservation operation identity mismatch' => static function (): void {
Capsule::table('cloud_resource_reservations')->where('id', 700)
->update(['operation_id' => str_repeat('f', 32)]);
},
];
foreach ($retainedEvidenceMutations as $label => $mutate) {
Capsule::table('cloud_instance_migrations')->where('id', 800)->update(
$retainedMigrationBaseline
);
Capsule::table('cloud_resource_reservations')->where('id', 700)->update(
$retainedReservationBaseline
);
$mutate();
$assertRetainedEvidenceFailure($label);
}
Capsule::table('cloud_instance_migrations')->where('id', 800)->update(
$retainedMigrationBaseline
);
Capsule::table('cloud_resource_reservations')->where('id', 700)->update(
$retainedReservationBaseline
);
// Every state transition repeats the same concrete identity checks. A valid
// text paired with different packed bytes, or an address moved to another
// host, cannot be committed, fenced or released.
$addPairHost(
7,
14,
80,
170,
270,
'20.0.0.0/24',
'2404:c140:156:70::/64'
);
$commitIdentityOperation = str_repeat('c', 32);
$addReservation(618, 7, $commitIdentityOperation);
CloudPublicNetworkAllocationService::reserveBundle(
7,
14,
618,
$commitIdentityOperation
);
$commitIpv4 = Capsule::table('cloud_public_ips')
->where('reservation_id', 618)->where('address_family', 4)->first();
$assert($commitIpv4 !== null, 'Commit identity fixture is missing IPv4.');
Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id)
->update(['address_binary' => inet_pton('20.0.0.11')]);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::commitBundle(
618,
918,
$commitIdentityOperation
),
'Commit accepted same-text/different-binary concrete identity.'
);
Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id)
->update(['address_binary' => inet_pton('20.0.0.10')]);
CloudPublicNetworkAllocationService::commitBundle(
618,
918,
$commitIdentityOperation
);
Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id)
->update(['host_id' => 999]);
$assertHardFailure(
static fn () =>
CloudPublicNetworkAllocationService::releaseCommittedBundle(
618,
918,
$commitIdentityOperation,
'instance_deleted',
true
),
'Committed release accepted a concrete address from another host.'
);
Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id)
->update(['host_id' => 7]);
CloudPublicNetworkAllocationService::releaseCommittedBundle(
618,
918,
$commitIdentityOperation,
'instance_deleted',
true
);
$fenceIdentityOperation = str_repeat('d', 32);
$addReservation(619, 7, $fenceIdentityOperation);
CloudPublicNetworkAllocationService::reserveBundle(
7,
14,
619,
$fenceIdentityOperation
);
$fenceIpv4 = Capsule::table('cloud_public_ips')
->where('reservation_id', 619)->where('address_family', 4)->first();
$assert($fenceIpv4 !== null, 'Fence identity fixture is missing IPv4.');
Capsule::table('cloud_public_ips')->where('id', (int) $fenceIpv4->id)
->update(['host_id' => 999]);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::fenceBundle(
619,
$fenceIdentityOperation
),
'Fence accepted a concrete address from another host.'
);
Capsule::table('cloud_public_ips')->where('id', (int) $fenceIpv4->id)
->update(['host_id' => 7]);
CloudPublicNetworkAllocationService::fenceBundle(
619,
$fenceIdentityOperation
);
CloudPublicNetworkAllocationService::releaseBundle(
619,
$fenceIdentityOperation,
'confirmed_not_applied',
true
);
$releaseIdentityOperation = str_repeat('e', 32);
$addReservation(620, 7, $releaseIdentityOperation);
CloudPublicNetworkAllocationService::reserveBundle(
7,
14,
620,
$releaseIdentityOperation
);
$releaseIpv4 = Capsule::table('cloud_public_ips')
->where('reservation_id', 620)->where('address_family', 4)->first();
$assert($releaseIpv4 !== null, 'Release identity fixture is missing IPv4.');
Capsule::table('cloud_public_ips')->where('id', (int) $releaseIpv4->id)
->update(['address_binary' => inet_pton('20.0.0.11')]);
$assertHardFailure(
static fn () => CloudPublicNetworkAllocationService::releaseBundle(
620,
$releaseIdentityOperation,
'confirmed_not_applied',
true
),
'Release accepted same-text/different-binary concrete identity.'
);
Capsule::table('cloud_public_ips')->where('id', (int) $releaseIpv4->id)
->update(['address_binary' => inet_pton('20.0.0.10')]);
CloudPublicNetworkAllocationService::releaseBundle(
620,
$releaseIdentityOperation,
'confirmed_not_applied',
true
);
echo "Atomic dual-stack public network allocation tests passed.\n";

@ -218,6 +218,38 @@ namespace {
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
});
$schema->create('cloud_host_network_attachments',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('line_id');
$table->string('network_selector');
$table->string('state');
$table->integer('priority')->default(0);
});
$schema->create('cloud_public_ip_pools',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('pool_key');
$table->integer('host_id');
$table->integer('network_attachment_id');
$table->integer('address_family');
$table->string('cidr');
$table->string('gateway');
$table->boolean('gateway_on_link');
$table->integer('guest_prefix_length');
$table->text('dns_servers_json');
$table->text('reserved_ips_json');
$table->string('allocation_start')->nullable();
$table->string('allocation_end')->nullable();
$table->string('allocation_cursor')->nullable();
$table->integer('max_allocations');
$table->string('state');
$table->integer('priority')->default(0);
$table->integer('desired_revision');
$table->integer('observed_revision');
$table->string('sync_state');
});
$schema->create('cloud_offers', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('stock')->default(-1);
@ -251,6 +283,7 @@ namespace {
$table->string('reservation_key');
$table->string('operation_id');
$table->integer('order_id');
$table->integer('backup_restore_id')->nullable();
$table->integer('offer_id');
$table->integer('resource_pool_id');
$table->integer('host_id');
@ -274,7 +307,9 @@ namespace {
$table->increments('id');
$table->integer('host_id');
$table->integer('public_ip_pool_id')->nullable();
$table->integer('address_family');
$table->string('address');
$table->binary('address_binary');
$table->integer('prefix_length');
$table->string('state');
$table->integer('reservation_id')->nullable();
@ -283,6 +318,21 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_resource_reservation_ips',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('reservation_id');
$table->integer('address_family');
$table->integer('network_attachment_id');
$table->integer('public_ip_pool_id');
$table->integer('public_ip_id');
$table->string('operation_id');
$table->string('state');
$table->integer('created_at');
$table->integer('updated_at');
$table->integer('released_at')->nullable();
$table->string('release_reason')->default('');
});
$schema->create('cloud_invoices',
static function (Blueprint $table): void {
$table->increments('id');
@ -522,6 +572,53 @@ namespace {
);
Capsule::table('user')->where('id', 1)->update(['money' => '0.00']);
Capsule::table('cloud_hosts')->insert(['id' => 7]);
Capsule::table('cloud_host_network_attachments')->insert([
'id' => 601,
'host_id' => 7,
'line_id' => 601,
'network_selector' => 'bridge:br0',
'state' => 'active',
'priority' => 0,
]);
$publicPool = [
'host_id' => 7,
'network_attachment_id' => 601,
'gateway_on_link' => 0,
'reserved_ips_json' => '[]',
'allocation_cursor' => null,
'state' => 'active',
'priority' => 0,
'desired_revision' => 1,
'observed_revision' => 1,
'sync_state' => 'applied',
];
Capsule::table('cloud_public_ip_pools')->insert([
array_merge($publicPool, [
'id' => 601,
'pool_key' => str_repeat('1', 32),
'address_family' => 4,
'cidr' => '8.8.8.0/24',
'gateway' => '8.8.8.1',
'guest_prefix_length' => 24,
'dns_servers_json' => '["1.1.1.1"]',
'allocation_start' => null,
'allocation_end' => null,
'max_allocations' => 0,
]),
array_merge($publicPool, [
'id' => 602,
'pool_key' => str_repeat('2', 32),
'address_family' => 6,
'cidr' => '2404:c140:156:3a::/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => 1,
'guest_prefix_length' => 64,
'dns_servers_json' => '["2606:4700:4700::1111"]',
'allocation_start' => '2404:c140:156:3a::10',
'allocation_end' => '2404:c140:156:3a::ff',
'max_allocations' => 8,
]),
]);
Capsule::table('cloud_offers')->insert([
'id' => 601,
'stock' => 0,
@ -554,14 +651,15 @@ namespace {
'reservation_key' => 'undispatched-create-reservation',
'operation_id' => $createOperationId,
'order_id' => 601,
'backup_restore_id' => null,
'offer_id' => 601,
'resource_pool_id' => 601,
'host_id' => 7,
'user_id' => 1,
'instance_id' => null,
'network_attachment_id' => 601,
'public_ip_pool_id' => 601,
'public_ip_id' => 601,
'network_attachment_id' => null,
'public_ip_pool_id' => null,
'public_ip_id' => null,
'cpu_cores' => 1,
'memory_mib' => 512,
'disk_gib' => 10,
@ -573,17 +671,66 @@ namespace {
'updated_at' => $now - 30,
]);
Capsule::table('cloud_public_ips')->insert([
'id' => 601,
'host_id' => 7,
'public_ip_pool_id' => 601,
'address' => '203.0.113.61',
'prefix_length' => 24,
'state' => 'reserved',
'reservation_id' => 601,
'instance_id' => null,
'operation_id' => $createOperationId,
'created_at' => $now - 120,
'updated_at' => $now - 30,
[
'id' => 601,
'host_id' => 7,
'public_ip_pool_id' => 601,
'address_family' => 4,
'address' => '8.8.8.61',
'address_binary' => inet_pton('8.8.8.61'),
'prefix_length' => 24,
'state' => 'reserved',
'reservation_id' => 601,
'instance_id' => null,
'operation_id' => $createOperationId,
'created_at' => $now - 120,
'updated_at' => $now - 30,
],
[
'id' => 602,
'host_id' => 7,
'public_ip_pool_id' => 602,
'address_family' => 6,
'address' => '2404:c140:156:3a::61',
'address_binary' => inet_pton('2404:c140:156:3a::61'),
'prefix_length' => 64,
'state' => 'reserved',
'reservation_id' => 601,
'instance_id' => null,
'operation_id' => $createOperationId,
'created_at' => $now - 120,
'updated_at' => $now - 30,
],
]);
Capsule::table('cloud_resource_reservation_ips')->insert([
[
'id' => 601,
'reservation_id' => 601,
'address_family' => 4,
'network_attachment_id' => 601,
'public_ip_pool_id' => 601,
'public_ip_id' => 601,
'operation_id' => $createOperationId,
'state' => 'reserved',
'created_at' => $now - 120,
'updated_at' => $now - 30,
'released_at' => null,
'release_reason' => '',
],
[
'id' => 602,
'reservation_id' => 601,
'address_family' => 6,
'network_attachment_id' => 601,
'public_ip_pool_id' => 602,
'public_ip_id' => 602,
'operation_id' => $createOperationId,
'state' => 'reserved',
'created_at' => $now - 120,
'updated_at' => $now - 30,
'released_at' => null,
'release_reason' => '',
],
]);
Capsule::table('cloud_jobs')->insert([
'id' => 601,
@ -693,8 +840,9 @@ namespace {
->value('money') === '0.00'
&& (string) Capsule::table('cloud_resource_reservations')
->where('id', 601)->value('state') === 'held'
&& (string) Capsule::table('cloud_public_ips')
->where('id', 601)->value('state') === 'reserved'
&& Capsule::table('cloud_public_ips')
->where('reservation_id', 601)
->where('state', 'reserved')->count() === 2
&& CloudAgentSettingsService::$requests === 0,
'Missing create ledger data caused a partial refund/release or Agent call.');
@ -763,10 +911,15 @@ namespace {
->value('stock') === 1
&& (string) Capsule::table('cloud_resource_reservations')
->where('id', 601)->value('state') === 'released'
&& (string) Capsule::table('cloud_public_ips')
->where('id', 601)->value('state') === 'available'
&& Capsule::table('cloud_public_ips')->where('id', 601)
->value('reservation_id') === null
&& Capsule::table('cloud_public_ips')
->whereIn('id', [601, 602])
->where('state', 'available')->count() === 2
&& Capsule::table('cloud_public_ips')
->whereIn('id', [601, 602])
->whereNotNull('reservation_id')->count() === 0
&& Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 601)
->where('state', 'released')->count() === 2
&& CloudAgentSettingsService::$requests === 0,
'Recovered create did not atomically refund, release, scrub, and close.');

Loading…
Cancel
Save