|
|
<?php
|
|
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
|
|
use App\Models\CloudHost;
|
|
|
use App\Models\CloudHostAgent;
|
|
|
use App\Models\CloudBackupRestore;
|
|
|
use App\Models\CloudHostCapacityPolicy;
|
|
|
use App\Models\CloudHostNetworkAttachment;
|
|
|
use App\Models\CloudHostResourcePoolMembership;
|
|
|
use App\Models\CloudHostStorageConfiguration;
|
|
|
use App\Models\CloudInstance;
|
|
|
use App\Models\CloudNetworkLine;
|
|
|
use App\Models\CloudOffer;
|
|
|
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;
|
|
|
use App\Models\Shop;
|
|
|
|
|
|
/**
|
|
|
* Database-only, payment-time placement and resource reservation.
|
|
|
*
|
|
|
* The caller owns the surrounding wallet transaction. No Agent or network
|
|
|
* request is permitted here: capacity comes from the configured host policy
|
|
|
* and the durable reservation/IP ledgers, with every mutable scheduling row
|
|
|
* locked before it is consumed.
|
|
|
*/
|
|
|
final class CloudPlacementService
|
|
|
{
|
|
|
private const GIB = 1073741824;
|
|
|
private const MAX_PUBLIC_IPS_PER_POOL = 254;
|
|
|
|
|
|
/**
|
|
|
* Advisory capacity check for an already-authorized active pool chain.
|
|
|
*
|
|
|
* Catalog construction has already joined and filtered the offer, plan,
|
|
|
* pool, line and region. Keeping this method resource-only avoids loading
|
|
|
* those models once per public offer while sharing the scheduler's exact
|
|
|
* host, reservation and address predicates.
|
|
|
*/
|
|
|
public static function isPoolCapacityAvailable(int $poolId, int $cpuCores,
|
|
|
int $memoryMib, int $diskGib,
|
|
|
?CloudPortableRestoreCompatibility $portableRestore = null): bool
|
|
|
{
|
|
|
if ($portableRestore !== null) {
|
|
|
$resources = [
|
|
|
'cpu_cores' => $cpuCores,
|
|
|
'memory_mib' => $memoryMib,
|
|
|
'disk_gib' => $diskGib,
|
|
|
];
|
|
|
if ($poolId < 1 || min($resources) < 1) {
|
|
|
return false;
|
|
|
}
|
|
|
$candidateRows = self::candidateHostRows($poolId);
|
|
|
$pendingByHost = self::pendingUsageByHost($candidateRows);
|
|
|
$availableIpHosts = self::availableIpHosts($candidateRows);
|
|
|
foreach ($candidateRows as $candidate) {
|
|
|
$hostId = (int) $candidate->id;
|
|
|
if (isset($availableIpHosts[$hostId])
|
|
|
&& self::candidateSupportsPortableRestore(
|
|
|
$candidate,
|
|
|
$portableRestore
|
|
|
)
|
|
|
&& self::hasCapacity(
|
|
|
$candidate,
|
|
|
$pendingByHost[$hostId] ?? self::emptyUsage(),
|
|
|
$resources
|
|
|
)) {
|
|
|
return true;
|
|
|
}
|
|
|
}
|
|
|
return false;
|
|
|
}
|
|
|
$availability = self::poolCapacityAvailability(['single' => [
|
|
|
'pool_id' => $poolId,
|
|
|
'cpu_cores' => $cpuCores,
|
|
|
'memory_mib' => $memoryMib,
|
|
|
'disk_gib' => $diskGib,
|
|
|
]]);
|
|
|
return $availability['single'] ?? false;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Advisory same-host capacity check for a grow-only instance upgrade.
|
|
|
*
|
|
|
* The current committed reservation is removed from the usage projection
|
|
|
* before the target vector is evaluated. enqueue() repeats this under the
|
|
|
* host/policy/reservation locks; this read is only for hiding options that
|
|
|
* are already known not to fit.
|
|
|
*/
|
|
|
public static function isUpgradeCapacityAvailable(
|
|
|
CloudInstance $instance,
|
|
|
array $targetResources
|
|
|
): bool {
|
|
|
$resources = self::upgradeResources($targetResources);
|
|
|
$reservation = $instance->reservation_id === null ? null
|
|
|
: CloudResourceReservation::where(
|
|
|
'id',
|
|
|
(int) $instance->reservation_id
|
|
|
)->first();
|
|
|
$policy = CloudHostCapacityPolicy::where(
|
|
|
'host_id',
|
|
|
(int) $instance->host_id
|
|
|
)->first();
|
|
|
if ($reservation === null || $policy === null
|
|
|
|| (string) $reservation->state !== 'committed'
|
|
|
|| (int) ($reservation->instance_id ?? 0) !== (int) $instance->id
|
|
|
|| (int) $reservation->host_id !== (int) $instance->host_id
|
|
|
|| (int) $reservation->resource_pool_id
|
|
|
!== (int) ($instance->resource_pool_id ?? 0)) {
|
|
|
return false;
|
|
|
}
|
|
|
$rows = CloudResourceReservation::where(
|
|
|
'host_id',
|
|
|
(int) $instance->host_id
|
|
|
)->whereIn('state', ['held', 'uncertain', 'committed'])->get();
|
|
|
$usage = CloudPanelUsageService::forHost(
|
|
|
(int) $instance->host_id,
|
|
|
$rows
|
|
|
);
|
|
|
$withoutCurrent = self::usageWithoutUpgradeReservation(
|
|
|
$usage,
|
|
|
$reservation
|
|
|
);
|
|
|
return $withoutCurrent !== null
|
|
|
&& self::hasCapacity($policy, $withoutCurrent, $resources);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Reserve the target vector on the instance's existing reservation.
|
|
|
*
|
|
|
* The caller owns the wallet/instance transaction. This method locks the
|
|
|
* fixed placement hierarchy and every active reservation before replacing
|
|
|
* the current row, so two paid upgrades cannot consume the same capacity.
|
|
|
*/
|
|
|
public static function reserveUpgradeCapacityLocked(
|
|
|
CloudInstance $instance,
|
|
|
int $targetOfferId,
|
|
|
array $sourceResources,
|
|
|
array $targetResources
|
|
|
): CloudResourceReservation {
|
|
|
$source = self::upgradeResources($sourceResources);
|
|
|
$target = self::upgradeResources($targetResources);
|
|
|
[$policy, $reservation, $rows] = self::lockUpgradePlacement(
|
|
|
$instance,
|
|
|
true
|
|
|
);
|
|
|
if ((int) $reservation->offer_id !== (int) ($instance->offer_id ?? 0)
|
|
|
|| (int) $reservation->cpu_cores !== $source['cpu_cores']
|
|
|
|| (int) $reservation->memory_mib !== $source['memory_mib']
|
|
|
|| (int) $reservation->disk_gib !== $source['disk_gib']) {
|
|
|
throw new CloudError('实例当前资源预留与套餐快照不一致', 409);
|
|
|
}
|
|
|
$usage = CloudPanelUsageService::forHost(
|
|
|
(int) $instance->host_id,
|
|
|
$rows
|
|
|
);
|
|
|
$withoutCurrent = self::usageWithoutUpgradeReservation(
|
|
|
$usage,
|
|
|
$reservation
|
|
|
);
|
|
|
if ($withoutCurrent === null
|
|
|
|| !self::hasCapacity($policy, $withoutCurrent, $target)) {
|
|
|
throw new CloudError('当前宿主机没有足够资源完成套餐升级', 409);
|
|
|
}
|
|
|
$reservation->offer_id = $targetOfferId;
|
|
|
$reservation->cpu_cores = $target['cpu_cores'];
|
|
|
$reservation->memory_mib = $target['memory_mib'];
|
|
|
$reservation->disk_gib = $target['disk_gib'];
|
|
|
$reservation->updated_at = time();
|
|
|
$reservation->save();
|
|
|
return $reservation;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Converge the capacity ledger after the original Agent operation.
|
|
|
* Unknown effects deliberately keep the target vector reserved.
|
|
|
*/
|
|
|
public static function finishUpgradeCapacityLocked(
|
|
|
CloudInstance $instance,
|
|
|
int $reservationId,
|
|
|
int $sourceOfferId,
|
|
|
int $targetOfferId,
|
|
|
array $sourceResources,
|
|
|
array $targetResources,
|
|
|
string $resolution
|
|
|
): void {
|
|
|
if (!in_array($resolution, ['applied', 'not_applied', 'unknown'], true)) {
|
|
|
throw new CloudError('实例升级容量结论无效', 409);
|
|
|
}
|
|
|
$source = self::upgradeResources($sourceResources);
|
|
|
$target = self::upgradeResources($targetResources);
|
|
|
[, $reservation] = self::lockUpgradePlacement($instance, false);
|
|
|
if ((int) $reservation->id !== $reservationId
|
|
|
|| (int) $reservation->offer_id !== $targetOfferId
|
|
|
|| (int) $reservation->cpu_cores !== $target['cpu_cores']
|
|
|
|| (int) $reservation->memory_mib !== $target['memory_mib']
|
|
|
|| (int) $reservation->disk_gib !== $target['disk_gib']) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'实例升级的目标容量预留账本不一致',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
if ($resolution !== 'not_applied') {
|
|
|
return;
|
|
|
}
|
|
|
$reservation->offer_id = $sourceOfferId;
|
|
|
$reservation->cpu_cores = $source['cpu_cores'];
|
|
|
$reservation->memory_mib = $source['memory_mib'];
|
|
|
$reservation->disk_gib = $source['disk_gib'];
|
|
|
$reservation->updated_at = time();
|
|
|
$reservation->save();
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Batch advisory availability without locks or resource reservation.
|
|
|
*
|
|
|
* @param array<string,array{pool_id:int,cpu_cores:int,memory_mib:int,
|
|
|
* disk_gib:int}> $requests
|
|
|
* @return array<string,bool>
|
|
|
*/
|
|
|
public static function poolCapacityAvailability(array $requests): array
|
|
|
{
|
|
|
$availability = [];
|
|
|
$byPool = [];
|
|
|
foreach ($requests as $key => $resources) {
|
|
|
$availability[$key] = false;
|
|
|
if (!is_array($resources)) {
|
|
|
continue;
|
|
|
}
|
|
|
$poolId = (int) ($resources['pool_id'] ?? 0);
|
|
|
$normalized = [
|
|
|
'cpu_cores' => (int) ($resources['cpu_cores'] ?? 0),
|
|
|
'memory_mib' => (int) ($resources['memory_mib'] ?? 0),
|
|
|
'disk_gib' => (int) ($resources['disk_gib'] ?? 0),
|
|
|
];
|
|
|
if ($poolId < 1 || min($normalized) < 1) {
|
|
|
continue;
|
|
|
}
|
|
|
$byPool[$poolId][$key] = $normalized;
|
|
|
}
|
|
|
|
|
|
foreach ($byPool as $poolId => $poolRequests) {
|
|
|
$candidateRows = self::candidateHostRows((int) $poolId);
|
|
|
if ($candidateRows->isEmpty()) {
|
|
|
continue;
|
|
|
}
|
|
|
$pendingByHost = self::pendingUsageByHost($candidateRows);
|
|
|
$availableIpHosts = self::availableIpHosts($candidateRows);
|
|
|
foreach ($poolRequests as $key => $resources) {
|
|
|
foreach ($candidateRows as $candidate) {
|
|
|
$hostId = (int) $candidate->id;
|
|
|
if (isset($availableIpHosts[$hostId])
|
|
|
&& self::hasCapacity($candidate,
|
|
|
$pendingByHost[$hostId] ?? self::emptyUsage(),
|
|
|
$resources)) {
|
|
|
$availability[$key] = true;
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
return $availability;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Select a host and atomically reserve one IPv4+IPv6 public network.
|
|
|
*
|
|
|
* @return array{host: CloudHost, reservation: CloudResourceReservation,
|
|
|
* public_network: CloudPublicNetworkSnapshot, payload: array,
|
|
|
* portable_restore_target: null|array{agent_revision:int,
|
|
|
* agent_contract_sha256:string}}
|
|
|
*/
|
|
|
public static function reserve(CloudOrder $order, CloudOffer $offer,
|
|
|
Shop $plan, array $payload,
|
|
|
?CloudPortableRestoreCompatibility $portableRestore = null): array
|
|
|
{
|
|
|
self::assertOrderOffer($order, $offer, $plan);
|
|
|
$resources = self::orderResources($order, $payload);
|
|
|
$orderSpec = json_decode((string) $order->spec_json, true);
|
|
|
$deploymentSnapshotSource = is_array($orderSpec)
|
|
|
&& !array_is_list($orderSpec)
|
|
|
&& ($orderSpec['source'] ?? null) === 'deployment_snapshot';
|
|
|
if ($deploymentSnapshotSource !== ($portableRestore !== null)) {
|
|
|
throw new CloudError('开通订单的可移植恢复合同无效', 409);
|
|
|
}
|
|
|
// The caller already owns the order row lock, and queued/terminal
|
|
|
// orders return before placement. A missing-row FOR UPDATE here would
|
|
|
// take an InnoDB right-edge gap lock for every new order; concurrent
|
|
|
// payments for different offers could then deadlock that gap against
|
|
|
// the shared region/pool locks when each inserts its reservation.
|
|
|
// Atomic payment plus UNIQUE(order_id) are the durable idempotency
|
|
|
// guards. A pre-existing row on an awaiting-payment order is therefore
|
|
|
// an invariant violation rather than a resumable state.
|
|
|
if (CloudResourceReservation::where('order_id', (int) $order->id)->exists()) {
|
|
|
throw new CloudError('待支付订单已存在异常资源预留,请联系管理员', 409);
|
|
|
}
|
|
|
|
|
|
// Resolve the hierarchy without trusting it yet, then lock it in the
|
|
|
// same parent-to-child order used by the administrator resource UI.
|
|
|
// This prevents a default-line update (region -> line) from cycling
|
|
|
// with a payment placement transaction.
|
|
|
$poolRef = CloudResourcePool::find((int) $offer->resource_pool_id);
|
|
|
$lineRef = $poolRef === null ? null
|
|
|
: CloudNetworkLine::find((int) $poolRef->line_id);
|
|
|
$regionId = $lineRef === null ? 0 : (int) $lineRef->region_id;
|
|
|
$region = $regionId < 1 ? null
|
|
|
: CloudRegion::where('id', $regionId)->lockForUpdate()->first();
|
|
|
$line = $lineRef === null ? null
|
|
|
: CloudNetworkLine::where('id', (int) $lineRef->id)
|
|
|
->lockForUpdate()->first();
|
|
|
$pool = $poolRef === null ? null
|
|
|
: CloudResourcePool::where('id', (int) $poolRef->id)
|
|
|
->lockForUpdate()->first();
|
|
|
if ($pool === null || (int) $pool->id !== (int) $offer->resource_pool_id
|
|
|
|| (string) $pool->status !== 'active') {
|
|
|
throw new CloudError('该销售方案的资源池暂不可用', 409);
|
|
|
}
|
|
|
if ($line === null || (int) $pool->line_id !== (int) $line->id
|
|
|
|| (string) $line->status !== 'active'
|
|
|
|| $region === null || (int) $line->region_id !== (int) $region->id
|
|
|
|| (string) $region->status !== 'active') {
|
|
|
throw new CloudError('该销售地区或线路暂不可用', 409);
|
|
|
}
|
|
|
if (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default) {
|
|
|
throw new CloudError('当前未开放线路选择,该销售方案暂不可购买', 409);
|
|
|
}
|
|
|
|
|
|
$candidateRows = self::candidateHostRows((int) $pool->id);
|
|
|
$pendingByHost = self::pendingUsageByHost($candidateRows);
|
|
|
$candidates = $candidateRows->map(static function ($row) use ($pendingByHost): array {
|
|
|
$pending = $pendingByHost[(int) $row->id] ?? self::emptyUsage();
|
|
|
return ['id' => (int) $row->id,
|
|
|
'score' => self::capacityScore($row, $pending)];
|
|
|
})->sort(static fn (array $left, array $right): int =>
|
|
|
($left['score'] <=> $right['score']) ?: ($left['id'] <=> $right['id'])
|
|
|
)->values()->all();
|
|
|
|
|
|
foreach ($candidates as $candidate) {
|
|
|
$placement = self::tryHost(
|
|
|
(int) $candidate['id'],
|
|
|
$pool,
|
|
|
$order,
|
|
|
$offer,
|
|
|
$resources,
|
|
|
$payload,
|
|
|
$portableRestore
|
|
|
);
|
|
|
if ($placement !== null) {
|
|
|
return $placement;
|
|
|
}
|
|
|
}
|
|
|
throw new CloudError('当前地区暂时没有足够的可用资源或公网 IP,请稍后重试', 409);
|
|
|
}
|
|
|
|
|
|
public static function commit(CloudOrder $order, int $instanceId,
|
|
|
array $confirmedPublicNetwork): void
|
|
|
{
|
|
|
if ($instanceId < 1) {
|
|
|
throw new CloudError('开通任务实例归属无效', 409);
|
|
|
}
|
|
|
$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
|
|
|
);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Return advisory restore targets for one immutable backup specification.
|
|
|
* Admission repeats every predicate while holding the target-host ledger.
|
|
|
*/
|
|
|
public static function backupRestoreTargets(int $sourceHostId,
|
|
|
array $resources): array
|
|
|
{
|
|
|
$resources = self::upgradeResources($resources);
|
|
|
$candidates = CloudHost::query()->join(
|
|
|
'cloud_host_resource_pool_memberships as restore_membership',
|
|
|
'restore_membership.host_id', '=', 'cloud_hosts.id'
|
|
|
)->join(
|
|
|
'cloud_resource_pools as restore_resource_pool',
|
|
|
'restore_resource_pool.id', '=',
|
|
|
'restore_membership.resource_pool_id'
|
|
|
)->join(
|
|
|
'cloud_network_lines as restore_line',
|
|
|
'restore_line.id', '=', 'restore_resource_pool.line_id'
|
|
|
)->join(
|
|
|
'cloud_regions as restore_region',
|
|
|
'restore_region.id', '=', 'restore_line.region_id'
|
|
|
)->join(
|
|
|
'cloud_host_capacity_policies as restore_capacity',
|
|
|
'restore_capacity.host_id', '=', 'cloud_hosts.id'
|
|
|
)->join(
|
|
|
'cloud_host_agents as restore_agent',
|
|
|
'restore_agent.host_id', '=', 'cloud_hosts.id'
|
|
|
)->join(
|
|
|
'cloud_host_storage_configurations as restore_storage',
|
|
|
'restore_storage.host_id', '=', 'cloud_hosts.id'
|
|
|
)->where('cloud_hosts.enabled', 1)
|
|
|
->where('restore_membership.scheduler_state', 'active')
|
|
|
->where('restore_resource_pool.status', 'active')
|
|
|
->where('restore_line.status', 'active')
|
|
|
->where('restore_region.status', 'active')
|
|
|
->where('restore_agent.enabled', 1)
|
|
|
->where('restore_agent.last_test_status', 'healthy')
|
|
|
->where('restore_agent.tested_revision', '>', 0)
|
|
|
->whereColumn(
|
|
|
'restore_agent.tested_revision',
|
|
|
'restore_agent.revision'
|
|
|
)->where('restore_storage.state', 'applied')
|
|
|
->where('restore_capacity.configured_cpu_cores', '>', 0)
|
|
|
->where('restore_capacity.configured_memory_mib', '>', 0)
|
|
|
->where('restore_capacity.configured_disk_gib', '>', 0)
|
|
|
->orderBy('cloud_hosts.id')
|
|
|
->orderBy('restore_resource_pool.id')
|
|
|
->get([
|
|
|
'cloud_hosts.id',
|
|
|
'cloud_hosts.name',
|
|
|
'restore_resource_pool.id as resource_pool_id',
|
|
|
'restore_resource_pool.name as resource_pool_name',
|
|
|
'restore_line.id as resource_pool_line_id',
|
|
|
'restore_line.name as line_name',
|
|
|
'restore_region.id as region_id',
|
|
|
'restore_region.name as region_name',
|
|
|
'restore_region.country_code',
|
|
|
'restore_capacity.configured_cpu_cores',
|
|
|
'restore_capacity.configured_memory_mib',
|
|
|
'restore_capacity.configured_disk_gib',
|
|
|
'restore_capacity.safety_cpu_cores',
|
|
|
'restore_capacity.safety_memory_mib',
|
|
|
'restore_capacity.safety_disk_gib',
|
|
|
'restore_capacity.max_instances',
|
|
|
]);
|
|
|
$pendingByHost = self::pendingUsageByHost($candidates);
|
|
|
$networkByHostLine = CloudPlacementNetworkService::
|
|
|
advisoryDualStackBundleEvidence($candidates);
|
|
|
$result = [];
|
|
|
foreach ($candidates as $candidate) {
|
|
|
$hostId = (int) $candidate->id;
|
|
|
$lineId = (int) $candidate->resource_pool_line_id;
|
|
|
$network = $networkByHostLine[$hostId][$lineId] ?? [];
|
|
|
$availableBundles = 0;
|
|
|
$selectors = [];
|
|
|
foreach ($network as $bundle) {
|
|
|
if (!is_array($bundle)
|
|
|
|| !CloudNetworkSelector::isValid(
|
|
|
$bundle['network_selector'] ?? null
|
|
|
)) {
|
|
|
continue;
|
|
|
}
|
|
|
$count = min(
|
|
|
(int) ($bundle['ipv4']['available_units'] ?? 0),
|
|
|
(int) ($bundle['ipv6']['available_units'] ?? 0)
|
|
|
);
|
|
|
if ($count < 1) {
|
|
|
continue;
|
|
|
}
|
|
|
$availableBundles += $count;
|
|
|
$selectors[(string) $bundle['network_selector']] = true;
|
|
|
}
|
|
|
if ($availableBundles < 1
|
|
|
|| !self::hasCapacity(
|
|
|
$candidate,
|
|
|
$pendingByHost[$hostId] ?? self::emptyUsage(),
|
|
|
$resources
|
|
|
)) {
|
|
|
continue;
|
|
|
}
|
|
|
$result[] = [
|
|
|
'id' => (string) $hostId,
|
|
|
'name' => (string) $candidate->name,
|
|
|
'region_id' => (string) $candidate->region_id,
|
|
|
'region' => (string) $candidate->region_name,
|
|
|
'country_code' => strtoupper(
|
|
|
(string) $candidate->country_code
|
|
|
),
|
|
|
'line_id' => (string) $lineId,
|
|
|
'line' => (string) $candidate->line_name,
|
|
|
'resource_pool_id' =>
|
|
|
(string) $candidate->resource_pool_id,
|
|
|
'resource_pool' =>
|
|
|
(string) $candidate->resource_pool_name,
|
|
|
'network_selectors' => array_keys($selectors),
|
|
|
// Keep the presentation key while changing its unit from a
|
|
|
// lone IPv4 row to one complete IPv4+IPv6 bundle.
|
|
|
'available_ip_count' => $availableBundles,
|
|
|
'is_source_host' => $hostId === $sourceHostId,
|
|
|
];
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
/** Same-pool, different-host candidates for a cold maintenance migration. */
|
|
|
public static function maintenanceMigrationTargets(CloudInstance $instance,
|
|
|
array $resources, int $additionalDiskGib = 0): array
|
|
|
{
|
|
|
$poolId = (int) ($instance->resource_pool_id ?? 0);
|
|
|
if ($poolId < 1) {
|
|
|
return [];
|
|
|
}
|
|
|
$capacityResources = self::upgradeResources($resources);
|
|
|
$capacityResources['disk_gib'] += max(0, $additionalDiskGib);
|
|
|
return array_values(array_filter(
|
|
|
self::backupRestoreTargets(
|
|
|
(int) $instance->host_id,
|
|
|
$capacityResources
|
|
|
),
|
|
|
static fn (array $target): bool =>
|
|
|
(int) ($target['id'] ?? 0) !== (int) $instance->host_id
|
|
|
&& (int) ($target['resource_pool_id'] ?? 0) === $poolId
|
|
|
));
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Reserve one exact dual-stack target for a still-gated maintenance
|
|
|
* migration. Legacy singular address columns deliberately remain NULL;
|
|
|
* the two active claim rows are the only network ownership authority.
|
|
|
*
|
|
|
* @return array{reservation:CloudResourceReservation,host:CloudHost,
|
|
|
* public_network:CloudPublicNetworkSnapshot,
|
|
|
* target_agent_revision:int}
|
|
|
*/
|
|
|
public static function reserveMaintenanceMigrationTarget(
|
|
|
CloudBackupRestore $restore,
|
|
|
int $userId,
|
|
|
array $resources,
|
|
|
int $requiredResourcePoolId,
|
|
|
int $additionalDiskGib = 0
|
|
|
): array {
|
|
|
if ($restore->backup_id !== null
|
|
|
|| (string) $restore->state !== 'reserved'
|
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
|
(string) $restore->operation_id) !== 1) {
|
|
|
throw new CloudError('维护迁移目标意图无效', 409);
|
|
|
}
|
|
|
$resources = self::upgradeResources($resources);
|
|
|
$capacityResources = $resources;
|
|
|
$capacityResources['disk_gib'] += max(0, $additionalDiskGib);
|
|
|
$hostId = (int) $restore->target_host_id;
|
|
|
if ($hostId < 1 || $userId < 1 || $requiredResourcePoolId < 1) {
|
|
|
throw new CloudError('维护迁移目标身份无效', 409);
|
|
|
}
|
|
|
return (new CloudResourceReservation())->getConnection()->transaction(
|
|
|
static function () use (
|
|
|
$restore,
|
|
|
$userId,
|
|
|
$resources,
|
|
|
$capacityResources,
|
|
|
$hostId,
|
|
|
$requiredResourcePoolId
|
|
|
): array {
|
|
|
$poolRef = CloudResourcePool::find($requiredResourcePoolId);
|
|
|
$lineRef = $poolRef === null ? null
|
|
|
: CloudNetworkLine::find((int) $poolRef->line_id);
|
|
|
$region = $lineRef === null ? null
|
|
|
: CloudRegion::where('id', (int) $lineRef->region_id)
|
|
|
->lockForUpdate()->first();
|
|
|
$line = $lineRef === null ? null
|
|
|
: CloudNetworkLine::where('id', (int) $lineRef->id)
|
|
|
->lockForUpdate()->first();
|
|
|
$pool = $poolRef === null ? null
|
|
|
: CloudResourcePool::where('id', (int) $poolRef->id)
|
|
|
->lockForUpdate()->first();
|
|
|
$host = CloudHost::where('id', $hostId)
|
|
|
->lockForUpdate()->first();
|
|
|
$membership = CloudHostResourcePoolMembership::where(
|
|
|
'host_id',
|
|
|
$hostId
|
|
|
)->where('resource_pool_id', $requiredResourcePoolId)
|
|
|
->lockForUpdate()->first();
|
|
|
$policy = CloudHostCapacityPolicy::where('host_id', $hostId)
|
|
|
->lockForUpdate()->first();
|
|
|
$storage = CloudHostStorageConfiguration::where(
|
|
|
'host_id',
|
|
|
$hostId
|
|
|
)->lockForUpdate()->first();
|
|
|
$agent = CloudHostAgent::where('host_id', $hostId)
|
|
|
->lockForUpdate()->first();
|
|
|
if ($host === null || $membership === null || $pool === null
|
|
|
|| $line === null || $region === null || $policy === null
|
|
|
|| $storage === null || !$storage->isApplied()
|
|
|
|| $agent === null || !$agent->isReady()
|
|
|
|| !(bool) $host->enabled
|
|
|
|| (string) $membership->scheduler_state !== 'active'
|
|
|
|| (int) $membership->resource_pool_id
|
|
|
!== $requiredResourcePoolId
|
|
|
|| (int) $pool->id !== $requiredResourcePoolId
|
|
|
|| (int) $pool->line_id !== (int) $line->id
|
|
|
|| (int) $line->region_id !== (int) $region->id
|
|
|
|| (string) $pool->status !== 'active'
|
|
|
|| (string) $line->status !== 'active'
|
|
|
|| (string) $region->status !== 'active') {
|
|
|
throw new CloudError(
|
|
|
'所选目标宿主机暂不支持维护迁移',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
$reservations = CloudResourceReservation::where(
|
|
|
'host_id',
|
|
|
$hostId
|
|
|
)->whereIn('state', ['held', 'uncertain', 'committed'])
|
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
|
if (!self::hasCapacity(
|
|
|
$policy,
|
|
|
CloudPanelUsageService::forHost($hostId, $reservations),
|
|
|
$capacityResources
|
|
|
)) {
|
|
|
throw new CloudError('目标宿主机没有足够的可用容量', 409);
|
|
|
}
|
|
|
|
|
|
$reservation = new CloudResourceReservation();
|
|
|
$reservation->reservation_key = bin2hex(random_bytes(16));
|
|
|
$reservation->operation_id = (string) $restore->operation_id;
|
|
|
$reservation->order_id = null;
|
|
|
$reservation->backup_restore_id = (int) $restore->id;
|
|
|
$reservation->backup_restore_attempt_key = null;
|
|
|
$reservation->migration_source_debt_id = null;
|
|
|
$reservation->offer_id = null;
|
|
|
$reservation->resource_pool_id = (int) $pool->id;
|
|
|
$reservation->host_id = $hostId;
|
|
|
$reservation->user_id = $userId;
|
|
|
$reservation->instance_id = null;
|
|
|
$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 = $capacityResources['disk_gib'];
|
|
|
$reservation->state = 'held';
|
|
|
$reservation->expires_at = null;
|
|
|
$reservation->released_at = null;
|
|
|
$reservation->release_reason = '';
|
|
|
$reservation->created_at =
|
|
|
$reservation->updated_at = time();
|
|
|
$reservation->save();
|
|
|
try {
|
|
|
$publicNetwork = CloudPublicNetworkAllocationService::
|
|
|
reserveBundle(
|
|
|
$hostId,
|
|
|
(int) $line->id,
|
|
|
(int) $reservation->id,
|
|
|
(string) $restore->operation_id
|
|
|
);
|
|
|
} catch (CloudPublicNetworkCapacityUnavailable) {
|
|
|
throw new CloudError(
|
|
|
'目标宿主机没有可分配的双栈公网地址',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
return [
|
|
|
'reservation' => $reservation,
|
|
|
'host' => $host,
|
|
|
'public_network' => $publicNetwork,
|
|
|
'target_agent_revision' => (int) $agent->revision,
|
|
|
];
|
|
|
},
|
|
|
3
|
|
|
);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Re-open the exact held dual-stack target without allocating replacements.
|
|
|
* The returned frozen identity is safe to place in the encrypted receive
|
|
|
* envelope and remains stable if Agent settings change after dispatch.
|
|
|
*
|
|
|
* @return array{reservation:CloudResourceReservation,
|
|
|
* public_network:CloudPublicNetworkSnapshot,
|
|
|
* identity:CloudFrozenPublicNetworkIdentity,
|
|
|
* target_agent_revision:int,target_agent_contract_sha256:string}
|
|
|
*/
|
|
|
public static function preparedMaintenanceMigrationTarget(
|
|
|
CloudBackupRestore $restore,
|
|
|
int $instanceId
|
|
|
): array {
|
|
|
if ($restore->backup_id !== null || $instanceId < 1
|
|
|
|| (int) $restore->reservation_id < 1
|
|
|
|| (string) $restore->state !== 'reserved'
|
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
|
(string) $restore->operation_id) !== 1
|
|
|
|| preg_match(
|
|
|
'/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/D',
|
|
|
strtolower((string) $restore->new_uuid)
|
|
|
) !== 1) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'维护迁移目标意图无效',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
return (new CloudResourceReservation())->getConnection()->transaction(
|
|
|
static function () use ($restore, $instanceId): array {
|
|
|
$instance = CloudInstance::where('id', $instanceId)
|
|
|
->lockForUpdate()->first();
|
|
|
$reservationHint = CloudResourceReservation::find(
|
|
|
(int) $restore->reservation_id
|
|
|
);
|
|
|
$poolHint = $reservationHint === null ? null
|
|
|
: CloudResourcePool::find(
|
|
|
(int) $reservationHint->resource_pool_id
|
|
|
);
|
|
|
$lineHint = $poolHint === null ? null
|
|
|
: CloudNetworkLine::find((int) $poolHint->line_id);
|
|
|
$region = $lineHint === null ? null
|
|
|
: CloudRegion::where(
|
|
|
'id',
|
|
|
(int) $lineHint->region_id
|
|
|
)->lockForUpdate()->first();
|
|
|
$line = $lineHint === null ? null
|
|
|
: CloudNetworkLine::where('id', (int) $lineHint->id)
|
|
|
->lockForUpdate()->first();
|
|
|
$pool = $poolHint === null ? null
|
|
|
: CloudResourcePool::where('id', (int) $poolHint->id)
|
|
|
->lockForUpdate()->first();
|
|
|
if ($instance === null || $reservationHint === null
|
|
|
|| $pool === null || $line === null || $region === null
|
|
|
|| (int) $pool->line_id !== (int) $line->id
|
|
|
|| (int) $line->region_id !== (int) $region->id) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'维护迁移目标预留已经变化',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
$publicNetwork = CloudPublicNetworkAllocationService::
|
|
|
verifyExistingBundle(
|
|
|
(int) $reservationHint->host_id,
|
|
|
(int) $line->id,
|
|
|
(int) $reservationHint->id,
|
|
|
(string) $restore->operation_id
|
|
|
);
|
|
|
$reservation = CloudResourceReservation::where(
|
|
|
'id',
|
|
|
(int) $reservationHint->id
|
|
|
)->lockForUpdate()->first();
|
|
|
$host = CloudHost::where(
|
|
|
'id',
|
|
|
(int) $reservationHint->host_id
|
|
|
)->lockForUpdate()->first();
|
|
|
$membership = CloudHostResourcePoolMembership::where(
|
|
|
'host_id',
|
|
|
(int) $reservationHint->host_id
|
|
|
)->where(
|
|
|
'resource_pool_id',
|
|
|
(int) $reservationHint->resource_pool_id
|
|
|
)->lockForUpdate()->first();
|
|
|
$storage = CloudHostStorageConfiguration::where(
|
|
|
'host_id',
|
|
|
(int) $reservationHint->host_id
|
|
|
)->lockForUpdate()->first();
|
|
|
$agent = CloudHostAgent::where(
|
|
|
'host_id',
|
|
|
(int) $reservationHint->host_id
|
|
|
)->lockForUpdate()->first();
|
|
|
$agentContract = $agent === null ? null
|
|
|
: $agent->testedPortableRestoreCompatibility();
|
|
|
if ($reservation === null || $host === null
|
|
|
|| $membership === null || $storage === null
|
|
|
|| $agent === null || !$agent->isReady()
|
|
|
|| $agentContract === null || !(bool) $host->enabled
|
|
|
|| !$storage->isApplied()
|
|
|
|| (string) $pool->status !== 'active'
|
|
|
|| (string) $line->status !== 'active'
|
|
|
|| (string) $region->status !== 'active'
|
|
|
|| (int) $restore->reservation_id
|
|
|
!== (int) $reservation->id
|
|
|
|| (int) $restore->target_host_id
|
|
|
!== (int) $reservation->host_id
|
|
|
|| (int) $reservation->backup_restore_id
|
|
|
!== (int) $restore->id
|
|
|
|| $reservation->order_id !== null
|
|
|
|| $reservation->offer_id !== null
|
|
|
|| $reservation->backup_restore_attempt_key !== null
|
|
|
|| $reservation->migration_source_debt_id !== null
|
|
|
|| $reservation->instance_id !== null
|
|
|
|| (string) $reservation->state !== 'held'
|
|
|
|| (int) $reservation->user_id
|
|
|
!== (int) $instance->user_id
|
|
|
|| (int) $reservation->resource_pool_id
|
|
|
!== (int) $instance->resource_pool_id
|
|
|
|| (string) $membership->scheduler_state !== 'active'
|
|
|
|| (int) $reservation->host_id !== (int) $host->id
|
|
|
|| (int) $reservation->resource_pool_id !== (int) $pool->id
|
|
|
|| $reservation->network_attachment_id !== null
|
|
|
|| $reservation->public_ip_pool_id !== null
|
|
|
|| $reservation->public_ip_id !== null
|
|
|
|| !hash_equals(
|
|
|
(string) $restore->operation_id,
|
|
|
(string) $reservation->operation_id
|
|
|
)) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'维护迁移目标预留已经变化',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
$claimSet = CloudPublicNetworkAllocationService::
|
|
|
currentClaimSet((int) $reservation->id, 'held');
|
|
|
$attachment = CloudHostNetworkAttachment::where(
|
|
|
'id',
|
|
|
$claimSet->networkAttachmentId()
|
|
|
)->lockForUpdate()->first();
|
|
|
$networkSelector = $publicNetwork->toArray()[
|
|
|
'network_selector'
|
|
|
] ?? null;
|
|
|
if ($attachment === null
|
|
|
|| (int) $attachment->host_id !== (int) $host->id
|
|
|
|| (int) $attachment->line_id !== (int) $line->id
|
|
|
|| (string) $attachment->state !== 'active'
|
|
|
|| (string) $attachment->verification_state !== 'verified'
|
|
|
|| (int) $attachment->last_verified_at < 1
|
|
|
|| !is_string($networkSelector)
|
|
|
|| !hash_equals(
|
|
|
(string) $attachment->network_selector,
|
|
|
$networkSelector
|
|
|
)
|
|
|
|| !CloudAgentSettingsService::publicNetworkReady(
|
|
|
$agent,
|
|
|
$networkSelector,
|
|
|
(int) $attachment->verified_agent_revision
|
|
|
)) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'维护迁移目标公网接入验证已经失效',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
if (!hash_equals(
|
|
|
$publicNetwork->fingerprint(),
|
|
|
$claimSet->publicNetwork()->fingerprint()
|
|
|
)) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'维护迁移目标双栈身份已经变化',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
return [
|
|
|
'reservation' => $reservation,
|
|
|
'public_network' => $publicNetwork,
|
|
|
'identity' => CloudFrozenPublicNetworkIdentity::
|
|
|
fromClaimSet(
|
|
|
strtolower((string) $restore->new_uuid),
|
|
|
$claimSet
|
|
|
),
|
|
|
'target_agent_revision' => (int) $agent->revision,
|
|
|
'target_agent_contract_sha256' =>
|
|
|
$agentContract->sha256(),
|
|
|
];
|
|
|
},
|
|
|
3
|
|
|
);
|
|
|
}
|
|
|
|
|
|
/** Keep an ambiguous create and both addresses unavailable for reconciliation. */
|
|
|
public static function markUncertain(CloudOrder $order): void
|
|
|
{
|
|
|
(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 proves that no guest owns either address. */
|
|
|
public static function release(CloudOrder $order, string $reason): void
|
|
|
{
|
|
|
(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
|
|
|
);
|
|
|
}
|
|
|
|
|
|
private static function tryHost(int $hostId, CloudResourcePool $pool,
|
|
|
CloudOrder $order, CloudOffer $offer, array $resources,
|
|
|
array $payload,
|
|
|
?CloudPortableRestoreCompatibility $portableRestore): ?array
|
|
|
{
|
|
|
// Every host-scoped writer starts with the host row. This serializes
|
|
|
// placement and administrator policy changes before any concrete IP
|
|
|
// row is locked.
|
|
|
$host = CloudHost::where('id', $hostId)->lockForUpdate()->first();
|
|
|
$membership = CloudHostResourcePoolMembership::where('host_id', $hostId)
|
|
|
->where('resource_pool_id', (int) $pool->id)
|
|
|
->lockForUpdate()->first();
|
|
|
$policy = CloudHostCapacityPolicy::where('host_id', $hostId)
|
|
|
->lockForUpdate()->first();
|
|
|
$storage = CloudHostStorageConfiguration::where('host_id', $hostId)
|
|
|
->lockForUpdate()->first();
|
|
|
$agent = CloudHostAgent::where('host_id', $hostId)
|
|
|
->lockForUpdate()->first();
|
|
|
$body = $payload['body'] ?? null;
|
|
|
$orderSpec = json_decode((string) $order->spec_json, true);
|
|
|
$deploymentSnapshotSource = is_array($orderSpec)
|
|
|
&& !array_is_list($orderSpec)
|
|
|
&& ($orderSpec['source'] ?? null) === 'deployment_snapshot';
|
|
|
$templateId = is_array($body) ? ($body['template_id'] ?? null) : null;
|
|
|
$templateRevision = is_array($body)
|
|
|
? filter_var($body['template_revision'] ?? null,
|
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]])
|
|
|
: false;
|
|
|
$generation = is_array($body)
|
|
|
? ($body['template_generation_token'] ?? null) : null;
|
|
|
$template = $deploymentSnapshotSource || !is_string($templateId)
|
|
|
? null : CloudTemplate::find($templateId);
|
|
|
$replica = $deploymentSnapshotSource || !is_string($templateId)
|
|
|
|| $templateRevision === false || !is_string($generation) ? null
|
|
|
: CloudTemplateReplica::query()->where('host_id', $hostId)
|
|
|
->where('template_id', $templateId)->lockForUpdate()->first();
|
|
|
$targetRestore = $portableRestore === null ? null
|
|
|
: $agent?->testedPortableRestoreCompatibility();
|
|
|
$sourceReady = $deploymentSnapshotSource
|
|
|
? is_array($body)
|
|
|
&& ($body['source'] ?? null) === ''
|
|
|
&& $templateId === ''
|
|
|
&& ($body['template_revision'] ?? null) === 0
|
|
|
&& $generation === ''
|
|
|
&& $portableRestore !== null
|
|
|
&& $targetRestore !== null
|
|
|
&& $portableRestore->matches($targetRestore)
|
|
|
: $template instanceof CloudTemplate
|
|
|
&& $portableRestore === null
|
|
|
&& $replica instanceof CloudTemplateReplica
|
|
|
&& (int) $template->revision === (int) $templateRevision
|
|
|
&& hash_equals(
|
|
|
(string) $template->generation_token,
|
|
|
(string) $generation
|
|
|
)
|
|
|
&& CloudTemplateReplicaCoordinator::isExactReplica(
|
|
|
$template,
|
|
|
$replica
|
|
|
);
|
|
|
if ($host === null || $membership === null || $policy === null
|
|
|
|| $agent === null || !$agent->isReady()
|
|
|
|| $storage === null || !$storage->isApplied()
|
|
|
|| (string) $membership->scheduler_state !== 'active'
|
|
|
|| !(bool) $host->enabled
|
|
|
|| !$sourceReady
|
|
|
|| (int) $policy->configured_cpu_cores < 1
|
|
|
|| (int) $policy->configured_memory_mib < 1
|
|
|
|| (int) $policy->configured_disk_gib < 1) {
|
|
|
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
|
|
|
// sees the latest committed state.
|
|
|
$reservationRows = CloudResourceReservation::where('host_id', $hostId)
|
|
|
->whereIn('state', ['held', 'uncertain', 'committed'])
|
|
|
->orderBy('id')->lockForUpdate()->get([
|
|
|
'id', 'instance_id', 'state', 'cpu_cores', 'memory_mib', 'disk_gib',
|
|
|
'updated_at',
|
|
|
]);
|
|
|
$pending = CloudPanelUsageService::forHost($hostId, $reservationRows);
|
|
|
if (!self::hasCapacity($policy, $pending, $resources)) {
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
$operationId = bin2hex(random_bytes(16));
|
|
|
$reservation = new CloudResourceReservation();
|
|
|
$reservation->reservation_key = bin2hex(random_bytes(16));
|
|
|
$reservation->operation_id = $operationId;
|
|
|
$reservation->order_id = $order->id;
|
|
|
$reservation->offer_id = $offer->id;
|
|
|
$reservation->resource_pool_id = $pool->id;
|
|
|
$reservation->host_id = $hostId;
|
|
|
$reservation->user_id = $order->user_id;
|
|
|
$reservation->instance_id = null;
|
|
|
$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'];
|
|
|
$reservation->state = 'held';
|
|
|
$reservation->expires_at = null;
|
|
|
$reservation->released_at = null;
|
|
|
$reservation->release_reason = '';
|
|
|
$reservation->created_at = $reservation->updated_at = time();
|
|
|
$reservation->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;
|
|
|
$order->reservation_id = $reservation->id;
|
|
|
$order->updated_at = time();
|
|
|
$order->save();
|
|
|
|
|
|
return [
|
|
|
'host' => $host,
|
|
|
'reservation' => $reservation,
|
|
|
'public_network' => $publicNetwork,
|
|
|
'payload' => self::placementPayload($payload, $publicNetwork),
|
|
|
'portable_restore_target' => $targetRestore === null ? null : [
|
|
|
'agent_revision' => (int) $agent->revision,
|
|
|
'agent_contract_sha256' => $targetRestore->sha256(),
|
|
|
],
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function placementPayload(array $payload,
|
|
|
CloudPublicNetworkSnapshot $publicNetwork): array
|
|
|
{
|
|
|
if (($payload['method'] ?? null) !== 'POST'
|
|
|
|| ($payload['request_target'] ?? null) !== '/v1/vms'
|
|
|
|| !is_array($payload['body'] ?? null)) {
|
|
|
throw new CloudError('开通订单的加密请求无效', 409);
|
|
|
}
|
|
|
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;
|
|
|
}
|
|
|
|
|
|
|
|
|
private static function assertOrderOffer(CloudOrder $order, CloudOffer $offer,
|
|
|
Shop $plan): void
|
|
|
{
|
|
|
if ((int) $order->offer_id !== (int) $offer->id
|
|
|
|| (int) $offer->plan_id !== (int) $plan->id
|
|
|
|| (int) $order->plan_id !== (int) $plan->id
|
|
|
|| (int) $order->resource_pool_id !== (int) $offer->resource_pool_id) {
|
|
|
throw new CloudError('订单与销售方案快照不匹配', 409);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
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
|
|
|
* values so reservation and eventual guest creation cannot drift apart.
|
|
|
*
|
|
|
* @return array{cpu_cores:int,memory_mib:int,disk_gib:int}
|
|
|
*/
|
|
|
private static function orderResources(CloudOrder $order, array $payload): array
|
|
|
{
|
|
|
$spec = json_decode((string) $order->spec_json, true);
|
|
|
$body = $payload['body'] ?? null;
|
|
|
if (!is_array($spec) || array_is_list($spec)
|
|
|
|| !is_array($body) || array_is_list($body)) {
|
|
|
throw new CloudError('订单的资源规格快照无效', 409);
|
|
|
}
|
|
|
$fields = [
|
|
|
'cpu_cores' => 'vcpu',
|
|
|
'memory_mib' => 'memory_mib',
|
|
|
'disk_gib' => 'disk_gib',
|
|
|
];
|
|
|
$resources = [];
|
|
|
foreach ($fields as $resource => $payloadField) {
|
|
|
$snapshotValue = filter_var(
|
|
|
$spec[$payloadField] ?? null,
|
|
|
FILTER_VALIDATE_INT,
|
|
|
['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]]
|
|
|
);
|
|
|
$payloadValue = filter_var(
|
|
|
$body[$payloadField] ?? null,
|
|
|
FILTER_VALIDATE_INT,
|
|
|
['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]]
|
|
|
);
|
|
|
if ($snapshotValue === false || $payloadValue === false
|
|
|
|| (int) $snapshotValue !== (int) $payloadValue) {
|
|
|
throw new CloudError('订单的资源规格快照与开通请求不一致', 409);
|
|
|
}
|
|
|
$resources[$resource] = (int) $snapshotValue;
|
|
|
}
|
|
|
if ((int) ($spec['plan_id'] ?? 0) !== (int) $order->plan_id
|
|
|
|| (int) ($spec['offer_id'] ?? 0) !== (int) $order->offer_id
|
|
|
|| (int) ($spec['resource_pool_id'] ?? 0) !== (int) $order->resource_pool_id) {
|
|
|
throw new CloudError('订单的销售与资源池快照不一致', 409);
|
|
|
}
|
|
|
$specPolicy = CloudPlatformTestNetworkPolicy::assertSnapshot(
|
|
|
$spec['platform_network_policy_snapshot'] ?? null
|
|
|
);
|
|
|
$payloadPolicy = CloudPlatformTestNetworkPolicy::assertSnapshot(
|
|
|
$body['platform_network_policy_snapshot'] ?? null
|
|
|
);
|
|
|
if ($specPolicy !== $payloadPolicy) {
|
|
|
throw new CloudError('订单与开通请求的平台网络策略快照不一致', 409);
|
|
|
}
|
|
|
return $resources;
|
|
|
}
|
|
|
|
|
|
private static function candidateHostRows(int $poolId)
|
|
|
{
|
|
|
return CloudHost::query()->join(
|
|
|
'cloud_host_resource_pool_memberships as pool_membership',
|
|
|
'pool_membership.host_id', '=', 'cloud_hosts.id'
|
|
|
)->join(
|
|
|
'cloud_resource_pools as membership_pool',
|
|
|
'membership_pool.id', '=', 'pool_membership.resource_pool_id'
|
|
|
)->join(
|
|
|
'cloud_host_capacity_policies as capacity_policy',
|
|
|
'capacity_policy.host_id', '=', 'cloud_hosts.id'
|
|
|
)->join(
|
|
|
'cloud_host_agents as host_agent',
|
|
|
'host_agent.host_id', '=', 'cloud_hosts.id'
|
|
|
)->join(
|
|
|
'cloud_host_storage_configurations as host_storage',
|
|
|
'host_storage.host_id', '=', 'cloud_hosts.id'
|
|
|
)->where('pool_membership.resource_pool_id', $poolId)
|
|
|
->where('pool_membership.scheduler_state', 'active')
|
|
|
->where('cloud_hosts.enabled', 1)
|
|
|
->where('host_agent.enabled', 1)
|
|
|
->where('host_agent.last_test_status', 'healthy')
|
|
|
->where('host_agent.tested_revision', '>', 0)
|
|
|
->whereColumn('host_agent.tested_revision',
|
|
|
'host_agent.revision')
|
|
|
->where('host_storage.state', 'applied')
|
|
|
->where('capacity_policy.configured_cpu_cores', '>', 0)
|
|
|
->where('capacity_policy.configured_memory_mib', '>', 0)
|
|
|
->where('capacity_policy.configured_disk_gib', '>', 0)
|
|
|
->distinct()
|
|
|
->get([
|
|
|
'cloud_hosts.id',
|
|
|
'membership_pool.line_id as resource_pool_line_id',
|
|
|
'capacity_policy.configured_cpu_cores',
|
|
|
'capacity_policy.configured_memory_mib',
|
|
|
'capacity_policy.configured_disk_gib',
|
|
|
'capacity_policy.safety_cpu_cores',
|
|
|
'capacity_policy.safety_memory_mib',
|
|
|
'capacity_policy.safety_disk_gib',
|
|
|
'capacity_policy.max_instances',
|
|
|
'host_agent.portable_restore_contract_json',
|
|
|
'host_agent.portable_restore_contract_sha256',
|
|
|
]);
|
|
|
}
|
|
|
|
|
|
private static function candidateSupportsPortableRestore(
|
|
|
object $candidate,
|
|
|
CloudPortableRestoreCompatibility $source
|
|
|
): bool {
|
|
|
try {
|
|
|
$target = CloudPortableRestoreCompatibility::fromStored(
|
|
|
(string) $candidate->portable_restore_contract_json,
|
|
|
(string) $candidate->portable_restore_contract_sha256
|
|
|
);
|
|
|
} catch (\InvalidArgumentException) {
|
|
|
return false;
|
|
|
}
|
|
|
return $source->matches($target);
|
|
|
}
|
|
|
|
|
|
private static function pendingUsageByHost($candidateRows): array
|
|
|
{
|
|
|
$candidateIds = $candidateRows->pluck('id')->map(
|
|
|
static fn ($id): int => (int) $id
|
|
|
)->unique()->values()->all();
|
|
|
if ($candidateIds === []) {
|
|
|
return [];
|
|
|
}
|
|
|
return CloudPanelUsageService::forHosts($candidateIds);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Return hosts with at least one concrete address in an eligible pool.
|
|
|
*
|
|
|
* This remains an advisory, non-locking read. The payment path repeats
|
|
|
* every predicate under the host, attachment, pool and IP row locks.
|
|
|
*
|
|
|
* @return array<int,bool>
|
|
|
*/
|
|
|
private static function availableIpHosts($candidateRows): array
|
|
|
{
|
|
|
return CloudPlacementNetworkService::advisoryDualStackAvailableHosts(
|
|
|
$candidateRows
|
|
|
);
|
|
|
}
|
|
|
|
|
|
private static function emptyUsage(): array
|
|
|
{
|
|
|
return [
|
|
|
'instance_count' => 0,
|
|
|
'cpu_sum' => 0,
|
|
|
'memory_sum' => 0,
|
|
|
'disk_sum' => 0,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/** @return array{cpu_cores:int,memory_mib:int,disk_gib:int} */
|
|
|
private static function upgradeResources(array $resources): array
|
|
|
{
|
|
|
$normalized = [];
|
|
|
foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $field) {
|
|
|
$value = filter_var(
|
|
|
$resources[$field] ?? null,
|
|
|
FILTER_VALIDATE_INT,
|
|
|
['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]]
|
|
|
);
|
|
|
if ($value === false) {
|
|
|
throw new CloudError('实例升级资源规格无效', 409);
|
|
|
}
|
|
|
$normalized[$field] = (int) $value;
|
|
|
}
|
|
|
return $normalized;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Lock the exact placement chain shared by admission and finalization.
|
|
|
*
|
|
|
* @return array{0:CloudHostCapacityPolicy,1:CloudResourceReservation,
|
|
|
* 2:mixed}
|
|
|
*/
|
|
|
private static function lockUpgradePlacement(
|
|
|
CloudInstance $instance,
|
|
|
bool $requireReady
|
|
|
): array {
|
|
|
$poolRef = CloudResourcePool::find(
|
|
|
(int) ($instance->resource_pool_id ?? 0)
|
|
|
);
|
|
|
$lineRef = $poolRef === null ? null
|
|
|
: CloudNetworkLine::find((int) $poolRef->line_id);
|
|
|
$region = $lineRef === null ? null
|
|
|
: CloudRegion::where('id', (int) $lineRef->region_id)
|
|
|
->lockForUpdate()->first();
|
|
|
$line = $lineRef === null ? null
|
|
|
: CloudNetworkLine::where('id', (int) $lineRef->id)
|
|
|
->lockForUpdate()->first();
|
|
|
$pool = $poolRef === null ? null
|
|
|
: CloudResourcePool::where('id', (int) $poolRef->id)
|
|
|
->lockForUpdate()->first();
|
|
|
$host = CloudHost::where('id', (int) $instance->host_id)
|
|
|
->lockForUpdate()->first();
|
|
|
$membership = CloudHostResourcePoolMembership::where(
|
|
|
'host_id',
|
|
|
(int) $instance->host_id
|
|
|
)->where(
|
|
|
'resource_pool_id',
|
|
|
(int) ($instance->resource_pool_id ?? 0)
|
|
|
)->lockForUpdate()->first();
|
|
|
$policy = CloudHostCapacityPolicy::where(
|
|
|
'host_id',
|
|
|
(int) $instance->host_id
|
|
|
)->lockForUpdate()->first();
|
|
|
$storage = CloudHostStorageConfiguration::where(
|
|
|
'host_id',
|
|
|
(int) $instance->host_id
|
|
|
)->lockForUpdate()->first();
|
|
|
$agent = CloudHostAgent::where(
|
|
|
'host_id',
|
|
|
(int) $instance->host_id
|
|
|
)->lockForUpdate()->first();
|
|
|
if ($region === null || $line === null || $pool === null
|
|
|
|| $host === null || $membership === null || $policy === null
|
|
|
|| (int) $line->region_id !== (int) $region->id
|
|
|
|| (int) $pool->line_id !== (int) $line->id
|
|
|
|| (int) $pool->id !== (int) ($instance->resource_pool_id ?? 0)
|
|
|
|| (int) $membership->host_id !== (int) $host->id
|
|
|
|| (int) $membership->resource_pool_id !== (int) $pool->id) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'实例升级的固定资源池账本不完整',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
if ($requireReady
|
|
|
&& ((string) $region->status !== 'active'
|
|
|
|| (string) $line->status !== 'active'
|
|
|
|| (string) $pool->status !== 'active'
|
|
|
|| !(bool) $host->enabled
|
|
|
|| (string) $membership->scheduler_state !== 'active'
|
|
|
|| $agent === null || !$agent->isReady()
|
|
|
|| $storage === null || !$storage->isApplied()
|
|
|
|| (int) $policy->configured_cpu_cores < 1
|
|
|
|| (int) $policy->configured_memory_mib < 1
|
|
|
|| (int) $policy->configured_disk_gib < 1)) {
|
|
|
throw new CloudError('实例所在宿主机暂不支持套餐升级', 409);
|
|
|
}
|
|
|
$rows = CloudResourceReservation::where(
|
|
|
'host_id',
|
|
|
(int) $host->id
|
|
|
)->whereIn('state', ['held', 'uncertain', 'committed'])
|
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
|
$reservation = $rows->first(static fn ($row): bool =>
|
|
|
(int) $row->id === (int) ($instance->reservation_id ?? 0));
|
|
|
if ($reservation === null
|
|
|
|| (string) $reservation->state !== 'committed'
|
|
|
|| (int) ($reservation->instance_id ?? 0) !== (int) $instance->id
|
|
|
|| (int) $reservation->user_id !== (int) $instance->user_id
|
|
|
|| (int) $reservation->host_id !== (int) $instance->host_id
|
|
|
|| (int) $reservation->resource_pool_id !== (int) $pool->id) {
|
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
|
'实例升级缺少有效的已提交资源预留',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
return [$policy, $reservation, $rows];
|
|
|
}
|
|
|
|
|
|
/** Remove the current instance from a complete usage projection. */
|
|
|
private static function usageWithoutUpgradeReservation(
|
|
|
array $usage,
|
|
|
CloudResourceReservation $reservation
|
|
|
): ?array {
|
|
|
if ((int) ($usage['unknown'] ?? 0) > 0
|
|
|
|| (int) ($usage['instance_count'] ?? 0) < 1
|
|
|
|| (int) ($usage['cpu_sum'] ?? 0) < (int) $reservation->cpu_cores
|
|
|
|| (int) ($usage['memory_sum'] ?? 0) < (int) $reservation->memory_mib
|
|
|
|| (int) ($usage['disk_sum'] ?? 0) < (int) $reservation->disk_gib) {
|
|
|
return null;
|
|
|
}
|
|
|
return [
|
|
|
'unknown' => 0,
|
|
|
'instance_count' => (int) $usage['instance_count'] - 1,
|
|
|
'cpu_sum' => (int) $usage['cpu_sum']
|
|
|
- (int) $reservation->cpu_cores,
|
|
|
'memory_sum' => (int) $usage['memory_sum']
|
|
|
- (int) $reservation->memory_mib,
|
|
|
'disk_sum' => (int) $usage['disk_sum']
|
|
|
- (int) $reservation->disk_gib,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function capacityState($policy, array $usage): array
|
|
|
{
|
|
|
$cpuLimit = max(0, (int) $policy->configured_cpu_cores
|
|
|
- (int) $policy->safety_cpu_cores);
|
|
|
$memoryLimit = max(0, (int) $policy->configured_memory_mib
|
|
|
- (int) $policy->safety_memory_mib);
|
|
|
$configuredDisk = (int) $policy->configured_disk_gib * self::GIB;
|
|
|
$safetyDisk = (int) $policy->safety_disk_gib * self::GIB;
|
|
|
$diskLimit = max(0, $configuredDisk - $safetyDisk);
|
|
|
return [
|
|
|
'cpu_limit' => $cpuLimit,
|
|
|
'memory_limit' => $memoryLimit,
|
|
|
'disk_limit' => $diskLimit,
|
|
|
'cpu_used' => $usage['cpu_sum'],
|
|
|
'memory_used' => $usage['memory_sum'],
|
|
|
'disk_used' => $usage['disk_sum'] * self::GIB,
|
|
|
'instances' => $usage['instance_count'],
|
|
|
'max_instances' => (int) $policy->max_instances,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function hasCapacity($policy, array $usage, array $resources): bool
|
|
|
{
|
|
|
if ((int) ($usage['unknown'] ?? 0) > 0) {
|
|
|
return false;
|
|
|
}
|
|
|
$state = self::capacityState($policy, $usage);
|
|
|
return $state['cpu_used'] + $resources['cpu_cores'] <= $state['cpu_limit']
|
|
|
&& $state['memory_used'] + $resources['memory_mib']
|
|
|
<= $state['memory_limit']
|
|
|
&& $state['disk_used'] + ($resources['disk_gib'] * self::GIB)
|
|
|
<= $state['disk_limit']
|
|
|
&& ($state['max_instances'] < 1
|
|
|
|| $state['instances'] + 1 <= $state['max_instances']);
|
|
|
}
|
|
|
|
|
|
private static function capacityScore($policy, array $usage): float
|
|
|
{
|
|
|
$state = self::capacityState($policy, $usage);
|
|
|
$instanceScore = $state['max_instances'] > 0
|
|
|
? $state['instances'] / $state['max_instances'] : 0.0;
|
|
|
return max(
|
|
|
$state['cpu_used'] / max(1, $state['cpu_limit']),
|
|
|
$state['memory_used'] / max(1, $state['memory_limit']),
|
|
|
$state['disk_used'] / max(1, $state['disk_limit']),
|
|
|
$instanceScore
|
|
|
);
|
|
|
}
|
|
|
|
|
|
|
|
|
}
|