You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudAdminTrafficPoolServic...

794 lines
30 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudInstanceNetworkPolicyState;
use App\Models\CloudInstanceNetworkRestriction;
use App\Models\CloudNetworkLine;
use App\Models\CloudOrder;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\CloudServicePeriod;
use App\Models\CloudTrafficEntitlement;
use App\Models\CloudTrafficInstanceCursor;
use App\Models\CloudTrafficPool;
use App\Models\CloudTrafficPoolGroup;
use App\Models\CloudTrafficScanFailure;
use Illuminate\Database\QueryException;
/** Administrator traffic-pool catalog, rollout state machine and safety gate. */
final class CloudAdminTrafficPoolService
{
private const MODES = ['disabled', 'shadow', 'enforced'];
private const SAMPLE_FRESHNESS_SECONDS = 300;
private const BLOCKER_LABELS = [
'no_network_lines' => '尚未绑定线路',
'line_frozen_identity_mismatch' => '订单或服务周期的冻结身份不一致',
'pool_attention' => '账本池需要人工核查',
'projection_invalid' => '账本投影校验失败',
'missing_entitlements' => '服务周期缺少流量权益',
'missing_pools' => '流量权益缺少账本池',
'period_identity_mismatch' => '服务周期与流量权益不一致',
'instance_not_ready' => '实例尚未达到核算条件',
'usage_unsettled' => '最新流量尚未完成结算',
'legacy_network_unsettled' => '实例网络状态尚未收敛',
'cursor_attention' => '实例核算游标需要人工核查',
'cursor_missing' => '实例缺少有效核算游标',
'traffic_sample_stale' => '流量采样已过期',
'traffic_scan_failures' => '流量扫描存在失败记录',
'policy_unsettled' => '实例网络策略尚未应用',
'traffic_restriction_present' => '仍有线路流量池断网限制',
'network_job_unsettled' => '仍有网络任务未完成',
];
public static function page(array $query = []): array
{
$items = [];
$summary = [
'groups_total' => 0,
'disabled' => 0,
'shadow' => 0,
'enforced' => 0,
'ready_to_enforce' => 0,
];
foreach (CloudTrafficPoolGroup::orderBy('id')->get() as $group) {
$item = self::groupDto($group);
$items[] = $item;
$summary['groups_total']++;
$summary[$item['mode']]++;
if ($item['readiness']['can_enforce']) {
$summary['ready_to_enforce']++;
}
}
return [
'items' => $items,
'lines' => self::lineCatalog(),
'summary' => $summary,
'sample_freshness_seconds' => self::SAMPLE_FRESHNESS_SECONDS,
'generated_at' => time(),
];
}
public static function read(int $groupId): array
{
return ['item' => self::groupDto(self::findGroup($groupId))];
}
public static function create(array $input): array
{
$code = self::code($input['code'] ?? null);
$name = self::name($input['name'] ?? null);
$connection = (new CloudTrafficPoolGroup())->getConnection();
try {
$groupId = $connection->transaction(function () use (
$code,
$name
): int {
if (CloudTrafficPoolGroup::where('code', $code)->exists()) {
throw new CloudError('线路流量池标识已存在', 409);
}
$now = time();
$group = new CloudTrafficPoolGroup();
$group->code = $code;
$group->name = $name;
$group->mode = 'disabled';
$group->revision = 1;
$group->created_at = $now;
$group->updated_at = $now;
$group->save();
return (int) $group->id;
}, 3);
} catch (QueryException $error) {
if (CloudTrafficPoolGroup::where('code', $code)->exists()) {
throw new CloudError('线路流量池标识已存在', 409);
}
throw $error;
}
return self::read($groupId);
}
public static function update(int $groupId, array $input): array
{
$expectedRevision = self::revision(
$input['expected_revision'] ?? null
);
$hint = self::findGroup($groupId);
$savedId = $hint->getConnection()->transaction(function () use (
$groupId,
$input,
$expectedRevision
): int {
$group = CloudTrafficPoolGroup::where('id', $groupId)
->lockForUpdate()->first();
if ($group === null) {
throw new CloudError('线路流量池不存在', 404);
}
self::assertRevision($group, $expectedRevision);
$name = array_key_exists('name', $input)
? self::name($input['name']) : (string) $group->name;
$mode = array_key_exists('mode', $input)
? self::mode($input['mode']) : (string) $group->mode;
self::assertModeTransition($group, $mode);
$group->name = $name;
$group->mode = $mode;
$group->revision = (int) $group->revision + 1;
$group->updated_at = time();
$group->save();
return (int) $group->id;
}, 3);
return self::read($savedId);
}
public static function replaceLines(int $groupId, array $input): array
{
$requested = self::lineIds($input['line_ids'] ?? null);
$expectedRevision = self::revision(
$input['expected_revision'] ?? null
);
$hint = self::findGroup($groupId);
$savedId = $hint->getConnection()->transaction(function () use (
$groupId,
$requested,
$expectedRevision
): int {
// Mapping is rare administrator work. Locking the complete line
// catalog provides one deterministic line(id ASC) -> group seam
// shared by purchases and concurrent group mappings.
$lines = CloudNetworkLine::where('id', '>', 0)
->orderBy('id')->lockForUpdate()->get();
$group = CloudTrafficPoolGroup::where('id', $groupId)
->lockForUpdate()->first();
if ($group === null) {
throw new CloudError('线路流量池不存在', 404);
}
self::assertRevision($group, $expectedRevision);
if ((string) $group->mode !== 'disabled') {
throw new CloudError(
'只有停用状态的线路流量池可以调整覆盖线路',
409
);
}
$byId = [];
foreach ($lines as $line) {
$byId[(int) $line->id] = $line;
}
foreach ($requested as $lineId) {
if (!isset($byId[$lineId])) {
throw new CloudError('所选线路不存在', 404);
}
$owner = $byId[$lineId]->traffic_pool_group_id;
if ($owner !== null && (int) $owner !== $groupId) {
throw new CloudError('所选线路已属于其他线路流量池', 409);
}
}
$removed = [];
foreach ($byId as $lineId => $line) {
if ((int) ($line->traffic_pool_group_id ?? 0) === $groupId
&& !in_array($lineId, $requested, true)) {
$removed[] = $lineId;
}
}
self::assertLinesMayLeave($groupId, $removed);
$now = time();
if ($removed !== []) {
CloudNetworkLine::whereIn('id', $removed)->update([
'traffic_pool_group_id' => null,
'updated_at' => $now,
]);
}
if ($requested !== []) {
CloudNetworkLine::whereIn('id', $requested)->update([
'traffic_pool_group_id' => $groupId,
'updated_at' => $now,
]);
}
$group->revision = (int) $group->revision + 1;
$group->updated_at = $now;
$group->save();
return (int) $group->id;
}, 3);
return self::read($savedId);
}
public static function readiness(
int $groupId,
?int $now = null
): array {
return self::buildReadiness(self::findGroup($groupId), $now ?? time());
}
private static function assertModeTransition(
CloudTrafficPoolGroup $group,
string $target
): void {
$current = (string) $group->mode;
if ($target === $current) {
return;
}
if ($current === 'enforced') {
throw new CloudError(
'已强制执行的线路流量池禁止回退或停用',
409
);
}
if ($current === 'disabled' && $target === 'shadow') {
if (!CloudNetworkLine::where(
'traffic_pool_group_id', (int) $group->id
)->exists()) {
throw new CloudError('进入影子核算前必须至少绑定一条线路', 409);
}
return;
}
if ($current === 'shadow' && $target === 'disabled') {
if (self::hasDurableReferences((int) $group->id)) {
throw new CloudError(
'线路流量池已生成冻结周期或账本投影,禁止停用',
409
);
}
return;
}
if ($current === 'shadow' && $target === 'enforced') {
$readiness = self::buildReadiness($group, time());
if (!$readiness['ready']) {
throw new CloudError(
'流量池尚未就绪:' . implode(',', array_column(
$readiness['blockers'],
'code'
)),
409
);
}
return;
}
throw new CloudError(
'流量池必须按停用、影子核算、强制执行顺序启用',
409
);
}
private static function buildReadiness(
CloudTrafficPoolGroup $group,
int $now
): array {
$groupId = (int) $group->id;
$blockers = [];
$lineIds = CloudNetworkLine::where(
'traffic_pool_group_id', $groupId
)->orderBy('id')->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$lineCount = count($lineIds);
if ($lineCount === 0) {
self::block($blockers, 'no_network_lines');
}
$resourcePoolIds = $lineIds === [] ? []
: CloudResourcePool::whereIn('line_id', $lineIds)
->pluck('id')->map(static fn ($id): int => (int) $id)->all();
if ($resourcePoolIds !== []) {
$orders = CloudOrder::whereIn(
'resource_pool_id', $resourcePoolIds
)->whereIn('status', ['awaiting_payment', 'queued', 'failed'])
->orderBy('id')->get(['id', 'status', 'spec_json']);
$failedOrderIds = $orders->filter(
static fn ($order): bool =>
(string) $order->status === 'failed'
)->pluck('id')->map(static fn ($id): int => (int) $id)->all();
$recoverableFailed = $failedOrderIds === [] ? []
: CloudJobService::blockingCreateQueryForOrders(
$failedOrderIds
)->pluck('order_id')->map(
static fn ($id): int => (int) $id
)->flip()->all();
foreach ($orders as $order) {
if ((string) $order->status === 'failed'
&& !isset($recoverableFailed[(int) $order->id])) {
continue;
}
$spec = json_decode((string) $order->spec_json, true);
if (!is_array($spec)
|| !is_int($spec['traffic_pool_group_id'] ?? null)
|| $spec['traffic_pool_group_id'] !== $groupId) {
self::block(
$blockers,
'line_frozen_identity_mismatch',
(int) $order->id
);
}
}
$mismatchedPeriods = CloudServicePeriod::query()
->join('cloud_instances as readiness_instance',
'readiness_instance.id', '=',
'cloud_service_periods.instance_id')
->whereIn('readiness_instance.resource_pool_id',
$resourcePoolIds)
->where('cloud_service_periods.traffic_quota_mode', 'finite')
->whereIn('cloud_service_periods.status',
['scheduled', 'active', 'exhausted'])
->where(function ($query) use ($groupId): void {
$query->whereNull(
'cloud_service_periods.traffic_pool_group_id'
)->orWhere(
'cloud_service_periods.traffic_pool_group_id',
'<>',
$groupId
);
})->orderBy('cloud_service_periods.id')
->get(['cloud_service_periods.id']);
foreach ($mismatchedPeriods as $period) {
self::block(
$blockers,
'line_frozen_identity_mismatch',
(int) $period->id
);
}
}
$periods = CloudServicePeriod::where(
'traffic_pool_group_id', $groupId
)->where('traffic_quota_mode', 'finite')->whereIn(
'status', ['scheduled', 'active', 'exhausted']
)->orderBy('id')->get();
$scanPeriodIds = CloudServicePeriod::where(
'traffic_pool_group_id', $groupId
)->orderBy('id')->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$periodIds = [];
$instanceIds = [];
$activePeriods = [];
$expectedPoolByInstance = [];
$poolById = [];
foreach (CloudTrafficPool::where(
'traffic_pool_group_id', $groupId
)->orderBy('id')->get() as $pool) {
$poolById[(int) $pool->id] = $pool;
if ((string) $pool->state === 'attention') {
self::block($blockers, 'pool_attention', (int) $pool->id);
}
try {
$verification = CloudTrafficPoolAccounting::verifyProjection(
(int) $pool->id,
$now
);
if (!($verification['valid'] ?? false)) {
self::block(
$blockers,
'projection_invalid',
(int) $pool->id
);
}
} catch (\Throwable) {
self::block(
$blockers,
'projection_invalid',
(int) $pool->id
);
}
}
foreach ($periods as $period) {
$periodId = (int) $period->id;
$instanceId = (int) $period->instance_id;
$periodIds[] = $periodId;
$instanceIds[$instanceId] = true;
$entitlement = CloudTrafficEntitlement::where(
'service_period_id', $periodId
)->first();
if ($entitlement === null) {
self::block($blockers, 'missing_entitlements', $periodId);
} else {
$pool = $poolById[(int) $entitlement->pool_id] ?? null;
$identityMatches = $pool !== null
&& (int) $pool->user_id === (int) $period->user_id
&& (int) $entitlement->user_id === (int) $period->user_id
&& (int) $entitlement->instance_id === $instanceId
&& (int) $entitlement->starts_at
=== (int) $period->starts_at
&& (int) $entitlement->ends_at === (int) $period->ends_at
&& (string) $entitlement->quota_mode === 'finite'
&& (int) $entitlement->granted_bytes
=== (int) $period->traffic_quota_bytes;
$stateMatches = (string) $period->status === 'scheduled'
? ((string) $entitlement->state === 'scheduled'
&& (int) $period->starts_at > $now)
: (in_array((string) $entitlement->state,
['active', 'exhausted'], true)
&& (int) $period->starts_at <= $now
&& (int) $period->ends_at > $now);
if ($pool === null) {
self::block($blockers, 'missing_pools', $periodId);
} elseif (!$identityMatches || !$stateMatches) {
self::block(
$blockers,
'period_identity_mismatch',
$periodId
);
} else {
$expectedPoolByInstance[$instanceId] = (int) $pool->id;
}
}
if (in_array((string) $period->status,
['active', 'exhausted'], true)
&& (int) $period->starts_at <= $now
&& (int) $period->ends_at > $now) {
$activePeriods[$instanceId] = $period;
}
}
foreach ($poolById as $poolId => $pool) {
if ((string) $pool->state === 'attention') {
continue;
}
$activeFinite = CloudTrafficEntitlement::where(
'pool_id', $poolId
)->where('quota_mode', 'finite')->whereIn(
'state', ['active', 'exhausted']
)->where('starts_at', '<=', $now)->where('ends_at', '>', $now)
->count();
$expectedState = (int) $pool->overage_bytes > 0
|| ($activeFinite > 0 && (int) $pool->available_bytes === 0)
? 'exhausted' : 'available';
if ((string) $pool->state !== $expectedState) {
self::block($blockers, 'projection_invalid', $poolId);
}
}
$cursorByInstance = [];
if ($poolById !== []) {
foreach (CloudTrafficInstanceCursor::whereIn(
'pool_id', array_keys($poolById)
)->orderBy('instance_id')->get() as $cursor) {
$cursorByInstance[(int) $cursor->instance_id] = $cursor;
$instanceIds[(int) $cursor->instance_id] = true;
}
}
$instances = [];
if ($instanceIds !== []) {
foreach (CloudInstance::whereIn('id', array_keys($instanceIds))
->get() as $instance) {
$instances[(int) $instance->id] = $instance;
}
}
foreach ($cursorByInstance as $instanceId => $cursor) {
$instance = $instances[$instanceId] ?? null;
if ($instance === null) {
self::block($blockers, 'instance_not_ready', $instanceId);
continue;
}
if ((int) $cursor->accounted_download_bytes
!== (int) $instance->lifetime_download_bytes
|| (int) $cursor->accounted_upload_bytes
!== (int) $instance->lifetime_upload_bytes
|| (int) $cursor->last_observed_at
< (int) $instance->traffic_synced_at) {
self::block($blockers, 'usage_unsettled', $instanceId);
}
}
$staleBefore = $now - self::SAMPLE_FRESHNESS_SECONDS;
foreach ($activePeriods as $instanceId => $period) {
$instance = $instances[$instanceId] ?? null;
if ($instance === null || (string) $instance->status !== 'active') {
self::block($blockers, 'instance_not_ready', $instanceId);
continue;
}
if (!in_array((string) $instance->network_status, [
'active', 'blocked_traffic', 'blocked_expired',
], true)) {
self::block(
$blockers,
'legacy_network_unsettled',
$instanceId
);
}
$cursor = $cursorByInstance[$instanceId] ?? null;
$cursorPool = $cursor === null ? null
: ($poolById[(int) $cursor->pool_id] ?? null);
if ($cursor !== null && (string) $cursor->state === 'attention') {
self::block($blockers, 'cursor_attention', $instanceId);
} elseif ($cursor === null || $cursorPool === null
|| !isset($expectedPoolByInstance[$instanceId])
|| (int) $cursor->pool_id
!== $expectedPoolByInstance[$instanceId]
|| (int) $cursor->user_id !== (int) $period->user_id
|| (int) $cursorPool->user_id !== (int) $period->user_id) {
self::block($blockers, 'cursor_missing', $instanceId);
}
if ((int) $instance->traffic_synced_at < $staleBefore
|| $cursor === null
|| (int) $cursor->last_observed_at < $staleBefore) {
self::block(
$blockers,
'traffic_sample_stale',
$instanceId
);
}
}
if ($scanPeriodIds !== []) {
foreach (CloudTrafficScanFailure::where('scan_kind', 'period')
->whereIn('subject_id', $scanPeriodIds)->get() as $failure) {
self::block(
$blockers,
'traffic_scan_failures',
(int) $failure->subject_id
);
}
}
$ids = array_keys($instanceIds);
if ($ids !== []) {
foreach (CloudTrafficScanFailure::where('scan_kind', 'instance')
->whereIn('subject_id', $ids)->get() as $failure) {
self::block(
$blockers,
'traffic_scan_failures',
(int) $failure->subject_id
);
}
foreach (CloudInstanceNetworkPolicyState::whereIn(
'instance_id', $ids
)->where('state', '<>', 'applied')->get() as $state) {
self::block(
$blockers,
'policy_unsettled',
(int) $state->instance_id
);
}
foreach (CloudInstanceNetworkRestriction::whereIn(
'instance_id', $ids
)->where('reason_code', 'traffic_pool_exhausted')
->where('desired_active', 1)->get() as $restriction) {
self::block(
$blockers,
'traffic_restriction_present',
(int) $restriction->instance_id
);
}
if (CloudJobService::blockingQueryForInstances($ids)
->whereIn('kind', ['network_suspend', 'network_resume'])
->exists()) {
self::block($blockers, 'network_job_unsettled');
}
}
ksort($blockers, SORT_STRING);
$list = [];
foreach ($blockers as $code => $subjects) {
$subjectIds = array_keys($subjects);
sort($subjectIds, SORT_NUMERIC);
$list[] = [
'code' => $code,
'label' => self::BLOCKER_LABELS[$code]
?? '存在未识别的就绪阻断项',
'count' => count($subjectIds),
'subject_ids' => array_slice($subjectIds, 0, 20),
];
}
return [
'ready' => $list === [],
'can_enforce' => (string) $group->mode === 'shadow'
&& $list === [],
'checked_at' => $now,
'sample_freshness_seconds' => self::SAMPLE_FRESHNESS_SECONDS,
'line_count' => $lineCount,
'pool_count' => count($poolById),
'period_count' => count($periodIds),
'active_instance_count' => count($activePeriods),
'blockers' => $list,
];
}
private static function groupDto(CloudTrafficPoolGroup $group): array
{
$lineRows = CloudNetworkLine::where(
'traffic_pool_group_id', (int) $group->id
)->orderBy('id')->get(['id', 'region_id']);
$lineIds = $lineRows->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$regionCount = $lineRows->pluck('region_id')->map(
static fn ($id): int => (int) $id
)->filter(static fn (int $id): bool => $id > 0)
->unique()->count();
$readiness = self::buildReadiness($group, time());
$nextMode = match ((string) $group->mode) {
'disabled' => 'shadow',
'shadow' => 'enforced',
default => null,
};
return [
'id' => (int) $group->id,
'code' => (string) $group->code,
'name' => (string) $group->name,
'mode' => (string) $group->mode,
'revision' => (int) $group->revision,
'line_ids' => $lineIds,
'line_count' => count($lineIds),
'region_count' => $regionCount,
'readiness' => $readiness,
'actions' => [
'can_rename' => true,
'can_replace_lines' => (string) $group->mode === 'disabled',
'next_mode' => $nextMode,
'can_advance' => $nextMode === 'shadow'
? count($lineIds) > 0
: ($nextMode === 'enforced'
&& $readiness['ready']),
'can_disable' => (string) $group->mode === 'shadow'
&& !self::hasDurableReferences((int) $group->id),
],
'created_at' => (int) $group->created_at,
'updated_at' => (int) $group->updated_at,
];
}
private static function lineCatalog(): array
{
$lines = CloudNetworkLine::orderBy('region_id')->orderBy('sort')
->orderBy('id')->get();
$regionIds = $lines->pluck('region_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
$regions = $regionIds === [] ? collect() : CloudRegion::whereIn(
'id', $regionIds
)->pluck('name', 'id');
$items = [];
foreach ($lines as $line) {
$items[] = [
'id' => (int) $line->id,
'region_id' => (int) $line->region_id,
'region_name' => (string) (
$regions[(int) $line->region_id] ?? '未知地区'
),
'code' => (string) $line->code,
'name' => (string) $line->name,
'status' => (string) $line->status,
'traffic_pool_group_id' =>
$line->traffic_pool_group_id === null
? null : (int) $line->traffic_pool_group_id,
];
}
return $items;
}
private static function hasDurableReferences(int $groupId): bool
{
return CloudServicePeriod::where(
'traffic_pool_group_id', $groupId
)->exists() || CloudTrafficPool::where(
'traffic_pool_group_id', $groupId
)->exists();
}
private static function assertLinesMayLeave(
int $groupId,
array $lineIds
): void {
if ($lineIds === []) {
return;
}
if (self::hasDurableReferences($groupId)) {
throw new CloudError(
'线路流量池已生成冻结周期或账本投影,禁止移出线路',
409
);
}
$poolIds = CloudResourcePool::whereIn('line_id', $lineIds)
->pluck('id')->all();
if ($poolIds !== [] && (CloudOrder::whereIn(
'resource_pool_id', $poolIds
)->exists() || CloudInstance::whereIn(
'resource_pool_id', $poolIds
)->exists())) {
throw new CloudError(
'已有订单或实例冻结了所选线路,禁止移出线路流量池',
409
);
}
}
private static function findGroup(int $groupId): CloudTrafficPoolGroup
{
$group = $groupId > 0 ? CloudTrafficPoolGroup::find($groupId) : null;
if ($group === null) {
throw new CloudError('线路流量池不存在', 404);
}
return $group;
}
private static function assertRevision(
CloudTrafficPoolGroup $group,
int $expected
): void {
if ((int) $group->revision !== $expected) {
throw new CloudError('线路流量池已被其他管理员修改,请刷新后重试', 409);
}
}
private static function code(mixed $value): string
{
if (!is_string($value)) {
throw new CloudError('线路流量池标识无效');
}
$value = strtolower(trim($value));
if (preg_match('/^[a-z][a-z0-9_-]{1,63}$/D', $value) !== 1) {
throw new CloudError('线路流量池标识须为 2 至 64 位小写字母、数字、下划线或短横线');
}
return $value;
}
private static function name(mixed $value): string
{
if (!is_string($value) || ($value = trim($value)) === ''
|| mb_strlen($value) > 80) {
throw new CloudError('线路流量池名称无效');
}
return $value;
}
private static function mode(mixed $value): string
{
if (!is_string($value) || !in_array($value, self::MODES, true)) {
throw new CloudError('线路流量池模式无效');
}
return $value;
}
private static function revision(mixed $value): int
{
if (!is_int($value) || $value < 1) {
throw new CloudError('线路流量池版本无效');
}
return $value;
}
/** @return list<int> */
private static function lineIds(mixed $value): array
{
if (!is_array($value) || !array_is_list($value)
|| count($value) > 1000) {
throw new CloudError('线路列表无效');
}
$ids = [];
foreach ($value as $lineId) {
if (!is_int($lineId) || $lineId < 1) {
throw new CloudError('线路列表无效');
}
$ids[$lineId] = true;
}
$ids = array_keys($ids);
sort($ids, SORT_NUMERIC);
return $ids;
}
private static function block(
array &$blockers,
string $code,
int $subjectId = 0
): void {
$blockers[$code][$subjectId] = true;
}
}