From ece7e24b526f36a73b3842925ef8316219c1cfa7 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 26 Oct 2026 12:06:15 +0800 Subject: [PATCH] feat(cloud): add paid automatic backups --- agent/api/server.go | 29 + agent/api/server_test.go | 56 ++ agent/cmd/virt-agent/main.go | 3 +- agent/cmd/virt-agent/main_test.go | 1 + agent/hypervisor/admission.go | 10 + agent/hypervisor/backup.go | 14 + agent/hypervisor/backup_test.go | 29 + agent/hypervisor/libvirt_backup_recovery.go | 279 +++++++++ agent/hypervisor/libvirt_connection.go | 6 + agent/hypervisor/libvirt_domain_features.go | 2 +- agent/hypervisor/libvirt_operation_admin.go | 64 +- agent/hypervisor/types.go | 24 + agent/operation/recovery_contract.json | 17 +- agent/operation/recovery_contract_test.go | 1 + web/app/Command/CloudSetup.php | 60 +- web/app/Controllers/Admin/ShopController.php | 16 +- web/app/Controllers/CloudApiController.php | 44 ++ web/app/Controllers/CloudPageController.php | 20 + web/app/Models/CloudBackupRecovery.php | 19 + web/app/Models/CloudBackupSubscription.php | 26 + web/app/Models/CloudInstanceBackup.php | 2 + web/app/Models/CloudInvoiceItem.php | 17 + web/app/Models/CloudJob.php | 1 + web/app/Models/CloudOffer.php | 34 +- web/app/Models/CloudOrderItem.php | 16 + .../CloudAdminOperationRecoveryService.php | 11 + .../Cloud/CloudAutomaticBackupService.php | 556 ++++++++++++++++++ web/app/Services/Cloud/CloudBackupService.php | 482 ++++++++++++++- .../Cloud/CloudDeploymentPageService.php | 7 + .../Cloud/CloudInvoicePaymentService.php | 12 +- .../Services/Cloud/CloudInvoiceService.php | 196 +++++- web/app/Services/Cloud/CloudJobService.php | 1 + .../Services/Cloud/CloudLifecycleService.php | 21 +- .../Services/Cloud/CloudOperationCatalog.php | 2 + .../Cloud/CloudOperationErrorCatalog.php | 3 + .../Cloud/CloudOperationRecoveryContract.php | 9 +- .../Cloud/CloudOperationRecoveryIdentity.php | 195 +++++- web/app/Services/Cloud/CloudOrderService.php | 366 ++++++++++-- .../Services/Cloud/CloudPlacementService.php | 25 +- .../Cloud/CloudPlanUpgradeService.php | 12 + .../Services/Cloud/CloudRenewalService.php | 16 +- .../Services/Cloud/CloudRuntimeHeartbeat.php | 4 + web/app/Services/Cloud/CloudWorkerService.php | 93 ++- web/config/routes.php | 1 + web/config/routes_cloud.php | 5 + web/public/cloud/app.js | 1 + web/public/cloud/backups.js | 197 +++++++ web/public/cloud/detail.js | 322 +++++++++- web/public/cloud/runtime.js | 109 +++- web/public/cloud/styles.css | 25 +- .../views/venix/admin/shop/offer_form.tpl | 5 +- web/resources/views/venix/cloud/page.tpl | 2 + .../views/venix/cloud/pages/backups.tpl | 19 + .../views/venix/cloud/pages/deploy.tpl | 26 +- .../views/venix/cloud/pages/detail.tpl | 19 + web/resources/views/venix/layout_assets.tpl | 2 +- .../views/venix/user/panel_sidebar.tpl | 3 + web/sql/cloud.sql | 83 +++ web/tests/AdminOfferCatalogContractTest.php | 18 +- web/tests/AdminOfferFormViewTest.php | 11 +- web/tests/AdminOfferWorkflowTest.php | 26 +- .../CloudAutomaticBackupScheduleTest.php | 40 ++ .../CloudAutomaticBackupSubscriptionTest.php | 199 +++++++ web/tests/CloudBillingLifecycleTest.php | 48 +- .../CloudDeploymentPageSsrContractTest.php | 9 +- web/tests/CloudFinancialWorkflowTest.php | 171 +++++- web/tests/CloudFreshSchemaContractTest.php | 19 +- web/tests/CloudInvoiceLifecycleTest.php | 41 +- web/tests/CloudInvoicePageServiceTest.php | 11 + .../CloudOperationRecoveryMatrixTest.php | 113 +++- .../CloudOperationRecoveryPolicyTest.php | 5 +- web/tests/CloudPlanDefinitionTest.php | 5 +- web/tests/CloudPlanUpgradeServiceTest.php | 14 + web/tests/CloudPortableBackupDeletionTest.php | 6 + .../CloudPortableBackupFinalizerTest.php | 96 +++ web/tests/CloudRuntimeHeartbeatTest.php | 11 + web/tests/CloudSnapshotWorkflowTest.php | 2 +- web/tests/CloudUserBackupUiContractTest.php | 79 +++ web/tests/CloudUserISOContractTest.php | 9 +- web/tests/LegalPagesContractTest.php | 2 +- web/tests/PublicPageLocaleContractTest.php | 2 +- web/tests/SiteBrandContractTest.php | 2 +- web/tests/VirtualizationAssetsTest.php | 31 +- 83 files changed, 4400 insertions(+), 190 deletions(-) create mode 100644 agent/hypervisor/libvirt_backup_recovery.go create mode 100644 web/app/Models/CloudBackupRecovery.php create mode 100644 web/app/Models/CloudBackupSubscription.php create mode 100644 web/app/Models/CloudInvoiceItem.php create mode 100644 web/app/Models/CloudOrderItem.php create mode 100644 web/app/Services/Cloud/CloudAutomaticBackupService.php create mode 100644 web/public/cloud/backups.js create mode 100644 web/resources/views/venix/cloud/pages/backups.tpl create mode 100644 web/tests/CloudAutomaticBackupScheduleTest.php create mode 100644 web/tests/CloudAutomaticBackupSubscriptionTest.php create mode 100644 web/tests/CloudUserBackupUiContractTest.php diff --git a/agent/api/server.go b/agent/api/server.go index de314f07..848c1a0b 100644 --- a/agent/api/server.go +++ b/agent/api/server.go @@ -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) { diff --git a/agent/api/server_test.go b/agent/api/server_test.go index de814b3f..3a85c878 100644 --- a/agent/api/server_test.go +++ b/agent/api/server_test.go @@ -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 ( diff --git a/agent/cmd/virt-agent/main.go b/agent/cmd/virt-agent/main.go index a93c10cd..0cd4e305 100644 --- a/agent/cmd/virt-agent/main.go +++ b/agent/cmd/virt-agent/main.go @@ -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 diff --git a/agent/cmd/virt-agent/main_test.go b/agent/cmd/virt-agent/main_test.go index ed0f0822..5897d79f 100644 --- a/agent/cmd/virt-agent/main_test.go +++ b/agent/cmd/virt-agent/main_test.go @@ -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) diff --git a/agent/hypervisor/admission.go b/agent/hypervisor/admission.go index b3fe48ef..7931867d 100644 --- a/agent/hypervisor/admission.go +++ b/agent/hypervisor/admission.go @@ -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{ diff --git a/agent/hypervisor/backup.go b/agent/hypervisor/backup.go index 12a83427..2b6ff123 100644 --- a/agent/hypervisor/backup.go +++ b/agent/hypervisor/backup.go @@ -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 diff --git a/agent/hypervisor/backup_test.go b/agent/hypervisor/backup_test.go index 1f5d2e34..958e7d75 100644 --- a/agent/hypervisor/backup_test.go +++ b/agent/hypervisor/backup_test.go @@ -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) { diff --git a/agent/hypervisor/libvirt_backup_recovery.go b/agent/hypervisor/libvirt_backup_recovery.go new file mode 100644 index 00000000..3029a66b --- /dev/null +++ b/agent/hypervisor/libvirt_backup_recovery.go @@ -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 +} diff --git a/agent/hypervisor/libvirt_connection.go b/agent/hypervisor/libvirt_connection.go index b6809336..7e295da6 100644 --- a/agent/hypervisor/libvirt_connection.go +++ b/agent/hypervisor/libvirt_connection.go @@ -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) diff --git a/agent/hypervisor/libvirt_domain_features.go b/agent/hypervisor/libvirt_domain_features.go index fe6dedf8..d0d6c385 100644 --- a/agent/hypervisor/libvirt_domain_features.go +++ b/agent/hypervisor/libvirt_domain_features.go @@ -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} { diff --git a/agent/hypervisor/libvirt_operation_admin.go b/agent/hypervisor/libvirt_operation_admin.go index 648b1f83..87ab3973 100644 --- a/agent/hypervisor/libvirt_operation_admin.go +++ b/agent/hypervisor/libvirt_operation_admin.go @@ -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 diff --git a/agent/hypervisor/types.go b/agent/hypervisor/types.go index 1edfe374..7d4548eb 100644 --- a/agent/hypervisor/types.go +++ b/agent/hypervisor/types.go @@ -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") } diff --git a/agent/operation/recovery_contract.json b/agent/operation/recovery_contract.json index 3f09a712..ef9c4492 100644 --- a/agent/operation/recovery_contract.json +++ b/agent/operation/recovery_contract.json @@ -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" ] diff --git a/agent/operation/recovery_contract_test.go b/agent/operation/recovery_contract_test.go index 0e101c92..86280f6f 100644 --- a/agent/operation/recovery_contract_test.go +++ b/agent/operation/recovery_contract_test.go @@ -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}, diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index 5281e1cc..d9e0f6c9 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -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', diff --git a/web/app/Controllers/Admin/ShopController.php b/web/app/Controllers/Admin/ShopController.php index ca65e22f..25379ade 100644 --- a/web/app/Controllers/Admin/ShopController.php +++ b/web/app/Controllers/Admin/ShopController.php @@ -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, diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 38c73c0c..548f882d 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -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) { diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 2df45f24..dfe26f92 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -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', []); diff --git a/web/app/Models/CloudBackupRecovery.php b/web/app/Models/CloudBackupRecovery.php new file mode 100644 index 00000000..e14998f1 --- /dev/null +++ b/web/app/Models/CloudBackupRecovery.php @@ -0,0 +1,19 @@ + 'int', + 'backup_id' => 'int', + 'instance_id' => 'int', + 'job_id' => 'int', + 'completed_at' => 'int', + 'created_at' => 'int', + 'updated_at' => 'int', + ]; +} diff --git a/web/app/Models/CloudBackupSubscription.php b/web/app/Models/CloudBackupSubscription.php new file mode 100644 index 00000000..5f42e6fa --- /dev/null +++ b/web/app/Models/CloudBackupSubscription.php @@ -0,0 +1,26 @@ + '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', + ]; +} diff --git a/web/app/Models/CloudInstanceBackup.php b/web/app/Models/CloudInstanceBackup.php index 7407ebe2..a0744e96 100644 --- a/web/app/Models/CloudInstanceBackup.php +++ b/web/app/Models/CloudInstanceBackup.php @@ -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', diff --git a/web/app/Models/CloudInvoiceItem.php b/web/app/Models/CloudInvoiceItem.php new file mode 100644 index 00000000..5b670cae --- /dev/null +++ b/web/app/Models/CloudInvoiceItem.php @@ -0,0 +1,17 @@ + 'int', + 'invoice_id' => 'int', + 'order_item_id' => 'int', + 'amount' => 'decimal:2', + 'created_at' => 'int', + ]; +} diff --git a/web/app/Models/CloudJob.php b/web/app/Models/CloudJob.php index 97f4c379..927bce14 100644 --- a/web/app/Models/CloudJob.php +++ b/web/app/Models/CloudJob.php @@ -10,6 +10,7 @@ final class CloudJob extends Model protected $casts = [ 'backup_id' => 'int', 'backup_restore_id' => 'int', + 'backup_recovery_id' => 'int', ]; /** diff --git a/web/app/Models/CloudOffer.php b/web/app/Models/CloudOffer.php index 31efacd6..fafa15ed 100644 --- a/web/app/Models/CloudOffer.php +++ b/web/app/Models/CloudOffer.php @@ -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'); + } } diff --git a/web/app/Models/CloudOrderItem.php b/web/app/Models/CloudOrderItem.php new file mode 100644 index 00000000..c613314a --- /dev/null +++ b/web/app/Models/CloudOrderItem.php @@ -0,0 +1,16 @@ + 'int', + 'order_id' => 'int', + 'amount' => 'decimal:2', + 'created_at' => 'int', + ]; +} diff --git a/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php b/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php index 7dc74ed4..b7a6924f 100644 --- a/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php +++ b/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php @@ -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', diff --git a/web/app/Services/Cloud/CloudAutomaticBackupService.php b/web/app/Services/Cloud/CloudAutomaticBackupService.php new file mode 100644 index 00000000..f0696b77 --- /dev/null +++ b/web/app/Services/Cloud/CloudAutomaticBackupService.php @@ -0,0 +1,556 @@ + ['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; + } +} diff --git a/web/app/Services/Cloud/CloudBackupService.php b/web/app/Services/Cloud/CloudBackupService.php index 434f306d..a3aba927 100644 --- a/web/app/Services/Cloud/CloudBackupService.php +++ b/web/app/Services/Cloud/CloudBackupService.php @@ -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') diff --git a/web/app/Services/Cloud/CloudDeploymentPageService.php b/web/app/Services/Cloud/CloudDeploymentPageService.php index 4e3e0fe0..4cfcadc7 100644 --- a/web/app/Services/Cloud/CloudDeploymentPageService.php +++ b/web/app/Services/Cloud/CloudDeploymentPageService.php @@ -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, diff --git a/web/app/Services/Cloud/CloudInvoicePaymentService.php b/web/app/Services/Cloud/CloudInvoicePaymentService.php index db71aae3..1b841e9a 100644 --- a/web/app/Services/Cloud/CloudInvoicePaymentService.php +++ b/web/app/Services/Cloud/CloudInvoicePaymentService.php @@ -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) { diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php index cb3ed4c8..bbbae6a3 100644 --- a/web/app/Services/Cloud/CloudInvoiceService.php +++ b/web/app/Services/Cloud/CloudInvoiceService.php @@ -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'; diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index 2c6af825..27aade27 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -41,6 +41,7 @@ final class CloudJobService private const PORTABLE_BACKUP_KINDS = [ 'backup_create', 'backup_restore', + 'backup_recover', ]; private const AGGREGATE_KINDS = [ 'template_import', diff --git a/web/app/Services/Cloud/CloudLifecycleService.php b/web/app/Services/Cloud/CloudLifecycleService.php index f5e3aa8f..a1c3cf91 100644 --- a/web/app/Services/Cloud/CloudLifecycleService.php +++ b/web/app/Services/Cloud/CloudLifecycleService.php @@ -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') diff --git a/web/app/Services/Cloud/CloudOperationCatalog.php b/web/app/Services/Cloud/CloudOperationCatalog.php index 3d144807..4e8917a6 100644 --- a/web/app/Services/Cloud/CloudOperationCatalog.php +++ b/web/app/Services/Cloud/CloudOperationCatalog.php @@ -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', diff --git a/web/app/Services/Cloud/CloudOperationErrorCatalog.php b/web/app/Services/Cloud/CloudOperationErrorCatalog.php index 32d6002f..c5afa4a7 100644 --- a/web/app/Services/Cloud/CloudOperationErrorCatalog.php +++ b/web/app/Services/Cloud/CloudOperationErrorCatalog.php @@ -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' => '实例策略执行失败;本次任务不会自动重试', diff --git a/web/app/Services/Cloud/CloudOperationRecoveryContract.php b/web/app/Services/Cloud/CloudOperationRecoveryContract.php index f234755f..693f0905 100644 --- a/web/app/Services/Cloud/CloudOperationRecoveryContract.php +++ b/web/app/Services/Cloud/CloudOperationRecoveryContract.php @@ -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' => [ diff --git a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php index 681f1a54..7bbf2aa8 100644 --- a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php +++ b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php @@ -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 diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index 2438acb4..12d15432 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -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( diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index c179c581..19e09e0c 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -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) { diff --git a/web/app/Services/Cloud/CloudPlanUpgradeService.php b/web/app/Services/Cloud/CloudPlanUpgradeService.php index b1cc607a..e8a35712 100644 --- a/web/app/Services/Cloud/CloudPlanUpgradeService.php +++ b/web/app/Services/Cloud/CloudPlanUpgradeService.php @@ -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', diff --git a/web/app/Services/Cloud/CloudRenewalService.php b/web/app/Services/Cloud/CloudRenewalService.php index 8da82fa5..74e78e6c 100644 --- a/web/app/Services/Cloud/CloudRenewalService.php +++ b/web/app/Services/Cloud/CloudRenewalService.php @@ -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); diff --git a/web/app/Services/Cloud/CloudRuntimeHeartbeat.php b/web/app/Services/Cloud/CloudRuntimeHeartbeat.php index 0850501a..2cb4d155 100644 --- a/web/app/Services/Cloud/CloudRuntimeHeartbeat.php +++ b/web/app/Services/Cloud/CloudRuntimeHeartbeat.php @@ -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', diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 4c05f0b7..69ab4ed4 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -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 diff --git a/web/config/routes.php b/web/config/routes.php index 6bf9d64e..0a5ae1d1 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -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'); diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index 6f8ead5c..73651450 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -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'); diff --git a/web/public/cloud/app.js b/web/public/cloud/app.js index b7b609ef..d837374f 100644 --- a/web/public/cloud/app.js +++ b/web/public/cloud/app.js @@ -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', diff --git a/web/public/cloud/backups.js b/web/public/cloud/backups.js new file mode 100644 index 00000000..a07665d8 --- /dev/null +++ b/web/public/cloud/backups.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 || '云备份页面加载失败,请刷新后重试。'); + } +} diff --git a/web/public/cloud/detail.js b/web/public/cloud/detail.js index 143c16e1..09f7ee73 100644 --- a/web/public/cloud/detail.js +++ b/web/public/cloud/detail.js @@ -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); diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 2a2e18bd..f88e33cf 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -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); diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css index 1363d419..dd6bdd73 100644 --- a/web/public/cloud/styles.css +++ b/web/public/cloud/styles.css @@ -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%}} diff --git a/web/resources/views/venix/admin/shop/offer_form.tpl b/web/resources/views/venix/admin/shop/offer_form.tpl index eee55541..c309bbac 100644 --- a/web/resources/views/venix/admin/shop/offer_form.tpl +++ b/web/resources/views/venix/admin/shop/offer_form.tpl @@ -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 @@
- 价格与销售状态价格固定使用 USD;库存为 0 或下架时停止新购。 + 价格与销售状态实例和自动备份价格固定使用 USD;库存为 0 或下架时停止新购。
$
{if $offer}
当前价格版本 v{$offer->price_version|escape};修改价格后自动递增。
{/if}
+
$
所有在售规格均可选购自动备份;这里只配置价格,备份频率和保留数量由用户在实例设置中选择。
-1 表示不限库存,0 表示暂停新购。
下架不会删除历史订单或已开通实例。
diff --git a/web/resources/views/venix/cloud/page.tpl b/web/resources/views/venix/cloud/page.tpl index 4ee0e3f6..ce144bf9 100644 --- a/web/resources/views/venix/cloud/page.tpl +++ b/web/resources/views/venix/cloud/page.tpl @@ -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'} diff --git a/web/resources/views/venix/cloud/pages/backups.tpl b/web/resources/views/venix/cloud/pages/backups.tpl new file mode 100644 index 00000000..30c8cf53 --- /dev/null +++ b/web/resources/views/venix/cloud/pages/backups.tpl @@ -0,0 +1,19 @@ +
+
+
CLOUD BACKUPS

云备份

集中查看当前账户的云备份,并选择可用备份创建新的付费实例。

+ +
+
恢复入口说明此页面只用于从备份创建新实例。将已有实例恢复到某个备份,只能在该实例详情的“实例设置 → 自动备份”中执行。
+
+

全部备份

只显示属于当前账户的普通云备份,不包含管理员维护迁移的临时数据。

0 个
+

正在读取云备份…

+
+ +
+ +
+ diff --git a/web/resources/views/venix/cloud/pages/deploy.tpl b/web/resources/views/venix/cloud/pages/deploy.tpl index 94747511..b54b3bce 100644 --- a/web/resources/views/venix/cloud/pages/deploy.tpl +++ b/web/resources/views/venix/cloud/pages/deploy.tpl @@ -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}
名称CPU内存硬盘每期流量价格
{/if} + {if !$default_line_has_offers}
名称CPU内存硬盘每期流量
{/if} {assign var=default_line_has_offers value=true} {assign var=offer_memory_gib value=$offer.memory_mib/1024} {/if} {/foreach} @@ -61,6 +60,12 @@
{if !empty($cloud_deploy_lines_enabled)}4{else}3{/if}

选择系统镜像(必选)

+ +
{if empty($cloud_deploy_template_groups)}

{if !empty($cloud_deploy_catalog_unavailable)}系统镜像目录暂时无法读取,请稍后刷新。{else}暂无可用云镜像,请联系管理员导入模板。{/if}

@@ -89,6 +94,23 @@
SSH 公钥
{if empty($cloud_deploy_ssh_keys)}

暂无公钥,可先到“公钥管理”添加。

{else}{foreach $cloud_deploy_ssh_keys as $key}{/foreach}{/if}
管理我的公钥
+
+
{if !empty($cloud_deploy_lines_enabled)}6{else}5{/if}

自动备份

+ +
+
+
{if !empty($cloud_deploy_lines_enabled)}7{else}6{/if}

确认费用

+

选择实例规格后显示本次最终金额。

+ +
diff --git a/web/resources/views/venix/cloud/pages/detail.tpl b/web/resources/views/venix/cloud/pages/detail.tpl index d730c0d7..618f9e2d 100644 --- a/web/resources/views/venix/cloud/pages/detail.tpl +++ b/web/resources/views/venix/cloud/pages/detail.tpl @@ -52,6 +52,7 @@ + {/if} @@ -153,6 +154,24 @@ +