From 59dff015355b93800d024e097dfc949584165536 Mon Sep 17 00:00:00 2001 From: codex Date: Fri, 16 Oct 2026 13:00:18 +0800 Subject: [PATCH] fix: preserve VM creation failure cause --- agent/api/server.go | 25 +- agent/api/server_test.go | 3 +- agent/hypervisor/libvirt_adapter.go | 178 ++++++++--- agent/hypervisor/libvirt_safety_test.go | 282 ++++++++++++++++++ agent/hypervisor/libvirt_snapshot_features.go | 6 +- agent/hypervisor/libvirt_storage_evidence.go | 109 +++++++ agent/operation/journal.go | 54 +++- agent/operation/journal_test.go | 64 +++- docs/ADMIN_OPERATIONS.md | 1 + docs/AGENT_API.md | 7 + docs/VALIDATION.md | 16 + gateway/agent/registry_test.go | 44 ++- .../Cloud/CloudAdminOperationsService.php | 14 +- web/app/Services/Cloud/CloudAgentClient.php | 18 ++ .../Cloud/CloudOperationErrorCatalog.php | 35 ++- web/app/Services/Cloud/CloudWorkerService.php | 20 ++ web/public/cloud/admin-operations.js | 1 + web/tests/CloudAdminOperationsServiceTest.php | 13 +- web/tests/CloudAgentProtocolTest.php | 36 +++ web/tests/CloudFinancialWorkflowTest.php | 28 ++ web/tests/CloudOperationErrorCatalogTest.php | 26 +- web/tests/CloudProtocolTest.php | 18 ++ 22 files changed, 928 insertions(+), 70 deletions(-) create mode 100644 agent/hypervisor/libvirt_storage_evidence.go diff --git a/agent/api/server.go b/agent/api/server.go index 3da577da..4813a5f0 100644 --- a/agent/api/server.go +++ b/agent/api/server.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "log" "net/http" "net/url" "regexp" @@ -29,6 +30,7 @@ var ( apiUUIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`) resourceIDPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`) operationIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`) + stableCodePattern = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`) sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`) catalogIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) sourceTokenPattern = regexp.MustCompile(`^[A-Za-z0-9._~-]{32,512}$`) @@ -75,6 +77,7 @@ type operationResponse struct { Replayed bool `json:"replayed"` Result json.RawMessage `json:"result,omitempty"` Error *operation.PublicError `json:"error,omitempty"` + CauseCode string `json:"cause_code,omitempty"` Retryable bool `json:"retryable"` } @@ -859,6 +862,7 @@ func (s *Server) routeOperations(w http.ResponseWriter, r *http.Request, segment ctx, cancel := context.WithTimeout(r.Context(), s.OperationTimeout) defer cancel() record, err := s.Journal.Reconcile(ctx, operationID, s.Hypervisor.Reconcile) + logOperationOutcome(record) if err != nil { if errors.Is(err, operation.ErrOperationUncertain) || operation.IsUncertain(err) { writeError(w, http.StatusConflict, "operation_uncertain", "operation remains uncertain", &record) @@ -925,6 +929,7 @@ func (s *Server) runMutationExpected( } return encoded, nil }) + logOperationOutcome(record) if errors.Is(callErr, operation.ErrFingerprint) { writeError(w, http.StatusConflict, "operation_id_conflict", "operation_id is already bound to a different request", nil) return @@ -1029,6 +1034,9 @@ func (s *Server) runAsyncMutation( defer func() { <-s.asyncSlots }() defer s.releaseAsync(operationID) <-done + if final, getErr := s.Journal.Get(operationID); getErr == nil { + logOperationOutcome(final) + } }() } } @@ -1097,11 +1105,26 @@ func (s *Server) releaseAsync(operationID string) { func operationWire(record operation.Record, replayed bool) operationResponse { return operationResponse{ OperationID: record.OperationID, Status: record.State, Replayed: replayed, - Result: record.Result, Error: record.Error, + Result: record.Result, Error: record.Error, CauseCode: record.CauseCode, Retryable: record.State == operation.StateUncertain, } } +// Log only bounded identifiers and stable codes. Free-form backend errors, +// request bodies, guest credentials, and host paths never enter this line. +func logOperationOutcome(record operation.Record) { + if record.State != operation.StateFailed && record.State != operation.StateUncertain { + return + } + errorCode := "" + if record.Error != nil && len(record.Error.Code) <= 64 && + stableCodePattern.MatchString(record.Error.Code) { + errorCode = record.Error.Code + } + log.Printf("Agent operation outcome operation_id=%s action=%s status=%s error_code=%s cause_code=%s", + record.OperationID, record.Action, record.State, errorCode, record.CauseCode) +} + func resolveOperationID(actorID, bodyID string) (string, error) { if actorID == "" && bodyID == "" { return "", errors.New("operation_id is required in X-Virt-Actor or request body") diff --git a/agent/api/server_test.go b/agent/api/server_test.go index 99a82594..cd8c387b 100644 --- a/agent/api/server_test.go +++ b/agent/api/server_test.go @@ -474,7 +474,7 @@ func TestFailedCreateRouteUsesReadOnlyReconciliationWithoutReplay(t *testing.T) } if record, _, err := api.journal.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { - return nil, errors.New("network selector is not configured") + return nil, hypervisor.NewError(hypervisor.ErrInvalid, "network_selector_invalid", "network selector is not configured", nil) }); err == nil || record.State != operation.StateFailed { t.Fatalf("initial failed create = %#v err=%v", record, err) } @@ -489,6 +489,7 @@ func TestFailedCreateRouteUsesReadOnlyReconciliationWithoutReplay(t *testing.T) "/v1/operations/"+operationID+"/reconcile", []byte(`{}`), actor) if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"status":"failed"`) || + !strings.Contains(response.Body.String(), `"cause_code":"network_selector_invalid"`) || !strings.Contains(response.Body.String(), `"managed_artifacts_absent":true`) { t.Fatalf("failed create reconcile response = %d %s", response.Code, response.Body.String()) } diff --git a/agent/hypervisor/libvirt_adapter.go b/agent/hypervisor/libvirt_adapter.go index 3bb2e0ae..968363fa 100644 --- a/agent/hypervisor/libvirt_adapter.go +++ b/agent/hypervisor/libvirt_adapter.go @@ -30,6 +30,61 @@ type Libvirt struct { traffic *trafficStore } +type createVMFailureStage struct { + code string + message string +} + +var ( + createVMTemplateLookupStage = createVMFailureStage{ + code: "template_lookup_failed", message: "template metadata or volume could not be located", + } + createVMTemplateCapacityStage = createVMFailureStage{ + code: "template_capacity_failed", message: "template capacity could not satisfy the requested disk", + } + createVMStorageCloneStage = createVMFailureStage{ + code: "storage_clone_failed", message: "system disk could not be cloned from the template", + } + createVMSeedCreateStage = createVMFailureStage{ + code: "seed_create_failed", message: "cloud-init seed volume could not be created", + } + createVMSeedUploadStage = createVMFailureStage{ + code: "seed_upload_failed", message: "cloud-init seed data could not be uploaded", + } + createVMNWFilterDefineStage = createVMFailureStage{ + code: "nwfilter_define_failed", message: "virtual machine network filter could not be defined", + } + createVMDomainDefineStage = createVMFailureStage{ + code: "domain_define_failed", message: "virtual machine definition could not be created", + } + createVMDomainAutostartStage = createVMFailureStage{ + code: "domain_autostart_failed", message: "virtual machine autostart could not be enabled", + } + createVMDomainStartStage = createVMFailureStage{ + code: "domain_start_failed", message: "virtual machine could not be started", + } +) + +type createVMStageError struct { + stage createVMFailureStage + cause error +} + +func (e *createVMStageError) Error() string { return e.stage.message } +func (e *createVMStageError) Unwrap() error { return e.cause } +func (e *createVMStageError) PublicCode() string { return e.stage.code } +func (e *createVMStageError) PublicMessage() string { return e.stage.message } + +// wrap exposes only a stable stage code and bounded public message. The full +// cause remains in the error chain for local diagnostics and, importantly, +// preserves operation uncertainty and the original hypervisor error kind. +func (stage createVMFailureStage) wrap(cause error) error { + if cause == nil { + return nil + } + return &createVMStageError{stage: stage, cause: cause} +} + func OpenLibvirt(uri string, local LocalConfig) (Hypervisor, error) { if uri != "qemu:///system" { return nil, NewError(ErrInvalid, "invalid_libvirt_uri", "only qemu:///system is allowed", nil) @@ -192,7 +247,7 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe attachment.MAC = mac templateRecord, err := l.loadImageTemplate(request.TemplateID) if err != nil { - return VMMetadata{}, err + return VMMetadata{}, createVMTemplateLookupStage.wrap(err) } if templateRecord.GenerationToken != request.TemplateGenerationToken { return VMMetadata{}, NewError(ErrConflict, "template_generation_changed", "template generation token no longer matches", nil) @@ -220,12 +275,13 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe cleanupErr := root.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL) _ = root.Free() if cleanupErr != nil { - return VMMetadata{}, operation.MarkUncertain(errors.Join( + return VMMetadata{}, operation.MarkUncertain(createVMStorageCloneStage.wrap(errors.Join( mutationLibvirtError("resolve cloned root volume path", err), mutationLibvirtError("roll back cloned root volume", cleanupErr), - )) + ))) } - return VMMetadata{}, mutationLibvirtError("resolve cloned root volume path", err) + return VMMetadata{}, createVMStorageCloneStage.wrap( + mutationLibvirtError("resolve cloned root volume path", err)) } rootOwned := true defer func() { @@ -247,12 +303,13 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe cleanupErr := seedVolume.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL) _ = seedVolume.Free() if cleanupErr != nil { - return VMMetadata{}, operation.MarkUncertain(errors.Join( + return VMMetadata{}, operation.MarkUncertain(createVMSeedCreateStage.wrap(errors.Join( mutationLibvirtError("resolve NoCloud volume path", err), mutationLibvirtError("roll back NoCloud seed volume", cleanupErr), - )) + ))) } - return VMMetadata{}, mutationLibvirtError("resolve NoCloud volume path", err) + return VMMetadata{}, createVMSeedCreateStage.wrap( + mutationLibvirtError("resolve NoCloud volume path", err)) } seedOwned := true defer func() { @@ -268,11 +325,19 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe filterName := networkFilterName(request.UUID) filterDocument, err := BuildPlatformFilterXML(filterName, request.PlatformNetworkPolicy) if err != nil { - return VMMetadata{}, err + return VMMetadata{}, createVMNWFilterDefineStage.wrap(err) } filter, err := l.conn.NWFilterDefineXML(filterDocument) if err != nil { - return VMMetadata{}, operation.MarkUncertain(mutationLibvirtError("define VM network filter", err)) + observed, inspectErr := l.lookupOptionalNetworkFilter(filterName) + artifactExists := observed != nil + if observed != nil { + _ = observed.Free() + } + return VMMetadata{}, createVMNWFilterDefineStage.wrap( + deterministicArtifactCreateFailure( + "define VM network filter", err, inspectErr, artifactExists, + )) } filterOwned := true defer func() { @@ -302,7 +367,7 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe PlatformNetworkPolicy: request.PlatformNetworkPolicy, }) if err != nil { - return VMMetadata{}, err + return VMMetadata{}, createVMDomainDefineStage.wrap(err) } trafficCreated, err := l.traffic.initialize(request.UUID, time.Now().UTC()) if err != nil { @@ -333,12 +398,12 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe // not let deferred cleanup remove disks, firewall, or accounting // state that the possibly-defined domain owns. preserveDefinedDomainArtifacts() - return VMMetadata{}, operation.MarkUncertain(errors.Join( + return VMMetadata{}, operation.MarkUncertain(createVMDomainDefineStage.wrap(errors.Join( mutationLibvirtError("define domain", err), translateOptionalLibvirtError("inspect domain after define failure", inspectErr), - )) + ))) } - return VMMetadata{}, mutationLibvirtError("define domain", err) + return VMMetadata{}, createVMDomainDefineStage.wrap(mutationLibvirtError("define domain", err)) } defer domain.Free() if err := domain.SetAutostart(true); err != nil { @@ -346,26 +411,28 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe absent, inspectErr := l.deleteDomainAbsent(ctx, request.UUID) if inspectErr != nil || !absent { preserveDefinedDomainArtifacts() - return VMMetadata{}, operation.MarkUncertain(errors.Join( + return VMMetadata{}, operation.MarkUncertain(createVMDomainAutostartStage.wrap(errors.Join( mutationLibvirtError("enable domain autostart", err), optionalMutationLibvirtError("roll back domain definition", rollbackErr), inspectErr, - )) + ))) } if rollbackErr != nil { - return VMMetadata{}, operation.MarkUncertain(errors.Join( + return VMMetadata{}, operation.MarkUncertain(createVMDomainAutostartStage.wrap(errors.Join( mutationLibvirtError("enable domain autostart", err), mutationLibvirtError("roll back domain definition", rollbackErr), - )) + ))) } - return VMMetadata{}, mutationLibvirtError("enable domain autostart", err) + return VMMetadata{}, createVMDomainAutostartStage.wrap( + mutationLibvirtError("enable domain autostart", err)) } preserveDefinedDomainArtifacts() // From this point onward Domain.Create may have taken effect even if its // response is lost. Retain the zero baseline so reconciliation and the // first successful sample account for all traffic since initial boot. if err := domain.Create(); err != nil { - return VMMetadata{}, operation.MarkUncertain(mutationLibvirtError("start newly defined domain", err)) + return VMMetadata{}, operation.MarkUncertain(createVMDomainStartStage.wrap( + mutationLibvirtError("start newly defined domain", err))) } if err := l.verifyCreatedDomain(domain, request, filterName, mac); err != nil { return VMMetadata{}, operation.MarkUncertain(err) @@ -421,32 +488,37 @@ func (l *Libvirt) resolvePublicNetwork(ctx context.Context, func (l *Libvirt) cloneRootVolume(request CreateVMRequest) (*libvirt.StorageVol, error) { templateRecord, err := l.loadImageTemplate(request.TemplateID) if err != nil { - return nil, err + return nil, createVMTemplateLookupStage.wrap(err) } if templateRecord.GenerationToken != request.TemplateGenerationToken { return nil, NewError(ErrConflict, "template_generation_changed", "template generation token no longer matches", nil) } templatePool, err := l.conn.LookupStoragePoolByName(l.local.TemplateStoragePool) if err != nil { - return nil, translateLibvirtError("lookup template storage pool", err) + return nil, createVMTemplateLookupStage.wrap( + translateLibvirtError("lookup template storage pool", err)) } defer templatePool.Free() template, err := templatePool.LookupStorageVolByName(templateVolumeName(request.TemplateID)) if err != nil { - return nil, translateLibvirtError("lookup template volume", err) + return nil, createVMTemplateLookupStage.wrap( + translateLibvirtError("lookup template volume", err)) } defer template.Free() templateInfo, err := template.GetInfo() if err != nil { - return nil, translateLibvirtError("read template volume size", err) + return nil, createVMTemplateCapacityStage.wrap( + translateLibvirtError("read template volume size", err)) } capacity := request.DiskGiB << 30 if capacity < templateInfo.Capacity { - return nil, NewError(ErrInvalid, "disk_smaller_than_template", "disk_gib is smaller than the selected template", nil) + return nil, createVMTemplateCapacityStage.wrap(NewError( + ErrInvalid, "disk_smaller_than_template", "disk_gib is smaller than the selected template", nil)) } managedPool, err := l.conn.LookupStoragePoolByName(l.local.ManagedStoragePool) if err != nil { - return nil, translateLibvirtError("lookup managed storage pool", err) + return nil, createVMStorageCloneStage.wrap( + translateLibvirtError("lookup managed storage pool", err)) } defer managedPool.Free() definition := libvirtxml.StorageVolume{ @@ -458,11 +530,16 @@ func (l *Libvirt) cloneRootVolume(request CreateVMRequest) (*libvirt.StorageVol, } document, err := definition.Marshal() if err != nil { - return nil, fmt.Errorf("marshal root volume XML: %w", err) + return nil, createVMStorageCloneStage.wrap(fmt.Errorf("marshal root volume XML: %w", err)) } volume, err := managedPool.StorageVolCreateXMLFrom(document, template, 0) if err != nil { - return nil, operation.MarkUncertain(mutationLibvirtError("clone template volume", err)) + artifactAbsent, inspectErr := l.dirPoolVolumeAbsent( + managedPool, rootVolumeName(request.UUID), + ) + return nil, createVMStorageCloneStage.wrap(deterministicArtifactCreateFailure( + "clone template volume", err, inspectErr, !artifactAbsent, + )) } return volume, nil } @@ -470,7 +547,8 @@ func (l *Libvirt) cloneRootVolume(request CreateVMRequest) (*libvirt.StorageVol, func (l *Libvirt) createSeedVolume(uuid string, contents []byte) (*libvirt.StorageVol, error) { pool, err := l.conn.LookupStoragePoolByName(l.local.SeedStoragePool) if err != nil { - return nil, translateLibvirtError("lookup seed storage pool", err) + return nil, createVMSeedCreateStage.wrap( + translateLibvirtError("lookup seed storage pool", err)) } defer pool.Free() definition := libvirtxml.StorageVolume{ @@ -480,20 +558,24 @@ func (l *Libvirt) createSeedVolume(uuid string, contents []byte) (*libvirt.Stora } document, err := definition.Marshal() if err != nil { - return nil, fmt.Errorf("marshal seed volume XML: %w", err) + return nil, createVMSeedCreateStage.wrap(fmt.Errorf("marshal seed volume XML: %w", err)) } volume, err := pool.StorageVolCreateXML(document, 0) if err != nil { - return nil, operation.MarkUncertain(mutationLibvirtError("create NoCloud volume", err)) + artifactAbsent, inspectErr := l.dirPoolVolumeAbsent(pool, seedVolumeName(uuid)) + return nil, createVMSeedCreateStage.wrap(deterministicArtifactCreateFailure( + "create NoCloud volume", err, inspectErr, !artifactAbsent, + )) } if err := l.uploadVolume(volume, contents); err != nil { + uploadErr := createVMSeedUploadStage.wrap(err) cleanupErr := volume.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL) _ = volume.Free() if cleanupErr != nil { - return nil, operation.MarkUncertain(errors.Join(err, + return nil, operation.MarkUncertain(errors.Join(uploadErr, mutationLibvirtError("roll back NoCloud seed volume", cleanupErr))) } - return nil, err + return nil, uploadErr } return volume, nil } @@ -1015,10 +1097,7 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera // These reconciliation paths can continue only target-state or cleanup // steps uniquely owned by the original operation. Serialize them with // normal domain mutations; the journal already holds the per-VM lock. - if record.Action == "delete-vm" || record.Action == "reinstall-vm" || - strings.HasPrefix(record.Action, "create-snapshot:") || - strings.HasPrefix(record.Action, "delete-snapshot:") || - strings.HasPrefix(record.Action, "restore-snapshot:") { + if reconciliationNeedsDomainMutationLock(record.Action) { domainMutationMu.Lock() defer domainMutationMu.Unlock() } @@ -1093,6 +1172,13 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera return operation.Resolution{}, nil } +func reconciliationNeedsDomainMutationLock(action string) bool { + return action == "create-vm" || action == "delete-vm" || action == "reinstall-vm" || + strings.HasPrefix(action, "create-snapshot:") || + strings.HasPrefix(action, "delete-snapshot:") || + strings.HasPrefix(action, "restore-snapshot:") +} + func (l *Libvirt) reconcileExistingDelete(ctx context.Context, uuid string, domain *libvirt.Domain) (operation.Resolution, error) { _, managed, err := requireManagedDomain(domain) @@ -1271,11 +1357,21 @@ func (l *Libvirt) cleanupDeletedVMArtifacts(ctx context.Context, uuid string) er } func (l *Libvirt) deleteArtifactsAbsent(uuid string) (bool, error) { + if !uuidPattern.MatchString(uuid) { + return false, NewError(ErrInvalid, "invalid_uuid", "uuid must be canonical", nil) + } pool, err := l.conn.LookupStoragePoolByName(l.local.ManagedStoragePool) if err != nil { return false, translateLibvirtError("lookup managed storage pool", err) } defer pool.Free() + rootAbsent, err := l.dirPoolVolumeAbsent(pool, rootVolumeName(uuid)) + if err != nil { + return false, err + } + if !rootAbsent { + return false, nil + } inventory, err := pool.ListStorageVolumes() if err != nil { return false, translateLibvirtError("list managed volumes for reconciliation", err) @@ -1287,12 +1383,16 @@ func (l *Libvirt) deleteArtifactsAbsent(uuid string) (bool, error) { if len(owned) != 0 { return false, nil } - seed, err := l.lookupOptionalManagedVolume(l.local.SeedStoragePool, seedVolumeName(uuid)) + seedPool, err := l.conn.LookupStoragePoolByName(l.local.SeedStoragePool) + if err != nil { + return false, translateLibvirtError("lookup seed storage pool", err) + } + defer seedPool.Free() + seedAbsent, err := l.dirPoolVolumeAbsent(seedPool, seedVolumeName(uuid)) if err != nil { return false, err } - if seed != nil { - _ = seed.Free() + if !seedAbsent { return false, nil } filter, err := l.lookupOptionalNetworkFilter(networkFilterName(uuid)) diff --git a/agent/hypervisor/libvirt_safety_test.go b/agent/hypervisor/libvirt_safety_test.go index e1ce513d..888853be 100644 --- a/agent/hypervisor/libvirt_safety_test.go +++ b/agent/hypervisor/libvirt_safety_test.go @@ -308,6 +308,288 @@ func TestDomainAbsenceEvidenceRequiresNoDomainCode(t *testing.T) { } } +func TestCreateMutationLibvirtErrorsOnlyMarkAmbiguousTransportFailuresUncertain(t *testing.T) { + for _, test := range []struct { + name string + cause error + uncertain bool + wantCode string + }{ + { + name: "deterministic-invalid-request", cause: libvirt.Error{Code: libvirt.ERR_INVALID_ARG}, + wantCode: "invalid_libvirt_request", + }, + { + name: "deterministic-operation-denied", cause: libvirt.Error{Code: libvirt.ERR_OPERATION_DENIED}, + wantCode: "libvirt_conflict", + }, + { + name: "rpc-result-unknown", cause: libvirt.Error{Code: libvirt.ERR_RPC}, + uncertain: true, wantCode: "libvirt_error", + }, + { + name: "system-result-unknown", cause: libvirt.Error{Code: libvirt.ERR_SYSTEM_ERROR}, + uncertain: true, wantCode: "libvirt_error", + }, + } { + t.Run(test.name, func(t *testing.T) { + err := mutationLibvirtError("create VM artifact", test.cause) + if got := operation.IsUncertain(err); got != test.uncertain { + t.Fatalf("uncertain = %v, want %v: %v", got, test.uncertain, err) + } + if got := errorPublicCode(err); got != test.wantCode { + t.Fatalf("public code = %q, want %q: %v", got, test.wantCode, err) + } + }) + } +} + +func TestCreateVMStageErrorsExposeStableSafeCodes(t *testing.T) { + stages := []struct { + stage createVMFailureStage + code string + }{ + {createVMTemplateLookupStage, "template_lookup_failed"}, + {createVMTemplateCapacityStage, "template_capacity_failed"}, + {createVMStorageCloneStage, "storage_clone_failed"}, + {createVMSeedCreateStage, "seed_create_failed"}, + {createVMSeedUploadStage, "seed_upload_failed"}, + {createVMNWFilterDefineStage, "nwfilter_define_failed"}, + {createVMDomainDefineStage, "domain_define_failed"}, + {createVMDomainAutostartStage, "domain_autostart_failed"}, + {createVMDomainStartStage, "domain_start_failed"}, + } + seen := make(map[string]struct{}, len(stages)) + for _, test := range stages { + t.Run(test.code, func(t *testing.T) { + cause := NewError(ErrInvalid, "internal_detail", "secret path /srv/private/image.qcow2", nil) + err := test.stage.wrap(cause) + if got := errorPublicCode(err); got != test.code { + t.Fatalf("public code = %q, want %q", got, test.code) + } + var public interface{ PublicMessage() string } + if !errors.As(err, &public) { + t.Fatalf("stage error has no public message: %v", err) + } + if got := public.PublicMessage(); got != test.stage.message { + t.Fatalf("public message = %q, want %q", got, test.stage.message) + } + if strings.Contains(err.Error(), "/srv/private") || strings.Contains(public.PublicMessage(), "/srv/private") { + t.Fatalf("stage error exposed its private cause: %v", err) + } + if !errors.Is(err, ErrInvalid) { + t.Fatalf("stage error lost backend classification: %v", err) + } + if _, duplicate := seen[test.code]; duplicate { + t.Fatalf("duplicate create stage code %q", test.code) + } + seen[test.code] = struct{}{} + }) + } +} + +func TestCreateVMStageErrorsPreserveArtifactUncertainty(t *testing.T) { + deterministic := createVMStorageCloneStage.wrap(deterministicArtifactCreateFailure( + "clone template volume", libvirt.Error{Code: libvirt.ERR_INVALID_ARG}, nil, false, + )) + if operation.IsUncertain(deterministic) || errorPublicCode(deterministic) != "storage_clone_failed" { + t.Fatalf("confirmed-absent clone failure = %v", deterministic) + } + + for _, test := range []struct { + name string + mutationErr error + inspectErr error + artifactFound bool + }{ + {name: "artifact-observed", mutationErr: libvirt.Error{Code: libvirt.ERR_INVALID_ARG}, artifactFound: true}, + {name: "absence-unknown", mutationErr: libvirt.Error{Code: libvirt.ERR_INVALID_ARG}, inspectErr: errors.New("inspection unavailable")}, + {name: "transport-result-unknown", mutationErr: libvirt.Error{Code: libvirt.ERR_RPC}}, + } { + t.Run(test.name, func(t *testing.T) { + err := createVMStorageCloneStage.wrap(deterministicArtifactCreateFailure( + "clone template volume", test.mutationErr, test.inspectErr, test.artifactFound, + )) + if !operation.IsUncertain(err) { + t.Fatalf("ambiguous create failure lost uncertainty: %v", err) + } + if got := errorPublicCode(err); got != "storage_clone_failed" { + t.Fatalf("uncertain public code = %q, want storage_clone_failed", got) + } + }) + } +} + +func TestDirPoolVolumePathRequiresDirectSafeFilename(t *testing.T) { + valid := `/var/lib/libvirt/images` + path, err := dirPoolVolumePath(valid, "vm-root.qcow2") + if err != nil || path != "/var/lib/libvirt/images/vm-root.qcow2" { + t.Fatalf("valid dir pool path = %q, %v", path, err) + } + for _, test := range []struct { + name string + document string + volume string + }{ + {name: "non-dir", document: `/mnt/images`, volume: "vm.qcow2"}, + {name: "relative-target", document: `images`, volume: "vm.qcow2"}, + {name: "root-target", document: `/`, volume: "vm.qcow2"}, + {name: "nested-name", document: valid, volume: "nested/vm.qcow2"}, + {name: "parent-name", document: valid, volume: "../vm.qcow2"}, + {name: "malformed-xml", document: `/var/lib/libvirt/images` + var calls []string + probe := storagePoolVolumeAbsenceProbe{ + refresh: func() error { + calls = append(calls, "refresh") + return nil + }, + lookup: func() (bool, error) { + calls = append(calls, "lookup") + return false, nil + }, + poolXML: func() (string, error) { + calls = append(calls, "xml") + return valid, nil + }, + lstat: func(path string) (os.FileInfo, error) { + calls = append(calls, "lstat:"+path) + return nil, os.ErrNotExist + }, + } + absent, err := proveDirPoolVolumeAbsent("vm-root.qcow2", probe) + if err != nil || !absent { + t.Fatalf("complete absence evidence = %v, %v", absent, err) + } + wantCalls := []string{"refresh", "lookup", "xml", "lstat:/var/lib/libvirt/images/vm-root.qcow2"} + if !reflect.DeepEqual(calls, wantCalls) { + t.Fatalf("absence evidence calls = %v, want %v", calls, wantCalls) + } + + t.Run("refresh-failure-stops-inspection", func(t *testing.T) { + refreshErr := errors.New("refresh failed") + lookupCalled := false + _, err := proveDirPoolVolumeAbsent("vm-root.qcow2", storagePoolVolumeAbsenceProbe{ + refresh: func() error { return refreshErr }, + lookup: func() (bool, error) { + lookupCalled = true + return false, nil + }, + poolXML: func() (string, error) { return valid, nil }, + lstat: os.Lstat, + }) + if !errors.Is(err, refreshErr) || lookupCalled { + t.Fatalf("refresh failure = %v, lookup called = %v", err, lookupCalled) + } + }) + + t.Run("refreshed-libvirt-object-is-present", func(t *testing.T) { + xmlCalled := false + absent, err := proveDirPoolVolumeAbsent("vm-root.qcow2", storagePoolVolumeAbsenceProbe{ + refresh: func() error { return nil }, + lookup: func() (bool, error) { return true, nil }, + poolXML: func() (string, error) { + xmlCalled = true + return valid, nil + }, + lstat: os.Lstat, + }) + if err != nil || absent || xmlCalled { + t.Fatalf("present libvirt object = %v, %v; xml called = %v", absent, err, xmlCalled) + } + }) + + t.Run("lookup-failure-is-not-absence", func(t *testing.T) { + lookupErr := errors.New("lookup failed") + absent, err := proveDirPoolVolumeAbsent("vm-root.qcow2", storagePoolVolumeAbsenceProbe{ + refresh: func() error { return nil }, + lookup: func() (bool, error) { return false, lookupErr }, + poolXML: func() (string, error) { return valid, nil }, + lstat: os.Lstat, + }) + if !errors.Is(err, lookupErr) || absent { + t.Fatalf("failed libvirt lookup = %v, %v", absent, err) + } + }) + + t.Run("pool-definition-failure-is-not-absence", func(t *testing.T) { + xmlErr := errors.New("pool XML unavailable") + absent, err := proveDirPoolVolumeAbsent("vm-root.qcow2", storagePoolVolumeAbsenceProbe{ + refresh: func() error { return nil }, + lookup: func() (bool, error) { return false, nil }, + poolXML: func() (string, error) { return "", xmlErr }, + lstat: os.Lstat, + }) + if !errors.Is(err, xmlErr) || absent { + t.Fatalf("failed pool definition read = %v, %v", absent, err) + } + }) + + t.Run("lookup-miss-with-file-is-not-absence", func(t *testing.T) { + absent, err := proveDirPoolVolumeAbsent("vm-root.qcow2", storagePoolVolumeAbsenceProbe{ + refresh: func() error { return nil }, + lookup: func() (bool, error) { return false, nil }, + poolXML: func() (string, error) { return valid, nil }, + lstat: func(string) (os.FileInfo, error) { return nil, nil }, + }) + if err != nil || absent { + t.Fatalf("unlisted on-disk volume was treated absent: %v, %v", absent, err) + } + }) + + for _, test := range []struct { + name string + poolXML string + lstat func(string) (os.FileInfo, error) + }{ + { + name: "unsupported-pool", poolXML: `/mnt/images`, + lstat: os.Lstat, + }, + { + name: "filesystem-inspection-failed", poolXML: valid, + lstat: func(string) (os.FileInfo, error) { return nil, os.ErrPermission }, + }, + } { + t.Run(test.name, func(t *testing.T) { + absent, err := proveDirPoolVolumeAbsent("vm-root.qcow2", storagePoolVolumeAbsenceProbe{ + refresh: func() error { return nil }, + lookup: func() (bool, error) { return false, nil }, + poolXML: func() (string, error) { return test.poolXML, nil }, + lstat: test.lstat, + }) + if err == nil || absent { + t.Fatalf("incomplete absence evidence = %v, %v", absent, err) + } + }) + } +} + +func TestCreateReconciliationUsesDomainMutationSerialization(t *testing.T) { + for _, action := range []string{ + "create-vm", "delete-vm", "reinstall-vm", "create-snapshot:key", "delete-snapshot:key", "restore-snapshot:key", + } { + if !reconciliationNeedsDomainMutationLock(action) { + t.Fatalf("reconciliation action %q is not serialized", action) + } + } + for _, action := range []string{"power-start", "create-snapshot", "list-vms"} { + if reconciliationNeedsDomainMutationLock(action) { + t.Fatalf("read-only or independently safe action %q was unexpectedly serialized", action) + } + } +} + func TestDeterministicVolumeCreateFailureRequiresReliableAbsence(t *testing.T) { cause := errors.New("clone rejected") if err := deterministicVolumeCreateFailure("clone", cause, nil, false); operation.IsUncertain(err) { diff --git a/agent/hypervisor/libvirt_snapshot_features.go b/agent/hypervisor/libvirt_snapshot_features.go index 6ec80bc7..a63ade8e 100644 --- a/agent/hypervisor/libvirt_snapshot_features.go +++ b/agent/hypervisor/libvirt_snapshot_features.go @@ -28,7 +28,7 @@ func snapshotRestoreVolumeName(uuid, operationID string) string { return "vrestore-" + compact + "-" + hex.EncodeToString(sum[:8]) + ".qcow2" } -func deterministicVolumeCreateFailure(action string, mutationErr, inspectErr error, artifactExists bool) error { +func deterministicArtifactCreateFailure(action string, mutationErr, inspectErr error, artifactExists bool) error { err := mutationLibvirtError(action, mutationErr) if inspectErr != nil || artifactExists { return operation.MarkUncertain(errors.Join(err, inspectErr)) @@ -36,6 +36,10 @@ func deterministicVolumeCreateFailure(action string, mutationErr, inspectErr err return err } +func deterministicVolumeCreateFailure(action string, mutationErr, inspectErr error, artifactExists bool) error { + return deterministicArtifactCreateFailure(action, mutationErr, inspectErr, artifactExists) +} + func validateSnapshotDeletePresence(metadataExists, volumeExists bool) error { if !metadataExists && !volumeExists { return NewError(ErrNotFound, "snapshot_not_found", "snapshot was not found", nil) diff --git a/agent/hypervisor/libvirt_storage_evidence.go b/agent/hypervisor/libvirt_storage_evidence.go new file mode 100644 index 00000000..7d7ca111 --- /dev/null +++ b/agent/hypervisor/libvirt_storage_evidence.go @@ -0,0 +1,109 @@ +//go:build libvirt + +package hypervisor + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "libvirt.org/go/libvirt" + "libvirt.org/go/libvirtxml" +) + +type storagePoolVolumeAbsenceProbe struct { + refresh func() error + lookup func() (bool, error) + poolXML func() (string, error) + lstat func(string) (os.FileInfo, error) +} + +// proveDirPoolVolumeAbsent requires independent agreement from libvirt's +// refreshed inventory and the dir pool filesystem. A single cache miss is not +// sufficient evidence after a volume-create call may have committed. +func proveDirPoolVolumeAbsent(volumeName string, probe storagePoolVolumeAbsenceProbe) (bool, error) { + if err := probe.refresh(); err != nil { + return false, err + } + present, err := probe.lookup() + if err != nil { + return false, err + } + if present { + return false, nil + } + document, err := probe.poolXML() + if err != nil { + return false, err + } + path, err := dirPoolVolumePath(document, volumeName) + if err != nil { + return false, err + } + if _, err := probe.lstat(path); err == nil { + return false, nil + } else if errors.Is(err, os.ErrNotExist) { + return true, nil + } else { + return false, err + } +} + +func dirPoolVolumePath(document, volumeName string) (string, error) { + if volumeName == "" || volumeName == "." || volumeName == ".." || filepath.Base(volumeName) != volumeName { + return "", errors.New("storage volume name is not a safe filename") + } + var definition libvirtxml.StoragePool + if err := definition.Unmarshal(document); err != nil { + return "", fmt.Errorf("parse storage pool XML: %w", err) + } + if definition.Type != "dir" || definition.Target == nil { + return "", errors.New("storage pool is not a supported dir pool") + } + target := filepath.Clean(strings.TrimSpace(definition.Target.Path)) + if !filepath.IsAbs(target) || target == string(filepath.Separator) { + return "", errors.New("storage dir pool target is invalid") + } + path := filepath.Join(target, volumeName) + if filepath.Dir(path) != target { + return "", errors.New("storage volume path escapes the pool target") + } + return path, nil +} + +func (l *Libvirt) dirPoolVolumeAbsent(pool *libvirt.StoragePool, volumeName string) (bool, error) { + absent, err := proveDirPoolVolumeAbsent(volumeName, storagePoolVolumeAbsenceProbe{ + refresh: func() error { + if err := pool.Refresh(0); err != nil { + return translateLibvirtError("refresh storage pool for absence evidence", err) + } + return nil + }, + lookup: func() (bool, error) { + volume, err := pool.LookupStorageVolByName(volumeName) + if err == nil { + _ = volume.Free() + return true, nil + } + if isNoStorageVolume(err) { + return false, nil + } + return false, translateLibvirtError("lookup storage volume for absence evidence", err) + }, + poolXML: func() (string, error) { + document, err := pool.GetXMLDesc(0) + if err != nil { + return "", translateLibvirtError("read storage pool definition for absence evidence", err) + } + return document, nil + }, + lstat: os.Lstat, + }) + if err != nil { + return false, NewError(ErrUnavailable, "storage_absence_unconfirmed", + "storage volume absence could not be confirmed", err) + } + return absent, nil +} diff --git a/agent/operation/journal.go b/agent/operation/journal.go index dcbbcfa2..3d0714fe 100644 --- a/agent/operation/journal.go +++ b/agent/operation/journal.go @@ -46,6 +46,7 @@ var ( hexDigestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`) networkSourcePattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`) + causeCodePattern = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`) metadataBucket = []byte("metadata") operationsBucket = []byte("operations") @@ -99,6 +100,7 @@ type Record struct { State State `json:"status"` Result json.RawMessage `json:"result,omitempty"` Error *PublicError `json:"error,omitempty"` + CauseCode string `json:"cause_code,omitempty"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` Tombstone bool `json:"tombstone,omitempty"` @@ -786,12 +788,13 @@ func (j *Journal) finish(operationID string, result json.RawMessage, callErr err message = public.PublicMessage() } } - return j.finishWithPublicError(operationID, code, message) + return j.finishWithCause(operationID, code, message, nil, code) } return j.updateRecord(operationID, func(record *Record) { record.State = StateSucceeded record.Result = append(json.RawMessage(nil), result...) record.Error = nil + record.CauseCode = "" record.UpdatedAt = j.currentTime() }) } @@ -812,10 +815,15 @@ func (j *Journal) finishWithPublicError(operationID, code, message string) (Reco } func (j *Journal) finishWithPublicErrorAndResult(operationID, code, message string, result json.RawMessage) (Record, error) { + return j.finishWithCause(operationID, code, message, result, "") +} + +func (j *Journal) finishWithCause(operationID, code, message string, result json.RawMessage, causeCode string) (Record, error) { return j.updateRecord(operationID, func(record *Record) { record.State = StateFailed record.Result = append(json.RawMessage(nil), result...) record.Error = &PublicError{Code: code, Message: message} + preserveCauseCode(record, causeCode) record.UpdatedAt = j.currentTime() }) } @@ -848,16 +856,53 @@ func notDispatchedEvidence(action string) json.RawMessage { func (j *Journal) markUncertain(operationID string, cause error) (Record, error) { return j.updateRecord(operationID, func(record *Record) { message := "operation crossed the dispatch boundary and requires reconciliation" - if cause != nil { - message += ": " + cause.Error() + if summary := publicMessageFromError(cause); summary != "" { + message += ": " + summary } record.State = StateUncertain record.Result = nil record.Error = &PublicError{Code: "result_uncertain", Message: message} + preserveCauseCode(record, publicCodeFromError(cause)) record.UpdatedAt = j.currentTime() }) } +func preserveCauseCode(record *Record, code string) { + if record.CauseCode == "" && validCauseCode(code) { + record.CauseCode = code + } +} + +func validCauseCode(code string) bool { + return len(code) <= 64 && causeCodePattern.MatchString(code) +} + +func publicCodeFromError(err error) string { + if err == nil { + return "" + } + var public interface{ PublicCode() string } + if !errors.As(err, &public) { + return "" + } + code := public.PublicCode() + if !validCauseCode(code) { + return "" + } + return code +} + +func publicMessageFromError(err error) string { + if err == nil { + return "" + } + var public interface{ PublicMessage() string } + if !errors.As(err, &public) { + return "" + } + return public.PublicMessage() +} + func (j *Journal) updateRecord(operationID string, mutate func(*Record)) (Record, error) { var result Record err := j.db.Update(func(tx *bolt.Tx) error { @@ -1037,6 +1082,9 @@ func validateRecord(record Record) error { default: return fmt.Errorf("invalid state %q", record.State) } + if record.CauseCode != "" && !validCauseCode(record.CauseCode) { + return errors.New("invalid operation cause_code") + } return nil } diff --git a/agent/operation/journal_test.go b/agent/operation/journal_test.go index b26d707d..5d62becc 100644 --- a/agent/operation/journal_test.go +++ b/agent/operation/journal_test.go @@ -17,6 +17,31 @@ import ( bolt "go.etcd.io/bbolt" ) +type testPublicError struct { + code string + message string + err error +} + +func (e *testPublicError) Error() string { return e.err.Error() } +func (e *testPublicError) Unwrap() error { return e.err } +func (e *testPublicError) PublicCode() string { return e.code } +func (e *testPublicError) PublicMessage() string { return e.message } + +func TestCauseCodeValidationUsesCanonicalLowerSnakeCase(t *testing.T) { + t.Parallel() + for _, code := range []string{"storage_clone_failed", "libvirt_error", "q35_uefi_unavailable"} { + if !validCauseCode(code) { + t.Fatalf("valid cause code rejected: %q", code) + } + } + for _, code := range []string{"", "Storage_clone_failed", "storage__clone", "storage_clone_", "storage/clone", strings.Repeat("a", 65)} { + if validCauseCode(code) { + t.Fatalf("invalid cause code accepted: %q", code) + } + } +} + func testJournal(t *testing.T) *Journal { t.Helper() j, err := Open(filepath.Join(t.TempDir(), "operations.db")) @@ -175,7 +200,7 @@ func TestFailedCreateReconciliationPreservesOnlyConfirmedAbsenceEvidence(t *test Fingerprint: Fingerprint("POST", "/v1/vms", []byte(`{}`)), Destructive: true, } if _, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { - return nil, MarkUncertain(errors.New("connection lost")) + return nil, MarkUncertain(&testPublicError{code: "storage_clone_failed", err: errors.New("connection lost")}) }); !IsUncertain(err) { t.Fatalf("execute error = %v, want uncertain", err) } @@ -188,11 +213,43 @@ func TestFailedCreateReconciliationPreservesOnlyConfirmedAbsenceEvidence(t *test if err != nil || record.State != StateFailed || record.Error == nil || record.Error.Code != "creation_absent" { t.Fatalf("reconciled record = %#v err=%v", record, err) } + if record.CauseCode != "storage_clone_failed" { + t.Fatalf("reconciled cause_code = %q, want storage_clone_failed", record.CauseCode) + } if string(record.Result) != `{"creation_absent":true,"managed_artifacts_absent":true}` { t.Fatalf("failure evidence = %s", record.Result) } } +func TestUncertainRecordUsesOnlyPublicMessage(t *testing.T) { + j := testJournal(t) + spec := Spec{ + OperationID: "operation-safe-diagnostic", ResourceID: "vm-safe", Action: "create-vm", + Fingerprint: Fingerprint("POST", "/v1/vms", []byte(`{}`)), Destructive: true, + } + record, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { + return nil, MarkUncertain(errors.Join( + &testPublicError{ + code: "storage_clone_failed", message: "template volume could not be cloned", + err: errors.New("libvirt private detail"), + }, + errors.New("/srv/private/template.qcow2 bearer-secret"), + )) + }) + if !IsUncertain(err) || record.State != StateUncertain || record.Error == nil { + t.Fatalf("uncertain operation = %#v err=%v", record, err) + } + if record.CauseCode != "storage_clone_failed" { + t.Fatalf("cause_code = %q", record.CauseCode) + } + if !strings.Contains(record.Error.Message, "template volume could not be cloned") || + strings.Contains(record.Error.Message, "/srv/private") || + strings.Contains(record.Error.Message, "bearer-secret") || + strings.Contains(record.Error.Message, "libvirt private detail") { + t.Fatalf("uncertain public message was not sanitized: %q", record.Error.Message) + } +} + func TestTerminalFailedCreateCanBeReconciledWithoutReplayingCreate(t *testing.T) { j := testJournal(t) spec := Spec{ @@ -202,7 +259,7 @@ func TestTerminalFailedCreateCanBeReconciledWithoutReplayingCreate(t *testing.T) createCalls := 0 record, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { createCalls++ - return nil, errors.New("network selector is not configured") + return nil, &testPublicError{code: "network_selector_invalid", err: errors.New("network selector is not configured")} }) if err == nil || record.State != StateFailed || createCalls != 1 { t.Fatalf("initial failed create = %#v calls=%d err=%v", record, createCalls, err) @@ -222,6 +279,9 @@ func TestTerminalFailedCreateCanBeReconciledWithoutReplayingCreate(t *testing.T) if err != nil || reconcileCalls != 1 || reconciled.State != StateFailed || reconciled.Error == nil || reconciled.Error.Code != "creation_absent" { t.Fatalf("failed create reconcile = %#v calls=%d err=%v", reconciled, reconcileCalls, err) } + if reconciled.CauseCode != "network_selector_invalid" { + t.Fatalf("failed create cause_code = %q, want network_selector_invalid", reconciled.CauseCode) + } if string(reconciled.Result) != `{"creation_absent":true,"managed_artifacts_absent":true}` { t.Fatalf("absence evidence = %s", reconciled.Result) } diff --git a/docs/ADMIN_OPERATIONS.md b/docs/ADMIN_OPERATIONS.md index 19a4c454..c373a922 100644 --- a/docs/ADMIN_OPERATIONS.md +++ b/docs/ADMIN_OPERATIONS.md @@ -10,6 +10,7 @@ - 默认“需要关注”:失败、待核对、已可调度超过 5 分钟且无有效租约的排队任务、执行租约已过期的运行中任务。未来的重试等待和无租约的正常核对轮次不会仅因等待而标为租约过期。 - 可按任务状态、类型、宿主机、任务编号、操作标识、实例名称或 UUID 筛选;每页 20/50/100 条。摘要统计跟随当前筛选。 - 详情区分操作人和实例所属用户,展示调度时间、尝试次数、脱敏错误和关联入口。实例已经删除或关联丢失时仍保留任务记录,不猜测所属用户。 +- Agent 返回的稳定 `cause_code` 仅在管理员任务 DTO 中映射为 `agent_cause_code`,用于定位最初根因。该字段不进入普通用户 DTO,也不替换面板公开 `error_code`。 列表、详情和健康检查保持数据库快照读取;超级管理员可以对快照创建/恢复/删除、实例删除及到期清理任务使用“中止任务”按钮。中止只在数据库事务中将未结束任务标记为 `cancelled`、清除执行租约并阻止后续 worker 领取,不删除任务、不退款,也不向 Agent 发送补偿请求。已经派发到 Agent 的操作不会被假定已回滚,快照/删除关联状态会保守保留为待核对,`expiry_delete` 会进入 `purge_failed` 等待人工核查。租约过期不等于操作失败,不应据此手动重放破坏性操作。 diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md index 6981a668..41f6d2b5 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -79,6 +79,13 @@ RAW_X_VIRT_ACTOR | 501 | capability 未实现,禁止静默降级 | | 503 | libvirt/本地依赖暂不可用;变更是否可重试仍取决于派发边界 | +持久操作响应包含 `operation_id`、`status`、`replayed`、`retryable`,并可按状态包含 +`result`、`error` 和可选 `cause_code`。已越过派发边界的错误 envelope 在 +`error.operation` 中携带同一持久记录,其可选 `cause_code` 规则相同。 +`cause_code` 是 1~64 字符的稳定 lower_snake_case 诊断标识;只保留首个有效根因, +后续 `uncertain`/`reconcile` 不得覆盖,操作最终成功时必须清除。它只用于管理员诊断, +不是业务分支或用户展示的公开错误码。 + 只有在请求明确尚未进入持久操作日志时,Gateway/Agent 才能在上述严格 `error` 对象中增加 `"dispatch_state":"not_dispatched"`。面板只接受顶层 仅含 `error`,且该对象恰好由 `code`、`message`、`retryable`、 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 937671c8..27e2356c 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -244,3 +244,19 @@ go test -race: Gateway 通过;Agent 沿用同一 source commit 的前置 race artifact inspection: 两个文件均为 ELF 64-bit x86-64,未嵌入本机路径或部署端点 known skips or risks: Agent 使用 libvirt_dlopen,宿主机运行时仍必须提供 libvirt.so.0;新产物未在本轮重复执行真实 VM 破坏性生命周期操作 ``` + +### 2026-10-16 创建失败根因保留与阶段诊断验收 + +```text +commit: 本记录所在 go 分支源码提交(基线 93781a2) +Go version / libvirt version / PHP version / MariaDB version: Go 1.27.1 / 本机 libvirt 12.8.0 / PHP 8.5.11 / MariaDB 未在本机运行 +go vet: Agent 默认及 libvirt+libvirt_dlopen 均通过 +go test: Agent 默认及 libvirt+libvirt_dlopen、Gateway 均通过;Gateway Agent 包连续 20 次通过;Agent go mod verify 通过 +go test -race: Agent libvirt+libvirt_dlopen 与 Gateway 均通过 +PHP tests: 119 个测试文件通过,app/config/public 下 272 个 PHP 文件逐文件 lint 通过;SourceSyntax 独立通过;仅输出既有测试 warning 与第三方依赖 deprecation,退出码为 0 +Node tests: 4 个行为测试及 admin-operations.js 语法检查通过 +libvirt XML: 当前 create 请求形态生成的 q35/UEFI、Secure Boot 关闭、br0 bridge 域 XML 通过 virt-xml-validate domain schema +read-only host capability check: 面板快照确认 Agent、public->br0、/29 地址池及模板副本均就绪;本轮桌面 SSH 自动化两次超时,未取得宿主机原始 libvirt 日志 +authorized host mutation test: 未重新提交真实付费创建;现有失败任务已完成退款且受管工件确认不存在 +known skips or risks: 旧 Agent 将最初错误覆盖为 creation_absent,历史任务无法恢复唯一根因;部署本提交后,新失败会保留首个 Agent cause_code 并区分模板、克隆、seed、NWFilter、domain define/autostart/start 阶段;卷缺失退款证据要求 dir pool 的刷新清单与目标文件 ENOENT 同时成立,其他池型保守保持 uncertain;随后须用一次受控创建完成宿主机实测 +``` diff --git a/gateway/agent/registry_test.go b/gateway/agent/registry_test.go index c7ea9244..e7ef78e6 100644 --- a/gateway/agent/registry_test.go +++ b/gateway/agent/registry_test.go @@ -95,7 +95,7 @@ func newTestRegistry(t *testing.T) (*Registry, *httptest.Server, []byte, <-chan return registry, server, shared, consoleReturned } -func dialControl(t *testing.T, serverURL, agentID string) *websocket.Conn { +func dialControl(t *testing.T, registry *Registry, serverURL, agentID string) *websocket.Conn { t.Helper() headers := http.Header{ "X-Virt-Agent-ID": []string{agentID}, @@ -110,13 +110,26 @@ func dialControl(t *testing.T, serverURL, agentID string) *websocket.Conn { if err != nil { t.Fatalf("dial Agent control: %v", err) } + // websocket.Dial returns as soon as the client receives 101. The server + // publishes the accepted session immediately afterwards, so wait for that + // publication before a test tries to dispatch through the registry. + deadline := time.NewTimer(time.Second) + defer deadline.Stop() + for registry.get(agentID) == nil { + select { + case <-deadline.C: + _ = conn.CloseNow() + t.Fatal("Agent control session was not registered after handshake") + case <-time.After(time.Millisecond): + } + } t.Cleanup(func() { _ = conn.CloseNow() }) return conn } func TestRegistryDispatchesAuthenticatedRequestAndReturnsExactResponse(t *testing.T) { - _, server, shared, _ := newTestRegistry(t) - control := dialControl(t, server.URL, "12") + registry, server, shared, _ := newTestRegistry(t) + control := dialControl(t, registry, server.URL, "12") agentDone := make(chan error, 1) go func() { @@ -333,7 +346,7 @@ func TestRegistryDrainRejectsNewDispatchBeforeAgentWrite(t *testing.T) { func TestRegistryDrainWaitsForAdmittedDispatch(t *testing.T) { registry, server, _, _ := newTestRegistry(t) - control := dialControl(t, server.URL, "47") + control := dialControl(t, registry, server.URL, "47") result := make(chan error, 1) go func() { _, err := registry.dispatch(context.Background(), "47", wireRequest{ @@ -342,7 +355,9 @@ func TestRegistryDrainWaitsForAdmittedDispatch(t *testing.T) { }) result <- err }() - messageType, raw, err := control.Read(t.Context()) + readCtx, cancelRead := context.WithTimeout(t.Context(), time.Second) + messageType, raw, err := control.Read(readCtx) + cancelRead() if err != nil || messageType != websocket.MessageText { t.Fatalf("read admitted dispatch: type=%v err=%v", messageType, err) } @@ -362,8 +377,13 @@ func TestRegistryDrainWaitsForAdmittedDispatch(t *testing.T) { if err := control.Write(t.Context(), websocket.MessageText, encoded); err != nil { t.Fatal(err) } - if err := <-result; err != nil { - t.Fatal(err) + select { + case err := <-result: + if err != nil { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("admitted dispatch did not finish after Agent response") } if err := registry.Wait(t.Context()); err != nil { t.Fatal(err) @@ -372,7 +392,7 @@ func TestRegistryDrainWaitsForAdmittedDispatch(t *testing.T) { func TestRegistryTimeoutAfterAgentWriteRemainsAmbiguous(t *testing.T) { registry, server, _, _ := newTestRegistry(t) - control := dialControl(t, server.URL, "48") + control := dialControl(t, registry, server.URL, "48") ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond) defer cancel() result := make(chan error, 1) @@ -394,7 +414,7 @@ func TestRegistryTimeoutAfterAgentWriteRemainsAmbiguous(t *testing.T) { func TestRegistryRevokesConnectedAgentBeforeOrdinaryDispatch(t *testing.T) { registry, server, _, _ := newTestRegistry(t) - control := dialControl(t, server.URL, "12") + control := dialControl(t, registry, server.URL, "12") authenticator := registry.authenticator.(*allowConnectionAuthenticator) authenticator.reject(errors.New("Agent secret was rotated")) @@ -418,7 +438,7 @@ func TestRegistryRevokesConnectedAgentBeforeOrdinaryDispatch(t *testing.T) { func TestRegistryRevokesConnectedAgentBeforeOpeningConsole(t *testing.T) { registry, server, _, _ := newTestRegistry(t) - control := dialControl(t, server.URL, "44") + control := dialControl(t, registry, server.URL, "44") authenticator := registry.authenticator.(*allowConnectionAuthenticator) authenticator.reject(errors.New("Agent was disabled")) @@ -463,7 +483,7 @@ func assertInternalError(t *testing.T, response *http.Response, status int, code func TestRegistryPairsOneUseReverseConsoleWithConnectedAgent(t *testing.T) { registry, server, _, consoleReturned := newTestRegistry(t) - control := dialControl(t, server.URL, "44") + control := dialControl(t, registry, server.URL, "44") opened := make(chan *websocket.Conn, 1) errors := make(chan error, 1) @@ -542,7 +562,7 @@ func TestRegistryPairsOneUseReverseConsoleWithConnectedAgent(t *testing.T) { func TestRegistryReturnsConsoleRejectionWithoutWaitingForReverseDial(t *testing.T) { registry, server, _, _ := newTestRegistry(t) - control := dialControl(t, server.URL, "45") + control := dialControl(t, registry, server.URL, "45") result := make(chan error, 1) go func() { diff --git a/web/app/Services/Cloud/CloudAdminOperationsService.php b/web/app/Services/Cloud/CloudAdminOperationsService.php index 9d50c445..0626078c 100644 --- a/web/app/Services/Cloud/CloudAdminOperationsService.php +++ b/web/app/Services/Cloud/CloudAdminOperationsService.php @@ -297,7 +297,10 @@ final class CloudAdminOperationsService . 'COALESCE(operation_instance.uuid, fallback_instance.uuid) AS instance_uuid, ' . 'COALESCE(operation_instance.status, fallback_instance.status) AS instance_status, ' . "CASE WHEN JSON_VALID(cloud_jobs.result_json) THEN " - . "JSON_EXTRACT(cloud_jobs.result_json, '$.phase') ELSE NULL END AS phase_json"); + . "JSON_EXTRACT(cloud_jobs.result_json, '$.phase') ELSE NULL END AS phase_json, " + . "CASE WHEN JSON_VALID(cloud_jobs.result_json) THEN " + . "JSON_EXTRACT(cloud_jobs.result_json, '$.cause_code') " + . "ELSE NULL END AS agent_cause_code_json"); } private static function queuedSql(): string @@ -366,6 +369,14 @@ final class CloudAdminOperationsService || in_array($phase, ['null', 'true', 'false'], true))) { $phase = null; } + $agentCauseCode = $job->agent_cause_code_json; + // MySQL returns a quoted JSON scalar; SQLite returns plain text. + if (is_string($agentCauseCode) && str_starts_with($agentCauseCode, '"')) { + $agentCauseCode = json_decode($agentCauseCode, true); + } + $agentCauseCode = CloudOperationErrorCatalog::agentCauseCode( + $agentCauseCode + ); $uuid = (string) ($job->instance_uuid ?? ''); $validUuid = preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $uuid) === 1; $attentionLabels = ['failed' => '任务已失败', 'uncertain' => '等待核对结果', @@ -384,6 +395,7 @@ final class CloudAdminOperationsService 'cancel_reason' => $cancelReason, 'attempts' => max(0, (int) $job->attempts), 'error_code' => CloudOperationErrorCatalog::publicCode($job->error_code), + 'agent_cause_code' => $agentCauseCode, 'error' => CloudOperationErrorCatalog::adminSummary( (string) $job->kind, $status, $job->error_code, $job->linked_order_id !== null, $action diff --git a/web/app/Services/Cloud/CloudAgentClient.php b/web/app/Services/Cloud/CloudAgentClient.php index cfa9209d..b45a06c8 100644 --- a/web/app/Services/Cloud/CloudAgentClient.php +++ b/web/app/Services/Cloud/CloudAgentClient.php @@ -264,6 +264,12 @@ final class CloudAgentClient || !is_bool($payload['retryable'] ?? null)) { return null; } + $causeCode = self::operationCauseCode($payload['cause_code'] ?? null); + if ($causeCode === null) { + unset($payload['cause_code']); + } else { + $payload['cause_code'] = $causeCode; + } return $payload; } @@ -294,6 +300,10 @@ final class CloudAgentClient if (array_key_exists('result', $record)) { $operation['result'] = $record['result']; } + $causeCode = self::operationCauseCode($record['cause_code'] ?? null); + if ($causeCode !== null) { + $operation['cause_code'] = $causeCode; + } if (is_array($record['error'] ?? null)) { $operation['error'] = $record['error']; } elseif (is_string($error['code'] ?? null)) { @@ -302,6 +312,14 @@ final class CloudAgentClient return $operation; } + private static function operationCauseCode(mixed $value): ?string + { + return is_string($value) + && strlen($value) <= 64 + && preg_match('/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/D', $value) === 1 + ? $value : null; + } + private static function responseError(int $status, array $payload): CloudAgentError { $error = is_array($payload['error'] ?? null) ? $payload['error'] : []; diff --git a/web/app/Services/Cloud/CloudOperationErrorCatalog.php b/web/app/Services/Cloud/CloudOperationErrorCatalog.php index 02f9354c..f70bb23d 100644 --- a/web/app/Services/Cloud/CloudOperationErrorCatalog.php +++ b/web/app/Services/Cloud/CloudOperationErrorCatalog.php @@ -327,11 +327,28 @@ final class CloudOperationErrorCatalog return array_key_exists($value, self::CODE_LABELS) ? $value : null; } + /** + * Validate the Agent's durable root-cause identifier. + * + * This code is administrator-only diagnostic metadata, not a tenant + * message. Accept the canonical lower-case snake_case wire format only + * so result_json cannot become a store for free-form host data. + */ + public static function agentCauseCode($value): ?string + { + if (!is_string($value) || strlen($value) > 64 + || preg_match('/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/D', $value) !== 1) { + return null; + } + return $value; + } + /** * Sanitize an operation result before it is persisted in result_json. - * Error-like fields are represented by the durable error_code instead; - * retaining them here would leave a second raw Agent-error store that a - * future DTO could accidentally expose. + * Error-like fields are represented by the durable error_code instead. + * The one exception is the Agent's strictly validated cause_code, which + * is retained for the dedicated administrator operations DTO and removed + * again at every ordinary presentation boundary. */ public static function workerResult(array $value): array { @@ -478,7 +495,7 @@ final class CloudOperationErrorCatalog private static function sanitizeResult(array $value, bool $administrator, ?string $kind, ?string $status, bool $hasOrder, ?string $action, - bool $persist): array + bool $persist, bool $nested = false): array { $value = CloudInput::safeResult($value); if (array_is_list($value)) { @@ -490,6 +507,14 @@ final class CloudOperationErrorCatalog if ($name === '' || in_array($name, self::FORBIDDEN_RESULT_KEYS, true)) { continue; } + if ($name === 'cause_code') { + $causeCode = !$nested && $persist + ? self::agentCauseCode($item) : null; + if ($causeCode !== null) { + $result[$name] = $causeCode; + } + continue; + } if (self::isDiagnosticKey($name)) { if ($persist || !$administrator) { continue; @@ -523,7 +548,7 @@ final class CloudOperationErrorCatalog if ($name === 'vm') { if (is_array($item) && !array_is_list($item)) { $result[$name] = self::sanitizeResult($item, $administrator, - $kind, $status, $hasOrder, $action, $persist); + $kind, $status, $hasOrder, $action, $persist, true); } continue; } diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 01c4fd90..403fba44 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -563,6 +563,18 @@ final class CloudWorkerService } $safe = is_array($result) ? CloudOperationErrorCatalog::workerResult($result) : null; + $causeCode = CloudOperationErrorCatalog::agentCauseCode( + $operation['cause_code'] ?? null + ); + if ($causeCode !== null) { + $durableResult = is_array($result) && !array_is_list($result) + ? $result : []; + // Keep the stable cause beside the sanitized operation + // evidence. It is never copied into the public error_code or + // ordinary user DTOs. + $durableResult['cause_code'] = $causeCode; + $safe = CloudOperationErrorCatalog::workerResult($durableResult); + } CloudSnapshotService::finishJobLocked($job, $status, $result, $payload); CloudSnapshotService::finishInstanceDeleteLocked($job, $status); CloudFirewallService::finishJobLocked( @@ -1116,6 +1128,14 @@ final class CloudWorkerService private static function normalizeAgentOperation(array $operation): array { + $causeCode = CloudOperationErrorCatalog::agentCauseCode( + $operation['cause_code'] ?? null + ); + if ($causeCode === null) { + unset($operation['cause_code']); + } else { + $operation['cause_code'] = $causeCode; + } $error = $operation['error'] ?? null; if (is_array($error) && is_string($error['code'] ?? null) && preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $error['code']) === 1) { diff --git a/web/public/cloud/admin-operations.js b/web/public/cloud/admin-operations.js index 39b5f6e9..be89a550 100644 --- a/web/public/cloud/admin-operations.js +++ b/web/public/cloud/admin-operations.js @@ -312,6 +312,7 @@ function renderDetail(payload) { body.replaceChildren(infoList([ ['任务状态', text(job.display?.status)], ['关注原因', text(job.display?.attention, '当前无异常标记')], ['操作标识', job.operation_id], ['处理阶段', job.phase], ['尝试次数', job.attempts], + ['Agent 原始故障码', job.agent_cause_code], ['操作人', `${text(job.actor_name)}${job.actor_id ? ` #${job.actor_id}` : ''}`], ['实例所属用户', job.owner_id ? `${text(job.owner_name)} #${job.owner_id}` : '未关联或无法确认'], ['宿主机', `${text(job.host_name)}${job.host_id ? ` #${job.host_id}` : ''}`], ['地区', job.region], diff --git a/web/tests/CloudAdminOperationsServiceTest.php b/web/tests/CloudAdminOperationsServiceTest.php index fafbebd1..8d7876c9 100644 --- a/web/tests/CloudAdminOperationsServiceTest.php +++ b/web/tests/CloudAdminOperationsServiceTest.php @@ -142,7 +142,7 @@ namespace { }; for ($id = 1; $id <= 205; $id++) { $insertJob($id); } $insertJob(206, ['status' => 'failed', 'kind' => 'reinstall', 'error_code' => 'password=never-expose-password token=never-expose-token']); - $insertJob(207, ['status' => 'uncertain', 'kind' => 'rescue', 'result_json' => '{"phase":"Bearer never-expose-bearer","private_key":"forbidden-result-key"}']); + $insertJob(207, ['status' => 'uncertain', 'kind' => 'rescue', 'result_json' => '{"phase":"Bearer never-expose-bearer","private_key":"forbidden-result-key","cause_code":"bad/path"}']); $insertJob(208, ['status' => 'queued', 'available_at' => $now - 301, 'order_id' => 100]); $insertJob(209, ['status' => 'queued', 'available_at' => $now - 290]); $insertJob(210, ['status' => 'queued', 'available_at' => $now - 600, 'lease_until' => $now + 50]); @@ -151,7 +151,8 @@ namespace { $insertJob(212, ['status' => 'running', 'lease_until' => $now + 50]); $insertJob(213, ['status' => 'running', 'lease_until' => 0]); $insertJob(214, ['status' => 'queued', 'available_at' => $now + 600]); - $insertJob(215, ['status' => 'uncertain', 'kind' => 'create', 'order_id' => 100, 'instance_id' => null]); + $insertJob(215, ['status' => 'uncertain', 'kind' => 'create', 'order_id' => 100, + 'instance_id' => null, 'result_json' => '{"phase":"等待核对结果","cause_code":"storage_clone_failed","message":"/srv/private/template.qcow2"}']); $insertJob(216, ['status' => 'failed', 'order_id' => 200, 'instance_id' => 10]); $insertJob(217, ['status' => 'failed', 'order_id' => 100, 'instance_id' => 20]); $insertJob(218, ['status' => 'failed', 'order_id' => 300, 'instance_id' => null]); @@ -205,7 +206,11 @@ namespace { && $detail['job']['links']['instance'] === '/admin/cloud/instances?q=11111111-1111-4111-8111-111111111110', 'Administrator actor was incorrectly treated as owner or UUID link was inexact.'); $fallback = Operations::detail($admin, '215')['job']; - $assert($fallback['instance_id'] === '10' && $fallback['owner_id'] === '1', 'Verified creation-order fallback missing.'); + $assert($fallback['instance_id'] === '10' && $fallback['owner_id'] === '1' + && ($fallback['agent_cause_code'] ?? null) === 'storage_clone_failed', + 'Verified creation-order fallback or stable Agent cause code missing.'); + $assert((Operations::detail($admin, '207')['job']['agent_cause_code'] ?? null) === null, + 'Malformed Agent cause code reached the administrator operations DTO.'); foreach (['216' => '1', '217' => '2'] as $id => $owner) { $item = Operations::detail($admin, (string) $id)['job']; $assert($item['owner_id'] === $owner && $item['order_id'] === null && $item['links']['billing'] === null, @@ -222,7 +227,7 @@ namespace { $assert(Operations::detail($admin, '222')['job']['instance_id'] === null, 'Cross-host instance attached to an unrelated job.'); $encoded = json_encode([$page, $detail, Operations::detail($admin, '207')]); - foreach (['forbidden-', 'never-expose-', 'sealed_payload', 'lease_token', 'sealed_credential', 'result_json'] as $secret) { + foreach (['forbidden-', 'never-expose-', '/srv/private', 'sealed_payload', 'lease_token', 'sealed_credential', 'result_json'] as $secret) { $assert(!str_contains($encoded, $secret), 'Response exposed secret/unsafe field: ' . $secret); } AdminPermission::$superAdmin = false; diff --git a/web/tests/CloudAgentProtocolTest.php b/web/tests/CloudAgentProtocolTest.php index 084d7415..bc2fd318 100644 --- a/web/tests/CloudAgentProtocolTest.php +++ b/web/tests/CloudAgentProtocolTest.php @@ -169,6 +169,30 @@ $handler = new MockHandler([ 'dispatch_state' => 'not_dispatched', 'unexpected' => true, ]], JSON_THROW_ON_ERROR)), + new Response(409, ['Content-Type' => 'application/json'], + json_encode(['error' => [ + 'code' => 'operation_failed', + 'message' => 'private upstream detail', + 'retryable' => false, + 'operation' => [ + 'operation_id' => 'operation_12345678', + 'status' => 'failed', + 'cause_code' => 'storage_clone_failed', + 'error' => ['code' => 'creation_absent'], + ], + ]], JSON_THROW_ON_ERROR)), + new Response(409, ['Content-Type' => 'application/json'], + json_encode(['error' => [ + 'code' => 'operation_failed', + 'message' => 'private upstream detail', + 'retryable' => false, + 'operation' => [ + 'operation_id' => 'operation_12345678', + 'status' => 'failed', + 'cause_code' => 'StorageCloneFailed', + 'error' => ['code' => 'creation_absent'], + ], + ]], JSON_THROW_ON_ERROR)), ]); $stack = HandlerStack::create($handler); $stack->push(Middleware::history($history)); @@ -289,5 +313,17 @@ foreach (['missing marker', 'unexpected field'] as $case) { "A {$case} envelope was accepted as definitive no-journal proof."); } } +$journalFailure = $client->request('POST', '/v1/vms', $actor, + ['operation_id' => 'operation_12345678']); +$assert(($journalFailure['status'] ?? null) === 'failed' + && ($journalFailure['cause_code'] ?? null) === 'storage_clone_failed' + && ($journalFailure['error']['code'] ?? null) === 'creation_absent' + && !isset($journalFailure['message']), + 'A valid durable Agent cause code was lost or free-form detail escaped its envelope.'); +$malformedCause = $client->request('POST', '/v1/vms', $actor, + ['operation_id' => 'operation_12345678']); +$assert(($malformedCause['status'] ?? null) === 'failed' + && !isset($malformedCause['cause_code']), + 'A malformed durable Agent cause code crossed the PHP trust boundary.'); echo "Agent outbound gateway and nested HMAC protocol contract passed.\n"; diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index 25e59df0..66518358 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -744,6 +744,34 @@ namespace { && $poweroffBody === ['action' => 'destroy'], 'Panel poweroff was not translated exactly once at the Agent wire boundary.'); + // Keep one bounded Agent cause for administrator diagnosis while the + // public job contract continues to expose only the panel-owned error. + $diagnosticJob = CloudJobService::enqueue( + $instance, $actor, 'action', 'POST', '/actions', ['action' => 'reboot'] + ); + $mock->append(new Response(200, [], json_encode([ + 'operation_id' => $diagnosticJob->operation_id, + 'status' => 'failed', + 'cause_code' => 'domain_start_failed', + 'error' => [ + 'code' => 'libvirt_error', + 'message' => 'private path /srv/libvirt/domain.xml', + ], + 'result' => ['state' => 'stopped'], + ]))); + $worker->tick(); + $diagnosticRow = CloudJob::find($diagnosticJob->id); + $diagnosticResult = json_decode((string) $diagnosticRow->result_json, + true, flags: JSON_THROW_ON_ERROR); + $publicDiagnostic = CloudJobService::display($diagnosticRow); + $assert($diagnosticRow->status === 'failed' + && $diagnosticRow->error_code === 'operation_failed' + && ($diagnosticResult['cause_code'] ?? null) === 'domain_start_failed' + && !isset($publicDiagnostic['result']['cause_code']) + && !str_contains(json_encode($publicDiagnostic, + JSON_UNESCAPED_UNICODE), '/srv/libvirt'), + 'Stable Agent cause was not persisted privately or leaked into the public job DTO.'); + // A signed two-hop admission rejection proves that the mutation never // reached the Agent journal. Only that exact case may clear dispatched_at // and retry the same durable operation from the PHP queue. diff --git a/web/tests/CloudOperationErrorCatalogTest.php b/web/tests/CloudOperationErrorCatalogTest.php index 0b40cd76..5b324a27 100644 --- a/web/tests/CloudOperationErrorCatalogTest.php +++ b/web/tests/CloudOperationErrorCatalogTest.php @@ -20,6 +20,7 @@ foreach (['errorMessage', 'stderrText', 'debugInfo', 'error-code', 'agent.error. $raw = [ 'status' => 'succeeded', + 'cause_code' => 'storage_clone_failed', 'phase' => 'Traceback: /var/lib/libvirt/private.xml', 'errorMessage' => 'libvirtError: source=/srv/secret-volume', 'safe_to_refund' => true, @@ -35,7 +36,7 @@ $raw = [ $user = CloudOperationErrorCatalog::result($raw, false, 'action', 'failed'); $assert(!isset($user['errorMessage'], $user['diagnostic'], $user['safe_to_refund'], - $user['unknown_agent_field']) + $user['unknown_agent_field'], $user['cause_code']) && !isset($user['vm']['disks'], $user['vm']['rescue_volume_name'], $user['vm']['console_port']) && !str_contains(json_encode($user, JSON_UNESCAPED_UNICODE), '/var/lib'), 'User operation result retained raw Agent diagnostics or storage metadata.'); @@ -43,15 +44,38 @@ $assert(!isset($user['errorMessage'], $user['diagnostic'], $user['safe_to_refund $admin = CloudOperationErrorCatalog::result($raw, true, 'action', 'failed'); $adminJson = json_encode($admin, JSON_UNESCAPED_UNICODE); $assert(isset($admin['diagnostic']) + && !isset($admin['cause_code']) && !str_contains($adminJson, '/var/lib') && !str_contains($adminJson, '/srv/secret'), 'Administrator operation result did not retain a redacted diagnostic summary.'); $durable = CloudOperationErrorCatalog::workerResult($raw); $assert(!isset($durable['errorMessage'], $durable['diagnostic'], $durable['safe_to_refund']) + && ($durable['cause_code'] ?? null) === 'storage_clone_failed' && !isset($durable['vm']['disks'], $durable['vm']['rescue_volume_name'], $durable['vm']['console_port']) && !str_contains(json_encode($durable, JSON_UNESCAPED_UNICODE), 'host-internal-value'), 'Durable operation result retained a non-allowlisted Agent field.'); +foreach (['StorageCloneFailed', 'storage__clone_failed', 'storage_clone_failed_', + 'storage-clone-failed', 'storage/clone', "storage_clone_failed\n", + str_repeat('a', 65)] as $invalidCauseCode) { + $assert(CloudOperationErrorCatalog::agentCauseCode($invalidCauseCode) === null + && !isset(CloudOperationErrorCatalog::workerResult([ + 'cause_code' => $invalidCauseCode, + ])['cause_code']), + 'Invalid Agent cause code entered durable result_json.'); +} +$assert(CloudOperationErrorCatalog::agentCauseCode('domain_define_failed') + === 'domain_define_failed' + && !isset(CloudOperationErrorCatalog::workerResult([ + 'vm' => ['cause_code' => 'nested_cause_must_not_persist'], + ])['vm']['cause_code']), + 'Stable Agent cause-code validation or top-level boundary failed.'); + +$assert(CloudOperationErrorCatalog::workerSummary('create', 'failed', [ + 'cause_code' => 'storage_clone_failed', + ], true) === 'provision_failed_refunded', + 'An administrator-only Agent cause replaced the public worker error code.'); + $assert(CloudOperationErrorCatalog::userStatus('SUCCEEDED') === 'succeeded' && CloudOperationErrorCatalog::userStatus('host-internal-state') === null, 'Unknown operation status bypassed the user status allow-list.'); diff --git a/web/tests/CloudProtocolTest.php b/web/tests/CloudProtocolTest.php index 395b2e6b..d32b5508 100644 --- a/web/tests/CloudProtocolTest.php +++ b/web/tests/CloudProtocolTest.php @@ -80,6 +80,24 @@ namespace { 'An ambiguous ' . $uncertainKind . ' operation was converted to a terminal failure.'); } + $normalizer = new ReflectionMethod(CloudWorkerService::class, + 'normalizeAgentOperation'); + $normalized = $normalizer->invoke(null, [ + 'status' => 'failed', + 'cause_code' => 'storage_clone_failed', + 'error' => ['code' => 'creation_absent', 'message' => '/srv/private'], + ]); + $assert(($normalized['cause_code'] ?? null) === 'storage_clone_failed' + && ($normalized['error_code'] ?? null) === 'creation_absent' + && !isset($normalized['error']), + 'Stable Agent cause code was lost while the free-form error was removed.'); + foreach (['StorageCloneFailed', 'storage/clone', 'storage_clone_failed_'] as $badCause) { + $normalized = $normalizer->invoke(null, [ + 'status' => 'failed', 'cause_code' => $badCause, + ]); + $assert(!isset($normalized['cause_code']), + 'Malformed Agent cause code survived operation normalization.'); + } foreach (['shortA1!', 'longwithoutupper1!', 'ALLUPPERCASE!123', 'LongWithoutSymbol123', 'NoDigitsLong!Aa', "StrongPassword!1\n", 'Strong Password!123', 'StrongPassword!123含中文', str_repeat('a', 126) . 'A1!'] as $bad) {