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/CloudOrderService.php

759 lines
35 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
use App\Models\CloudJob;
use App\Models\CloudNetworkLine;
use App\Models\CloudOffer;
use App\Models\CloudOrder;
use App\Models\CloudOrderItem;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\Shop;
use App\Models\User;
final class CloudOrderService
{
private const AUTOMATIC_NAME_SCAN_LIMIT = 256;
public static function purchase(array $input, array $actor): CloudOrder
{
if (array_key_exists('backup_id', $input)) {
throw new CloudError(
'云备份不能直接创建实例,请先保存为云快照'
);
}
CloudInput::only($input, [
'offer_id', 'source', 'template_id', 'cloud_snapshot_key',
'guest_ssh_key_id', 'root_password', 'name',
'automatic_backup', 'idempotency_key',
]);
$requestedName = CloudInput::optionalName($input['name'] ?? null);
$automaticBackup = $input['automatic_backup'] ?? false;
if (!is_bool($automaticBackup)) {
throw new CloudError('自动备份选择必须为布尔值');
}
// Missing, null and an empty field describe the same request. Keep the
// fingerprint stable without storing a generated name in the request.
$input['name'] = $requestedName ?? '';
$input['automatic_backup'] = $automaticBackup;
$idempotency = $input['idempotency_key'] ?? '';
if (!is_string($idempotency) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('请提供 16 至 128 字符的请求幂等标识');
}
$offerId = filter_var($input['offer_id'] ?? null, FILTER_VALIDATE_INT);
if (!$offerId || $offerId < 1) {
throw new CloudError('请选择可用的销售方案');
}
$source = $input['source'] ?? 'cloud';
if (!in_array($source, ['cloud', 'deployment_snapshot'], true)) {
throw new CloudError('实例来源无效');
}
$template = '';
$snapshotKey = null;
if ($source === 'cloud') {
if (array_key_exists('cloud_snapshot_key', $input)) {
throw new CloudError('云镜像部署不能携带云快照标识');
}
$template = CloudInput::template($input['template_id'] ?? '');
} else {
if (array_key_exists('template_id', $input)
|| array_key_exists('guest_ssh_key_id', $input)
|| array_key_exists('root_password', $input)) {
throw new CloudError('从云快照创建实例不能替换镜像或登录凭据');
}
$candidate = $input['cloud_snapshot_key'] ?? null;
if (!is_string($candidate)
|| preg_match('/^[a-f0-9]{32}$/D', $candidate) !== 1) {
throw new CloudError('请选择可用的云快照');
}
$snapshotKey = $candidate;
}
ksort($input);
$requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('order-request-hash'));
return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $snapshotKey, $automaticBackup, $idempotency, $requestHash) {
$user = User::where('id', $actor['user_id'])->lockForUpdate()->first();
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
$existing = CloudOrder::where('user_id', $user->id)->where('idempotency_key', $idempotency)->first();
if ($existing !== null) {
if (!hash_equals($existing->request_hash, $requestHash)) {
throw new CloudError('同一请求标识不能用于不同订单', 409);
}
return $existing;
}
// Generate only after an idempotency replay has been resolved, so
// retries return the original order and its original display name.
$name = $requestedName ?? self::automaticName($user);
$offer = CloudOffer::where('id', $offerId)->lockForUpdate()->first();
if ($offer === null || !(bool) $offer->status || (int) $offer->stock === 0
|| strtoupper((string) $offer->currency) !== 'USD') {
throw new CloudError('销售方案不可购买或已售罄', 409);
}
$plan = Shop::where('id', (int) $offer->plan_id)->lockForUpdate()->first();
$pool = CloudResourcePool::find((int) $offer->resource_pool_id);
$line = $pool === null ? null : CloudNetworkLine::find((int) $pool->line_id);
$region = $line === null ? null : CloudRegion::find((int) $line->region_id);
if ($plan === null || (int) $plan->status !== 1
|| $pool === null || (string) $pool->status !== 'active'
|| $line === null || (string) $line->status !== 'active'
|| $region === null || (string) $region->status !== 'active'
|| (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default)) {
throw new CloudError('该销售方案的地区、线路或资源池暂不可用', 409);
}
if ($source === 'cloud') {
CloudTemplateCatalogService::assertProvisionableForPool(
$template,
(int) $pool->id
);
}
$sourceSnapshot = null;
$sourceBackup = null;
$backupSpec = null;
if ($source === 'deployment_snapshot') {
$resolved = CloudDeploymentSnapshotService::resolveForOrder(
(string) $snapshotKey,
(int) $user->id
);
$sourceSnapshot = $resolved['snapshot'];
$sourceBackup = $resolved['backup'];
if ((int) $sourceSnapshot->backup_id
!== (int) $sourceBackup->id
|| (int) $sourceSnapshot->source_instance_id
!== (int) $sourceBackup->source_instance_id) {
throw new CloudError('云快照与存储对象绑定不一致', 409);
}
$backupSpec = self::assertDeploymentSnapshotBackup(
$sourceBackup,
(int) $plan->disk_gib
);
}
if (!CloudPlacementService::isPoolCapacityAvailable(
(int) $pool->id,
(int) $plan->cpu_cores,
(int) $plan->memory_mib,
(int) $plan->disk_gib,
$sourceBackup === null ? null
: $backupSpec['portable_restore_compatibility']
)) {
throw new CloudError('该销售方案当前没有足够的可用资源或公网 IP', 409);
}
$trafficPoolBinding =
CloudTrafficPoolPeriodBinding::purchaseSnapshot(
$pool,
$line,
(int) $plan->traffic_quota_bytes
);
$instancePrice = CloudMoney::cents($offer->price);
$backupPrice = $automaticBackup
? CloudMoney::cents($offer->backup_price) : 0;
$totalPrice = $instancePrice + $backupPrice;
$payload = ['source' => $source === 'cloud' ? 'cloud' : '',
'name' => $name, 'vcpu' => (int) $plan->cpu_cores,
'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps];
$credential = null;
if ($source === 'cloud') {
$key = CloudSSHKeys::owned(
$input['guest_ssh_key_id'] ?? null,
(int) $user->id
);
$password = CloudInput::password(
$input['root_password'] ?? null
);
$payload += [
'template_id' => $template,
'guest_ssh_public_key' => $key?->public_key ?? '',
'root_password' => $password,
];
$credential = [
'password' => $password,
'login_name' => 'root',
'auth_mode' => $key
? 'password_and_key' : 'password',
];
} else {
$payload += [
'description' => '',
'template_id' => '',
'template_revision' => 0,
'template_generation_token' => '',
'startup_script' => '',
// The restored system disk remains authoritative for its
// guest hostname, just as it is for the login password.
// An empty placeholder satisfies the flat create-like
// wire contract without asking the Agent to replace it.
'hostname' => '',
'guest_ssh_public_key' => '',
'root_password' => '',
'debian_12_network_fix' =>
$backupSpec['debian_12_network_fix'],
'backup_key' => (string) $sourceBackup->backup_key,
'source_size_bytes' =>
(int) $sourceBackup->object_size_bytes,
'source_sha256' => (string) $sourceBackup->sha256,
];
}
$safeSpec = CloudInput::safeResult($payload);
$safeSpec['source'] = $source;
if ($sourceBackup !== null) {
$safeSpec['deployment_snapshot_id'] =
(int) $sourceSnapshot->id;
$safeSpec['cloud_snapshot_key'] =
(string) $sourceSnapshot->snapshot_key;
$safeSpec['backing_backup_id'] = (int) $sourceBackup->id;
$safeSpec['backing_backup_key'] =
(string) $sourceBackup->backup_key;
$safeSpec['backing_backup_size_bytes'] =
(int) $sourceBackup->object_size_bytes;
$safeSpec['backing_backup_virtual_size_bytes'] =
(int) $sourceBackup->virtual_size_bytes;
$safeSpec['backing_backup_sha256'] =
(string) $sourceBackup->sha256;
$safeSpec['backing_backup_identity'] =
self::backingBackupIdentity($sourceBackup);
$safeSpec['source_portable_restore_contract_sha256'] =
$backupSpec['portable_restore_compatibility']->sha256();
foreach (['os_source', 'os_name', 'login_name',
'debian_12_network_fix'] as $field) {
$safeSpec[$field] = $backupSpec[$field];
}
}
$safeSpec['plan_name'] = $plan->name;
$safeSpec['plan_id'] = (int) $plan->id;
$safeSpec['offer_id'] = (int) $offer->id;
$safeSpec['offer_name'] = (string) $offer->name;
$safeSpec['resource_pool_id'] = (int) $pool->id;
$safeSpec['resource_pool_name'] = (string) $pool->name;
$safeSpec['line_id'] = (int) $line->id;
$safeSpec['line_name'] = (string) $line->name;
$safeSpec['region_id'] = (int) $region->id;
$safeSpec['country_code'] = strtoupper((string) $region->country_code);
$safeSpec['region'] = (string) $region->name;
$safeSpec['currency'] = 'USD';
$safeSpec['price_version'] = (int) $offer->price_version;
$safeSpec['stock_mode'] = (int) $offer->stock === -1
? 'unlimited' : 'finite';
$safeSpec['validity_days'] = (int) $plan->validity_days;
$safeSpec['traffic_quota_bytes'] = (int) $plan->traffic_quota_bytes;
$safeSpec['traffic_pool_group_id'] =
$trafficPoolBinding['traffic_pool_group_id'];
$safeSpec['traffic_quota_mode'] =
$trafficPoolBinding['traffic_quota_mode'];
$safeSpec['instance_price'] = CloudMoney::decimal($instancePrice);
$safeSpec['automatic_backup'] = $automaticBackup;
$safeSpec['backup_price'] = CloudMoney::decimal($backupPrice);
$safeSpec['renewal_price'] = CloudMoney::decimal($instancePrice);
$order = new CloudOrder();
$order->user_id = $user->id;
$order->plan_id = $plan->id;
$order->offer_id = $offer->id;
$order->resource_pool_id = $pool->id;
$order->host_id = null;
$order->reservation_id = null;
$order->deployment_snapshot_id = $sourceSnapshot === null
? null : (int) $sourceSnapshot->id;
$order->idempotency_key = $idempotency;
$order->request_hash = $requestHash;
$order->amount = CloudMoney::decimal($totalPrice);
$order->currency = 'USD';
$order->status = 'awaiting_payment';
$order->spec_json = json_encode($safeSpec, JSON_THROW_ON_ERROR);
$order->sealed_payload = CloudSecrets::encrypt(['method' => 'POST',
'request_target' => '/v1/vms', 'body' => $payload,
'credential' => $credential,
'deployment_snapshot_id' => $sourceSnapshot === null
? null : (int) $sourceSnapshot->id,
'backup_id' => $sourceBackup === null
? null : (int) $sourceBackup->id,
], 'order-payload');
$order->created_at = $order->updated_at = time();
if ((int) $offer->stock > 0) {
$offer->stock--;
$offer->updated_at = time();
$offer->save();
$order->stock_reserved_at = time();
}
$order->save();
self::createPurchaseItems(
$order,
$plan,
$offer,
$instancePrice,
$automaticBackup,
$backupPrice
);
CloudInvoiceService::issueProvision($order, $plan, $offer, time());
return $order;
}, 3);
}
private static function assertDeploymentSnapshotBackup(
?CloudInstanceBackup $backup,
int $diskGiB
): array {
$spec = $backup === null ? null
: json_decode((string) $backup->spec_json, true);
$portableRestoreCompatibility = $backup === null ? null
: $backup->sourcePortableRestoreCompatibility();
$capacity = $diskGiB > 0 && $diskGiB <= intdiv(PHP_INT_MAX, 1073741824)
? $diskGiB * 1073741824 : 0;
if ($backup === null
|| (string) $backup->purpose !== 'portable'
|| (string) $backup->source !== 'automatic'
|| $backup->subscription_id === null
|| (string) $backup->state !== 'ready'
|| (int) $backup->object_size_bytes < 1
|| (int) $backup->virtual_size_bytes < 1
|| (int) $backup->virtual_size_bytes > $capacity
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $backup->backup_key) !== 1
|| preg_match('/^[a-f0-9]{64}$/D',
(string) $backup->sha256) !== 1
|| !is_array($spec) || array_is_list($spec)
|| $portableRestoreCompatibility === null
|| ($spec['managed'] ?? null) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template'
|| !is_string($spec['os_name'] ?? null)
|| trim($spec['os_name']) === ''
|| ($spec['login_name'] ?? null) !== 'root'
|| !is_bool($spec['debian_12_network_fix'] ?? null)) {
throw new CloudError(
'云快照不可用,或所选套餐系统盘小于快照磁盘容量',
409
);
}
try {
CloudBackupStorageAuthority::readyEvidence($backup);
} catch (\InvalidArgumentException) {
throw new CloudError(
'云快照不可用,或所选套餐系统盘小于快照磁盘容量',
409
);
}
return [
'os_source' => 'cloud_template',
'os_name' => (string) $spec['os_name'],
'login_name' => 'root',
'debian_12_network_fix' => $spec['debian_12_network_fix'],
'portable_restore_compatibility' =>
$portableRestoreCompatibility,
];
}
private static function backingBackupIdentity(
CloudInstanceBackup $backup
): string {
return CloudBackupStorageAuthority::backingBackupIdentity($backup);
}
private static function createPurchaseItems(
CloudOrder $order,
Shop $plan,
CloudOffer $offer,
int $instancePrice,
bool $automaticBackup,
int $backupPrice
): void {
$now = time();
$items = [[
'code' => 'instance',
'label' => '实例套餐',
'amount' => $instancePrice,
'snapshot' => [
'plan_id' => (int) $plan->id,
'offer_id' => (int) $offer->id,
'offer_name' => (string) $offer->name,
'price_version' => (int) $offer->price_version,
'validity_days' => (int) $plan->validity_days,
],
]];
if ($automaticBackup) {
$items[] = [
'code' => 'automatic_backup',
'label' => '自动备份',
'amount' => $backupPrice,
'snapshot' => [
'offer_id' => (int) $offer->id,
'price_version' => (int) $offer->price_version,
'validity_days' => (int) $plan->validity_days,
],
];
}
$total = 0;
foreach ($items as $value) {
$item = new CloudOrderItem();
$item->order_id = (int) $order->id;
$item->code = $value['code'];
$item->label = $value['label'];
$item->amount = CloudMoney::decimal($value['amount']);
$item->currency = 'USD';
$item->snapshot_json = json_encode(
$value['snapshot'],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$item->created_at = $now;
$item->save();
$total += $value['amount'];
}
if ($total !== CloudMoney::cents((string) $order->amount)) {
throw new \RuntimeException('开通订单费用明细合计不一致');
}
}
private static function automaticName(User $user): string
{
$occupied = [];
foreach (CloudInstance::where('user_id', $user->id)
->where('status', '<>', 'deleted')->orderByDesc('id')
->limit(self::AUTOMATIC_NAME_SCAN_LIMIT)->pluck('name') as $name) {
if (is_string($name) && $name !== '') {
$occupied[$name] = true;
}
}
foreach (CloudOrder::where('user_id', $user->id)->whereIn('status',
['awaiting_payment', 'queued'])
->orderByDesc('id')->limit(self::AUTOMATIC_NAME_SCAN_LIMIT)
->get(['spec_json']) as $order) {
$spec = json_decode((string) $order->spec_json, true);
$name = is_array($spec) ? ($spec['name'] ?? null) : null;
if (is_string($name) && $name !== '') {
$occupied[$name] = true;
}
}
for ($attempt = 0; $attempt < 32; $attempt++) {
$name = CloudInput::generateInstanceName();
if (!isset($occupied[$name])) {
return $name;
}
}
throw new CloudError('暂时无法生成唯一实例名称,请重试', 503);
}
/**
* Transfer a paid provisioning invoice into the worker queue.
*
* The caller owns the surrounding wallet transaction and has locked the
* user, invoice and order rows in that order. The unique job order key is
* the final database guard against duplicate payment callbacks.
*/
public static function queuePaidProvision(CloudInvoice $invoice,
CloudOrder $order): CloudOrder
{
if ((string) $invoice->purpose !== 'provision'
|| (int) $invoice->order_id !== (int) $order->id
|| (int) $invoice->user_id !== (int) $order->user_id
|| (int) $invoice->plan_id !== (int) $order->plan_id
|| (int) $invoice->offer_id !== (int) $order->offer_id
|| strtoupper((string) $invoice->currency) !== 'USD'
|| strtoupper((string) $order->currency) !== 'USD'
|| CloudMoney::cents((string) $invoice->amount)
!== CloudMoney::cents((string) $order->amount)) {
throw new CloudError('开通账单与订单快照不匹配', 409);
}
if (in_array((string) $order->status,
['queued', 'succeeded'], true)) {
if (!CloudJob::where('order_id', $order->id)->exists()) {
throw new CloudError('开通订单缺少任务记录,请联系管理员', 409);
}
return $order;
}
if ((string) $order->status !== 'awaiting_payment'
|| !is_string($order->sealed_payload)
|| trim((string) $order->sealed_payload) === '') {
throw new CloudError('开通订单已失效或不可支付', 409);
}
$payload = CloudSecrets::decrypt(
(string) $order->sealed_payload,
'order-payload'
);
if (($payload['method'] ?? null) !== 'POST'
|| ($payload['request_target'] ?? null) !== '/v1/vms'
|| !is_array($payload['body'] ?? null)) {
throw new CloudError('开通订单的加密请求无效', 409);
}
$orderSpec = json_decode((string) $order->spec_json, true);
if (!is_array($orderSpec) || array_is_list($orderSpec)) {
throw new CloudError('开通订单的规格快照无效', 409);
}
$offer = CloudOffer::where('id', (int) $order->offer_id)
->lockForUpdate()->first();
$plan = Shop::where('id', (int) $order->plan_id)->lockForUpdate()->first();
if ($offer === null || !(bool) $offer->status || $plan === null
|| (int) $plan->status !== 1
|| (int) $offer->plan_id !== (int) $plan->id
|| (int) $offer->resource_pool_id !== (int) $order->resource_pool_id) {
throw new CloudError('该销售方案已经失效,不能继续支付', 409);
}
// Freeze the complete effective platform deny policy at the payment
// boundary. An unpaid order therefore receives the current catalog,
// while an accepted create can never drift after an administrator
// edits or deletes a test rule.
$platformPolicy =
CloudPlatformTestNetworkPolicy::snapshotForProvisioning();
$payload['body']['platform_network_policy_snapshot'] = $platformPolicy;
$source = $orderSpec['source'] ?? null;
$sourceBackup = null;
if ($source === 'cloud') {
if ($order->deployment_snapshot_id !== null
|| (int) ($payload['deployment_snapshot_id'] ?? 0) !== 0
|| (int) ($payload['backup_id'] ?? 0) !== 0) {
throw new CloudError('开通订单的云镜像来源不匹配', 409);
}
$payload['body'] = CloudTemplateCatalogService::
applyProvisioningSnapshotForPool(
$payload['body'],
(int) $order->resource_pool_id
);
$templateMetadata =
CloudTemplateCatalogService::templateMetadataSnapshot(
$payload['body']
);
if (!is_string($orderSpec['template_id'] ?? null)
|| !hash_equals(
(string) $templateMetadata['template_id'],
$orderSpec['template_id']
)) {
throw new CloudError('开通订单的云镜像快照不匹配', 409);
}
// Keep PHP-only presentation metadata beside the strict Go
// request. Only payload.body crosses the Agent boundary.
$payload['template_metadata'] = $templateMetadata;
$orderSpec = array_replace($orderSpec, $templateMetadata);
} elseif ($source === 'deployment_snapshot') {
$snapshotId = filter_var(
$orderSpec['deployment_snapshot_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
$backupId = filter_var(
$orderSpec['backing_backup_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
$snapshotKey = $orderSpec['cloud_snapshot_key'] ?? null;
if ($snapshotId === false || $backupId === false
|| !is_string($snapshotKey)
|| preg_match('/^[a-f0-9]{32}$/D', $snapshotKey) !== 1
|| (int) ($order->deployment_snapshot_id ?? 0)
!== (int) $snapshotId
|| (int) ($payload['deployment_snapshot_id'] ?? 0)
!== (int) $snapshotId
|| (int) ($payload['backup_id'] ?? 0) !== (int) $backupId) {
throw new CloudError('开通订单的云快照来源不匹配', 409);
}
$resolved = CloudDeploymentSnapshotService::resolveForOrder(
$snapshotKey,
(int) $order->user_id
);
$sourceSnapshot = $resolved['snapshot'];
$sourceBackup = $resolved['backup'];
$frozenDiskGiB = filter_var(
$orderSpec['disk_gib'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($frozenDiskGiB === false) {
throw new CloudError(
'开通订单的系统盘容量快照无效',
409
);
}
$metadata = self::assertDeploymentSnapshotBackup(
$sourceBackup,
(int) $frozenDiskGiB
);
if ((int) $sourceSnapshot->id !== (int) $snapshotId
|| (int) $sourceSnapshot->backup_id !== (int) $backupId
|| (int) $sourceSnapshot->source_instance_id
!== (int) $sourceBackup->source_instance_id
|| (int) $sourceBackup->id !== (int) $backupId
|| !hash_equals((string) $sourceSnapshot->snapshot_key,
$snapshotKey)
|| !hash_equals((string) $sourceBackup->backup_key,
(string) ($orderSpec['backing_backup_key'] ?? ''))
|| !hash_equals((string) $sourceBackup->backup_key,
(string) ($payload['body']['backup_key'] ?? ''))
|| (int) $sourceBackup->object_size_bytes
!== (int) ($orderSpec['backing_backup_size_bytes'] ?? 0)
|| (int) $sourceBackup->object_size_bytes
!== (int) ($payload['body']['source_size_bytes'] ?? 0)
|| (int) $sourceBackup->virtual_size_bytes
!== (int) ($orderSpec[
'backing_backup_virtual_size_bytes'
] ?? 0)
|| !hash_equals((string) $sourceBackup->sha256,
(string) ($orderSpec['backing_backup_sha256'] ?? ''))
|| !hash_equals((string) $sourceBackup->sha256,
(string) ($payload['body']['source_sha256'] ?? ''))
|| !hash_equals(
self::backingBackupIdentity($sourceBackup),
(string) ($orderSpec['backing_backup_identity'] ?? '')
)
|| !hash_equals(
$metadata['portable_restore_compatibility']->sha256(),
(string) ($orderSpec[
'source_portable_restore_contract_sha256'
] ?? '')
)) {
throw new CloudError('开通订单的云快照存储对象身份已变化', 409);
}
$transfer = CloudBackupService::provisioningSource($sourceBackup);
$payload['body']['source_url'] = $transfer['source_url'];
$payload['body']['source_size_bytes'] =
(int) $sourceBackup->object_size_bytes;
$payload['body']['source_sha256'] =
(string) $sourceBackup->sha256;
$payload['backup_metadata'] = [
'deployment_snapshot_id' => (int) $sourceSnapshot->id,
'cloud_snapshot_key' =>
(string) $sourceSnapshot->snapshot_key,
'backing_backup_id' => (int) $sourceBackup->id,
'backing_backup_key' => (string) $sourceBackup->backup_key,
'backup_id' => (int) $sourceBackup->id,
'backup_key' => (string) $sourceBackup->backup_key,
'os_source' => $metadata['os_source'],
'os_name' => $metadata['os_name'],
'login_name' => $metadata['login_name'],
'debian_12_network_fix' =>
$metadata['debian_12_network_fix'],
'source_portable_restore_contract_sha256' =>
$metadata['portable_restore_compatibility']->sha256(),
];
unset($payload['credential']);
} else {
throw new CloudError('开通订单的实例来源无效', 409);
}
$orderSpec['platform_network_policy_snapshot'] = $platformPolicy;
$order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$placement = CloudPlacementService::reserve(
$order,
$offer,
$plan,
$payload,
$sourceBackup === null ? null
: $metadata['portable_restore_compatibility']
);
$orderSpec['public_network'] =
$placement['public_network']->toArray();
if ($orderSpec['public_network']
!== $placement['payload']['body']['public_network']) {
throw new CloudError('开通订单与任务的双栈公网快照不一致', 409);
}
$order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($sourceBackup !== null) {
$restoreTarget = $placement['portable_restore_target'] ?? null;
if (!is_array($restoreTarget)
|| array_is_list($restoreTarget)
|| filter_var(
$restoreTarget['agent_revision'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
) === false
|| !is_string(
$restoreTarget['agent_contract_sha256'] ?? null
)
|| !hash_equals(
$metadata['portable_restore_compatibility']->sha256(),
$restoreTarget['agent_contract_sha256']
)) {
throw new CloudError(
'开通订单的目标 Agent 恢复合同快照无效',
409
);
}
$orderSpec['target_agent_revision'] =
(int) $restoreTarget['agent_revision'];
$orderSpec['target_agent_contract_sha256'] =
$restoreTarget['agent_contract_sha256'];
$placement['payload']['backup_metadata'][
'target_agent_revision'
] = (int) $restoreTarget['agent_revision'];
$placement['payload']['backup_metadata'][
'target_agent_contract_sha256'
] = $restoreTarget['agent_contract_sha256'];
$order->spec_json = json_encode(
$orderSpec,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
$uuid = CloudOperationRecoveryIdentity::operationUuid(
(string) $placement['reservation']->operation_id
);
$placement['payload']['request_target'] = '/v1/vms/'
. rawurlencode($uuid) . '/restore-backup';
$placement['payload']['body']['uuid'] = $uuid;
$placement['payload']['body']['operation_id'] =
(string) $placement['reservation']->operation_id;
}
$job = new CloudJob();
$job->operation_id = (string) $placement['reservation']->operation_id;
$job->order_id = $order->id;
$job->user_id = $order->user_id;
$job->host_id = $placement['host']->id;
$job->kind = 'create';
$job->backup_id = $sourceBackup === null
? null : (int) $sourceBackup->id;
$job->execution_mode = 'agent';
$job->status = 'queued';
$job->sealed_payload = CloudSecrets::encrypt(
$placement['payload'], 'job-payload'
);
$job->available_at = $job->created_at = $job->updated_at = time();
$job->save();
// The worker now owns the sole recoverable credential copy.
$order->sealed_payload = null;
$order->status = 'queued';
$order->updated_at = time();
$order->save();
return $order;
}
/** Release a finite plan reservation exactly once. */
public static function releaseStock(CloudOrder $order): void
{
if ($order->stock_reserved_at === null || $order->stock_released_at !== null) {
return;
}
$offer = CloudOffer::where('id', $order->offer_id)->lockForUpdate()->first();
if ($offer !== null && (int) $offer->stock >= 0) {
$offer->stock = (int) $offer->stock + 1;
$offer->updated_at = time();
$offer->save();
}
$order->stock_released_at = time();
$order->updated_at = time();
$order->save();
}
public static function display(CloudOrder $order): array
{
$job = CloudJob::where('order_id', $order->id)->first();
$invoice = CloudInvoice::where('order_id', $order->id)->first();
$jobStatus = $job === null ? null
: ((string) $job->phase === 'terminal'
&& in_array((string) $job->outcome,
['succeeded', 'failed'], true)
? (string) $job->outcome : 'active');
$error = $job === null ? null : CloudOperationErrorCatalog::userMessage(
(string) $job->kind, $jobStatus, $job->error_code, true
);
return ['id' => (string) $order->id, 'user_id' => (int) $order->user_id, 'status' => $order->status, 'amount' => (string) $order->amount,
'offer_id' => (int) $order->offer_id,
'instance_id' => $order->instance_id === null ? null : (string) $order->instance_id,
'created_at' => (int) $order->created_at, 'updated_at' => (int) ($job?->updated_at ?? $order->updated_at),
'invoice_id' => $invoice === null ? null : (string) $invoice->id,
'task_id' => $job === null ? '' : (string) $job->id,
'job_status' => $jobStatus,
'job_completed' => $job === null ? null
: (string) $job->phase === 'terminal',
'attempts' => (int) ($job?->attempts ?? 0),
'error' => $error];
}
}