feat: add VPC network preaccess contracts
parent
887072ac61
commit
4046a895ea
@ -0,0 +1,110 @@
|
||||
"""Network-role and public-filter boundary contracts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import pytest
|
||||
|
||||
from virsh_panel.network_roles import (
|
||||
assert_public_interface,
|
||||
interface_role,
|
||||
private_interface_has_public_filter,
|
||||
select_private_interface,
|
||||
select_public_interface,
|
||||
)
|
||||
|
||||
|
||||
def test_explicit_roles_do_not_depend_on_xml_order():
|
||||
public = ET.fromstring(
|
||||
"<interface><alias name='public0'/><source bridge='br0'/></interface>"
|
||||
)
|
||||
private = ET.fromstring(
|
||||
"<interface><source bridge='vpc0'/><alias name='private0'/></interface>"
|
||||
)
|
||||
assert interface_role(public) == "public"
|
||||
assert interface_role(private) == "private"
|
||||
assert_public_interface(public)
|
||||
with pytest.raises(ValueError):
|
||||
assert_public_interface(private)
|
||||
|
||||
|
||||
def test_unlabelled_multi_nic_is_ambiguous_and_private_filter_is_rejected():
|
||||
unlabelled = ET.fromstring(
|
||||
"<interface><source bridge='vpc0'/><filterref filter='clean-traffic'/></interface>"
|
||||
)
|
||||
assert interface_role(unlabelled) == "unknown"
|
||||
assert private_interface_has_public_filter(unlabelled)
|
||||
with pytest.raises(ValueError):
|
||||
assert_public_interface(unlabelled)
|
||||
|
||||
|
||||
def test_explicit_public_with_unlabelled_second_nic_fails_closed():
|
||||
public = ET.fromstring(
|
||||
"<interface><alias name='public0'/><source bridge='br0'/></interface>"
|
||||
)
|
||||
unknown = ET.fromstring("<interface><source bridge='vpc0'/></interface>")
|
||||
with pytest.raises(ValueError, match="声明"):
|
||||
select_public_interface([public, unknown])
|
||||
|
||||
|
||||
def test_explicit_public_private_pair_selects_public_interface():
|
||||
public = ET.fromstring("<interface><alias name='public0'/></interface>")
|
||||
private = ET.fromstring("<interface><alias name='private0'/></interface>")
|
||||
assert select_public_interface([private, public]) is public
|
||||
|
||||
|
||||
def test_legacy_single_public_nic_can_still_be_updated():
|
||||
legacy = ET.fromstring("<interface><source bridge='br0'/></interface>")
|
||||
assert interface_role(legacy) == "unknown"
|
||||
assert interface_role(legacy, legacy_public=True) == "public"
|
||||
assert_public_interface(legacy, legacy_public=True)
|
||||
|
||||
generated = ET.fromstring(
|
||||
"<interface><alias name='net0'/><source bridge='br0'/></interface>"
|
||||
)
|
||||
assert interface_role(generated) == "unknown"
|
||||
assert select_public_interface([generated]) is generated
|
||||
assert_public_interface(generated, legacy_public=True)
|
||||
|
||||
renamed = ET.fromstring(
|
||||
"<interface><alias name='operator0'/><source bridge='br0'/></interface>"
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
select_public_interface([renamed])
|
||||
|
||||
|
||||
def test_private_selection_requires_one_explicit_private_role():
|
||||
private = ET.fromstring(
|
||||
"<interface><alias name='private0'/><source bridge='vpc0'/></interface>"
|
||||
)
|
||||
public = ET.fromstring(
|
||||
"<interface><alias name='public0'/><source bridge='br0'/></interface>"
|
||||
)
|
||||
assert select_private_interface([public, private]) is private
|
||||
assert select_private_interface([public]) is None
|
||||
with pytest.raises(ValueError):
|
||||
select_private_interface([private, ET.fromstring(
|
||||
"<interface><alias name='private0'/></interface>")])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("alias", ["net0", "ua-net-0"])
|
||||
def test_libvirt_generated_single_nic_alias_is_legacy_public(alias):
|
||||
legacy = ET.fromstring(
|
||||
f"<interface><alias name='{alias}'/><source bridge='br0'/></interface>"
|
||||
)
|
||||
assert interface_role(legacy) == "unknown"
|
||||
assert interface_role(legacy, legacy_public=True) == "public"
|
||||
assert select_public_interface([legacy]) is legacy
|
||||
assert_public_interface(legacy, legacy_public=True)
|
||||
|
||||
|
||||
def test_generated_alias_is_not_guessed_in_a_multi_nic_domain():
|
||||
public = ET.fromstring(
|
||||
"<interface><alias name='public0'/><source bridge='br0'/></interface>"
|
||||
)
|
||||
legacy = ET.fromstring(
|
||||
"<interface><alias name='net1'/><source bridge='vpc0'/></interface>"
|
||||
)
|
||||
with pytest.raises(ValueError, match="声明"):
|
||||
select_public_interface([public, legacy])
|
||||
@ -0,0 +1,148 @@
|
||||
"""Stable guest network-role helpers shared by cloud-init and libvirt.
|
||||
|
||||
The public interface is the only interface that may carry the panel's
|
||||
provider-facing anti-spoofing/nwfilter policy. A future VPC interface is a
|
||||
separate L3 dataplane and must never be inferred from the public bridge.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Any
|
||||
|
||||
|
||||
PUBLIC_INTERFACE_ALIAS = "public0"
|
||||
PRIVATE_INTERFACE_ALIAS = "private0"
|
||||
SUPPORTED_INTERFACE_ALIASES = frozenset({
|
||||
PUBLIC_INTERFACE_ALIAS,
|
||||
PRIVATE_INTERFACE_ALIAS,
|
||||
})
|
||||
_ALIAS_RE = re.compile(r"[a-z][a-z0-9-]{0,15}\Z")
|
||||
# libvirt adds a generated interface alias when an older domain definition did
|
||||
# not provide one. Those aliases identify the first/only legacy NIC, but they
|
||||
# do not constitute an explicit private role. Keep the compatibility scope
|
||||
# narrow so an arbitrary operator alias is never silently treated as public.
|
||||
_LEGACY_PUBLIC_ALIAS_RE = re.compile(r"(?:net|ua-net-)[0-9]+\Z")
|
||||
|
||||
|
||||
def _is_legacy_public_alias(alias: str | None) -> bool:
|
||||
return alias is not None and _LEGACY_PUBLIC_ALIAS_RE.fullmatch(alias) is not None
|
||||
|
||||
|
||||
def interface_alias(interface: ET.Element) -> str | None:
|
||||
"""Return a validated libvirt interface alias, if one is present."""
|
||||
alias = interface.find("alias")
|
||||
value = alias.get("name") if alias is not None else None
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, str) or not _ALIAS_RE.fullmatch(value):
|
||||
raise ValueError("虚拟机网卡别名无效")
|
||||
return value
|
||||
|
||||
|
||||
def interface_role(interface: ET.Element, *, legacy_public: bool = False) -> str:
|
||||
"""Classify one interface without guessing a role for a multi-NIC VM.
|
||||
|
||||
A legacy single-NIC domain with no alias, or with libvirt's generated
|
||||
``net0``/``ua-net-0`` alias, is treated as public for backwards
|
||||
compatibility when ``legacy_public`` is requested. An unaliased or
|
||||
generated interface in a multi-NIC domain is intentionally ``unknown``
|
||||
and must be rejected by callers that apply a security policy.
|
||||
"""
|
||||
alias = interface_alias(interface)
|
||||
if alias == PUBLIC_INTERFACE_ALIAS:
|
||||
return "public"
|
||||
if alias == PRIVATE_INTERFACE_ALIAS:
|
||||
return "private"
|
||||
if alias is not None:
|
||||
if legacy_public and _is_legacy_public_alias(alias):
|
||||
return "public"
|
||||
return "unknown"
|
||||
if legacy_public and alias is None:
|
||||
return "public"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def role_for_cloud_key(key: Any) -> str:
|
||||
"""Map a cloud-init ethernet key to a product network role."""
|
||||
if key == PUBLIC_INTERFACE_ALIAS:
|
||||
return "public"
|
||||
if key == PRIVATE_INTERFACE_ALIAS:
|
||||
return "private"
|
||||
raise ValueError("cloud-init 网卡角色不受支持")
|
||||
|
||||
|
||||
def select_public_interface(
|
||||
interfaces: list[ET.Element] | tuple[ET.Element, ...],
|
||||
*,
|
||||
allow_legacy_single: bool = True,
|
||||
) -> ET.Element:
|
||||
"""Select the provider-facing NIC and validate every other NIC's role.
|
||||
|
||||
New definitions must label every interface. The sole exception is an
|
||||
old one-NIC domain without an alias, which is still safely identifiable as
|
||||
the public NIC. Once a second NIC exists, an unlabelled or unknown alias
|
||||
is rejected rather than being treated as private by accident.
|
||||
"""
|
||||
values = list(interfaces)
|
||||
if not values:
|
||||
raise ValueError("虚拟机缺少网卡")
|
||||
candidates = [
|
||||
item for item in values
|
||||
if interface_role(item, legacy_public=False) == "public"
|
||||
]
|
||||
if not candidates and allow_legacy_single and len(values) == 1:
|
||||
if interface_role(values[0], legacy_public=True) == "public":
|
||||
candidates = [values[0]]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("虚拟机公网网卡角色不明确")
|
||||
selected = candidates[0]
|
||||
private_count = 0
|
||||
for item in values:
|
||||
if item is selected:
|
||||
continue
|
||||
role = interface_role(item)
|
||||
if role == "private":
|
||||
private_count += 1
|
||||
elif role == "unknown":
|
||||
raise ValueError("多网卡虚拟机必须声明每张网卡的角色")
|
||||
if private_count > 1:
|
||||
raise ValueError("虚拟机不能包含多张 private0 网卡")
|
||||
return selected
|
||||
|
||||
|
||||
def select_private_interface(
|
||||
interfaces: list[ET.Element] | tuple[ET.Element, ...],
|
||||
) -> ET.Element | None:
|
||||
"""Return the single explicit private NIC, if a domain has one."""
|
||||
candidates = [
|
||||
item for item in interfaces
|
||||
if interface_role(item, legacy_public=False) == "private"
|
||||
]
|
||||
if len(candidates) > 1:
|
||||
raise ValueError("虚拟机不能包含多张 private0 网卡")
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def assert_public_interface(interface: ET.Element, *, legacy_public: bool = False) -> None:
|
||||
"""Reject attaching public policy to a private or ambiguous interface."""
|
||||
role = interface_role(interface, legacy_public=legacy_public)
|
||||
if role != "public":
|
||||
raise ValueError("公网过滤器只能绑定 public0 网卡")
|
||||
|
||||
|
||||
def private_interface_has_public_filter(interface: ET.Element) -> bool:
|
||||
"""Return whether a non-public role carries a public filter reference.
|
||||
|
||||
An explicitly private NIC is the normal case. Treating an unknown alias
|
||||
as unsafe here also matters during migration: a future or externally
|
||||
edited NIC must never become an unreviewed place to attach a provider
|
||||
anti-spoofing policy.
|
||||
"""
|
||||
role = interface_role(interface)
|
||||
# The private dataplane is governed by its own nftables context. Any
|
||||
# libvirt nwfilter on a non-public NIC is therefore outside this contract;
|
||||
# accepting an arbitrary filter would make it impossible to prove that a
|
||||
# provider anti-spoofing policy was not copied to the private interface.
|
||||
return role != "public" and bool(interface.findall("filterref"))
|
||||
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** Immutable-ish operator configuration for the global private CIDR pool. */
|
||||
final class CloudPrivateCidrAllocatorConfig extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_private_cidr_allocator_configs';
|
||||
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'quantum_prefix_length' => 'int',
|
||||
'min_prefix_length' => 'int',
|
||||
'max_prefix_length' => 'int',
|
||||
'revision' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** One /24 quantum claimed by a live private network allocation. */
|
||||
final class CloudPrivateCidrClaim extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_private_cidr_claims';
|
||||
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'created_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** One globally allocated, tenant-owned VPC network CIDR. */
|
||||
final class CloudPrivateNetwork extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_private_networks';
|
||||
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'user_id' => 'int',
|
||||
'region_id' => 'int',
|
||||
'network_address' => 'int',
|
||||
'broadcast_address' => 'int',
|
||||
'prefix_length' => 'int',
|
||||
'revision' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
'released_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,511 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudPrivateCidrAllocatorConfig;
|
||||
use App\Models\CloudPrivateCidrClaim;
|
||||
use App\Models\CloudPrivateNetwork;
|
||||
|
||||
/**
|
||||
* Concurrent allocator for the first VPC private-address release.
|
||||
*
|
||||
* The address space is global rather than host- or region-scoped. Allocation
|
||||
* uses /24 quantum claims: every candidate claims each /24 it contains under
|
||||
* one database transaction, and the unique block key is the conflict point.
|
||||
* Independent candidates therefore proceed concurrently without a process or
|
||||
* global mutex. A larger VPC CIDR simply claims more adjacent quantum rows.
|
||||
*/
|
||||
final class CloudPrivateCidrAllocator
|
||||
{
|
||||
public const CONFIG_ID = 1;
|
||||
public const DEFAULT_POOL_CIDR = '10.0.0.0/8';
|
||||
public const DEFAULT_MIN_PREFIX_LENGTH = 16;
|
||||
public const DEFAULT_MAX_PREFIX_LENGTH = 24;
|
||||
public const QUANTUM_PREFIX_LENGTH = 24;
|
||||
private const MAX_ALLOCATION_RETRIES = 8;
|
||||
|
||||
private const LIVE_STATES = ['active', 'applying', 'degraded', 'uncertain'];
|
||||
private const STATES = ['active', 'applying', 'degraded', 'uncertain', 'released'];
|
||||
|
||||
/**
|
||||
* Allocate one globally unique private network.
|
||||
*
|
||||
* `$allocationKey` is the caller's durable idempotency key. A retry with
|
||||
* the same key returns the original row only when all immutable request
|
||||
* fields match. The optional request CIDR is canonicalised before the
|
||||
* claim; omitted requests use first-fit aligned blocks.
|
||||
*/
|
||||
public static function allocate(string $allocationKey, int $userId, int $regionId,
|
||||
?string $requestedCidr = null, int $prefixLength = self::DEFAULT_MAX_PREFIX_LENGTH,
|
||||
?string $vpcKey = null): CloudPrivateNetwork
|
||||
{
|
||||
self::assertKey($allocationKey, 'CIDR 分配请求');
|
||||
if ($userId < 1 || $regionId < 1) {
|
||||
throw new CloudError('私网分配的用户或地区无效', 422);
|
||||
}
|
||||
$providedVpcKey = $vpcKey;
|
||||
$vpcKey ??= substr(hash('sha256', 'virt-cloud-vpc:' . $allocationKey), 0, 32);
|
||||
self::assertKey($vpcKey, 'VPC');
|
||||
|
||||
$requested = $requestedCidr === null
|
||||
? null : self::normalizeCidr($requestedCidr, $prefixLength);
|
||||
$connection = (new CloudPrivateNetwork())->getConnection();
|
||||
|
||||
for ($attempt = 0; $attempt < self::MAX_ALLOCATION_RETRIES; $attempt++) {
|
||||
try {
|
||||
return $connection->transaction(function () use (
|
||||
$allocationKey, $userId, $regionId, $requestedCidr,
|
||||
$requested, $prefixLength, $vpcKey, $providedVpcKey
|
||||
): CloudPrivateNetwork {
|
||||
$config = CloudPrivateCidrAllocatorConfig::where(
|
||||
'id', self::CONFIG_ID
|
||||
)->first();
|
||||
if ($config === null) {
|
||||
throw new CloudError('私网 CIDR 分配器尚未初始化', 503);
|
||||
}
|
||||
$pool = self::poolConfig($config);
|
||||
self::assertPrefixAllowed($prefixLength, $pool);
|
||||
|
||||
$existing = CloudPrivateNetwork::where(
|
||||
'allocation_key', $allocationKey
|
||||
)->lockForUpdate()->first();
|
||||
if ($existing !== null) {
|
||||
self::assertIdempotent(
|
||||
$existing,
|
||||
$providedVpcKey === null
|
||||
? (string) $existing->vpc_key : $vpcKey,
|
||||
$userId, $regionId, $requestedCidr, $prefixLength,
|
||||
);
|
||||
return $existing;
|
||||
}
|
||||
$sameVpc = CloudPrivateNetwork::where('vpc_key', $vpcKey)
|
||||
->lockForUpdate()->first();
|
||||
if ($sameVpc !== null) {
|
||||
throw new CloudError('该 VPC 已存在私网 CIDR 分配', 409);
|
||||
}
|
||||
|
||||
if ($requested !== null
|
||||
&& !self::within(
|
||||
$requested['network'], $requested['broadcast'], $pool
|
||||
)) {
|
||||
throw new CloudError('请求的私网 CIDR 不在全局地址池内', 409);
|
||||
}
|
||||
$occupied = self::occupied($pool);
|
||||
$candidate = $requested ?? self::firstFree(
|
||||
$occupied, $pool, $prefixLength
|
||||
);
|
||||
if ($candidate === null) {
|
||||
throw new CloudError('全局私网 CIDR 地址池已耗尽', 409);
|
||||
}
|
||||
foreach ($occupied as $row) {
|
||||
if (self::overlaps(
|
||||
$candidate['network'], $candidate['broadcast'], $row
|
||||
)) {
|
||||
throw new CloudError('请求的私网 CIDR 与现有 VPC 重叠', 409);
|
||||
}
|
||||
}
|
||||
|
||||
self::claimCandidate($candidate, $allocationKey);
|
||||
$now = time();
|
||||
$network = new CloudPrivateNetwork();
|
||||
$network->vpc_key = $vpcKey;
|
||||
$network->allocation_key = $allocationKey;
|
||||
$network->user_id = $userId;
|
||||
$network->region_id = $regionId;
|
||||
$network->cidr = $candidate['cidr'];
|
||||
$network->requested_cidr = $requested === null
|
||||
? null : $requested['cidr'];
|
||||
$network->active_cidr = $candidate['cidr'];
|
||||
$network->network_address = $candidate['network'];
|
||||
$network->broadcast_address = $candidate['broadcast'];
|
||||
$network->prefix_length = $candidate['prefix'];
|
||||
$network->state = 'active';
|
||||
$network->revision = 1;
|
||||
$network->created_at = $now;
|
||||
$network->updated_at = $now;
|
||||
$network->released_at = null;
|
||||
$network->save();
|
||||
return $network;
|
||||
});
|
||||
} catch (\Throwable $error) {
|
||||
// A unique claim/network key can be lost to a concurrent
|
||||
// worker. A fresh transaction observes its committed row and
|
||||
// either returns an idempotent result or chooses the next
|
||||
// free candidate. Explicit requests eventually become a
|
||||
// normal 409 once the winner is visible.
|
||||
if (!self::isDuplicateKey($error)
|
||||
&& !self::isTransientConflict($error)
|
||||
&& !($error instanceof CloudPrivateCidrClaimConflict)) {
|
||||
throw $error;
|
||||
}
|
||||
if ($attempt + 1 >= self::MAX_ALLOCATION_RETRIES) {
|
||||
throw new CloudError(
|
||||
$requested === null
|
||||
? '私网 CIDR 并发分配冲突,请稍后重试'
|
||||
: '请求的私网 CIDR 已被其他 VPC 占用',
|
||||
409,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new CloudError('私网 CIDR 分配未完成,请稍后重试', 409);
|
||||
}
|
||||
|
||||
/** Compare-and-swap a network lifecycle state under its own row lock. */
|
||||
public static function compareAndSwapState(string $allocationKey,
|
||||
int $expectedRevision, string $from, string $to): CloudPrivateNetwork
|
||||
{
|
||||
self::assertKey($allocationKey, 'CIDR 分配请求');
|
||||
if ($expectedRevision < 1 || !in_array($from, self::LIVE_STATES, true)
|
||||
|| !in_array($to, self::STATES, true)) {
|
||||
throw new CloudError('私网 CIDR 状态变更参数无效', 422);
|
||||
}
|
||||
return self::transition($allocationKey, $expectedRevision, $from, $to);
|
||||
}
|
||||
|
||||
/** Release any live allocation with an explicit revision check. */
|
||||
public static function release(string $allocationKey, int $expectedRevision): CloudPrivateNetwork
|
||||
{
|
||||
self::assertKey($allocationKey, 'CIDR 分配请求');
|
||||
if ($expectedRevision < 1) {
|
||||
throw new CloudError('私网 CIDR 状态变更参数无效', 422);
|
||||
}
|
||||
$connection = (new CloudPrivateNetwork())->getConnection();
|
||||
return $connection->transaction(function () use (
|
||||
$allocationKey, $expectedRevision
|
||||
): CloudPrivateNetwork {
|
||||
$network = CloudPrivateNetwork::where('allocation_key', $allocationKey)
|
||||
->lockForUpdate()->first();
|
||||
if ($network === null) {
|
||||
throw new CloudError('私网 CIDR 分配记录不存在', 404);
|
||||
}
|
||||
if (!in_array((string) $network->state, self::LIVE_STATES, true)
|
||||
|| (int) $network->revision !== $expectedRevision) {
|
||||
throw new CloudError('私网 CIDR 状态已被其他操作更新,请重新读取', 409);
|
||||
}
|
||||
self::deleteClaims($allocationKey);
|
||||
return self::markReleased($network, $expectedRevision);
|
||||
});
|
||||
}
|
||||
|
||||
/** Return a canonical RFC1918 IPv4 network description without the DB. */
|
||||
public static function normalize(string $cidr, ?int $expectedPrefix = null): array
|
||||
{
|
||||
$normalized = self::normalizeCidr($cidr, $expectedPrefix);
|
||||
if (!self::isRfc1918($normalized['network'], $normalized['broadcast'])) {
|
||||
throw new CloudError('私网 CIDR 必须使用 RFC1918 地址', 422);
|
||||
}
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private static function transition(string $allocationKey, int $expectedRevision,
|
||||
string $from, string $to): CloudPrivateNetwork
|
||||
{
|
||||
$connection = (new CloudPrivateNetwork())->getConnection();
|
||||
return $connection->transaction(function () use (
|
||||
$allocationKey, $expectedRevision, $from, $to
|
||||
): CloudPrivateNetwork {
|
||||
$network = CloudPrivateNetwork::where('allocation_key', $allocationKey)
|
||||
->lockForUpdate()->first();
|
||||
if ($network === null) {
|
||||
throw new CloudError('私网 CIDR 分配记录不存在', 404);
|
||||
}
|
||||
if ((int) $network->revision !== $expectedRevision
|
||||
|| (string) $network->state !== $from) {
|
||||
throw new CloudError('私网 CIDR 状态已被其他操作更新,请重新读取', 409);
|
||||
}
|
||||
if ($to === 'released') {
|
||||
self::deleteClaims($allocationKey);
|
||||
return self::markReleased($network, $expectedRevision);
|
||||
}
|
||||
if ($network->active_cidr === null) {
|
||||
throw new CloudError('已释放的私网 CIDR 不允许恢复', 409);
|
||||
}
|
||||
$network->state = $to;
|
||||
$network->revision = $expectedRevision + 1;
|
||||
$network->updated_at = time();
|
||||
$network->save();
|
||||
return $network;
|
||||
});
|
||||
}
|
||||
|
||||
private static function markReleased(CloudPrivateNetwork $network,
|
||||
int $expectedRevision): CloudPrivateNetwork
|
||||
{
|
||||
$network->state = 'released';
|
||||
$network->revision = $expectedRevision + 1;
|
||||
$network->active_cidr = null;
|
||||
$network->released_at = time();
|
||||
$network->updated_at = (int) $network->released_at;
|
||||
$network->save();
|
||||
return $network;
|
||||
}
|
||||
|
||||
private static function deleteClaims(string $allocationKey): void
|
||||
{
|
||||
CloudPrivateCidrClaim::where('allocation_key', $allocationKey)->delete();
|
||||
}
|
||||
|
||||
/** @param array{network:int,broadcast:int,cidr:string,prefix:int} $candidate */
|
||||
private static function claimCandidate(array $candidate, string $allocationKey): void
|
||||
{
|
||||
$blockSize = self::blockSize(self::QUANTUM_PREFIX_LENGTH);
|
||||
$count = 1 << (self::QUANTUM_PREFIX_LENGTH - $candidate['prefix']);
|
||||
for ($index = 0; $index < $count; $index++) {
|
||||
$block = self::description(
|
||||
$candidate['network'] + ($index * $blockSize),
|
||||
self::QUANTUM_PREFIX_LENGTH,
|
||||
);
|
||||
$claim = new CloudPrivateCidrClaim();
|
||||
$claim->block_cidr = $block['cidr'];
|
||||
$claim->allocation_key = $allocationKey;
|
||||
$claim->created_at = time();
|
||||
try {
|
||||
$claim->save();
|
||||
} catch (\Throwable $error) {
|
||||
if (self::isDuplicateKey($error)) {
|
||||
throw new CloudPrivateCidrClaimConflict($error->getMessage(), 0, $error);
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{pool:string,pool_network:int,pool_broadcast:int,min_prefix:int,max_prefix:int,quantum_prefix:int} */
|
||||
private static function poolConfig(CloudPrivateCidrAllocatorConfig $config): array
|
||||
{
|
||||
$pool = self::normalizeCidr((string) $config->pool_cidr);
|
||||
$min = (int) $config->min_prefix_length;
|
||||
$max = (int) $config->max_prefix_length;
|
||||
$quantum = (int) $config->quantum_prefix_length;
|
||||
if ($quantum !== self::QUANTUM_PREFIX_LENGTH
|
||||
|| $min < $pool['prefix'] || $min > $max || $max > $quantum
|
||||
|| $pool['prefix'] > $quantum) {
|
||||
throw new CloudError('私网 CIDR 分配器配置无效', 503);
|
||||
}
|
||||
$poolNetwork = self::ipv4ToInt($pool['network_address']);
|
||||
$poolBroadcast = self::ipv4ToInt($pool['broadcast_address']);
|
||||
if (!self::isRfc1918($poolNetwork, $poolBroadcast)) {
|
||||
throw new CloudError('私网 CIDR 分配器必须使用 RFC1918 地址池', 503);
|
||||
}
|
||||
return [
|
||||
'pool' => $pool['cidr'],
|
||||
'pool_network' => $poolNetwork,
|
||||
'pool_broadcast' => $poolBroadcast,
|
||||
'min_prefix' => $min,
|
||||
'max_prefix' => $max,
|
||||
'quantum_prefix' => $quantum,
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array{min_prefix:int,max_prefix:int} $pool */
|
||||
private static function assertPrefixAllowed(int $prefix, array $pool): void
|
||||
{
|
||||
if ($prefix < $pool['min_prefix'] || $prefix > $pool['max_prefix']
|
||||
|| $prefix > self::QUANTUM_PREFIX_LENGTH) {
|
||||
throw new CloudError('私网 CIDR 前缀不在分配器允许范围内', 422);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array{pool_network:int,pool_broadcast:int,min_prefix:int,max_prefix:int} $pool */
|
||||
private static function occupied(array $pool): array
|
||||
{
|
||||
$rows = CloudPrivateNetwork::orderBy('network_address')->orderBy('id')
|
||||
->get()->all();
|
||||
$occupied = [];
|
||||
foreach ($rows as $row) {
|
||||
$state = (string) $row->state;
|
||||
if ($state === 'released') {
|
||||
if ($row->active_cidr !== null) {
|
||||
throw new CloudError('已释放私网 CIDR 账本不一致,已停止分配', 503);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!in_array($state, self::LIVE_STATES, true)) {
|
||||
throw new CloudError('未知私网 CIDR 状态,已停止分配', 503);
|
||||
}
|
||||
$network = (int) $row->network_address;
|
||||
$broadcast = (int) $row->broadcast_address;
|
||||
$prefix = (int) $row->prefix_length;
|
||||
$expected = self::description($network, $prefix);
|
||||
if ($network < $pool['pool_network']
|
||||
|| $broadcast > $pool['pool_broadcast']
|
||||
|| $network > $broadcast
|
||||
|| $prefix < $pool['min_prefix']
|
||||
|| $prefix > $pool['max_prefix']
|
||||
|| (string) ($row->active_cidr ?? '') !== (string) $row->cidr
|
||||
|| (string) $row->cidr !== $expected['cidr']
|
||||
|| $broadcast !== $expected['broadcast']) {
|
||||
throw new CloudError('现有私网 CIDR 账本不一致,已停止分配', 503);
|
||||
}
|
||||
$occupied[] = $row;
|
||||
}
|
||||
return $occupied;
|
||||
}
|
||||
|
||||
/** @param array{pool_network:int,pool_broadcast:int} $pool */
|
||||
private static function firstFree(array $occupied, array $pool, int $prefix): ?array
|
||||
{
|
||||
$blockSize = self::blockSize($prefix);
|
||||
$candidate = $pool['pool_network'];
|
||||
foreach ($occupied as $row) {
|
||||
$start = (int) $row->network_address;
|
||||
$end = (int) $row->broadcast_address;
|
||||
if ($end < $candidate) {
|
||||
continue;
|
||||
}
|
||||
if ($start > $candidate && $candidate + $blockSize - 1 < $start) {
|
||||
break;
|
||||
}
|
||||
$next = $end + 1;
|
||||
$offset = $next - $pool['pool_network'];
|
||||
$alignedBlocks = intdiv($offset + $blockSize - 1, $blockSize);
|
||||
$candidate = $pool['pool_network'] + ($alignedBlocks * $blockSize);
|
||||
}
|
||||
if ($candidate < $pool['pool_network']
|
||||
|| $candidate + $blockSize - 1 > $pool['pool_broadcast']) {
|
||||
return null;
|
||||
}
|
||||
return self::description($candidate, $prefix);
|
||||
}
|
||||
|
||||
/** @return array{cidr:string,network:int,broadcast:int,prefix:int,network_address:string,broadcast_address:string} */
|
||||
private static function normalizeCidr(string $cidr, ?int $expectedPrefix = null): array
|
||||
{
|
||||
if (PHP_INT_SIZE < 8) {
|
||||
throw new CloudError('当前 PHP 平台不支持安全的 IPv4 CIDR 分配', 503);
|
||||
}
|
||||
$parts = explode('/', trim($cidr), 2);
|
||||
if (count($parts) !== 2 || filter_var($parts[0], FILTER_VALIDATE_IP,
|
||||
FILTER_FLAG_IPV4) === false || preg_match(
|
||||
'/^(?:[0-9]|[12][0-9]|3[0-2])$/D', $parts[1]
|
||||
) !== 1) {
|
||||
throw new CloudError('私网 CIDR 格式无效', 422);
|
||||
}
|
||||
$prefix = (int) $parts[1];
|
||||
if ($expectedPrefix !== null && $prefix !== $expectedPrefix) {
|
||||
throw new CloudError('私网 CIDR 前缀与请求不一致', 422);
|
||||
}
|
||||
$address = self::ipv4ToInt($parts[0]);
|
||||
$blockSize = self::blockSize($prefix);
|
||||
$network = intdiv($address, $blockSize) * $blockSize;
|
||||
$broadcast = $network + $blockSize - 1;
|
||||
return self::description($network, $prefix, $broadcast);
|
||||
}
|
||||
|
||||
private static function description(int $network, int $prefix,
|
||||
?int $broadcast = null): array
|
||||
{
|
||||
$broadcast ??= $network + self::blockSize($prefix) - 1;
|
||||
return [
|
||||
'cidr' => self::intToIpv4($network) . '/' . $prefix,
|
||||
'network' => $network,
|
||||
'broadcast' => $broadcast,
|
||||
'prefix' => $prefix,
|
||||
'network_address' => self::intToIpv4($network),
|
||||
'broadcast_address' => self::intToIpv4($broadcast),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array{network:int,broadcast:int} $candidate */
|
||||
private static function within(int $network, int $broadcast, array $pool): bool
|
||||
{
|
||||
return $network >= $pool['pool_network']
|
||||
&& $broadcast <= $pool['pool_broadcast'];
|
||||
}
|
||||
|
||||
/** @param object{network_address:int,broadcast_address:int} $row */
|
||||
private static function overlaps(int $network, int $broadcast, $row): bool
|
||||
{
|
||||
return $network <= (int) $row->broadcast_address
|
||||
&& $broadcast >= (int) $row->network_address;
|
||||
}
|
||||
|
||||
private static function blockSize(int $prefix): int
|
||||
{
|
||||
if ($prefix < 0 || $prefix > 30) {
|
||||
throw new CloudError('私网 CIDR 前缀无效', 422);
|
||||
}
|
||||
return 1 << (32 - $prefix);
|
||||
}
|
||||
|
||||
private static function ipv4ToInt(string $value): int
|
||||
{
|
||||
$packed = inet_pton($value);
|
||||
if ($packed === false || strlen($packed) !== 4) {
|
||||
throw new CloudError('私网 CIDR 地址无效', 422);
|
||||
}
|
||||
$parts = unpack('Nnumber', $packed);
|
||||
if (!is_array($parts) || !isset($parts['number'])) {
|
||||
throw new CloudError('私网 CIDR 地址无效', 422);
|
||||
}
|
||||
return (int) sprintf('%u', $parts['number']);
|
||||
}
|
||||
|
||||
private static function intToIpv4(int $value): string
|
||||
{
|
||||
if ($value < 0 || $value > 4294967295) {
|
||||
throw new CloudError('私网 CIDR 地址超出 IPv4 范围', 422);
|
||||
}
|
||||
$packed = pack('N', $value);
|
||||
$result = inet_ntop($packed);
|
||||
if ($result === false) {
|
||||
throw new CloudError('私网 CIDR 地址无效', 422);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function isRfc1918(int $network, int $broadcast): bool
|
||||
{
|
||||
foreach ([
|
||||
[self::ipv4ToInt('10.0.0.0'), self::ipv4ToInt('10.255.255.255')],
|
||||
[self::ipv4ToInt('172.16.0.0'), self::ipv4ToInt('172.31.255.255')],
|
||||
[self::ipv4ToInt('192.168.0.0'), self::ipv4ToInt('192.168.255.255')],
|
||||
] as [$start, $end]) {
|
||||
if ($network >= $start && $broadcast <= $end) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function assertKey(string $value, string $label): void
|
||||
{
|
||||
if (preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) {
|
||||
throw new CloudError($label . '标识无效', 422);
|
||||
}
|
||||
}
|
||||
|
||||
private static function assertIdempotent(CloudPrivateNetwork $existing,
|
||||
string $vpcKey, int $userId, int $regionId,
|
||||
?string $requestedCidr, int $prefixLength): void
|
||||
{
|
||||
$requested = $requestedCidr === null ? null
|
||||
: self::normalizeCidr($requestedCidr, $prefixLength)['cidr'];
|
||||
if ((string) $existing->vpc_key !== $vpcKey
|
||||
|| (int) $existing->user_id !== $userId
|
||||
|| (int) $existing->region_id !== $regionId
|
||||
|| (int) $existing->prefix_length !== $prefixLength
|
||||
|| (string) ($existing->requested_cidr ?? '')
|
||||
!== (string) ($requested ?? '')) {
|
||||
throw new CloudError('CIDR 分配请求标识已用于另一组参数', 409);
|
||||
}
|
||||
}
|
||||
|
||||
private static function isDuplicateKey(\Throwable $error): bool
|
||||
{
|
||||
$info = isset($error->errorInfo) ? $error->errorInfo : null;
|
||||
return is_array($info) && (($info[0] ?? null) === '23000'
|
||||
|| (int) ($info[1] ?? 0) === 1062)
|
||||
|| str_contains(strtolower($error->getMessage()), 'duplicate');
|
||||
}
|
||||
|
||||
private static function isTransientConflict(\Throwable $error): bool
|
||||
{
|
||||
$info = isset($error->errorInfo) ? $error->errorInfo : null;
|
||||
$sqlState = is_array($info) ? (string) ($info[0] ?? '') : '';
|
||||
$driverCode = is_array($info) ? (int) ($info[1] ?? 0) : 0;
|
||||
return $sqlState === '40001' || in_array($driverCode, [1205, 1213], true);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** Internal retry signal for a /24 claim lost to another allocator worker. */
|
||||
final class CloudPrivateCidrClaimConflict extends \RuntimeException
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
use App\Models\CloudPrivateCidrAllocatorConfig;
|
||||
use App\Models\CloudPrivateCidrClaim;
|
||||
use App\Models\CloudPrivateNetwork;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudPrivateCidrAllocator;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
// The contract portion is intentionally useful even on a checkout without a
|
||||
// PHP runtime. The SQLite section below exercises canonicalisation,
|
||||
// idempotency, overlap rejection, release/reuse and revision CAS when the
|
||||
// project's normal PHP dependencies are available.
|
||||
$root = dirname(__DIR__);
|
||||
$schemaSource = file_get_contents($root . '/sql/cloud.sql');
|
||||
$serviceSource = file_get_contents($root
|
||||
. '/app/Services/Cloud/CloudPrivateCidrAllocator.php');
|
||||
$modelSource = file_get_contents($root . '/app/Models/CloudPrivateNetwork.php');
|
||||
$configModelSource = file_get_contents($root
|
||||
. '/app/Models/CloudPrivateCidrAllocatorConfig.php');
|
||||
$claimModelSource = file_get_contents($root
|
||||
. '/app/Models/CloudPrivateCidrClaim.php');
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$assert(is_string($schemaSource)
|
||||
&& str_contains($schemaSource,
|
||||
'CREATE TABLE IF NOT EXISTS cloud_private_cidr_allocator_configs (')
|
||||
&& str_contains($schemaSource,
|
||||
'CREATE TABLE IF NOT EXISTS cloud_private_cidr_claims (')
|
||||
&& str_contains($schemaSource,
|
||||
'CREATE TABLE IF NOT EXISTS cloud_private_networks (')
|
||||
&& str_contains($schemaSource,
|
||||
'UNIQUE KEY cloud_private_network_active_cidr (active_cidr)')
|
||||
&& str_contains($schemaSource,
|
||||
'UNIQUE KEY cloud_private_cidr_claim_block (block_cidr)')
|
||||
&& str_contains($schemaSource, 'requested_cidr VARCHAR(18)')
|
||||
&& str_contains($schemaSource,
|
||||
'KEY cloud_private_network_overlap (state, network_address, broadcast_address, id)')
|
||||
&& str_contains($schemaSource,
|
||||
"VALUES (1, '10.0.0.0/8', 24, 16, 24, 1, UNIX_TIMESTAMP())"),
|
||||
'Global private CIDR schema lost its quantum claim, interval index or seed.');
|
||||
$assert(is_string($serviceSource)
|
||||
&& str_contains($serviceSource, 'claimCandidate')
|
||||
&& str_contains($serviceSource, 'CloudPrivateCidrClaimConflict')
|
||||
&& str_contains($serviceSource, '->transaction(')
|
||||
&& str_contains($serviceSource, 'self::LIVE_STATES')
|
||||
&& str_contains($serviceSource, '未知私网 CIDR 状态')
|
||||
&& str_contains($serviceSource, 'compareAndSwapState')
|
||||
&& str_contains($serviceSource, 'active_cidr')
|
||||
&& str_contains($serviceSource, 'isTransientConflict')
|
||||
&& !str_contains($serviceSource, 'CloudPrivateCidrAllocatorLock')
|
||||
&& !str_contains($serviceSource, "CloudPrivateCidrAllocatorConfig::where(\n 'id', self::CONFIG_ID\n )->lockForUpdate()"),
|
||||
'CIDR allocation no longer uses a database transaction, overlap ledger and CAS.');
|
||||
$assert(is_string($modelSource)
|
||||
&& str_contains($modelSource, "protected \$table = 'cloud_private_networks';")
|
||||
&& is_string($configModelSource)
|
||||
&& str_contains($configModelSource,
|
||||
"protected \$table = 'cloud_private_cidr_allocator_configs';")
|
||||
&& is_string($claimModelSource)
|
||||
&& str_contains($claimModelSource,
|
||||
"protected \$table = 'cloud_private_cidr_claims';"),
|
||||
'Private CIDR Eloquent boundaries are missing.');
|
||||
|
||||
if (!is_file($root . '/vendor/autoload.php')) {
|
||||
echo "Cloud private CIDR schema and source contracts passed (runtime skipped).\n";
|
||||
return;
|
||||
}
|
||||
require $root . '/vendor/autoload.php';
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('cloud_private_cidr_allocator_configs', static function (Blueprint $table): void {
|
||||
$table->unsignedTinyInteger('id')->primary();
|
||||
$table->string('pool_cidr', 18);
|
||||
$table->unsignedTinyInteger('quantum_prefix_length');
|
||||
$table->unsignedTinyInteger('min_prefix_length');
|
||||
$table->unsignedTinyInteger('max_prefix_length');
|
||||
$table->unsignedBigInteger('revision');
|
||||
$table->unsignedBigInteger('updated_at');
|
||||
});
|
||||
$schema->create('cloud_private_cidr_claims', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('block_cidr', 18)->unique();
|
||||
$table->string('allocation_key', 32);
|
||||
$table->unsignedBigInteger('created_at');
|
||||
$table->index(['allocation_key', 'block_cidr']);
|
||||
});
|
||||
$schema->create('cloud_private_networks', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('vpc_key', 32)->unique();
|
||||
$table->string('allocation_key', 32)->unique();
|
||||
$table->unsignedInteger('user_id');
|
||||
$table->unsignedInteger('region_id');
|
||||
$table->string('cidr', 18);
|
||||
$table->string('requested_cidr', 18)->nullable();
|
||||
$table->string('active_cidr', 18)->nullable()->unique();
|
||||
$table->unsignedBigInteger('network_address');
|
||||
$table->unsignedBigInteger('broadcast_address');
|
||||
$table->unsignedTinyInteger('prefix_length');
|
||||
$table->string('state', 16);
|
||||
$table->unsignedBigInteger('revision');
|
||||
$table->unsignedBigInteger('created_at');
|
||||
$table->unsignedBigInteger('updated_at');
|
||||
$table->unsignedBigInteger('released_at')->nullable();
|
||||
});
|
||||
$config = new CloudPrivateCidrAllocatorConfig();
|
||||
$config->id = 1;
|
||||
$config->pool_cidr = '10.0.0.0/8';
|
||||
$config->quantum_prefix_length = 24;
|
||||
$config->min_prefix_length = 16;
|
||||
$config->max_prefix_length = 24;
|
||||
$config->revision = 1;
|
||||
$config->updated_at = time();
|
||||
$config->save();
|
||||
|
||||
$key = str_repeat('a', 32);
|
||||
$vpc = str_repeat('b', 32);
|
||||
$first = CloudPrivateCidrAllocator::allocate($key, 7, 1, null, 24, $vpc);
|
||||
$assert($first->cidr === '10.0.0.0/24'
|
||||
&& $first->active_cidr === $first->cidr, 'First global CIDR was not canonical.');
|
||||
$assert(CloudPrivateCidrClaim::where('allocation_key', $key)->count() === 1,
|
||||
'The active network did not claim its /24 quantum.');
|
||||
$second = CloudPrivateCidrAllocator::allocate(str_repeat('c', 32), 8, 2,
|
||||
null, 24, str_repeat('d', 32));
|
||||
$assert($second->cidr === '10.0.1.0/24',
|
||||
'Automatic CIDR allocation did not advance to the next aligned block.');
|
||||
$retry = CloudPrivateCidrAllocator::allocate($key, 7, 1, null, 24, $vpc);
|
||||
$assert((int) $retry->id === (int) $first->id,
|
||||
'A repeated allocation key created a second private network.');
|
||||
|
||||
$expectConflict = static function (callable $operation, string $message) use ($assert): void {
|
||||
try {
|
||||
$operation();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409, $message . ' returned the wrong status.');
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException($message);
|
||||
};
|
||||
$expectConflict(static fn () => CloudPrivateCidrAllocator::allocate(
|
||||
str_repeat('e', 32), 9, 3, '10.0.0.1/24', 24, str_repeat('f', 32)
|
||||
), 'Overlapping CIDR was accepted.');
|
||||
$expectConflict(static fn () => CloudPrivateCidrAllocator::allocate(
|
||||
$key, 99, 1, null, 24, $vpc
|
||||
), 'Allocation-key parameter drift was accepted.');
|
||||
|
||||
$released = CloudPrivateCidrAllocator::release($key, 1);
|
||||
$assert($released->state === 'released' && $released->active_cidr === null
|
||||
&& (int) $released->revision === 2,
|
||||
'Release did not clear the active claim and advance its revision.');
|
||||
$assert(CloudPrivateCidrClaim::where('allocation_key', $key)->count() === 0,
|
||||
'Release did not remove the reusable quantum claim.');
|
||||
$reused = CloudPrivateCidrAllocator::allocate(str_repeat('1', 32), 10, 1,
|
||||
'10.0.0.0/24', 24, str_repeat('2', 32));
|
||||
$assert($reused->cidr === '10.0.0.0/24',
|
||||
'A released CIDR was not safely reusable under quantum claims.');
|
||||
$expectConflict(static fn () => CloudPrivateCidrAllocator::release($key, 1),
|
||||
'A stale revision released a CIDR a second time.');
|
||||
|
||||
$normalized = CloudPrivateCidrAllocator::normalize('10.2.3.4/16', 16);
|
||||
$assert($normalized['cidr'] === '10.2.0.0/16'
|
||||
&& $normalized['broadcast_address'] === '10.2.255.255',
|
||||
'CIDR canonicalisation or broadcast calculation is incorrect.');
|
||||
|
||||
echo "Cloud private CIDR allocation schema, overlap, idempotency, release and CAS tests passed.\n";
|
||||
Loading…
Reference in New Issue