feat(cloud): add paid automatic backups

go
codex 4 weeks ago
parent 1ea91bd9f3
commit ece7e24b52

@ -427,6 +427,35 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
)
return
}
case "recover-backup":
if len(segments) == 4 && r.Method == http.MethodPost {
if !requireManage(w, actor) {
return
}
request, ok := decodeRequired[hypervisor.RecoverBackupRequest](w, body)
if !ok {
return
}
resolvedOperationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
request.OperationID = resolvedOperationID
if err := hypervisor.ValidateRecoverBackupRequest(request); err != nil {
writePreDispatchMappedError(w, err)
return
}
action := "recover-backup:" + request.BackupKey + ":" + request.SourceSHA256
s.runAsyncMutationWithDeadline(
w, r, body, actor, request.OperationID, uuid, action, true,
hypervisor.RecoverBackupAdmission(uuid, request), backupOperationTimeout,
func(ctx context.Context) (any, error) {
return s.Hypervisor.RecoverBackup(ctx, uuid, request)
},
)
return
}
case "force-delete":
if len(segments) == 4 && r.Method == http.MethodPost {
if !requireSuperAdminPrivilegedOperation(w, actor) {

@ -990,6 +990,62 @@ func TestCreateBackupUsesDedicatedAsyncActionAndHeavyAdmission(t *testing.T) {
}
}
func TestRecoverBackupUsesDestructiveDiskTransitionAdmission(t *testing.T) {
api := newTestAPI(t)
const (
uuid = "123e4567-e89b-42d3-a456-426614174000"
backupKey = "0123456789abcdef0123456789abcdef"
)
backupSHA := strings.Repeat("b", 64)
result := hypervisor.RecoverBackupResult{
BackupKey: backupKey, SHA256: backupSHA,
Restored: true, PowerState: hypervisor.VMStateRunning,
}
encodedResult, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
executor := &fakeMutationExecutor{result: encodedResult}
if err := api.handler.SetMutationExecutor(executor); err != nil {
t.Fatal(err)
}
request := hypervisor.RecoverBackupRequest{
OperationID: "operation-recover-backup", BackupKey: backupKey,
SourceURL: "https://objects.example.test/object?signature=secret",
SourceSizeBytes: 4 << 20, SourceSHA256: backupSHA,
}
body, err := json.Marshal(request)
if err != nil {
t.Fatal(err)
}
actor := auth.Actor{
UserID: 1, IsAdmin: true, IsSuperAdmin: true, CanManage: true,
OperationID: request.OperationID,
}
response := api.request(t, http.MethodPost,
"/v1/vms/"+uuid+"/recover-backup", body, actor)
if response.Code != http.StatusAccepted {
t.Fatalf("backup recovery response = %d %s", response.Code,
response.Body.String())
}
record := waitForTerminal(t, api.journal, request.OperationID)
if record.State != operation.StateSucceeded ||
record.Action != "recover-backup:"+backupKey+":"+backupSHA ||
record.ResourceID != uuid || !record.Destructive || !record.HeavyIO {
t.Fatalf("backup recovery operation record = %#v", record)
}
for _, want := range []string{
"domain:" + uuid,
"volume:virt-cloud-managed/vm-" + uuid,
"catalog:backup/" + backupKey,
} {
if !containsTestString(record.LockKeys, want) {
t.Fatalf("backup recovery locks missing %q: %v", want,
record.LockKeys)
}
}
}
func TestRestoreBackupDerivesDomainAndUsesCreateLikeAction(t *testing.T) {
api := newTestAPI(t)
const (

@ -298,7 +298,8 @@ func isolatedWorkerLifetime(method, path string) time.Duration {
}
segments := strings.Split(strings.Trim(path, "/"), "/")
if len(segments) == 4 && segments[0] == "v1" && segments[1] == "vms" &&
(segments[3] == "backups" || segments[3] == "restore-backup") {
(segments[3] == "backups" || segments[3] == "restore-backup" ||
segments[3] == "recover-backup") {
return isolatedBackupWorkerMaximumLifetime
}
return isolatedWorkerMaximumLifetime

@ -33,6 +33,7 @@ func TestIsolatedWorkerLifetimeAllowsPortableBackupDeadline(t *testing.T) {
for _, path := range []string{
"/v1/vms/123e4567-e89b-42d3-a456-426614174000/backups",
"/v1/vms/123e4567-e89b-42d3-a456-426614174000/restore-backup",
"/v1/vms/123e4567-e89b-42d3-a456-426614174000/recover-backup",
} {
if got := isolatedWorkerLifetime("POST", path); got != 24*time.Hour+30*time.Second {
t.Fatalf("backup worker lifetime for %q = %s", path, got)

@ -147,6 +147,16 @@ func RestoreBackupAdmission(request RestoreBackupRequest) MutationAdmission {
return MutationAdmission{HeavyIO: true, LockKeys: locks}
}
func RecoverBackupAdmission(uuid string, request RecoverBackupRequest) MutationAdmission {
uuid = strings.ToLower(uuid)
return MutationAdmission{HeavyIO: true, LockKeys: []string{
domainLockKey(uuid), vmManagedVolumesLockKey(uuid),
volumeLockKey(managedStoragePoolName,
snapshotRestoreVolumeName(uuid, request.OperationID)),
catalogLockKey("backup", request.BackupKey),
}}
}
func DeleteSnapshotAdmission(uuid, snapshotKey string) MutationAdmission {
uuid = strings.ToLower(uuid)
return MutationAdmission{LockKeys: []string{

@ -119,6 +119,20 @@ func ValidateRestoreBackupRequest(request RestoreBackupRequest) error {
return nil
}
func ValidateRecoverBackupRequest(request RecoverBackupRequest) error {
if !operationIdentifierPattern.MatchString(request.OperationID) ||
!catalogIDPattern.MatchString(request.BackupKey) {
return NewError(ErrInvalid, "invalid_backup_recovery", "backup recovery operation id or key is invalid", nil)
}
if request.SourceSizeBytes > maxBackupObjectBytes {
return NewError(ErrInvalid, "backup_object_too_large", "backup object is too large", nil)
}
if err := objecttransfer.ValidateDownload(request.SourceURL, request.SourceSizeBytes, request.SourceSHA256); err != nil {
return NewError(ErrInvalid, "invalid_backup_object", "backup object identity is invalid", err)
}
return nil
}
func translateObjectTransferError(err error) error {
if err == nil {
return nil

@ -118,6 +118,21 @@ func TestValidateRestoreBackupReusesCreateIntentWithoutReplacingCredentials(t *t
}
}
func TestValidateRecoverBackupAcceptsOnlyBoundImmutableObject(t *testing.T) {
request := RecoverBackupRequest{
OperationID: "operation-recover-backup", BackupKey: testBackupKey,
SourceURL: "https://objects.example.test/backups/object?signature=secret",
SourceSizeBytes: 4 << 20, SourceSHA256: strings.Repeat("b", 64),
}
if err := ValidateRecoverBackupRequest(request); err != nil {
t.Fatalf("valid backup recovery rejected: %v", err)
}
request.SourceURL = "http://objects.example.test/unsafe"
if err := ValidateRecoverBackupRequest(request); err == nil {
t.Fatal("backup recovery accepted a plain-HTTP object capability")
}
}
func TestBackupAdmissionsFenceSourceAndNewVMArtifacts(t *testing.T) {
const uuid = "123e4567-e89b-42d3-a456-426614174000"
backupRequest := validBackupRequest()
@ -142,6 +157,20 @@ func TestBackupAdmissionsFenceSourceAndNewVMArtifacts(t *testing.T) {
t.Fatalf("restore admission missing %q: %#v", key, restore)
}
}
recoveryRequest := RecoverBackupRequest{
OperationID: "operation-recover-backup", BackupKey: testBackupKey,
}
recovery := RecoverBackupAdmission(uuid, recoveryRequest)
for _, key := range []string{
domainLockKey(uuid), vmManagedVolumesLockKey(uuid),
volumeLockKey(managedStoragePoolName,
snapshotRestoreVolumeName(uuid, recoveryRequest.OperationID)),
catalogLockKey("backup", recoveryRequest.BackupKey),
} {
if !containsString(recovery.LockKeys, key) || !recovery.HeavyIO {
t.Fatalf("recovery admission missing %q: %#v", key, recovery)
}
}
}
func TestMigrationBundleValidationAndAdmissionIncludeEverySnapshot(t *testing.T) {

@ -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
}

@ -566,6 +566,12 @@ func (m *managedLibvirt) RestoreBackup(ctx context.Context, request RestoreBacku
})
}
func (m *managedLibvirt) RecoverBackup(ctx context.Context, uuid string, request RecoverBackupRequest) (RecoverBackupResult, error) {
return managedCall(m, ctx, true, func(h Hypervisor) (RecoverBackupResult, error) {
return h.RecoverBackup(ctx, uuid, request)
})
}
func (m *managedLibvirt) DeleteVM(ctx context.Context, uuid string, request DeleteVMRequest) (DeleteVMResult, error) {
return managedCall(m, ctx, true, func(h Hypervisor) (DeleteVMResult, error) {
return h.DeleteVM(ctx, uuid, request)

@ -1342,7 +1342,7 @@ func inspectManagedDomain(document string) (*libvirtxml.Domain, *domainMetadataX
if (metadata.RescueTemplateID != "" && !catalogIDPattern.MatchString(metadata.RescueTemplateID)) || (metadata.RescueTemplateID == "" && (metadata.RescueWasRunning || metadata.RescueAutostart)) {
return nil, nil, true, NewError(ErrConflict, "managed_metadata_invalid", "Virt Cloud rescue metadata is invalid", nil)
}
if (metadata.DiskTransitionKind == "") != (metadata.DiskTransitionID == "") || (metadata.DiskTransitionKind != "" && metadata.DiskTransitionKind != "reinstall" && metadata.DiskTransitionKind != "snapshot_restore") || (metadata.DiskTransitionID != "" && !operationIdentifierPattern.MatchString(metadata.DiskTransitionID)) {
if (metadata.DiskTransitionKind == "") != (metadata.DiskTransitionID == "") || (metadata.DiskTransitionKind != "" && metadata.DiskTransitionKind != "reinstall" && metadata.DiskTransitionKind != "snapshot_restore" && metadata.DiskTransitionKind != "backup_recover") || (metadata.DiskTransitionID != "" && !operationIdentifierPattern.MatchString(metadata.DiskTransitionID)) {
return nil, nil, true, NewError(ErrConflict, "managed_metadata_invalid", "Virt Cloud disk transition metadata is invalid", nil)
}
for _, transitionID := range []string{metadata.SettingsTransitionID, metadata.ResourcesTransitionID, metadata.NetworkTransitionID, metadata.FirewallTransitionID} {

@ -243,7 +243,8 @@ func (l *Libvirt) inspectExistingDomainOperation(ctx context.Context, record ope
if strings.HasPrefix(record.Action, "create-snapshot:") ||
strings.HasPrefix(record.Action, "create-backup:") ||
strings.HasPrefix(record.Action, "delete-snapshot:") ||
strings.HasPrefix(record.Action, "restore-snapshot:") {
strings.HasPrefix(record.Action, "restore-snapshot:") ||
strings.HasPrefix(record.Action, "recover-backup:") {
resolution, steps := l.inspectSnapshotOperation(record, domain)
return resolution, steps, nil
}
@ -716,6 +717,46 @@ func (l *Libvirt) inspectSnapshotOperation(record operation.Record,
return operation.Resolution{Resolved: true, Succeeded: false,
ErrorCode: "snapshot_not_restored", ErrorMessage: "host evidence confirms the root volume was not switched"}, operationCleanupInspection{}
}
case "recover-backup":
if len(parts) != 3 || !catalogIDPattern.MatchString(parts[1]) ||
!sha256Pattern.MatchString(parts[2]) {
return operation.Resolution{}, operationCleanupInspection{}
}
key, sourceSHA256 := parts[1], parts[2]
replacementName := snapshotRestoreVolumeName(record.ResourceID, record.OperationID)
replacement, lookupErr := l.lookupOptionalManagedVolume(
l.storagePoolName(StorageRoleManaged), replacementName)
if lookupErr != nil {
return operation.Resolution{}, operationCleanupInspection{}
}
replacementExists := replacement != nil
if replacement != nil {
replacement.Free()
}
if diskTransitionCommitted(metadata, replacementName,
"backup_recover", record.OperationID) && replacementExists {
state, _, stateErr := domain.GetState()
if stateErr != nil || !diskTransitionPowerStateMatches(
metadata, state, "backup_recover", record.OperationID) {
return operation.Resolution{}, operationCleanupInspection{}
}
if metadata.PendingCleanupVolume != "" {
return operation.Resolution{},
l.inspectDiskTransitionCleanupSteps(domain, document, metadata)
}
result, _ := json.Marshal(RecoverBackupResult{
BackupKey: key, SHA256: sourceSHA256, Restored: true,
PowerState: mapDomainState(state), ActiveVolumeName: replacementName,
})
return operation.Resolution{Resolved: true, Succeeded: true,
Result: result}, operationCleanupInspection{}
}
if !replacementExists && metadata.DiskTransitionID != record.OperationID {
return operation.Resolution{Resolved: true, Succeeded: false,
ErrorCode: "backup_not_recovered",
ErrorMessage: "host evidence confirms the root volume was not switched"},
operationCleanupInspection{}
}
}
return operation.Resolution{}, operationCleanupInspection{}
}
@ -1113,7 +1154,8 @@ func inspectedEffectResolution(record operation.Record, resolution operation.Res
record.Action == "change-network",
record.Action == "reinstall-vm",
record.Action == "apply-firewall",
strings.HasPrefix(record.Action, "restore-snapshot:"):
strings.HasPrefix(record.Action, "restore-snapshot:"),
strings.HasPrefix(record.Action, "recover-backup:"):
return InspectionEffectApplied
default:
return InspectionEffectInconclusive
@ -1125,7 +1167,8 @@ func inspectedEffectResolution(record operation.Record, resolution operation.Res
record.Action == "change-network" && resolution.ErrorCode == "network_not_committed",
record.Action == "reinstall-vm" && resolution.ErrorCode == "reinstall_not_committed",
record.Action == "apply-firewall" && resolution.ErrorCode == "firewall_not_committed",
strings.HasPrefix(record.Action, "restore-snapshot:") && resolution.ErrorCode == "snapshot_not_restored":
strings.HasPrefix(record.Action, "restore-snapshot:") && resolution.ErrorCode == "snapshot_not_restored",
strings.HasPrefix(record.Action, "recover-backup:") && resolution.ErrorCode == "backup_not_recovered":
return InspectionEffectNotApplied
default:
return InspectionEffectInconclusive
@ -1232,6 +1275,21 @@ func operationEffectProjection(record operation.Record, raw []byte) json.RawMess
SnapshotArtifacts: value.SnapshotArtifacts,
StagedPoweredOff: value.StagedPoweredOff,
}
case strings.HasPrefix(record.Action, "recover-backup:"):
parts := strings.Split(record.Action, ":")
var value RecoverBackupResult
if len(parts) != 3 || !catalogIDPattern.MatchString(parts[1]) ||
!sha256Pattern.MatchString(parts[2]) ||
!decodeOperationEffectResult(raw, &value) || !value.Restored ||
value.BackupKey != parts[1] || value.SHA256 != parts[2] {
return nil
}
projection = struct {
BackupKey string `json:"backup_key"`
SHA256 string `json:"sha256,omitempty"`
Restored bool `json:"restored"`
PowerState VMStateName `json:"power_state"`
}{value.BackupKey, value.SHA256, value.Restored, value.PowerState}
case operation.IsCreateLikeAction(record.Action) || record.Action == "update-settings" ||
record.Action == "change-network" || record.Action == "reinstall-vm":
var value VMMetadata

@ -297,6 +297,26 @@ type RestoreBackupResult struct {
StagedPoweredOff bool `json:"staged_powered_off,omitempty"`
}
// RecoverBackupRequest replaces the managed root disk of an existing VM with
// one immutable portable-backup object. Network identity, NoCloud seed,
// billing identity and the domain UUID are deliberately outside this request
// and remain attached to the existing domain.
type RecoverBackupRequest struct {
OperationID string `json:"operation_id,omitempty"`
BackupKey string `json:"backup_key"`
SourceURL string `json:"source_url"`
SourceSizeBytes int64 `json:"source_size_bytes"`
SourceSHA256 string `json:"source_sha256"`
}
type RecoverBackupResult struct {
BackupKey string `json:"backup_key"`
SHA256 string `json:"sha256"`
Restored bool `json:"restored"`
PowerState VMStateName `json:"power_state"`
ActiveVolumeName string `json:"-"`
}
// DomainDefinition is resolved entirely by the Agent. No host path in this
// structure is accepted from a panel request.
type DomainDefinition struct {
@ -760,6 +780,7 @@ type Hypervisor interface {
CreateVM(context.Context, CreateVMRequest) (VMMetadata, error)
CreateBackup(context.Context, string, BackupRequest) (BackupResult, error)
RestoreBackup(context.Context, RestoreBackupRequest) (RestoreBackupResult, error)
RecoverBackup(context.Context, string, RecoverBackupRequest) (RecoverBackupResult, error)
DeleteVM(context.Context, string, DeleteVMRequest) (DeleteVMResult, error)
ForceDeleteVM(context.Context, string, ForceDeleteVMRequest) (DeleteVMResult, error)
Power(context.Context, string, PowerRequest) (VMState, error)
@ -830,6 +851,9 @@ func (Unsupported) CreateBackup(context.Context, string, BackupRequest) (BackupR
func (Unsupported) RestoreBackup(context.Context, RestoreBackupRequest) (RestoreBackupResult, error) {
return RestoreBackupResult{}, unsupported("VM backup restore")
}
func (Unsupported) RecoverBackup(context.Context, string, RecoverBackupRequest) (RecoverBackupResult, error) {
return RecoverBackupResult{}, unsupported("VM backup recovery")
}
func (Unsupported) DeleteVM(context.Context, string, DeleteVMRequest) (DeleteVMResult, error) {
return DeleteVMResult{}, unsupported("VM delete")
}

@ -216,6 +216,19 @@
"not_applied"
]
},
{
"kind": "backup_recover",
"recovery_mode": "generic",
"identity_scope": "instance",
"actions": [],
"action_patterns": [
"^recover-backup:[a-f0-9]{32}:[a-f0-9]{64}$"
],
"system_resolutions": [
"applied",
"not_applied"
]
},
{
"kind": "firewall_apply",
"recovery_mode": "generic",
@ -366,7 +379,9 @@
"actions": [
"create-vm"
],
"action_patterns": [],
"action_patterns": [
"^restore-backup:[a-f0-9]{32}$"
],
"system_resolutions": [
"not_applied"
]

@ -18,6 +18,7 @@ func TestEmbeddedRecoveryContractControlsSystemResolutions(t *testing.T) {
{name: "resize applied", action: "resize-vm", resolution: FenceResolutionApplied, want: true},
{name: "parameterized snapshot", action: "create-snapshot:0123456789abcdef0123456789abcdef:filesystem", resolution: FenceResolutionApplied, want: true},
{name: "backup create applied", action: "create-backup:0123456789abcdef0123456789abcdef:crash", resolution: FenceResolutionApplied, want: true},
{name: "backup recover applied", action: "recover-backup:0123456789abcdef0123456789abcdef:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", resolution: FenceResolutionApplied, want: true},
{name: "backup restore not applied", action: "restore-backup:0123456789abcdef0123456789abcdef", resolution: FenceResolutionNotApplied, want: true},
{name: "backup restore applied denied", action: "restore-backup:0123456789abcdef0123456789abcdef", resolution: FenceResolutionApplied, want: false},
{name: "create not applied", action: "create-vm", resolution: FenceResolutionNotApplied, want: true},

@ -8,7 +8,7 @@ use App\Services\Config;
/** Initializes only the clean-break PHP business and Agent log schemas. */
final class CloudSetup
{
private const SCHEMA_VERSION = 'go-agent-wss-v6-migration-bundles';
private const SCHEMA_VERSION = 'go-agent-wss-v7-automatic-backups';
private const MAIN_TABLES = [
'cloud_regions', 'cloud_network_lines', 'cloud_resource_pools',
'cloud_hosts', 'cloud_host_agents',
@ -23,11 +23,13 @@ final class CloudSetup
'cloud_instance_firewall_versions', 'cloud_instance_firewall_rules',
'cloud_platform_test_policy_state',
'cloud_platform_test_policy_rules', 'cloud_instance_snapshots',
'cloud_instance_backups', 'cloud_backup_restores',
'cloud_backup_subscriptions', 'cloud_instance_backups',
'cloud_backup_restores', 'cloud_backup_recoveries',
'cloud_instance_migrations', 'cloud_migration_bundle_artifacts',
'cloud_instance_runtime', 'cloud_orders',
'cloud_instance_runtime', 'cloud_orders', 'cloud_order_items',
'cloud_resource_reservations', 'cloud_service_periods',
'cloud_renewals', 'cloud_invoices', 'cloud_invoice_payments',
'cloud_renewals', 'cloud_invoices', 'cloud_invoice_items',
'cloud_invoice_payments',
'cloud_mail_outbox', 'cloud_jobs', 'cloud_agent_completion_events',
'cloud_ssh_keys',
'cloud_sessions', 'cloud_console_tickets',
@ -45,7 +47,7 @@ final class CloudSetup
'cloud_jobs' => [
'id', 'operation_id', 'request_idempotency_key',
'request_fingerprint', 'parent_job_id', 'user_id', 'host_id',
'backup_id', 'backup_restore_id',
'backup_id', 'backup_restore_id', 'backup_recovery_id',
'kind', 'execution_mode', 'phase', 'outcome', 'status',
'attempts', 'dispatch_attempts', 'dispatch_deadline_at',
'dispatch_started_at', 'agent_accepted_at',
@ -62,9 +64,16 @@ final class CloudSetup
'error_code', 'result_json', 'disposition', 'received_at',
'applied_at',
],
'cloud_backup_subscriptions' => [
'id', 'instance_id', 'user_id', 'offer_id', 'enabled',
'renew_next_period', 'frequency', 'weekday', 'retention_count',
'timezone', 'price', 'currency', 'price_version', 'next_run_at',
'last_scheduled_at', 'last_backup_id', 'created_at', 'updated_at',
],
'cloud_instance_backups' => [
'id', 'backup_key', 'source_instance_id', 'source_host_id',
'user_id', 'source_uuid', 'name', 'purpose', 'state', 'consistency',
'user_id', 'source_uuid', 'name', 'purpose', 'source',
'subscription_id', 'scheduled_for', 'state', 'consistency',
'object_key', 'object_size_bytes', 'virtual_size_bytes',
'sha256', 'spec_json', 'sealed_storage_runtime',
'sealed_credential', 'storage_revision', 'active_job_id',
@ -77,6 +86,19 @@ final class CloudSetup
'new_uuid', 'new_name', 'state', 'error_code', 'ready_at',
'created_at', 'updated_at',
],
'cloud_backup_recoveries' => [
'id', 'recovery_key', 'backup_id', 'instance_id', 'job_id',
'operation_id', 'state', 'error_code', 'completed_at',
'created_at', 'updated_at',
],
'cloud_order_items' => [
'id', 'order_id', 'code', 'label', 'amount', 'currency',
'snapshot_json', 'created_at',
],
'cloud_invoice_items' => [
'id', 'invoice_id', 'order_item_id', 'code', 'label', 'amount',
'currency', 'snapshot_json', 'created_at',
],
'cloud_instance_migrations' => [
'id', 'migration_key', 'instance_id', 'backup_id', 'restore_id',
'source_host_id', 'source_uuid', 'source_reservation_id',
@ -123,6 +145,11 @@ final class CloudSetup
],
];
private const REQUIRED_CHECKS = [
'cloud_backup_subscriptions' => [
'chk_cloud_backup_subscription_frequency',
'chk_cloud_backup_subscription_weekday',
'chk_cloud_backup_subscription_retention',
],
'cloud_invoice_payments' => [
'chk_cloud_invoice_payment_status',
],
@ -148,13 +175,20 @@ final class CloudSetup
'uniq_cloud_job_completion_event', 'uniq_cloud_provision_order',
'cloud_job_poll', 'cloud_job_receipt_deadline',
'cloud_job_backup', 'cloud_job_backup_restore',
'cloud_job_backup_recovery',
],
'cloud_agent_completion_events' => [
'PRIMARY', 'uniq_cloud_completion_operation',
],
'cloud_backup_subscriptions' => [
'PRIMARY', 'cloud_backup_subscription_instance',
'cloud_backup_subscription_due',
'cloud_backup_subscription_owner',
],
'cloud_instance_backups' => [
'PRIMARY', 'cloud_instance_backup_key',
'cloud_instance_backup_object', 'cloud_instance_backup_source',
'cloud_instance_backup_object', 'cloud_instance_backup_schedule',
'cloud_instance_backup_source',
'cloud_instance_backup_owner', 'cloud_instance_backup_operation',
],
'cloud_backup_restores' => [
@ -164,6 +198,18 @@ final class CloudSetup
'cloud_backup_restore_instance', 'cloud_backup_restore_backup',
'cloud_backup_restore_host',
],
'cloud_backup_recoveries' => [
'PRIMARY', 'cloud_backup_recovery_key',
'cloud_backup_recovery_operation', 'cloud_backup_recovery_job',
'cloud_backup_recovery_instance', 'cloud_backup_recovery_backup',
],
'cloud_order_items' => [
'PRIMARY', 'cloud_order_item_code', 'cloud_order_item_order',
],
'cloud_invoice_items' => [
'PRIMARY', 'cloud_invoice_item_code',
'cloud_invoice_item_invoice', 'cloud_invoice_item_order_item',
],
'cloud_instance_migrations' => [
'PRIMARY', 'cloud_instance_migration_key',
'cloud_instance_migration_backup',

@ -243,7 +243,10 @@ class ShopController extends AdminController
);
}
$input = [];
foreach (['resource_pool_id', 'name', 'price', 'stock', 'status', 'sort'] as $field) {
foreach ([
'resource_pool_id', 'name', 'price', 'backup_price', 'stock',
'status', 'sort',
] as $field) {
$input[$field] = $request->getParam($field, $offer === null ? null : $offer->$field);
}
$input['code'] = $offer === null
@ -312,7 +315,10 @@ class ShopController extends AdminController
throw new \InvalidArgumentException('销售方案系统标识已被使用');
}
$priceChanged = $locked->exists && (string) $locked->price !== (string) $values['price'];
$priceChanged = $locked->exists
&& ((string) $locked->price !== (string) $values['price']
|| (string) $locked->backup_price
!== (string) $values['backup_price']);
foreach ($values as $field => $value) {
if ($locked->exists && $field === 'code') {
continue;
@ -463,6 +469,12 @@ class ShopController extends AdminController
(string) $offer->pool_name,
], static fn ($value) => $value !== ''))),
'price' => '$' . number_format((float) $offer->price, 2, '.', ''),
'backup_price' => '$' . number_format(
(float) $offer->backup_price,
2,
'.',
''
),
'price_version' => (int) $offer->price_version,
'stock' => (int) $offer->stock,
'status' => (bool) $offer->status,

@ -2,6 +2,7 @@
namespace App\Controllers;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
@ -12,6 +13,8 @@ use App\Services\Auth;
use App\Services\AdminCsrf;
use App\Services\Config;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAutomaticBackupService;
use App\Services\Cloud\CloudBackupService;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudConsoleTicketService;
@ -1032,6 +1035,47 @@ final class CloudApiController
));
}
/** Owner-only automatic backup library. */
public function backups($request, $response)
{
return $this->json($response, CloudAutomaticBackupService::library(
$this->actor($request), $request->getQueryParams()
));
}
/** Read or replace the paid instance automatic-backup policy. */
public function automaticBackup($request, $response, $args)
{
$actor = $this->actor($request);
$write = $request->getMethod() === 'PUT';
$instance = CloudAccess::instance($args['id'], $actor, $write);
$value = $write
? CloudAutomaticBackupService::update(
$instance, $actor, CloudInput::object($request)
)
: CloudAutomaticBackupService::settings($instance, $actor);
return $this->json($response, $value);
}
/** Queue a destructive in-place system-disk recovery. */
public function restoreAutomaticBackup($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$backup = CloudInstanceBackup::find((int) $args['backup_id']);
if ($backup === null) {
throw new CloudError('云备份不存在', 404);
}
$queued = CloudBackupService::recover(
$instance, $backup, $actor, CloudInput::object($request)
);
$job = $queued['job'];
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
/** Database-only read and revisioned whole-policy firewall replacement. */
public function firewall($request, $response, $args)
{

@ -5,6 +5,7 @@ namespace App\Controllers;
use App\Services\AdminCsrf;
use App\Services\Auth;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAutomaticBackupService;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInstancePageService;
@ -136,6 +137,24 @@ final class CloudPageController
]);
}
public function backups($request, $response, $args)
{
$actor = CloudAccess::actor(false);
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
$page = $this->pageNumber(
$request->getQueryParams()['page'] ?? '1'
);
$payload = CloudAutomaticBackupService::library(
$actor,
['page' => $page, 'per_page' => 20]
);
$payload['user'] = $this->userBootstrap($user, $actor);
return $this->render($response, 'backups', '云备份', '', '', [
'cloud_backup_bootstrap_json' => $this->safeJson($payload),
]);
}
public function isoImages($request, $response, $args)
{
if (!CloudUserIsoFeature::enabled()) {
@ -299,6 +318,7 @@ final class CloudPageController
$smarty->assign('cloud_deploy_default_line_id', 0);
$smarty->assign('cloud_deploy_catalog_unavailable', false);
$smarty->assign('cloud_deploy_bootstrap_json', '{}');
$smarty->assign('cloud_backup_bootstrap_json', '{}');
$smarty->assign('cloud_ssh_keys', []);
$smarty->assign('cloud_ssh_keys_bootstrap_json', '{}');
$smarty->assign('cloud_reinstall_vm', []);

@ -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',
];
}

@ -13,6 +13,8 @@ final class CloudInstanceBackup extends Model
'source_instance_id' => 'int',
'source_host_id' => 'int',
'user_id' => 'int',
'subscription_id' => 'int',
'scheduled_for' => 'int',
'object_size_bytes' => 'int',
'virtual_size_bytes' => 'int',
'storage_revision' => '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',
];
}

@ -10,6 +10,7 @@ final class CloudJob extends Model
protected $casts = [
'backup_id' => 'int',
'backup_restore_id' => 'int',
'backup_recovery_id' => 'int',
];
/**

@ -12,6 +12,7 @@ final class CloudOffer extends Model
'plan_id' => 'int',
'resource_pool_id' => 'int',
'price' => 'decimal:2',
'backup_price' => 'decimal:2',
'price_version' => 'int',
'revision' => 'int',
'status' => 'boolean',
@ -44,21 +45,20 @@ final class CloudOffer extends Model
throw new \InvalidArgumentException('销售名称需为 1 至 128 个字符');
}
$price = $input['price'] ?? '';
if ((!is_string($price) && !is_int($price))
|| preg_match('/^\d{1,10}(?:\.\d{1,2})?$/D', (string) $price) !== 1) {
throw new \InvalidArgumentException('价格需为非负美元金额,最多两位小数');
}
$parts = explode('.', (string) $price);
$whole = ltrim($parts[0], '0');
$normalizedPrice = ($whole === '' ? '0' : $whole) . '.'
. str_pad($parts[1] ?? '', 2, '0');
$normalizedPrice = self::normalizePrice(
$input['price'] ?? '',
'实例价格'
);
$normalizedBackupPrice = self::normalizePrice(
$input['backup_price'] ?? '',
'自动备份价格'
);
$data = [
'resource_pool_id' => (int) $poolId,
'code' => $code,
'name' => $name,
'price' => $normalizedPrice,
'backup_price' => $normalizedBackupPrice,
'currency' => 'USD',
];
foreach ([
@ -79,4 +79,18 @@ final class CloudOffer extends Model
return $data;
}
private static function normalizePrice($value, string $label): string
{
if ((!is_string($value) && !is_int($value))
|| preg_match('/^\d{1,10}(?:\.\d{1,2})?$/D', (string) $value) !== 1) {
throw new \InvalidArgumentException(
$label . '需为非负美元金额,最多两位小数'
);
}
$parts = explode('.', (string) $value);
$whole = ltrim($parts[0], '0');
return ($whole === '' ? '0' : $whole) . '.'
. str_pad($parts[1] ?? '', 2, '0');
}
}

@ -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',
];
}

@ -1005,6 +1005,14 @@ final class CloudAdminOperationRecoveryService
if ($kind === 'backup_create') {
return self::BACKUP_PROJECTION;
}
if ($kind === 'backup_recover') {
return [
'backup_key' => 'string',
'sha256' => 'string',
'restored' => 'boolean',
'power_state' => 'string',
];
}
if (in_array($kind,
['snapshot_restore', 'snapshot_delete'], true)) {
return self::SNAPSHOT_MUTATION_PROJECTION;
@ -1083,6 +1091,9 @@ final class CloudAdminOperationRecoveryService
'backup_key', 'size_bytes', 'virtual_size_bytes', 'sha256',
'consistency',
],
'backup_recover' => [
'backup_key', 'sha256', 'restored', 'power_state',
],
'backup_restore' => [
'uuid', 'public_ip_cidr', 'public_pool_key', 'backup_key',
'sha256',

@ -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;
}
}

@ -3,6 +3,8 @@
namespace App\Services\Cloud;
use App\Models\CloudBackupRestore;
use App\Models\CloudBackupRecovery;
use App\Models\CloudBackupSubscription;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
@ -181,7 +183,13 @@ final class CloudBackupService
}
$backups = [];
$targetMap = [];
$manualActiveCount = 0;
foreach ($rows as $row) {
if ((string) $row->source === 'manual'
&& in_array((string) $row->state,
self::ACTIVE_BACKUP_STATES, true)) {
$manualActiveCount++;
}
$display = self::displayBackup(
$row,
$jobs[(string) $row->last_operation_id] ?? null,
@ -269,9 +277,7 @@ final class CloudBackupService
&& $supported
&& (bool) ($storage['ready'] ?? false);
$canCreate = $canOperate
&& count(array_filter($backups, static fn (array $backup): bool =>
in_array($backup['state'], self::ACTIVE_BACKUP_STATES, true)
)) < self::MAX_PER_INSTANCE;
&& $manualActiveCount < self::MAX_PER_INSTANCE;
$reason = null;
if (!$canManage) {
$reason = '当前管理员仅可查看,超级管理员才可以创建或恢复备份';
@ -420,7 +426,28 @@ final class CloudBackupService
public static function create(CloudInstance $instance, array $actor,
array $input): array
{
return self::createInternal($instance, $actor, $input, null);
return self::createInternal($instance, $actor, $input, null, null);
}
/** Queue one deterministic paid automatic backup for a scheduled slot. */
public static function createAutomatic(CloudInstance $instance,
CloudBackupSubscription $subscription, array $actor,
int $scheduledFor): array
{
if ($scheduledFor < 1) {
throw new CloudError('自动备份计划时间无效', 409);
}
$zone = new \DateTimeZone(CloudAutomaticBackupService::TIMEZONE);
$name = 'automatic-'
. (new \DateTimeImmutable('@' . $scheduledFor))
->setTimezone($zone)->format('Ymd-His');
return self::createInternal($instance, $actor, [
'name' => $name,
'consistency_mode' => 'filesystem',
], null, [
'subscription_id' => (int) $subscription->id,
'scheduled_for' => $scheduledFor,
]);
}
/** Begin one cold same-service maintenance migration. */
@ -445,13 +472,18 @@ final class CloudBackupService
], [
'target_host_id' => (int) $targetHostId,
'cleanup_mode' => (string) $cleanupMode,
]);
], null);
}
private static function createInternal(CloudInstance $instance, array $actor,
array $input, ?array $maintenance): array
array $input, ?array $maintenance, ?array $automatic): array
{
CloudAccess::manage($actor);
if ($automatic === null) {
CloudAccess::manage($actor);
} elseif ((int) ($actor['user_id'] ?? 0)
!== (int) $instance->user_id) {
throw new CloudError('无权为该实例创建自动备份', 403);
}
CloudInput::only($input, ['name', 'consistency_mode']);
$name = CloudInput::snapshotName($input['name'] ?? null);
$mode = CloudInput::snapshotConsistency(
@ -470,6 +502,13 @@ final class CloudBackupService
$canonicalRequest['maintenance_cleanup_mode'] =
(string) $maintenance['cleanup_mode'];
}
if ($automatic !== null) {
$canonicalRequest['source'] = 'automatic';
$canonicalRequest['subscription_id'] =
(int) $automatic['subscription_id'];
$canonicalRequest['scheduled_for'] =
(int) $automatic['scheduled_for'];
}
$fingerprint = CloudJobService::standaloneRequestFingerprint(
(int) $instance->host_id,
'backup_create',
@ -500,7 +539,7 @@ final class CloudBackupService
try {
return $instance->getConnection()->transaction(function () use (
$instance, $actor, $name, $mode, $runtime, $requestTarget,
$canonicalRequest, $fingerprint, $maintenance,
$canonicalRequest, $fingerprint, $maintenance, $automatic,
&$plan, &$objectKey, &$bundlePlans
): array {
$locked = CloudInstance::where('id', (int) $instance->id)
@ -518,9 +557,50 @@ final class CloudBackupService
return ['backup' => self::displayBackup($backup, $prior),
'job' => $prior];
}
$automaticSubscription = null;
if ($automatic !== null) {
$automaticSubscription = CloudBackupSubscription::where(
'id', (int) $automatic['subscription_id']
)->lockForUpdate()->first();
$spec = self::decodeSpec((string) $locked->spec_json);
if ($automaticSubscription === null
|| !(bool) $automaticSubscription->enabled
|| (int) $automaticSubscription->instance_id
!== (int) $locked->id
|| (int) $automaticSubscription->user_id
!== (int) $locked->user_id
|| ($spec['automatic_backup'] ?? null) !== true) {
throw new CloudError('自动备份订阅与实例账本不一致', 409);
}
$existing = CloudInstanceBackup::where(
'subscription_id', (int) $automaticSubscription->id
)->where('scheduled_for',
(int) $automatic['scheduled_for'])->first();
if ($existing !== null) {
$job = CloudJob::where('kind', 'backup_create')
->where('backup_id', (int) $existing->id)
->orderByDesc('id')->first();
if ($job === null) {
throw new CloudError('自动备份计划账本不完整', 409);
}
CloudAutomaticBackupService::advanceAfterScheduled(
$automaticSubscription,
(int) $automatic['scheduled_for'],
(int) $existing->id
);
return [
'backup' => self::displayBackup($existing, $job),
'job' => $job,
];
}
}
if ((string) $locked->status !== 'active') {
throw new CloudError('只有活动实例可以创建备份', 409);
}
if ($automatic !== null
&& (string) $locked->service_status !== 'active') {
throw new CloudError('实例服务当前不可创建自动备份', 409);
}
self::assertManagedSource($locked);
self::assertNoActiveJob($locked);
$snapshots = [];
@ -538,14 +618,29 @@ final class CloudBackupService
)
);
}
$used = CloudInstanceBackup::where(
$usedQuery = CloudInstanceBackup::where(
'source_instance_id', (int) $locked->id
)->where('purpose', 'portable')
->whereIn('state', self::ACTIVE_BACKUP_STATES)->count('id');
if ($maintenance === null
&& (int) $used >= self::MAX_PER_INSTANCE) {
->whereIn('state', self::ACTIVE_BACKUP_STATES);
if ($automatic === null) {
$usedQuery->where('source', 'manual');
} else {
$usedQuery->where('source', 'automatic')
->where('subscription_id',
(int) $automaticSubscription->id);
}
$used = (int) $usedQuery->count('id');
if ($maintenance === null && $automatic === null
&& $used >= self::MAX_PER_INSTANCE) {
throw new CloudError('每台实例最多保留十个有效备份', 409);
}
if ($automatic !== null
&& $used >= min(
CloudAutomaticBackupService::MAX_RETENTION,
max(1, (int) $automaticSubscription->retention_count)
) + 1) {
throw new CloudError('自动备份正在等待旧备份安全清理', 409);
}
$spec = self::freezeRestoreCompatibility(
self::decodeSpec((string) $locked->spec_json)
);
@ -603,6 +698,12 @@ final class CloudBackupService
$backup->name = $name;
$backup->purpose = $maintenance === null
? 'portable' : 'migration_bundle';
$backup->source = $automatic === null
? 'manual' : 'automatic';
$backup->subscription_id = $automatic === null ? null
: (int) $automaticSubscription->id;
$backup->scheduled_for = $automatic === null ? null
: (int) $automatic['scheduled_for'];
$backup->state = 'creating';
$backup->consistency = $mode;
$backup->object_key = $objectKey;
@ -658,6 +759,13 @@ final class CloudBackupService
$backup->last_operation_id = (string) $job->operation_id;
$backup->updated_at = time();
$backup->save();
if ($automaticSubscription !== null) {
CloudAutomaticBackupService::advanceAfterScheduled(
$automaticSubscription,
(int) $automatic['scheduled_for'],
(int) $backup->id
);
}
if ($maintenance !== null) {
$migration = CloudInstanceMigrationService::createLedgerLocked(
$locked,
@ -922,6 +1030,174 @@ final class CloudBackupService
}, 3);
}
/**
* Build the short-lived download capability for a paid create order.
* The caller must already hold and validate the owner/order row locks;
* signing is local and therefore does not extend that transaction across
* a remote object-storage request.
*
* @return array{source_url:string}
*/
public static function provisioningSource(
CloudInstanceBackup $backup
): array {
if ((string) $backup->purpose !== 'portable'
|| (string) $backup->state !== 'ready'
|| (int) $backup->object_size_bytes < 1
|| preg_match('/^[a-f0-9]{64}$/D',
(string) $backup->sha256) !== 1) {
throw new CloudError('云备份尚未处于可创建实例状态', 409);
}
$runtime = self::storageRuntime($backup);
return [
'source_url' => (new CloudObjectStorageS3Client())->presignedGet(
$runtime['config'],
$runtime['credentials'],
(string) $backup->object_key,
self::TRANSFER_URL_SECONDS
),
];
}
/** Replace an owner's existing system disk from its own automatic backup. */
public static function recover(CloudInstance $instance,
CloudInstanceBackup $backup, array $actor, array $input): array
{
if ((int) ($actor['user_id'] ?? 0) !== (int) $instance->user_id) {
throw new CloudError('无权恢复该实例', 403);
}
CloudInput::only($input, ['confirm_restore']);
if (($input['confirm_restore'] ?? false) !== true) {
throw new CloudError('请确认恢复会覆盖当前系统盘内容');
}
$requestKey = $actor['request_idempotency_key'] ?? null;
if (!is_string($requestKey) || $requestKey === '') {
throw new CloudError('恢复云备份必须提供请求幂等标识', 400);
}
self::assertRecoverableAutomaticBackup($instance, $backup);
$target = '/v1/vms/' . rawurlencode((string) $instance->uuid)
. '/recover-backup';
$canonical = [
'instance_id' => (int) $instance->id,
'backup_id' => (int) $backup->id,
'confirm_restore' => true,
];
$fingerprint = CloudJobService::standaloneRequestFingerprint(
(int) $instance->host_id,
'backup_recover',
'POST',
$target,
$canonical
);
$prior = self::priorJob($actor, 'backup_recover',
(int) $instance->id, (int) $backup->id, $fingerprint, false);
if ($prior !== null) {
return self::priorRecoveryResult($prior);
}
$runtime = self::storageRuntime($backup);
$object = (new CloudObjectStorageS3Client())->headObject(
$runtime['config'], $runtime['credentials'],
(string) $backup->object_key
);
if ((int) $object['size_bytes'] !== (int) $backup->object_size_bytes) {
throw new CloudError('备份对象大小与目录记录不一致,不能恢复', 409);
}
$sourceUrl = (new CloudObjectStorageS3Client())->presignedGet(
$runtime['config'], $runtime['credentials'],
(string) $backup->object_key, self::TRANSFER_URL_SECONDS
);
return $instance->getConnection()->transaction(function () use (
$instance, $backup, $actor, $target, $canonical, $fingerprint,
$sourceUrl
): array {
$lockedInstance = CloudInstance::where(
'id', (int) $instance->id
)->lockForUpdate()->first();
$lockedBackup = CloudInstanceBackup::where(
'id', (int) $backup->id
)->lockForUpdate()->first();
if ($lockedInstance === null || $lockedBackup === null) {
throw new CloudError('实例或云备份不存在', 404);
}
self::assertRecoverableAutomaticBackup(
$lockedInstance, $lockedBackup
);
$prior = self::priorJob($actor, 'backup_recover',
(int) $lockedInstance->id, (int) $lockedBackup->id,
$fingerprint);
if ($prior !== null) {
return self::priorRecoveryResult($prior);
}
if ((string) $lockedInstance->status !== 'active'
|| (string) $lockedInstance->service_status !== 'active') {
throw new CloudError('只有服务正常的活动实例可以恢复云备份', 409);
}
self::assertNoActiveJob($lockedInstance);
if (CloudBackupRecovery::where(
'instance_id', (int) $lockedInstance->id
)->whereIn('state', ['recovering', 'uncertain'])->exists()) {
throw new CloudError('实例已有恢复任务或未确认效果', 409);
}
$operationId = bin2hex(random_bytes(16));
$recoveryKey = bin2hex(random_bytes(16));
$now = time();
$recovery = new CloudBackupRecovery();
$recovery->recovery_key = $recoveryKey;
$recovery->backup_id = (int) $lockedBackup->id;
$recovery->instance_id = (int) $lockedInstance->id;
$recovery->job_id = null;
$recovery->operation_id = $operationId;
$recovery->state = 'recovering';
$recovery->error_code = '';
$recovery->completed_at = null;
$recovery->created_at = $recovery->updated_at = $now;
$recovery->save();
$body = [
'backup_key' => (string) $lockedBackup->backup_key,
'source_url' => $sourceUrl,
'source_size_bytes' => (int) $lockedBackup->object_size_bytes,
'source_sha256' => (string) $lockedBackup->sha256,
];
$jobActor = $actor;
$jobActor['can_manage'] = true;
[$job, $created] = CloudJobService::
reserveStandaloneAgentMutation(
$jobActor,
(int) $lockedInstance->host_id,
'backup_recover',
'POST',
$target,
$body,
[
'owner_id' => (int) $lockedInstance->user_id,
'can_manage' => true,
'backup_key' => (string) $lockedBackup->backup_key,
'recovery_key' => $recoveryKey,
],
$canonical,
$operationId
);
if (!$created) {
throw new CloudError('云备份恢复幂等任务状态冲突', 409);
}
$job->instance_id = (int) $lockedInstance->id;
$job->backup_id = (int) $lockedBackup->id;
$job->backup_recovery_id = (int) $recovery->id;
$job->save();
$recovery->job_id = (int) $job->id;
$recovery->updated_at = time();
$recovery->save();
return [
'recovery' => self::displayRecovery($recovery),
'job' => $job,
];
}, 3);
}
/** Apply a terminal/running Agent result inside CloudWorkerService's lock. */
public static function finishJobLocked(CloudJob $job, string $status,
$result, array $payload): void
@ -930,6 +1206,8 @@ final class CloudBackupService
self::finishCreateLocked($job, $status, $result, $payload);
} elseif ($job->kind === 'backup_restore') {
self::finishRestoreLocked($job, $status, $result, $payload);
} elseif ($job->kind === 'backup_recover') {
self::finishRecoveryLocked($job, $status, $result, $payload);
}
}
@ -946,6 +1224,13 @@ final class CloudBackupService
->where('operation_id', (string) $job->operation_id)
->update(['state' => 'uncertain', 'error_code' =>
'finalization_incident', 'updated_at' => time()]);
} elseif ($job->kind === 'backup_recover'
&& $job->backup_recovery_id !== null) {
CloudBackupRecovery::where(
'id', (int) $job->backup_recovery_id
)->where('operation_id', (string) $job->operation_id)
->update(['state' => 'uncertain', 'error_code' =>
'finalization_incident', 'updated_at' => time()]);
}
CloudInstanceMigrationService::markJobUncertain($job);
}
@ -1125,6 +1410,175 @@ final class CloudBackupService
$restore->save();
}
private static function finishRecoveryLocked(CloudJob $job,
string $status, $result, array $payload): void
{
$recovery = $job->backup_recovery_id === null ? null
: CloudBackupRecovery::where(
'id', (int) $job->backup_recovery_id
)->lockForUpdate()->first();
$backup = $job->backup_id === null ? null
: CloudInstanceBackup::where('id', (int) $job->backup_id)
->lockForUpdate()->first();
$instance = $job->instance_id === null ? null
: CloudInstance::where('id', (int) $job->instance_id)
->lockForUpdate()->first();
$body = is_array($payload['body'] ?? null)
? $payload['body'] : [];
if ($recovery === null || $backup === null || $instance === null
|| (int) $recovery->job_id !== (int) $job->id
|| (int) $recovery->backup_id !== (int) $backup->id
|| (int) $recovery->instance_id !== (int) $instance->id
|| !hash_equals((string) $recovery->operation_id,
(string) $job->operation_id)
|| !hash_equals((string) $recovery->recovery_key,
(string) ($payload['recovery_key'] ?? ''))
|| !hash_equals((string) $backup->backup_key,
(string) ($payload['backup_key'] ?? ''))
|| !hash_equals((string) $backup->backup_key,
(string) ($body['backup_key'] ?? ''))
|| !hash_equals((string) $backup->sha256,
(string) ($body['source_sha256'] ?? ''))
|| (int) $backup->object_size_bytes
!== (int) ($body['source_size_bytes'] ?? 0)
|| (int) $instance->user_id
!== (int) ($payload['owner_id'] ?? 0)
|| (int) $job->user_id !== (int) $instance->user_id
|| (int) $job->host_id !== (int) $instance->host_id) {
throw new CloudRecoveryInstanceStateConflict(
'云备份恢复任务与实例、备份或恢复账本不一致',
409
);
}
if ($status === 'running') {
return;
}
$now = time();
if ($status === 'uncertain') {
$recovery->state = 'uncertain';
$recovery->error_code = 'operation_effect_unknown';
$recovery->completed_at = null;
} elseif ($status === 'failed') {
$recovery->state = 'failed';
$recovery->error_code = 'backup_recovery_failed';
$recovery->completed_at = $now;
} elseif ($status === 'succeeded') {
if (!is_array($result)
|| ($result['restored'] ?? null) !== true
|| !hash_equals((string) $backup->backup_key,
(string) ($result['backup_key'] ?? ''))
|| !hash_equals((string) $backup->sha256,
(string) ($result['sha256'] ?? ''))
|| CloudInstanceRuntimeService::normalizeState(
$result['power_state'] ?? null
) === 'unknown') {
throw new CloudError(
'Agent 恢复成功结果缺少可信的备份或电源身份',
502
);
}
$backupSpec = self::decodeSpec((string) $backup->spec_json);
if (($backupSpec['managed'] ?? null) !== true
|| ($backupSpec['os_source'] ?? null) !== 'cloud_template'
|| !is_string($backupSpec['os_name'] ?? null)
|| trim((string) $backupSpec['os_name']) === ''
|| ($backupSpec['login_name'] ?? null) !== 'root'
|| !is_bool($backupSpec['debian_12_network_fix'] ?? null)) {
throw new CloudRecoveryInstanceStateConflict(
'云备份的客户机身份快照无效',
409
);
}
$instanceSpec = self::decodeSpec((string) $instance->spec_json);
foreach ([
'template_id', 'template_revision',
'template_generation_token', 'os_source', 'os_name',
'login_name', 'debian_12_network_fix', 'guest_hostname',
] as $field) {
if (array_key_exists($field, $backupSpec)) {
$instanceSpec[$field] = $backupSpec[$field];
} else {
unset($instanceSpec[$field]);
}
}
unset($instanceSpec['install_iso']);
$instanceSpec['managed'] = true;
$instanceSpec['restored_from_backup'] =
(string) $backup->backup_key;
$instance->spec_json = json_encode(
CloudInput::safeResult($instanceSpec),
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
// The restored disk contains the backup-time guest credentials.
// Retaining a newer panel credential would mislead the owner and
// can leave them unable to log in after a successful rollback.
$instance->sealed_credential = $backup->sealed_credential;
$instance->updated_at = $now;
$instance->save();
$recovery->state = 'succeeded';
$recovery->error_code = '';
$recovery->completed_at = $now;
self::recordRuntime($instance, $result);
}
$recovery->updated_at = $now;
$recovery->save();
}
private static function assertRecoverableAutomaticBackup(
CloudInstance $instance, CloudInstanceBackup $backup
): void {
if ((int) $backup->user_id !== (int) $instance->user_id
|| (int) $backup->source_instance_id !== (int) $instance->id
|| (string) $backup->source_uuid
!== strtolower((string) $instance->uuid)
|| (string) $backup->purpose !== 'portable'
|| (string) $backup->source !== 'automatic'
|| $backup->subscription_id === null) {
throw new CloudError('云备份不属于该实例的自动备份', 404);
}
$subscription = CloudBackupSubscription::where(
'id', (int) $backup->subscription_id
)->first();
if ($subscription === null
|| (int) $subscription->instance_id !== (int) $instance->id
|| (int) $subscription->user_id !== (int) $instance->user_id) {
throw new CloudError('云备份订阅账本不一致', 409);
}
if ((string) $backup->state !== 'ready'
|| (int) $backup->object_size_bytes < 1
|| preg_match('/^[a-f0-9]{64}$/D',
(string) $backup->sha256) !== 1) {
throw new CloudError('云备份尚未处于可恢复状态', 409);
}
}
private static function priorRecoveryResult(CloudJob $job): array
{
$recovery = $job->backup_recovery_id === null ? null
: CloudBackupRecovery::find((int) $job->backup_recovery_id);
if ($recovery === null) {
throw new CloudError('云备份恢复任务目录记录缺失', 409);
}
return [
'recovery' => self::displayRecovery($recovery),
'job' => $job,
];
}
private static function displayRecovery(CloudBackupRecovery $recovery): array
{
return [
'recovery_key' => (string) $recovery->recovery_key,
'backup_id' => (string) $recovery->backup_id,
'instance_id' => (string) $recovery->instance_id,
'state' => (string) $recovery->state,
'created_at' => max(0, (int) $recovery->created_at),
'completed_at' => $recovery->completed_at === null ? null
: max(0, (int) $recovery->completed_at),
];
}
private static function assertManagedSource(CloudInstance $instance): void
{
$spec = self::decodeSpec((string) $instance->spec_json);
@ -1160,6 +1614,10 @@ final class CloudBackupService
->whereIn('state', ['restoring', 'uncertain'])->exists()) {
throw new CloudError('备份仍有恢复任务或未知效果,不能删除', 409);
}
if (CloudBackupRecovery::where('backup_id', (int) $backup->id)
->whereIn('state', ['recovering', 'uncertain'])->exists()) {
throw new CloudError('备份仍有原实例恢复任务或未知效果,不能删除', 409);
}
if (CloudJob::where('backup_id', (int) $backup->id)
->where(static function ($query): void {
$query->where('phase', '<>', 'terminal')

@ -45,6 +45,7 @@ final class CloudDeploymentPageService
->get([
'offer.id as offer_id', 'offer.name as offer_name',
'offer.price as offer_price', 'offer.stock as offer_stock',
'offer.backup_price',
'plan.cpu_cores', 'plan.memory_mib', 'plan.bandwidth_mbps',
'plan.disk_gib', 'plan.validity_days', 'plan.traffic_quota_bytes',
'pool.id as internal_pool_id',
@ -101,6 +102,12 @@ final class CloudDeploymentPageService
'id' => (int) $row->offer_id,
'name' => trim((string) $row->offer_name),
'price' => number_format((float) $row->offer_price, 2, '.', ''),
'backup_price' => number_format(
(float) $row->backup_price,
2,
'.',
''
),
'currency' => 'USD',
'region_id' => $regionId,
'line_id' => $lineId,

@ -225,8 +225,10 @@ final class CloudInvoicePaymentService
if ($instance->expires_at === null
|| (int) $instance->expires_at !== (int) $current->renews_expires_at
|| $instance->renewal_price === null
|| CloudMoney::cents((string) $instance->renewal_price)
!== CloudMoney::cents((string) $current->amount)
|| !CloudInvoiceService::renewalInvoiceMatches(
$instance,
$current
)
|| (int) $instance->renewal_days !== (int) $current->validity_days
|| (int) $instance->renewal_traffic_bytes
!== (int) $current->traffic_quota_bytes) {
@ -402,8 +404,10 @@ final class CloudInvoicePaymentService
|| $instance->expires_at === null
|| (int) $instance->expires_at !== (int) $invoice->renews_expires_at
|| $instance->renewal_price === null
|| CloudMoney::cents((string) $instance->renewal_price)
!== CloudMoney::cents((string) $invoice->amount)
|| !CloudInvoiceService::renewalInvoiceMatches(
$instance,
$invoice
)
|| (int) $instance->renewal_days !== (int) $invoice->validity_days
|| (int) $instance->renewal_traffic_bytes
!== (int) $invoice->traffic_quota_bytes) {

@ -2,11 +2,14 @@
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudBackupSubscription;
use App\Models\CloudInvoice;
use App\Models\CloudInvoiceItem;
use App\Models\CloudInvoicePayment;
use App\Models\CloudMailOutbox;
use App\Models\CloudOffer;
use App\Models\CloudOrder;
use App\Models\CloudOrderItem;
use App\Models\CloudRenewal;
use App\Models\CloudJob;
use App\Models\Shop;
@ -79,6 +82,24 @@ final class CloudInvoiceService
|| trim((string) $order->sealed_payload) === '') {
throw new CloudError('开通订单状态无效', 409);
}
$orderItems = CloudOrderItem::where('order_id', (int) $order->id)
->orderBy('id')->get();
$itemTotal = 0;
$codes = [];
foreach ($orderItems as $orderItem) {
$code = (string) $orderItem->code;
if (!in_array($code, ['instance', 'automatic_backup'], true)
|| isset($codes[$code])
|| strtoupper((string) $orderItem->currency) !== 'USD') {
throw new CloudError('开通订单费用明细无效', 409);
}
$codes[$code] = true;
$itemTotal += CloudMoney::cents((string) $orderItem->amount);
}
if (!isset($codes['instance'])
|| $itemTotal !== CloudMoney::cents((string) $order->amount)) {
throw new CloudError('开通订单费用明细合计不一致', 409);
}
$invoice = new CloudInvoice();
$invoice->invoice_no = self::invoiceNumber();
$invoice->purpose = 'provision';
@ -101,6 +122,18 @@ final class CloudInvoiceService
$invoice->paid_at = null;
$invoice->created_at = $invoice->updated_at = $now;
$invoice->save();
foreach ($orderItems as $orderItem) {
$item = new CloudInvoiceItem();
$item->invoice_id = (int) $invoice->id;
$item->order_item_id = (int) $orderItem->id;
$item->code = (string) $orderItem->code;
$item->label = (string) $orderItem->label;
$item->amount = (string) $orderItem->amount;
$item->currency = (string) $orderItem->currency;
$item->snapshot_json = (string) $orderItem->snapshot_json;
$item->created_at = $now;
$item->save();
}
return $invoice;
}
@ -267,9 +300,8 @@ final class CloudInvoiceService
}
}
$amount = CloudMoney::decimal(
CloudMoney::cents((string) $instance->renewal_price)
);
$quote = self::renewalQuoteLocked($instance);
$amount = CloudMoney::decimal($quote['total_cents']);
$matchesFinalSnapshot = static function ($candidate) use (
$instance,
$amount
@ -279,6 +311,7 @@ final class CloudInvoiceService
&& (int) $candidate->plan_id === (int) $instance->plan_id
&& CloudMoney::cents((string) $candidate->amount)
=== CloudMoney::cents($amount)
&& self::renewalInvoiceMatches($instance, $candidate)
&& (int) $candidate->validity_days
=== (int) $instance->renewal_days
&& (int) $candidate->traffic_quota_bytes
@ -316,6 +349,7 @@ final class CloudInvoiceService
int $dueAt,
int $now
): CloudInvoice {
$quote = self::renewalQuoteLocked($instance);
$invoice = new CloudInvoice();
$invoice->invoice_no = self::invoiceNumber();
$invoice->purpose = 'renewal';
@ -326,9 +360,7 @@ final class CloudInvoiceService
$invoice->renewal_id = null;
$invoice->renews_expires_at = (int) $instance->expires_at;
$invoice->due_at = $dueAt;
$invoice->amount = CloudMoney::decimal(
CloudMoney::cents((string) $instance->renewal_price)
);
$invoice->amount = CloudMoney::decimal($quote['total_cents']);
$invoice->currency = 'USD';
$invoice->validity_days = (int) $instance->renewal_days;
$invoice->traffic_quota_bytes =
@ -339,10 +371,149 @@ final class CloudInvoiceService
$invoice->paid_at = null;
$invoice->created_at = $invoice->updated_at = $now;
$invoice->save();
self::createRenewalItems($invoice, $instance, $quote, $now);
self::enqueueMail($invoice, 'renewal_due', $now);
return $invoice;
}
/**
* Compose one renewal from the immutable instance base price and its paid
* automatic-backup subscription. Callers already hold the instance row.
*
* @return array{instance_cents:int,backup_cents:int,total_cents:int,
* backup_subscription_id:?int}
*/
public static function renewalQuoteLocked(
CloudInstance $instance
): array {
$instanceCents = $instance->renewal_price === null
? -1 : CloudMoney::cents((string) $instance->renewal_price);
if ($instanceCents < 0) {
throw new CloudError('实例缺少基础续费价格快照', 409);
}
$spec = json_decode((string) $instance->spec_json, true);
if (!is_array($spec) || array_is_list($spec)) {
throw new CloudError('实例计费快照损坏', 409);
}
$entitled = ($spec['automatic_backup'] ?? null) === true;
if (!$entitled) {
return [
'instance_cents' => $instanceCents,
'backup_cents' => 0,
'total_cents' => $instanceCents,
'backup_subscription_id' => null,
];
}
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->lockForUpdate()->first();
if ($subscription === null) {
throw new CloudError('实例自动备份订阅账本缺失', 409);
}
if ($subscription !== null
&& ((int) $subscription->user_id !== (int) $instance->user_id
|| (int) $subscription->offer_id !== (int) $instance->offer_id
|| strtoupper((string) $subscription->currency) !== 'USD'
|| !(bool) $subscription->enabled
|| !(bool) $subscription->renew_next_period)) {
throw new CloudError('实例自动备份订阅账本不一致', 409);
}
$backupCents = CloudMoney::cents((string) $subscription->price);
return [
'instance_cents' => $instanceCents,
'backup_cents' => $backupCents,
'total_cents' => $instanceCents + $backupCents,
'backup_subscription_id' => (int) $subscription->id,
];
}
public static function renewalInvoiceMatches(
CloudInstance $instance,
CloudInvoice $invoice
): bool {
try {
$quote = self::renewalQuoteLocked($instance);
} catch (\Throwable $error) {
return false;
}
if ((string) $invoice->purpose !== 'renewal'
|| CloudMoney::cents((string) $invoice->amount)
!== $quote['total_cents']) {
return false;
}
$items = CloudInvoiceItem::where(
'invoice_id', (int) $invoice->id
)->orderBy('id')->get();
$amounts = [];
foreach ($items as $item) {
$code = (string) $item->code;
if (isset($amounts[$code])
|| !in_array($code,
['instance', 'automatic_backup'], true)
|| strtoupper((string) $item->currency) !== 'USD') {
return false;
}
$amounts[$code] = CloudMoney::cents(
(string) $item->amount
);
}
return ($amounts['instance'] ?? -1) === $quote['instance_cents']
&& ($amounts['automatic_backup'] ?? 0)
=== $quote['backup_cents']
&& (($quote['backup_subscription_id'] === null)
=== !array_key_exists('automatic_backup', $amounts));
}
private static function createRenewalItems(
CloudInvoice $invoice,
CloudInstance $instance,
array $quote,
int $now
): void {
$rows = [[
'code' => 'instance',
'label' => '实例套餐续费',
'amount' => $quote['instance_cents'],
'snapshot' => [
'instance_id' => (int) $instance->id,
'plan_id' => (int) $instance->plan_id,
'validity_days' => (int) $instance->renewal_days,
],
]];
if ($quote['backup_subscription_id'] !== null) {
$rows[] = [
'code' => 'automatic_backup',
'label' => '自动备份续费',
'amount' => $quote['backup_cents'],
'snapshot' => [
'subscription_id' =>
$quote['backup_subscription_id'],
'validity_days' => (int) $instance->renewal_days,
],
];
}
$total = 0;
foreach ($rows as $row) {
$item = new CloudInvoiceItem();
$item->invoice_id = (int) $invoice->id;
$item->order_item_id = null;
$item->code = $row['code'];
$item->label = $row['label'];
$item->amount = CloudMoney::decimal($row['amount']);
$item->currency = 'USD';
$item->snapshot_json = json_encode(
$row['snapshot'],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$item->created_at = $now;
$item->save();
$total += $row['amount'];
}
if ($total !== $quote['total_cents']) {
throw new \RuntimeException('续费账单费用明细合计不一致');
}
}
/** Queue one idempotent notification after a paid instance is available. */
public static function queueProvisionSucceeded(CloudInvoice $invoice,
int $now): bool
@ -1007,6 +1178,16 @@ final class CloudInvoiceService
(string) ($job->kind ?? 'create'), (string) $jobStatus,
$job->error_code, true
);
$items = CloudInvoiceItem::where('invoice_id', (int) $invoice->id)
->orderBy('id')->get([
'id', 'code', 'label', 'amount', 'currency',
])->map(static fn (CloudInvoiceItem $item): array => [
'id' => (string) $item->id,
'code' => (string) $item->code,
'label' => (string) $item->label,
'amount' => (string) $item->amount,
'currency' => (string) $item->currency,
])->all();
return [
'id' => (string) $invoice->id,
'title' => $title,
@ -1054,6 +1235,7 @@ final class CloudInvoiceService
'error' => $jobError,
] : null,
'amount' => (string) $invoice->amount,
'items' => $items,
'validity_days' => (int) $invoice->validity_days,
'service_days' => (int) $invoice->validity_days,
'traffic_quota_bytes' => (int) $invoice->traffic_quota_bytes,
@ -1258,7 +1440,7 @@ final class CloudInvoiceService
|| (int) $instance->user_id !== (int) $user->id
|| $instance->expires_at === null
|| (int) $instance->expires_at !== (int) $invoice->renews_expires_at
|| CloudMoney::cents((string) $instance->renewal_price) !== CloudMoney::cents((string) $invoice->amount)
|| !self::renewalInvoiceMatches($instance, $invoice)
|| (int) $instance->renewal_days !== (int) $invoice->validity_days
|| (int) $instance->renewal_traffic_bytes !== (int) $invoice->traffic_quota_bytes) {
$invoice->status = 'void';

@ -41,6 +41,7 @@ final class CloudJobService
private const PORTABLE_BACKUP_KINDS = [
'backup_create',
'backup_restore',
'backup_recover',
];
private const AGGREGATE_KINDS = [
'template_import',

@ -52,6 +52,26 @@ final class CloudLifecycleService
// Invoice creation is database-only and must not stop policy.
error_log('cloud invoice generation unavailable: ' . get_class($error));
}
$queued = 0;
$automaticLimit = max(1, min(10, $batchSize));
$this->heartbeat?->busy('automatic_backup_schedule');
try {
$queued += CloudAutomaticBackupService::scheduleDue(
$automaticLimit
);
} catch (\Throwable $error) {
$this->observeFailure('automatic_backup_schedule_failed');
error_log('cloud automatic backup schedule unavailable: '
. get_class($error));
}
$this->heartbeat?->busy('automatic_backup_retention');
try {
CloudAutomaticBackupService::pruneRetention($automaticLimit);
} catch (\Throwable $error) {
$this->observeFailure('automatic_backup_retention_failed');
error_log('cloud automatic backup retention unavailable: '
. get_class($error));
}
$this->heartbeat?->busy('traffic_sync');
try {
$collection = CloudTrafficService::collect($batchSize);
@ -77,7 +97,6 @@ final class CloudLifecycleService
$this->observeFailure('runtime_status_sync_failed');
error_log('cloud runtime status sync unavailable: ' . get_class($error));
}
$queued = 0;
$this->heartbeat?->busy('instance_reconcile');
CloudInstance::where('status', '<>', 'deleted')
->where('service_status', '<>', 'exempt')

@ -26,6 +26,7 @@ final class CloudOperationCatalog
'snapshot_delete' => '删除快照',
'backup_create' => '创建可移植备份',
'backup_restore' => '从备份创建实例',
'backup_recover' => '从云备份恢复实例',
'instance_migration_cleanup' => '清理维护迁移源副本',
'instance_migration_rollback' => '恢复维护迁移源实例',
'instance_migration_activate' => '恢复维护迁移目标状态',
@ -71,6 +72,7 @@ final class CloudOperationCatalog
'snapshot_delete',
'backup_create',
'backup_restore',
'backup_recover',
'instance_migration_cleanup',
'instance_migration_rollback',
'instance_migration_activate',

@ -504,6 +504,9 @@ final class CloudOperationErrorCatalog
'snapshot_create' => '创建快照失败;任务已结束且不会自动重试',
'snapshot_restore' => '恢复快照失败;任务已结束且不会自动重试',
'snapshot_delete' => '删除快照失败;任务已结束且不会自动重试',
'backup_create' => '创建云备份失败;任务已结束且不会自动重试',
'backup_restore' => '从备份创建实例失败;任务已结束且不会自动重试',
'backup_recover' => '从云备份恢复实例失败;任务已结束且不会自动重试',
'firewall_apply' => '防火墙应用失败;任务已结束且不会自动重试',
'service_suspend', 'network_suspend', 'network_resume'
=> '实例策略执行失败;本次任务不会自动重试',

@ -119,6 +119,13 @@ final class CloudOperationRecoveryContract
'action_patterns' => ['^create-backup:[a-f0-9]{32}:(?:filesystem|crash)$'],
'system_resolutions' => ['applied', 'not_applied'],
],
'backup_recover' => [
'recovery_mode' => 'generic',
'identity_scope' => 'instance',
'actions' => [],
'action_patterns' => ['^recover-backup:[a-f0-9]{32}:[a-f0-9]{64}$'],
'system_resolutions' => ['applied', 'not_applied'],
],
'firewall_apply' => [
'recovery_mode' => 'generic',
'identity_scope' => 'instance',
@ -200,7 +207,7 @@ final class CloudOperationRecoveryContract
'recovery_mode' => 'create',
'identity_scope' => 'create',
'actions' => ['create-vm'],
'action_patterns' => [],
'action_patterns' => ['^restore-backup:[a-f0-9]{32}$'],
'system_resolutions' => ['not_applied'],
],
'backup_restore' => [

@ -9,8 +9,10 @@ use App\Models\CloudInstanceFirewallVersion;
use App\Models\CloudInstanceSnapshot;
use App\Models\CloudMigrationBundleArtifact;
use App\Models\CloudBackupRestore;
use App\Models\CloudBackupRecovery;
use App\Models\CloudHostStorageConfiguration;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudPublicIp;
use App\Models\CloudResourceReservation;
use App\Models\CloudRescueTemplateDeletion;
@ -330,6 +332,9 @@ final class CloudOperationRecoveryIdentity
'backup_restore' => self::backupRestoreAction(
$job, $payload, $instance, $method, $target, $base, $body
),
'backup_recover' => self::backupRecoverAction(
$job, $payload, $instance, $method, $target, $base, $body
),
'firewall_apply' => self::firewallAction(
$job, $payload, $instance, $method, $target, $base, $body
),
@ -495,6 +500,31 @@ final class CloudOperationRecoveryIdentity
array $body,
bool $forAppliedEffect
): array {
$backupProvision = array_key_exists('backup_metadata', $payload)
|| $job->backup_id !== null;
if ($backupProvision) {
$order = $job->order_id === null ? null
: CloudOrder::find((int) $job->order_id);
$orderSpec = $order === null ? null
: json_decode((string) $order->spec_json, true);
if ($order === null || !is_array($orderSpec)
|| array_is_list($orderSpec)
|| ($orderSpec['source'] ?? null) !== 'backup') {
self::invalidPayload(
'从云备份创建实例缺少可信订单快照'
);
}
return self::backupProvisionIdentity(
$job,
$payload,
$method,
$target,
$body,
$order,
$orderSpec,
$forAppliedEffect
);
}
self::expectRequest($method, $target, 'POST', '/v1/vms');
self::assertAllowedBody($body, [
'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu',
@ -570,6 +600,111 @@ final class CloudOperationRecoveryIdentity
return ['create-vm', $resourceId];
}
private static function backupProvisionIdentity(
CloudJob $job,
array $payload,
string $method,
string $target,
array $body,
CloudOrder $order,
array $orderSpec,
bool $forAppliedEffect
): array {
$resourceId = self::operationUuid((string) $job->operation_id);
self::expectRequest(
$method,
$target,
'POST',
'/v1/vms/' . rawurlencode($resourceId) . '/restore-backup'
);
self::assertAllowedBody($body, [
'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu',
'memory_mib', 'disk_gib', 'bandwidth_mbps', 'network',
'template_id', 'template_revision', 'template_generation_token',
'startup_script', 'hostname', 'guest_ssh_public_key',
'root_password', 'public_pool_key', 'public_pool_cidr',
'public_ip_cidr', 'gateway', 'dns_servers',
'platform_network_policy_snapshot', 'debian_12_network_fix',
'backup_key', 'source_url', 'source_size_bytes', 'source_sha256',
]);
$backup = $job->backup_id === null ? null
: CloudInstanceBackup::find((int) $job->backup_id);
$backupMetadata = $payload['backup_metadata'] ?? null;
$integers = ['vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps'];
foreach ($integers as $field) {
if (filter_var(
$body[$field] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
) === false) {
self::invalidPayload('从云备份创建实例的资源规格无效');
}
}
if ($backup === null
|| (int) $order->user_id !== (int) $job->user_id
|| (int) $backup->user_id !== (int) $job->user_id
|| (int) ($orderSpec['backup_id'] ?? 0) !== (int) $backup->id
|| !is_array($backupMetadata) || array_is_list($backupMetadata)
|| (int) ($backupMetadata['backup_id'] ?? 0) !== (int) $backup->id
|| !hash_equals((string) $backup->backup_key,
(string) ($orderSpec['backup_key'] ?? ''))
|| !hash_equals((string) $backup->backup_key,
(string) ($backupMetadata['backup_key'] ?? ''))
|| !hash_equals((string) $backup->backup_key,
(string) ($body['backup_key'] ?? ''))
|| (int) $backup->object_size_bytes
!== (int) ($orderSpec['backup_size_bytes'] ?? 0)
|| (int) $backup->object_size_bytes
!== (int) ($body['source_size_bytes'] ?? 0)
|| !hash_equals((string) $backup->sha256,
(string) ($orderSpec['backup_sha256'] ?? ''))
|| !hash_equals((string) $backup->sha256,
(string) ($body['source_sha256'] ?? ''))
|| (string) $backup->purpose !== 'portable'
|| (string) $backup->state !== 'ready'
|| ($body['uuid'] ?? null) !== $resourceId
|| ($body['source'] ?? null) !== ''
|| ($body['template_id'] ?? null) !== ''
|| ($body['template_revision'] ?? null) !== 0
|| ($body['template_generation_token'] ?? null) !== ''
|| ($body['startup_script'] ?? null) !== ''
|| ($body['guest_ssh_public_key'] ?? null) !== ''
|| ($body['root_password'] ?? null) !== ''
|| !is_string($body['name'] ?? null)
|| preg_match('/^[A-Za-z0-9_.-]{1,80}$/D', $body['name']) !== 1
|| !is_string($body['network'] ?? null)
|| trim($body['network']) === ''
|| !is_string($body['public_pool_key'] ?? null)
|| preg_match(self::CATALOG_ID_PATTERN,
$body['public_pool_key']) !== 1
|| !is_string($body['public_pool_cidr'] ?? null)
|| !is_string($body['public_ip_cidr'] ?? null)
|| !is_string($body['gateway'] ?? null)
|| !is_array($body['dns_servers'] ?? null)
|| !array_is_list($body['dns_servers'])
|| $body['dns_servers'] === []
|| !is_array($body['platform_network_policy_snapshot'] ?? null)
|| array_is_list($body['platform_network_policy_snapshot'])
|| !is_bool($body['debian_12_network_fix'] ?? null)
|| !is_string($body['source_url'] ?? null)
|| !str_starts_with($body['source_url'], 'https://')
|| preg_match('/^[a-f0-9]{64}$/D',
(string) ($body['source_sha256'] ?? '')) !== 1
|| (int) $job->user_id < 1
|| $job->order_id === null
|| array_key_exists('owner_id', $payload)) {
self::invalidPayload(
'从云备份创建实例的请求与订单、备份账本不匹配'
);
}
if ($forAppliedEffect
&& (!is_string($payload['backup_sealed_credential'] ?? null)
|| trim($payload['backup_sealed_credential']) === '')) {
self::invalidPayload('从云备份创建实例缺少恢复凭据快照');
}
return ['restore-backup:' . (string) $backup->backup_key, $resourceId];
}
private static function assertCreateAppliedEscrow(
array $payload,
array $body
@ -664,7 +799,7 @@ final class CloudOperationRecoveryIdentity
}
/** Exact Go agent/api.operationUUID derivation for body-omitted UUIDs. */
private static function operationUuid(string $operationId): string
public static function operationUuid(string $operationId): string
{
$digest = hash(
'sha256',
@ -1236,6 +1371,64 @@ final class CloudOperationRecoveryIdentity
return 'restore-backup:' . $key;
}
private static function backupRecoverAction(
CloudJob $job,
array $payload,
CloudInstance $instance,
string $method,
string $target,
string $base,
array $body
): string {
self::expectRequest(
$method,
$target,
'POST',
$base . '/recover-backup'
);
self::assertAllowedBody($body, [
'operation_id', 'backup_key', 'source_url',
'source_size_bytes', 'source_sha256',
]);
$recovery = $job->backup_recovery_id === null ? null
: CloudBackupRecovery::find((int) $job->backup_recovery_id);
$backup = $job->backup_id === null ? null
: CloudInstanceBackup::find((int) $job->backup_id);
$key = $body['backup_key'] ?? null;
if ($recovery === null || $backup === null
|| (int) $recovery->job_id !== (int) $job->id
|| (int) $recovery->backup_id !== (int) $backup->id
|| (int) $recovery->instance_id !== (int) $instance->id
|| !hash_equals((string) $recovery->operation_id,
(string) $job->operation_id)
|| !hash_equals((string) $recovery->recovery_key,
(string) ($payload['recovery_key'] ?? ''))
|| (int) $backup->user_id !== (int) $instance->user_id
|| (int) $backup->source_instance_id !== (int) $instance->id
|| (string) $backup->source_uuid
!== strtolower((string) $instance->uuid)
|| (string) $backup->purpose !== 'portable'
|| (string) $backup->source !== 'automatic'
|| (string) $backup->state !== 'ready'
|| !is_string($key)
|| preg_match(self::CATALOG_ID_PATTERN, $key) !== 1
|| !hash_equals((string) $backup->backup_key, $key)
|| !hash_equals((string) $backup->backup_key,
(string) ($payload['backup_key'] ?? ''))
|| (int) $backup->object_size_bytes
!== (int) ($body['source_size_bytes'] ?? 0)
|| !hash_equals((string) $backup->sha256,
(string) ($body['source_sha256'] ?? ''))
|| !is_string($body['source_url'] ?? null)
|| !str_starts_with($body['source_url'], 'https://')) {
self::invalidPayload(
'云备份恢复请求与实例、备份或恢复账本不匹配'
);
}
return 'recover-backup:' . $key . ':'
. (string) $body['source_sha256'];
}
private static function assertMigrationBundleExportBody(
mixed $value,
CloudInstanceMigration $migration

@ -3,10 +3,12 @@ namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
use App\Models\CloudJob;
use App\Models\CloudNetworkLine;
use App\Models\CloudOffer;
use App\Models\CloudOrder;
use App\Models\CloudOrderItem;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\Shop;
@ -18,12 +20,20 @@ final class CloudOrderService
public static function purchase(array $input, array $actor): CloudOrder
{
CloudInput::only($input, ['offer_id', 'source', 'template_id', 'guest_ssh_key_id',
'root_password', 'name', 'idempotency_key']);
CloudInput::only($input, [
'offer_id', 'source', 'template_id', 'backup_id',
'guest_ssh_key_id', 'root_password', 'name',
'automatic_backup', 'idempotency_key',
]);
$requestedName = CloudInput::optionalName($input['name'] ?? null);
$automaticBackup = $input['automatic_backup'] ?? false;
if (!is_bool($automaticBackup)) {
throw new CloudError('自动备份选择必须为布尔值');
}
// Missing, null and an empty field describe the same request. Keep the
// fingerprint stable without storing a generated name in the request.
$input['name'] = $requestedName ?? '';
$input['automatic_backup'] = $automaticBackup;
$idempotency = $input['idempotency_key'] ?? '';
if (!is_string($idempotency) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('请提供 16 至 128 字符的请求幂等标识');
@ -33,14 +43,38 @@ final class CloudOrderService
throw new CloudError('请选择可用的销售方案');
}
$source = $input['source'] ?? 'cloud';
if ($source !== 'cloud') {
throw new CloudError('当前只支持从云镜像部署实例');
if (!in_array($source, ['cloud', 'backup'], true)) {
throw new CloudError('实例来源无效');
}
$template = '';
$backupId = null;
if ($source === 'cloud') {
if (array_key_exists('backup_id', $input)) {
throw new CloudError('云镜像部署不能携带备份标识');
}
$template = CloudInput::template($input['template_id'] ?? '');
} else {
if (array_key_exists('template_id', $input)
|| array_key_exists('guest_ssh_key_id', $input)
|| array_key_exists('root_password', $input)) {
throw new CloudError('从云备份创建实例不能替换镜像或登录凭据');
}
$parsedBackupId = filter_var(
$input['backup_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($parsedBackupId === false) {
throw new CloudError('请选择可用的云备份');
}
$backupId = (int) $parsedBackupId;
}
$template = CloudInput::template($input['template_id'] ?? '');
ksort($input);
$requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('order-request-hash'));
return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $idempotency, $requestHash) {
CloudTemplateCatalogService::assertProvisionable($template);
return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $backupId, $automaticBackup, $idempotency, $requestHash) {
if ($source === 'cloud') {
CloudTemplateCatalogService::assertProvisionable($template);
}
$user = User::where('id', $actor['user_id'])->lockForUpdate()->first();
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
@ -71,6 +105,18 @@ final class CloudOrderService
|| (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default)) {
throw new CloudError('该销售方案的地区、线路或资源池暂不可用', 409);
}
$sourceBackup = null;
$backupSpec = null;
if ($source === 'backup') {
$sourceBackup = CloudInstanceBackup::where(
'id', (int) $backupId
)->where('user_id', (int) $user->id)
->lockForUpdate()->first();
$backupSpec = self::assertPurchasableBackup(
$sourceBackup,
(int) $plan->disk_gib
);
}
if (!CloudPlacementService::isPoolCapacityAvailable(
(int) $pool->id,
(int) $plan->cpu_cores,
@ -79,20 +125,73 @@ final class CloudOrderService
)) {
throw new CloudError('该销售方案当前没有足够的可用资源或公网 IP', 409);
}
$price = CloudMoney::cents($offer->price);
$payload = ['source' => $source, 'name' => $name, 'vcpu' => (int) $plan->cpu_cores,
$instancePrice = CloudMoney::cents($offer->price);
$backupPrice = $automaticBackup
? CloudMoney::cents($offer->backup_price) : 0;
$totalPrice = $instancePrice + $backupPrice;
$payload = ['source' => $source === 'cloud' ? 'cloud' : '',
'name' => $name, 'vcpu' => (int) $plan->cpu_cores,
'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'network' => ''];
$credential = null;
$key = CloudSSHKeys::owned($input['guest_ssh_key_id'] ?? null, (int) $user->id);
$password = CloudInput::password($input['root_password'] ?? null);
$payload += ['template_id' => $template, 'guest_ssh_public_key' => $key?->public_key ?? '',
'root_password' => $password, 'public_pool_key' => '',
'public_pool_cidr' => '', 'public_ip_cidr' => '',
'gateway' => '', 'dns_servers' => []];
$credential = ['password' => $password, 'login_name' => 'root',
'auth_mode' => $key ? 'password_and_key' : 'password'];
if ($source === 'cloud') {
$key = CloudSSHKeys::owned(
$input['guest_ssh_key_id'] ?? null,
(int) $user->id
);
$password = CloudInput::password(
$input['root_password'] ?? null
);
$payload += [
'template_id' => $template,
'guest_ssh_public_key' => $key?->public_key ?? '',
'root_password' => $password,
'public_pool_key' => '', 'public_pool_cidr' => '',
'public_ip_cidr' => '', 'gateway' => '',
'dns_servers' => [],
];
$credential = [
'password' => $password,
'login_name' => 'root',
'auth_mode' => $key
? 'password_and_key' : 'password',
];
} else {
$payload += [
'description' => '',
'template_id' => '',
'template_revision' => 0,
'template_generation_token' => '',
'startup_script' => '',
'hostname' => CloudInput::hostname($name),
'guest_ssh_public_key' => '',
'root_password' => '',
'public_pool_key' => '', 'public_pool_cidr' => '',
'public_ip_cidr' => '', 'gateway' => '',
'dns_servers' => [],
'debian_12_network_fix' =>
$backupSpec['debian_12_network_fix'],
'backup_key' => (string) $sourceBackup->backup_key,
'source_size_bytes' =>
(int) $sourceBackup->object_size_bytes,
'source_sha256' => (string) $sourceBackup->sha256,
];
}
$safeSpec = CloudInput::safeResult($payload);
$safeSpec['source'] = $source;
if ($sourceBackup !== null) {
$safeSpec['backup_id'] = (int) $sourceBackup->id;
$safeSpec['backup_key'] = (string) $sourceBackup->backup_key;
$safeSpec['backup_size_bytes'] =
(int) $sourceBackup->object_size_bytes;
$safeSpec['backup_virtual_size_bytes'] =
(int) $sourceBackup->virtual_size_bytes;
$safeSpec['backup_sha256'] = (string) $sourceBackup->sha256;
foreach (['os_source', 'os_name', 'login_name',
'debian_12_network_fix'] as $field) {
$safeSpec[$field] = $backupSpec[$field];
}
}
$safeSpec['plan_name'] = $plan->name;
$safeSpec['plan_id'] = (int) $plan->id;
$safeSpec['offer_id'] = (int) $offer->id;
@ -110,7 +209,10 @@ final class CloudOrderService
? 'unlimited' : 'finite';
$safeSpec['validity_days'] = (int) $plan->validity_days;
$safeSpec['traffic_quota_bytes'] = (int) $plan->traffic_quota_bytes;
$safeSpec['renewal_price'] = CloudMoney::decimal($price);
$safeSpec['instance_price'] = CloudMoney::decimal($instancePrice);
$safeSpec['automatic_backup'] = $automaticBackup;
$safeSpec['backup_price'] = CloudMoney::decimal($backupPrice);
$safeSpec['renewal_price'] = CloudMoney::decimal($instancePrice);
$order = new CloudOrder();
$order->user_id = $user->id;
$order->plan_id = $plan->id;
@ -120,13 +222,16 @@ final class CloudOrderService
$order->reservation_id = null;
$order->idempotency_key = $idempotency;
$order->request_hash = $requestHash;
$order->amount = CloudMoney::decimal($price);
$order->amount = CloudMoney::decimal($totalPrice);
$order->currency = 'USD';
$order->status = 'awaiting_payment';
$order->spec_json = json_encode($safeSpec, JSON_THROW_ON_ERROR);
$order->sealed_payload = CloudSecrets::encrypt(['method' => 'POST',
'request_target' => '/v1/vms', 'body' => $payload,
'credential' => $credential], 'order-payload');
'credential' => $credential,
'backup_id' => $sourceBackup === null
? null : (int) $sourceBackup->id,
], 'order-payload');
$order->created_at = $order->updated_at = time();
if ((int) $offer->stock > 0) {
$offer->stock--;
@ -135,11 +240,113 @@ final class CloudOrderService
$order->stock_reserved_at = time();
}
$order->save();
self::createPurchaseItems(
$order,
$plan,
$offer,
$instancePrice,
$automaticBackup,
$backupPrice
);
CloudInvoiceService::issueProvision($order, $plan, $offer, time());
return $order;
}, 3);
}
private static function assertPurchasableBackup(
?CloudInstanceBackup $backup,
int $diskGiB
): array {
$spec = $backup === null ? null
: json_decode((string) $backup->spec_json, true);
$capacity = $diskGiB > 0 && $diskGiB <= intdiv(PHP_INT_MAX, 1073741824)
? $diskGiB * 1073741824 : 0;
if ($backup === null
|| (string) $backup->purpose !== 'portable'
|| (string) $backup->state !== 'ready'
|| (int) $backup->object_size_bytes < 1
|| (int) $backup->virtual_size_bytes < 1
|| (int) $backup->virtual_size_bytes > $capacity
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $backup->backup_key) !== 1
|| preg_match('/^[a-f0-9]{64}$/D',
(string) $backup->sha256) !== 1
|| !is_string($backup->sealed_credential)
|| trim($backup->sealed_credential) === ''
|| !is_array($spec) || array_is_list($spec)
|| ($spec['managed'] ?? null) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template'
|| !is_string($spec['os_name'] ?? null)
|| trim($spec['os_name']) === ''
|| ($spec['login_name'] ?? null) !== 'root'
|| !is_bool($spec['debian_12_network_fix'] ?? null)) {
throw new CloudError(
'云备份不可用,或所选套餐系统盘小于备份磁盘容量',
409
);
}
return [
'os_source' => 'cloud_template',
'os_name' => (string) $spec['os_name'],
'login_name' => 'root',
'debian_12_network_fix' => $spec['debian_12_network_fix'],
];
}
private static function createPurchaseItems(
CloudOrder $order,
Shop $plan,
CloudOffer $offer,
int $instancePrice,
bool $automaticBackup,
int $backupPrice
): void {
$now = time();
$items = [[
'code' => 'instance',
'label' => '实例套餐',
'amount' => $instancePrice,
'snapshot' => [
'plan_id' => (int) $plan->id,
'offer_id' => (int) $offer->id,
'offer_name' => (string) $offer->name,
'price_version' => (int) $offer->price_version,
'validity_days' => (int) $plan->validity_days,
],
]];
if ($automaticBackup) {
$items[] = [
'code' => 'automatic_backup',
'label' => '自动备份',
'amount' => $backupPrice,
'snapshot' => [
'offer_id' => (int) $offer->id,
'price_version' => (int) $offer->price_version,
'validity_days' => (int) $plan->validity_days,
],
];
}
$total = 0;
foreach ($items as $value) {
$item = new CloudOrderItem();
$item->order_id = (int) $order->id;
$item->code = $value['code'];
$item->label = $value['label'];
$item->amount = CloudMoney::decimal($value['amount']);
$item->currency = 'USD';
$item->snapshot_json = json_encode(
$value['snapshot'],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$item->created_at = $now;
$item->save();
$total += $value['amount'];
}
if ($total !== CloudMoney::cents((string) $order->amount)) {
throw new \RuntimeException('开通订单费用明细合计不一致');
}
}
private static function automaticName(User $user): string
{
$occupied = [];
@ -211,37 +418,10 @@ final class CloudOrderService
|| !is_array($payload['body'] ?? null)) {
throw new CloudError('开通订单的加密请求无效', 409);
}
$payload['body'] = CloudTemplateCatalogService::applyProvisioningSnapshot(
$payload['body']
);
$templateMetadata =
CloudTemplateCatalogService::templateMetadataSnapshot(
$payload['body']
);
// Keep PHP-only presentation metadata beside the strict Go request.
// The encrypted job carries the same immutable snapshot used by the
// durable order record, but only payload.body is sent to the Agent.
$payload['template_metadata'] = $templateMetadata;
// Freeze the complete effective platform deny policy at the payment
// boundary. An unpaid order therefore receives the current catalog,
// while an accepted create can never drift after an administrator
// edits or deletes a test rule.
$platformPolicy = CloudPlatformTestNetworkPolicy::snapshotForProvisioning();
$payload['body']['platform_network_policy_snapshot'] = $platformPolicy;
$orderSpec = json_decode((string) $order->spec_json, true);
if (!is_array($orderSpec) || array_is_list($orderSpec)) {
throw new CloudError('开通订单的规格快照无效', 409);
}
if (($orderSpec['source'] ?? null) !== 'cloud'
|| !is_string($orderSpec['template_id'] ?? null)
|| !hash_equals((string) $templateMetadata['template_id'],
$orderSpec['template_id'])) {
throw new CloudError('开通订单的云镜像快照不匹配', 409);
}
$orderSpec = array_replace($orderSpec, $templateMetadata);
$orderSpec['platform_network_policy_snapshot'] = $platformPolicy;
$order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$offer = CloudOffer::where('id', (int) $order->offer_id)
->lockForUpdate()->first();
$plan = Shop::where('id', (int) $order->plan_id)->lockForUpdate()->first();
@ -251,15 +431,107 @@ final class CloudOrderService
|| (int) $offer->resource_pool_id !== (int) $order->resource_pool_id) {
throw new CloudError('该销售方案已经失效,不能继续支付', 409);
}
// Freeze the complete effective platform deny policy at the payment
// boundary. An unpaid order therefore receives the current catalog,
// while an accepted create can never drift after an administrator
// edits or deletes a test rule.
$platformPolicy =
CloudPlatformTestNetworkPolicy::snapshotForProvisioning();
$payload['body']['platform_network_policy_snapshot'] = $platformPolicy;
$source = $orderSpec['source'] ?? null;
$sourceBackup = null;
if ($source === 'cloud') {
$payload['body'] =
CloudTemplateCatalogService::applyProvisioningSnapshot(
$payload['body']
);
$templateMetadata =
CloudTemplateCatalogService::templateMetadataSnapshot(
$payload['body']
);
if (!is_string($orderSpec['template_id'] ?? null)
|| !hash_equals(
(string) $templateMetadata['template_id'],
$orderSpec['template_id']
)) {
throw new CloudError('开通订单的云镜像快照不匹配', 409);
}
// Keep PHP-only presentation metadata beside the strict Go
// request. Only payload.body crosses the Agent boundary.
$payload['template_metadata'] = $templateMetadata;
$orderSpec = array_replace($orderSpec, $templateMetadata);
} elseif ($source === 'backup') {
$backupId = filter_var(
$orderSpec['backup_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($backupId === false
|| (int) ($payload['backup_id'] ?? 0) !== (int) $backupId) {
throw new CloudError('开通订单的云备份快照不匹配', 409);
}
$sourceBackup = CloudInstanceBackup::where('id', (int) $backupId)
->where('user_id', (int) $order->user_id)
->lockForUpdate()->first();
$metadata = self::assertPurchasableBackup(
$sourceBackup,
(int) $plan->disk_gib
);
if (!hash_equals((string) $sourceBackup->backup_key,
(string) ($orderSpec['backup_key'] ?? ''))
|| (int) $sourceBackup->object_size_bytes
!== (int) ($orderSpec['backup_size_bytes'] ?? 0)
|| (int) $sourceBackup->virtual_size_bytes
!== (int) ($orderSpec['backup_virtual_size_bytes'] ?? 0)
|| !hash_equals((string) $sourceBackup->sha256,
(string) ($orderSpec['backup_sha256'] ?? ''))) {
throw new CloudError('开通订单的云备份对象身份已变化', 409);
}
$transfer = CloudBackupService::provisioningSource($sourceBackup);
$payload['body']['source_url'] = $transfer['source_url'];
$payload['body']['source_size_bytes'] =
(int) $sourceBackup->object_size_bytes;
$payload['body']['source_sha256'] =
(string) $sourceBackup->sha256;
$payload['backup_metadata'] = [
'backup_id' => (int) $sourceBackup->id,
'backup_key' => (string) $sourceBackup->backup_key,
'os_source' => $metadata['os_source'],
'os_name' => $metadata['os_name'],
'login_name' => $metadata['login_name'],
'debian_12_network_fix' =>
$metadata['debian_12_network_fix'],
];
$payload['backup_sealed_credential'] =
(string) $sourceBackup->sealed_credential;
unset($payload['credential']);
} else {
throw new CloudError('开通订单的实例来源无效', 409);
}
$orderSpec['platform_network_policy_snapshot'] = $platformPolicy;
$order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$placement = CloudPlacementService::reserve(
$order, $offer, $plan, $payload
);
if ($sourceBackup !== null) {
$uuid = CloudOperationRecoveryIdentity::operationUuid(
(string) $placement['reservation']->operation_id
);
$placement['payload']['request_target'] = '/v1/vms/'
. rawurlencode($uuid) . '/restore-backup';
$placement['payload']['body']['uuid'] = $uuid;
$placement['payload']['body']['operation_id'] =
(string) $placement['reservation']->operation_id;
}
$job = new CloudJob();
$job->operation_id = (string) $placement['reservation']->operation_id;
$job->order_id = $order->id;
$job->user_id = $order->user_id;
$job->host_id = $placement['host']->id;
$job->kind = 'create';
$job->backup_id = $sourceBackup === null
? null : (int) $sourceBackup->id;
$job->execution_mode = 'agent';
$job->status = 'queued';
$job->sealed_payload = CloudSecrets::encrypt(

@ -1103,6 +1103,10 @@ final class CloudPlacementService
$agent = CloudHostAgent::where('host_id', $hostId)
->lockForUpdate()->first();
$body = $payload['body'] ?? null;
$orderSpec = json_decode((string) $order->spec_json, true);
$backupSource = is_array($orderSpec)
&& !array_is_list($orderSpec)
&& ($orderSpec['source'] ?? null) === 'backup';
$templateId = is_array($body) ? ($body['template_id'] ?? null) : null;
$templateRevision = is_array($body)
? filter_var($body['template_revision'] ?? null,
@ -1110,19 +1114,30 @@ final class CloudPlacementService
: false;
$generation = is_array($body)
? ($body['template_generation_token'] ?? null) : null;
$replica = !is_string($templateId) || $templateRevision === false
|| !is_string($generation) ? null
$replica = $backupSource || !is_string($templateId)
|| $templateRevision === false || !is_string($generation) ? null
: CloudTemplateReplica::query()->where('host_id', $hostId)
->where('template_id', $templateId)->lockForUpdate()->first();
$sourceReady = $backupSource
? is_array($body)
&& ($body['source'] ?? null) === ''
&& $templateId === ''
&& ($body['template_revision'] ?? null) === 0
&& $generation === ''
: $replica !== null
&& (string) $replica->state === 'active'
&& (int) $replica->revision === (int) $templateRevision
&& hash_equals(
(string) $replica->generation_token,
(string) $generation
);
if ($host === null || $membership === null || $policy === null
|| !CloudNetworkSelector::isValid($host->default_network)
|| $agent === null || !$agent->isReady()
|| $storage === null || !$storage->isApplied()
|| (string) $membership->scheduler_state !== 'active'
|| !(bool) $host->enabled
|| $replica === null || (string) $replica->state !== 'active'
|| (int) $replica->revision !== (int) $templateRevision
|| !hash_equals((string) $replica->generation_token, $generation)
|| !$sourceReady
|| (int) $policy->configured_cpu_cores < 1
|| (int) $policy->configured_memory_mib < 1
|| (int) $policy->configured_disk_gib < 1) {

@ -550,6 +550,9 @@ final class CloudPlanUpgradeService
$spec['traffic_quota_bytes'] =
(int) $target['traffic_quota_bytes'];
$spec['renewal_price'] = (string) $target['price'];
if (($source['automatic_backup'] ?? false) === true) {
$spec['backup_price'] = (string) $target['backup_price'];
}
unset($spec['agent_metadata_version']);
$period->plan_id = (int) $target['plan_id'];
@ -585,6 +588,10 @@ final class CloudPlanUpgradeService
);
$instance->updated_at = $now;
$instance->save();
CloudAutomaticBackupService::refreshPriceAfterUpgradeLocked(
$instance,
$targetOffer
);
CloudInvoiceService::refreshRenewalAfterUpgradeLocked(
$instance,
$now
@ -844,6 +851,8 @@ final class CloudPlanUpgradeService
'offer_name' => is_string($spec['offer_name'] ?? null)
? (string) $spec['offer_name'] : '当前套餐',
'stock_mode' => $stockMode,
'automatic_backup' =>
($spec['automatic_backup'] ?? null) === true,
'resources' => $resources,
'spec_hash' => hash('sha256', (string) $instance->spec_json),
'quoted_at' => $now,
@ -909,6 +918,9 @@ final class CloudPlanUpgradeService
'offer_name' => (string) $offer->name,
'price' => CloudMoney::decimal($priceCents),
'price_version' => (int) $offer->price_version,
'backup_price' => CloudMoney::decimal(
CloudMoney::cents((string) $offer->backup_price)
),
'revision' => (int) $offer->revision,
'stock_mode' => (int) $offer->stock === -1
? 'unlimited' : 'finite',

@ -54,8 +54,10 @@ final class CloudRenewalService
throw new CloudError('实例正在升级或等待核对,暂时不能续费', 409);
}
$days = (int) $locked->renewal_days;
$price = $locked->renewal_price === null ? -1 : CloudMoney::cents((string) $locked->renewal_price);
if ($days < 1 || $price < 0 || $locked->expires_at === null) {
$basePrice = $locked->renewal_price === null
? -1 : CloudMoney::cents((string) $locked->renewal_price);
if ($days < 1 || $basePrice < 0
|| $locked->expires_at === null) {
throw new CloudError('此实例没有可续费的套餐快照', 409);
}
$now = time();
@ -70,6 +72,16 @@ final class CloudRenewalService
|| $deadline <= $now) {
throw new CloudError('续费宽限期已结束,实例将被删除', 409);
}
if ($invoice === null
|| !in_array((string) $invoice->status,
['open', 'overdue'], true)
|| !CloudInvoiceService::renewalInvoiceMatches(
$locked,
$invoice
)) {
throw new CloudError('续费账单费用快照不一致', 409);
}
$price = CloudMoney::cents((string) $invoice->amount);
$balance = CloudMoney::cents((string) $user->money);
if ($balance < $price) {
throw new CloudError('账户余额不足', 409);

@ -13,6 +13,8 @@ final class CloudRuntimeHeartbeat
'migration_bundle_cleanup' => '迁移传输包清理',
'notification' => '邮件通知', 'lifecycle_tick' => '生命周期巡检',
'provision_expiry' => '开通账单过期处理', 'invoice_generation' => '续费账单生成',
'automatic_backup_schedule' => '自动备份调度',
'automatic_backup_retention' => '自动备份保留数清理',
'traffic_sync' => '流量同步',
'runtime_status_sync' => '实例状态同步',
'instance_reconcile' => '实例策略核对',
@ -21,6 +23,8 @@ final class CloudRuntimeHeartbeat
'migration_bundle_cleanup_failed',
'notification_failed',
'lifecycle_tick_failed', 'provision_expiry_failed', 'invoice_generation_failed',
'automatic_backup_schedule_failed',
'automatic_backup_retention_failed',
'traffic_sync_failed', 'runtime_status_sync_failed',
'runtime_status_sync_unconfigured', 'traffic_collection_unconfigured',
'traffic_log_schema_missing', 'traffic_agent_unavailable',

@ -2,6 +2,7 @@
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudBackupSubscription;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOffer;
@ -1546,6 +1547,23 @@ final class CloudWorkerService
],
];
}
if ($kind === 'backup_recover') {
$body = is_array($payload['body'] ?? null)
? $payload['body'] : [];
return [
CloudOperationRecoveryIdentity::payloadKey() => $identity,
'owner_id' => $payload['owner_id'] ?? null,
'can_manage' => $payload['can_manage'] ?? null,
'backup_key' => $payload['backup_key'] ?? null,
'recovery_key' => $payload['recovery_key'] ?? null,
'body' => [
'backup_key' => $body['backup_key'] ?? null,
'source_size_bytes' =>
$body['source_size_bytes'] ?? null,
'source_sha256' => $body['source_sha256'] ?? null,
],
];
}
return $payload;
}
@ -2609,6 +2627,9 @@ final class CloudWorkerService
if ($days === false || $traffic === false) {
throw new CloudError('订单缺少不可变的计费周期快照', 409);
}
$instancePrice = CloudMoney::cents(
$spec['instance_price'] ?? null
);
$instance->plan_id = $order->plan_id;
// A duplicate completion result must not overwrite a display
// name the owner changed after the first success committed.
@ -2619,7 +2640,11 @@ final class CloudWorkerService
$instance->service_status = 'active';
$instance->network_status = 'active';
$instance->expires_at = $now + $days * 86400;
$instance->renewal_price = $order->amount;
// Optional services are renewed from their own subscription
// ledgers. Keep this field as the base compute price only.
$instance->renewal_price = CloudMoney::decimal(
$instancePrice
);
$instance->renewal_days = $days;
$instance->renewal_traffic_bytes = $traffic;
$instance->traffic_quota_bytes = $traffic;
@ -2652,10 +2677,24 @@ final class CloudWorkerService
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
$instance->sealed_credential = isset($payload['credential'])
? CloudSecrets::encrypt(
$payload['credential'], 'instance-credential'
) : null;
if (isset($payload['backup_metadata'])) {
if (!is_string(
$payload['backup_sealed_credential'] ?? null
)
|| trim($payload['backup_sealed_credential']) === '') {
throw new CloudError(
'云备份开通任务缺少登录凭据快照',
409
);
}
$instance->sealed_credential =
$payload['backup_sealed_credential'];
} else {
$instance->sealed_credential = isset($payload['credential'])
? CloudSecrets::encrypt(
$payload['credential'], 'instance-credential'
) : null;
}
// The paid service begins when provisioning actually succeeds,
// not while an opening invoice is waiting for payment. A
// duplicate success must retain the original value.
@ -2692,6 +2731,7 @@ final class CloudWorkerService
$period->save();
$instance->current_period_id = $period->id;
$instance->save();
CloudAutomaticBackupService::activatePurchased($instance);
$job->instance_id = $order->instance_id = $instance->id;
$provisionInvoice->instance_id = $instance->id;
$provisionInvoice->updated_at = time();
@ -2861,6 +2901,12 @@ final class CloudWorkerService
['delete', 'expiry_delete', 'delete_force'], true)) {
$instance->status = 'deleted';
$instance->sealed_credential = null;
CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->where('enabled', 1)->update([
'enabled' => 0,
'updated_at' => time(),
]);
CloudPlacementService::releaseDeletedInstance(
$instance,
'instance_deleted'
@ -3306,6 +3352,43 @@ final class CloudWorkerService
*/
private static function trustedTemplateMetadata(array $payload): array
{
if (array_key_exists('backup_metadata', $payload)) {
$metadata = $payload['backup_metadata'];
$body = $payload['body'] ?? null;
if (!is_array($metadata) || array_is_list($metadata)
|| !is_array($body) || array_is_list($body)
|| filter_var(
$metadata['backup_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
) === false
|| preg_match('/^[a-f0-9]{32}$/D',
(string) ($metadata['backup_key'] ?? '')) !== 1
|| !hash_equals(
(string) $metadata['backup_key'],
(string) ($body['backup_key'] ?? '')
)
|| ($metadata['os_source'] ?? null) !== 'cloud_template'
|| !is_string($metadata['os_name'] ?? null)
|| trim($metadata['os_name']) === ''
|| ($metadata['login_name'] ?? null) !== 'root'
|| !is_bool($metadata['debian_12_network_fix'] ?? null)
|| ($body['debian_12_network_fix'] ?? null)
!== $metadata['debian_12_network_fix']) {
throw new CloudError(
'任务中的云备份展示快照与 Agent 请求不匹配,必须人工核查',
409
);
}
return [
'os_source' => 'cloud_template',
'os_name' => $metadata['os_name'],
'login_name' => 'root',
'debian_12_network_fix' =>
$metadata['debian_12_network_fix'],
'restored_from_backup' => $metadata['backup_key'],
];
}
if (!array_key_exists('template_metadata', $payload)) {
throw new CloudError(
'任务缺少云镜像展示快照,必须终止并人工核查', 409

@ -97,6 +97,7 @@ $app->group('/user', function () {
$this->get('/cloud/instances/{id:[0-9]+}', 'App\Controllers\CloudPageController:detail');
$this->get('/cloud/instances/{id:[0-9]+}/reinstall', 'App\Controllers\CloudPageController:reinstall');
$this->get('/cloud/deploy', 'App\Controllers\CloudPageController:deploy');
$this->get('/cloud/backups', 'App\Controllers\CloudPageController:backups');
$this->get('/cloud/iso-images', 'App\Controllers\CloudPageController:isoImages');
$this->get('/cloud/ssh-keys', 'App\Controllers\CloudPageController:sshKeys');
$this->get('/cloud/invoices', 'App\Controllers\CloudPageController:invoices');

@ -25,6 +25,7 @@ $app->group('/api/v1', function () {
$this->get('/tasks', 'App\Controllers\CloudApiController:tasks');
$this->get('/tasks/{id:[0-9]+}', 'App\Controllers\CloudApiController:job');
$this->post('/tasks/read', 'App\Controllers\CloudApiController:readTasks');
$this->get('/backups', 'App\Controllers\CloudApiController:backups');
$this->get('/resources', 'App\Controllers\CloudApiController:resources');
$this->map(['GET', 'POST'], '/user-isos', 'App\Controllers\CloudApiController:userIsos');
$this->delete('/user-isos/{id:[0-9a-f]{32}}',
@ -52,6 +53,10 @@ $app->group('/api/v1', function () {
'App\Controllers\CloudApiController:restoreSnapshot');
$this->delete('/vms/{id:[0-9]+}/snapshots/{snapshot_key:[0-9a-f]{32}}',
'App\Controllers\CloudApiController:deleteSnapshot');
$this->map(['GET', 'PUT'], '/vms/{id:[0-9]+}/automatic-backup',
'App\Controllers\CloudApiController:automaticBackup');
$this->post('/vms/{id:[0-9]+}/automatic-backup/{backup_id:[0-9]+}/restore',
'App\Controllers\CloudApiController:restoreAutomaticBackup');
$this->patch('/vms/{id:[0-9]+}/display-name', 'App\Controllers\CloudApiController:displayName');
$this->get('/vms', 'App\Controllers\CloudApiController:vms');
$this->get('/vms/{id}', 'App\Controllers\CloudApiController:vm');

@ -2,6 +2,7 @@ const pageModules = Object.freeze({
instances: '/cloud/instances.js',
detail: '/cloud/detail.js',
deploy: '/cloud/deploy.js',
backups: '/cloud/backups.js',
isos: '/cloud/iso-images.js',
keys: '/cloud/ssh-keys.js',
invoices: '/cloud/invoices.js',

@ -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 || '云备份页面加载失败,请刷新后重试。');
}
}

@ -401,11 +401,11 @@ function bindDetailTabs(vmId) {
const INSTANCE_SETTING_LABELS = Object.freeze({
hostname: '主机名', password: 'root 密码', ssh_key: 'SSH 公钥',
ip_change: '公网 IP', upgrade: '实例升级', firewall: '防火墙',
ip_change: '公网 IP', upgrade: '实例升级', automatic_backup: '自动备份', firewall: '防火墙',
snapshots: '在线快照', rescue: '紧急救援',
});
const INSTANCE_SETTING_TABS = Object.freeze([
'hostname', 'password', 'ssh_key', 'ip_change', 'upgrade', 'firewall', 'snapshots', 'rescue',
'hostname', 'password', 'ssh_key', 'ip_change', 'upgrade', 'automatic_backup', 'firewall', 'snapshots', 'rescue',
]);
const UPGRADE_OFFER_FIELDS = Object.freeze([
'offer_id', 'name', 'cpu_cores', 'memory_mib', 'disk_gib',
@ -431,6 +431,11 @@ let snapshotLoadedVmId = null;
let snapshotPayload = null;
let snapshotMutation = null;
let snapshotEffectLocked = false;
let automaticBackupRequest = null;
let automaticBackupLoadedVmId = null;
let automaticBackupPayload = null;
let automaticBackupSaving = false;
let automaticBackupRestoring = false;
let firewallRequest = null;
let firewallLoadedVmId = null;
let firewallPayload = null;
@ -475,6 +480,9 @@ function activateInstanceSettingTab(vmId, tab, focus = false) {
if (tab === 'upgrade') {
settingStatus();
void loadUpgradeOptions(vmId).catch(() => null);
} else if (tab === 'automatic_backup') {
settingStatus();
void loadAutomaticBackup(vmId).catch(() => null);
} else if (tab === 'firewall') {
settingStatus();
void loadVmFirewall(vmId);
@ -1380,6 +1388,309 @@ function bindSnapshotControls(vmId) {
});
}
function automaticBackupStatus(message = '', type = '') {
const target = byId('vm-automatic-backup-status');
if (!target) return;
target.textContent = message;
target.className = `vm-settings-status ${type}`.trim();
target.hidden = !message;
}
function automaticBackupError(message = '') {
const target = byId('vm-automatic-backup-error');
if (!target) return;
target.textContent = message;
target.hidden = !message;
}
function automaticBackupSubscription(payload = automaticBackupPayload) {
return payload?.subscription && typeof payload.subscription === 'object'
? payload.subscription : payload || {};
}
function automaticBackupSchedule(payload = automaticBackupPayload) {
const subscription = automaticBackupSubscription(payload);
const schedule = payload?.schedule && typeof payload.schedule === 'object'
? payload.schedule : subscription?.schedule && typeof subscription.schedule === 'object'
? subscription.schedule : subscription;
const frequency = String(schedule?.frequency || 'daily').toLowerCase() === 'weekly'
? 'weekly' : 'daily';
const weekday = Math.min(6, Math.max(0, Number(schedule?.weekday) || 0));
const retention = Number(schedule?.retention_count) === 1 ? 1 : 2;
return { frequency, weekday, retention };
}
function automaticBackupPurchased(payload = automaticBackupPayload) {
const subscription = automaticBackupSubscription(payload);
return payload?.entitled === true || payload?.purchased === true || payload?.subscribed === true
|| subscription?.purchased === true || subscription?.active === true
|| ['active', 'pending', 'cancel_at_period_end'].includes(
String(subscription?.status || payload?.subscription_status || '').toLowerCase()
);
}
function automaticBackupItems(payload = automaticBackupPayload) {
const values = Array.isArray(payload?.backups) ? payload.backups
: Array.isArray(payload?.items) ? payload.items : [];
return values.filter(item => item && typeof item === 'object');
}
function automaticBackupId(backup) {
const id = String(backup?.id ?? backup?.backup_id ?? '');
return /^[1-9]\d*$/.test(id) ? id : '';
}
function automaticBackupRestoreStorageKey(vmId) {
return `virt-cloud:pending-automatic-backup-restore:${state.userId || 'unknown'}:${vmId}`;
}
function pendingAutomaticBackupRestoreKey(vmId, backupId) {
let saved = null;
try {
saved = JSON.parse(sessionStorage.getItem(automaticBackupRestoreStorageKey(vmId)) || 'null');
} catch {}
const fingerprint = String(backupId);
const key = saved?.fingerprint === fingerprint
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
? String(saved.key) : firewallIdempotencyKey();
try {
sessionStorage.setItem(automaticBackupRestoreStorageKey(vmId), JSON.stringify({ fingerprint, key }));
} catch {}
return key;
}
function clearPendingAutomaticBackupRestoreKey(vmId) {
try { sessionStorage.removeItem(automaticBackupRestoreStorageKey(vmId)); } catch {}
}
function automaticBackupState(backup) {
const value = String(backup?.state || backup?.status || '').toLowerCase();
const labels = {
ready: ['可恢复', 'running'], creating: ['正在备份', 'warning'],
queued: ['等待备份', 'warning'], failed: ['备份失败', 'stopped'],
uncertain: ['等待核对', 'warning'], restoring: ['正在恢复', 'warning'],
};
return labels[value] || [value || '状态未知', 'other'];
}
function renderAutomaticBackupList(vmId, items, allowed) {
const list = byId('vm-automatic-backup-list');
if (!list) return;
list.replaceChildren();
if (!items.length) {
const empty = document.createElement('div');
empty.className = 'vm-automatic-backup-empty';
const title = document.createElement('strong');
const detail = document.createElement('span');
title.textContent = '还没有可用备份';
detail.textContent = '计划启用后,系统会在太平洋时间 00:00 自动执行。';
empty.append(title, detail);
list.append(empty);
return;
}
for (const backup of items) {
const id = automaticBackupId(backup);
const [label, tone] = automaticBackupState(backup);
const card = document.createElement('article');
card.className = 'vm-automatic-backup-card';
const main = document.createElement('div');
main.className = 'vm-automatic-backup-card-main';
const name = document.createElement('strong');
name.textContent = String(backup?.name || (id ? `云备份 #${id}` : '云备份'));
const meta = document.createElement('small');
const size = snapshotSize(backup?.object_size_bytes);
meta.textContent = [snapshotTime(backup?.ready_at ?? backup?.created_at),
snapshotConsistency(backup?.consistency), size].filter(Boolean).join(' · ');
main.append(name, meta);
const status = document.createElement('span');
status.className = `state-pill ${tone} vm-automatic-backup-card-status`;
status.textContent = label;
card.append(main, status);
if (id && backup?.can_restore_original !== false
&& String(backup?.state || backup?.status || '').toLowerCase() === 'ready') {
const actions = document.createElement('div');
actions.className = 'vm-automatic-backup-card-actions';
const restore = document.createElement('button');
restore.type = 'button';
restore.className = 'button button-danger small';
restore.textContent = automaticBackupRestoring ? '恢复任务已提交' : '恢复当前实例';
restore.disabled = !allowed || automaticBackupRestoring;
restore.addEventListener('click', () => void restoreAutomaticBackup(vmId, backup));
actions.append(restore);
card.append(actions);
}
list.append(card);
}
}
function renderAutomaticBackup(vmId, payload = automaticBackupPayload) {
const form = byId('vm-automatic-backup-form');
if (!form) return;
const schedule = automaticBackupSchedule(payload);
const purchased = automaticBackupPurchased(payload);
const canConfigure = payload?.can_configure !== false
&& automaticBackupSubscription(payload)?.can_configure !== false;
const allowed = purchased && canConfigure
&& selectedVm()?.can_operate === true && !instanceOperationBusy()
&& !automaticBackupSaving && !automaticBackupRestoring;
form.elements.frequency.value = schedule.frequency;
form.elements.weekday.value = String(schedule.weekday);
form.elements.retention_count.value = String(schedule.retention);
byId('vm-automatic-backup-weekday-field').hidden = schedule.frequency !== 'weekly';
for (const control of form.querySelectorAll('select, button')) control.disabled = !allowed;
renderAutomaticBackupList(vmId, automaticBackupItems(payload), allowed);
if (!purchased) {
automaticBackupStatus('当前实例没有有效的自动备份服务,请在部署新实例时选择自动备份。', 'warning');
} else if (automaticBackupSaving) {
automaticBackupStatus('正在保存自动备份计划,请勿重复提交。');
} else if (automaticBackupRestoring) {
automaticBackupStatus('正在恢复当前实例,请勿重复提交其他实例操作。', 'warning');
} else if (!canConfigure) {
automaticBackupStatus(String(payload?.message || '当前自动备份服务暂不能修改。'), 'warning');
} else {
automaticBackupStatus('自动备份服务已启用,可修改下次执行计划。', 'success');
}
}
async function loadAutomaticBackup(vmId, force = false) {
if (!byId('vm-settings-section-automatic-backup')) return null;
if (!force && automaticBackupLoadedVmId === String(vmId) && automaticBackupPayload) {
renderAutomaticBackup(vmId, automaticBackupPayload);
return automaticBackupPayload;
}
if (automaticBackupRequest) return automaticBackupRequest;
automaticBackupStatus('正在读取自动备份计划…');
automaticBackupError();
automaticBackupRequest = (async () => {
try {
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup`);
if (String(selectedVm()?.api_id || '') !== String(vmId)) return null;
automaticBackupLoadedVmId = String(vmId);
automaticBackupPayload = payload || {};
renderAutomaticBackup(vmId, automaticBackupPayload);
return automaticBackupPayload;
} catch (error) {
automaticBackupLoadedVmId = null;
automaticBackupPayload = null;
automaticBackupStatus(error?.message || '自动备份配置读取失败,请稍后重试。', 'error');
throw error;
} finally {
automaticBackupRequest = null;
}
})();
return automaticBackupRequest;
}
function pollAutomaticBackupRestore(vmId, receipt) {
return watchTask(receipt, '恢复云备份', {
onUpdate: () => automaticBackupStatus('恢复任务正在后台执行,请勿重复提交。', 'warning'),
onTerminal: task => {
void (async () => {
automaticBackupRestoring = false;
await refreshMetadataAndStatus(vmId, false, true, true);
await loadAutomaticBackup(vmId, true).catch(() => null);
if (taskSucceededWithoutRecovery(task)) {
clearPendingAutomaticBackupRestoreKey(vmId);
automaticBackupStatus('云备份已经恢复到当前实例。', 'success');
toast('实例已从云备份恢复。', 'success');
} else {
const effectUnknown = task?.recovery?.pending === true
|| (task?.effect_may_have_applied === true
&& String(task?.effect_resolution || '') === 'unknown');
if (!effectUnknown) clearPendingAutomaticBackupRestoreKey(vmId);
automaticBackupStatus(taskFailureMessage(task, '恢复云备份失败。'), 'error');
}
})();
},
onStop: reason => {
if (reason === 'pagehide') return;
automaticBackupRestoring = false;
void (async () => {
await loadAutomaticBackup(vmId, true).catch(() => null);
automaticBackupStatus('自动观察已停止,请在任务中心核对恢复结果后再执行其他操作。', 'warning');
})();
},
});
}
async function restoreAutomaticBackup(vmId, backup) {
const id = automaticBackupId(backup);
if (!id || automaticBackupRestoring || automaticBackupSaving || instanceOperationBusy()) return;
const confirmed = await requestUserConfirmation({
title: '从云备份恢复当前实例',
message: `当前系统盘将被备份“${String(backup?.name || `#${id}`)}”覆盖,实例会短暂停止。账单、服务周期和公网 IP 不会回滚。`,
confirmText: '确认覆盖并恢复',
tone: 'danger',
});
if (!confirmed) return;
automaticBackupRestoring = true;
automaticBackupError();
renderAutomaticBackup(vmId, automaticBackupPayload);
const idempotencyKey = pendingAutomaticBackupRestoreKey(vmId, id);
try {
const receipt = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup/${encodeURIComponent(id)}/restore`, {
headers: { 'Idempotency-Key': idempotencyKey },
method: 'POST', body: { confirm_restore: true },
expectedStatus: 202, requireTaskReceipt: true,
});
automaticBackupStatus('恢复任务已接收,可在任务中心查看结果。', 'warning');
toast('恢复云备份任务已接收。', 'success');
if (!pollAutomaticBackupRestore(vmId, receipt)) {
automaticBackupRestoring = false;
await loadAutomaticBackup(vmId, true).catch(() => null);
automaticBackupStatus('任务已接收,但任务回执协议无效。请勿重复提交,并联系管理员核查。', 'error');
}
} catch (error) {
automaticBackupRestoring = false;
if (!firewallTransportUncertain(error)) clearPendingAutomaticBackupRestoreKey(vmId);
await loadAutomaticBackup(vmId, true).catch(() => null);
automaticBackupStatus(error?.message || '恢复云备份提交失败,请稍后重试。', 'error');
}
}
function bindAutomaticBackup(vmId) {
const form = byId('vm-automatic-backup-form');
if (!form) return;
form.elements.frequency.addEventListener('change', () => {
byId('vm-automatic-backup-weekday-field').hidden = form.elements.frequency.value !== 'weekly';
});
form.addEventListener('submit', async event => {
event.preventDefault();
if (automaticBackupSaving || automaticBackupRestoring
|| !automaticBackupPurchased() || instanceOperationBusy()) return;
const frequency = form.elements.frequency.value === 'weekly' ? 'weekly' : 'daily';
const weekday = Math.min(6, Math.max(0, Number(form.elements.weekday.value) || 0));
const retention = Number(form.elements.retention_count.value) === 1 ? 1 : 2;
automaticBackupSaving = true;
let outcome = '';
automaticBackupError();
renderAutomaticBackup(vmId, automaticBackupPayload);
try {
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup`, {
method: 'PUT', body: { frequency, weekday, retention_count: retention },
});
automaticBackupPayload = {
...automaticBackupPayload,
...(payload && typeof payload === 'object' ? payload : {}),
schedule: payload?.schedule || { frequency, weekday, retention_count: retention },
};
automaticBackupLoadedVmId = String(vmId);
outcome = 'saved';
toast('自动备份计划已保存。', 'success');
} catch (error) {
outcome = error?.message || '自动备份计划保存失败,请稍后重试。';
} finally {
automaticBackupSaving = false;
if (automaticBackupPayload) renderAutomaticBackup(vmId, automaticBackupPayload);
if (outcome === 'saved') automaticBackupStatus('自动备份计划已保存。', 'success');
else if (outcome) {
automaticBackupError(outcome);
automaticBackupStatus('自动备份计划未保存。', 'error');
}
}
});
}
function ipChangeStatus(message = '', type = '') {
const target = byId('vm-ip-change-status');
if (!target) return;
@ -2362,6 +2673,7 @@ function bindInstanceSettings(vmId) {
bindInstanceSettingTabs(vmId, requestedTab);
bindIpChange(vmId);
bindInstanceUpgrade(vmId);
bindAutomaticBackup(vmId);
bindFirewallControls(vmId);
bindSnapshotControls(vmId);
bindRescue(vmId);
@ -2469,6 +2781,7 @@ export async function initialize() {
if (state.detailTab === 'operations-log') await loadOperationLogs(vmId, true);
if (!byId('vm-settings-section-ip-change')?.hidden) await loadIpChangeQuote(vmId, true);
if (!byId('vm-settings-section-upgrade')?.hidden) await loadUpgradeOptions(vmId, true).catch(() => null);
if (!byId('vm-settings-section-automatic-backup')?.hidden) await loadAutomaticBackup(vmId, true).catch(() => null);
if (!byId('vm-settings-section-firewall')?.hidden) await loadVmFirewall(vmId, true);
if (!byId('vm-settings-section-snapshots')?.hidden) await loadVmSnapshots(vmId, true);
if (!byId('vm-settings-section-rescue')?.hidden) await loadRescue(vmId, true).catch(() => null);
@ -2553,6 +2866,11 @@ export async function initialize() {
if (!byId('vm-settings-section-upgrade')?.hidden) {
void loadUpgradeOptions(vmId, true).catch(() => null);
}
if (!byId('vm-settings-section-automatic-backup')?.hidden) {
automaticBackupRestoring = false;
automaticBackupSaving = false;
void loadAutomaticBackup(vmId, true).catch(() => null);
}
if (!byId('vm-settings-section-rescue')?.hidden) {
rescueSubmitting = false;
void loadRescue(vmId, true).catch(() => null);

@ -23,7 +23,7 @@ const {
// address, token, host credential or unrestricted create API exists in this UI.
const byId = (id) => document.getElementById(id);
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false);
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', deployBackupId: '', rescueActive: false, rescueStaged: false };
let vmStatusRequest = null;
let vmStatusGeneration = 0;
const activeTaskObservers = new Set();
@ -33,6 +33,7 @@ const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:';
const CLOUD_PATHS = Object.freeze({
instances: '/user/cloud/instances',
deploy: '/user/cloud/deploy',
backups: '/user/cloud/backups',
keys: '/user/cloud/ssh-keys',
invoices: '/user/cloud/invoices',
});
@ -620,10 +621,85 @@ function setDeploymentStepEnabled(id, enabled) {
step.classList.toggle('is-disabled', !enabled);
step.setAttribute('aria-disabled', String(!enabled));
}
function selectedSaleOffer() {
return saleOffers().find(item => String(item.id) === byId('vm-offer')?.value) || null;
}
function syncDeploymentPricing() {
const offer = selectedSaleOffer();
const option = byId('vm-automatic-backup-option');
const checkbox = byId('vm-automatic-backup');
const help = byId('vm-automatic-backup-help');
const backupAvailable = Boolean(offer);
if (checkbox) {
checkbox.disabled = !backupAvailable || state.mutationBusy;
if (!backupAvailable) checkbox.checked = false;
}
option?.classList.toggle('is-disabled', !backupAvailable || state.mutationBusy);
if (help) {
help.textContent = offer
? '购买后可在实例详情的“自动备份”中管理备份计划。'
: '选择实例规格后可以启用。';
}
const summary = byId('vm-order-summary');
const empty = byId('vm-order-summary-empty');
if (!offer) {
if (summary) summary.hidden = true;
if (empty) empty.hidden = false;
if (byId('create-submit')) byId('create-submit').textContent = '生成账单';
return;
}
const instancePrice = Number(offer.price);
const backupPrice = Number(offer.backup_price);
const backupSelected = backupAvailable && checkbox?.checked === true;
const total = Math.max(0, Number.isFinite(instancePrice) ? instancePrice : 0)
+ (backupSelected && Number.isFinite(backupPrice) ? Math.max(0, backupPrice) : 0);
if (byId('vm-order-instance-price')) byId('vm-order-instance-price').textContent = formatUsd(instancePrice);
if (byId('vm-order-backup-price')) byId('vm-order-backup-price').textContent = formatUsd(backupPrice);
if (byId('vm-order-backup-row')) byId('vm-order-backup-row').hidden = !backupSelected;
if (byId('vm-order-total-price')) byId('vm-order-total-price').textContent = formatUsd(total);
if (byId('vm-order-renewal-price')) byId('vm-order-renewal-price').textContent = `${formatUsd(total)} / 期`;
if (summary) summary.hidden = false;
if (empty) empty.hidden = true;
if (byId('create-submit')) byId('create-submit').textContent = `生成 ${formatUsd(total)} 账单`;
}
function applyDeploymentSource() {
const backupId = state.deployBackupId;
const source = byId('vm-backup-source');
const templateField = byId('vm-template-field');
const authFields = byId('vm-cloud-fields');
const template = byId('vm-template');
const password = byId('vm-root-password');
if (byId('vm-backup-id')) byId('vm-backup-id').value = backupId;
if (source) source.hidden = !backupId;
if (templateField) templateField.hidden = Boolean(backupId);
if (authFields) authFields.hidden = Boolean(backupId);
if (template) template.disabled = Boolean(backupId) || !state.templates.some(item => item?.id);
if (password) password.disabled = Boolean(backupId);
if (byId('deploy-source-title') && backupId) byId('deploy-source-title').textContent = '备份来源';
if (byId('vm-backup-source-name') && backupId) {
byId('vm-backup-source-name').textContent = `云备份 #${backupId},将按所选规格创建新的付费实例。`;
}
}
function initializeDeploymentOptions() {
const requestedBackup = new URLSearchParams(location.search).get('backup_id') || '';
state.deployBackupId = /^[1-9]\d*$/.test(requestedBackup) ? requestedBackup : '';
const checkbox = byId('vm-automatic-backup');
if (checkbox && checkbox.dataset.bound !== 'true') {
checkbox.dataset.bound = 'true';
checkbox.addEventListener('change', () => {
showError('create-error', '');
syncDeploymentPricing();
updateCreateAvailability();
});
}
applyDeploymentSource();
syncDeploymentPricing();
}
function updateCreateAvailability() {
const offer = saleOffers().find(item => String(item.id) === byId('vm-offer')?.value);
const validMedia = Boolean(byId('vm-template')?.value);
const offer = selectedSaleOffer();
const validMedia = Boolean(state.deployBackupId || byId('vm-template')?.value);
if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(offer) || !validMedia;
syncDeploymentPricing();
}
function strongPassword(value) { return !value || (value.length >= 12 && value.length <= 128 && /^[\x21-\x7e]+$/.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9]/.test(value)); }
function formatUsd(value) {
@ -705,12 +781,11 @@ function renderOfferPicker() {
selectedOfferId = '';
}
const header = makeElement('div', 'offer-table-head');
['名称', 'CPU', '内存', '硬盘', '每期流量', '价格'].forEach(label => header.append(makeElement('span', '', label)));
['名称', 'CPU', '内存', '硬盘', '每期流量'].forEach(label => header.append(makeElement('span', '', label)));
const rows = offers.map(offer => {
const button = makeElement('button', 'offer-option');
const memory = formatMemoryGiB(offer.memory_mib);
const traffic = formatTrafficTiB(offer.traffic_tib);
const price = formatUsd(offer.price);
const sellable = isOfferSellable(offer);
const name = makeElement('strong', 'offer-option-name', offer.name);
if (!sellable) name.append(makeElement('span', 'offer-option-status', '暂时售罄'));
@ -721,15 +796,14 @@ function renderOfferPicker() {
button.setAttribute('aria-disabled', String(!sellable));
button.setAttribute('aria-pressed', String(sellable && selectedOfferId === String(offer.id)));
button.setAttribute('aria-label', sellable
? `选择实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price}`
: `实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price},暂时售罄`);
? `选择实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic}`
: `实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},暂时售罄`);
button.append(
name,
makeElement('span', 'offer-option-value', `${offer.cpu_cores} vCPU`),
makeElement('span', 'offer-option-value', memory),
makeElement('span', 'offer-option-value', `${offer.disk_gib} GB`),
makeElement('span', 'offer-option-value', traffic),
makeElement('strong', 'offer-option-price', price),
);
if (sellable) button.addEventListener('click', () => void selectOffer(String(offer.id)));
return button;
@ -746,6 +820,7 @@ async function selectRegion(regionId) {
byId('vm-region').value = state.selectedRegionId;
byId('vm-line').value = state.selectedLineId;
byId('vm-offer').value = '';
if (byId('vm-automatic-backup')) byId('vm-automatic-backup').checked = false;
renderRegionPicker();
renderLinePicker();
renderOfferPicker();
@ -761,6 +836,7 @@ async function selectLine(lineId) {
state.selectedLineId = line.id;
byId('vm-line').value = line.id;
byId('vm-offer').value = '';
if (byId('vm-automatic-backup')) byId('vm-automatic-backup').checked = false;
byId('vm-line-picker')?.querySelectorAll('.line-option').forEach(button => {
button.setAttribute('aria-pressed', String(button.dataset.lineId === line.id));
});
@ -783,6 +859,7 @@ async function selectOffer(offerId) {
async function openCreate(bootstrap = null) {
state.view = 'create'; state.selectedVmId = null; showError('create-error', '');
byId('vm-offer').value = '';
initializeDeploymentOptions();
if (bootstrap && Array.isArray(bootstrap.offers) && Array.isArray(bootstrap.regions)
&& Array.isArray(bootstrap.lines) && Array.isArray(bootstrap.templates)) {
applySaleCatalog(bootstrap);
@ -799,6 +876,7 @@ async function openCreate(bootstrap = null) {
byId('vm-template').disabled = !state.templates.some(item => item?.id);
byId('vm-name').disabled = false;
byId('vm-root-password').disabled = false;
applyDeploymentSource();
setDeploymentStepEnabled('vm-line-step', state.linesEnabled && Boolean(state.selectedRegionId));
setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId));
setDeploymentStepEnabled('vm-source-step', true);
@ -844,6 +922,7 @@ async function loadGlobalTemplates() {
byId('vm-template').disabled = !state.templates.some(item => item?.id);
byId('vm-name').disabled = false;
byId('vm-root-password').disabled = false;
applyDeploymentSource();
setDeploymentStepEnabled('vm-source-step', true);
setDeploymentStepEnabled('vm-config-step', true);
updateCreateAvailability();
@ -889,8 +968,8 @@ async function existingProvisionInvoice(key) {
async function buy(event) {
event.preventDefault(); if (state.mutationBusy) return;
const password = byId('vm-root-password').value;
if (!strongPassword(password)) return showError('create-error', '密码需为 12 至 128 位英文可打印字符且不能包含空格,并包含大写、小写、数字和符号。');
if (!byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。');
if (!state.deployBackupId && !strongPassword(password)) return showError('create-error', '密码需为 12 至 128 位英文可打印字符且不能包含空格,并包含大写、小写、数字和符号。');
if (!state.deployBackupId && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。');
if (!byId('vm-offer').value) return showError('create-error', '请先选择可用实例规格。');
const selectedOffer = saleOffers().find(offer => String(offer.id) === byId('vm-offer').value);
if (!selectedOffer) return showError('create-error', '地区、线路与实例规格不匹配,请重新选择。');
@ -899,9 +978,13 @@ async function buy(event) {
const formBody = byId('create-form')?.querySelector('.workspace-form-body');
if (formBody) { formBody.inert = true; formBody.setAttribute('aria-busy', 'true'); }
byId('create-submit').disabled = true; showError('create-error', '');
const body = { offer_id: Number(byId('vm-offer').value), name: byId('vm-name').value.trim(), source: 'cloud', template_id: byId('vm-template').value };
if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create;
if (password) body.root_password = password;
const body = { offer_id: Number(byId('vm-offer').value), name: byId('vm-name').value.trim(),
source: state.deployBackupId ? 'backup' : 'cloud',
automatic_backup: byId('vm-automatic-backup')?.checked === true };
if (state.deployBackupId) body.backup_id = Number(state.deployBackupId);
else body.template_id = byId('vm-template').value;
if (!state.deployBackupId && state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create;
if (!state.deployBackupId && password) body.root_password = password;
try {
const fingerprint = await provisionInvoiceFingerprint(body);
const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint);

@ -218,7 +218,7 @@ tbody tr:hover{background:#fcfefe}
.line-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)}
.line-option strong{font-size:13px;line-height:1.5;overflow-wrap:anywhere}
.offer-picker{display:grid;min-width:0;overflow:hidden;border:1px solid #dce7ec;border-radius:11px;background:#fff}
.offer-table-head,.offer-option{display:grid;grid-template-columns:minmax(150px,1.35fr) repeat(5,minmax(92px,1fr));align-items:center;column-gap:18px}
.offer-table-head,.offer-option{display:grid;grid-template-columns:minmax(150px,1.35fr) repeat(4,minmax(92px,1fr));align-items:center;column-gap:18px}
.offer-table-head{padding:13px 48px 13px 19px;border-bottom:1px solid #e5ecef;background:#f8fafb;color:#8292a3;font-size:10px;font-weight:800}
.offer-option{position:relative;width:100%;min-width:0;min-height:72px;padding:15px 48px 15px 19px;border:0;border-bottom:1px solid #e7edef;border-radius:0;background:#fff;color:#4e6577;text-align:left}
.offer-option:last-of-type{border-bottom:0;border-bottom-right-radius:10px;border-bottom-left-radius:10px}
@ -226,14 +226,20 @@ tbody tr:hover{background:#fcfefe}
.offer-option:focus-visible{z-index:2;outline:3px solid rgba(18,166,176,.22);outline-offset:-3px}
.offer-option[aria-pressed="true"]{z-index:1;background:#eef9fa;box-shadow:inset 0 0 0 2px #2eabb4;color:#30485d}
.offer-option[aria-pressed="true"]::after{content:"✓";position:absolute;top:8px;right:10px;display:grid;place-items:center;width:21px;height:21px;border-radius:50%;background:#18a6b0;color:#fff;font-size:12px;font-weight:900}
.offer-option-name,.offer-option-price{min-width:0;color:#273d52;font-size:12px;overflow-wrap:anywhere}
.offer-option-name{min-width:0;color:#273d52;font-size:12px;overflow-wrap:anywhere}
.offer-option-name{display:flex;align-items:center;gap:7px;flex-wrap:wrap}
.offer-option-price{color:#0d929d;font-size:13px}
.offer-option-value{min-width:0;font-size:11px;font-weight:700;white-space:nowrap}
.offer-option.is-sold-out{cursor:not-allowed;opacity:1;background:#f8fafb;color:#8b99a6}
.offer-option.is-sold-out:hover{background:#f8fafb}
.offer-option.is-sold-out .offer-option-name,.offer-option.is-sold-out .offer-option-price{color:#697b8c}
.offer-option.is-sold-out .offer-option-name{color:#697b8c}
.offer-option-status{display:inline-flex;align-items:center;min-height:20px;padding:2px 7px;border-radius:999px;background:#edf1f4;color:#6f7e8c;font-size:9px;font-weight:800;line-height:1;white-space:nowrap}
.deployment-backup-source{display:flex;align-items:center;gap:13px;padding:16px 17px;border:1px solid #bce0e2;border-radius:11px;background:#f2fbfb;color:#315165}
.deployment-backup-source[hidden]{display:none}
.deployment-backup-source-icon{display:grid;place-items:center;flex:0 0 40px;width:40px;height:40px;border-radius:10px;background:#dff5f5;color:#168d96;font-size:21px}
.deployment-backup-source>div{display:grid;gap:3px;min-width:0;flex:1}.deployment-backup-source strong{font-size:13px}.deployment-backup-source small{color:#718798;font-size:10px;overflow-wrap:anywhere}.deployment-backup-source .button{flex:none}
.deployment-addon-option{display:flex;align-items:flex-start;gap:13px;padding:17px 18px;border:1px solid #dce7ec;border-radius:11px;background:#fff;cursor:pointer;transition:border-color .18s,background .18s,box-shadow .18s}
.deployment-addon-option:hover{border-color:#acdadd;background:#f8fcfc}.deployment-addon-option:has(input:checked){border-color:#2eabb4;background:#eef9fa;box-shadow:inset 0 0 0 1px #2eabb4}.deployment-addon-option.is-disabled{cursor:not-allowed;opacity:.62;background:#f7f9fa}.deployment-addon-option input{margin:3px 0 0;accent-color:#18a6b0}.deployment-addon-option span{display:grid;gap:4px}.deployment-addon-option strong{color:#30485d;font-size:13px}.deployment-addon-option small{color:#7f91a0;font-size:10px;line-height:1.6}
.deployment-order-summary>dl{margin:0;border:1px solid #dfe9ed;border-radius:11px;background:#fbfdfd;overflow:hidden}.deployment-order-summary>dl>div{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:13px 17px;border-bottom:1px solid #e7edef}.deployment-order-summary>dl>div:last-child{border-bottom:0}.deployment-order-summary dt{color:#718496;font-size:11px;font-weight:700}.deployment-order-summary dd{margin:0;color:#30475b;font-size:12px;font-weight:800}.deployment-order-summary .deployment-order-total{background:#eef9fa}.deployment-order-summary .deployment-order-total dt{color:#286f75}.deployment-order-summary .deployment-order-total dd{color:#0d929d;font-size:17px}
/* Keep every user-facing button control free of browser or hover underlines.
Plain content and navigation links intentionally keep their own styling. */
body[data-cloud-page] :is(button, [role="button"], .button, .row-button, .icon-button, .vu-btn, .vu-icon-btn),
@ -264,6 +270,7 @@ body.vu-body .ssh-key-picker-manage:hover {
.user-iso-details small{color:#8b9cab;font-size:10px;line-height:1.5;overflow-wrap:anywhere}
.user-iso-delete{flex:none;color:#b94b57;border-color:#efd8dc}
.user-isos-grid .host-test-status{margin:16px 0 0}
.cloud-backups-notice{margin-bottom:20px}.cloud-backups-panel{padding:0;overflow:hidden}.cloud-backups-panel>.panel-heading{padding:20px 22px;border-bottom:1px solid #e8eef2}.cloud-backups-panel>#cloud-backups-status{margin:18px 22px 0}.cloud-backups-list{display:grid;gap:13px;padding:20px 22px}.cloud-backup-card{display:grid;gap:17px;padding:18px;border:1px solid #dfe8ed;border-radius:11px;background:#fff}.cloud-backup-card-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:15px}.cloud-backup-title{display:flex;align-items:center;gap:11px;min-width:0;color:#2b4358;font-size:13px;font-weight:800}.cloud-backup-title>div{display:grid;gap:3px;min-width:0;overflow-wrap:anywhere}.cloud-backup-title small{color:#8192a1;font-size:10px;font-weight:500}.cloud-backup-icon{display:grid;place-items:center;flex:0 0 38px;width:38px;height:38px;border-radius:10px;background:#eaf8f8;color:#168e97;font-size:18px}.cloud-backup-facts{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:11px;margin:0}.cloud-backup-facts>div{display:grid;gap:4px;min-width:0;padding:11px 12px;border-radius:8px;background:#f7f9fa}.cloud-backup-facts dt{color:#8998a6;font-size:9px;font-weight:700}.cloud-backup-facts dd{margin:0;color:#40566a;font-size:11px;font-weight:750;overflow-wrap:anywhere}.cloud-backup-actions{display:flex;align-items:center;justify-content:flex-end;gap:9px;flex-wrap:wrap}.cloud-backups-empty{display:grid;justify-items:center;gap:6px;padding:45px 18px;color:#8595a3;text-align:center}.cloud-backups-empty strong{color:#52697b;font-size:14px}.cloud-backups-empty span{font-size:11px}.cloud-backups-pagination{display:flex;align-items:center;justify-content:center;gap:14px;padding:16px 22px;border-top:1px solid #e8eef2;background:#fbfcfd}.cloud-backups-pagination span{min-width:100px;color:#7f909f;font-size:10px;text-align:center}
@media(max-width:960px){.user-isos-grid{grid-template-columns:1fr}}
@media(max-width:740px){
.region-picker,.line-picker{grid-template-columns:repeat(2,minmax(0,1fr))}
@ -271,15 +278,17 @@ body.vu-body .ssh-key-picker-manage:hover {
.offer-option:first-of-type{border-top-left-radius:10px;border-top-right-radius:10px}
.offer-option{grid-template-columns:repeat(2,minmax(0,1fr));gap:13px 18px;min-height:0;padding:18px 45px 18px 18px}
.offer-option-name{grid-column:1/-1;font-size:13px}
.offer-option-value,.offer-option-price{display:grid;gap:3px;white-space:normal}
.offer-option-value::before,.offer-option-price::before{color:#91a0ae;font-size:9px;font-weight:800}
.offer-option-value{display:grid;gap:3px;white-space:normal}
.offer-option-value::before{color:#91a0ae;font-size:9px;font-weight:800}
.offer-option>:nth-child(2)::before{content:"CPU"}
.offer-option>:nth-child(3)::before{content:"内存"}
.offer-option>:nth-child(4)::before{content:"硬盘"}
.offer-option>:nth-child(5)::before{content:"每期流量"}
.offer-option>:nth-child(6)::before{content:"价格"}
.cloud-backup-facts{grid-template-columns:repeat(2,minmax(0,1fr))}
}
@media(max-width:510px){.deployment-step{padding-bottom:23px;margin-bottom:22px}.deployment-step-heading{margin-bottom:16px}.region-picker,.line-picker{grid-template-columns:1fr}.region-option{min-height:66px}.line-option{min-height:54px}.offer-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;padding:15px 14px 14px 16px}.offer-option::after{content:"";position:absolute;top:13px;right:14px;display:grid;place-items:center;width:22px;height:22px;border:1.5px solid #bdccd4;border-radius:50%;background:#fff;color:transparent;font-size:12px;font-weight:900}.offer-option[aria-pressed="true"]{box-shadow:none}.offer-option[aria-pressed="true"]::after{content:"✓";top:13px;right:14px;width:22px;height:22px;border:1.5px solid #18a6b0;background:#18a6b0;color:#fff}.offer-option.is-sold-out::after{display:none}.offer-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}.offer-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;font-size:14px;white-space:nowrap}.offer-option.is-sold-out .offer-option-price{padding-right:0}.offer-option-price::before{display:none;content:none}.offer-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}.offer-option-value::before{color:#718599;font-size:9px;font-weight:800;white-space:nowrap}.offer-option>:nth-child(2){grid-column:1}.offer-option>:nth-child(3){grid-column:2}.offer-option>:nth-child(4){grid-column:3}.offer-option>:nth-child(5){grid-column:4}.template-family-card{height:140px;min-height:140px;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden;box-shadow:none}.template-family-summary{height:100%;min-height:100%;border:0;border-radius:inherit;background:transparent}.template-family-card[open]{z-index:70;border-color:#a8dadd;box-shadow:0 12px 28px rgba(30,66,82,.14)}.template-family-card.has-selection{border-color:#2eabb4;background:#f5fbfb}.template-versions{position:absolute;inset:0;z-index:80;width:auto;height:auto;max-height:none;margin:0;padding:6px 8px 40px;overflow-y:auto;border:0;border-radius:inherit;background:#fbfdfd;box-shadow:none;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}.template-family-card[open] .template-family-footer{position:absolute;right:7px;bottom:7px;z-index:90;width:32px;min-height:32px;border-radius:999px;background:#eaf8f8}.template-family-card[open] .template-family-selection{display:none}.user-iso-row{align-items:flex-start;flex-direction:column}.user-iso-row .row-button{width:100%}}
@media(max-width:510px){.deployment-step{padding-bottom:23px;margin-bottom:22px}.deployment-step-heading{margin-bottom:16px}.region-picker,.line-picker{grid-template-columns:1fr}.region-option{min-height:66px}.line-option{min-height:54px}.offer-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;padding:15px 14px 14px 16px}.offer-option::after{content:"";position:absolute;top:13px;right:14px;display:grid;place-items:center;width:22px;height:22px;border:1.5px solid #bdccd4;border-radius:50%;background:#fff;color:transparent;font-size:12px;font-weight:900}.offer-option[aria-pressed="true"]{box-shadow:none}.offer-option[aria-pressed="true"]::after{content:"✓";top:13px;right:14px;width:22px;height:22px;border:1.5px solid #18a6b0;background:#18a6b0;color:#fff}.offer-option.is-sold-out::after{display:none}.offer-option-name{grid-column:1/5;grid-row:1;align-self:center;padding-right:31px;font-size:14px}.offer-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}.offer-option-value::before{color:#718599;font-size:9px;font-weight:800;white-space:nowrap}.offer-option>:nth-child(2){grid-column:1}.offer-option>:nth-child(3){grid-column:2}.offer-option>:nth-child(4){grid-column:3}.offer-option>:nth-child(5){grid-column:4}.deployment-backup-source{align-items:flex-start;flex-wrap:wrap}.deployment-backup-source .button{width:100%}.template-family-card{height:140px;min-height:140px;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden;box-shadow:none}.template-family-summary{height:100%;min-height:100%;border:0;border-radius:inherit;background:transparent}.template-family-card[open]{z-index:70;border-color:#a8dadd;box-shadow:0 12px 28px rgba(30,66,82,.14)}.template-family-card.has-selection{border-color:#2eabb4;background:#f5fbfb}.template-versions{position:absolute;inset:0;z-index:80;width:auto;height:auto;max-height:none;margin:0;padding:6px 8px 40px;overflow-y:auto;border:0;border-radius:inherit;background:#fbfdfd;box-shadow:none;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}.template-family-card[open] .template-family-footer{position:absolute;right:7px;bottom:7px;z-index:90;width:32px;min-height:32px;border-radius:999px;background:#eaf8f8}.template-family-card[open] .template-family-selection{display:none}.user-iso-row{align-items:flex-start;flex-direction:column}.user-iso-row .row-button{width:100%}}
@media(max-width:510px){.cloud-backups-panel>.panel-heading,.cloud-backups-list{padding-inline:16px}.cloud-backup-card{padding:15px}.cloud-backup-facts{grid-template-columns:1fr 1fr}.cloud-backup-actions .button{flex:1 1 100%;width:100%}.cloud-backups-pagination{gap:8px;padding-inline:14px}.cloud-backups-pagination .button{min-width:82px}}
.vm-state-sync{display:block;margin-top:4px;color:#8b9aaa;font-size:10px;line-height:1.35;white-space:nowrap}.vm-state-sync.stale{color:#b98129}.vm-state-sync.offline{color:#bd5b63}.vm-detail-state-stack{display:flex;flex-direction:column;align-items:flex-end;gap:3px}.vm-detail-state-stack .vm-state-sync{margin-top:0}
.vm-ip-change-facts{display:grid;grid-template-columns:1fr;gap:1px;margin:0 0 24px;padding:1px;background:#e5ecef}.vm-ip-change-facts>div{min-width:0;padding:14px 16px;background:#fff}.vm-ip-change-facts dt{margin-bottom:5px;color:#8796a4;font-size:10px}.vm-ip-change-facts dd{margin:0;color:#294257;font:700 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}@media screen and (max-width:510px){.vm-ip-change-facts>div{padding:11px 13px}}
.vm-upgrade-section{max-width:880px}.vm-upgrade-current-card{margin:0 0 25px;padding:18px;border:1px solid #e1e9ed;border-radius:10px;background:#fbfcfd}.vm-upgrade-current-card h4,.vm-upgrade-picker-heading h4{margin:0;color:#314a5f;font-size:13px}.vm-upgrade-spec-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;margin:14px 0 0;padding:1px;background:#e3eaee}.vm-upgrade-spec-grid>div{min-width:0;padding:11px 13px;background:#fff}.vm-upgrade-spec-grid dt{margin-bottom:4px;color:#8797a5;font-size:9px}.vm-upgrade-spec-grid dd{margin:0;color:#294257;font-size:11px;font-weight:800;overflow-wrap:anywhere}.vm-upgrade-picker-heading{display:flex;align-items:baseline;justify-content:space-between;gap:15px;margin-bottom:11px}.vm-upgrade-picker-heading span{color:#8a99a7;font-size:10px}.vm-upgrade-offers{display:grid;gap:10px;margin:0 0 22px}.vm-upgrade-offer{position:relative;display:grid;width:100%;gap:14px;padding:16px 18px;border:1px solid #dce7ec;border-radius:10px;background:#fff;color:#50677a;text-align:left;cursor:pointer}.vm-upgrade-offer:hover:not(:disabled){border-color:#8ecdd2;background:#f8fcfc}.vm-upgrade-offer:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.vm-upgrade-offer[aria-checked=true]{border-color:#2eabb4;background:#eef9fa;box-shadow:inset 0 0 0 1px #2eabb4}.vm-upgrade-offer[aria-checked=true]::after{content:"✓";position:absolute;top:10px;right:10px;display:grid;place-items:center;width:21px;height:21px;border-radius:50%;background:#18a6b0;color:#fff;font-size:12px;font-weight:900}.vm-upgrade-offer:disabled{cursor:not-allowed;opacity:.66}.vm-upgrade-offer-heading{display:flex;align-items:center;justify-content:space-between;gap:35px;padding-right:21px}.vm-upgrade-offer-name{min-width:0;color:#293f53;font-size:13px;overflow-wrap:anywhere}.vm-upgrade-offer-price{flex:none;color:#0d929d;font-size:13px}.vm-upgrade-offer-facts{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}.vm-upgrade-offer-fact{display:grid;min-width:0;gap:3px}.vm-upgrade-offer-fact small{color:#8a99a7;font-size:9px}.vm-upgrade-offer-fact b{color:#445d70;font-size:10px;overflow-wrap:anywhere}.vm-upgrade-empty{margin:0;padding:24px;border:1px dashed #d7e1e6;border-radius:10px;color:#8494a2;font-size:11px;text-align:center}@media screen and (max-width:510px){.vm-upgrade-current-card{padding:14px}.vm-upgrade-spec-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.vm-upgrade-picker-heading{align-items:flex-start;flex-direction:column;gap:4px}.vm-upgrade-offer{gap:13px;padding:15px}.vm-upgrade-offer-heading{align-items:flex-start;flex-direction:column;gap:5px;padding-right:27px}.vm-upgrade-offer-facts{grid-template-columns:repeat(2,minmax(0,1fr));gap:11px 8px}.vm-upgrade-offer-fact:last-child{grid-column:1/-1}.vm-upgrade-offer-price{font-size:12px}}
.vm-automatic-backup-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-automatic-backup-field-label{color:#40566a;font-size:12px;font-weight:800}.vm-automatic-backup-fixed-time{display:flex;align-items:center;height:44px;padding:0 13px;border:1px solid #dbe5ea;border-radius:8px;background:#f7f9fa;color:#40566a;font-size:12px}.vm-automatic-backup-list-heading{display:flex;align-items:center;justify-content:space-between;gap:15px;margin:32px 0 12px;padding-top:24px;border-top:1px solid #e6ecef}.vm-automatic-backup-list-heading h4{margin:0 0 4px;color:#354c60;font-size:14px}.vm-automatic-backup-list-heading small{color:#8797a5;font-size:10px}.vm-automatic-backup-list{display:grid;gap:10px}.vm-automatic-backup-card{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:13px 18px;padding:15px;border:1px solid #dfe8ed;border-radius:9px;background:#fbfdfd}.vm-automatic-backup-card-main{display:grid;gap:5px;min-width:0}.vm-automatic-backup-card-main strong{color:#31495d;font-size:12px;overflow-wrap:anywhere}.vm-automatic-backup-card-main small{color:#8192a1;font-size:10px;line-height:1.55}.vm-automatic-backup-card-status{align-self:start}.vm-automatic-backup-card-actions{grid-column:1/-1;display:flex;justify-content:flex-end}.vm-automatic-backup-empty{display:grid;gap:5px;padding:25px 17px;border:1px dashed #cedce2;border-radius:9px;color:#8797a5;text-align:center}.vm-automatic-backup-empty strong{color:#506779;font-size:12px}.vm-automatic-backup-empty span{font-size:10px}@media screen and (max-width:740px){.vm-automatic-backup-grid{grid-template-columns:1fr}}@media screen and (max-width:510px){.vm-automatic-backup-list-heading{align-items:flex-start;flex-direction:column}.vm-automatic-backup-list-heading .button{width:100%}.vm-automatic-backup-card{grid-template-columns:1fr}.vm-automatic-backup-card-status,.vm-automatic-backup-card-actions{grid-column:1}.vm-automatic-backup-card-actions .button{width:100%}}

@ -4,6 +4,7 @@
{assign var=offer_code value=$offer->code}
{assign var=offer_name value=$offer->name}
{assign var=offer_price value=$offer->price}
{assign var=offer_backup_price value=$offer->backup_price}
{assign var=offer_stock value=$offer->stock}
{assign var=offer_sort value=$offer->sort}
{else}
@ -12,6 +13,7 @@
{assign var=offer_code value=''}
{assign var=offer_name value=''}
{assign var=offer_price value='0.00'}
{assign var=offer_backup_price value='0.00'}
{assign var=offer_stock value=-1}
{assign var=offer_sort value=0}
{/if}
@ -60,9 +62,10 @@
</details>
<details class="card admin-config-section" open>
<summary><span><strong>价格与销售状态</strong><small>价格固定使用 USD;库存为 0 或下架时停止新购。</small></span><i class="mdi mdi-chevron-down" aria-hidden="true"></i></summary>
<summary><span><strong>价格与销售状态</strong><small>实例和自动备份价格固定使用 USD;库存为 0 或下架时停止新购。</small></span><i class="mdi mdi-chevron-down" aria-hidden="true"></i></summary>
<div class="admin-config-body"><div class="row g-3">
<div class="col-md-6 col-xl-4"><label class="form-label" for="price">每期价格(USD)</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="price" name="price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div>{if $offer}<div class="form-text">当前价格版本 v{$offer->price_version|escape};修改价格后自动递增。</div>{/if}</div>
<div class="col-md-6 col-xl-4"><label class="form-label" for="backup_price">自动备份每期价格(USD)</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="backup_price" name="backup_price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_backup_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div><div class="form-text">所有在售规格均可选购自动备份;这里只配置价格,备份频率和保留数量由用户在实例设置中选择。</div></div>
<div class="col-md-6 col-xl-4"><label class="form-label" for="stock">可售库存</label><input class="form-control" id="stock" name="stock" type="number" min="-1" max="2147483647" step="1" value="{$offer_stock|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}><div class="form-text">-1 表示不限库存,0 表示暂停新购。</div></div>
<div class="col-md-6 col-xl-4"><label class="form-label" for="status">销售状态</label><select class="form-select" id="status" name="status" {if !$admin_can_manage|default:false}disabled{/if}><option value="1" {if !$offer || $offer->status}selected{/if}>上架销售</option><option value="0" {if $offer && !$offer->status}selected{/if}>下架停售</option></select><div class="form-text">下架不会删除历史订单或已开通实例。</div></div>
</div></div>

@ -28,6 +28,8 @@
{include file='cloud/pages/detail.tpl'}
{elseif $cloud_page == 'deploy'}
{include file='cloud/pages/deploy.tpl'}
{elseif $cloud_page == 'backups'}
{include file='cloud/pages/backups.tpl'}
{elseif $cloud_page == 'isos'}
{include file='cloud/pages/isos.tpl'}
{elseif $cloud_page == 'keys'}

@ -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>

@ -43,7 +43,7 @@
{assign var=default_line_has_offers value=false}
{foreach $cloud_deploy_offers as $offer}
{if $offer.region_id == $cloud_deploy_default_region_id && $offer.line_id == $cloud_deploy_default_line_id}
{if !$default_line_has_offers}<div class="offer-table-head"><span>名称</span><span>CPU</span><span>内存</span><span>硬盘</span><span>每期流量</span><span>价格</span></div>{/if}
{if !$default_line_has_offers}<div class="offer-table-head"><span>名称</span><span>CPU</span><span>内存</span><span>硬盘</span><span>每期流量</span></div>{/if}
{assign var=default_line_has_offers value=true}
{assign var=offer_memory_gib value=$offer.memory_mib/1024}
<button class="offer-option{if empty($offer.sellable)} is-sold-out{/if}" type="button" data-offer-id="{$offer.id|escape:"html"}" aria-pressed="false" aria-disabled="{if empty($offer.sellable)}true{else}false{/if}" aria-label="{if empty($offer.sellable)}实例规格 {$offer.name|escape:"html"},暂时售罄{else}选择实例规格 {$offer.name|escape:"html"}{/if}"{if empty($offer.sellable)} disabled{/if}>
@ -52,7 +52,6 @@
<span class="offer-option-value">{$offer_memory_gib|string_format:"%g"|escape:"html"} GB</span>
<span class="offer-option-value">{$offer.disk_gib|escape:"html"} GB</span>
<span class="offer-option-value">{if $offer.traffic_gib == 0}不限{else}{$offer.traffic_tib|escape:"html"} TB{/if}</span>
<strong class="offer-option-price">${$offer.price|escape:"html"} USD</strong>
</button>
{/if}
{/foreach}
@ -61,6 +60,12 @@
</section>
<section id="vm-source-step" class="deployment-step" aria-labelledby="deploy-source-title" aria-disabled="false">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}4{else}3{/if}</span><h2 id="deploy-source-title">选择系统镜像<span class="deployment-required-mark" aria-hidden="true">*</span><span class="sr-only">(必选)</span></h2></div>
<input id="vm-backup-id" type="hidden" value="" />
<div id="vm-backup-source" class="deployment-backup-source" hidden>
<span class="deployment-backup-source-icon" aria-hidden="true"><i class="mdi mdi-cloud-check-outline"></i></span>
<div><strong>从云备份创建新实例</strong><small id="vm-backup-source-name">正在核对备份…</small></div>
<a class="button button-outline small" href="/user/cloud/backups">重新选择</a>
</div>
<div class="field full" id="vm-template-field"><input id="vm-template" name="template_id" type="hidden" value=""{if empty($cloud_deploy_template_groups)} disabled{/if} /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="deploy-source-title" aria-required="true">
{if empty($cloud_deploy_template_groups)}
<p class="template-catalog-empty">{if !empty($cloud_deploy_catalog_unavailable)}系统镜像目录暂时无法读取,请稍后刷新。{else}暂无可用云镜像,请联系管理员导入模板。{/if}</p>
@ -89,6 +94,23 @@
<div class="cloud-fields full" id="vm-cloud-fields"><div class="form-grid vm-cloud-auth-fields"><div class="field full"><span class="ssh-key-picker-title">SSH 公钥</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="部署实例时选择 SSH 公钥">{if empty($cloud_deploy_ssh_keys)}<p class="muted">暂无公钥,可先到“公钥管理”添加。</p>{else}{foreach $cloud_deploy_ssh_keys as $key}<button class="ssh-key-option" type="button" aria-pressed="false" data-key-id="{$key.id|escape:"html"}" aria-label="选择 SSH 公钥 {$key.name|escape:"html"},指纹 {$key.fingerprint|escape:"html"}"><i class="mdi mdi-key-variant ssh-key-choice-icon" aria-hidden="true"></i><span class="ssh-key-choice-copy"><strong class="ssh-key-choice-label">{$key.name|escape:"html"}</strong><small class="ssh-key-choice-fingerprint" title="{$key.fingerprint|escape:"html"}">{$key.fingerprint|escape:"html"}</small></span><span class="ssh-key-choice-check" aria-hidden="true">&#x2713;</span></button>{/foreach}{/if}</div><a id="vm-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div><div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码</label><input id="vm-root-password" name="root_password" type="password" maxlength="128" autocomplete="new-password" spellcheck="false" /></div></div></div>
</div>
</section>
<section id="vm-backup-step" class="deployment-step" aria-labelledby="deploy-backup-title">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}6{else}5{/if}</span><h2 id="deploy-backup-title">自动备份</h2></div>
<label id="vm-automatic-backup-option" class="deployment-addon-option is-disabled">
<input id="vm-automatic-backup" name="automatic_backup" type="checkbox" disabled/>
<span><strong>启用自动备份</strong><small id="vm-automatic-backup-help">选择实例规格后可以启用。</small></span>
</label>
</section>
<section id="vm-order-summary-step" class="deployment-step deployment-order-summary" aria-labelledby="deploy-order-summary-title">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}7{else}6{/if}</span><h2 id="deploy-order-summary-title">确认费用</h2></div>
<p id="vm-order-summary-empty" class="muted">选择实例规格后显示本次最终金额。</p>
<dl id="vm-order-summary" aria-live="polite" hidden>
<div><dt>实例费用</dt><dd id="vm-order-instance-price">—</dd></div>
<div id="vm-order-backup-row" hidden><dt>自动备份</dt><dd id="vm-order-backup-price">—</dd></div>
<div class="deployment-order-total"><dt>本次应付</dt><dd id="vm-order-total-price">—</dd></div>
<div><dt>下次续费</dt><dd id="vm-order-renewal-price">—</dd></div>
</dl>
</section>
<p id="create-error" class="form-error" role="alert" hidden></p>
</div>
<div class="workspace-form-actions"><button id="create-submit" class="button button-primary" type="submit" disabled>创建实例</button></div>

@ -52,6 +52,7 @@
<button id="vm-settings-nav-ssh-key" class="vm-settings-navigation-button" type="button" role="tab" aria-selected="false" aria-controls="vm-settings-section-ssh-key" data-instance-setting-tab="ssh_key" tabindex="-1">更新 SSH 公钥</button>
<button id="vm-settings-nav-ip-change" class="vm-settings-navigation-button" type="button" role="tab" aria-selected="false" aria-controls="vm-settings-section-ip-change" data-instance-setting-tab="ip_change" tabindex="-1">付费更换 IP</button>
<button id="vm-settings-nav-upgrade" class="vm-settings-navigation-button" type="button" role="tab" aria-selected="false" aria-controls="vm-settings-section-upgrade" data-instance-setting-tab="upgrade" tabindex="-1">实例升级</button>
<button id="vm-settings-nav-automatic-backup" class="vm-settings-navigation-button" type="button" role="tab" aria-selected="false" aria-controls="vm-settings-section-automatic-backup" data-instance-setting-tab="automatic_backup" tabindex="-1">自动备份</button>
<button id="vm-settings-nav-firewall" class="vm-settings-navigation-button" type="button" role="tab" aria-selected="false" aria-controls="vm-settings-section-firewall" data-instance-setting-tab="firewall" tabindex="-1">防火墙</button>
<button id="vm-settings-nav-snapshots" class="vm-settings-navigation-button" type="button" role="tab" aria-selected="false" aria-controls="vm-settings-section-snapshots" data-instance-setting-tab="snapshots" tabindex="-1">在线快照</button>
{/if}
@ -153,6 +154,24 @@
<p id="vm-firewall-form-error" class="form-error" role="alert" hidden></p>
</form>
</section>
<section id="vm-settings-section-automatic-backup" class="vm-settings-section vm-automatic-backup-section" role="tabpanel" aria-labelledby="vm-settings-nav-automatic-backup" data-instance-setting-panel="automatic_backup" hidden>
<header class="vm-settings-section-heading"><span class="eyebrow">AUTOMATIC BACKUP</span><h3>自动备份</h3><p>管理这台实例的自动备份计划,并选择已有备份恢复当前实例。</p></header>
<div class="vm-settings-notice"><strong>固定执行时间</strong><span>自动任务统一在太平洋时间 00:00 执行;系统使用 America/Los_Angeles 时区并自动处理夏令时。</span></div>
<div class="vm-settings-notice warning"><strong>恢复会覆盖当前系统盘</strong><span>恢复当前实例必须在这里操作。恢复期间实例会停止,系统盘将回到所选备份的内容;账单、服务周期和公网 IP 不会回滚。</span></div>
<p id="vm-automatic-backup-status" class="vm-settings-status" role="status" aria-live="polite">打开本栏目后加载。</p>
<form id="vm-automatic-backup-form" class="vm-settings-form" novalidate>
<div class="vm-automatic-backup-grid">
<div class="vm-settings-field"><label for="vm-automatic-backup-frequency">备份频率</label><select id="vm-automatic-backup-frequency" name="frequency" disabled><option value="daily" selected>每天</option><option value="weekly">每周</option></select></div>
<div id="vm-automatic-backup-weekday-field" class="vm-settings-field" hidden><label for="vm-automatic-backup-weekday">每周执行日</label><select id="vm-automatic-backup-weekday" name="weekday" disabled><option value="0" selected>星期日</option><option value="1">星期一</option><option value="2">星期二</option><option value="3">星期三</option><option value="4">星期四</option><option value="5">星期五</option><option value="6">星期六</option></select></div>
<div class="vm-settings-field"><label for="vm-automatic-backup-retention">保留份数</label><select id="vm-automatic-backup-retention" name="retention_count" disabled><option value="1">保留 1 份</option><option value="2" selected>保留 2 份</option></select><small>最多保留 2 份;超过数量后自动删除最早的一份。</small></div>
<div class="vm-settings-field"><span class="vm-automatic-backup-field-label">执行时间</span><strong class="vm-automatic-backup-fixed-time">太平洋时间 00:00</strong></div>
</div>
<div class="vm-settings-actions"><button id="vm-automatic-backup-save" class="button button-primary" type="submit" disabled>保存备份计划</button></div>
<p id="vm-automatic-backup-error" class="form-error" role="alert" hidden></p>
</form>
<div class="vm-automatic-backup-list-heading"><div><h4>此实例的备份</h4><small>在“云备份”页面可使用这些备份创建新实例。</small></div><a class="button button-outline small" href="/user/cloud/backups">查看全部备份</a></div>
<div id="vm-automatic-backup-list" class="vm-automatic-backup-list" aria-live="polite"></div>
</section>
<section id="vm-settings-section-snapshots" class="vm-settings-section" role="tabpanel" aria-labelledby="vm-settings-nav-snapshots" data-instance-setting-panel="snapshots" hidden>
<header class="vm-settings-section-heading"><span class="eyebrow">ONLINE SNAPSHOTS</span><h3>在线快照</h3><p>为当前系统盘创建短期恢复点,每台实例最多保留 2 份。</p></header>
<div class="vm-settings-notice"><strong>创建无需关机</strong><span>QEMU Guest Agent(QGA)可用时会短暂冻结文件系统;恢复时会短暂关机并回到快照中的系统盘。快照不包含内存,也不回滚账单、服务周期、公网 IP 或当前登录设置;保留快照期间不能重装系统。</span></div>

@ -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'}

@ -20,6 +20,9 @@
<a class="sidebar-link{if $panel_cloud_active_key == 'deploy'} active{/if}" href="/user/cloud/deploy">
<i class="mdi mdi-cart-outline nav-icon" aria-hidden="true"></i><span>部署实例</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'backups'} active{/if}" href="/user/cloud/backups">
<i class="mdi mdi-cloud-upload-outline nav-icon" aria-hidden="true"></i><span>云备份</span>
</a>
{if !empty($user_iso_enabled)}
<a class="sidebar-link{if $panel_cloud_active_key == 'isos'} active{/if}" href="/user/cloud/iso-images">
<i class="mdi mdi-disc nav-icon" aria-hidden="true"></i><span>ISO 上传</span>

@ -224,6 +224,7 @@ CREATE TABLE cloud_offers (
code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
name VARCHAR(128) NOT NULL,
price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
backup_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'USD',
price_version INT UNSIGNED NOT NULL DEFAULT 1,
revision INT UNSIGNED NOT NULL DEFAULT 1,
@ -516,6 +517,35 @@ CREATE TABLE cloud_instance_snapshots (
KEY cloud_instance_snapshot_owner (user_id, instance_id, id),
KEY cloud_instance_snapshot_operation (last_operation_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- One paid automatic-backup entitlement belongs to one billed instance. The
-- sales offer freezes only the price; scheduling preferences live here so a
-- user can change them without mutating the commercial plan snapshot.
CREATE TABLE cloud_backup_subscriptions (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
instance_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
offer_id BIGINT UNSIGNED NOT NULL,
enabled TINYINT(1) NOT NULL DEFAULT 1,
renew_next_period TINYINT(1) NOT NULL DEFAULT 1,
frequency VARCHAR(8) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'daily',
weekday TINYINT UNSIGNED NOT NULL DEFAULT 0,
retention_count TINYINT UNSIGNED NOT NULL DEFAULT 2,
timezone VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'America/Los_Angeles',
price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'USD',
price_version INT UNSIGNED NOT NULL,
next_run_at BIGINT UNSIGNED NOT NULL,
last_scheduled_at BIGINT UNSIGNED DEFAULT NULL,
last_backup_id BIGINT UNSIGNED DEFAULT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_backup_subscription_instance (instance_id),
KEY cloud_backup_subscription_due (enabled, next_run_at, id),
KEY cloud_backup_subscription_owner (user_id, id),
CONSTRAINT chk_cloud_backup_subscription_frequency CHECK (frequency IN ('daily','weekly')),
CONSTRAINT chk_cloud_backup_subscription_weekday CHECK (weekday <= 6),
CONSTRAINT chk_cloud_backup_subscription_retention CHECK (retention_count IN (1,2))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Portable, object-storage-backed VM system-disk backups. The immutable
-- source/spec and sealed storage target snapshots keep old backups restorable
-- after the global object-storage configuration changes. Object URLs and
@ -529,6 +559,9 @@ CREATE TABLE cloud_instance_backups (
source_uuid CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
name VARCHAR(80) NOT NULL,
purpose VARCHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'portable',
source VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'manual',
subscription_id BIGINT UNSIGNED DEFAULT NULL,
scheduled_for BIGINT UNSIGNED DEFAULT NULL,
state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'creating',
consistency VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
object_key VARCHAR(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
@ -547,6 +580,7 @@ CREATE TABLE cloud_instance_backups (
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_instance_backup_key (backup_key),
UNIQUE KEY cloud_instance_backup_object (object_key),
UNIQUE KEY cloud_instance_backup_schedule (subscription_id, scheduled_for),
KEY cloud_instance_backup_source (source_instance_id, state, id),
KEY cloud_instance_backup_owner (user_id, id),
KEY cloud_instance_backup_operation (last_operation_id)
@ -578,6 +612,27 @@ CREATE TABLE cloud_backup_restores (
KEY cloud_backup_restore_backup (backup_id, state, id),
KEY cloud_backup_restore_host (target_host_id, state, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Restoring a backup onto its source instance is a destructive disk switch,
-- distinct from creating an independent restored VM. This ledger fences the
-- original operation until its exact Agent receipt is reconciled.
CREATE TABLE cloud_backup_recoveries (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
recovery_key CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
backup_id BIGINT UNSIGNED NOT NULL,
instance_id BIGINT UNSIGNED NOT NULL,
job_id BIGINT UNSIGNED DEFAULT NULL,
operation_id CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'recovering',
error_code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
completed_at BIGINT UNSIGNED DEFAULT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_backup_recovery_key (recovery_key),
UNIQUE KEY cloud_backup_recovery_operation (operation_id),
UNIQUE KEY cloud_backup_recovery_job (job_id),
KEY cloud_backup_recovery_instance (instance_id, state, id),
KEY cloud_backup_recovery_backup (backup_id, state, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- A maintenance migration keeps the original business instance row and its
-- billing/traffic periods. This separate ledger binds the cold source backup,
-- hidden target restore and optional source cleanup without overloading the
@ -696,6 +751,18 @@ CREATE TABLE cloud_orders (
KEY cloud_order_admin_status (status, created_at, id),
KEY cloud_order_admin_user (user_id, created_at, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE cloud_order_items (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
order_id BIGINT UNSIGNED NOT NULL,
code VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
label VARCHAR(128) NOT NULL,
amount DECIMAL(12,2) NOT NULL,
currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'USD',
snapshot_json LONGTEXT NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_order_item_code (order_id, code),
KEY cloud_order_item_order (order_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Reservations are the auditable resource ledger. The per-host capacity
-- policy row is locked before sums over held/committed/uncertain rows are
@ -812,6 +879,20 @@ CREATE TABLE cloud_invoices (
KEY cloud_invoice_admin_user (user_id, created_at, id),
KEY cloud_invoice_admin_method (paid_via, created_at, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE cloud_invoice_items (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
invoice_id BIGINT UNSIGNED NOT NULL,
order_item_id BIGINT UNSIGNED DEFAULT NULL,
code VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
label VARCHAR(128) NOT NULL,
amount DECIMAL(12,2) NOT NULL,
currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'USD',
snapshot_json LONGTEXT NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_invoice_item_code (invoice_id, code),
KEY cloud_invoice_item_invoice (invoice_id, id),
KEY cloud_invoice_item_order_item (order_item_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE cloud_invoice_payments (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
invoice_id BIGINT UNSIGNED NOT NULL,
@ -863,6 +944,7 @@ CREATE TABLE cloud_jobs (
snapshot_id BIGINT UNSIGNED DEFAULT NULL,
backup_id BIGINT UNSIGNED DEFAULT NULL,
backup_restore_id BIGINT UNSIGNED DEFAULT NULL,
backup_recovery_id BIGINT UNSIGNED DEFAULT NULL,
user_id INT NOT NULL,
host_id BIGINT UNSIGNED DEFAULT NULL,
kind VARCHAR(32) NOT NULL,
@ -977,6 +1059,7 @@ CREATE TABLE cloud_jobs (
KEY cloud_job_snapshot (snapshot_id, id),
KEY cloud_job_backup (backup_id, id),
KEY cloud_job_backup_restore (backup_restore_id, id),
KEY cloud_job_backup_recovery (backup_recovery_id, id),
KEY cloud_job_overview_state (kind, order_id, phase, outcome, terminal_at, created_at),
KEY cloud_job_owner (user_id, id),
KEY cloud_job_parent (parent_job_id, id)

@ -18,12 +18,15 @@ namespace {
$valid = [
'resource_pool_id' => '8', 'code' => 'tokyo-premium', 'name' => '东京高级线路',
'price' => '019.9', 'stock' => '-1', 'status' => '1', 'sort' => '-20',
'price' => '019.9', 'backup_price' => '003.5', 'stock' => '-1',
'status' => '1', 'sort' => '-20',
];
$normalized = CloudOffer::validateOffer($valid);
$assert($normalized === [
'resource_pool_id' => 8, 'code' => 'tokyo-premium', 'name' => '东京高级线路',
'price' => '19.90', 'currency' => 'USD', 'status' => 1, 'stock' => -1, 'sort' => -20,
'price' => '19.90', 'backup_price' => '3.50', 'currency' => 'USD',
'status' => 1,
'stock' => -1, 'sort' => -20,
], 'Offer input was not normalized into the expected pool, USD price, inventory and status fields.');
$firstSystemCode = CloudOffer::generateSystemCode();
$secondSystemCode = CloudOffer::generateSystemCode();
@ -33,7 +36,8 @@ namespace {
foreach ([
['resource_pool_id' => 0], ['code' => 'Tokyo Premium'], ['code' => ''],
['name' => ''], ['price' => '-1'], ['price' => '1.999'], ['stock' => -2],
['name' => ''], ['price' => '-1'], ['price' => '1.999'],
['backup_price' => '-1'], ['backup_price' => '1.999'], ['stock' => -2],
['status' => 2], ['sort' => 1000001],
] as $invalid) {
try {
@ -102,11 +106,17 @@ namespace {
&& str_contains($controller, '$locked->status = 0;'),
'Offer mutation lacks server authorization, price versioning, or reference-aware deletion.');
foreach (['resource_pool_id', 'name', 'price', 'stock', 'status', 'sort', 'revision'] as $field) {
foreach ([
'resource_pool_id', 'name', 'price', 'backup_price', 'stock',
'status', 'sort', 'revision',
] as $field) {
$assert(str_contains($offerView, 'name="' . $field . '"'),
'Offer editor is missing field: ' . $field);
}
$assert(str_contains($offerView, '每期价格(USD)')
&& str_contains($offerView, '自动备份每期价格(USD)')
&& !str_contains($offerView, 'name="backup_available"')
&& str_contains($offerView, '备份频率和保留数量由用户在实例设置中选择')
&& str_contains($offerView, '当前价格版本')
&& str_contains($offerView, '销售名称与位置')
&& str_contains($offerView, '$line_feature_enabled|default:false')

@ -18,7 +18,8 @@ $offer = new CloudOffer();
$offer->setRawAttributes([
'id' => 11, 'plan_id' => 71, 'resource_pool_id' => 8,
'code' => 'tokyo-standard', 'name' => '东京标准云服务器',
'price' => '19.90', 'price_version' => 3, 'revision' => 4,
'price' => '19.90', 'backup_price' => '3.50',
'price_version' => 3, 'revision' => 4,
'stock' => 25, 'status' => 1, 'sort' => 10,
]);
$pools = [
@ -91,7 +92,10 @@ $assert($editForm->getAttribute('data-method') === 'PUT'
&& $editForm->getAttribute('data-url') === '/admin/shop/71/offers/11',
'Edit form lost its PUT endpoint.');
foreach (['resource_pool_id', 'name', 'price', 'stock', 'status', 'sort', 'revision'] as $field) {
foreach ([
'resource_pool_id', 'name', 'price', 'backup_price', 'stock',
'status', 'sort', 'revision',
] as $field) {
$one($create, '//*[@name="' . $field . '"]');
$one($edit, '//*[@name="' . $field . '"]');
}
@ -104,6 +108,9 @@ $assert($namePosition !== false && $poolPosition !== false && $sortPosition !==
'Create must lead with name/location and must not expose a system-identifier field.');
$assert(str_contains($createHtml, '销售名称与位置')
&& str_contains($createHtml, '价格与销售状态')
&& str_contains($createHtml, '自动备份每期价格(USD)')
&& !str_contains($createHtml, 'name="backup_available"')
&& str_contains($createHtml, '备份频率和保留数量由用户在实例设置中选择')
&& str_contains($createHtml, '高级设置')
&& !str_contains($createHtml, '方案代码'),
'Offer fields were not grouped under the simplified terminology.');

@ -87,6 +87,7 @@ $schema->create('cloud_offers', function (Blueprint $table): void {
$table->string('code')->unique();
$table->string('name');
$table->decimal('price', 12, 2);
$table->decimal('backup_price', 12, 2)->default(0);
$table->string('currency');
$table->integer('price_version');
$table->integer('revision');
@ -186,6 +187,7 @@ $baseInput = [
'resource_pool_id' => '1',
'name' => '东京标准云服务器',
'price' => '19.90',
'backup_price' => '3.50',
'stock' => '-1',
'status' => '1',
'sort' => '0',
@ -198,6 +200,7 @@ $created = $controller->offerAdd(
$stored = $connection->table('cloud_offers')->where('id', 1)->first();
$assert($created->status === 200 && ($created->payload['ret'] ?? 0) === 1
&& $stored !== null
&& (string) $stored->backup_price === '3.5'
&& preg_match('/^offer-[a-f0-9]{32}$/D', (string) $stored->code) === 1,
'Creating an offer without a code did not persist an opaque system identifier.');
$originalCode = (string) $stored->code;
@ -240,9 +243,27 @@ $afterUpdate = $connection->table('cloud_offers')->where('id', 1)->first();
$assert($updated->status === 200 && ($updated->payload['ret'] ?? 0) === 1
&& (string) $afterUpdate->code === $originalCode
&& (string) $afterUpdate->name === '东京标准云服务器新名称'
&& (int) $afterUpdate->price_version === 1
&& (int) $afterUpdate->revision === 2,
'Updating without a code did not preserve the immutable identifier.');
$backupPriceUpdated = $controller->offerUpdate(
new AdminOfferWorkflowRequest(array_replace($baseInput, [
'name' => '东京标准云服务器新名称',
'backup_price' => '4.25',
'revision' => '2',
])),
$response,
['id' => 1, 'offer_id' => 1]
);
$afterBackupPriceUpdate = $connection->table('cloud_offers')
->where('id', 1)->first();
$assert($backupPriceUpdated->status === 200
&& (int) $afterBackupPriceUpdate->price_version === 2
&& (int) $afterBackupPriceUpdate->revision === 3
&& (string) $afterBackupPriceUpdate->backup_price === '4.25',
'Changing the automatic-backup price did not advance the shared price version.');
$connection->table('cloud_invoices')->insert([
'id' => 1, 'purpose' => 'upgrade', 'offer_id' => 1,
]);
@ -254,7 +275,8 @@ $blockedModeSwitch = $controller->offerUpdate(
new AdminOfferWorkflowRequest(array_replace($baseInput, [
'name' => '不应保存的有限库存',
'stock' => '5',
'revision' => '2',
'backup_price' => '4.25',
'revision' => '3',
])),
$response,
['id' => 1, 'offer_id' => 1]
@ -264,7 +286,7 @@ $afterBlockedModeSwitch = $connection->table('cloud_offers')
$assert($blockedModeSwitch->status === 409
&& ($blockedModeSwitch->payload['ret'] ?? 1) === 0
&& (int) $afterBlockedModeSwitch->stock === -1
&& (int) $afterBlockedModeSwitch->revision === 2,
&& (int) $afterBlockedModeSwitch->revision === 3,
'An active upgrade allowed its target offer stock mode to change.');
$nonDefault = $controller->offerAdd(

@ -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";

@ -43,6 +43,7 @@ namespace {
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudInvoiceItem;
use App\Models\CloudJob;
use App\Models\CloudRenewal;
use App\Models\CloudServicePeriod;
@ -185,6 +186,18 @@ namespace {
$table->index(['instance_id', 'renews_expires_at', 'status']);
$table->unique('renewal_id');
});
$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')->default('USD');
$table->text('snapshot_json');
$table->integer('created_at');
$table->unique(['invoice_id', 'code']);
});
$schema->create('cloud_mail_outbox', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('invoice_id');
@ -291,7 +304,7 @@ namespace {
$instance->renewal_days = 30;
$instance->renewal_traffic_bytes = 1000;
$instance->traffic_quota_bytes = 1000;
$instance->spec_json = '{}';
$instance->spec_json = '{"automatic_backup":false}';
$instance->created_at = $instance->updated_at = $now - 100;
$instance->save();
@ -475,7 +488,7 @@ namespace {
$purge->renewal_traffic_bytes = 1000;
$purge->traffic_quota_bytes = 1000;
$purge->network_suspended_at = $purgeDueAt;
$purge->spec_json = '{}';
$purge->spec_json = '{"automatic_backup":false}';
$purge->created_at = $purge->updated_at = $purgeDueAt - 3600;
$purge->save();
$purgeInvoice = new CloudInvoice();
@ -491,6 +504,19 @@ namespace {
$purgeInvoice->status = 'open';
$purgeInvoice->created_at = $purgeInvoice->updated_at = $purgeDueAt;
$purgeInvoice->save();
$purgeItem = new CloudInvoiceItem();
$purgeItem->invoice_id = $purgeInvoice->id;
$purgeItem->code = 'instance';
$purgeItem->label = '实例套餐续费';
$purgeItem->amount = '10.00';
$purgeItem->currency = 'USD';
$purgeItem->snapshot_json = json_encode([
'instance_id' => (int) $purge->id,
'plan_id' => 7,
'validity_days' => 30,
], JSON_THROW_ON_ERROR);
$purgeItem->created_at = $purgeDueAt;
$purgeItem->save();
$lifecycle->tick(100);
$purge->refresh();
@ -560,7 +586,7 @@ namespace {
$stale->lifetime_download_bytes = 5000;
$stale->lifetime_upload_bytes = 2000;
$stale->traffic_synced_at = $now - 300;
$stale->spec_json = '{}';
$stale->spec_json = '{"automatic_backup":false}';
$stale->created_at = $stale->updated_at = $now - 7200;
$stale->save();
@ -665,7 +691,7 @@ namespace {
$late->traffic_quota_bytes = 1000;
$late->lifetime_download_bytes = 2000;
$late->lifetime_upload_bytes = 1000;
$late->spec_json = '{}';
$late->spec_json = '{"automatic_backup":false}';
$late->created_at = $late->updated_at = $now - 7200;
$late->save();
$expiredPeriod = new CloudServicePeriod();
@ -686,6 +712,16 @@ namespace {
$late->current_period_id = $expiredPeriod->id;
$late->save();
$issueLateInvoice = new ReflectionMethod(
CloudInvoiceService::class,
'issueOne'
);
$assert($issueLateInvoice->invoke(
null,
(int) $late->id,
time()
) === true, 'The late-renewal invoice fixture was not created.');
$lateRenewal = CloudRenewalService::renew($late, [
'idempotency_key' => 'late-renewal-period-0001',
], $actor);
@ -712,7 +748,7 @@ namespace {
$candidate->service_status = 'active';
$candidate->network_status = 'active';
$candidate->expires_at = $now - 1;
$candidate->spec_json = '{}';
$candidate->spec_json = '{"automatic_backup":false}';
$candidate->created_at = $candidate->updated_at = $now - 100;
$candidate->save();
$expiredIds[] = $candidate->id;
@ -739,7 +775,7 @@ namespace {
$value->service_status = $serviceStatus;
$value->network_status = $networkStatus;
$value->expires_at = $expiresAt;
$value->spec_json = '{}';
$value->spec_json = '{"automatic_backup":false}';
$value->created_at = $value->updated_at = $now - 7200;
$value->save();
return $value;

@ -134,8 +134,9 @@ $assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/j
&& str_contains($deployTemplate, '{foreach $cloud_deploy_offers as $offer}')
&& str_contains($deployTemplate, 'data-offer-id="{$offer.id|escape:"html"}"')
&& str_contains($deployTemplate, '{$offer.traffic_tib|escape:"html"} TB')
&& str_contains($deployTemplate, '${$offer.price|escape:"html"} USD')
&& str_contains($deployTemplate, 'USD</strong>')
&& !str_contains($deployTemplate, 'offer-option-price')
&& str_contains($deployTemplate, 'id="vm-automatic-backup"')
&& str_contains($deployTemplate, 'id="vm-order-total-price"')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}')
&& str_contains($deployTemplate, '$cloud_deploy_catalog_unavailable')
@ -201,10 +202,12 @@ $assert($selectRegion !== '' && $selectLine !== '' && $selectOffer !== ''
&& !str_contains($selectOffer, 'renderTemplateCatalog(')
&& !str_contains($selectOffer, 'loadGlobalTemplates(')
&& str_contains($buy, 'offer_id: Number(byId(\'vm-offer\').value)')
&& str_contains($buy, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
&& str_contains($buy, 'body.backup_id = Number(state.deployBackupId)')
&& !str_contains($buy, 'plan_id:')
&& str_contains($buy, 'provisionInvoiceFingerprint(body)')
&& str_contains($buy, 'pendingProvisionInvoiceKey(fingerprint)'),
'Changing a region, line or offer must preserve the global image and purchasing must keep offer-scoped idempotency.');
'Changing a region, line or offer must preserve the source and purchasing must keep backup-aware offer idempotency.');
$assert(!str_contains($buy, 'confirm(')
&& !str_contains($buy, 'toast(')
&& !str_contains($buy, 'purchaseSummary')

@ -91,6 +91,8 @@ namespace {
use App\Models\CloudHostCapacityPolicy;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudHostResourcePoolMembership;
use App\Models\CloudBackupSubscription;
use App\Models\CloudInstanceBackup;
use App\Models\CloudBackupRestore;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
@ -99,6 +101,7 @@ namespace {
use App\Models\CloudNetworkLine;
use App\Models\CloudOffer;
use App\Models\CloudOrder;
use App\Models\CloudOrderItem;
use App\Models\CloudJob;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
@ -244,15 +247,17 @@ namespace {
$schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->string('cidr'); $t->string('gateway'); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id')->nullable(); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); });
$schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('backup_price')->default('0.00'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); });
$schema->create('cloud_templates', function (Blueprint $t) { $t->string('id')->primary(); $t->string('name'); $t->string('os_family'); $t->string('os_version'); $t->string('source_type'); $t->text('sealed_source_url'); $t->integer('image_bytes'); $t->string('sha256'); $t->text('startup_script'); $t->integer('revision'); $t->string('generation_token'); $t->string('state'); $t->integer('active_job_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_user_isos', function (Blueprint $t) { $t->string('id')->primary(); $t->integer('active_job_id')->nullable(); });
$schema->create('cloud_template_replicas', function (Blueprint $t) { $t->integer('host_id'); $t->string('template_id'); $t->integer('job_id')->nullable(); $t->integer('revision'); $t->string('generation_token'); $t->string('state')->default('pending'); $t->integer('image_bytes')->default(0); $t->string('sha256')->default(''); $t->string('operation_id')->default(''); $t->string('error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->primary(['host_id', 'template_id']); });
$schema->create('cloud_platform_test_policy_state', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('revision')->default(0); $t->integer('updated_by')->nullable(); $t->integer('updated_at')->default(0); });
$schema->create('cloud_platform_test_policy_rules', function (Blueprint $t) { $t->increments('id'); $t->string('rule_key', 32)->unique(); $t->string('service', 120); $t->string('protocol', 8); $t->integer('port_from'); $t->integer('port_to'); $t->string('direction', 8); $t->string('reason', 500); $t->integer('created_by'); $t->integer('updated_by'); $t->integer('deleted_by')->nullable(); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('sealed_payload')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_order_items', function (Blueprint $t) { $t->increments('id'); $t->integer('order_id'); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['order_id', 'code']); });
$schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); $t->integer('order_id')->nullable(); $t->integer('backup_restore_id')->nullable(); $t->integer('offer_id')->nullable(); foreach (['resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique('backup_restore_id'); });
$schema->create('cloud_backup_restores', function (Blueprint $t) { $t->increments('id'); $t->string('restore_key')->unique(); $t->integer('backup_id'); $t->integer('target_host_id'); $t->integer('target_instance_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('job_id')->nullable(); $t->string('operation_id')->unique(); $t->string('new_uuid'); $t->string('new_name'); $t->string('state'); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_instance_backups', function (Blueprint $t) { $t->increments('id'); $t->string('backup_key')->unique(); $t->integer('source_instance_id'); $t->integer('source_host_id'); $t->integer('user_id'); $t->string('source_uuid'); $t->string('name'); $t->string('purpose')->default('portable'); $t->string('source')->default('manual'); $t->integer('subscription_id')->nullable(); $t->integer('scheduled_for')->nullable(); $t->string('state')->default('creating'); $t->string('consistency'); $t->string('object_key')->unique(); $t->integer('object_size_bytes')->default(0); $t->integer('virtual_size_bytes')->default(0); $t->string('sha256')->default(''); $t->text('spec_json'); $t->text('sealed_storage_runtime'); $t->text('sealed_credential')->nullable(); $t->integer('storage_revision'); $t->integer('active_job_id')->nullable(); $t->string('last_operation_id')->nullable(); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['subscription_id', 'scheduled_for']); });
$schema->create('cloud_jobs', function (Blueprint $t) {
$t->increments('id');
$t->string('operation_id')->unique();
@ -317,6 +322,8 @@ namespace {
$schema->create('cloud_renewals', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->integer('user_id'); $t->integer('plan_id')->nullable(); $t->integer('period_id')->nullable(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->integer('validity_days'); $t->integer('traffic_bytes_added'); $t->integer('previous_expires_at'); $t->integer('new_expires_at'); $t->integer('created_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_service_periods', function (Blueprint $t) { $t->increments('id'); foreach (['instance_id', 'user_id'] as $v) { $t->integer($v); } foreach (['plan_id', 'order_id', 'renewal_id', 'download_base_bytes', 'upload_base_bytes', 'activated_at'] as $v) { $t->integer($v)->nullable(); } foreach (['starts_at', 'ends_at', 'traffic_quota_bytes', 'download_used_bytes', 'upload_used_bytes', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } $t->string('status'); $t->unique('order_id'); $t->unique('renewal_id'); });
$schema->create('cloud_invoices', function (Blueprint $t) { $t->increments('id'); $t->string('invoice_no')->unique(); $t->string('purpose')->default('renewal'); $t->integer('instance_id')->nullable(); $t->integer('order_id')->nullable()->unique(); $t->integer('user_id'); $t->integer('plan_id')->nullable(); $t->integer('offer_id')->nullable(); $t->integer('renewal_id')->nullable(); $t->integer('renews_expires_at')->nullable(); $t->integer('due_at'); $t->string('amount'); $t->string('currency')->default('USD'); $t->integer('validity_days'); $t->integer('traffic_quota_bytes'); $t->string('status'); $t->string('paid_via')->nullable(); $t->string('payment_reference')->nullable(); $t->integer('paid_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_invoice_items', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->integer('order_item_id')->nullable(); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['invoice_id', 'code']); });
$schema->create('cloud_backup_subscriptions', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id')->unique(); $t->integer('user_id'); $t->integer('offer_id'); $t->boolean('enabled')->default(true); $t->boolean('renew_next_period')->default(true); $t->string('frequency')->default('daily'); $t->integer('weekday')->default(0); $t->integer('retention_count')->default(2); $t->string('timezone')->default('America/Los_Angeles'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version'); $t->integer('next_run_at'); $t->integer('last_scheduled_at')->nullable(); $t->integer('last_backup_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_invoice_payments', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->integer('user_id'); $t->string('provider'); $t->string('provider_order_no'); $t->string('idempotency_key'); $t->string('amount'); $t->string('status'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['provider', 'provider_order_no']); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_mail_outbox', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->string('kind'); $t->string('status'); $t->integer('attempts'); $t->integer('available_at'); $t->string('lease_token')->nullable(); $t->integer('lease_until'); $t->integer('sent_at')->nullable(); $t->string('last_error'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['invoice_id', 'kind']); });
$schema->create('cloud_ssh_keys', function (Blueprint $t) { $t->increments('id'); $t->integer('user_id'); $t->string('name'); $t->text('public_key'); $t->string('fingerprint'); $t->integer('created_at'); });
@ -366,8 +373,8 @@ namespace {
foreach (['203.0.113.34', '203.0.113.35'] as $address) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->public_ip_pool_id = $targetPublicPool->id; $ip->address = $address; $ip->prefix_length = 28; $ip->state = 'available'; $ip->created_at = $ip->updated_at = $now; $ip->save(); }
$plan = new Shop(); $plan->name = 'plan'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->validity_days = 30; $plan->traffic_quota_bytes = 1024 * 1024 * 1024; $plan->status = 1; $plan->sort = 0; $plan->save();
$soldOutPlan = new Shop(); $soldOutPlan->name = 'sold-out-plan'; $soldOutPlan->cpu_cores = 2; $soldOutPlan->memory_mib = 2048; $soldOutPlan->bandwidth_mbps = 100; $soldOutPlan->disk_gib = 20; $soldOutPlan->validity_days = 30; $soldOutPlan->traffic_quota_bytes = 1024 * 1024 * 1024; $soldOutPlan->status = 1; $soldOutPlan->sort = 0; $soldOutPlan->save();
$offer = new CloudOffer(); $offer->plan_id = $plan->id; $offer->resource_pool_id = $pool->id; $offer->code = 'test-offer'; $offer->name = 'Test Offer'; $offer->price = '9.99'; $offer->currency = 'USD'; $offer->price_version = 1; $offer->status = 1; $offer->stock = 10; $offer->sort = 0; $offer->created_at = $offer->updated_at = $now; $offer->save();
$soldOutOffer = new CloudOffer(); $soldOutOffer->plan_id = $soldOutPlan->id; $soldOutOffer->resource_pool_id = $pool->id; $soldOutOffer->code = 'sold-out-offer'; $soldOutOffer->name = 'Sold Out Offer'; $soldOutOffer->price = '8.99'; $soldOutOffer->currency = 'USD'; $soldOutOffer->price_version = 1; $soldOutOffer->status = 1; $soldOutOffer->stock = 0; $soldOutOffer->sort = 0; $soldOutOffer->created_at = $soldOutOffer->updated_at = $now; $soldOutOffer->save();
$offer = new CloudOffer(); $offer->plan_id = $plan->id; $offer->resource_pool_id = $pool->id; $offer->code = 'test-offer'; $offer->name = 'Test Offer'; $offer->price = '9.99'; $offer->backup_price = '2.50'; $offer->currency = 'USD'; $offer->price_version = 1; $offer->status = 1; $offer->stock = 10; $offer->sort = 0; $offer->created_at = $offer->updated_at = $now; $offer->save();
$soldOutOffer = new CloudOffer(); $soldOutOffer->plan_id = $soldOutPlan->id; $soldOutOffer->resource_pool_id = $pool->id; $soldOutOffer->code = 'sold-out-offer'; $soldOutOffer->name = 'Sold Out Offer'; $soldOutOffer->price = '8.99'; $soldOutOffer->backup_price = '0.00'; $soldOutOffer->currency = 'USD'; $soldOutOffer->price_version = 1; $soldOutOffer->status = 1; $soldOutOffer->stock = 0; $soldOutOffer->sort = 0; $soldOutOffer->created_at = $soldOutOffer->updated_at = $now; $soldOutOffer->save();
$template = new CloudTemplate();
$template->id = 'alma10-1234abcd-0123456789abcdef';
$template->name = 'AlmaLinux 10';
@ -528,6 +535,12 @@ namespace {
&& !array_key_exists('invoice_no', $openingDisplay)
&& ($openingDisplay['order_status'] ?? null) === 'awaiting_payment'
&& ($firstSpec['stock_mode'] ?? null) === 'finite'
&& ($firstSpec['automatic_backup'] ?? null) === false
&& ($firstSpec['instance_price'] ?? null) === '9.99'
&& ($firstSpec['backup_price'] ?? null) === '0.00'
&& count($openingDisplay['items'] ?? []) === 1
&& ($openingDisplay['items'][0]['code'] ?? null) === 'instance'
&& CloudOrderItem::where('order_id', $first->id)->count() === 1
&& $first->stock_reserved_at !== null
&& $first->stock_released_at === null
&& User::find(1)->money === '0.00'
@ -781,8 +794,19 @@ namespace {
// queue, changing the wallet, or retaining its encrypted credential.
$abandoned = CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-abandoned', 'idempotency_key' => 'test-request-key-abandoned',
'automatic_backup' => true,
]), $actor);
$abandonedInvoice = CloudInvoice::where('order_id', $abandoned->id)->first();
$abandonedSpec = json_decode((string) $abandoned->spec_json, true,
flags: JSON_THROW_ON_ERROR);
$abandonedDisplay = CloudInvoiceService::display($abandonedInvoice);
$assert((string) $abandoned->amount === '12.49'
&& ($abandonedSpec['automatic_backup'] ?? null) === true
&& ($abandonedSpec['instance_price'] ?? null) === '9.99'
&& ($abandonedSpec['backup_price'] ?? null) === '2.50'
&& array_column($abandonedDisplay['items'] ?? [], 'code')
=== ['instance', 'automatic_backup'],
'Automatic backup was not frozen as a separate opening-bill item.');
$abandonedInvoice->due_at = time() - 1;
$abandonedInvoice->save();
$assert(CloudInvoiceService::expireProvision() === 1
@ -802,13 +826,95 @@ namespace {
try { CloudAccess::instance((string) $instance->id, $admin, true); throw new RuntimeException('Regular admin wrote other owner.'); } catch (CloudError $e) {}
try { CloudJobService::enqueue($instance, array_replace($admin, ['can_manage' => true]), 'action', 'POST', '/actions', ['action' => 'reboot']); throw new RuntimeException('Scoped can_manage bypassed cross-owner queue authorization.'); } catch (CloudError $e) {}
try { CloudAccess::manage($actor + ['can_provision' => true]); throw new RuntimeException('Provision actor globally privileged.'); } catch (CloudError $e) {}
$failed = CloudOrderService::purchase(array_replace($input, ['name' => 'vm-two', 'idempotency_key' => 'test-request-key-0002']), $actor);
// A backup-origin deployment must cross the same paid create ledger, but
// dispatch a signed restore-backup request and retain the exact backup
// identity until a deterministic Agent rejection safely refunds it.
$originalSourceSpec = (string) $instance->spec_json;
$sourceBackupSpec = json_decode(
$originalSourceSpec,
true,
64,
JSON_THROW_ON_ERROR
);
$sourceBackupSpec['automatic_backup'] = true;
$sourceBackupSpec['backup_price'] = '2.50';
$instance->spec_json = json_encode(
$sourceBackupSpec,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$instance->save();
$subscription = new CloudBackupSubscription();
$subscription->instance_id = (int) $instance->id;
$subscription->user_id = 1;
$subscription->offer_id = (int) $offer->id;
$subscription->enabled = true;
$subscription->renew_next_period = true;
$subscription->frequency = 'daily';
$subscription->weekday = 0;
$subscription->retention_count = 2;
$subscription->timezone = 'America/Los_Angeles';
$subscription->price = '2.50';
$subscription->currency = 'USD';
$subscription->price_version = 1;
$subscription->next_run_at = time() + 86400;
$subscription->created_at = $subscription->updated_at = time();
$subscription->save();
$sourceBackup = new CloudInstanceBackup();
$sourceBackup->backup_key = str_repeat('c', 32);
$sourceBackup->source_instance_id = (int) $instance->id;
$sourceBackup->source_host_id = (int) $host->id;
$sourceBackup->user_id = 1;
$sourceBackup->source_uuid = strtolower((string) $instance->uuid);
$sourceBackup->name = 'automatic-backup-fixture';
$sourceBackup->purpose = 'portable';
$sourceBackup->source = 'automatic';
$sourceBackup->subscription_id = (int) $subscription->id;
$sourceBackup->scheduled_for = time() - 60;
$sourceBackup->state = 'ready';
$sourceBackup->consistency = 'filesystem';
$sourceBackup->object_key = 'virt-cloud/backups/'
. $sourceBackup->backup_key . '/system.qcow2';
$sourceBackup->object_size_bytes = 1073741824;
$sourceBackup->virtual_size_bytes = 10 * 1073741824;
$sourceBackup->sha256 = str_repeat('d', 64);
$sourceBackup->spec_json = json_encode(
$sourceBackupSpec,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$sourceBackup->sealed_storage_runtime =
\App\Services\Cloud\CloudSecrets::encrypt([
'config' => [
'endpoint' => 'https://objects.example.test',
'region' => 'us-east-1',
'bucket' => 'virt-test',
'path_style' => true,
],
'credentials' => [
'access_key_id' => 'test-access-key',
'secret_access_key' => 'test-secret-key',
],
'revision' => 1,
], 'object-storage-backup-runtime');
$sourceBackup->sealed_credential = $instance->sealed_credential;
$sourceBackup->storage_revision = 1;
$sourceBackup->ready_at = time();
$sourceBackup->created_at = $sourceBackup->updated_at = time();
$sourceBackup->save();
$failed = CloudOrderService::purchase([
'offer_id' => (int) $offer->id,
'source' => 'backup',
'backup_id' => (int) $sourceBackup->id,
'name' => 'vm-two',
'automatic_backup' => false,
'idempotency_key' => 'test-request-key-0002',
], $actor);
$assert(User::find(1)->money === '90.01'
&& CloudJob::where('order_id', $failed->id)->count() === 0,
'A second unpaid deployment charged or entered the worker queue.');
CloudInvoiceService::payBalance(CloudInvoice::where('order_id', $failed->id)->first(),
$actor, 'provision-balance-test-0002');
$failedJob = CloudJob::where('order_id', $failed->id)->first();
$beforeBackupDispatch = count($history);
$mock->append(new Response(422, [], json_encode(['error' => [
'code' => 'invalid_request',
'message' => '虚拟机参数校验失败',
@ -816,6 +922,34 @@ namespace {
'dispatch_state' => 'not_dispatched',
]])));
$worker->tick(); $worker->tick();
$backupAgentRequest = $agentRequest($history[$beforeBackupDispatch]);
$backupAgentBody = json_decode(
$backupAgentRequest['body'], true, 64, JSON_THROW_ON_ERROR
);
$assert($backupAgentRequest['method'] === 'POST'
&& str_ends_with(
$backupAgentRequest['request_target'],
'/restore-backup'
)
&& ($backupAgentBody['backup_key'] ?? null)
=== $sourceBackup->backup_key
&& ($backupAgentBody['source_sha256'] ?? null)
=== $sourceBackup->sha256
&& ($backupAgentBody['source_size_bytes'] ?? null)
=== (int) $sourceBackup->object_size_bytes
&& str_starts_with(
(string) ($backupAgentBody['source_url'] ?? ''),
'https://'
)
&& ($backupAgentBody['source'] ?? null) === ''
&& ($backupAgentBody['root_password'] ?? null) === ''
&& (int) $failedJob->backup_id === (int) $sourceBackup->id,
'Paid backup-origin create lost its signed object identity or used the cloud-template endpoint.');
$instance->spec_json = $originalSourceSpec;
$instance->save();
$subscription->enabled = false;
$subscription->updated_at = time();
$subscription->save();
$failedDisplay = CloudOrderService::display(CloudOrder::find($failed->id));
$failedInvoiceDisplay = CloudInvoiceService::display(
CloudInvoice::where('order_id', $failed->id)->first());
@ -1701,6 +1835,23 @@ namespace {
// Any later destructive force action must be a separately audited task;
// inspection never rewrites the prior terminal receipt.
Capsule::table('cloud_backup_subscriptions')->insert([
'instance_id' => (int) $purgeForceRequired->id,
'user_id' => (int) $purgeForceRequired->user_id,
'offer_id' => (int) $purgeForceRequired->offer_id,
'enabled' => 1,
'renew_next_period' => 1,
'frequency' => 'daily',
'weekday' => 0,
'retention_count' => 2,
'timezone' => 'America/Los_Angeles',
'price' => '2.50',
'currency' => 'USD',
'price_version' => 1,
'next_run_at' => time() + 3600,
'created_at' => time(),
'updated_at' => time(),
]);
$purgeForceJob = CloudJobService::enqueueForceDelete(
$purgeForcePrior, $adminActor
);
@ -1720,6 +1871,9 @@ namespace {
&& $purgeForcePrior->fresh()->status === 'failed'
&& $purgeForcePrior->fresh()->error_code === 'force_required'
&& $purgeForceRequired->fresh()->status === 'deleted'
&& (int) Capsule::table('cloud_backup_subscriptions')
->where('instance_id', (int) $purgeForceRequired->id)
->value('enabled') === 0
&& $purgeForcedRequest['method'] === 'POST'
&& str_ends_with($purgeForcedRequest['request_target'], '/force-delete')
&& ($purgeForcedBody['prior_operation_id'] ?? null)
@ -2985,6 +3139,15 @@ namespace {
'created_at' => $past - 86400,
'updated_at' => $past,
]);
$issueOne = new ReflectionMethod(
CloudInvoiceService::class,
'issueOne'
);
if ($issueOne->invoke(null, (int) $target->id, time()) !== true) {
throw new RuntimeException(
'Failed to create the renewal invoice fixture.'
);
}
};
$user->money = '1000.00';
$user->save();

@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v6-migration-bundles'")
"SCHEMA_VERSION = 'go-agent-wss-v7-automatic-backups'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"),
'Outbound Agent schema must reject the incompatible earlier Go database.');
@ -30,8 +30,9 @@ foreach (['cloud_host_agents', 'cloud_templates', 'cloud_hosts', 'cloud_instance
'cloud_orders', 'cloud_invoices', 'cloud_jobs',
'cloud_agent_completion_events', 'cloud_console_tickets',
'cloud_rescue_template_imports', 'cloud_instance_backups',
'cloud_backup_restores', 'cloud_instance_migrations',
'cloud_migration_bundle_artifacts'] as $table) {
'cloud_backup_subscriptions', 'cloud_backup_restores',
'cloud_backup_recoveries', 'cloud_order_items', 'cloud_invoice_items',
'cloud_instance_migrations', 'cloud_migration_bundle_artifacts'] as $table) {
$assert(str_contains($schema, 'CREATE TABLE ' . $table . ' ('),
'Missing fresh-install table: ' . $table);
}
@ -60,6 +61,8 @@ $assert(str_contains($schema,
'Fresh task schema is missing single-dispatch or immutable-receipt constraints.');
$assert(str_contains($schema,
'backup_restore_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema,
'backup_recovery_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema,
'CONSTRAINT chk_cloud_resource_reservation_source CHECK (')
&& str_contains($schema,
@ -67,10 +70,16 @@ $assert(str_contains($schema,
&& str_contains($schema, 'KEY cloud_job_backup (backup_id, id)')
&& str_contains($schema,
'KEY cloud_job_backup_restore (backup_restore_id, id)')
&& str_contains($schema,
'KEY cloud_job_backup_recovery (backup_recovery_id, id)')
&& str_contains($setup,
"'cloud_backup_subscriptions', 'cloud_instance_backups'")
&& str_contains($setup,
"'cloud_backup_restores', 'cloud_backup_recoveries'")
&& str_contains($setup,
"'cloud_instance_backups', 'cloud_backup_restores'")
"'cloud_job_backup', 'cloud_job_backup_restore'")
&& str_contains($setup,
"'cloud_job_backup', 'cloud_job_backup_restore'"),
"'cloud_job_backup_recovery'"),
'Fresh schema is missing portable-backup catalog or restore reservation constraints.');
$assert(str_contains($schema, 'CREATE TABLE cloud_instance_migrations (')
&& str_contains($schema, 'purpose VARCHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT \'portable\'')

@ -147,6 +147,17 @@ namespace {
$table->integer('paid_at')->nullable(); $table->integer('created_at'); $table->integer('updated_at');
$table->index(['instance_id', 'renews_expires_at', 'status']); $table->unique('renewal_id');
});
$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')->default('USD');
$table->text('snapshot_json');
$table->integer('created_at');
});
$schema->create('cloud_invoice_payments', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('invoice_id'); $table->integer('user_id');
$table->string('provider'); $table->string('provider_order_no'); $table->string('idempotency_key');
@ -219,6 +230,16 @@ namespace {
$second->due_at = $currentExpiry; $second->amount = '12.50'; $second->validity_days = 30;
$second->traffic_quota_bytes = 4096; $second->status = 'open'; $second->created_at = $second->updated_at = $now;
$second->save();
Capsule::table('cloud_invoice_items')->insert([
'invoice_id' => (int) $second->id,
'order_item_id' => null,
'code' => 'instance',
'label' => '实例套餐续费',
'amount' => '12.50',
'currency' => 'USD',
'snapshot_json' => '{}',
'created_at' => $now,
]);
$payment = new CloudInvoicePayment(); $payment->invoice_id = $second->id; $payment->user_id = 1;
$payment->provider = 'paytaro'; $payment->provider_order_no = 'PT-GATEWAY';
$payment->idempotency_key = 'invoice-gateway-test-0001'; $payment->amount = '12.50';
@ -281,7 +302,10 @@ namespace {
$candidate->network_status = 'active'; $candidate->expires_at = $expiry;
$candidate->renewal_price = '12.50'; $candidate->renewal_days = 30;
$candidate->renewal_traffic_bytes = 4096; $candidate->traffic_quota_bytes = 4096;
$candidate->spec_json = '{}'; $candidate->created_at = $candidate->updated_at = $now;
$candidate->spec_json = json_encode([
'automatic_backup' => false,
], JSON_THROW_ON_ERROR);
$candidate->created_at = $candidate->updated_at = $now;
$candidate->save();
return $candidate;
};
@ -344,7 +368,10 @@ namespace {
$candidate->network_status = $networkStatus; $candidate->expires_at = $expiry;
$candidate->renewal_price = '12.50'; $candidate->renewal_days = 30;
$candidate->renewal_traffic_bytes = 4096; $candidate->traffic_quota_bytes = 4096;
$candidate->spec_json = '{}'; $candidate->created_at = $candidate->updated_at = $now;
$candidate->spec_json = json_encode([
'automatic_backup' => false,
], JSON_THROW_ON_ERROR);
$candidate->created_at = $candidate->updated_at = $now;
$candidate->save();
$candidatePeriod = new CloudServicePeriod();
@ -366,6 +393,16 @@ namespace {
$bill->amount = '12.50'; $bill->validity_days = 30; $bill->traffic_quota_bytes = 4096;
$bill->status = $status; $bill->created_at = $bill->updated_at = $createdAt;
$bill->save();
Capsule::table('cloud_invoice_items')->insert([
'invoice_id' => (int) $bill->id,
'order_item_id' => null,
'code' => 'instance',
'label' => '实例套餐续费',
'amount' => '12.50',
'currency' => 'USD',
'snapshot_json' => '{}',
'created_at' => $createdAt,
]);
return $bill;
};

@ -59,6 +59,17 @@ $schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->integer('paid_at')->nullable();
$table->integer('created_at');
});
$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')->default('USD');
$table->text('snapshot_json');
$table->integer('created_at');
});
$now = time();
$expiry = $now + 3600;

@ -108,6 +108,7 @@ namespace {
$table->integer('snapshot_id')->nullable();
$table->integer('backup_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->integer('backup_recovery_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->nullable();
$table->string('kind');
@ -185,6 +186,9 @@ namespace {
$table->string('source_uuid');
$table->string('name');
$table->string('purpose')->default('portable');
$table->string('source')->default('manual');
$table->integer('subscription_id')->nullable();
$table->integer('scheduled_for')->nullable();
$table->string('state');
$table->string('consistency');
$table->string('object_key');
@ -202,6 +206,20 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_backup_recoveries',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('recovery_key')->unique();
$table->integer('backup_id');
$table->integer('instance_id');
$table->integer('job_id')->nullable();
$table->string('operation_id')->unique();
$table->string('state');
$table->string('error_code')->default('');
$table->integer('completed_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_backup_restores',
static function (Blueprint $table): void {
$table->increments('id');
@ -427,7 +445,8 @@ namespace {
string $executionMode = 'agent',
int $userId = 41,
?int $backupId = null,
?int $backupRestoreId = null
?int $backupRestoreId = null,
?int $backupRecoveryId = null
) use (&$nextJobId, $hostId, $now): array {
$id = $nextJobId++;
$operationId = hash('md5', 'recovery-matrix-job:' . $id);
@ -444,6 +463,7 @@ namespace {
'snapshot_id' => $snapshotId,
'backup_id' => $backupId,
'backup_restore_id' => $backupRestoreId,
'backup_recovery_id' => $backupRecoveryId,
'user_id' => $userId,
'host_id' => $hostId,
'kind' => $kind,
@ -1044,6 +1064,97 @@ namespace {
);
}
$recoverBackupId = 204;
$recoverBackupKey = hash('md5',
'recovery-matrix-backup:' . $recoverBackupId);
$recoverBackupSha = str_repeat('7', 64);
$recoverLedgerId = 301;
$recoverLedgerKey = hash('md5',
'recovery-matrix-ledger:' . $recoverLedgerId);
$recoverRecord = $insertJob(
'backup_recover',
static function (int $jobId, string $operationId) use (
$instanceUuid,
$ownerId,
$recoverBackupKey,
$recoverBackupSha,
$recoverLedgerKey
): array {
return [
'method' => 'POST',
'request_target' => '/v1/vms/'
. rawurlencode($instanceUuid) . '/recover-backup',
'body' => [
'operation_id' => $operationId,
'backup_key' => $recoverBackupKey,
'source_url' => 'https://objects.invalid/recover.qcow2',
'source_size_bytes' => 1073741824,
'source_sha256' => $recoverBackupSha,
],
'owner_id' => $ownerId,
'can_manage' => false,
'backup_key' => $recoverBackupKey,
'recovery_key' => $recoverLedgerKey,
];
},
$instanceId,
null,
null,
null,
'agent',
$ownerId,
$recoverBackupId,
null,
$recoverLedgerId
);
Capsule::table('cloud_instance_backups')->insert([
'id' => $recoverBackupId,
'backup_key' => $recoverBackupKey,
'source_instance_id' => $instanceId,
'source_host_id' => $hostId,
'user_id' => $ownerId,
'source_uuid' => $instanceUuid,
'name' => 'matrix-automatic-backup',
'purpose' => 'portable',
'source' => 'automatic',
'state' => 'ready',
'consistency' => 'filesystem',
'object_key' => 'vm-backups/' . $recoverBackupKey . '/system.qcow2',
'object_size_bytes' => 1073741824,
'virtual_size_bytes' => 42949672960,
'sha256' => $recoverBackupSha,
'spec_json' => '{}',
'sealed_storage_runtime' => 'sealed-runtime',
'created_at' => $now - 600,
'updated_at' => $now - 300,
]);
Capsule::table('cloud_backup_recoveries')->insert([
'id' => $recoverLedgerId,
'recovery_key' => $recoverLedgerKey,
'backup_id' => $recoverBackupId,
'instance_id' => $instanceId,
'job_id' => $recoverRecord['id'],
'operation_id' => $recoverRecord['operation_id'],
'state' => 'uncertain',
'error_code' => 'operation_effect_unknown',
'completed_at' => null,
'created_at' => $now - 180,
'updated_at' => $now - 20,
]);
$addFixture(
'backup_recover',
'recover',
$recoverRecord,
'recover-backup:' . $recoverBackupKey . ':' . $recoverBackupSha,
$instanceUuid,
[
'backup_key' => $recoverBackupKey,
'sha256' => $recoverBackupSha,
'restored' => true,
'power_state' => 'running',
]
);
$firewallVersionId = 1;
$firewallRevision = 9;
$firewallDigest = str_repeat('d', 64);

@ -64,6 +64,7 @@ namespace {
'snapshot_restore',
'snapshot_delete',
'backup_create',
'backup_recover',
'firewall_apply',
'service_suspend',
'network_suspend',
@ -78,8 +79,8 @@ namespace {
];
$assert(CloudOperationRecoveryPolicy::kinds() === $expectedKinds,
'The Agent leaf recovery policy changed without updating its contract.');
$assert(count(CloudOperationRecoveryPolicy::kinds()) === 27,
'The recovery policy contract must contain exactly 27 Agent leaf kinds.');
$assert(count(CloudOperationRecoveryPolicy::kinds()) === 28,
'The recovery policy contract must contain exactly 28 Agent leaf kinds.');
foreach ($expectedKinds as $kind) {
$assert(CloudOperationRecoveryPolicy::supports($kind),
'The recovery policy omitted ' . $kind . '.');

@ -145,7 +145,10 @@ namespace {
&& !str_contains($shopController, "'host_id' => \$shop->host_id"),
'The administrator catalog must keep canonical plan units and move placement/pricing to offers.');
$assert(str_contains($client, 'function formatUsd(value)')
&& str_contains($client, 'formatUsd(offer.price)')
&& str_contains($client, 'formatUsd(instancePrice)')
&& str_contains($client, 'formatUsd(backupPrice)')
&& str_contains($client, 'formatUsd(total)')
&& !str_contains($client, 'formatUsd(offer.price)')
&& str_contains($client, 'formatUsd(invoice.amount)')
&& str_contains($client, 'formatUsd(balance)')
&& !str_contains($client, '¥') && !str_contains($invoiceView, '¥')

@ -187,6 +187,7 @@ namespace {
$table->string('code')->unique();
$table->string('name');
$table->string('price');
$table->string('backup_price')->default('0.00');
$table->string('currency')->default('USD');
$table->integer('price_version');
$table->integer('revision');
@ -303,6 +304,17 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$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')->default('USD');
$table->text('snapshot_json');
$table->integer('created_at');
});
$schema->create('cloud_invoice_payments',
static function (Blueprint $table): void {
$table->increments('id');
@ -469,6 +481,7 @@ namespace {
'id' => $sourceOfferId, 'plan_id' => $sourcePlanId,
'resource_pool_id' => 1, 'code' => 'source-' . $sequence,
'name' => 'Source Offer ' . $sequence, 'price' => '10.00',
'backup_price' => '2.00',
'currency' => 'USD', 'price_version' => 1, 'revision' => 1,
'status' => 1, 'stock' => 5, 'sort' => 1,
'created_at' => $now, 'updated_at' => $now,
@ -477,6 +490,7 @@ namespace {
'id' => $targetOfferId, 'plan_id' => $targetPlanId,
'resource_pool_id' => 1, 'code' => 'target-' . $sequence,
'name' => 'Target Offer ' . $sequence, 'price' => '20.00',
'backup_price' => '3.00',
'currency' => 'USD', 'price_version' => 3, 'revision' => 4,
'status' => 1, 'stock' => 3, 'sort' => 2,
'created_at' => $now, 'updated_at' => $now,

@ -93,6 +93,12 @@ namespace {
$table->integer('backup_id');
$table->string('state');
});
$schema->create('cloud_backup_recoveries',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id');
$table->string('state');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id')->nullable();

@ -69,6 +69,20 @@ $schema->create('cloud_backup_restores',
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_backup_recoveries',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('recovery_key')->unique();
$table->integer('backup_id');
$table->integer('instance_id');
$table->integer('job_id')->nullable();
$table->string('operation_id')->unique();
$table->string('state');
$table->string('error_code')->default('');
$table->integer('completed_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('kind');
@ -76,6 +90,8 @@ $schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->integer('instance_id')->nullable();
$table->integer('backup_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->integer('backup_recovery_id')->nullable();
$table->integer('user_id')->nullable();
$table->string('operation_id')->unique();
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
@ -139,6 +155,7 @@ $sourceSpec = [
'os_source' => 'cloud_template',
'os_name' => 'Debian 12',
'login_name' => 'root',
'guest_hostname' => 'backup-host',
'vcpu' => 2,
'memory_mib' => 2048,
'disk_gib' => 20,
@ -429,4 +446,83 @@ $assert((string) $uncertainRestore->state === 'uncertain'
=== 'sealed-target-credential',
'Unknown restore effect released resources, IP or target credentials.');
// In-place recovery keeps the existing instance identity and converges only
// from an exact backup/ledger/Agent result tuple.
$recoveryOperation = str_repeat('e', 32);
$recoveryKey = str_repeat('f', 32);
$capsule->table('cloud_instances')->insert([
'id' => 101,
'uuid' => '11111111-1111-4111-8111-111111111111',
'host_id' => 3,
'user_id' => 9,
'status' => 'active',
'service_status' => 'active',
'network_status' => 'active',
'spec_json' => json_encode(array_replace($sourceSpec, [
'guest_hostname' => 'current-host',
]), JSON_THROW_ON_ERROR),
'sealed_credential' => 'sealed-current-credential',
'updated_at' => $now,
]);
$capsule->table('cloud_backup_recoveries')->insert([
'id' => 200,
'recovery_key' => $recoveryKey,
'backup_id' => 1,
'instance_id' => 101,
'job_id' => 200,
'operation_id' => $recoveryOperation,
'state' => 'recovering',
'error_code' => '',
'completed_at' => null,
'created_at' => $now,
'updated_at' => $now,
]);
$capsule->table('cloud_jobs')->insert([
'id' => 200,
'kind' => 'backup_recover',
'host_id' => 3,
'instance_id' => 101,
'backup_id' => 1,
'backup_restore_id' => null,
'backup_recovery_id' => 200,
'user_id' => 9,
'operation_id' => $recoveryOperation,
]);
$recoveryJob = CloudJob::findOrFail(200);
CloudBackupService::finishJobLocked($recoveryJob, 'succeeded', [
'backup_key' => str_repeat('a', 32),
'sha256' => str_repeat('b', 64),
'restored' => true,
'power_state' => 'running',
'active_volume_name' => 'managed-recovery-volume',
], [
'owner_id' => 9,
'backup_key' => str_repeat('a', 32),
'recovery_key' => $recoveryKey,
'body' => [
'backup_key' => str_repeat('a', 32),
'source_size_bytes' => 1024,
'source_sha256' => str_repeat('b', 64),
],
]);
$recovery = \App\Models\CloudBackupRecovery::findOrFail(200);
$recoveredInstance = CloudInstance::findOrFail(101);
$recoveredSpec = json_decode(
(string) $recoveredInstance->spec_json,
true,
64,
JSON_THROW_ON_ERROR
);
$assert((string) $recovery->state === 'succeeded'
&& $recovery->completed_at !== null
&& (string) $recoveredInstance->uuid
=== '11111111-1111-4111-8111-111111111111'
&& (string) $recoveredInstance->status === 'active'
&& (string) $recoveredInstance->sealed_credential
=== 'sealed-source-credential'
&& ($recoveredSpec['guest_hostname'] ?? null) === 'backup-host'
&& ($recoveredSpec['restored_from_backup'] ?? null)
=== str_repeat('a', 32),
'In-place backup recovery did not preserve the business instance while restoring guest identity.');
echo "Portable backup create/restore finalizer behavior tests passed.\n";

@ -335,9 +335,20 @@ try {
): void {
$table->increments('id');
$table->string('purpose');
$table->string('source')->default('manual');
$table->integer('subscription_id')->nullable();
$table->integer('user_id')->default(0);
$table->string('state');
$table->integer('updated_at');
});
$schema->create('cloud_backup_subscriptions', static function (
Blueprint $table
): void {
$table->increments('id');
$table->boolean('enabled')->default(false);
$table->integer('next_run_at')->default(0);
$table->integer('retention_count')->default(2);
});
$schema->create('cloud_instance_migrations', static function (
Blueprint $table
): void {

@ -633,7 +633,7 @@ namespace {
'action', 'reinstall', 'instance_settings', 'network_change',
'instance_upgrade', 'firewall_apply', 'snapshot_create',
'snapshot_restore', 'snapshot_delete', 'backup_create',
'backup_restore', 'instance_migration_cleanup',
'backup_restore', 'backup_recover', 'instance_migration_cleanup',
'instance_migration_rollback', 'instance_migration_activate', 'rescue',
], 'The instance operation log does not cover every settings operation.');
$assert(in_array((string) $settingsAfterDelete->id, $operationLogIds, true),

@ -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";

@ -82,16 +82,17 @@ $assert(str_contains($service, 'final class CloudUserIsoService')
'User ISO service lost its one-shot child dispatch, terminal aggregate, result validation or quota boundary.');
$runtime = file_get_contents($root . '/public/cloud/runtime.js');
$assert(str_contains($orders, "if (\$source !== 'cloud')")
&& str_contains($orders, '当前只支持从云镜像部署实例')
$assert(str_contains($orders, "if (!in_array(\$source, ['cloud', 'backup'], true))")
&& str_contains($orders, '实例来源无效')
&& !str_contains($orders, "'iso_id'")
&& !str_contains($orders, "\$payload['user_iso_id']")
&& !str_contains($orders, 'iso_path')
&& str_contains($runtime, "source: 'cloud'")
&& str_contains($runtime,
"source: state.deployBackupId ? 'backup' : 'cloud'")
&& !str_contains($runtime, 'body.iso_id')
&& !str_contains($runtime, "byId('vm-iso')")
&& !str_contains($runtime, 'body.iso_path ='),
'VM provisioning must remain cloud-template-only while personal ISOs stay a separate owner library.');
'VM provisioning must remain limited to cloud templates and portable backups while personal ISOs stay a separate owner library.');
$assert(str_contains($schema, 'CREATE TABLE cloud_user_isos')
&& str_contains($schema, 'sealed_source_url LONGTEXT NOT NULL')

@ -73,7 +73,7 @@ $assert(str_contains($auth, "Config::get('tos_reg') === 'true'")
'Legal consent is only client-side and can be bypassed.');
$assets = $read('web/resources/views/venix/layout_assets.tpl');
$assert(str_contains($assets, "value='2026102601'")
$assert(str_contains($assets, "value='2026102602'")
&& str_contains($admin, '?v={$venix_asset_version}')
&& str_contains($read('web/resources/views/venix/home/layout_header.tpl'), '?v={$venix_asset_version}'),
'Shared browser asset version was not coupled to the new assets.');

@ -80,7 +80,7 @@ $assert(preg_match('/\.landing-site-header\s*\{[^}]*position:\s*fixed;/s', $css)
&& str_contains($accountCss, 'padding-top: 88px;')
&& str_contains($accountCss, 'padding-top: 76px;'),
'Persistent desktop or mobile public-navigation styling is incomplete.');
$assert(str_contains($read('web/resources/views/venix/layout_assets.tpl'), "value='2026102601'"),
$assert(str_contains($read('web/resources/views/venix/layout_assets.tpl'), "value='2026102602'"),
'The shared browser asset version was not advanced with the navigation styles.');
echo "Public page locale and shared-layout contract tests passed.\n";

@ -69,7 +69,7 @@ foreach ($templates as $template) {
}
$assets = $read('web/resources/views/venix/layout_assets.tpl');
$assert(str_contains($assets, "value='2026102601'"),
$assert(str_contains($assets, "value='2026102602'"),
'The shared asset version was not updated for the canonical logo.');
echo "Shared site-brand contract passed across public, auth, user, cloud and admin layouts.\n";

@ -43,7 +43,7 @@ $sharedSidebar = file_get_contents($views . '/user/panel_sidebar.tpl');
$sharedTopbar = file_get_contents($views . '/user/panel_topbar.tpl');
$clientEntry = file_get_contents($public . '/app.js');
$clientScript = $clientEntry . "\n" . file_get_contents($public . '/runtime.js');
foreach (['instances', 'detail', 'deploy', 'iso-images', 'ssh-keys', 'invoices', 'invoice-detail', 'reinstall'] as $module) {
foreach (['instances', 'detail', 'deploy', 'backups', 'iso-images', 'ssh-keys', 'invoices', 'invoice-detail', 'reinstall'] as $module) {
$path = $public . '/' . $module . '.js';
$assert(is_file($path), 'Cloud page module missing: ' . $module);
$clientScript .= "\n" . file_get_contents($path);
@ -216,6 +216,11 @@ $assert(str_contains($cloudTemplate, '>实例管理</h1>')
&& str_contains($cloudTemplate, '部署实例</a>'),
'Instance page terminology missing');
$assert(str_contains($sharedSidebar, '>我的实例</span>') && str_contains($sharedSidebar, '>部署实例</span>'), 'Shared sidebar instance terminology missing');
$assert(str_contains($sharedSidebar, 'href="/user/cloud/backups"')
&& str_contains($sharedSidebar, '>云备份</span>')
&& str_contains($cloudShell, "cloud_page == 'backups'")
&& str_contains($clientEntry, "backups: '/cloud/backups.js'"),
'User cloud-backup page must be reachable from the shared navigation and module bootstrap.');
$assert(str_contains($sharedSidebar, 'href="/user/cloud/iso-images"')
&& str_contains($sharedSidebar, '{if !empty($user_iso_enabled)}')
&& str_contains($sharedSidebar, '>ISO 上传</span>')
@ -231,8 +236,9 @@ $assert($regionPosition !== false && $linePosition > $regionPosition
&& str_contains($clientScript, 'function renderRegionPicker()')
&& str_contains($clientScript, 'function renderLinePicker()')
&& str_contains($clientScript, 'function renderOfferPicker()')
&& str_contains($clientScript, "source: 'cloud'")
&& str_contains($clientScript, "source: state.deployBackupId ? 'backup' : 'cloud'")
&& str_contains($clientScript, "offer_id: Number(byId('vm-offer').value)")
&& str_contains($clientScript, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
&& !str_contains($deployTemplate, 'host_id')
&& !str_contains($deployTemplate, 'plan_id')
&& !str_contains($clientScript, "body.iso_id")
@ -305,10 +311,12 @@ $offerRenderer = $offerRendererStart === false || $offerRendererEnd === false
$assert(str_contains($offerRenderer, "'offer-table-head'")
&& str_contains($offerRenderer, 'formatMemoryGiB(offer.memory_mib)')
&& str_contains($offerRenderer, 'formatTrafficTiB(offer.traffic_tib)')
&& str_contains($offerRenderer, 'formatUsd(offer.price)')
&& !str_contains($offerRenderer, 'formatUsd(offer.price)')
&& !str_contains($offerRenderer, 'bandwidth_mbps')
&& str_contains($baseStyles, '.offer-option[aria-pressed="true"]::after{content:"✓"')
&& str_contains($baseStyles, '.offer-option>:nth-child(6)::before{content:"价格"}')
&& !str_contains($baseStyles, '.offer-option>:nth-child(6)::before{content:"价格"}')
&& !str_contains($deployTemplate, 'offer-option-price')
&& str_contains($deployTemplate, 'id="vm-order-total-price"')
&& !str_contains($cloudTemplate, 'id="vm-plan-summary"')
&& !str_contains($cloudTemplate, 'class="vm-auto-public-pool"')
&& !str_contains($cloudTemplate, 'id="create-cloud-tip"')
@ -366,7 +374,7 @@ $assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/j
&& str_contains($deployTemplate, '{foreach $cloud_deploy_lines as $line}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_offers as $offer}')
&& str_contains($deployTemplate, '$cloud_deploy_lines_enabled')
&& str_contains($deployTemplate, 'USD</strong>')
&& !str_contains($deployTemplate, 'offer-option-price')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}')
&& !str_contains($deployTemplate, '正在加载系统镜像')
@ -443,7 +451,7 @@ $catalogRendererEnd = $catalogRendererStart === false ? false
$catalogRenderer = $catalogRendererStart === false || $catalogRendererEnd === false ? ''
: substr($runtimeDeployScript, $catalogRendererStart,
$catalogRendererEnd - $catalogRendererStart);
$mobileDeploymentStylesStart = strrpos($baseStyles, '@media(max-width:510px){');
$mobileDeploymentStylesStart = strpos($baseStyles, '@media(max-width:510px){.deployment-step');
$mobileDeploymentStyles = $mobileDeploymentStylesStart === false ? ''
: substr($baseStyles, $mobileDeploymentStylesStart);
$cardVersionRule = strpos($baseStyles,
@ -453,9 +461,7 @@ $flatVersionRule = strpos($baseStyles,
$assert(str_contains($mobileDeploymentStyles,
'.offer-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;')
&& str_contains($mobileDeploymentStyles,
'.offer-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}')
&& str_contains($mobileDeploymentStyles,
'.offer-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;')
'.offer-option-name{grid-column:1/5;grid-row:1;align-self:center;padding-right:31px;font-size:14px}')
&& str_contains($mobileDeploymentStyles,
'.offer-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}')
&& str_contains($mobileDeploymentStyles,
@ -463,8 +469,7 @@ $assert(str_contains($mobileDeploymentStyles,
&& str_contains($mobileDeploymentStyles,
'.offer-option[aria-pressed="true"]{box-shadow:none}')
&& !str_contains($mobileDeploymentStyles, 'box-shadow:inset 4px 0 0')
&& str_contains($mobileDeploymentStyles,
'.offer-option-price::before{display:none;content:none}')
&& !str_contains($mobileDeploymentStyles, '.offer-option-price')
&& !str_contains($mobileDeploymentStyles,
'.offer-option{grid-template-columns:repeat(2,minmax(0,1fr))'),
'Mobile deployment offers must use a compact two-row comparison layout without replacing semantic offer buttons.');
@ -604,8 +609,8 @@ $availabilityEnd = $availabilityStart === false ? false
: strpos($runtimeDeployScript, 'function strongPassword(', $availabilityStart);
$availability = $availabilityStart === false || $availabilityEnd === false ? ''
: substr($runtimeDeployScript, $availabilityStart, $availabilityEnd - $availabilityStart);
$assert(str_contains($availability, 'const offer = saleOffers()')
&& str_contains($availability, "const validMedia = Boolean(byId('vm-template')?.value)")
$assert(str_contains($availability, 'const offer = selectedSaleOffer()')
&& str_contains($availability, "const validMedia = Boolean(state.deployBackupId || byId('vm-template')?.value)")
&& !str_contains($availability, 'state.resources'),
'Deployment submission must require a matching region/line/offer and selected global image.');
$assert(str_contains($baseStyles, '.deployment-step')

Loading…
Cancel
Save