feat(cloud): carry snapshots in maintenance migrations
parent
f491b99d35
commit
01807ab444
@ -0,0 +1,399 @@
|
||||
//go:build libvirt
|
||||
|
||||
package hypervisor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.luoli.live/root/virt/agent/objecttransfer"
|
||||
"git.luoli.live/root/virt/agent/operation"
|
||||
"libvirt.org/go/libvirt"
|
||||
"libvirt.org/go/libvirtxml"
|
||||
)
|
||||
|
||||
// createMigrationBundle exports the immutable local snapshot set first and
|
||||
// stops the source only for the final system-disk capture. A partially
|
||||
// completed multi-object upload is deliberately fenced as uncertain: the
|
||||
// Agent has no object-store delete credential and must never pretend the
|
||||
// already committed artifacts do not exist.
|
||||
func (l *Libvirt) createMigrationBundle(ctx context.Context, uuid string,
|
||||
request BackupRequest) (_ BackupResult, resultErr error) {
|
||||
client := objecttransfer.New()
|
||||
defer client.CloseIdleConnections()
|
||||
|
||||
stored, err := l.validateMigrationBundleSource(ctx, uuid, request)
|
||||
if err != nil {
|
||||
return BackupResult{}, l.abortRejectedMigrationBundlePlans(
|
||||
ctx, client, request, err,
|
||||
)
|
||||
}
|
||||
artifacts := make([]MigrationBundleArtifactResult, 0, len(stored))
|
||||
for index, metadata := range stored {
|
||||
volume, lookupErr := l.lookupOptionalManagedVolume(
|
||||
l.storagePoolName(StorageRoleManaged),
|
||||
snapshotVolumeName(uuid, metadata.Key),
|
||||
)
|
||||
if lookupErr != nil || volume == nil {
|
||||
return BackupResult{}, l.migrationBundleExportFailure(
|
||||
ctx, client, request, index, len(artifacts) > 0,
|
||||
NewError(ErrUnavailable, "migration_snapshot_unavailable",
|
||||
"migration snapshot volume is unavailable", lookupErr),
|
||||
)
|
||||
}
|
||||
info, inspectErr := validateStandaloneQCOW2Volume(volume, metadata.SizeBytes)
|
||||
path, pathErr := volume.GetPath()
|
||||
_ = volume.Free()
|
||||
if inspectErr != nil || pathErr != nil || !filepath.IsAbs(path) {
|
||||
cause := inspectErr
|
||||
if cause == nil {
|
||||
cause = translateOptionalLibvirtError(
|
||||
"resolve migration snapshot path", pathErr,
|
||||
)
|
||||
}
|
||||
return BackupResult{}, l.migrationBundleExportFailure(
|
||||
ctx, client, request, index, len(artifacts) > 0, cause,
|
||||
)
|
||||
}
|
||||
upload, uploadErr := client.UploadFile(
|
||||
ctx, path, request.MigrationBundle.Snapshots[index].ObjectUpload,
|
||||
)
|
||||
if uploadErr != nil {
|
||||
return BackupResult{}, l.migrationBundleExportFailure(
|
||||
ctx, client, request, index+1, len(artifacts) > 0,
|
||||
translateObjectTransferError(uploadErr),
|
||||
)
|
||||
}
|
||||
if upload.SizeBytes <= 0 || upload.SHA256 == "" {
|
||||
return BackupResult{}, operation.MarkUncertain(NewError(
|
||||
ErrUnavailable, "migration_snapshot_upload_invalid",
|
||||
"migration snapshot upload result is invalid", nil,
|
||||
))
|
||||
}
|
||||
artifacts = append(artifacts, MigrationBundleArtifactResult{
|
||||
SnapshotKey: metadata.Key, Name: metadata.Name,
|
||||
Consistency: metadata.Consistency, SizeBytes: upload.SizeBytes,
|
||||
VirtualSizeBytes: info.Capacity, SHA256: upload.SHA256,
|
||||
CreatedAt: metadata.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
maintenanceState, err := l.prepareMaintenanceMigrationSource(ctx, uuid)
|
||||
if err != nil {
|
||||
return BackupResult{}, operation.MarkUncertain(err)
|
||||
}
|
||||
defer func() {
|
||||
if resultErr == nil {
|
||||
return
|
||||
}
|
||||
if rollbackErr := l.restoreMaintenanceMigrationSource(
|
||||
context.WithoutCancel(ctx), uuid, maintenanceState,
|
||||
); rollbackErr != nil {
|
||||
resultErr = operation.MarkUncertain(errors.Join(resultErr, rollbackErr))
|
||||
}
|
||||
}()
|
||||
|
||||
snapshot, err := l.createStoppedBackupSnapshot(ctx, uuid, SnapshotRequest{
|
||||
OperationID: request.OperationID, SnapshotKey: request.BackupKey,
|
||||
Name: request.Name, ConsistencyMode: request.ConsistencyMode,
|
||||
})
|
||||
if err != nil {
|
||||
return BackupResult{}, operation.MarkUncertain(err)
|
||||
}
|
||||
volume, err := l.lookupOptionalManagedVolume(
|
||||
l.storagePoolName(StorageRoleManaged), snapshotVolumeName(uuid, request.BackupKey),
|
||||
)
|
||||
if err != nil || volume == nil {
|
||||
return BackupResult{}, operation.MarkUncertain(NewError(
|
||||
ErrUnavailable, "backup_snapshot_unavailable",
|
||||
"local migration root snapshot is unavailable", err,
|
||||
))
|
||||
}
|
||||
info, inspectErr := validateStandaloneQCOW2Volume(volume, snapshot.SizeBytes)
|
||||
path, pathErr := volume.GetPath()
|
||||
_ = volume.Free()
|
||||
if inspectErr != nil || pathErr != nil || !filepath.IsAbs(path) {
|
||||
cause := inspectErr
|
||||
if cause == nil {
|
||||
cause = translateOptionalLibvirtError(
|
||||
"resolve migration root snapshot path", pathErr,
|
||||
)
|
||||
}
|
||||
return BackupResult{}, operation.MarkUncertain(cause)
|
||||
}
|
||||
upload, err := client.UploadFile(ctx, path, request.ObjectUpload)
|
||||
if err != nil {
|
||||
return BackupResult{}, operation.MarkUncertain(
|
||||
translateObjectTransferError(err),
|
||||
)
|
||||
}
|
||||
if upload.SizeBytes <= 0 || upload.SHA256 == "" {
|
||||
return BackupResult{}, operation.MarkUncertain(NewError(
|
||||
ErrUnavailable, "backup_upload_invalid",
|
||||
"migration root upload result is invalid", nil,
|
||||
))
|
||||
}
|
||||
result := BackupResult{
|
||||
BackupKey: request.BackupKey, SizeBytes: upload.SizeBytes,
|
||||
VirtualSizeBytes: info.Capacity, SHA256: upload.SHA256,
|
||||
Consistency: snapshot.Consistency, SourceStopped: true,
|
||||
SourceWasRunning: maintenanceState.wasRunning,
|
||||
SourceAutostartEnabled: maintenanceState.autostart,
|
||||
SourceAutostartDisabled: true, MigrationBundleVersion: 1,
|
||||
SnapshotArtifacts: artifacts,
|
||||
}
|
||||
cleanupCtx, cleanupCancel := backupLocalCleanupContext(ctx)
|
||||
_, cleanupErr := l.DeleteSnapshot(cleanupCtx, uuid, request.BackupKey,
|
||||
SnapshotMutationRequest{OperationID: request.OperationID})
|
||||
cleanupCancel()
|
||||
if cleanupErr != nil {
|
||||
result.CleanupPending = true
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (l *Libvirt) validateMigrationBundleSource(ctx context.Context, uuid string,
|
||||
request BackupRequest) ([]domainSnapshotMetadataXML, error) {
|
||||
if _, err := l.validateBackupSource(ctx, uuid, request.BackupKey); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
domain, err := l.domainByUUID(ctx, uuid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer domain.Free()
|
||||
document, err := domain.GetXMLDesc(0)
|
||||
if err != nil {
|
||||
return nil, translateLibvirtError("read migration source metadata", err)
|
||||
}
|
||||
_, metadata, err := parseManagedDomain(document)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(metadata.Snapshots) != len(request.MigrationBundle.Snapshots) {
|
||||
return nil, NewError(ErrConflict, "migration_snapshot_catalog_changed",
|
||||
"migration bundle must include every current snapshot", nil)
|
||||
}
|
||||
byKey := make(map[string]domainSnapshotMetadataXML, len(metadata.Snapshots))
|
||||
for _, snapshot := range metadata.Snapshots {
|
||||
byKey[snapshot.Key] = snapshot
|
||||
}
|
||||
ordered := make([]domainSnapshotMetadataXML, 0, len(metadata.Snapshots))
|
||||
for _, requested := range request.MigrationBundle.Snapshots {
|
||||
snapshot, ok := byKey[requested.SnapshotKey]
|
||||
if !ok {
|
||||
return nil, NewError(ErrConflict, "migration_snapshot_catalog_changed",
|
||||
"migration snapshot catalog changed before export", nil)
|
||||
}
|
||||
ordered = append(ordered, snapshot)
|
||||
}
|
||||
return ordered, nil
|
||||
}
|
||||
|
||||
func (l *Libvirt) abortRejectedMigrationBundlePlans(ctx context.Context,
|
||||
client *objecttransfer.Client, request BackupRequest, rejection error) error {
|
||||
errs := []error{rejection}
|
||||
if err := client.AbortMultipart(ctx, request.ObjectUpload); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
for _, snapshot := range request.MigrationBundle.Snapshots {
|
||||
if err := client.AbortMultipart(ctx, snapshot.ObjectUpload); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return operation.MarkNotApplied(errors.Join(errs...))
|
||||
}
|
||||
|
||||
// migrationBundleExportFailure aborts plans that have not started. Once an
|
||||
// artifact completed, the overall multi-object effect can no longer be called
|
||||
// not-applied even when a later upload fails deterministically.
|
||||
func (l *Libvirt) migrationBundleExportFailure(ctx context.Context,
|
||||
client *objecttransfer.Client, request BackupRequest, nextSnapshot int,
|
||||
completed bool, cause error) error {
|
||||
errs := []error{cause}
|
||||
if err := client.AbortMultipart(ctx, request.ObjectUpload); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
for index := nextSnapshot; index < len(request.MigrationBundle.Snapshots); index++ {
|
||||
if err := client.AbortMultipart(
|
||||
ctx, request.MigrationBundle.Snapshots[index].ObjectUpload,
|
||||
); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
joined := errors.Join(errs...)
|
||||
if completed || len(errs) > 1 || operation.IsUncertain(cause) {
|
||||
return operation.MarkUncertain(joined)
|
||||
}
|
||||
return operation.MarkNotApplied(joined)
|
||||
}
|
||||
|
||||
func (l *Libvirt) restoreMigrationBundle(ctx context.Context,
|
||||
request RestoreBackupRequest, create CreateVMRequest,
|
||||
attachment NetworkAttachment, seed []byte,
|
||||
root *libvirt.StorageVol) (_ RestoreBackupResult, resultErr error) {
|
||||
volumes := make([]*libvirt.StorageVol, 0,
|
||||
len(request.MigrationBundle.Snapshots))
|
||||
metadata := make([]domainSnapshotMetadataXML, 0,
|
||||
len(request.MigrationBundle.Snapshots))
|
||||
artifacts := make([]MigrationBundleArtifactResult, 0,
|
||||
len(request.MigrationBundle.Snapshots))
|
||||
for _, source := range request.MigrationBundle.Snapshots {
|
||||
volume, err := l.createMigrationSnapshotVolume(ctx, request.UUID, source)
|
||||
if err != nil {
|
||||
for _, prior := range volumes {
|
||||
if cleanupErr := prior.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL); cleanupErr != nil {
|
||||
resultErr = operation.MarkUncertain(errors.Join(
|
||||
err, mutationLibvirtError(
|
||||
"roll back restored migration snapshot", cleanupErr,
|
||||
),
|
||||
))
|
||||
}
|
||||
_ = prior.Free()
|
||||
}
|
||||
if cleanupErr := root.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL); cleanupErr != nil {
|
||||
resultErr = operation.MarkUncertain(errors.Join(
|
||||
resultErr, err, mutationLibvirtError(
|
||||
"roll back restored migration root", cleanupErr,
|
||||
),
|
||||
))
|
||||
}
|
||||
_ = root.Free()
|
||||
if resultErr != nil {
|
||||
return RestoreBackupResult{}, resultErr
|
||||
}
|
||||
return RestoreBackupResult{}, err
|
||||
}
|
||||
volumes = append(volumes, volume)
|
||||
metadata = append(metadata, domainSnapshotMetadataXML{
|
||||
Key: source.SnapshotKey, Name: source.Name,
|
||||
Consistency: source.Consistency, SizeBytes: source.VirtualSizeBytes,
|
||||
CreatedAt: source.CreatedAt,
|
||||
})
|
||||
artifacts = append(artifacts, MigrationBundleArtifactResult{
|
||||
SnapshotKey: source.SnapshotKey, Name: source.Name,
|
||||
Consistency: source.Consistency, SizeBytes: source.SourceSizeBytes,
|
||||
VirtualSizeBytes: source.VirtualSizeBytes,
|
||||
SHA256: source.SourceSHA256, CreatedAt: source.CreatedAt,
|
||||
})
|
||||
}
|
||||
vm, err := l.createVMWithPreparedRootOptions(
|
||||
ctx, create, attachment, seed, root, preparedVMOptions{
|
||||
Autostart: false, Start: false,
|
||||
NetworkSuspended: request.MigrationBundle.NetworkSuspended,
|
||||
Snapshots: metadata, SnapshotVolumes: volumes,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return RestoreBackupResult{}, err
|
||||
}
|
||||
return RestoreBackupResult{
|
||||
VMMetadata: vm, BackupKey: request.BackupKey,
|
||||
SHA256: request.SourceSHA256, MigrationBundleVersion: 1,
|
||||
SnapshotArtifacts: artifacts, StagedPoweredOff: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *Libvirt) createMigrationSnapshotVolume(ctx context.Context,
|
||||
uuid string, source MigrationBundleSnapshotSource) (*libvirt.StorageVol, error) {
|
||||
volumeName := snapshotVolumeName(uuid, source.SnapshotKey)
|
||||
initialCapacity := source.VirtualSizeBytes
|
||||
if objectBytes := uint64(source.SourceSizeBytes); objectBytes > initialCapacity {
|
||||
initialCapacity = objectBytes
|
||||
}
|
||||
pool, err := l.conn.LookupStoragePoolByName(
|
||||
l.storagePoolName(StorageRoleManaged),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, createVMStorageCloneStage.wrap(
|
||||
translateLibvirtError("lookup managed storage pool", err),
|
||||
)
|
||||
}
|
||||
defer pool.Free()
|
||||
definition := libvirtxml.StorageVolume{
|
||||
Name: volumeName,
|
||||
Capacity: &libvirtxml.StorageVolumeSize{
|
||||
Value: initialCapacity, Unit: "bytes",
|
||||
},
|
||||
Target: &libvirtxml.StorageVolumeTarget{
|
||||
Format: &libvirtxml.StorageVolumeTargetFormat{Type: "qcow2"},
|
||||
},
|
||||
}
|
||||
document, err := definition.Marshal()
|
||||
if err != nil {
|
||||
return nil, createVMStorageCloneStage.wrap(
|
||||
fmt.Errorf("marshal restored migration snapshot XML: %w", err),
|
||||
)
|
||||
}
|
||||
volume, err := pool.StorageVolCreateXML(document, 0)
|
||||
if err != nil {
|
||||
absent, inspectErr := l.dirPoolVolumeAbsent(pool, volumeName)
|
||||
return nil, createVMStorageCloneStage.wrap(
|
||||
deterministicArtifactCreateFailure(
|
||||
"create restored migration snapshot", err, inspectErr, !absent,
|
||||
),
|
||||
)
|
||||
}
|
||||
stream, err := l.conn.NewStream(libvirt.STREAM_NONBLOCK)
|
||||
if err != nil {
|
||||
return nil, createVMStorageCloneStage.wrap(l.rollbackUnpublishedVolume(
|
||||
pool, volume, volumeName, err,
|
||||
"roll back restored migration snapshot",
|
||||
))
|
||||
}
|
||||
transfer := &storageStreamTransfer{stream: stream}
|
||||
if err := volume.Upload(stream, 0, uint64(source.SourceSizeBytes), 0); err != nil {
|
||||
cause := transfer.abort(err)
|
||||
return nil, createVMStorageCloneStage.wrap(l.rollbackRestoreStreamFailure(
|
||||
pool, volume, volumeName, cause,
|
||||
"roll back restored migration snapshot",
|
||||
))
|
||||
}
|
||||
client := objecttransfer.New()
|
||||
defer client.CloseIdleConnections()
|
||||
download, downloadErr := client.Download(
|
||||
ctx, source.SourceURL, source.SourceSizeBytes, source.SourceSHA256,
|
||||
&storageStreamWriter{ctx: ctx, transfer: transfer},
|
||||
)
|
||||
if downloadErr != nil {
|
||||
cause := transfer.abort(translateObjectTransferError(downloadErr))
|
||||
return nil, createVMStorageCloneStage.wrap(l.rollbackRestoreStreamFailure(
|
||||
pool, volume, volumeName, cause,
|
||||
"roll back restored migration snapshot",
|
||||
))
|
||||
}
|
||||
if err := transfer.finish(ctx); err != nil {
|
||||
return nil, createVMStorageCloneStage.wrap(l.rollbackRestoreStreamFailure(
|
||||
pool, volume, volumeName, err,
|
||||
"roll back restored migration snapshot",
|
||||
))
|
||||
}
|
||||
if download.SizeBytes != source.SourceSizeBytes ||
|
||||
!strings.EqualFold(download.SHA256, source.SourceSHA256) {
|
||||
return nil, createVMStorageCloneStage.wrap(l.rollbackUnpublishedVolume(
|
||||
pool, volume, volumeName,
|
||||
NewError(ErrConflict, "backup_object_mismatch",
|
||||
"downloaded migration snapshot identity does not match", nil),
|
||||
"roll back restored migration snapshot",
|
||||
))
|
||||
}
|
||||
if err := pool.Refresh(0); err != nil {
|
||||
return nil, createVMStorageCloneStage.wrap(l.rollbackUnpublishedVolume(
|
||||
pool, volume, volumeName,
|
||||
translateLibvirtError("refresh restored migration snapshot", err),
|
||||
"roll back restored migration snapshot",
|
||||
))
|
||||
}
|
||||
if _, err := validateStandaloneQCOW2Volume(
|
||||
volume, source.VirtualSizeBytes,
|
||||
); err != nil {
|
||||
return nil, createVMStorageCloneStage.wrap(l.rollbackUnpublishedVolume(
|
||||
pool, volume, volumeName, err,
|
||||
"roll back restored migration snapshot",
|
||||
))
|
||||
}
|
||||
return volume, nil
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** One immutable local snapshot transported only by a maintenance migration. */
|
||||
final class CloudMigrationBundleArtifact extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_migration_bundle_artifacts';
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'migration_id' => 'int',
|
||||
'source_snapshot_id' => 'int',
|
||||
'object_size_bytes' => 'int',
|
||||
'virtual_size_bytes' => 'int',
|
||||
'snapshot_created_at' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,332 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudInstanceMigration;
|
||||
use App\Models\CloudInstanceSnapshot;
|
||||
use App\Models\CloudMigrationBundleArtifact;
|
||||
|
||||
/**
|
||||
* Snapshot transport owned exclusively by cold maintenance migration.
|
||||
*
|
||||
* Ordinary cloud backups stay a single portable root object. This module
|
||||
* freezes the complete ready snapshot catalog, creates one immutable object
|
||||
* per snapshot, validates Agent receipts, and rebinds the catalog only after
|
||||
* the target Agent has proved every restored volume and its offline domain.
|
||||
*/
|
||||
final class CloudMigrationBundleService
|
||||
{
|
||||
public const VERSION = 1;
|
||||
private const GIB = 1073741824;
|
||||
|
||||
/** @param array<int,CloudInstanceSnapshot> $snapshots */
|
||||
public static function additionalDiskGib(array $snapshots): int
|
||||
{
|
||||
$bytes = 0;
|
||||
foreach ($snapshots as $snapshot) {
|
||||
$bytes += max(0, (int) ($snapshot->size_bytes ?? 0));
|
||||
}
|
||||
return (int) ceil($bytes / self::GIB);
|
||||
}
|
||||
|
||||
/** Snapshot capacity frozen into one persisted migration bundle. */
|
||||
public static function artifactDiskGib(
|
||||
CloudInstanceMigration $migration
|
||||
): int {
|
||||
$bytes = (int) CloudMigrationBundleArtifact::where(
|
||||
'migration_id', (int) $migration->id
|
||||
)->sum('virtual_size_bytes');
|
||||
return (int) ceil(max(0, $bytes) / self::GIB);
|
||||
}
|
||||
|
||||
public static function advisoryAdditionalDiskGib(
|
||||
CloudInstance $instance
|
||||
): int {
|
||||
return self::additionalDiskGib(CloudInstanceSnapshot::where(
|
||||
'instance_id', (int) $instance->id
|
||||
)->where('host_id', (int) $instance->host_id)
|
||||
->where('user_id', (int) $instance->user_id)
|
||||
->where('state', 'ready')->get()->all());
|
||||
}
|
||||
|
||||
/** @return array<int,CloudInstanceSnapshot> */
|
||||
public static function freezeSnapshotsLocked(CloudInstance $instance): array
|
||||
{
|
||||
$rows = CloudInstanceSnapshot::where(
|
||||
'instance_id', (int) $instance->id
|
||||
)->where('user_id', (int) $instance->user_id)
|
||||
->whereIn('state', [
|
||||
'creating', 'ready', 'restoring', 'deleting', 'uncertain',
|
||||
])->orderBy('id')->lockForUpdate()->get()->all();
|
||||
if (count($rows) > CloudSnapshotService::MAX_PER_INSTANCE) {
|
||||
throw new CloudError('实例快照目录超过可迁移上限', 409);
|
||||
}
|
||||
foreach ($rows as $snapshot) {
|
||||
if ((string) $snapshot->state !== 'ready'
|
||||
|| (int) $snapshot->host_id !== (int) $instance->host_id
|
||||
|| (int) ($snapshot->size_bytes ?? 0) < 1
|
||||
|| preg_match('/^[a-f0-9]{32}$/D',
|
||||
(string) $snapshot->snapshot_key) !== 1) {
|
||||
throw new CloudError(
|
||||
'实例存在未就绪或宿主机不一致的快照,不能维护迁移',
|
||||
409
|
||||
);
|
||||
}
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,CloudInstanceSnapshot> $snapshots
|
||||
* @return array{body:array<int,array<string,mixed>>,prepared:array<int,array<string,mixed>>}
|
||||
*/
|
||||
public static function beginExportPlans(array $snapshots, array $runtime,
|
||||
string $prefix, string $bundleKey, int $maximumBytes): array
|
||||
{
|
||||
$client = new CloudObjectStorageS3Client();
|
||||
$body = [];
|
||||
$prepared = [];
|
||||
try {
|
||||
foreach ($snapshots as $snapshot) {
|
||||
$objectKey = ($prefix === '' ? '' : $prefix . '/')
|
||||
. 'vm-migrations/' . $bundleKey . '/snapshots/'
|
||||
. (string) $snapshot->snapshot_key . '.qcow2';
|
||||
$plan = $client->beginMultipartPlan(
|
||||
$runtime['config'], $runtime['credentials'], $objectKey,
|
||||
$maximumBytes, 604800
|
||||
);
|
||||
$prepared[] = [
|
||||
'snapshot' => $snapshot,
|
||||
'object_key' => $objectKey,
|
||||
'plan' => $plan,
|
||||
];
|
||||
$body[] = [
|
||||
'snapshot_key' => (string) $snapshot->snapshot_key,
|
||||
'object_upload' => self::publicTransferPlan($plan),
|
||||
];
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
self::abortPreparedPlans($runtime, $prepared);
|
||||
throw $error;
|
||||
}
|
||||
return ['body' => $body, 'prepared' => $prepared];
|
||||
}
|
||||
|
||||
/** @param array<int,array<string,mixed>> $prepared */
|
||||
public static function persistArtifactsLocked(
|
||||
CloudInstanceMigration $migration,
|
||||
array $prepared
|
||||
): void {
|
||||
$now = time();
|
||||
foreach ($prepared as $item) {
|
||||
$snapshot = $item['snapshot'] ?? null;
|
||||
if (!$snapshot instanceof CloudInstanceSnapshot) {
|
||||
throw new \LogicException('Invalid migration snapshot plan');
|
||||
}
|
||||
$artifact = new CloudMigrationBundleArtifact();
|
||||
$artifact->migration_id = (int) $migration->id;
|
||||
$artifact->source_snapshot_id = (int) $snapshot->id;
|
||||
$artifact->snapshot_key = (string) $snapshot->snapshot_key;
|
||||
$artifact->name = (string) $snapshot->name;
|
||||
$artifact->consistency = (string) $snapshot->consistency;
|
||||
$artifact->object_key = (string) $item['object_key'];
|
||||
$artifact->object_size_bytes = 0;
|
||||
$artifact->virtual_size_bytes = (int) $snapshot->size_bytes;
|
||||
$artifact->sha256 = '';
|
||||
$artifact->state = 'creating';
|
||||
$artifact->snapshot_created_at = (int) $snapshot->created_at;
|
||||
$artifact->created_at = $artifact->updated_at = $now;
|
||||
$artifact->save();
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate the complete Agent export receipt before target restore. */
|
||||
public static function finishExportLocked(
|
||||
CloudInstanceMigration $migration,
|
||||
array $result
|
||||
): void {
|
||||
if ((int) ($result['migration_bundle_version'] ?? 0)
|
||||
!== self::VERSION
|
||||
|| !is_array($result['snapshot_artifacts'] ?? null)) {
|
||||
throw new CloudError('Agent 未返回完整的迁移快照包', 502);
|
||||
}
|
||||
$artifacts = CloudMigrationBundleArtifact::where(
|
||||
'migration_id', (int) $migration->id
|
||||
)->orderBy('id')->lockForUpdate()->get();
|
||||
$received = [];
|
||||
foreach ($result['snapshot_artifacts'] as $item) {
|
||||
$key = is_array($item) ? ($item['snapshot_key'] ?? null) : null;
|
||||
if (!is_string($key) || isset($received[$key])) {
|
||||
throw new CloudError('Agent 迁移快照回执存在重复标识', 502);
|
||||
}
|
||||
$received[$key] = $item;
|
||||
}
|
||||
if (count($received) !== count($artifacts)) {
|
||||
throw new CloudError('Agent 迁移快照回执数量不一致', 502);
|
||||
}
|
||||
$now = time();
|
||||
foreach ($artifacts as $artifact) {
|
||||
$item = $received[(string) $artifact->snapshot_key] ?? null;
|
||||
$size = filter_var($item['size_bytes'] ?? null,
|
||||
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
$virtual = filter_var($item['virtual_size_bytes'] ?? null,
|
||||
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
$digest = $item['sha256'] ?? null;
|
||||
if (!is_array($item)
|
||||
|| !hash_equals((string) $artifact->name,
|
||||
(string) ($item['name'] ?? ''))
|
||||
|| !hash_equals((string) $artifact->consistency,
|
||||
(string) ($item['consistency'] ?? ''))
|
||||
|| $size === false || $virtual === false
|
||||
|| (int) $virtual !== (int) $artifact->virtual_size_bytes
|
||||
|| filter_var($item['created_at'] ?? null,
|
||||
FILTER_VALIDATE_INT,
|
||||
['options' => ['min_range' => 1]]) === false
|
||||
|| !is_string($digest)
|
||||
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1) {
|
||||
throw new CloudError('Agent 迁移快照回执与冻结目录不一致', 502);
|
||||
}
|
||||
$artifact->object_size_bytes = (int) $size;
|
||||
$artifact->sha256 = $digest;
|
||||
// The PHP row is created when the request is admitted, while the
|
||||
// Agent metadata records the later instant the volume was actually
|
||||
// frozen. Preserve the authoritative Agent timestamp inside the
|
||||
// transport bundle without weakening the immutable key/name/size
|
||||
// checks above.
|
||||
$artifact->snapshot_created_at = (int) $item['created_at'];
|
||||
$artifact->state = 'ready';
|
||||
$artifact->updated_at = $now;
|
||||
$artifact->save();
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<int,array<string,mixed>> */
|
||||
public static function restoreSources(CloudInstanceMigration $migration,
|
||||
array $runtime): array
|
||||
{
|
||||
$rows = CloudMigrationBundleArtifact::where(
|
||||
'migration_id', (int) $migration->id
|
||||
)->orderBy('id')->get();
|
||||
$client = new CloudObjectStorageS3Client();
|
||||
$sources = [];
|
||||
foreach ($rows as $artifact) {
|
||||
if ((string) $artifact->state !== 'ready'
|
||||
|| (int) $artifact->object_size_bytes < 1
|
||||
|| (int) $artifact->virtual_size_bytes < 1
|
||||
|| preg_match('/^[a-f0-9]{64}$/D',
|
||||
(string) $artifact->sha256) !== 1) {
|
||||
throw new CloudError('迁移快照包尚未就绪', 409);
|
||||
}
|
||||
$sources[] = [
|
||||
'snapshot_key' => (string) $artifact->snapshot_key,
|
||||
'name' => (string) $artifact->name,
|
||||
'consistency' => (string) $artifact->consistency,
|
||||
'virtual_size_bytes' => (int) $artifact->virtual_size_bytes,
|
||||
'source_url' => $client->presignedGet(
|
||||
$runtime['config'], $runtime['credentials'],
|
||||
(string) $artifact->object_key, 604800
|
||||
),
|
||||
'source_size_bytes' => (int) $artifact->object_size_bytes,
|
||||
'source_sha256' => (string) $artifact->sha256,
|
||||
'created_at' => (int) $artifact->snapshot_created_at,
|
||||
];
|
||||
}
|
||||
return $sources;
|
||||
}
|
||||
|
||||
/** Prove target artifact receipts and atomically move the PHP catalog. */
|
||||
public static function finishRestoreLocked(
|
||||
CloudInstanceMigration $migration,
|
||||
array $result
|
||||
): void {
|
||||
$vm = is_array($result['vm'] ?? null) ? $result['vm'] : $result;
|
||||
if (($result['staged_powered_off'] ?? null) !== true
|
||||
|| (int) ($result['migration_bundle_version'] ?? 0)
|
||||
!== self::VERSION
|
||||
|| !is_array($result['snapshot_artifacts'] ?? null)
|
||||
|| !is_array($vm)
|
||||
|| (string) ($vm['status'] ?? '') !== 'shutoff') {
|
||||
throw new CloudError('Agent 未确认迁移目标保持关机且快照完整', 502);
|
||||
}
|
||||
$received = [];
|
||||
foreach ($result['snapshot_artifacts'] as $item) {
|
||||
$key = is_array($item) ? ($item['snapshot_key'] ?? null) : null;
|
||||
if (!is_string($key) || isset($received[$key])) {
|
||||
throw new CloudError('Agent 目标快照回执存在重复标识', 502);
|
||||
}
|
||||
$received[$key] = $item;
|
||||
}
|
||||
$artifacts = CloudMigrationBundleArtifact::where(
|
||||
'migration_id', (int) $migration->id
|
||||
)->orderBy('id')->lockForUpdate()->get();
|
||||
if (count($received) !== count($artifacts)) {
|
||||
throw new CloudError('Agent 目标快照回执数量不一致', 502);
|
||||
}
|
||||
foreach ($artifacts as $artifact) {
|
||||
$item = $received[(string) $artifact->snapshot_key] ?? null;
|
||||
if (!is_array($item)
|
||||
|| !hash_equals((string) $artifact->sha256,
|
||||
(string) ($item['sha256'] ?? ''))
|
||||
|| (int) $artifact->object_size_bytes
|
||||
!== (int) ($item['size_bytes'] ?? -1)
|
||||
|| (int) $artifact->virtual_size_bytes
|
||||
!== (int) ($item['virtual_size_bytes'] ?? -1)
|
||||
|| (int) $artifact->snapshot_created_at
|
||||
!== (int) ($item['created_at'] ?? -1)) {
|
||||
throw new CloudError('Agent 目标快照与迁移包不一致', 502);
|
||||
}
|
||||
$snapshot = CloudInstanceSnapshot::where(
|
||||
'id', (int) $artifact->source_snapshot_id
|
||||
)->lockForUpdate()->first();
|
||||
if ($snapshot === null
|
||||
|| (int) $snapshot->instance_id !== (int) $migration->instance_id
|
||||
|| (int) $snapshot->host_id !== (int) $migration->source_host_id
|
||||
|| (string) $snapshot->state !== 'ready'
|
||||
|| !hash_equals((string) $artifact->snapshot_key,
|
||||
(string) $snapshot->snapshot_key)) {
|
||||
throw new CloudRecoveryInstanceStateConflict(
|
||||
'迁移期间实例快照目录已变化',
|
||||
409
|
||||
);
|
||||
}
|
||||
$snapshot->host_id = (int) $migration->target_host_id;
|
||||
$snapshot->updated_at = time();
|
||||
$snapshot->save();
|
||||
$artifact->state = 'restored';
|
||||
$artifact->updated_at = time();
|
||||
$artifact->save();
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<int,array<string,mixed>> $prepared */
|
||||
public static function abortPreparedPlans(array $runtime,
|
||||
array $prepared): void
|
||||
{
|
||||
$client = new CloudObjectStorageS3Client();
|
||||
foreach ($prepared as $item) {
|
||||
try {
|
||||
$client->abortMultipart(
|
||||
$runtime['config'], $runtime['credentials'],
|
||||
(string) ($item['object_key'] ?? ''),
|
||||
(string) ($item['plan']['upload_id'] ?? '')
|
||||
);
|
||||
} catch (\Throwable $error) {
|
||||
error_log('migration bundle multipart cleanup unavailable: '
|
||||
. get_class($error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function publicTransferPlan(array $plan): array
|
||||
{
|
||||
return [
|
||||
'part_size_bytes' => (int) $plan['part_size_bytes'],
|
||||
'maximum_size_bytes' => (int) $plan['maximum_size_bytes'],
|
||||
'part_urls' => array_values($plan['part_urls']),
|
||||
'complete_url' => (string) $plan['complete_url'],
|
||||
'abort_url' => (string) $plan['abort_url'],
|
||||
'verify_url' => (string) $plan['verify_url'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026102505' scope='global'}
|
||||
{assign var=venix_asset_version value='2026102506' scope='global'}
|
||||
|
||||
@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudInstanceMigration;
|
||||
use App\Models\CloudInstanceSnapshot;
|
||||
use App\Models\CloudMigrationBundleArtifact;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudMigrationBundleService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection([
|
||||
'driver' => 'sqlite', 'database' => ':memory:',
|
||||
], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('host_id');
|
||||
$table->integer('user_id');
|
||||
});
|
||||
$schema->create('cloud_instance_snapshots',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('snapshot_key')->unique();
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('host_id');
|
||||
$table->string('name');
|
||||
$table->string('state');
|
||||
$table->string('consistency');
|
||||
$table->integer('size_bytes')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_instance_migrations',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id');
|
||||
$table->integer('source_host_id');
|
||||
$table->integer('target_host_id');
|
||||
});
|
||||
$schema->create('cloud_migration_bundle_artifacts',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('migration_id');
|
||||
$table->integer('source_snapshot_id');
|
||||
$table->string('snapshot_key');
|
||||
$table->string('name');
|
||||
$table->string('consistency');
|
||||
$table->string('object_key');
|
||||
$table->integer('object_size_bytes')->default(0);
|
||||
$table->integer('virtual_size_bytes')->default(0);
|
||||
$table->string('sha256')->default('');
|
||||
$table->string('state');
|
||||
$table->integer('snapshot_created_at');
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
|
||||
$now = time();
|
||||
$instance = new CloudInstance();
|
||||
$instance->id = 10;
|
||||
$instance->host_id = 1;
|
||||
$instance->user_id = 90;
|
||||
$instance->save();
|
||||
$snapshots = [];
|
||||
foreach ([
|
||||
[11, str_repeat('a', 32), 'before-upgrade', 'filesystem', 20 * 1073741824],
|
||||
[12, str_repeat('b', 32), 'after-upgrade', 'crash', 30 * 1073741824],
|
||||
] as [$id, $key, $name, $consistency, $bytes]) {
|
||||
$snapshot = new CloudInstanceSnapshot();
|
||||
$snapshot->id = $id;
|
||||
$snapshot->snapshot_key = $key;
|
||||
$snapshot->instance_id = 10;
|
||||
$snapshot->user_id = 90;
|
||||
$snapshot->host_id = 1;
|
||||
$snapshot->name = $name;
|
||||
$snapshot->state = 'ready';
|
||||
$snapshot->consistency = $consistency;
|
||||
$snapshot->size_bytes = $bytes;
|
||||
$snapshot->created_at = $now - $id;
|
||||
$snapshot->updated_at = $now;
|
||||
$snapshot->save();
|
||||
$snapshots[] = $snapshot;
|
||||
}
|
||||
|
||||
$frozen = CloudMigrationBundleService::freezeSnapshotsLocked($instance);
|
||||
$assert(count($frozen) === 2
|
||||
&& CloudMigrationBundleService::additionalDiskGib($frozen) === 50,
|
||||
'MigrationBundle did not freeze and reserve every ready snapshot.');
|
||||
|
||||
$migration = new CloudInstanceMigration();
|
||||
$migration->id = 20;
|
||||
$migration->instance_id = 10;
|
||||
$migration->source_host_id = 1;
|
||||
$migration->target_host_id = 2;
|
||||
$migration->save();
|
||||
$prepared = [];
|
||||
foreach ($snapshots as $snapshot) {
|
||||
$prepared[] = [
|
||||
'snapshot' => $snapshot,
|
||||
'object_key' => 'virt/vm-migrations/bundle/snapshots/'
|
||||
. $snapshot->snapshot_key . '.qcow2',
|
||||
'plan' => ['upload_id' => 'upload-' . $snapshot->id],
|
||||
];
|
||||
}
|
||||
CloudMigrationBundleService::persistArtifactsLocked($migration, $prepared);
|
||||
|
||||
$receipts = [];
|
||||
foreach ($snapshots as $index => $snapshot) {
|
||||
$receipts[] = [
|
||||
'snapshot_key' => (string) $snapshot->snapshot_key,
|
||||
'name' => (string) $snapshot->name,
|
||||
'consistency' => (string) $snapshot->consistency,
|
||||
'size_bytes' => 1000 + $index,
|
||||
'virtual_size_bytes' => (int) $snapshot->size_bytes,
|
||||
'sha256' => str_repeat((string) ($index + 1), 64),
|
||||
'created_at' => (int) $snapshot->created_at - 30 - $index,
|
||||
];
|
||||
}
|
||||
CloudMigrationBundleService::finishExportLocked($migration, [
|
||||
'migration_bundle_version' => CloudMigrationBundleService::VERSION,
|
||||
'snapshot_artifacts' => $receipts,
|
||||
]);
|
||||
$assert(CloudMigrationBundleArtifact::where('migration_id', 20)
|
||||
->where('state', 'ready')->count() === 2
|
||||
&& (int) CloudMigrationBundleArtifact::where('migration_id', 20)
|
||||
->orderBy('id')->first()->snapshot_created_at
|
||||
=== (int) $receipts[0]['created_at'],
|
||||
'MigrationBundle did not seal every exported snapshot receipt.');
|
||||
|
||||
try {
|
||||
CloudMigrationBundleService::finishRestoreLocked($migration, [
|
||||
'status' => 'running',
|
||||
'staged_powered_off' => false,
|
||||
'migration_bundle_version' => CloudMigrationBundleService::VERSION,
|
||||
'snapshot_artifacts' => $receipts,
|
||||
]);
|
||||
throw new RuntimeException(
|
||||
'MigrationBundle accepted a target before powered-off staging was proven.'
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 502,
|
||||
'MigrationBundle rejected unsafe staging with the wrong status.');
|
||||
}
|
||||
$assert(CloudInstanceSnapshot::where('host_id', 1)->count() === 2,
|
||||
'Snapshot ownership moved before powered-off target staging was proven.');
|
||||
|
||||
CloudMigrationBundleService::finishRestoreLocked($migration, [
|
||||
'status' => 'shutoff',
|
||||
'staged_powered_off' => true,
|
||||
'migration_bundle_version' => CloudMigrationBundleService::VERSION,
|
||||
'snapshot_artifacts' => $receipts,
|
||||
]);
|
||||
$assert(CloudInstanceSnapshot::where('host_id', 2)->count() === 2
|
||||
&& CloudMigrationBundleArtifact::where('migration_id', 20)
|
||||
->where('state', 'restored')->count() === 2,
|
||||
'MigrationBundle did not atomically rebind the complete snapshot catalog.');
|
||||
|
||||
echo "Maintenance MigrationBundle snapshot transport behavior passed.\n";
|
||||
@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudPanelUsageService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection([
|
||||
'driver' => 'sqlite', 'database' => ':memory:',
|
||||
], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('host_id');
|
||||
$table->string('status');
|
||||
$table->text('spec_json');
|
||||
});
|
||||
$schema->create('cloud_resource_reservations',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('host_id');
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('cpu_cores');
|
||||
$table->integer('memory_mib');
|
||||
$table->integer('disk_gib');
|
||||
$table->string('state');
|
||||
});
|
||||
$schema->create('cloud_instance_snapshots',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id');
|
||||
$table->integer('host_id');
|
||||
$table->string('state');
|
||||
$table->integer('size_bytes')->nullable();
|
||||
});
|
||||
$schema->create('cloud_instance_migrations',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('source_host_id');
|
||||
$table->string('state');
|
||||
});
|
||||
$schema->create('cloud_migration_bundle_artifacts',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('migration_id');
|
||||
$table->integer('virtual_size_bytes');
|
||||
$table->string('state');
|
||||
});
|
||||
|
||||
$gib = 1073741824;
|
||||
$capsule->table('cloud_instances')->insert([
|
||||
'id' => 10,
|
||||
'host_id' => 1,
|
||||
'status' => 'active',
|
||||
'spec_json' => json_encode([
|
||||
'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
|
||||
], JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
$capsule->table('cloud_resource_reservations')->insert([
|
||||
[
|
||||
'id' => 1, 'host_id' => 1, 'instance_id' => 10,
|
||||
'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
|
||||
'state' => 'committed',
|
||||
],
|
||||
[
|
||||
'id' => 2, 'host_id' => 2, 'instance_id' => 10,
|
||||
'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 90,
|
||||
'state' => 'held',
|
||||
],
|
||||
]);
|
||||
$capsule->table('cloud_instance_snapshots')->insert([
|
||||
[
|
||||
'id' => 11, 'instance_id' => 10, 'host_id' => 1,
|
||||
'state' => 'ready', 'size_bytes' => 20 * $gib,
|
||||
],
|
||||
[
|
||||
'id' => 12, 'instance_id' => 10, 'host_id' => 1,
|
||||
'state' => 'ready', 'size_bytes' => 30 * $gib,
|
||||
],
|
||||
]);
|
||||
$capsule->table('cloud_instance_migrations')->insert([
|
||||
'id' => 20, 'source_host_id' => 1, 'state' => 'restoring',
|
||||
]);
|
||||
$capsule->table('cloud_migration_bundle_artifacts')->insert([
|
||||
[
|
||||
'id' => 21, 'migration_id' => 20,
|
||||
'virtual_size_bytes' => 20 * $gib, 'state' => 'ready',
|
||||
],
|
||||
[
|
||||
'id' => 22, 'migration_id' => 20,
|
||||
'virtual_size_bytes' => 30 * $gib, 'state' => 'ready',
|
||||
],
|
||||
]);
|
||||
|
||||
$source = CloudPanelUsageService::forHost(1);
|
||||
$target = CloudPanelUsageService::forHost(2);
|
||||
$assert($source['disk_sum'] === 90,
|
||||
'Source capacity did not include its ready snapshot volumes.');
|
||||
$assert($target['disk_sum'] === 90,
|
||||
'Target capacity did not retain the complete MigrationBundle claim.');
|
||||
|
||||
// After target staging, the logical snapshot catalog moves to the target and
|
||||
// the temporary target reservation returns to the root-disk size. The source
|
||||
// copies still exist until their cleanup has been proven, so the source
|
||||
// reservation temporarily retains the transported snapshot capacity.
|
||||
$capsule->table('cloud_instance_snapshots')->update(['host_id' => 2]);
|
||||
$capsule->table('cloud_migration_bundle_artifacts')
|
||||
->update(['state' => 'restored']);
|
||||
$capsule->table('cloud_instance_migrations')
|
||||
->update(['state' => 'cutover']);
|
||||
$capsule->table('cloud_resource_reservations')->where('id', 2)
|
||||
->update(['disk_gib' => 40, 'state' => 'committed']);
|
||||
$capsule->table('cloud_resource_reservations')->where('id', 1)
|
||||
->update(['disk_gib' => 90]);
|
||||
$capsule->table('cloud_instances')->where('id', 10)
|
||||
->update(['host_id' => 2]);
|
||||
|
||||
$source = CloudPanelUsageService::forHost(1);
|
||||
$target = CloudPanelUsageService::forHost(2);
|
||||
$assert($source['disk_sum'] === 90,
|
||||
'Source capacity was released before duplicate snapshot cleanup.');
|
||||
$assert($target['disk_sum'] === 90,
|
||||
'Target snapshot volumes were double-counted or omitted after cutover.');
|
||||
|
||||
$capsule->table('cloud_instance_migrations')
|
||||
->update(['state' => 'completed']);
|
||||
$capsule->table('cloud_resource_reservations')->where('id', 1)
|
||||
->update(['state' => 'released']);
|
||||
$source = CloudPanelUsageService::forHost(1);
|
||||
$assert($source['disk_sum'] === 0,
|
||||
'Source snapshot capacity remained reserved after proven cleanup.');
|
||||
|
||||
echo "Maintenance MigrationBundle capacity accounting passed.\n";
|
||||
Loading…
Reference in New Issue