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/CloudPortableRestoreJobDisp...

390 lines
17 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudBackupRestore;
use App\Models\CloudBackupRestoreAttempt;
use App\Models\CloudHost;
use App\Models\CloudInstanceBackup;
use App\Models\CloudJob;
use App\Models\CloudResourceReservation;
use App\Models\User;
/** Converts one fully reserved portable-restore generation into one job. */
final class CloudPortableRestoreJobDispatcher
{
private const MAX_HINT_RETRIES = 3;
public static function queue(array $actor, string $attemptKey): CloudJob
{
CloudAccess::manage($actor);
$requesterId = filter_var(
$actor['user_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($requesterId === false
|| preg_match('/^[a-f0-9]{32}$/D', $attemptKey) !== 1) {
throw new CloudError('恢复任务派发身份无效', 409);
}
return self::queueForRequester(
(int) $requesterId,
$attemptKey,
false
);
}
/**
* Continue one exact admission which is durably proven undispatched.
* Authorization was committed with that admission; like an ordinary
* queued job, a later account-role change must not strand its resources.
*/
public static function recoverUndispatched(
string $attemptKey
): CloudJob {
if (preg_match('/^[a-f0-9]{32}$/D', $attemptKey) !== 1) {
throw new CloudError('恢复任务派发身份无效', 409);
}
$hints = self::hints($attemptKey);
return self::queueForRequester(
(int) $hints['requester_user_id'],
$attemptKey,
true
);
}
private static function queueForRequester(int $requesterId,
string $attemptKey, bool $durableAdmission): CloudJob
{
for ($round = 0; $round < self::MAX_HINT_RETRIES; $round++) {
$hints = self::hints($attemptKey);
$result = (new CloudJob())->getConnection()->transaction(
static function () use (
$requesterId,
$attemptKey,
$hints,
$durableAdmission
): array {
$userIds = array_values(array_unique([
(int) $requesterId,
(int) $hints['owner_user_id'],
]));
sort($userIds, SORT_NUMERIC);
$users = User::whereIn('id', $userIds)->orderBy('id')
->lockForUpdate()->get()->keyBy('id');
$requester = $users->get((int) $requesterId);
$owner = $users->get((int) $hints['owner_user_id']);
if (!$requester instanceof User
|| (!$durableAdmission
&& (int) $requester->enable !== 1)
|| !$owner instanceof User
|| (!$durableAdmission
&& (int) $owner->enable !== 1)) {
throw new CloudError('恢复任务账户不可用', 403);
}
$parentJob = self::lockJob($hints['parent_job_id']);
$exactJob = $hints['job_id'] === $hints['parent_job_id']
? $parentJob : self::lockJob($hints['job_id']);
$backup = CloudInstanceBackup::where(
'id',
(int) $hints['backup_id']
)->lockForUpdate()->first();
$host = CloudHost::where(
'id',
(int) $hints['host_id']
)->lockForUpdate()->first();
$restore = CloudBackupRestore::where(
'id',
(int) $hints['restore_id']
)->lockForUpdate()->first();
$attempt = CloudBackupRestoreAttempt::where(
'id',
(int) $hints['attempt_id']
)->where('attempt_key', $attemptKey)
->lockForUpdate()->first();
if (!$backup instanceof CloudInstanceBackup
|| !$host instanceof CloudHost
|| !$restore instanceof CloudBackupRestore
|| !$attempt instanceof CloudBackupRestoreAttempt) {
throw new CloudError('恢复任务派发账本不完整', 409);
}
if (($attempt->job_id === null ? null
: (int) $attempt->job_id)
!== $hints['job_id']
|| ($restore->job_id === null ? null
: (int) $restore->job_id)
!== $hints['parent_job_id']) {
return ['retry' => true];
}
if (($hints['job_id'] !== null
&& !$exactJob instanceof CloudJob)
|| ($hints['parent_job_id'] !== null
&& !$parentJob instanceof CloudJob)) {
throw new CloudError('恢复任务关联作业已经丢失', 409);
}
if ($durableAdmission
&& ((string) $attempt->state !== 'reserved'
|| $attempt->job_id !== null
|| $exactJob instanceof CloudJob)) {
throw new CloudError('恢复预留已经派发,不可重复续派', 409);
}
$plan = self::plan($restore, $attempt);
$planValue = $plan->toArray();
if ((int) $restore->backup_id !== (int) $backup->id
|| (int) $restore->requested_by_user_id
!== (int) $requesterId
|| (int) $backup->user_id
!== (int) $hints['owner_user_id']
|| (int) $attempt->backup_restore_id
!== (int) $restore->id
|| (int) $attempt->target_host_id !== (int) $host->id
|| (int) $restore->target_host_id !== (int) $host->id
|| (int) $planValue['target']['host_id']
!== (int) $host->id) {
throw new CloudError('恢复任务派发归属已经变化', 409);
}
$evidence = CloudPortableRestoreBackupEvidence::fromBackup(
$backup
);
self::assertPlanEvidence($planValue, $evidence);
CloudPublicNetworkAllocationService::verifyExistingBundle(
(int) $host->id,
(int) $planValue['target']['line_id'],
(int) $attempt->reservation_id,
(string) $attempt->operation_id
);
$reservation = CloudResourceReservation::where(
'id',
(int) $attempt->reservation_id
)->lockForUpdate()->first();
if (!$reservation instanceof CloudResourceReservation
|| (string) $reservation->state !== 'held'
|| $reservation->instance_id !== null
|| (int) $reservation->host_id !== (int) $host->id
|| (int) $reservation->user_id
!== (int) $backup->user_id
|| !hash_equals(
(string) $reservation->operation_id,
(string) $attempt->operation_id
)) {
throw new CloudError('恢复任务资源预留不可派发', 409);
}
$claimSet =
CloudPublicNetworkAllocationService::currentClaimSet(
(int) $reservation->id,
'held'
);
try {
$network = CloudFrozenPublicNetworkIdentity::fromStored(
(int) $reservation->id,
(int) $attempt->target_host_id,
(string) $attempt->target_uuid,
(int) $attempt->target_network_attachment_id,
(string) $attempt->target_identity_json,
(string) $attempt->target_identity_sha256,
(string) $attempt->target_public_network_json,
(string) $attempt->target_public_network_sha256,
(string) $attempt->target_claim_set_sha256,
$claimSet
);
} catch (\InvalidArgumentException) {
throw new CloudError('恢复任务冻结公网身份损坏', 409);
}
$envelope = CloudPortableRestoreJobEnvelope::fromLedger(
$backup,
$restore,
$attempt,
$reservation,
$plan,
$evidence,
$network
);
if ($exactJob instanceof CloudJob) {
self::assertReplayJob(
$exactJob,
$backup,
$restore,
$attempt,
$envelope
);
return ['job' => $exactJob];
}
if ((string) $attempt->state !== 'reserved'
|| (string) $attempt->effect_resolution
!== 'not_applicable'
|| $attempt->active_attempt === null
|| $attempt->effect_resolved_at !== null
|| $attempt->terminal_at !== null) {
throw new CloudError('恢复尝试当前不可派发', 409);
}
$now = time();
$job = new CloudJob();
$job->operation_id = (string) $attempt->operation_id;
$job->request_idempotency_key =
(string) $attempt->attempt_key;
$job->request_fingerprint = $envelope->fingerprint();
$job->user_id = (int) $backup->user_id;
$job->host_id = (int) $attempt->target_host_id;
$job->instance_id = null;
$job->backup_id = (int) $backup->id;
$job->backup_restore_id = (int) $restore->id;
$job->kind = 'backup_restore';
$job->execution_mode = 'agent';
$job->status = 'queued';
$job->sealed_payload = CloudSecrets::encrypt(
$envelope->payload(),
'job-payload'
);
$job->available_at = $job->created_at = $job->updated_at =
$now;
$job->save();
$attempt->job_id = (int) $job->id;
$attempt->state = 'queued';
$attempt->last_error_code = '';
$attempt->finalization_error_code = '';
$attempt->updated_at = $now;
$attempt->save();
if ((int) $attempt->generation === 1) {
if ($restore->job_id !== null
&& (int) $restore->job_id !== (int) $job->id) {
throw new CloudError(
'恢复父请求已经绑定其他首代作业',
409
);
}
$restore->job_id = (int) $job->id;
$restore->updated_at = $now;
$restore->save();
}
return ['job' => $job];
},
3
);
if (($result['retry'] ?? false) === true) {
continue;
}
if (($result['job'] ?? null) instanceof CloudJob) {
return $result['job'];
}
break;
}
throw new CloudError('恢复任务派发账本正在变化,请稍后重试', 409);
}
private static function hints(string $attemptKey): array
{
$attempt = CloudBackupRestoreAttempt::where(
'attempt_key',
$attemptKey
)->first();
$restore = $attempt instanceof CloudBackupRestoreAttempt
? CloudBackupRestore::find((int) $attempt->backup_restore_id)
: null;
$backup = $restore instanceof CloudBackupRestore
? CloudInstanceBackup::find((int) $restore->backup_id)
: null;
if (!$attempt instanceof CloudBackupRestoreAttempt
|| !$restore instanceof CloudBackupRestore
|| !$backup instanceof CloudInstanceBackup
|| (int) $attempt->id < 1 || (int) $restore->id < 1
|| (int) $backup->id < 1 || (int) $attempt->target_host_id < 1
|| (int) $backup->user_id < 1
|| (int) $restore->requested_by_user_id < 1) {
throw new CloudError('恢复任务派发账本不存在', 404);
}
return [
'attempt_id' => (int) $attempt->id,
'restore_id' => (int) $restore->id,
'backup_id' => (int) $backup->id,
'owner_user_id' => (int) $backup->user_id,
'requester_user_id' => (int) $restore->requested_by_user_id,
'host_id' => (int) $attempt->target_host_id,
'parent_job_id' => $restore->job_id === null
? null : (int) $restore->job_id,
'job_id' => $attempt->job_id === null
? null : (int) $attempt->job_id,
];
}
private static function lockJob(?int $jobId): ?CloudJob
{
return $jobId === null ? null
: CloudJob::where('id', $jobId)->lockForUpdate()->first();
}
private static function plan(CloudBackupRestore $restore,
CloudBackupRestoreAttempt $attempt): CloudPortableRestoreTargetPlan
{
try {
$plan = CloudPortableRestoreTargetPlan::fromStored(
(string) $attempt->target_plan_json,
(string) $attempt->target_plan_sha256
);
} catch (\InvalidArgumentException) {
throw new CloudError('恢复任务保存的目标计划损坏', 409);
}
if (!hash_equals(
(string) $restore->selected_plan_sha256,
$plan->sha256()
)
|| !hash_equals(
(string) $restore->selected_plan_json,
$plan->json()
)) {
throw new CloudError('恢复任务与父请求目标计划不一致', 409);
}
return $plan;
}
private static function assertPlanEvidence(array $plan,
CloudPortableRestoreBackupEvidence $evidence): void
{
if (CloudCanonicalJson::normalize($plan['backup'])
!== CloudCanonicalJson::normalize($evidence->backup())
|| CloudCanonicalJson::normalize($plan['resources'])
!== CloudCanonicalJson::normalize($evidence->resources())) {
throw new CloudError('恢复任务备份或冻结规格已经变化', 409);
}
}
private static function assertReplayJob(CloudJob $job,
CloudInstanceBackup $backup, CloudBackupRestore $restore,
CloudBackupRestoreAttempt $attempt,
CloudPortableRestoreJobEnvelope $envelope): void
{
if ((int) $job->user_id !== (int) $backup->user_id
|| (int) $job->host_id !== (int) $attempt->target_host_id
|| (int) $job->backup_id !== (int) $backup->id
|| (int) $job->backup_restore_id !== (int) $restore->id
|| $job->instance_id !== null
|| (string) $job->kind !== 'backup_restore'
|| (string) $job->execution_mode !== 'agent'
|| !hash_equals(
(string) $job->operation_id,
(string) $attempt->operation_id
)
|| !hash_equals(
(string) $job->request_idempotency_key,
(string) $attempt->attempt_key
)
|| (string) $attempt->state !== 'queued'
|| (string) $attempt->effect_resolution !== 'not_applicable'
|| $attempt->active_attempt === null
|| !in_array((string) $job->phase,
['accepted', 'dispatching', 'awaiting_receipt'], true)
|| $job->outcome !== null
|| (string) $job->effect_resolution !== 'not_applicable') {
throw new CloudError('恢复任务幂等作业身份不一致', 409);
}
$envelope->assertStoredJob($job);
}
}