feat(cloud): add paid automatic backups
parent
1ea91bd9f3
commit
ece7e24b52
@ -0,0 +1,279 @@
|
||||
//go:build libvirt
|
||||
|
||||
package hypervisor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.luoli.live/root/virt/agent/objecttransfer"
|
||||
"git.luoli.live/root/virt/agent/operation"
|
||||
"libvirt.org/go/libvirt"
|
||||
"libvirt.org/go/libvirtxml"
|
||||
)
|
||||
|
||||
// RecoverBackup replaces only the managed root disk of an existing domain.
|
||||
// The UUID, domain definition, NoCloud seed, public IP, firewall and service
|
||||
// identity remain untouched. The disk transition follows the same
|
||||
// fail-closed two-root protocol as snapshot restore.
|
||||
func (l *Libvirt) RecoverBackup(ctx context.Context, uuid string,
|
||||
request RecoverBackupRequest) (_ RecoverBackupResult, resultErr error) {
|
||||
mutationStarted := false
|
||||
defer func() {
|
||||
if !mutationStarted {
|
||||
resultErr = operation.MarkNotApplied(resultErr)
|
||||
}
|
||||
}()
|
||||
if err := ValidateRecoverBackupRequest(request); err != nil {
|
||||
return RecoverBackupResult{}, err
|
||||
}
|
||||
domain, err := l.domainByUUID(ctx, uuid)
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, err
|
||||
}
|
||||
defer domain.Free()
|
||||
originalXML, _, metadata, pool, oldRoot, err := l.managedRootContext(domain)
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, err
|
||||
}
|
||||
defer pool.Free()
|
||||
defer oldRoot.Free()
|
||||
if metadata.PendingCleanupVolume != "" {
|
||||
return RecoverBackupResult{}, NewError(ErrConflict,
|
||||
"backup_disk_transition_active",
|
||||
"VM backup recovery is unavailable during a disk transition", nil)
|
||||
}
|
||||
if metadata.RescueTemplateID != "" {
|
||||
return RecoverBackupResult{}, NewError(ErrConflict,
|
||||
"backup_recovery_rescue_active",
|
||||
"VM backup recovery is unavailable while rescue is staged or active", nil)
|
||||
}
|
||||
autostart, err := domain.GetAutostart()
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, translateLibvirtError(
|
||||
"read backup recovery domain autostart", err)
|
||||
}
|
||||
oldInfo, err := validateStandaloneQCOW2Volume(oldRoot, 0)
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, err
|
||||
}
|
||||
replacementName := snapshotRestoreVolumeName(uuid, request.OperationID)
|
||||
if existing, lookupErr := l.lookupOptionalManagedVolume(
|
||||
l.storagePoolName(StorageRoleManaged), replacementName,
|
||||
); lookupErr != nil {
|
||||
return RecoverBackupResult{}, lookupErr
|
||||
} else if existing != nil {
|
||||
existing.Free()
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(NewError(
|
||||
ErrConflict, "backup_recovery_volume_exists",
|
||||
"deterministic backup recovery volume already exists", nil))
|
||||
}
|
||||
mutationStarted = true
|
||||
replacement, err := l.createBackupRecoveryVolume(
|
||||
ctx, pool, replacementName, oldInfo.Capacity, request,
|
||||
)
|
||||
if err != nil {
|
||||
if !operation.IsUncertain(err) {
|
||||
err = operation.MarkNotApplied(err)
|
||||
}
|
||||
return RecoverBackupResult{}, err
|
||||
}
|
||||
defer replacement.Free()
|
||||
replacementPath, err := replacement.GetPath()
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(
|
||||
translateLibvirtError("resolve backup recovery volume path", err))
|
||||
}
|
||||
wasRunning, err := stopForDefinitionChange(ctx, domain)
|
||||
if err != nil {
|
||||
if cleanupErr := replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL); cleanupErr != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(errors.Join(
|
||||
err, mutationLibvirtError("roll back backup recovery volume", cleanupErr)))
|
||||
}
|
||||
return RecoverBackupResult{}, operation.MarkNotApplied(err)
|
||||
}
|
||||
updatedXML, err := mutateDomainDocument(originalXML,
|
||||
func(definition *libvirtxml.Domain, stored *domainMetadataXML) error {
|
||||
root, rootErr := managedRootDisk(definition)
|
||||
if rootErr != nil {
|
||||
return rootErr
|
||||
}
|
||||
root.Source = &libvirtxml.DomainDiskSource{File: &libvirtxml.DomainDiskSourceFile{File: replacementPath}}
|
||||
stored.PendingCleanupVolume = stored.RootVolumeName
|
||||
stored.RootVolumeName = replacementName
|
||||
stored.DiskTransitionKind = "backup_recover"
|
||||
stored.DiskTransitionID = request.OperationID
|
||||
stored.DiskTransitionRunning = wasRunning
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
restartErr := restartOriginalDomain(domain, wasRunning)
|
||||
cleanupErr := replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
|
||||
if restartErr != nil || cleanupErr != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(errors.Join(
|
||||
err, restartErr,
|
||||
optionalMutationLibvirtError("roll back backup recovery volume", cleanupErr)))
|
||||
}
|
||||
return RecoverBackupResult{}, operation.MarkNotApplied(err)
|
||||
}
|
||||
defined, err := l.conn.DomainDefineXML(updatedXML)
|
||||
if err != nil {
|
||||
_, observed, inspectErr := requireManagedDomain(domain)
|
||||
if inspectErr != nil || observed.RootVolumeName != metadata.RootVolumeName {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(errors.Join(
|
||||
mutationLibvirtError("switch backup recovery system disk", err), inspectErr))
|
||||
}
|
||||
restartErr := restartOriginalDomain(domain, wasRunning)
|
||||
cleanupErr := replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
|
||||
if restartErr != nil || cleanupErr != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(errors.Join(
|
||||
mutationLibvirtError("switch backup recovery system disk", err),
|
||||
restartErr,
|
||||
optionalMutationLibvirtError("roll back backup recovery volume", cleanupErr)))
|
||||
}
|
||||
return RecoverBackupResult{}, operation.MarkNotApplied(
|
||||
mutationLibvirtError("switch backup recovery system disk", err))
|
||||
}
|
||||
defer defined.Free()
|
||||
if err := defined.SetAutostart(autostart); err != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(
|
||||
mutationLibvirtError("preserve backup recovery autostart", err))
|
||||
}
|
||||
if wasRunning {
|
||||
if err := defined.Create(); err != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(
|
||||
mutationLibvirtError("start recovered domain", err))
|
||||
}
|
||||
}
|
||||
observedXML, observed, err := requireManagedDomain(defined)
|
||||
if err != nil || observed.RootVolumeName != replacementName ||
|
||||
observed.DiskTransitionKind != "backup_recover" ||
|
||||
observed.DiskTransitionID != request.OperationID {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(errors.Join(
|
||||
NewError(ErrConflict, "backup_recovery_observation_failed",
|
||||
"recovered domain did not expose the committed disk transition", nil), err))
|
||||
}
|
||||
oldPath, err := oldRoot.GetPath()
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(
|
||||
translateLibvirtError("resolve previous backup recovery root", err))
|
||||
}
|
||||
used, err := l.anyDomainUsesVolume(
|
||||
oldPath, l.storagePoolName(StorageRoleManaged), metadata.RootVolumeName,
|
||||
)
|
||||
if err != nil || used {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(errors.Join(err,
|
||||
NewError(ErrConflict, "backup_recovery_cleanup_pending",
|
||||
"backup recovery committed but the previous root is still referenced", nil)))
|
||||
}
|
||||
if err := oldRoot.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL); err != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(NewError(
|
||||
ErrUnavailable, "backup_recovery_cleanup_pending",
|
||||
"backup recovery committed but previous root cleanup failed", err))
|
||||
}
|
||||
cleanXML, err := mutateManagedMetadata(observedXML,
|
||||
func(stored *domainMetadataXML) error {
|
||||
stored.PendingCleanupVolume = ""
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(err)
|
||||
}
|
||||
cleaned, err := l.conn.DomainDefineXML(cleanXML)
|
||||
if err != nil {
|
||||
return RecoverBackupResult{}, operation.MarkUncertain(
|
||||
mutationLibvirtError("clear backup recovery transition metadata", err))
|
||||
}
|
||||
cleaned.Free()
|
||||
state := VMStateShutoff
|
||||
if wasRunning {
|
||||
state = VMStateRunning
|
||||
}
|
||||
return RecoverBackupResult{
|
||||
BackupKey: request.BackupKey, SHA256: request.SourceSHA256,
|
||||
Restored: true, PowerState: state, ActiveVolumeName: replacementName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *Libvirt) createBackupRecoveryVolume(ctx context.Context,
|
||||
pool *libvirt.StoragePool, name string, capacity uint64,
|
||||
request RecoverBackupRequest) (*libvirt.StorageVol, error) {
|
||||
initialCapacity := capacity
|
||||
if objectBytes := uint64(request.SourceSizeBytes); objectBytes > initialCapacity {
|
||||
initialCapacity = objectBytes
|
||||
}
|
||||
definition := libvirtxml.StorageVolume{
|
||||
Name: name,
|
||||
Capacity: &libvirtxml.StorageVolumeSize{
|
||||
Value: initialCapacity, Unit: "bytes"},
|
||||
Target: &libvirtxml.StorageVolumeTarget{Format: &libvirtxml.StorageVolumeTargetFormat{Type: "qcow2"}},
|
||||
}
|
||||
document, err := definition.Marshal()
|
||||
if err != nil {
|
||||
return nil, operation.MarkNotApplied(err)
|
||||
}
|
||||
volume, err := pool.StorageVolCreateXML(document, 0)
|
||||
if err != nil {
|
||||
absent, inspectErr := l.dirPoolVolumeAbsent(pool, name)
|
||||
return nil, deterministicArtifactCreateFailure(
|
||||
"create backup recovery system disk", err, inspectErr, !absent)
|
||||
}
|
||||
rollback := func(cause error) (*libvirt.StorageVol, error) {
|
||||
rolledBack := l.rollbackUnpublishedVolume(
|
||||
pool, volume, name, cause, "roll back backup recovery system disk")
|
||||
if operation.IsUncertain(rolledBack) {
|
||||
return nil, rolledBack
|
||||
}
|
||||
return nil, operation.MarkNotApplied(rolledBack)
|
||||
}
|
||||
stream, err := l.conn.NewStream(libvirt.STREAM_NONBLOCK)
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
transfer := &storageStreamTransfer{stream: stream}
|
||||
if err := volume.Upload(stream, 0, uint64(request.SourceSizeBytes), 0); err != nil {
|
||||
return rollback(transfer.abort(err))
|
||||
}
|
||||
client := objecttransfer.New()
|
||||
defer client.CloseIdleConnections()
|
||||
download, downloadErr := client.Download(
|
||||
ctx, request.SourceURL, request.SourceSizeBytes, request.SourceSHA256,
|
||||
&storageStreamWriter{ctx: ctx, transfer: transfer},
|
||||
)
|
||||
if downloadErr != nil {
|
||||
cause := transfer.abort(translateObjectTransferError(downloadErr))
|
||||
if !restoreStreamFailureAllowsVolumeRollback(cause) {
|
||||
_ = volume.Free()
|
||||
return nil, cause
|
||||
}
|
||||
return rollback(cause)
|
||||
}
|
||||
if err := transfer.finish(ctx); err != nil {
|
||||
if !restoreStreamFailureAllowsVolumeRollback(err) {
|
||||
_ = volume.Free()
|
||||
return nil, err
|
||||
}
|
||||
return rollback(err)
|
||||
}
|
||||
if download.SizeBytes != request.SourceSizeBytes ||
|
||||
download.SHA256 != request.SourceSHA256 {
|
||||
return rollback(NewError(ErrConflict, "backup_object_mismatch",
|
||||
"downloaded backup object identity does not match", nil))
|
||||
}
|
||||
if err := pool.Refresh(0); err != nil {
|
||||
return rollback(translateLibvirtError(
|
||||
"refresh backup recovery system disk", err))
|
||||
}
|
||||
info, err := validateStandaloneQCOW2Volume(volume, 0)
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if info.Capacity > capacity {
|
||||
return rollback(NewError(ErrInvalid, "disk_smaller_than_backup",
|
||||
"existing system disk is smaller than the backup system disk", nil))
|
||||
}
|
||||
if err := establishNewRootVolumeCapacity(volume, capacity); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
return volume, nil
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** A destructive in-place system-disk recovery from one portable backup. */
|
||||
final class CloudBackupRecovery extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_backup_recoveries';
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'backup_id' => 'int',
|
||||
'instance_id' => 'int',
|
||||
'job_id' => 'int',
|
||||
'completed_at' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** One paid automatic-backup policy bound to one business instance. */
|
||||
final class CloudBackupSubscription extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_backup_subscriptions';
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'instance_id' => 'int',
|
||||
'user_id' => 'int',
|
||||
'offer_id' => 'int',
|
||||
'enabled' => 'bool',
|
||||
'renew_next_period' => 'bool',
|
||||
'weekday' => 'int',
|
||||
'retention_count' => 'int',
|
||||
'price_version' => 'int',
|
||||
'next_run_at' => 'int',
|
||||
'last_scheduled_at' => 'int',
|
||||
'last_backup_id' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
final class CloudInvoiceItem extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_invoice_items';
|
||||
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'invoice_id' => 'int',
|
||||
'order_item_id' => 'int',
|
||||
'amount' => 'decimal:2',
|
||||
'created_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
final class CloudOrderItem extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_order_items';
|
||||
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'order_id' => 'int',
|
||||
'amount' => 'decimal:2',
|
||||
'created_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,556 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudBackupSubscription;
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudInstanceBackup;
|
||||
use App\Models\CloudJob;
|
||||
use App\Models\CloudOffer;
|
||||
|
||||
/** Owner-facing paid automatic-backup policy and bounded scheduler. */
|
||||
final class CloudAutomaticBackupService
|
||||
{
|
||||
public const TIMEZONE = 'America/Los_Angeles';
|
||||
public const RUN_AT = '00:00';
|
||||
public const MAX_RETENTION = 2;
|
||||
|
||||
private const RETRY_SECONDS = 300;
|
||||
|
||||
public static function activatePurchased(CloudInstance $instance): ?CloudBackupSubscription
|
||||
{
|
||||
$spec = self::spec($instance);
|
||||
if (($spec['automatic_backup'] ?? null) !== true) {
|
||||
return null;
|
||||
}
|
||||
$price = self::moneySnapshot($spec['backup_price'] ?? null);
|
||||
// Validate the complete commercial snapshot. This deliberately does
|
||||
// not infer legacy aliases or the offer's current mutable price.
|
||||
self::moneySnapshot($spec['instance_price'] ?? null);
|
||||
$version = filter_var($spec['price_version'] ?? null,
|
||||
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
$currency = strtoupper((string) ($spec['currency'] ?? ''));
|
||||
if ($version === false || $currency !== 'USD'
|
||||
|| (int) $instance->offer_id < 1) {
|
||||
throw new CloudError('实例缺少可信的自动备份计费快照', 409);
|
||||
}
|
||||
|
||||
return $instance->getConnection()->transaction(function () use (
|
||||
$instance, $price, $version, $currency
|
||||
): CloudBackupSubscription {
|
||||
$locked = CloudInstance::where('id', (int) $instance->id)
|
||||
->lockForUpdate()->first();
|
||||
if ($locked === null || (string) $locked->status === 'deleted'
|
||||
|| (int) $locked->user_id !== (int) $instance->user_id) {
|
||||
throw new CloudError('虚拟机不存在', 404);
|
||||
}
|
||||
$subscription = CloudBackupSubscription::where(
|
||||
'instance_id', (int) $locked->id
|
||||
)->lockForUpdate()->first();
|
||||
if ($subscription !== null) {
|
||||
if ((int) $subscription->user_id !== (int) $locked->user_id
|
||||
|| (int) $subscription->offer_id !== (int) $locked->offer_id
|
||||
|| CloudMoney::cents((string) $subscription->price)
|
||||
!== CloudMoney::cents($price)
|
||||
|| strtoupper((string) $subscription->currency)
|
||||
!== $currency
|
||||
|| (int) $subscription->price_version !== (int) $version) {
|
||||
throw new CloudError('自动备份订阅与实例计费账本不一致', 409);
|
||||
}
|
||||
return $subscription;
|
||||
}
|
||||
$now = time();
|
||||
$subscription = new CloudBackupSubscription();
|
||||
$subscription->instance_id = (int) $locked->id;
|
||||
$subscription->user_id = (int) $locked->user_id;
|
||||
$subscription->offer_id = (int) $locked->offer_id;
|
||||
$subscription->enabled = true;
|
||||
$subscription->renew_next_period = true;
|
||||
$subscription->frequency = 'daily';
|
||||
$subscription->weekday = 0;
|
||||
$subscription->retention_count = self::MAX_RETENTION;
|
||||
$subscription->timezone = self::TIMEZONE;
|
||||
$subscription->price = $price;
|
||||
$subscription->currency = $currency;
|
||||
$subscription->price_version = (int) $version;
|
||||
$subscription->next_run_at = self::nextRunAt(
|
||||
$now, 'daily', 0
|
||||
);
|
||||
$subscription->last_scheduled_at = null;
|
||||
$subscription->last_backup_id = null;
|
||||
$subscription->created_at = $subscription->updated_at = $now;
|
||||
$subscription->save();
|
||||
return $subscription;
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public static function settings(CloudInstance $instance, array $actor): array
|
||||
{
|
||||
self::assertOwner($instance, $actor);
|
||||
$entitled = self::entitled($instance);
|
||||
$subscription = CloudBackupSubscription::where(
|
||||
'instance_id', (int) $instance->id
|
||||
)->first();
|
||||
if (!$entitled && $subscription !== null) {
|
||||
throw new CloudError('自动备份订阅与实例计费快照不一致', 409);
|
||||
}
|
||||
if ($entitled && $subscription === null) {
|
||||
throw new CloudError('自动备份订阅尚未激活,请联系管理员', 409);
|
||||
}
|
||||
return [
|
||||
'instance_id' => (string) $instance->id,
|
||||
'entitled' => $entitled,
|
||||
'subscription' => $subscription === null ? null
|
||||
: self::displaySubscription($subscription),
|
||||
'timezone' => self::TIMEZONE,
|
||||
'run_at' => self::RUN_AT,
|
||||
'max_retention' => self::MAX_RETENTION,
|
||||
'backups' => self::backupsForInstance($instance),
|
||||
];
|
||||
}
|
||||
|
||||
/** Keep the next-cycle backup fee aligned with a completed plan upgrade. */
|
||||
public static function refreshPriceAfterUpgradeLocked(
|
||||
CloudInstance $instance,
|
||||
CloudOffer $offer
|
||||
): void {
|
||||
$spec = self::spec($instance);
|
||||
if (($spec['automatic_backup'] ?? null) !== true) {
|
||||
return;
|
||||
}
|
||||
$subscription = CloudBackupSubscription::where(
|
||||
'instance_id', (int) $instance->id
|
||||
)->lockForUpdate()->first();
|
||||
if ($subscription === null
|
||||
|| (int) $offer->id !== (int) $instance->offer_id
|
||||
|| (int) $subscription->user_id !== (int) $instance->user_id
|
||||
|| strtoupper((string) $offer->currency) !== 'USD') {
|
||||
throw new CloudError('升级后的自动备份价格账本不一致', 409);
|
||||
}
|
||||
$price = self::moneySnapshot($offer->backup_price);
|
||||
if (!hash_equals($price, (string) ($spec['backup_price'] ?? ''))) {
|
||||
throw new CloudError('升级后的自动备份价格快照不一致', 409);
|
||||
}
|
||||
$subscription->offer_id = (int) $offer->id;
|
||||
$subscription->price = $price;
|
||||
$subscription->price_version = (int) $offer->price_version;
|
||||
$subscription->updated_at = time();
|
||||
$subscription->save();
|
||||
}
|
||||
|
||||
public static function update(CloudInstance $instance, array $actor,
|
||||
array $input): array
|
||||
{
|
||||
self::assertOwner($instance, $actor);
|
||||
if (!self::entitled($instance)) {
|
||||
throw new CloudError('该实例未购买自动备份', 409);
|
||||
}
|
||||
CloudInput::only($input, [
|
||||
'frequency', 'weekday', 'retention_count',
|
||||
]);
|
||||
$frequency = $input['frequency'] ?? null;
|
||||
if (!is_string($frequency)
|
||||
|| !in_array($frequency, ['daily', 'weekly'], true)) {
|
||||
throw new CloudError('备份频率仅支持每天或每周');
|
||||
}
|
||||
$retention = filter_var($input['retention_count'] ?? null,
|
||||
FILTER_VALIDATE_INT);
|
||||
if ($retention === false || !in_array((int) $retention, [1, 2], true)) {
|
||||
throw new CloudError('自动备份最多可保留两份');
|
||||
}
|
||||
$weekday = $input['weekday'] ?? 0;
|
||||
if ($frequency === 'weekly') {
|
||||
$weekday = filter_var($weekday, FILTER_VALIDATE_INT);
|
||||
if ($weekday === false || (int) $weekday < 0
|
||||
|| (int) $weekday > 6) {
|
||||
throw new CloudError('每周备份日必须为 0 至 6');
|
||||
}
|
||||
} elseif (array_key_exists('weekday', $input)) {
|
||||
$weekday = filter_var($weekday, FILTER_VALIDATE_INT);
|
||||
if ($weekday === false || (int) $weekday < 0
|
||||
|| (int) $weekday > 6) {
|
||||
throw new CloudError('备份日必须为 0 至 6');
|
||||
}
|
||||
}
|
||||
|
||||
$subscription = $instance->getConnection()->transaction(
|
||||
function () use (
|
||||
$instance, $frequency, $weekday, $retention
|
||||
): CloudBackupSubscription {
|
||||
$locked = CloudBackupSubscription::where(
|
||||
'instance_id', (int) $instance->id
|
||||
)->lockForUpdate()->first();
|
||||
if ($locked === null
|
||||
|| (int) $locked->user_id !== (int) $instance->user_id) {
|
||||
throw new CloudError('自动备份订阅尚未激活,请联系管理员', 409);
|
||||
}
|
||||
$changedSchedule = (string) $locked->frequency !== $frequency
|
||||
|| (int) $locked->weekday !== (int) $weekday;
|
||||
$locked->frequency = $frequency;
|
||||
$locked->weekday = (int) $weekday;
|
||||
$locked->retention_count = (int) $retention;
|
||||
$locked->timezone = self::TIMEZONE;
|
||||
if ($changedSchedule) {
|
||||
$locked->next_run_at = self::nextRunAt(
|
||||
time(), $frequency, (int) $weekday
|
||||
);
|
||||
}
|
||||
$locked->updated_at = time();
|
||||
$locked->save();
|
||||
return $locked;
|
||||
}, 3
|
||||
);
|
||||
|
||||
return [
|
||||
'instance_id' => (string) $instance->id,
|
||||
'entitled' => true,
|
||||
'subscription' => self::displaySubscription($subscription),
|
||||
'timezone' => self::TIMEZONE,
|
||||
'run_at' => self::RUN_AT,
|
||||
'max_retention' => self::MAX_RETENTION,
|
||||
'backups' => self::backupsForInstance($instance),
|
||||
];
|
||||
}
|
||||
|
||||
public static function library(array $actor, array $input): array
|
||||
{
|
||||
CloudInput::only($input, ['page', 'per_page']);
|
||||
$userId = (int) ($actor['user_id'] ?? 0);
|
||||
if ($userId < 1) {
|
||||
throw new CloudError('请先登录', 401);
|
||||
}
|
||||
$page = self::positiveInteger($input['page'] ?? 1, 1, 1000000);
|
||||
$perPage = self::positiveInteger($input['per_page'] ?? 20, 1, 50);
|
||||
if (!in_array($perPage, [20, 50], true)) {
|
||||
throw new CloudError('备份库每页条数仅支持 20 或 50');
|
||||
}
|
||||
$query = CloudInstanceBackup::where('user_id', $userId)
|
||||
->where('purpose', 'portable')->where('source', 'automatic')
|
||||
->where('state', '<>', 'deleted');
|
||||
$total = (int) (clone $query)->count('id');
|
||||
$pages = max(1, (int) ceil($total / $perPage));
|
||||
$page = min($page, $pages);
|
||||
$rows = $query->orderByDesc('id')
|
||||
->offset(($page - 1) * $perPage)->limit($perPage)->get();
|
||||
$instances = [];
|
||||
$ids = array_values(array_unique(array_map(
|
||||
static fn (CloudInstanceBackup $backup): int =>
|
||||
(int) $backup->source_instance_id,
|
||||
$rows->all()
|
||||
)));
|
||||
if ($ids !== []) {
|
||||
foreach (CloudInstance::whereIn('id', $ids)
|
||||
->get(['id', 'name', 'status']) as $instance) {
|
||||
$instances[(int) $instance->id] = $instance;
|
||||
}
|
||||
}
|
||||
$items = [];
|
||||
foreach ($rows as $backup) {
|
||||
$items[] = self::displayBackup(
|
||||
$backup,
|
||||
$instances[(int) $backup->source_instance_id] ?? null
|
||||
);
|
||||
}
|
||||
$from = $total === 0 ? 0 : (($page - 1) * $perPage) + 1;
|
||||
return [
|
||||
'items' => $items,
|
||||
'pagination' => [
|
||||
'page' => $page,
|
||||
'per_page' => $perPage,
|
||||
'total' => $total,
|
||||
'total_pages' => $pages,
|
||||
'from' => $from,
|
||||
'to' => $from === 0 ? 0 : $from + count($items) - 1,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** Queue at most $limit due backups; one bad subscription cannot starve later rows. */
|
||||
public static function scheduleDue(int $limit = 10): int
|
||||
{
|
||||
$limit = max(1, min(50, $limit));
|
||||
$now = time();
|
||||
$ids = CloudBackupSubscription::where('enabled', 1)
|
||||
->where('next_run_at', '<=', $now)->orderBy('next_run_at')
|
||||
->orderBy('id')->limit($limit)->pluck('id')->all();
|
||||
$queued = 0;
|
||||
foreach ($ids as $id) {
|
||||
try {
|
||||
if (self::scheduleOne((int) $id, $now)) {
|
||||
$queued++;
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
CloudBackupSubscription::where('id', (int) $id)
|
||||
->where('enabled', 1)
|
||||
->where('next_run_at', '<=', $now)
|
||||
->update([
|
||||
'next_run_at' => $now + self::RETRY_SECONDS,
|
||||
'updated_at' => time(),
|
||||
]);
|
||||
error_log('cloud automatic backup schedule unavailable: '
|
||||
. get_class($error));
|
||||
}
|
||||
}
|
||||
return $queued;
|
||||
}
|
||||
|
||||
/** Delete at most $limit oldest ready objects beyond each subscription's cap. */
|
||||
public static function pruneRetention(int $limit = 10): int
|
||||
{
|
||||
$limit = max(1, min(50, $limit));
|
||||
$actorFor = static fn (int $userId): array => [
|
||||
'user_id' => $userId,
|
||||
'is_admin' => true,
|
||||
'is_super_admin' => true,
|
||||
'can_manage' => true,
|
||||
'session_id' => 'automatic-backup-retention',
|
||||
];
|
||||
$processed = 0;
|
||||
$removed = 0;
|
||||
// Ambiguous object deletion is reconciled by HEAD only. Keep it in a
|
||||
// bounded system path; otherwise it drops out of the ready-count
|
||||
// query and can never converge after the first uncertain DELETE.
|
||||
$pending = CloudInstanceBackup::where('source', 'automatic')
|
||||
->where('purpose', 'portable')
|
||||
->whereIn('state', ['deleting', 'delete_uncertain'])
|
||||
->orderBy('id')->limit($limit)->get();
|
||||
foreach ($pending as $backup) {
|
||||
try {
|
||||
$result = CloudBackupService::delete(
|
||||
$backup, $actorFor((int) $backup->user_id)
|
||||
);
|
||||
if (($result['deleted'] ?? false) === true) {
|
||||
$removed++;
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
error_log('cloud automatic backup retention unavailable: '
|
||||
. get_class($error));
|
||||
}
|
||||
$processed++;
|
||||
}
|
||||
if ($processed >= $limit) {
|
||||
return $removed;
|
||||
}
|
||||
$subscriptions = CloudBackupSubscription::whereRaw(
|
||||
'(SELECT COUNT(*) FROM cloud_instance_backups '
|
||||
. 'WHERE cloud_instance_backups.subscription_id = '
|
||||
. 'cloud_backup_subscriptions.id '
|
||||
. "AND cloud_instance_backups.source = 'automatic' "
|
||||
. "AND cloud_instance_backups.purpose = 'portable' "
|
||||
. "AND cloud_instance_backups.state = 'ready') "
|
||||
. '> cloud_backup_subscriptions.retention_count'
|
||||
)->orderBy('id')->limit($limit - $processed)->get();
|
||||
foreach ($subscriptions as $subscription) {
|
||||
if ($processed >= $limit) {
|
||||
break;
|
||||
}
|
||||
$ready = CloudInstanceBackup::where(
|
||||
'subscription_id', (int) $subscription->id
|
||||
)->where('source', 'automatic')->where('purpose', 'portable')
|
||||
->where('state', 'ready')->orderBy('scheduled_for')
|
||||
->orderBy('id')->get();
|
||||
$excess = max(0, $ready->count()
|
||||
- min(self::MAX_RETENTION,
|
||||
max(1, (int) $subscription->retention_count)));
|
||||
foreach ($ready->take($excess) as $backup) {
|
||||
if ($processed >= $limit) {
|
||||
break 2;
|
||||
}
|
||||
try {
|
||||
$result = CloudBackupService::delete(
|
||||
$backup,
|
||||
$actorFor((int) $subscription->user_id)
|
||||
);
|
||||
if (($result['deleted'] ?? false) === true) {
|
||||
$removed++;
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
error_log('cloud automatic backup retention unavailable: '
|
||||
. get_class($error));
|
||||
}
|
||||
$processed++;
|
||||
}
|
||||
}
|
||||
return $removed;
|
||||
}
|
||||
|
||||
/** First Pacific midnight strictly after $after. Weekday uses PHP w: 0=Sunday. */
|
||||
public static function nextRunAt(int $after, string $frequency,
|
||||
int $weekday): int
|
||||
{
|
||||
if (!in_array($frequency, ['daily', 'weekly'], true)
|
||||
|| $weekday < 0 || $weekday > 6) {
|
||||
throw new \InvalidArgumentException('Invalid automatic backup schedule');
|
||||
}
|
||||
$zone = new \DateTimeZone(self::TIMEZONE);
|
||||
$local = (new \DateTimeImmutable('@' . max(0, $after)))
|
||||
->setTimezone($zone);
|
||||
$candidate = $local->setTime(0, 0, 0);
|
||||
if ($candidate->getTimestamp() <= $after) {
|
||||
$candidate = $candidate->modify('+1 day');
|
||||
}
|
||||
if ($frequency === 'weekly') {
|
||||
while ((int) $candidate->format('w') !== $weekday) {
|
||||
$candidate = $candidate->modify('+1 day');
|
||||
}
|
||||
}
|
||||
return $candidate->getTimestamp();
|
||||
}
|
||||
|
||||
public static function advanceAfterScheduled(
|
||||
CloudBackupSubscription $subscription,
|
||||
int $scheduledFor,
|
||||
int $backupId
|
||||
): void {
|
||||
$subscription->last_scheduled_at = $scheduledFor;
|
||||
$subscription->last_backup_id = $backupId;
|
||||
$subscription->next_run_at = self::nextRunAt(
|
||||
max(time(), $scheduledFor),
|
||||
(string) $subscription->frequency,
|
||||
(int) $subscription->weekday
|
||||
);
|
||||
$subscription->updated_at = time();
|
||||
$subscription->save();
|
||||
}
|
||||
|
||||
private static function scheduleOne(int $subscriptionId, int $now): bool
|
||||
{
|
||||
$subscription = CloudBackupSubscription::find($subscriptionId);
|
||||
if ($subscription === null || !(bool) $subscription->enabled
|
||||
|| (int) $subscription->next_run_at > $now) {
|
||||
return false;
|
||||
}
|
||||
$instance = CloudInstance::find((int) $subscription->instance_id);
|
||||
if ($instance === null || (string) $instance->status !== 'active'
|
||||
|| (string) $instance->service_status !== 'active'
|
||||
|| (int) $instance->user_id !== (int) $subscription->user_id) {
|
||||
throw new CloudError('实例当前不可创建自动备份', 409);
|
||||
}
|
||||
$scheduledFor = (int) $subscription->next_run_at;
|
||||
$actor = [
|
||||
'user_id' => (int) $instance->user_id,
|
||||
'is_admin' => false,
|
||||
'is_super_admin' => false,
|
||||
'can_manage' => true,
|
||||
'session_id' => 'automatic-backup-scheduler',
|
||||
'request_idempotency_key' => 'automatic-backup-'
|
||||
. (int) $subscription->id . '-' . $scheduledFor,
|
||||
];
|
||||
$queued = CloudBackupService::createAutomatic(
|
||||
$instance, $subscription, $actor, $scheduledFor
|
||||
);
|
||||
return $queued['job'] instanceof CloudJob;
|
||||
}
|
||||
|
||||
private static function backupsForInstance(CloudInstance $instance): array
|
||||
{
|
||||
$items = [];
|
||||
foreach (CloudInstanceBackup::where(
|
||||
'source_instance_id', (int) $instance->id
|
||||
)->where('user_id', (int) $instance->user_id)
|
||||
->where('purpose', 'portable')->where('source', 'automatic')
|
||||
->where('state', '<>', 'deleted')->orderByDesc('id')->get()
|
||||
as $backup) {
|
||||
$items[] = self::displayBackup($backup, $instance);
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
|
||||
private static function displayBackup(CloudInstanceBackup $backup,
|
||||
?CloudInstance $instance): array
|
||||
{
|
||||
$state = in_array((string) $backup->state, [
|
||||
'creating', 'ready', 'failed', 'uncertain', 'deleting',
|
||||
'delete_uncertain',
|
||||
], true) ? (string) $backup->state : 'uncertain';
|
||||
return [
|
||||
'id' => (string) $backup->id,
|
||||
'name' => (string) $backup->name,
|
||||
'state' => $state,
|
||||
'consistency' => in_array((string) $backup->consistency,
|
||||
['filesystem', 'crash'], true)
|
||||
? (string) $backup->consistency : 'unknown',
|
||||
'object_size_bytes' => max(0, (int) $backup->object_size_bytes),
|
||||
'virtual_size_bytes' => max(0, (int) $backup->virtual_size_bytes),
|
||||
'scheduled_for' => $backup->scheduled_for === null ? null
|
||||
: max(0, (int) $backup->scheduled_for),
|
||||
'created_at' => max(0, (int) $backup->created_at),
|
||||
'ready_at' => $backup->ready_at === null ? null
|
||||
: max(0, (int) $backup->ready_at),
|
||||
'source_instance' => [
|
||||
'id' => (string) $backup->source_instance_id,
|
||||
'name' => $instance === null ? '' : (string) $instance->name,
|
||||
'status' => $instance === null ? 'missing'
|
||||
: (string) $instance->status,
|
||||
],
|
||||
'can_restore_original' => $state === 'ready'
|
||||
&& $instance !== null
|
||||
&& (string) $instance->status !== 'deleted',
|
||||
'can_create_instance' => $state === 'ready',
|
||||
];
|
||||
}
|
||||
|
||||
private static function displaySubscription(
|
||||
CloudBackupSubscription $subscription
|
||||
): array {
|
||||
return [
|
||||
'enabled' => (bool) $subscription->enabled,
|
||||
'renew_next_period' => (bool) $subscription->renew_next_period,
|
||||
'frequency' => (string) $subscription->frequency,
|
||||
'weekday' => (int) $subscription->weekday,
|
||||
'retention_count' => (int) $subscription->retention_count,
|
||||
'timezone' => self::TIMEZONE,
|
||||
'run_at' => self::RUN_AT,
|
||||
'next_run_at' => max(0, (int) $subscription->next_run_at),
|
||||
'last_scheduled_at' => $subscription->last_scheduled_at === null
|
||||
? null : max(0, (int) $subscription->last_scheduled_at),
|
||||
'price' => (string) $subscription->price,
|
||||
'currency' => (string) $subscription->currency,
|
||||
'price_version' => (int) $subscription->price_version,
|
||||
];
|
||||
}
|
||||
|
||||
private static function entitled(CloudInstance $instance): bool
|
||||
{
|
||||
return (self::spec($instance)['automatic_backup'] ?? null) === true;
|
||||
}
|
||||
|
||||
private static function spec(CloudInstance $instance): array
|
||||
{
|
||||
$spec = json_decode((string) $instance->spec_json, true);
|
||||
if (!is_array($spec) || array_is_list($spec)) {
|
||||
throw new CloudError('实例计费快照损坏', 409);
|
||||
}
|
||||
return $spec;
|
||||
}
|
||||
|
||||
private static function moneySnapshot($value): string
|
||||
{
|
||||
return CloudMoney::decimal(CloudMoney::cents($value));
|
||||
}
|
||||
|
||||
private static function assertOwner(CloudInstance $instance,
|
||||
array $actor): void
|
||||
{
|
||||
if ((int) ($actor['user_id'] ?? 0) !== (int) $instance->user_id) {
|
||||
throw new CloudError('无权查看或修改该实例的自动备份', 403);
|
||||
}
|
||||
}
|
||||
|
||||
private static function positiveInteger($value, int $minimum,
|
||||
int $maximum): int
|
||||
{
|
||||
if (is_int($value)) {
|
||||
$parsed = $value;
|
||||
} elseif (is_string($value)
|
||||
&& preg_match('/^[1-9][0-9]{0,9}$/D', $value) === 1) {
|
||||
$parsed = (int) $value;
|
||||
} else {
|
||||
throw new CloudError('备份库分页参数无效');
|
||||
}
|
||||
if ($parsed < $minimum || $parsed > $maximum) {
|
||||
throw new CloudError('备份库分页参数超出范围');
|
||||
}
|
||||
return $parsed;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,197 @@
|
||||
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
||||
|
||||
function versionedModuleUrl(path) {
|
||||
const url = new URL(path, import.meta.url);
|
||||
url.search = '';
|
||||
if (assetVersion) url.searchParams.set('v', assetVersion);
|
||||
return url.href;
|
||||
}
|
||||
|
||||
const {
|
||||
api, byId, initializeSession, readBootstrap, showError,
|
||||
} = await import(versionedModuleUrl('./runtime.js'));
|
||||
|
||||
const state = {
|
||||
items: [], page: 1, totalPages: 1, total: 0, loading: false,
|
||||
controller: null,
|
||||
};
|
||||
|
||||
function makeElement(tag, className = '', content) {
|
||||
const element = document.createElement(tag);
|
||||
if (className) element.className = className;
|
||||
if (content !== undefined) element.textContent = String(content);
|
||||
return element;
|
||||
}
|
||||
|
||||
function firstText(...values) {
|
||||
for (const value of values) {
|
||||
if (value !== null && value !== undefined && String(value).trim() !== '') {
|
||||
return String(value).trim();
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function formatDate(value) {
|
||||
const raw = Number(value);
|
||||
const timestamp = Number.isFinite(raw) && raw > 0
|
||||
? (raw < 1e12 ? raw * 1000 : raw) : Date.parse(String(value || ''));
|
||||
const date = new Date(timestamp);
|
||||
return Number.isFinite(date.getTime())
|
||||
? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录';
|
||||
}
|
||||
|
||||
function formatBytes(value) {
|
||||
let amount = Number(value);
|
||||
if (!Number.isFinite(amount) || amount < 0) return '等待完成';
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
||||
let index = 0;
|
||||
while (amount >= 1024 && index < units.length - 1) {
|
||||
amount /= 1024;
|
||||
index += 1;
|
||||
}
|
||||
const precision = index === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2;
|
||||
return `${amount.toFixed(precision)} ${units[index]}`;
|
||||
}
|
||||
|
||||
function backupState(value) {
|
||||
const normalized = String(value || '').toLowerCase();
|
||||
const values = {
|
||||
ready: ['可用', 'running'], creating: ['正在备份', 'warning'], queued: ['等待备份', 'warning'],
|
||||
failed: ['备份失败', 'stopped'], uncertain: ['等待核对', 'warning'], deleting: ['正在删除', 'warning'],
|
||||
delete_uncertain: ['删除待核对', 'warning'],
|
||||
};
|
||||
return values[normalized] || [normalized || '状态未知', 'other'];
|
||||
}
|
||||
|
||||
function normalizeItems(payload) {
|
||||
const values = Array.isArray(payload?.items) ? payload.items
|
||||
: Array.isArray(payload?.backups) ? payload.backups : [];
|
||||
return values.filter(item => item && typeof item === 'object'
|
||||
&& /^[1-9]\d*$/.test(String(item.id ?? item.backup_id ?? '')));
|
||||
}
|
||||
|
||||
function sourceInstance(backup) {
|
||||
const source = backup?.source_instance && typeof backup.source_instance === 'object'
|
||||
? backup.source_instance
|
||||
: backup?.source && typeof backup.source === 'object' ? backup.source : {};
|
||||
return {
|
||||
id: String(source.id ?? source.instance_id ?? backup.source_instance_id ?? ''),
|
||||
name: firstText(source.instance_name, source.name, backup.source_instance_name),
|
||||
deleted: source.deleted === true || source.status === 'deleted'
|
||||
|| source.status === 'missing' || backup.source_instance_deleted === true,
|
||||
};
|
||||
}
|
||||
|
||||
function render() {
|
||||
const container = byId('cloud-backups-list');
|
||||
container.replaceChildren();
|
||||
if (!state.items.length) {
|
||||
const empty = makeElement('div', 'cloud-backups-empty');
|
||||
empty.append(makeElement('strong', '', '还没有云备份'),
|
||||
makeElement('span', '', '购买自动备份后,可在实例详情中设置备份计划。'));
|
||||
container.append(empty);
|
||||
}
|
||||
for (const backup of state.items) {
|
||||
const id = String(backup.id ?? backup.backup_id);
|
||||
const source = sourceInstance(backup);
|
||||
const [stateLabel, stateClass] = backupState(backup.state ?? backup.status);
|
||||
const card = makeElement('article', 'cloud-backup-card');
|
||||
const heading = makeElement('div', 'cloud-backup-card-heading');
|
||||
const title = makeElement('div', 'cloud-backup-title');
|
||||
title.append(makeElement('span', 'cloud-backup-icon', '☁'),
|
||||
makeElement('div', '', firstText(backup.name, `云备份 #${id}`)));
|
||||
title.lastElementChild.append(makeElement('small', '', source.deleted
|
||||
? '源实例已删除' : `来源:${source.name || (source.id ? `实例 #${source.id}` : '实例未记录')}`));
|
||||
heading.append(title, makeElement('span', `state-pill ${stateClass}`, stateLabel));
|
||||
const facts = makeElement('dl', 'cloud-backup-facts');
|
||||
const rows = [
|
||||
['创建时间', formatDate(backup.ready_at ?? backup.created_at)],
|
||||
['一致性', String(backup.consistency || '') === 'filesystem' ? '文件系统一致' : '崩溃一致'],
|
||||
['对象大小', formatBytes(backup.object_size_bytes)],
|
||||
['磁盘容量', formatBytes(backup.virtual_size_bytes)],
|
||||
];
|
||||
for (const [label, value] of rows) {
|
||||
const row = document.createElement('div');
|
||||
row.append(makeElement('dt', '', label), makeElement('dd', '', value));
|
||||
facts.append(row);
|
||||
}
|
||||
const actions = makeElement('div', 'cloud-backup-actions');
|
||||
if (backup.can_restore_original === true && !source.deleted
|
||||
&& /^[1-9]\d*$/.test(source.id)) {
|
||||
const restore = makeElement('a', 'button button-outline small', '恢复原实例');
|
||||
restore.href = `/user/cloud/instances/${encodeURIComponent(source.id)}?tab=settings&setting=automatic_backup`;
|
||||
actions.append(restore);
|
||||
}
|
||||
if (backup.can_create_instance === true
|
||||
|| (backup.can_create_instance === undefined
|
||||
&& String(backup.state ?? backup.status).toLowerCase() === 'ready')) {
|
||||
const create = makeElement('a', 'button button-primary small', '创建新实例');
|
||||
create.href = `/user/cloud/deploy?backup_id=${encodeURIComponent(id)}`;
|
||||
actions.append(create);
|
||||
}
|
||||
card.append(heading, facts, actions);
|
||||
container.append(card);
|
||||
}
|
||||
byId('cloud-backups-count').textContent = `${state.total} 个`;
|
||||
byId('cloud-backups-page').textContent = `第 ${state.page} / ${state.totalPages} 页`;
|
||||
byId('cloud-backups-previous').disabled = state.loading || state.page <= 1;
|
||||
byId('cloud-backups-next').disabled = state.loading || state.page >= state.totalPages;
|
||||
}
|
||||
|
||||
function applyPayload(payload) {
|
||||
state.items = normalizeItems(payload);
|
||||
const pagination = payload?.pagination && typeof payload.pagination === 'object'
|
||||
? payload.pagination : {};
|
||||
state.page = Math.max(1, Number(pagination.page ?? payload?.page) || 1);
|
||||
state.totalPages = Math.max(1, Number(pagination.total_pages ?? payload?.total_pages) || 1);
|
||||
state.total = Math.max(0, Number(pagination.total ?? payload?.total) || state.items.length);
|
||||
render();
|
||||
}
|
||||
|
||||
async function load(page = 1) {
|
||||
if (state.loading) return;
|
||||
state.loading = true;
|
||||
state.controller?.abort();
|
||||
const controller = new AbortController();
|
||||
state.controller = controller;
|
||||
byId('cloud-backups-status').hidden = false;
|
||||
byId('cloud-backups-status').className = 'vm-settings-status';
|
||||
byId('cloud-backups-status').textContent = '正在读取云备份…';
|
||||
render();
|
||||
try {
|
||||
const payload = await api(`/api/v1/backups?page=${encodeURIComponent(Math.max(1, page))}&per_page=20`, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
applyPayload(payload);
|
||||
byId('cloud-backups-status').hidden = true;
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) return;
|
||||
byId('cloud-backups-status').className = 'vm-settings-status error';
|
||||
byId('cloud-backups-status').textContent = error?.message || '云备份读取失败,请稍后重试。';
|
||||
} finally {
|
||||
if (state.controller === controller) state.controller = null;
|
||||
state.loading = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
export async function initialize() {
|
||||
try {
|
||||
const bootstrap = readBootstrap('cloud-backups-bootstrap');
|
||||
if (!await initializeSession('backups', bootstrap?.user)) return;
|
||||
if (Array.isArray(bootstrap?.items) || Array.isArray(bootstrap?.backups)) {
|
||||
applyPayload(bootstrap);
|
||||
byId('cloud-backups-status').hidden = true;
|
||||
} else {
|
||||
await load(1);
|
||||
}
|
||||
byId('cloud-backups-refresh')?.addEventListener('click', () => void load(state.page));
|
||||
byId('cloud-backups-previous')?.addEventListener('click', () => void load(state.page - 1));
|
||||
byId('cloud-backups-next')?.addEventListener('click', () => void load(state.page + 1));
|
||||
window.addEventListener('pagehide', () => state.controller?.abort());
|
||||
} catch (error) {
|
||||
showError('cloud-page-error', error?.message || '云备份页面加载失败,请刷新后重试。');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
<div id="cloud-backups-workspace">
|
||||
<div class="page-heading">
|
||||
<div><span class="eyebrow">CLOUD BACKUPS</span><h1>云备份</h1><p>集中查看当前账户的云备份,并选择可用备份创建新的付费实例。</p></div>
|
||||
<button id="cloud-backups-refresh" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button>
|
||||
</div>
|
||||
<div class="vm-settings-notice cloud-backups-notice"><strong>恢复入口说明</strong><span>此页面只用于从备份创建新实例。将已有实例恢复到某个备份,只能在该实例详情的“实例设置 → 自动备份”中执行。</span></div>
|
||||
<section class="inventory-panel cloud-backups-panel" aria-labelledby="cloud-backups-list-title">
|
||||
<div class="panel-heading"><div><h2 id="cloud-backups-list-title">全部备份</h2><p>只显示属于当前账户的普通云备份,不包含管理员维护迁移的临时数据。</p></div><span id="cloud-backups-count" class="state-pill other">0 个</span></div>
|
||||
<p id="cloud-backups-status" class="vm-settings-status" role="status" aria-live="polite">正在读取云备份…</p>
|
||||
<div id="cloud-backups-list" class="cloud-backups-list" aria-live="polite"></div>
|
||||
<nav class="cloud-backups-pagination" aria-label="云备份分页">
|
||||
<button id="cloud-backups-previous" class="button button-outline small" type="button" disabled>上一页</button>
|
||||
<span id="cloud-backups-page">第 1 / 1 页</span>
|
||||
<button id="cloud-backups-next" class="button button-outline small" type="button" disabled>下一页</button>
|
||||
</nav>
|
||||
</section>
|
||||
<noscript><p class="resource-warning">查看云备份和创建新实例需要启用 JavaScript。</p></noscript>
|
||||
</div>
|
||||
<script id="cloud-backups-bootstrap" type="application/json">{$cloud_backup_bootstrap_json|default:'{}' nofilter}</script>
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026102601' scope='global'}
|
||||
{assign var=venix_asset_version value='2026102602' scope='global'}
|
||||
|
||||
@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudAutomaticBackupService;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
// America/Los_Angeles changes from PST to PDT between these two local
|
||||
// midnights. The UTC interval is 23 hours, while the user-facing run time
|
||||
// remains exactly 00:00 Pacific.
|
||||
$beforeDst = strtotime('2026-03-08T07:30:00Z');
|
||||
$first = CloudAutomaticBackupService::nextRunAt($beforeDst, 'daily', 0);
|
||||
$second = CloudAutomaticBackupService::nextRunAt($first, 'daily', 0);
|
||||
$assert(gmdate('Y-m-d H:i:s', $first) === '2026-03-08 08:00:00'
|
||||
&& gmdate('Y-m-d H:i:s', $second) === '2026-03-09 07:00:00'
|
||||
&& $second - $first === 23 * 3600,
|
||||
'Pacific midnight drifted across the spring daylight-saving transition.');
|
||||
|
||||
$weekly = CloudAutomaticBackupService::nextRunAt(
|
||||
strtotime('2026-10-24T19:00:00Z'), 'weekly', 1
|
||||
);
|
||||
$local = (new DateTimeImmutable('@' . $weekly))->setTimezone(
|
||||
new DateTimeZone(CloudAutomaticBackupService::TIMEZONE)
|
||||
);
|
||||
$assert($local->format('w H:i') === '1 00:00',
|
||||
'Weekly schedule did not use the selected Pacific weekday at midnight.');
|
||||
|
||||
$routes = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php');
|
||||
$assert(str_contains($routes, "'/backups'")
|
||||
&& str_contains($routes, "'/vms/{id:[0-9]+}/automatic-backup'")
|
||||
&& str_contains($routes,
|
||||
"'/vms/{id:[0-9]+}/automatic-backup/{backup_id:[0-9]+}/restore'"),
|
||||
'Owner backup routes are incomplete.');
|
||||
|
||||
echo "Automatic backup Pacific schedule and route contract passed.\n";
|
||||
@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudInvoice;
|
||||
use App\Services\Cloud\CloudAutomaticBackupService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudInvoiceService;
|
||||
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('user_id');
|
||||
$table->integer('offer_id');
|
||||
$table->string('name');
|
||||
$table->string('status');
|
||||
$table->string('service_status');
|
||||
$table->string('renewal_price')->nullable();
|
||||
$table->text('spec_json');
|
||||
});
|
||||
$schema->create('cloud_backup_subscriptions',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id')->unique();
|
||||
$table->integer('user_id');
|
||||
$table->integer('offer_id');
|
||||
$table->boolean('enabled');
|
||||
$table->boolean('renew_next_period');
|
||||
$table->string('frequency');
|
||||
$table->integer('weekday');
|
||||
$table->integer('retention_count');
|
||||
$table->string('timezone');
|
||||
$table->decimal('price', 12, 2);
|
||||
$table->string('currency');
|
||||
$table->integer('price_version');
|
||||
$table->integer('next_run_at');
|
||||
$table->integer('last_scheduled_at')->nullable();
|
||||
$table->integer('last_backup_id')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_invoices', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('purpose');
|
||||
$table->string('amount');
|
||||
});
|
||||
$schema->create('cloud_invoice_items',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('invoice_id');
|
||||
$table->integer('order_item_id')->nullable();
|
||||
$table->string('code');
|
||||
$table->string('label');
|
||||
$table->string('amount');
|
||||
$table->string('currency');
|
||||
$table->text('snapshot_json');
|
||||
$table->integer('created_at');
|
||||
});
|
||||
$schema->create('cloud_instance_backups',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('source_instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->string('purpose');
|
||||
$table->string('source');
|
||||
$table->string('state');
|
||||
$table->string('name');
|
||||
$table->string('consistency');
|
||||
$table->integer('object_size_bytes');
|
||||
$table->integer('virtual_size_bytes');
|
||||
$table->integer('scheduled_for')->nullable();
|
||||
$table->integer('ready_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
|
||||
$instance = new CloudInstance();
|
||||
$instance->id = 1;
|
||||
$instance->user_id = 9;
|
||||
$instance->offer_id = 3;
|
||||
$instance->name = 'paid-backup-vm';
|
||||
$instance->status = 'active';
|
||||
$instance->service_status = 'active';
|
||||
$instance->renewal_price = '10.00';
|
||||
$instance->spec_json = json_encode([
|
||||
'automatic_backup' => true,
|
||||
'instance_price' => '10.00',
|
||||
'backup_price' => '2.50',
|
||||
'price_version' => 4,
|
||||
'currency' => 'USD',
|
||||
], JSON_THROW_ON_ERROR);
|
||||
$instance->save();
|
||||
|
||||
$subscription = CloudAutomaticBackupService::activatePurchased($instance);
|
||||
$assert($subscription !== null
|
||||
&& (bool) $subscription->enabled
|
||||
&& (bool) $subscription->renew_next_period
|
||||
&& (string) $subscription->frequency === 'daily'
|
||||
&& (int) $subscription->retention_count === 2
|
||||
&& (string) $subscription->timezone === 'America/Los_Angeles'
|
||||
&& (string) $subscription->price === '2.50',
|
||||
'Paid provisioning did not freeze the default backup subscription.');
|
||||
|
||||
$updated = CloudAutomaticBackupService::update($instance, [
|
||||
'user_id' => 9,
|
||||
], [
|
||||
'frequency' => 'weekly',
|
||||
'weekday' => 3,
|
||||
'retention_count' => 1,
|
||||
]);
|
||||
$assert($updated['entitled'] === true
|
||||
&& $updated['subscription']['enabled'] === true
|
||||
&& $updated['subscription']['frequency'] === 'weekly'
|
||||
&& $updated['subscription']['weekday'] === 3
|
||||
&& $updated['subscription']['retention_count'] === 1,
|
||||
'Schedule-only PUT did not preserve the paid enabled state.');
|
||||
|
||||
foreach (['enabled' => false, 'renew_next_period' => false] as $field => $value) {
|
||||
$rejected = false;
|
||||
try {
|
||||
CloudAutomaticBackupService::update($instance, [
|
||||
'user_id' => 9,
|
||||
], [
|
||||
'frequency' => 'weekly',
|
||||
'weekday' => 3,
|
||||
'retention_count' => 1,
|
||||
$field => $value,
|
||||
]);
|
||||
} catch (CloudError $error) {
|
||||
$rejected = true;
|
||||
}
|
||||
$assert($rejected, 'User schedule API accepted hidden billing control: '
|
||||
. $field);
|
||||
}
|
||||
$subscription->refresh();
|
||||
$assert((bool) $subscription->enabled
|
||||
&& (bool) $subscription->renew_next_period,
|
||||
'Rejected hidden billing controls changed the paid subscription.');
|
||||
|
||||
$quote = CloudInvoiceService::renewalQuoteLocked($instance);
|
||||
$assert($quote['instance_cents'] === 1000
|
||||
&& $quote['backup_cents'] === 250
|
||||
&& $quote['total_cents'] === 1250
|
||||
&& $quote['backup_subscription_id'] === (int) $subscription->id,
|
||||
'Renewal quote did not combine the base instance and backup price.');
|
||||
$invoice = new CloudInvoice();
|
||||
$invoice->purpose = 'renewal';
|
||||
$invoice->amount = '12.50';
|
||||
$invoice->save();
|
||||
$capsule->table('cloud_invoice_items')->insert([
|
||||
[
|
||||
'invoice_id' => (int) $invoice->id,
|
||||
'order_item_id' => null,
|
||||
'code' => 'instance',
|
||||
'label' => '实例套餐续费',
|
||||
'amount' => '10.00',
|
||||
'currency' => 'USD',
|
||||
'snapshot_json' => '{}',
|
||||
'created_at' => time(),
|
||||
],
|
||||
[
|
||||
'invoice_id' => (int) $invoice->id,
|
||||
'order_item_id' => null,
|
||||
'code' => 'automatic_backup',
|
||||
'label' => '自动备份续费',
|
||||
'amount' => '2.50',
|
||||
'currency' => 'USD',
|
||||
'snapshot_json' => '{}',
|
||||
'created_at' => time(),
|
||||
],
|
||||
]);
|
||||
$assert(CloudInvoiceService::renewalInvoiceMatches($instance, $invoice),
|
||||
'Renewal invoice did not accept the exact two-item backup quote.');
|
||||
$subscription->renew_next_period = false;
|
||||
$subscription->save();
|
||||
$failedClosed = false;
|
||||
try {
|
||||
CloudInvoiceService::renewalQuoteLocked($instance);
|
||||
} catch (CloudError $error) {
|
||||
$failedClosed = true;
|
||||
}
|
||||
$assert($failedClosed,
|
||||
'An entitled instance accepted a disabled backup renewal ledger.');
|
||||
|
||||
echo "Automatic backup subscription activation and update tests passed.\n";
|
||||
@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$read = static fn (string $path): string => file_get_contents($root . '/' . $path);
|
||||
|
||||
$deploy = $read('resources/views/venix/cloud/pages/deploy.tpl');
|
||||
$detail = $read('resources/views/venix/cloud/pages/detail.tpl');
|
||||
$backupPage = $read('resources/views/venix/cloud/pages/backups.tpl');
|
||||
$runtime = $read('public/cloud/runtime.js');
|
||||
$detailScript = $read('public/cloud/detail.js');
|
||||
$backupScript = $read('public/cloud/backups.js');
|
||||
$app = $read('public/cloud/app.js');
|
||||
$shell = $read('resources/views/venix/cloud/page.tpl');
|
||||
$sidebar = $read('resources/views/venix/user/panel_sidebar.tpl');
|
||||
$styles = $read('public/cloud/styles.css');
|
||||
|
||||
$assert(str_contains($deploy, 'id="vm-automatic-backup"')
|
||||
&& str_contains($deploy, 'id="vm-order-instance-price"')
|
||||
&& str_contains($deploy, 'id="vm-order-backup-price"')
|
||||
&& str_contains($deploy, 'id="vm-order-total-price"')
|
||||
&& !str_contains($deploy, 'offer-option-price')
|
||||
&& !str_contains($deploy, '>备份频率<')
|
||||
&& !str_contains($deploy, '>保留份数<'),
|
||||
'Deployment must expose only the automatic-backup purchase choice and final total, never schedule controls or per-offer prices.');
|
||||
$assert(str_contains($runtime, 'const backupAvailable = Boolean(offer);')
|
||||
&& !str_contains($runtime, 'backup_available')
|
||||
&& str_contains($runtime, 'Number(offer.backup_price)')
|
||||
&& str_contains($runtime, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
|
||||
&& str_contains($runtime, "new URLSearchParams(location.search).get('backup_id')")
|
||||
&& str_contains($runtime, 'body.backup_id = Number(state.deployBackupId)')
|
||||
&& str_contains($runtime, "source: state.deployBackupId ? 'backup' : 'cloud'")
|
||||
&& str_contains($runtime,
|
||||
'if (!state.deployBackupId && !strongPassword(password))')
|
||||
&& str_contains($runtime, 'provisionInvoiceFingerprint(body)'),
|
||||
'Deployment pricing and idempotency must include the backup purchase and optional backup source.');
|
||||
|
||||
$assert(str_contains($detail, 'data-instance-setting-tab="automatic_backup"')
|
||||
&& str_contains($detail, 'id="vm-automatic-backup-frequency"')
|
||||
&& str_contains($detail, '<option value="daily" selected>每天</option>')
|
||||
&& str_contains($detail, '<option value="weekly">每周</option>')
|
||||
&& str_contains($detail, 'id="vm-automatic-backup-retention"')
|
||||
&& str_contains($detail, '<option value="2" selected>保留 2 份</option>')
|
||||
&& str_contains($detail, '太平洋时间 00:00')
|
||||
&& str_contains($detail, 'America/Los_Angeles'),
|
||||
'Instance settings must own daily/weekly scheduling, Pacific midnight and the two-backup retention limit.');
|
||||
$assert(str_contains($detailScript,
|
||||
"`/api/v1/vms/\${encodeURIComponent(vmId)}/automatic-backup`")
|
||||
&& str_contains($detailScript, "method: 'PUT', body: { frequency, weekday, retention_count: retention }")
|
||||
&& str_contains($detailScript,
|
||||
"`/api/v1/vms/\${encodeURIComponent(vmId)}/automatic-backup/\${encodeURIComponent(id)}/restore`")
|
||||
&& str_contains($detailScript, "headers: { 'Idempotency-Key': idempotencyKey }")
|
||||
&& str_contains($detailScript, 'body: { confirm_restore: true }')
|
||||
&& str_contains($detailScript, 'expectedStatus: 202, requireTaskReceipt: true'),
|
||||
'Only the instance settings module may restore an automatic backup over its source instance.');
|
||||
|
||||
$assert(str_contains($sidebar, 'href="/user/cloud/backups"')
|
||||
&& str_contains($sidebar, '>云备份</span>')
|
||||
&& str_contains($shell, "cloud_page == 'backups'")
|
||||
&& str_contains($app, "backups: '/cloud/backups.js'")
|
||||
&& str_contains($backupPage, 'id="cloud-backups-list"')
|
||||
&& str_contains($backupScript, "api(`/api/v1/backups?page=")
|
||||
&& str_contains($backupScript, "`/user/cloud/deploy?backup_id=\${encodeURIComponent(id)}`")
|
||||
&& str_contains($backupScript,
|
||||
"`/user/cloud/instances/\${encodeURIComponent(source.id)}?tab=settings&setting=automatic_backup`")
|
||||
&& str_contains($backupScript, 'backup?.source_instance')
|
||||
&& !str_contains($backupScript, "method: 'POST'"),
|
||||
'The global backup library must create new instances or link to instance settings, never restore the source directly.');
|
||||
$assert(str_contains($styles, '.cloud-backups-list')
|
||||
&& str_contains($styles, '.vm-automatic-backup-grid')
|
||||
&& str_contains($styles, '@media screen and (max-width:510px)')
|
||||
&& str_contains($styles, '.cloud-backup-actions .button{flex:1 1 100%;width:100%}'),
|
||||
'Backup library and settings must retain mobile layouts.');
|
||||
|
||||
echo "Cloud user backup UI contract tests passed\n";
|
||||
Loading…
Reference in New Issue