fix: harden agent dispatch and reconciliation

go
codex 1 month ago
parent 177fa24dd5
commit e7fa6256c2

@ -58,10 +58,11 @@ type Server struct {
}
type errorBody struct {
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
Operation *operation.Record `json:"operation,omitempty"`
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
DispatchState string `json:"dispatch_state,omitempty"`
Operation *operation.Record `json:"operation,omitempty"`
}
type errorEnvelope struct {
@ -106,37 +107,38 @@ func NewServer(
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
setResponseHeaders(w)
if !s.beginRequest() {
writeError(w, http.StatusServiceUnavailable, "agent_shutting_down", "Agent is shutting down", nil)
writePreDispatchError(w, http.StatusServiceUnavailable, "agent_shutting_down", "Agent is shutting down")
return
}
defer s.requestWG.Done()
if !strings.HasPrefix(r.URL.Path, "/v1/") || strings.HasSuffix(r.URL.Path, "/") {
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
return
}
body, err := readBoundedBody(w, r, s.MaxBodyBytes)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
writeError(w, http.StatusRequestEntityTooLarge, "body_too_large", "request body exceeds configured limit", nil)
writePreDispatchError(w, http.StatusRequestEntityTooLarge, "body_too_large", "request body exceeds configured limit")
} else {
writeError(w, http.StatusBadRequest, "invalid_body", "could not read request body", nil)
writePreDispatchError(w, http.StatusBadRequest, "invalid_body", "could not read request body")
}
return
}
actor, err := s.Authenticator.Authenticate(r, body)
if err != nil {
if errors.Is(err, auth.ErrNonceStore) {
writeError(w, http.StatusServiceUnavailable, "nonce_store_unavailable", "authentication state is unavailable", nil)
writePreDispatchError(w, http.StatusServiceUnavailable, "nonce_store_unavailable", "authentication state is unavailable")
return
}
code := "unauthorized"
message := "request authentication failed"
if errors.Is(err, auth.ErrReplay) {
code = "replayed_request"
message = "request nonce has already been used"
// The matching nonce may belong to an earlier request that already
// crossed the durable operation boundary. A replay rejection is not
// proof that the operation was never dispatched.
writeError(w, http.StatusUnauthorized, "replayed_request", "request nonce has already been used", nil)
return
}
writeError(w, http.StatusUnauthorized, code, message, nil)
writePreDispatchError(w, http.StatusUnauthorized, "unauthorized", "request authentication failed")
return
}
s.route(w, r, body, actor)
@ -145,7 +147,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func (s *Server) route(w http.ResponseWriter, r *http.Request, body []byte, actor auth.Actor) {
segments := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
if len(segments) < 2 || segments[0] != "v1" {
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
return
}
switch segments[1] {
@ -181,7 +183,7 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request, body []byte, acto
case "operations":
s.routeOperations(w, r, segments, actor)
default:
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
}
@ -201,13 +203,13 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
}
normalized, err := hypervisor.NormalizeStartupScript(request.StartupScript)
if err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
request.StartupScript = normalized
resolvedOperationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
request.OperationID = resolvedOperationID
@ -215,7 +217,7 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
request.UUID = operationUUID(resolvedOperationID)
}
if err := hypervisor.ValidateCreateVM(request); err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
s.runMutation(w, r, body, actor, request.OperationID, request.UUID, "create-vm", true, http.StatusCreated,
@ -226,7 +228,7 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
return
}
if len(segments) < 3 || !apiUUIDPattern.MatchString(segments[2]) {
writeError(w, http.StatusUnprocessableEntity, "invalid_uuid", "VM UUID must be canonical", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_uuid", "VM UUID must be canonical")
return
}
uuid := strings.ToLower(segments[2])
@ -244,7 +246,7 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
return
}
if !request.RemoveManagedDisks {
writeError(w, http.StatusUnprocessableEntity, "managed_disk_cleanup_required", "remove_managed_disks must be true", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "managed_disk_cleanup_required", "remove_managed_disks must be true")
return
}
s.runMutation(w, r, body, actor, request.OperationID, uuid, "delete-vm", true, http.StatusOK,
@ -281,7 +283,7 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
return
}
if !validPowerAction(request.Action) {
writeError(w, http.StatusUnprocessableEntity, "invalid_power_action", "action must be start, shutdown, reboot, reset, or destroy", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_power_action", "action must be start, shutdown, reboot, reset, or destroy")
return
}
s.runMutation(w, r, body, actor, request.OperationID, uuid, "power-"+string(request.Action), true, http.StatusOK,
@ -298,11 +300,11 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
return
}
if request.Hostname == nil && request.RootPassword == nil && request.SSHPublicKey == nil {
writeError(w, http.StatusUnprocessableEntity, "empty_settings", "at least one setting is required", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "empty_settings", "at least one setting is required")
return
}
if !request.ConfirmRestart {
writeError(w, http.StatusUnprocessableEntity, "restart_confirmation_required", "confirm_restart must be true", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "restart_confirmation_required", "confirm_restart must be true")
return
}
expected := &operation.ExpectedState{
@ -326,19 +328,19 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
return
}
if !request.ConfirmRestart {
writeError(w, http.StatusUnprocessableEntity, "restart_confirmation_required", "confirm_restart must be true", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "restart_confirmation_required", "confirm_restart must be true")
return
}
if err := hypervisor.ValidatePublicNetworkIntent(
request.NetworkSelector, request.PublicPoolKey, request.PublicPoolCIDR,
request.PublicIPCIDR, request.Gateway, request.DNSServers,
); err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
source, err := s.Hypervisor.ResolveNetworkSelector(r.Context(), request.NetworkSelector)
if err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
expected := &operation.ExpectedState{
@ -397,12 +399,12 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
return
}
if err := hypervisor.ValidateTemplateSnapshot(request.TemplateID, request.TemplateRevision, request.TemplateGenerationToken); err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
resolvedOperationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
request.OperationID = resolvedOperationID
@ -420,7 +422,7 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
if len(segments) == 5 && segments[4] == "daily" && r.Method == http.MethodGet {
days, err := strconv.Atoi(r.URL.Query().Get("days"))
if err != nil || days < 1 || days > 30 {
writeError(w, http.StatusUnprocessableEntity, "invalid_days", "days must be between 1 and 30", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_days", "days must be between 1 and 30")
return
}
result, err := s.Hypervisor.GetDailyTraffic(r.Context(), uuid, days)
@ -469,7 +471,7 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
operationID := request.OperationID
request, err := hypervisor.NormalizeFirewallPolicy(request)
if err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
expected := &operation.ExpectedState{Kind: operation.ExpectedFirewall, FirewallRevision: request.Revision, FirewallDigest: request.PolicyDigest}
@ -484,7 +486,7 @@ func (s *Server) routeVMs(w http.ResponseWriter, r *http.Request, segments []str
s.routeRescue(w, r, segments, body, actor, uuid)
return
}
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
func (s *Server) routeSnapshots(w http.ResponseWriter, r *http.Request, segments []string, body []byte, actor auth.Actor, uuid string) {
@ -506,7 +508,7 @@ func (s *Server) routeSnapshots(w http.ResponseWriter, r *http.Request, segments
}
resolvedOperationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
request.OperationID = resolvedOperationID
@ -519,7 +521,7 @@ func (s *Server) routeSnapshots(w http.ResponseWriter, r *http.Request, segments
return
}
if len(segments) < 5 || !resourceIDPattern.MatchString(segments[4]) {
writeError(w, http.StatusUnprocessableEntity, "invalid_snapshot_id", "snapshot ID is invalid", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_snapshot_id", "snapshot ID is invalid")
return
}
snapshotID := segments[4]
@ -548,7 +550,7 @@ func (s *Server) routeSnapshots(w http.ResponseWriter, r *http.Request, segments
}
resolvedOperationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
request.OperationID = resolvedOperationID
@ -571,7 +573,7 @@ func (s *Server) routeSnapshots(w http.ResponseWriter, r *http.Request, segments
}
resolvedOperationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
request.OperationID = resolvedOperationID
@ -581,7 +583,7 @@ func (s *Server) routeSnapshots(w http.ResponseWriter, r *http.Request, segments
})
return
}
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
func (s *Server) routeRescue(w http.ResponseWriter, r *http.Request, segments []string, body []byte, actor auth.Actor, uuid string) {
@ -607,7 +609,7 @@ func (s *Server) routeRescue(w http.ResponseWriter, r *http.Request, segments []
return
}
if !request.AckDataLoss {
writeError(w, http.StatusUnprocessableEntity, "data_loss_ack_required", "ack_data_loss must be true", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "data_loss_ack_required", "ack_data_loss must be true")
return
}
s.runMutation(w, r, body, actor, request.OperationID, uuid, "force-start-rescue", true, http.StatusAccepted,
@ -618,7 +620,7 @@ func (s *Server) routeRescue(w http.ResponseWriter, r *http.Request, segments []
return
}
if request.NetworkSuspended == nil {
writeError(w, http.StatusUnprocessableEntity, "network_state_required", "network_suspended must be provided", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "network_state_required", "network_suspended must be provided")
return
}
action := "exit-rescue:connected"
@ -630,12 +632,12 @@ func (s *Server) routeRescue(w http.ResponseWriter, r *http.Request, segments []
}
return
}
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
func (s *Server) routeTemplates(w http.ResponseWriter, r *http.Request, segments []string, body []byte, actor auth.Actor) {
if !actor.IsAdmin && !actor.IsSuperAdmin {
writeError(w, http.StatusForbidden, "forbidden", "administrator privileges are required", nil)
writePreDispatchError(w, http.StatusForbidden, "forbidden", "administrator privileges are required")
return
}
if len(segments) == 2 {
@ -652,7 +654,7 @@ func (s *Server) routeTemplates(w http.ResponseWriter, r *http.Request, segments
return
}
if err := validateImportSource(request.SourceURL, request.SourceToken, request.SHA256); err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
s.runAsyncMutation(w, r, body, actor, request.OperationID, "template:"+request.ID, "import-template", false,
@ -674,7 +676,7 @@ func (s *Server) routeTemplates(w http.ResponseWriter, r *http.Request, segments
return
}
if strings.TrimSpace(request.Name) == "" || len(request.Name) > 120 {
writeError(w, http.StatusUnprocessableEntity, "invalid_template_name", "template name must contain 1-120 characters", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_template_name", "template name must contain 1-120 characters")
return
}
s.runMutation(w, r, body, actor, request.OperationID, "template:"+templateID, "update-template", false, http.StatusOK,
@ -697,12 +699,12 @@ func (s *Server) routeTemplates(w http.ResponseWriter, r *http.Request, segments
}
return
}
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
func (s *Server) routeRescueTemplates(w http.ResponseWriter, r *http.Request, segments []string, body []byte, actor auth.Actor) {
if !actor.IsAdmin && !actor.IsSuperAdmin {
writeError(w, http.StatusForbidden, "forbidden", "administrator privileges are required", nil)
writePreDispatchError(w, http.StatusForbidden, "forbidden", "administrator privileges are required")
return
}
if len(segments) == 2 {
@ -720,18 +722,18 @@ func (s *Server) routeRescueTemplates(w http.ResponseWriter, r *http.Request, se
}
operationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
if request.ID == "" {
request.ID = operationCatalogID(operationID)
}
if !catalogIDPattern.MatchString(request.ID) {
writeError(w, http.StatusUnprocessableEntity, "invalid_rescue_template_id", "id must contain 32 lowercase hexadecimal characters", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_rescue_template_id", "id must contain 32 lowercase hexadecimal characters")
return
}
if err := validateImportSource(request.SourceURL, request.SourceToken, request.SHA256); err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
s.runAsyncMutation(w, r, body, actor, request.OperationID, "rescue-template:"+request.ID, "import-rescue-template", false,
@ -757,13 +759,13 @@ func (s *Server) routeRescueTemplates(w http.ResponseWriter, r *http.Request, se
})
return
}
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
func (s *Server) routeUserISOs(w http.ResponseWriter, r *http.Request, segments []string, body []byte, actor auth.Actor) {
ownerID, err := ownerFromRequest(r, actor)
if err != nil {
writeError(w, http.StatusForbidden, "forbidden", err.Error(), nil)
writePreDispatchError(w, http.StatusForbidden, "forbidden", err.Error())
return
}
if len(segments) == 2 {
@ -783,23 +785,23 @@ func (s *Server) routeUserISOs(w http.ResponseWriter, r *http.Request, segments
request.OwnerID = ownerID
}
if request.OwnerID != ownerID && !actor.IsAdmin && !actor.IsSuperAdmin {
writeError(w, http.StatusForbidden, "forbidden", "cannot import ISO for another owner", nil)
writePreDispatchError(w, http.StatusForbidden, "forbidden", "cannot import ISO for another owner")
return
}
operationID, err := resolveOperationID(actor.OperationID, request.OperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
if request.ID == "" {
request.ID = operationCatalogID(operationID)
}
if !catalogIDPattern.MatchString(request.ID) {
writeError(w, http.StatusUnprocessableEntity, "invalid_user_iso_id", "id must contain 32 lowercase hexadecimal characters", nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_user_iso_id", "id must contain 32 lowercase hexadecimal characters")
return
}
if err := validateImportSource(request.SourceURL, request.SourceToken, request.SHA256); err != nil {
writeMappedError(w, err, nil)
writePreDispatchMappedError(w, err)
return
}
s.runAsyncMutation(w, r, body, actor, request.OperationID, fmt.Sprintf("user-iso:%d:%s", request.OwnerID, request.ID), "import-user-iso", false,
@ -825,7 +827,7 @@ func (s *Server) routeUserISOs(w http.ResponseWriter, r *http.Request, segments
})
return
}
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
func catalogDeleteResult(resourceType, id string, ownerID int64, deleted bool) hypervisor.CatalogDeleteResult {
@ -868,7 +870,7 @@ func (s *Server) routeOperations(w http.ResponseWriter, r *http.Request, segment
writeJSON(w, http.StatusOK, record)
return
}
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
}
func (s *Server) runMutation(
@ -897,7 +899,7 @@ func (s *Server) runMutationExpected(
) {
operationID, err := resolveOperationID(actor.OperationID, bodyOperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
if expectedState != nil {
@ -964,7 +966,7 @@ func (s *Server) runAsyncMutation(
) {
operationID, err := resolveOperationID(actor.OperationID, bodyOperationID)
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error(), nil)
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_operation_id", err.Error())
return
}
spec := operation.Spec{
@ -1170,7 +1172,7 @@ func ownerFromRequest(r *http.Request, actor auth.Actor) (int64, error) {
func requireManage(w http.ResponseWriter, actor auth.Actor) bool {
if !actor.CanManage {
writeError(w, http.StatusForbidden, "forbidden", "actor is not authorized to manage this resource", nil)
writePreDispatchError(w, http.StatusForbidden, "forbidden", "actor is not authorized to manage this resource")
return false
}
return true
@ -1179,11 +1181,11 @@ func requireManage(w http.ResponseWriter, actor auth.Actor) bool {
func decodeRequired[T any](w http.ResponseWriter, body []byte) (T, bool) {
var value T
if len(body) == 0 {
writeError(w, http.StatusBadRequest, "invalid_json", "JSON request body is required", nil)
writePreDispatchError(w, http.StatusBadRequest, "invalid_json", "JSON request body is required")
return value, false
}
if err := decodeStrict(body, &value); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error(), nil)
writePreDispatchError(w, http.StatusBadRequest, "invalid_json", err.Error())
return value, false
}
return value, true
@ -1195,7 +1197,7 @@ func decodeOptional[T any](w http.ResponseWriter, body []byte) (T, bool) {
return value, true
}
if err := decodeStrict(body, &value); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error(), nil)
writePreDispatchError(w, http.StatusBadRequest, "invalid_json", err.Error())
return value, false
}
return value, true
@ -1250,6 +1252,15 @@ func writeMappedError(w http.ResponseWriter, err error, record *operation.Record
writeError(w, status, code, message, record)
}
// writePreDispatchMappedError is only for validation or dependency checks
// completed before Journal.Execute/Reserve. The explicit marker lets the
// panel distinguish a proven no-journal outcome from a lost response after a
// mutation may already have crossed its durable dispatch boundary.
func writePreDispatchMappedError(w http.ResponseWriter, err error) {
status, code, message := classifyError(err)
writePreDispatchError(w, status, code, message)
}
func classifyError(err error) (int, string, string) {
if errors.Is(err, operation.ErrNotFound) {
return http.StatusNotFound, "operation_not_found", "operation was not found"
@ -1324,11 +1335,18 @@ func writeOperationFailure(w http.ResponseWriter, record operation.Record, repla
func methodOrNotFound(w http.ResponseWriter, r *http.Request, exists bool, methods ...string) {
if !exists {
writeError(w, http.StatusNotFound, "not_found", "endpoint not found", nil)
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
return
}
w.Header().Set("Allow", strings.Join(methods, ", "))
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "method is not allowed", nil)
writePreDispatchError(w, http.StatusMethodNotAllowed, "method_not_allowed", "method is not allowed")
}
func writePreDispatchError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, errorEnvelope{Error: errorBody{
Code: code, Message: message, Retryable: retryableError(status, code),
DispatchState: "not_dispatched",
}})
}
func writeError(w http.ResponseWriter, status int, code, message string, record *operation.Record) {

@ -6,6 +6,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@ -25,11 +26,22 @@ type fakeHypervisor struct {
hypervisor.Unsupported
mu sync.Mutex
creates int
reconciles int
lastReconcile operation.Record
reconcileTo operation.Resolution
reconcileErr error
templateCalls chan hypervisor.ImportTemplateRequest
templateWait <-chan struct{}
rescueCalls chan hypervisor.ImportRescueTemplateRequest
userISOCalls chan hypervisor.ImportUserISORequest
forceCalls chan hypervisor.ForceRescueStartRequest
powerCalls chan hypervisor.PowerRequest
}
type failingNonceStore struct{}
func (failingNonceStore) UseNonce(string, time.Time, time.Time) (bool, error) {
return false, errors.New("nonce store failed")
}
func (f *fakeHypervisor) ListVMs(context.Context) ([]hypervisor.VMMetadata, error) {
@ -40,10 +52,11 @@ func (f *fakeHypervisor) Ping(context.Context) error { return nil }
func (f *fakeHypervisor) Capabilities(context.Context) (hypervisor.Capabilities, error) {
return hypervisor.Capabilities{
Backend: "fake",
Features: hypervisor.FeatureSet{CreateVM: true, Console: true, UEFI: true},
PowerActions: []hypervisor.PowerAction{hypervisor.PowerStart},
Firmware: []string{"uefi"},
Backend: "fake",
Features: hypervisor.FeatureSet{CreateVM: true, Console: true, UEFI: true},
PowerActions: []hypervisor.PowerAction{hypervisor.PowerStart},
Firmware: []string{"uefi"},
NetworkSelectors: []string{"public"},
}, nil
}
@ -58,6 +71,14 @@ func (f *fakeHypervisor) CreateVM(_ context.Context, request hypervisor.CreateVM
}, nil
}
func (f *fakeHypervisor) Reconcile(_ context.Context, record operation.Record) (operation.Resolution, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.reconciles++
f.lastReconcile = record
return f.reconcileTo, f.reconcileErr
}
func (f *fakeHypervisor) GetConsole(context.Context, string) (hypervisor.ConsoleSession, error) {
return hypervisor.ConsoleSession{Protocol: "vnc", Address: "127.0.0.1:5900"}, nil
}
@ -102,6 +123,11 @@ func (f *fakeHypervisor) ForceStartRescue(_ context.Context, _ string, request h
return hypervisor.RescueState{Active: true, TemplateID: "0123456789abcdef0123456789abcdef"}, nil
}
func (f *fakeHypervisor) Power(_ context.Context, _ string, request hypervisor.PowerRequest) (hypervisor.VMState, error) {
f.powerCalls <- request
return hypervisor.VMState{State: hypervisor.VMStateShutoff}, nil
}
type testAPI struct {
handler *Server
hv *fakeHypervisor
@ -134,6 +160,7 @@ func newTestAPI(t *testing.T) *testAPI {
rescueCalls: make(chan hypervisor.ImportRescueTemplateRequest, 1),
userISOCalls: make(chan hypervisor.ImportUserISORequest, 1),
forceCalls: make(chan hypervisor.ForceRescueStartRequest, 1),
powerCalls: make(chan hypervisor.PowerRequest, 1),
}
handler, err := NewServer(authenticator, journal, hv, broker, 64<<10, time.Second)
if err != nil {
@ -201,23 +228,64 @@ func TestListResponsesUseNamedNonNullEnvelope(t *testing.T) {
}
}
func TestCapabilitiesExposeStableNetworkSelectorKeys(t *testing.T) {
api := newTestAPI(t)
response := api.request(t, http.MethodGet, "/v1/capabilities", nil,
auth.Actor{UserID: 1})
if response.Code != http.StatusOK {
t.Fatalf("capabilities response = %d %s",
response.Code, response.Body.String())
}
var payload struct {
NetworkSelectors []string `json:"network_selectors"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.NetworkSelectors) != 1 ||
payload.NetworkSelectors[0] != "public" {
t.Fatalf("network selectors = %#v", payload.NetworkSelectors)
}
}
func TestReinstallRejectsStartupScript(t *testing.T) {
api := newTestAPI(t)
actor := auth.Actor{UserID: 1, CanManage: true, OperationID: "operation-reinstall"}
body := []byte(`{"operation_id":"operation-reinstall","template_id":"debian-12","template_revision":1,"template_generation_token":"0123456789abcdef0123456789abcdef","startup_script":"echo forbidden"}`)
response := api.request(t, http.MethodPost,
"/v1/vms/123e4567-e89b-42d3-a456-426614174000/reinstall", body, actor)
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), `"code":"invalid_json"`) {
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), `"code":"invalid_json"`) ||
!strings.Contains(response.Body.String(), `"dispatch_state":"not_dispatched"`) {
t.Fatalf("reinstall startup script response = %d %s", response.Code, response.Body.String())
}
}
func TestPowerDestroyWireActionIsAccepted(t *testing.T) {
api := newTestAPI(t)
actor := auth.Actor{UserID: 1, CanManage: true, OperationID: "operation-poweroff"}
body := []byte(`{"action":"destroy"}`)
response := api.request(t, http.MethodPost,
"/v1/vms/123e4567-e89b-42d3-a456-426614174000/actions", body, actor)
if response.Code != http.StatusOK {
t.Fatalf("destroy action response = %d %s", response.Code, response.Body.String())
}
select {
case request := <-api.hv.powerCalls:
if request.Action != hypervisor.PowerDestroy {
t.Fatalf("power action = %q, want destroy", request.Action)
}
default:
t.Fatal("destroy action did not reach the hypervisor")
}
}
func TestEveryHTTPRouteRequiresHMACIncludingHealth(t *testing.T) {
api := newTestAPI(t)
request := httptest.NewRequest(http.MethodGet, "/v1/health", nil)
response := httptest.NewRecorder()
api.handler.ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized {
if response.Code != http.StatusUnauthorized ||
!strings.Contains(response.Body.String(), `"dispatch_state":"not_dispatched"`) {
t.Fatalf("health without HMAC status = %d, body=%s", response.Code, response.Body.String())
}
@ -227,6 +295,143 @@ func TestEveryHTTPRouteRequiresHMACIncludingHealth(t *testing.T) {
}
}
func TestReplayAuthenticationFailureDoesNotClaimNotDispatched(t *testing.T) {
api := newTestAPI(t)
request := httptest.NewRequest(http.MethodGet, "/v1/health", nil)
if err := auth.Sign(request, nil, auth.Actor{UserID: 1}, api.secret,
api.now.Unix(), "fixed-replay-nonce-1234"); err != nil {
t.Fatal(err)
}
first := httptest.NewRecorder()
api.handler.ServeHTTP(first, request)
if first.Code != http.StatusOK {
t.Fatalf("first request status = %d body=%s", first.Code, first.Body.String())
}
replay := httptest.NewRequest(http.MethodGet, "/v1/health", nil)
if err := auth.Sign(replay, nil, auth.Actor{UserID: 1}, api.secret,
api.now.Unix(), "fixed-replay-nonce-1234"); err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
api.handler.ServeHTTP(response, replay)
if response.Code != http.StatusUnauthorized ||
!strings.Contains(response.Body.String(), `"code":"replayed_request"`) ||
strings.Contains(response.Body.String(), `"dispatch_state"`) {
t.Fatalf("replay response = %d %s", response.Code, response.Body.String())
}
}
func TestTerminalPreJournalContractIsExplicit(t *testing.T) {
api := newTestAPI(t)
tests := []struct {
name string
method string
target string
body []byte
actor auth.Actor
status int
code string
}{
{
name: "forbidden mutation", method: http.MethodPost, target: "/v1/vms",
body: []byte(`{}`), actor: auth.Actor{UserID: 1},
status: http.StatusForbidden, code: "forbidden",
},
{
name: "route missing", method: http.MethodPost, target: "/v1/missing",
body: []byte(`{}`), actor: auth.Actor{UserID: 1, CanManage: true},
status: http.StatusNotFound, code: "not_found",
},
{
name: "method mismatch", method: http.MethodDelete, target: "/v1/health",
actor: auth.Actor{UserID: 1, CanManage: true},
status: http.StatusMethodNotAllowed, code: "method_not_allowed",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
response := api.request(t, test.method, test.target, test.body, test.actor)
var payload errorEnvelope
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if response.Code != test.status || payload.Error.Code != test.code ||
payload.Error.Retryable || payload.Error.DispatchState != "not_dispatched" ||
payload.Error.Operation != nil {
t.Fatalf("response = %d %#v", response.Code, payload)
}
})
}
}
func TestRetryablePreJournalContractIsExplicit(t *testing.T) {
t.Run("shutting down", func(t *testing.T) {
api := newTestAPI(t)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := api.handler.Shutdown(ctx); err != nil {
t.Fatal(err)
}
response := api.request(t, http.MethodGet, "/v1/health", nil,
auth.Actor{UserID: 1})
assertRetryableNotDispatched(t, response, "agent_shutting_down")
})
t.Run("nonce store unavailable", func(t *testing.T) {
journal, err := operation.Open(filepath.Join(t.TempDir(), "operations.db"))
if err != nil {
t.Fatal(err)
}
defer journal.Close()
secret := []byte("0123456789abcdef0123456789abcdef")
now := time.Unix(2_000_000_000, 0)
authenticator, err := auth.NewWithNonceStore(
secret, 5*time.Minute, 10*time.Minute, failingNonceStore{},
)
if err != nil {
t.Fatal(err)
}
authenticator.SetClockForTesting(func() time.Time { return now })
broker, err := consolebroker.NewBroker(time.Minute)
if err != nil {
t.Fatal(err)
}
server, err := NewServer(authenticator, journal, &fakeHypervisor{},
broker, 64<<10, time.Second)
if err != nil {
t.Fatal(err)
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = server.Shutdown(ctx)
}()
request := httptest.NewRequest(http.MethodGet, "/v1/health", nil)
if err := auth.Sign(request, nil, auth.Actor{UserID: 1}, secret,
now.Unix(), "nonce-store-failure-1234"); err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
assertRetryableNotDispatched(t, response, "nonce_store_unavailable")
})
}
func assertRetryableNotDispatched(t *testing.T, response *httptest.ResponseRecorder, code string) {
t.Helper()
var payload errorEnvelope
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if response.Code != http.StatusServiceUnavailable ||
payload.Error.Code != code || !payload.Error.Retryable ||
payload.Error.DispatchState != "not_dispatched" ||
payload.Error.Operation != nil {
t.Fatalf("response = %d %#v", response.Code, payload)
}
}
func TestCreateVMOperationIsDurablyIdempotentAndConflictsOnPayloadChange(t *testing.T) {
api := newTestAPI(t)
actor := auth.Actor{UserID: 1, CanManage: true, OperationID: "operation-create-one"}
@ -251,11 +456,61 @@ func TestCreateVMOperationIsDurablyIdempotentAndConflictsOnPayloadChange(t *test
}
conflict := api.request(t, http.MethodPost, "/v1/vms", validCreateBody(actor.OperationID, "vm-different"), actor)
if conflict.Code != http.StatusConflict || !strings.Contains(conflict.Body.String(), "operation_id_conflict") {
if conflict.Code != http.StatusConflict ||
!strings.Contains(conflict.Body.String(), "operation_id_conflict") ||
strings.Contains(conflict.Body.String(), `"dispatch_state"`) {
t.Fatalf("conflict status = %d body=%s", conflict.Code, conflict.Body.String())
}
}
func TestFailedCreateRouteUsesReadOnlyReconciliationWithoutReplay(t *testing.T) {
api := newTestAPI(t)
operationID := "operation-create-api-failed"
uuid := "123e4567-e89b-42d3-a456-426614174000"
spec := operation.Spec{
OperationID: operationID, ResourceID: uuid, Action: "create-vm",
Fingerprint: operation.Fingerprint("POST", "/v1/vms", []byte(`{}`)),
Destructive: true,
}
if record, _, err := api.journal.Execute(context.Background(), spec,
func(context.Context) (json.RawMessage, error) {
return nil, errors.New("network selector is not configured")
}); err == nil || record.State != operation.StateFailed {
t.Fatalf("initial failed create = %#v err=%v", record, err)
}
api.hv.mu.Lock()
api.hv.reconcileTo = operation.Resolution{
Resolved: true, Succeeded: false, ErrorCode: "creation_absent",
Result: json.RawMessage(`{"creation_absent":true,"managed_artifacts_absent":true}`),
}
api.hv.mu.Unlock()
actor := auth.Actor{UserID: 1, CanManage: true, OperationID: operationID}
response := api.request(t, http.MethodPost,
"/v1/operations/"+operationID+"/reconcile", []byte(`{}`), actor)
if response.Code != http.StatusOK ||
!strings.Contains(response.Body.String(), `"status":"failed"`) ||
!strings.Contains(response.Body.String(), `"managed_artifacts_absent":true`) {
t.Fatalf("failed create reconcile response = %d %s", response.Code, response.Body.String())
}
api.hv.mu.Lock()
reconciles := api.hv.reconciles
last := api.hv.lastReconcile
creates := api.hv.creates
api.hv.mu.Unlock()
if reconciles != 1 || creates != 0 || last.OperationID != operationID || last.ResourceID != uuid || last.Action != "create-vm" {
t.Fatalf("reconcile calls=%d creates=%d record=%#v", reconciles, creates, last)
}
second := api.request(t, http.MethodPost,
"/v1/operations/"+operationID+"/reconcile", []byte(`{}`), actor)
api.hv.mu.Lock()
reconciles = api.hv.reconciles
api.hv.mu.Unlock()
if second.Code != http.StatusOK || reconciles != 1 {
t.Fatalf("confirmed absence was reinspected: status=%d calls=%d body=%s",
second.Code, reconciles, second.Body.String())
}
}
func TestUnsupportedTypedMutationUsesStable501Contract(t *testing.T) {
api := newTestAPI(t)
actor := auth.Actor{UserID: 1, CanManage: true, OperationID: "operation-network-one"}

@ -15,7 +15,12 @@ import (
"time"
)
const maxConfigBytes = 1 << 20
const (
maxConfigBytes = 1 << 20
maxNetworkSelectors = 64
defaultOperationTimeoutSeconds = int64(840)
maximumOperationTimeoutSeconds = int64(840)
)
// Config contains only host-agent settings. File ownership and mode are
// deliberately not part of validation: a readable configuration is accepted
@ -45,6 +50,7 @@ type NetworkSource struct {
}
var localNamePattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`)
var selectorNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$`)
var agentIDPattern = regexp.MustCompile(`^[1-9][0-9]{0,18}$`)
func (c *Config) applyDefaults() {
@ -61,7 +67,7 @@ func (c *Config) applyDefaults() {
c.NonceTTLSeconds = 600
}
if c.OperationTimeoutSec == 0 {
c.OperationTimeoutSec = 120
c.OperationTimeoutSec = defaultOperationTimeoutSeconds
}
}
@ -77,8 +83,9 @@ func (c Config) Validate() error {
strings.IndexFunc(c.AgentSecret, func(value rune) bool { return value < 0x21 || value > 0x7e }) >= 0 {
problems = append(problems, "agent_secret must contain 32-256 non-space printable ASCII bytes")
}
if strings.TrimSpace(c.JournalPath) == "" {
problems = append(problems, "journal_path is required")
if c.JournalPath == "" || !filepath.IsAbs(c.JournalPath) ||
filepath.Clean(c.JournalPath) != c.JournalPath || strings.ContainsRune(c.JournalPath, 0) {
problems = append(problems, "journal_path must be a clean absolute path")
}
if c.LibvirtURI != "qemu:///system" {
problems = append(problems, "libvirt_uri must be qemu:///system")
@ -96,8 +103,8 @@ func (c Config) Validate() error {
if minimumNonceTTL == 0 || c.NonceTTLSeconds < minimumNonceTTL || c.NonceTTLSeconds > 86400 {
problems = append(problems, "nonce_ttl_seconds must be at least twice clock_skew_seconds and at most 86400")
}
if c.OperationTimeoutSec < 5 || c.OperationTimeoutSec > 3600 {
problems = append(problems, "operation_timeout_seconds must be between 5 and 3600")
if c.OperationTimeoutSec < 5 || c.OperationTimeoutSec > maximumOperationTimeoutSeconds {
problems = append(problems, "operation_timeout_seconds must be between 5 and 840")
}
for label, value := range map[string]string{
"managed_storage_pool": c.ManagedStoragePool,
@ -119,9 +126,11 @@ func (c Config) Validate() error {
}
if len(c.NetworkSelectors) == 0 {
problems = append(problems, "network_selectors must define at least one host network")
} else if len(c.NetworkSelectors) > maxNetworkSelectors {
problems = append(problems, "network_selectors must not define more than 64 host networks")
}
for selector, source := range c.NetworkSelectors {
if !localNamePattern.MatchString(selector) || !localNamePattern.MatchString(source.Source) || (source.Type != "bridge" && source.Type != "network") {
if !selectorNamePattern.MatchString(selector) || !localNamePattern.MatchString(source.Source) || (source.Type != "bridge" && source.Type != "network") {
problems = append(problems, "network_selectors contains an invalid selector")
}
}

@ -38,6 +38,9 @@ func TestLoadAcceptsReadableConfigRegardlessOfMode(t *testing.T) {
if cfg.LibvirtURI != "qemu:///system" {
t.Fatalf("unexpected default URI: %q", cfg.LibvirtURI)
}
if cfg.OperationTimeoutSec != 840 {
t.Fatalf("unexpected default operation timeout: %d", cfg.OperationTimeoutSec)
}
})
}
}
@ -122,6 +125,71 @@ func TestLoadAcceptsMaximumLengthDecimalAgentID(t *testing.T) {
}
}
func TestLoadRejectsRawBridgeSyntaxAsSelectorKey(t *testing.T) {
path := filepath.Join(t.TempDir(), "agent.json")
body := strings.Replace(
validConfigJSON(""),
`"network_selectors":{"public":`,
`"network_selectors":{"bridge:br0":`,
1,
)
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil || !strings.Contains(err.Error(),
"network_selectors contains an invalid selector") {
t.Fatalf("raw bridge selector error = %v", err)
}
}
func TestLoadRequiresCleanAbsoluteJournalPath(t *testing.T) {
for name, value := range map[string]string{
"relative": "var/lib/virt-agent/operations.db",
"unclean": "/var/lib/virt-agent/../virt-agent/operations.db",
} {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "agent.json")
body := strings.ReplaceAll(
validConfigJSON(""), "/tmp/virt-agent-operations.db", value,
)
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil || !strings.Contains(err.Error(), "clean absolute path") {
t.Fatalf("journal path %q error = %v", value, err)
}
})
}
}
func TestLoadBoundsAdvertisedNetworkSelectors(t *testing.T) {
selectors := make(map[string]NetworkSource, maxNetworkSelectors+1)
for index := 0; index <= maxNetworkSelectors; index++ {
selectors[fmt.Sprintf("network-%02d", index)] = NetworkSource{
Type: "bridge", Source: fmt.Sprintf("br%d", index),
}
}
cfg := Config{
PanelURL: "https://panel.example.com", AgentID: "42",
AgentSecret: testSecret, JournalPath: "/tmp/agent.db",
LibvirtURI: "qemu:///system", MaxBodyBytes: 1 << 20,
ClockSkewSeconds: 300, NonceTTLSeconds: 600,
OperationTimeoutSec: maximumOperationTimeoutSeconds,
ManagedStoragePool: "managed", TemplateStoragePool: "templates",
SeedStoragePool: "seeds", FirmwareLoader: "/firmware/loader",
FirmwareNVRAMTemplate: "/firmware/vars", NVRAMDirectory: "/nvram",
NetworkSelectors: selectors,
}
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(),
"network_selectors must not define more than 64 host networks") {
t.Fatalf("oversized selector set error = %v", err)
}
delete(selectors, fmt.Sprintf("network-%02d", maxNetworkSelectors))
if err := cfg.Validate(); err != nil {
t.Fatalf("maximum selector set was rejected: %v", err)
}
}
func TestLoadRequiresNonceTTLToCoverFullClockSkewWindow(t *testing.T) {
path := filepath.Join(t.TempDir(), "agent.json")
if err := os.WriteFile(path, []byte(validConfigJSON(`,"clock_skew_seconds":300,"nonce_ttl_seconds":599`)), 0o600); err != nil {
@ -131,3 +199,19 @@ func TestLoadRequiresNonceTTLToCoverFullClockSkewWindow(t *testing.T) {
t.Fatalf("short nonce TTL error = %v", err)
}
}
func TestLoadCapsOperationTimeoutBelowGatewayDeadline(t *testing.T) {
path := filepath.Join(t.TempDir(), "agent.json")
if err := os.WriteFile(path, []byte(validConfigJSON(`,"operation_timeout_seconds":840`)), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err != nil {
t.Fatalf("maximum layered operation timeout was rejected: %v", err)
}
if err := os.WriteFile(path, []byte(validConfigJSON(`,"operation_timeout_seconds":841`)), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil || !strings.Contains(err.Error(), "between 5 and 840") {
t.Fatalf("operation timeout above Gateway margin error = %v", err)
}
}

@ -7,7 +7,7 @@ import (
"testing"
)
func TestAgentSystemdSandboxOnlyGrantsAgentStateWrites(t *testing.T) {
func TestAgentSystemdSandboxOnlyGrantsStateAndManagedNVRAMWrites(t *testing.T) {
servicePath := filepath.Join("..", "..", "deploy", "virt-cloud-agent.service")
contents, err := os.ReadFile(servicePath)
if err != nil {
@ -17,8 +17,8 @@ func TestAgentSystemdSandboxOnlyGrantsAgentStateWrites(t *testing.T) {
for _, required := range []string{
"ProtectSystem=strict",
"StateDirectory=virt-agent",
"ReadWritePaths=/var/lib/virt-agent",
"NVRAM and libvirt storage paths are written by the separate libvirt/QEMU",
"ReadWritePaths=/var/lib/virt-agent -/var/lib/libvirt/qemu/nvram",
"If nvram_directory is configured elsewhere, replace this path in a drop-in.",
} {
if !strings.Contains(service, required) {
t.Fatalf("agent service is missing %q", required)

@ -29,16 +29,20 @@ import (
)
const (
ControlSubprotocol = "virt-agent-control.v1"
ConsoleProtocol = "virt-agent-console."
controlPath = "/agent/connect"
consolePath = "/agent/console"
maxControlFrame = 4 << 20
maxResponseBytes = 2 << 20
maxRequestBody = 1 << 20
maxInFlight = 32
maxActiveConsoles = 16
reconnectDelay = 5 * time.Second
ControlSubprotocol = "virt-agent-control.v1"
ConsoleProtocol = "virt-agent-console."
controlPath = "/agent/connect"
consolePath = "/agent/console"
maxControlFrame = 4 << 20
maxResponseBytes = 2 << 20
maxRequestBody = 1 << 20
maxInFlight = 32
maxActiveConsoles = 16
reconnectDelay = 5 * time.Second
controlPingInterval = 30 * time.Second
controlPingTimeout = 10 * time.Second
controlResultMargin = 15 * time.Second
maximumAPITimeout = 840 * time.Second
)
var (
@ -86,7 +90,7 @@ func NewClient(
handler http.Handler,
console *consolebroker.Broker,
maxBodyBytes int64,
requestTimeout time.Duration,
operationTimeout time.Duration,
) (*Client, error) {
origin, err := parsePanelOrigin(panelURL)
if err != nil {
@ -105,8 +109,8 @@ func NewClient(
if maxBodyBytes < 1024 || maxBodyBytes > maxRequestBody {
return nil, errors.New("maximum body size is invalid")
}
if requestTimeout < 5*time.Second || requestTimeout > time.Hour {
return nil, errors.New("request timeout must be between 5 seconds and 1 hour")
if operationTimeout < 5*time.Second || operationTimeout > maximumAPITimeout {
return nil, errors.New("operation timeout must be between 5 and 840 seconds")
}
dialer := &net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}
transport := &http.Transport{
@ -118,13 +122,16 @@ func NewClient(
ResponseHeaderTimeout: 15 * time.Second,
}
return &Client{
panelOrigin: origin,
agentID: agentID,
agentSecret: string(append([]byte(nil), agentSecret...)),
handler: handler,
console: console,
maxBodyBytes: maxBodyBytes,
requestTimeout: requestTimeout,
panelOrigin: origin,
agentID: agentID,
agentSecret: string(append([]byte(nil), agentSecret...)),
handler: handler,
console: console,
maxBodyBytes: maxBodyBytes,
// The API owns the durable mutation deadline. Keep the WSS response
// envelope alive long enough to carry its structured result, while the
// Gateway still retains another 15 seconds before its 870s deadline.
requestTimeout: operationTimeout + controlResultMargin,
inFlight: make(chan struct{}, maxInFlight),
activeConsoles: make(chan struct{}, maxActiveConsoles),
httpClient: &http.Client{
@ -180,9 +187,23 @@ func (c *Client) runSession(parent context.Context) error {
}
connection.SetReadLimit(maxControlFrame)
writer := &connectionWriter{connection: connection}
heartbeatErrors := make(chan error, 1)
go func() {
if heartbeatErr := maintainControlHeartbeat(
ctx, connection, controlPingInterval, controlPingTimeout,
); heartbeatErr != nil {
heartbeatErrors <- heartbeatErr
cancel()
}
}()
for {
messageType, payload, err := connection.Read(ctx)
if err != nil {
select {
case heartbeatErr := <-heartbeatErrors:
return fmt.Errorf("maintain panel control heartbeat: %w", heartbeatErr)
default:
}
return fmt.Errorf("read panel control message: %w", err)
}
if messageType != websocket.MessageText {
@ -206,6 +227,40 @@ func (c *Client) runSession(parent context.Context) error {
}
}
type controlPinger interface {
Ping(context.Context) error
}
// maintainControlHeartbeat creates traffic in both directions often enough to
// keep an otherwise idle WSS session alive through reverse proxies and CDNs.
// Ping waits for the peer's Pong, so an unresponsive gateway also causes the
// session to close and reconnect instead of remaining half-open indefinitely.
func maintainControlHeartbeat(
ctx context.Context,
connection controlPinger,
interval time.Duration,
timeout time.Duration,
) error {
if interval <= 0 || timeout <= 0 {
return errors.New("control heartbeat timing is invalid")
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
pingCtx, cancel := context.WithTimeout(ctx, timeout)
err := connection.Ping(pingCtx)
cancel()
if err != nil {
return fmt.Errorf("control ping failed: %w", err)
}
}
}
}
func (c *Client) dispatch(
ctx context.Context,
writer *connectionWriter,
@ -222,13 +277,15 @@ func (c *Client) dispatch(
}()
default:
_ = writer.respond(ctx, notDispatchedErrorResponse(input.ID,
http.StatusServiceUnavailable, "agent_busy"))
http.StatusServiceUnavailable, "agent_busy", true))
}
}
func (c *Client) handleRequest(sessionCtx, requestCtx context.Context, writer *connectionWriter, input message) {
if err := c.validateRequest(input); err != nil {
_ = writer.respond(sessionCtx, errorResponse(input.ID, http.StatusBadRequest, "invalid_control_request"))
_ = writer.respond(sessionCtx, notDispatchedErrorResponse(
input.ID, http.StatusBadRequest, "invalid_control_request", false,
))
return
}
requestURL, _ := url.ParseRequestURI(input.RequestTarget)
@ -478,11 +535,11 @@ func errorResponse(id string, status int, code string) response {
// signed request reaches the API handler (and therefore before the durable
// operation journal). The panel may safely put the same operation back in
// its persistent queue only when this exact marker is present.
func notDispatchedErrorResponse(id string, status int, code string) response {
func notDispatchedErrorResponse(id string, status int, code string, retryable bool) response {
body, _ := json.Marshal(map[string]any{
"error": map[string]any{
"code": code, "message": "Agent control request was not dispatched",
"retryable": true, "dispatch_state": "not_dispatched",
"retryable": retryable, "dispatch_state": "not_dispatched",
},
})
return response{Type: "response", ID: id, Status: status, Body: string(body)}

@ -23,6 +23,90 @@ import (
const controlTestSecret = "0123456789abcdef0123456789abcdef"
func TestControlDeadlineWrapsAPIOperationDeadline(t *testing.T) {
broker, err := consolebroker.NewBroker(time.Minute)
if err != nil {
t.Fatal(err)
}
client, err := NewClient(
"https://panel.example", "42", []byte(controlTestSecret),
http.NotFoundHandler(), broker, 64<<10, maximumAPITimeout,
)
if err != nil {
t.Fatal(err)
}
if client.requestTimeout != 855*time.Second {
t.Fatalf("control request timeout = %s, want 855s", client.requestTimeout)
}
if _, err := NewClient(
"https://panel.example", "42", []byte(controlTestSecret),
http.NotFoundHandler(), broker, 64<<10, maximumAPITimeout+time.Second,
); err == nil {
t.Fatal("control client accepted an API timeout that crosses the Gateway margin")
}
}
type controlPingerFunc func(context.Context) error
func (function controlPingerFunc) Ping(ctx context.Context) error {
return function(ctx)
}
func TestControlHeartbeatPingsUntilSessionCloses(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
pinged := make(chan struct{}, 1)
finished := make(chan error, 1)
go func() {
finished <- maintainControlHeartbeat(ctx, controlPingerFunc(
func(context.Context) error {
select {
case pinged <- struct{}{}:
default:
}
return nil
},
), time.Millisecond, 50*time.Millisecond)
}()
select {
case <-pinged:
cancel()
case <-time.After(time.Second):
cancel()
t.Fatal("control heartbeat did not send a Ping")
}
select {
case err := <-finished:
if err != nil {
t.Fatalf("heartbeat returned an error after session cancellation: %v", err)
}
case <-time.After(time.Second):
t.Fatal("control heartbeat did not stop with its session")
}
}
func TestControlHeartbeatRejectsMissingPong(t *testing.T) {
finished := make(chan error, 1)
go func() {
finished <- maintainControlHeartbeat(context.Background(), controlPingerFunc(
func(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
},
), time.Millisecond, 5*time.Millisecond)
}()
select {
case err := <-finished:
if err == nil || !strings.Contains(err.Error(), "control ping failed") ||
!errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("missing Pong error = %v", err)
}
case <-time.After(time.Second):
t.Fatal("missing Pong did not fail the control heartbeat")
}
}
func TestControlSessionAuthenticatesAndDispatchesInnerSignedRequest(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
authenticator, err := auth.New([]byte(controlTestSecret), time.Minute, 2*time.Minute)

@ -21,6 +21,7 @@ var (
uuidPattern = 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}$`)
namePattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,80}$`)
netPattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,64}$`)
networkSelectorPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$`)
templateIDPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
generationTokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
poolKeyPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
@ -310,7 +311,7 @@ func ValidateCreateVM(request CreateVMRequest) error {
// ValidatePublicNetworkIntent verifies a signed PHP/IPAM allocation without
// making the host agent a second pool authority.
func ValidatePublicNetworkIntent(selector, poolKey, poolCIDR, publicIPCIDR, gateway string, dnsServers []string) error {
if !netPattern.MatchString(selector) {
if !networkSelectorPattern.MatchString(selector) {
return NewError(ErrInvalid, "invalid_network", "network selector is invalid", nil)
}
if !poolKeyPattern.MatchString(poolKey) {

@ -208,6 +208,12 @@ func validIntentCreateRequest(t *testing.T) CreateVMRequest {
func TestValidatePublicNetworkIntentRejectsPoolDrift(t *testing.T) {
request := validIntentCreateRequest(t)
request.NetworkSelector = "bridge:br0"
if err := ValidateCreateVM(request); err == nil || !strings.Contains(err.Error(),
"network selector is invalid") {
t.Fatalf("raw bridge selector error = %v", err)
}
request = validIntentCreateRequest(t)
request.PublicIPCIDR = "8.8.4.10/24"
if err := ValidateCreateVM(request); err == nil || !strings.Contains(err.Error(), "inside") {
t.Fatalf("outside allocation error = %v", err)

@ -11,6 +11,7 @@ import (
"fmt"
"net"
"net/netip"
"os"
"path/filepath"
"sort"
"strconv"
@ -79,7 +80,7 @@ func (l *Libvirt) Capabilities(ctx context.Context) (Capabilities, error) {
if err := ctx.Err(); err != nil {
return Capabilities{}, err
}
features, checks := l.probeRuntimeCapabilities()
features, checks, networkSelectors := l.probeRuntimeCapabilities()
powerActions := []PowerAction(nil)
if features.Power {
powerActions = []PowerAction{PowerStart, PowerShutdown, PowerReboot, PowerReset, PowerDestroy}
@ -91,7 +92,8 @@ func (l *Libvirt) Capabilities(ctx context.Context) (Capabilities, error) {
return Capabilities{
Backend: "libvirt", LibvirtVersion: formatLibvirtVersion(libVersion),
QEMUVersion: formatLibvirtVersion(qemuVersion),
Features: features, PowerActions: powerActions, Firmware: firmware, Checks: checks,
Features: features, PowerActions: powerActions, Firmware: firmware,
NetworkSelectors: networkSelectors, Checks: checks,
}, nil
}
@ -163,7 +165,9 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
}
domainMutationMu.Lock()
defer domainMutationMu.Unlock()
attachment, err := l.resolvePublicNetwork(request)
unlockTrafficSample := l.traffic.lockSample(request.UUID)
defer unlockTrafficSample()
attachment, err := l.resolvePublicNetwork(ctx, request)
if err != nil {
return VMMetadata{}, err
}
@ -268,7 +272,7 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
}
filter, err := l.conn.NWFilterDefineXML(filterDocument)
if err != nil {
return VMMetadata{}, mutationLibvirtError("define VM network filter", err)
return VMMetadata{}, operation.MarkUncertain(mutationLibvirtError("define VM network filter", err))
}
filterOwned := true
defer func() {
@ -300,13 +304,54 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
if err != nil {
return VMMetadata{}, err
}
trafficCreated, err := l.traffic.initialize(request.UUID, time.Now().UTC())
if err != nil {
return VMMetadata{}, NewError(ErrUnavailable, "traffic_state_unavailable", "new VM traffic baseline could not be initialized", err)
}
trafficOwned := trafficCreated
defer func() {
if trafficOwned {
if cleanupErr := l.traffic.remove(request.UUID); cleanupErr != nil {
resultErr = markTrafficCleanupUncertain(resultErr, cleanupErr)
}
}
}()
preserveDefinedDomainArtifacts := func() {
rootOwned = false
seedOwned = false
filterOwned = false
trafficOwned = false
}
domain, err := l.conn.DomainDefineXML(document)
if err != nil {
observed, inspectErr := l.conn.LookupDomainByUUIDString(request.UUID)
if observed != nil {
_ = observed.Free()
}
if domainMayExistAfterDefine(inspectErr) {
// DomainDefineXML may have committed before its response failed. Do
// not let deferred cleanup remove disks, firewall, or accounting
// state that the possibly-defined domain owns.
preserveDefinedDomainArtifacts()
return VMMetadata{}, operation.MarkUncertain(errors.Join(
mutationLibvirtError("define domain", err),
translateOptionalLibvirtError("inspect domain after define failure", inspectErr),
))
}
return VMMetadata{}, mutationLibvirtError("define domain", err)
}
defer domain.Free()
if err := domain.SetAutostart(true); err != nil {
rollbackErr := domain.UndefineFlags(libvirt.DOMAIN_UNDEFINE_NVRAM)
absent, inspectErr := l.deleteDomainAbsent(ctx, request.UUID)
if inspectErr != nil || !absent {
preserveDefinedDomainArtifacts()
return VMMetadata{}, operation.MarkUncertain(errors.Join(
mutationLibvirtError("enable domain autostart", err),
optionalMutationLibvirtError("roll back domain definition", rollbackErr),
inspectErr,
))
}
if rollbackErr != nil {
return VMMetadata{}, operation.MarkUncertain(errors.Join(
mutationLibvirtError("enable domain autostart", err),
@ -315,9 +360,10 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
}
return VMMetadata{}, mutationLibvirtError("enable domain autostart", err)
}
rootOwned = false
seedOwned = false
filterOwned = false
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))
}
@ -337,20 +383,28 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
return metadata, nil
}
func markTrafficCleanupUncertain(prior, cleanupErr error) error {
return operation.MarkUncertain(errors.Join(prior, NewError(
ErrUnavailable, "traffic_state_unavailable",
"unused VM traffic baseline could not be removed", cleanupErr,
)))
}
func isDebian12Template(template ImageTemplate) bool {
return strings.EqualFold(strings.TrimSpace(template.OSFamily), "debian") && strings.TrimSpace(template.Version) == "12"
}
func (l *Libvirt) resolvePublicNetwork(request CreateVMRequest) (NetworkAttachment, error) {
func (l *Libvirt) resolvePublicNetwork(ctx context.Context,
request CreateVMRequest) (NetworkAttachment, error) {
if err := ValidatePublicNetworkIntent(
request.NetworkSelector, request.PublicPoolKey, request.PublicPoolCIDR,
request.PublicIPCIDR, request.Gateway, request.DNSServers,
); err != nil {
return NetworkAttachment{}, err
}
source, ok := l.local.NetworkSelectors[request.NetworkSelector]
if !ok {
return NetworkAttachment{}, NewError(ErrInvalid, "network_not_found", "host network selector is not configured", nil)
source, err := l.ResolveNetworkSelector(ctx, request.NetworkSelector)
if err != nil {
return NetworkAttachment{}, err
}
attachment := NetworkAttachment{}
switch source.Type {
@ -408,7 +462,7 @@ func (l *Libvirt) cloneRootVolume(request CreateVMRequest) (*libvirt.StorageVol,
}
volume, err := managedPool.StorageVolCreateXMLFrom(document, template, 0)
if err != nil {
return nil, mutationLibvirtError("clone template volume", err)
return nil, operation.MarkUncertain(mutationLibvirtError("clone template volume", err))
}
return volume, nil
}
@ -430,7 +484,7 @@ func (l *Libvirt) createSeedVolume(uuid string, contents []byte) (*libvirt.Stora
}
volume, err := pool.StorageVolCreateXML(document, 0)
if err != nil {
return nil, mutationLibvirtError("create NoCloud volume", err)
return nil, operation.MarkUncertain(mutationLibvirtError("create NoCloud volume", err))
}
if err := l.uploadVolume(volume, contents); err != nil {
cleanupErr := volume.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
@ -591,6 +645,29 @@ func (l *Libvirt) DeleteVM(ctx context.Context, uuid string, request DeleteVMReq
if err != nil {
return err
}
if err := l.validateDeleteVMArtifacts(ctx, uuid, managed); err != nil {
return err
}
if err := driveDeleteDomainToAbsent(domain, func() (bool, error) {
return l.deleteDomainAbsent(ctx, uuid)
}); err != nil {
return err
}
if err := l.cleanupDeletedVMArtifacts(ctx, uuid); err != nil {
// Domain absence is already confirmed, so any later failure describes a
// partially completed cleanup tail and must never become a terminal
// failed delete in the journal.
return operation.MarkUncertain(err)
}
return nil
}
// validateDeleteVMArtifacts proves that every disk selected by a VM deletion
// is Agent-owned and is not referenced by another live or persistent domain.
// It deliberately runs before the domain is stopped so a corrupt ownership
// marker cannot turn an otherwise rejected request into a partial deletion.
func (l *Libvirt) validateDeleteVMArtifacts(ctx context.Context, uuid string,
managed *domainMetadataXML) error {
managedPool, err := l.conn.LookupStoragePoolByName(l.local.ManagedStoragePool)
if err != nil {
return translateLibvirtError("lookup managed storage pool", err)
@ -604,17 +681,10 @@ func (l *Libvirt) DeleteVM(ctx context.Context, uuid string, request DeleteVMReq
if err != nil {
return err
}
type pendingVolume struct {
name string
volume *libvirt.StorageVol
}
volumes := make([]pendingVolume, 0, len(volumeNames))
defer func() {
for _, item := range volumes {
_ = item.volume.Free()
}
}()
for _, name := range volumeNames {
if err := ctx.Err(); err != nil {
return err
}
volume, lookupErr := managedPool.LookupStorageVolByName(name)
if isNoStorageVolume(lookupErr) {
continue
@ -640,68 +710,116 @@ func (l *Libvirt) DeleteVM(ctx context.Context, uuid string, request DeleteVMReq
_ = volume.Free()
return NewError(ErrConflict, "managed_disk_shared", "managed VM volume is referenced by another domain", nil)
}
volumes = append(volumes, pendingVolume{name: name, volume: volume})
_ = volume.Free()
}
seedVolume, err := l.lookupOptionalManagedVolume(l.local.SeedStoragePool, seedVolumeName(uuid))
if err != nil {
return err
}
if seedVolume != nil {
defer seedVolume.Free()
seedPath, pathErr := seedVolume.GetPath()
if pathErr != nil {
_ = seedVolume.Free()
return translateLibvirtError("resolve managed NoCloud seed volume", pathErr)
}
referenced, referenceErr := l.otherDomainUsesPath(seedPath, uuid)
if referenceErr != nil {
_ = seedVolume.Free()
return referenceErr
}
if referenced {
_ = seedVolume.Free()
return NewError(ErrConflict, "managed_disk_shared", "managed NoCloud seed volume is referenced by another domain", nil)
}
_ = seedVolume.Free()
}
filter, err := l.lookupOptionalNetworkFilter(networkFilterName(uuid))
if err != nil {
return err
}
if filter != nil {
defer filter.Free()
_ = filter.Free()
}
return nil
}
type deleteDomainControl interface {
IsActive() (bool, error)
DestroyFlags(libvirt.DomainDestroyFlags) error
UndefineFlags(libvirt.DomainUndefineFlagsValues) error
}
// driveDeleteDomainToAbsent advances only the remaining stages of the exact
// delete operation being reconciled. Mutation-call errors are never accepted
// on their own: the observed domain state must prove that the requested stage
// took effect, otherwise the operation remains uncertain and can be reconciled
// again under the same operation ID.
func driveDeleteDomainToAbsent(domain deleteDomainControl,
domainAbsent func() (bool, error)) error {
active, err := domain.IsActive()
if err != nil {
return translateLibvirtError("check domain activity", err)
}
if active {
if err := domain.DestroyFlags(libvirt.DOMAIN_DESTROY_DEFAULT); err != nil {
return mutationLibvirtError("destroy domain before undefine", err)
destroyErr := domain.DestroyFlags(libvirt.DOMAIN_DESTROY_DEFAULT)
stillActive, inspectErr := domain.IsActive()
if inspectErr != nil || stillActive {
var mutationErr, observedErr error
if destroyErr != nil {
mutationErr = mutationLibvirtError("destroy domain before undefine", destroyErr)
} else {
mutationErr = NewError(ErrConflict, "delete_domain_still_active",
"domain remained active after destroy", nil)
}
if inspectErr != nil {
observedErr = translateLibvirtError("recheck domain activity after destroy", inspectErr)
}
return operation.MarkUncertain(errors.Join(mutationErr, observedErr))
}
}
flags := libvirt.DOMAIN_UNDEFINE_NVRAM |
libvirt.DOMAIN_UNDEFINE_SNAPSHOTS_METADATA |
libvirt.DOMAIN_UNDEFINE_CHECKPOINTS_METADATA
if err := domain.UndefineFlags(flags); err != nil {
return operation.MarkUncertain(mutationLibvirtError("undefine domain", err))
}
for _, item := range volumes {
if err := item.volume.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL); err != nil {
return operation.MarkUncertain(mutationLibvirtError("delete managed VM volume "+item.name, err))
undefineErr := domain.UndefineFlags(flags)
absent, inspectErr := domainAbsent()
if inspectErr != nil || !absent {
var mutationErr error
if undefineErr != nil {
mutationErr = mutationLibvirtError("undefine domain", undefineErr)
} else {
mutationErr = NewError(ErrConflict, "delete_domain_still_defined",
"domain remained present after undefine", nil)
}
return operation.MarkUncertain(errors.Join(mutationErr, inspectErr))
}
if seedVolume != nil {
if err := seedVolume.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL); err != nil {
return operation.MarkUncertain(mutationLibvirtError("delete NoCloud seed volume", err))
}
return nil
}
func (l *Libvirt) deleteDomainAbsent(ctx context.Context, uuid string) (bool, error) {
if err := ctx.Err(); err != nil {
return false, err
}
if filter != nil {
if err := filter.Undefine(); err != nil {
return operation.MarkUncertain(mutationLibvirtError("undefine VM network filter", err))
}
if !uuidPattern.MatchString(uuid) {
return false, NewError(ErrInvalid, "invalid_uuid", "uuid must be canonical", nil)
}
if err := l.traffic.remove(uuid); err != nil {
return operation.MarkUncertain(NewError(ErrUnavailable, "traffic_state_unavailable", "deleted VM traffic state could not be removed", err))
domain, err := l.conn.LookupDomainByUUIDString(uuid)
if err == nil {
_ = domain.Free()
return false, nil
}
return nil
if isNoDomain(err) {
return true, nil
}
return false, translateLibvirtError("confirm deleted domain absence", err)
}
func isNoDomain(err error) bool {
var libvirtErr libvirt.Error
return errors.As(err, &libvirtErr) && libvirtErr.Code == libvirt.ERR_NO_DOMAIN
}
func domainMayExistAfterDefine(inspectErr error) bool {
return inspectErr == nil || !isNoDomain(inspectErr)
}
func collectVMManagedVolumeNames(uuid string, metadata *domainMetadataXML, inventory []string) ([]string, error) {
@ -781,7 +899,37 @@ func (l *Libvirt) Power(ctx context.Context, uuid string, request PowerRequest)
if _, _, err := requireManagedDomain(domain); err != nil {
return VMState{}, err
}
switch request.Action {
if err := dispatchPowerMutation(domain, request.Action); err != nil {
return VMState{}, err
}
if request.Action == PowerShutdown {
if err := waitForShutoff(ctx, domain); err != nil {
return VMState{}, operation.MarkUncertain(err)
}
}
state, reason, err := domain.GetState()
if err != nil {
return VMState{}, operation.MarkUncertain(translateLibvirtError("confirm power action", err))
}
mapped := mapDomainState(state)
if err := confirmPowerTargetState(request.Action, mapped); err != nil {
return VMState{}, err
}
name, _ := domain.GetName()
return VMState{UUID: uuid, Name: name, State: mapped, Reason: reason}, nil
}
type powerDomainControl interface {
Create() error
ShutdownFlags(libvirt.DomainShutdownFlags) error
Reboot(libvirt.DomainRebootFlagValues) error
Reset(uint32) error
DestroyFlags(libvirt.DomainDestroyFlags) error
}
func dispatchPowerMutation(domain powerDomainControl, action PowerAction) error {
var err error
switch action {
case PowerStart:
err = domain.Create()
case PowerShutdown:
@ -793,22 +941,32 @@ func (l *Libvirt) Power(ctx context.Context, uuid string, request PowerRequest)
case PowerDestroy:
err = domain.DestroyFlags(libvirt.DOMAIN_DESTROY_DEFAULT)
default:
return VMState{}, NewError(ErrInvalid, "invalid_power_action", "unknown power action", nil)
return NewError(ErrInvalid, "invalid_power_action", "unknown power action", nil)
}
if err != nil {
return VMState{}, mutationLibvirtError("perform power action", err)
// A libvirt lifecycle call can take effect before its transport reports
// an error. Keep the exact operation reconcilable instead of recording a
// terminal failure that could invite a second destructive request.
return operation.MarkUncertain(mutationLibvirtError("perform power action", err))
}
if request.Action == PowerShutdown {
if err := waitForShutoff(ctx, domain); err != nil {
return VMState{}, operation.MarkUncertain(err)
}
return nil
}
func confirmPowerTargetState(action PowerAction, state VMStateName) error {
reached := true
switch action {
case PowerStart:
reached = state == VMStateRunning || state == VMStateBlocked
case PowerShutdown, PowerDestroy:
reached = state == VMStateShutoff
}
state, reason, err := domain.GetState()
if err != nil {
return VMState{}, operation.MarkUncertain(translateLibvirtError("confirm power action", err))
if !reached {
return operation.MarkUncertain(NewError(
ErrConflict, "power_state_unconfirmed",
"power action did not reach the requested target state", nil,
))
}
name, _ := domain.GetName()
return VMState{UUID: uuid, Name: name, State: mapDomainState(state), Reason: reason}, nil
return nil
}
func (l *Libvirt) GetConsole(ctx context.Context, uuid string) (ConsoleSession, error) {
@ -817,6 +975,13 @@ func (l *Libvirt) GetConsole(ctx context.Context, uuid string) (ConsoleSession,
return ConsoleSession{}, err
}
defer domain.Free()
active, err := domain.IsActive()
if err != nil {
return ConsoleSession{}, translateLibvirtError("check console domain activity", err)
}
if !active {
return ConsoleSession{}, NewError(ErrNotFound, "console_not_available", "VM has no active local VNC console", nil)
}
document, err := domain.GetXMLDesc(0)
if err != nil {
return ConsoleSession{}, translateLibvirtError("get live console XML", err)
@ -847,6 +1012,16 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
if resolution, handled, err := l.reconcileCatalogOperation(record); handled {
return resolution, err
}
// 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:") {
domainMutationMu.Lock()
defer domainMutationMu.Unlock()
}
domain, err := l.domainByUUID(ctx, record.ResourceID)
if errors.Is(err, ErrNotFound) {
if record.Action == "create-vm" {
@ -855,6 +1030,9 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
return operation.Resolution{}, inspectErr
}
if absent {
if cleanupErr := l.removeAbsentVMTrafficState(record.ResourceID); cleanupErr != nil {
return operation.Resolution{}, cleanupErr
}
return operation.Resolution{
Resolved: true, Succeeded: false,
Result: []byte(`{"creation_absent":true,"managed_artifacts_absent":true}`),
@ -864,6 +1042,12 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
}
}
if record.Action == "delete-vm" {
// The original delete already crossed its dispatch boundary and the
// domain is now absent. Continue only deterministic, UUID-owned
// cleanup; never invoke DeleteVM again or touch panel/IP state.
if cleanupErr := l.cleanupDeletedVMArtifacts(ctx, record.ResourceID); cleanupErr != nil {
return operation.Resolution{}, cleanupErr
}
absent, inspectErr := l.deleteArtifactsAbsent(record.ResourceID)
if inspectErr != nil {
return operation.Resolution{}, inspectErr
@ -881,6 +1065,9 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
return operation.Resolution{}, err
}
defer domain.Free()
if record.Action == "delete-vm" {
return l.reconcileExistingDelete(ctx, record.ResourceID, domain)
}
if resolution, handled, err := l.reconcileDomainFeatureOperation(record, domain); handled {
return resolution, err
}
@ -897,7 +1084,7 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
return operation.Resolution{Resolved: true, Succeeded: true, Result: []byte(`{"state":"running"}`)}, nil
}
case "power-shutdown", "power-destroy":
if mapped == VMStateShutoff || mapped == VMStateShutdown {
if mapped == VMStateShutoff {
return operation.Resolution{Resolved: true, Succeeded: true, Result: []byte(`{"state":"shutoff"}`)}, nil
}
}
@ -906,6 +1093,183 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
return operation.Resolution{}, nil
}
func (l *Libvirt) reconcileExistingDelete(ctx context.Context, uuid string,
domain *libvirt.Domain) (operation.Resolution, error) {
_, managed, err := requireManagedDomain(domain)
if err != nil {
return operation.Resolution{}, err
}
if err := l.validateDeleteVMArtifacts(ctx, uuid, managed); err != nil {
return operation.Resolution{}, err
}
if err := driveDeleteDomainToAbsent(domain, func() (bool, error) {
return l.deleteDomainAbsent(ctx, uuid)
}); err != nil {
return operation.Resolution{}, err
}
if err := l.cleanupDeletedVMArtifacts(ctx, uuid); err != nil {
return operation.Resolution{}, err
}
absent, err := l.deleteArtifactsAbsent(uuid)
if err != nil {
return operation.Resolution{}, err
}
if !absent {
return operation.Resolution{}, nil
}
return operation.Resolution{
Resolved: true, Succeeded: true,
Result: []byte(`{"absent":true,"managed_disks_absent":true}`),
}, nil
}
func (l *Libvirt) removeAbsentVMTrafficState(uuid string) error {
unlockTrafficSample := l.traffic.lockSample(uuid)
defer unlockTrafficSample()
if err := l.traffic.remove(uuid); err != nil {
return NewError(ErrUnavailable, "traffic_state_unavailable",
"absent VM traffic state could not be removed", err)
}
return nil
}
// cleanupDeletedVMArtifacts resumes the idempotent tail of a delete after the
// domain definition is already gone. Every target is derived from the VM UUID,
// validated as Agent-owned, and checked for cross-domain references first.
func (l *Libvirt) cleanupDeletedVMArtifacts(ctx context.Context, uuid string) error {
if err := ctx.Err(); err != nil {
return err
}
unlockTrafficSample := l.traffic.lockSample(uuid)
defer unlockTrafficSample()
pool, err := l.conn.LookupStoragePoolByName(l.local.ManagedStoragePool)
if err != nil {
return translateLibvirtError("lookup managed storage pool", err)
}
defer pool.Free()
inventory, err := pool.ListStorageVolumes()
if err != nil {
return translateLibvirtError("list managed volumes for VM cleanup", err)
}
names, err := collectVMManagedVolumeNames(uuid, nil, inventory)
if err != nil {
return err
}
for _, name := range names {
if err := ctx.Err(); err != nil {
return err
}
volume, lookupErr := pool.LookupStorageVolByName(name)
if isNoStorageVolume(lookupErr) {
continue
}
if lookupErr != nil {
return translateLibvirtError("lookup managed VM cleanup volume", lookupErr)
}
if _, validateErr := validateQCOW2Volume(volume, 0); validateErr != nil {
_ = volume.Free()
return validateErr
}
path, pathErr := volume.GetPath()
if pathErr != nil {
_ = volume.Free()
return translateLibvirtError("resolve managed VM cleanup volume", pathErr)
}
referenced, referenceErr := l.anyDomainUsesPath(path)
if referenceErr != nil {
_ = volume.Free()
return referenceErr
}
if referenced {
_ = volume.Free()
return NewError(ErrConflict, "managed_disk_shared", "managed VM cleanup volume is referenced by a domain", nil)
}
deleteErr := volume.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
_ = volume.Free()
if deleteErr != nil {
observed, inspectErr := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, name)
if observed != nil {
_ = observed.Free()
}
if inspectErr != nil || observed != nil {
return operation.MarkUncertain(errors.Join(
mutationLibvirtError("delete managed VM cleanup volume "+name, deleteErr), inspectErr,
))
}
}
}
seed, err := l.lookupOptionalManagedVolume(l.local.SeedStoragePool, seedVolumeName(uuid))
if err != nil {
return err
}
if seed != nil {
path, pathErr := seed.GetPath()
if pathErr != nil {
_ = seed.Free()
return translateLibvirtError("resolve managed NoCloud cleanup volume", pathErr)
}
referenced, referenceErr := l.anyDomainUsesPath(path)
if referenceErr != nil {
_ = seed.Free()
return referenceErr
}
if referenced {
_ = seed.Free()
return NewError(ErrConflict, "managed_disk_shared", "managed NoCloud cleanup volume is referenced by a domain", nil)
}
deleteErr := seed.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
_ = seed.Free()
if deleteErr != nil {
observed, inspectErr := l.lookupOptionalManagedVolume(l.local.SeedStoragePool, seedVolumeName(uuid))
if observed != nil {
_ = observed.Free()
}
if inspectErr != nil || observed != nil {
return operation.MarkUncertain(errors.Join(
mutationLibvirtError("delete NoCloud cleanup volume", deleteErr), inspectErr,
))
}
}
}
filter, err := l.lookupOptionalNetworkFilter(networkFilterName(uuid))
if err != nil {
return err
}
if filter != nil {
undefineErr := filter.Undefine()
_ = filter.Free()
if undefineErr != nil {
observed, inspectErr := l.lookupOptionalNetworkFilter(networkFilterName(uuid))
if observed != nil {
_ = observed.Free()
}
if inspectErr != nil || observed != nil {
return operation.MarkUncertain(errors.Join(
mutationLibvirtError("undefine VM cleanup network filter", undefineErr), inspectErr,
))
}
}
}
for _, name := range managedNVRAMArtifactNames(uuid) {
path := filepath.Join(l.local.NVRAMDirectory, name)
referenced, referenceErr := l.anyDomainUsesPath(path)
if referenceErr != nil {
return referenceErr
}
if referenced {
return NewError(ErrConflict, "managed_nvram_shared",
"managed VM firmware state is referenced by another domain", nil)
}
}
if err := removeManagedNVRAMArtifacts(l.local.NVRAMDirectory, uuid); err != nil {
return NewError(ErrUnavailable, "nvram_cleanup_pending", "managed VM firmware cleanup is incomplete", err)
}
if err := l.traffic.remove(uuid); err != nil {
return NewError(ErrUnavailable, "traffic_state_unavailable", "deleted VM traffic state could not be removed", err)
}
return nil
}
func (l *Libvirt) deleteArtifactsAbsent(uuid string) (bool, error) {
pool, err := l.conn.LookupStoragePoolByName(l.local.ManagedStoragePool)
if err != nil {
@ -939,9 +1303,61 @@ func (l *Libvirt) deleteArtifactsAbsent(uuid string) (bool, error) {
_ = filter.Free()
return false, nil
}
nvramAbsent, err := managedNVRAMArtifactAbsent(l.local.NVRAMDirectory, uuid)
if err != nil {
return false, NewError(ErrUnavailable, "nvram_state_unavailable",
"managed VM firmware state could not be inspected", err)
}
if !nvramAbsent {
return false, nil
}
return true, nil
}
func managedNVRAMArtifactAbsent(directory, uuid string) (bool, error) {
candidates := managedNVRAMArtifactNames(uuid)
for _, name := range candidates {
if _, err := os.Lstat(filepath.Join(directory, name)); err == nil {
return false, nil
} else if !errors.Is(err, os.ErrNotExist) {
return false, err
}
}
return true, nil
}
func managedNVRAMArtifactNames(uuid string) []string {
normalized := strings.ToLower(uuid)
candidates := []string{normalized + "_VARS.fd"}
if uuid != normalized {
// CreateVM historically accepted an uppercase UUID and used its exact
// spelling for the NVRAM filename. Check both spellings so absence is
// never claimed while either managed artifact remains.
candidates = append(candidates, uuid+"_VARS.fd")
}
return candidates
}
func removeManagedNVRAMArtifacts(directory, uuid string) error {
for _, name := range managedNVRAMArtifactNames(uuid) {
path := filepath.Join(directory, name)
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return fmt.Errorf("managed NVRAM artifact is not a regular file")
}
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
}
return nil
}
func (l *Libvirt) domainByUUID(ctx context.Context, uuid string) (*libvirt.Domain, error) {
if err := ctx.Err(); err != nil {
return nil, err
@ -968,7 +1384,7 @@ func waitForShutoff(ctx context.Context, domain *libvirt.Domain) error {
if err != nil {
return translateLibvirtError("wait for shutdown", err)
}
if state == libvirt.DOMAIN_SHUTOFF || state == libvirt.DOMAIN_SHUTDOWN {
if state == libvirt.DOMAIN_SHUTOFF {
return nil
}
select {

@ -6,6 +6,8 @@ import (
"encoding/xml"
"net"
"os"
"path/filepath"
"sort"
"strings"
"libvirt.org/go/libvirt"
@ -13,15 +15,16 @@ import (
)
const (
capabilityMissing = "not_configured"
capabilityUnreadable = "not_readable"
capabilityInvalid = "invalid_resource"
capabilityUnavailable = "unavailable"
capabilityInactive = "inactive"
capabilityExhausted = "no_available_capacity"
capabilityUnsupported = "unsupported"
capabilitySelectorMissing = "no_network_selectors"
capabilitySelectorUnusable = "network_selector_unavailable"
maxCapabilityNetworkSelectors = 64
capabilityMissing = "not_configured"
capabilityUnreadable = "not_readable"
capabilityInvalid = "invalid_resource"
capabilityUnavailable = "unavailable"
capabilityInactive = "inactive"
capabilityExhausted = "no_available_capacity"
capabilityUnsupported = "unsupported"
capabilitySelectorMissing = "no_network_selectors"
capabilitySelectorUnusable = "network_selector_unavailable"
)
type capabilityPrerequisites struct {
@ -29,6 +32,7 @@ type capabilityPrerequisites struct {
nvramTemplate bool
nvramDirectory bool
managedPool bool
snapshotPool bool
templatePool bool
seedPool bool
networks bool
@ -47,7 +51,7 @@ func (p capabilityPrerequisites) features() FeatureSet {
Settings: p.seedPool,
Network: p.seedPool && p.networks && p.nwfilter,
Reinstall: create,
Snapshots: p.managedPool && p.liveBackup,
Snapshots: p.managedPool && p.snapshotPool && p.liveBackup,
Firewall: p.nwfilter,
Rescue: p.templatePool && p.seedPool,
Metrics: true,
@ -60,16 +64,20 @@ func (p capabilityPrerequisites) features() FeatureSet {
}
}
func (l *Libvirt) probeRuntimeCapabilities() (FeatureSet, map[string]CapabilityCheck) {
func (l *Libvirt) probeRuntimeCapabilities() (FeatureSet, map[string]CapabilityCheck, []string) {
q35UEFI, liveBackup := l.probeDomainCapabilities()
networkCheck, networkSelectors := probeNetworkSelectorSet(
l.local.NetworkSelectors, l.probeNetworkSource,
)
checks := map[string]CapabilityCheck{
"firmware_loader": probeReadableRegularFile(l.local.FirmwareLoader),
"firmware_nvram_template": probeReadableRegularFile(l.local.FirmwareNVRAMTemplate),
"nvram_directory": probeExistingDirectory(l.local.NVRAMDirectory),
"managed_storage_pool": l.probeStoragePool(l.local.ManagedStoragePool),
"snapshot_storage_pool": l.probeSnapshotStoragePool(l.local.ManagedStoragePool),
"template_storage_pool": l.probeStoragePool(l.local.TemplateStoragePool),
"seed_storage_pool": l.probeStoragePool(l.local.SeedStoragePool),
"network_selectors": l.probeNetworkSelectors(),
"network_selectors": networkCheck,
"nwfilter_api": l.probeNWFilterAPI(),
"q35_uefi": q35UEFI,
"live_backup": liveBackup,
@ -79,6 +87,7 @@ func (l *Libvirt) probeRuntimeCapabilities() (FeatureSet, map[string]CapabilityC
nvramTemplate: checks["firmware_nvram_template"].Available,
nvramDirectory: checks["nvram_directory"].Available,
managedPool: checks["managed_storage_pool"].Available,
snapshotPool: checks["snapshot_storage_pool"].Available,
templatePool: checks["template_storage_pool"].Available,
seedPool: checks["seed_storage_pool"].Available,
networks: checks["network_selectors"].Available,
@ -86,7 +95,7 @@ func (l *Libvirt) probeRuntimeCapabilities() (FeatureSet, map[string]CapabilityC
q35UEFI: checks["q35_uefi"].Available,
liveBackup: checks["live_backup"].Available,
}
return prerequisites.features(), checks
return prerequisites.features(), checks, networkSelectors
}
func availableCheck() CapabilityCheck { return CapabilityCheck{Available: true} }
@ -154,34 +163,101 @@ func (l *Libvirt) probeStoragePool(name string) CapabilityCheck {
return availableCheck()
}
func (l *Libvirt) probeNetworkSelectors() CapabilityCheck {
if len(l.local.NetworkSelectors) == 0 {
return unavailableCheck(capabilitySelectorMissing)
}
for _, source := range l.local.NetworkSelectors {
switch source.Type {
case "bridge":
device, err := net.InterfaceByName(source.Source)
if err != nil || device.Flags&net.FlagUp == 0 {
return unavailableCheck(capabilitySelectorUnusable)
}
case "network":
network, err := l.conn.LookupNetworkByName(source.Source)
if err != nil {
return unavailableCheck(capabilitySelectorUnusable)
}
active, activeErr := network.IsActive()
network.Free()
if activeErr != nil || !active {
return unavailableCheck(capabilitySelectorUnusable)
}
default:
// Snapshot and restore use QEMU file-backed backup targets and direct volume
// paths. An active logical, RBD, iSCSI, or other non-file pool can satisfy
// ordinary volume operations but cannot safely satisfy that contract.
func (l *Libvirt) probeSnapshotStoragePool(name string) CapabilityCheck {
if strings.TrimSpace(name) == "" {
return unavailableCheck(capabilityMissing)
}
pool, err := l.conn.LookupStoragePoolByName(name)
if err != nil {
return unavailableCheck(capabilityUnavailable)
}
defer pool.Free()
document, err := pool.GetXMLDesc(0)
if err != nil {
return unavailableCheck(capabilityUnavailable)
}
if !snapshotStoragePoolXMLSupported(document) {
return unavailableCheck(capabilityUnsupported)
}
return availableCheck()
}
func snapshotStoragePoolXMLSupported(document string) bool {
var definition libvirtxml.StoragePool
if definition.Unmarshal(document) != nil || definition.Target == nil {
return false
}
if definition.Type != "dir" && definition.Type != "fs" && definition.Type != "netfs" {
return false
}
path := filepath.Clean(strings.TrimSpace(definition.Target.Path))
return filepath.IsAbs(path) && path != string(filepath.Separator)
}
func probeNetworkSelectorSet(selectors map[string]LocalNetworkSource,
probe func(LocalNetworkSource) CapabilityCheck) (CapabilityCheck, []string) {
if len(selectors) == 0 {
return unavailableCheck(capabilitySelectorMissing), []string{}
}
if len(selectors) > maxCapabilityNetworkSelectors {
return unavailableCheck(capabilityInvalid), []string{}
}
usable := make([]string, 0, len(selectors))
for selector, source := range selectors {
if probe(source).Available {
usable = append(usable, selector)
}
}
sort.Strings(usable)
if len(usable) != 0 {
return availableCheck(), usable
}
return unavailableCheck(capabilitySelectorUnusable), usable
}
func (l *Libvirt) probeNetworkSource(source LocalNetworkSource) CapabilityCheck {
switch source.Type {
case "bridge":
device, err := net.InterfaceByName(source.Source)
if err != nil || device.Flags&net.FlagUp == 0 {
return unavailableCheck(capabilitySelectorUnusable)
}
case "network":
network, err := l.conn.LookupNetworkByName(source.Source)
if err != nil {
return unavailableCheck(capabilitySelectorUnusable)
}
active, activeErr := network.IsActive()
network.Free()
if activeErr != nil || !active {
return unavailableCheck(capabilitySelectorUnusable)
}
default:
return unavailableCheck(capabilitySelectorUnusable)
}
return availableCheck()
}
func resolveConfiguredNetworkSelector(
selectors map[string]LocalNetworkSource,
selector string,
probe func(LocalNetworkSource) CapabilityCheck,
) (LocalNetworkSource, error) {
source, ok := selectors[selector]
if !ok {
return LocalNetworkSource{}, NewError(ErrInvalid, "network_not_found",
"host network selector is not configured", nil)
}
if !probe(source).Available {
return LocalNetworkSource{}, NewError(ErrUnavailable,
"network_unavailable", "host network selector is not active", nil)
}
return source, nil
}
func (l *Libvirt) probeNWFilterAPI() CapabilityCheck {
filters, err := l.conn.ListAllNWFilters(0)
if err != nil {
@ -190,9 +266,26 @@ func (l *Libvirt) probeNWFilterAPI() CapabilityCheck {
for index := range filters {
_ = filters[index].Free()
}
baseline, err := l.conn.LookupNWFilterByName("clean-traffic")
if err != nil {
return unavailableCheck(capabilityUnavailable)
}
document, readErr := baseline.GetXMLDesc(0)
_ = baseline.Free()
if readErr != nil {
return unavailableCheck(capabilityUnavailable)
}
if !cleanTrafficFilterXMLValid(document) {
return unavailableCheck(capabilityInvalid)
}
return availableCheck()
}
func cleanTrafficFilterXMLValid(document string) bool {
var filter libvirtxml.NWFilter
return filter.Unmarshal(document) == nil && filter.Name == "clean-traffic"
}
func (l *Libvirt) probeDomainCapabilities() (CapabilityCheck, CapabilityCheck) {
document, err := l.conn.GetDomainCapabilities("", "x86_64", "q35", "kvm", 0)
if err != nil {

@ -40,6 +40,32 @@ func userISOMetadataVolumeName(ownerID int64, id string) string {
return "virt-useriso-" + strconv.FormatInt(ownerID, 10) + "-" + id + ".json"
}
type catalogDeleteEvidence struct {
label string
notFoundCode string
inconsistentCode string
}
func validateCatalogDeletePresence(imageExists, metadataExists bool, evidence catalogDeleteEvidence) error {
if !imageExists && !metadataExists {
return NewError(ErrNotFound, evidence.notFoundCode, evidence.label+" was not found", nil)
}
if imageExists != metadataExists {
return NewError(ErrConflict, evidence.inconsistentCode, evidence.label+" image and managed metadata are inconsistent", nil)
}
return nil
}
func catalogDeleteEvidenceChanged(err error, evidence catalogDeleteEvidence) error {
if err == nil || !errors.Is(err, ErrNotFound) {
return err
}
// Do not retain ErrNotFound in the unwrap chain: the HTTP layer checks that
// kind before ErrConflict, and PHP deliberately treats only a proven
// double-absence tombstone as a successful delete.
return NewError(ErrConflict, evidence.inconsistentCode, evidence.label+" managed artifacts changed during deletion", nil)
}
func (l *Libvirt) ListTemplates(ctx context.Context) ([]ImageTemplate, error) {
if err := ctx.Err(); err != nil {
return nil, err
@ -194,18 +220,19 @@ func (l *Libvirt) DeleteTemplate(ctx context.Context, id string) error {
if err != nil {
return err
}
if !imageExists && !metadataExists {
return NewError(ErrNotFound, "template_not_found", "template was not found", nil)
evidence := catalogDeleteEvidence{
label: "template", notFoundCode: "template_not_found",
inconsistentCode: "template_artifacts_inconsistent",
}
if imageExists != metadataExists {
return NewError(ErrConflict, "template_artifacts_inconsistent", "template image and managed metadata are inconsistent", nil)
if err := validateCatalogDeletePresence(imageExists, metadataExists, evidence); err != nil {
return err
}
if _, err := l.loadImageTemplate(id); err != nil {
return err
return catalogDeleteEvidenceChanged(err, evidence)
}
pool, volume, err := l.templateVolume(id)
if err != nil {
return err
return catalogDeleteEvidenceChanged(err, evidence)
}
defer pool.Free()
defer volume.Free()
@ -347,21 +374,22 @@ func (l *Libvirt) DeleteRescueTemplate(ctx context.Context, id string) error {
if err != nil {
return err
}
if !imageExists && !metadataExists {
return NewError(ErrNotFound, "rescue_template_not_found", "rescue template was not found", nil)
evidence := catalogDeleteEvidence{
label: "rescue template", notFoundCode: "rescue_template_not_found",
inconsistentCode: "rescue_template_artifacts_inconsistent",
}
if imageExists != metadataExists {
return NewError(ErrConflict, "rescue_template_artifacts_inconsistent", "rescue template image and managed metadata are inconsistent", nil)
if err := validateCatalogDeletePresence(imageExists, metadataExists, evidence); err != nil {
return err
}
if _, err := l.loadRescueTemplate(id); err != nil {
return err
return catalogDeleteEvidenceChanged(err, evidence)
}
volume, err := l.lookupOptionalManagedVolume(l.local.TemplateStoragePool, rescueImageVolumeName(id))
if err != nil {
return err
}
if volume == nil {
return NewError(ErrNotFound, "rescue_template_not_found", "rescue template was not found", nil)
return NewError(ErrConflict, evidence.inconsistentCode, "rescue template image disappeared during deletion", nil)
}
defer volume.Free()
used, err := l.volumeReferenced(volume)
@ -514,25 +542,26 @@ func (l *Libvirt) DeleteUserISO(ctx context.Context, id string, ownerID int64) e
if err != nil {
return err
}
if !imageExists && !metadataExists {
return NewError(ErrNotFound, "user_iso_not_found", "user ISO was not found", nil)
evidence := catalogDeleteEvidence{
label: "user ISO", notFoundCode: "user_iso_not_found",
inconsistentCode: "user_iso_artifacts_inconsistent",
}
if imageExists != metadataExists {
return NewError(ErrConflict, "user_iso_artifacts_inconsistent", "user ISO image and managed metadata are inconsistent", nil)
if err := validateCatalogDeletePresence(imageExists, metadataExists, evidence); err != nil {
return err
}
item, err := l.loadUserISO(ownerID, id)
if err != nil {
return err
return catalogDeleteEvidenceChanged(err, evidence)
}
if item.OwnerID != ownerID {
return NewError(ErrNotFound, "user_iso_not_found", "user ISO was not found", nil)
return NewError(ErrConflict, evidence.inconsistentCode, "user ISO managed metadata ownership is inconsistent", nil)
}
volume, err := l.lookupOptionalManagedVolume(l.local.SeedStoragePool, userISOImageVolumeName(ownerID, id))
if err != nil {
return err
}
if volume == nil {
return NewError(ErrNotFound, "user_iso_not_found", "user ISO was not found", nil)
return NewError(ErrConflict, evidence.inconsistentCode, "user ISO image disappeared during deletion", nil)
}
defer volume.Free()
used, err := l.volumeReferenced(volume)
@ -578,7 +607,7 @@ func (l *Libvirt) loadImageTemplate(id string) (ImageTemplate, error) {
return ImageTemplate{}, err
}
if volume == nil {
return ImageTemplate{}, NewError(ErrNotFound, "template_not_found", "template image is not present on this host", nil)
return ImageTemplate{}, NewError(ErrConflict, "template_volume_missing", "template catalog references a missing image volume", nil)
}
info, err := volume.GetInfo()
volume.Free()
@ -607,7 +636,7 @@ func (l *Libvirt) loadRescueTemplate(id string) (RescueTemplate, error) {
return RescueTemplate{}, err
}
if volume == nil {
return RescueTemplate{}, NewError(ErrNotFound, "rescue_template_not_found", "rescue template ISO is not present on this host", nil)
return RescueTemplate{}, NewError(ErrConflict, "rescue_volume_missing", "rescue template catalog references a missing ISO volume", nil)
}
info, err := volume.GetInfo()
volume.Free()
@ -624,7 +653,7 @@ func (l *Libvirt) loadUserISO(ownerID int64, id string) (UserISO, error) {
return UserISO{}, err
}
if item.OwnerID != ownerID || item.ID != id || !catalogIDPattern.MatchString(item.ID) || !sha256Pattern.MatchString(item.SHA256) {
return UserISO{}, NewError(ErrNotFound, "user_iso_not_found", "user ISO was not found", nil)
return UserISO{}, NewError(ErrConflict, "user_iso_catalog_invalid", "user ISO catalog metadata is invalid", nil)
}
return item, nil
}
@ -681,7 +710,7 @@ func (l *Libvirt) writeCatalogEntry(name string, value any, replace bool) error
}
volume, err := pool.StorageVolCreateXML(document, 0)
if err != nil {
return mutationLibvirtError("create catalog entry", err)
return operation.MarkUncertain(mutationLibvirtError("create catalog entry", err))
}
defer volume.Free()
if err := l.uploadVolume(volume, encoded); err != nil {
@ -718,7 +747,7 @@ func (l *Libvirt) templateVolume(id string) (*libvirt.StoragePool, *libvirt.Stor
if err != nil {
pool.Free()
if isNoStorageVolume(err) {
return nil, nil, NewError(ErrNotFound, "template_not_found", "template image is not present on this host", err)
return nil, nil, NewError(ErrConflict, "template_volume_missing", "template catalog references a missing image volume", err)
}
return nil, nil, translateLibvirtError("lookup template volume", err)
}
@ -775,7 +804,7 @@ func (l *Libvirt) downloadVolume(ctx context.Context, pool *libvirt.StoragePool,
}
volume, err := pool.StorageVolCreateXML(document, 0)
if err != nil {
return nil, 0, "", mutationLibvirtError("create imported image volume", err)
return nil, 0, "", operation.MarkUncertain(mutationLibvirtError("create imported image volume", err))
}
stream, err := l.conn.NewStream(0)
if err != nil {

@ -124,9 +124,9 @@ func (l *Libvirt) ChangeNetwork(ctx context.Context, uuid string, request Change
expected.Gateway != request.Gateway || !slices.Equal(expected.DNSServers, request.DNSServers) {
return VMMetadata{}, NewError(ErrConflict, "reconciliation_descriptor_mismatch", "network request does not match its durable reconciliation descriptor", nil)
}
source, ok := l.local.NetworkSelectors[request.NetworkSelector]
if !ok {
return VMMetadata{}, NewError(ErrInvalid, "network_not_found", "host network selector is not configured", nil)
source, err := l.ResolveNetworkSelector(ctx, request.NetworkSelector)
if err != nil {
return VMMetadata{}, err
}
if expected.NetworkSourceType != source.Type || expected.NetworkSourceName != source.Source {
return VMMetadata{}, NewError(ErrConflict, "reconciliation_descriptor_mismatch", "network source does not match its durable reconciliation descriptor", nil)
@ -213,11 +213,9 @@ func (l *Libvirt) ResolveNetworkSelector(ctx context.Context, selector string) (
if err := ctx.Err(); err != nil {
return LocalNetworkSource{}, err
}
source, ok := l.local.NetworkSelectors[selector]
if !ok {
return LocalNetworkSource{}, NewError(ErrInvalid, "network_not_found", "host network selector is not configured", nil)
}
return source, nil
return resolveConfiguredNetworkSelector(
l.local.NetworkSelectors, selector, l.probeNetworkSource,
)
}
func (l *Libvirt) replaceSeedAndDefinition(seed *libvirt.StorageVol, originalSeed, replacement []byte, originalXML, updatedXML string, restart bool) error {
@ -227,7 +225,7 @@ func (l *Libvirt) replaceSeedAndDefinition(seed *libvirt.StorageVol, originalSee
}
if uint64(len(replacement)) > info.Capacity {
if err := seed.Resize(uint64(len(replacement)), 0); err != nil {
return mutationLibvirtError("grow NoCloud volume", err)
return operation.MarkUncertain(mutationLibvirtError("grow NoCloud volume", err))
}
}
seedChanged := false
@ -250,7 +248,7 @@ func (l *Libvirt) replaceSeedAndDefinition(seed *libvirt.StorageVol, originalSee
if definitionChanged && restart {
active, inspectErr := defined.IsActive()
if inspectErr != nil || active {
return operation.MarkUncertain(errors.Join(mutationLibvirtError("start updated domain", err), translateLibvirtError("inspect updated domain after start failure", inspectErr)))
return operation.MarkUncertain(errors.Join(mutationLibvirtError("start updated domain", err), translateOptionalLibvirtError("inspect updated domain after start failure", inspectErr)))
}
}
original, rollbackErr := l.conn.DomainDefineXML(originalXML)
@ -264,7 +262,7 @@ func (l *Libvirt) replaceSeedAndDefinition(seed *libvirt.StorageVol, originalSee
}
}
if rollbackErr != nil || definitionChanged {
return operation.MarkUncertain(errors.Join(mutationLibvirtError("apply VM definition", err), mutationLibvirtError("roll back VM definition", rollbackErr)))
return operation.MarkUncertain(errors.Join(mutationLibvirtError("apply VM definition", err), optionalMutationLibvirtError("roll back VM definition", rollbackErr)))
}
return mutationLibvirtError("apply VM definition", err)
}
@ -294,29 +292,19 @@ func (l *Libvirt) SetNetworkState(ctx context.Context, uuid string, enabled bool
if !persistent {
return NewError(ErrConflict, "persistent_vm_required", "network state can only be changed for a persistent VM", nil)
}
state := "down"
if enabled {
state = "up"
}
inactive, err := domain.GetXMLDesc(libvirt.DOMAIN_XML_INACTIVE)
if err != nil {
return translateLibvirtError("read inactive domain XML", err)
}
var definition libvirtxml.Domain
if err := definition.Unmarshal(inactive); err != nil || definition.Devices == nil || len(definition.Devices.Interfaces) == 0 {
return NewError(ErrConflict, "network_layout_changed", "domain has no managed network interfaces", err)
documents, err := networkInterfaceLinkDocuments(inactive, enabled)
if err != nil {
return err
}
active, err := domain.IsActive()
if err != nil {
return translateLibvirtError("check domain activity", err)
}
for index := range definition.Devices.Interfaces {
iface := definition.Devices.Interfaces[index]
iface.Link = &libvirtxml.DomainInterfaceLink{State: state}
document, marshalErr := iface.Marshal()
if marshalErr != nil {
return marshalErr
}
for _, document := range documents {
if err := domain.UpdateDeviceFlags(document, libvirt.DOMAIN_DEVICE_MODIFY_CONFIG); err != nil {
return operation.MarkUncertain(mutationLibvirtError("persist interface link state", err))
}
@ -329,6 +317,28 @@ func (l *Libvirt) SetNetworkState(ctx context.Context, uuid string, enabled bool
return nil
}
func networkInterfaceLinkDocuments(document string, enabled bool) ([]string, error) {
var definition libvirtxml.Domain
if err := definition.Unmarshal(document); err != nil || definition.Devices == nil || len(definition.Devices.Interfaces) == 0 {
return nil, NewError(ErrConflict, "network_layout_changed", "domain has no managed network interfaces", err)
}
state := "down"
if enabled {
state = "up"
}
documents := make([]string, 0, len(definition.Devices.Interfaces))
for index := range definition.Devices.Interfaces {
iface := definition.Devices.Interfaces[index]
iface.Link = &libvirtxml.DomainInterfaceLink{State: state}
encoded, err := iface.Marshal()
if err != nil {
return nil, err
}
documents = append(documents, encoded)
}
return documents, nil
}
func (l *Libvirt) SetServiceState(ctx context.Context, uuid string, enabled bool, request ServiceStateRequest) (VMState, error) {
expected, err := expectedMutationState(ctx, operation.ExpectedServiceState)
if err != nil {
@ -355,27 +365,30 @@ func (l *Libvirt) SetServiceState(ctx context.Context, uuid string, enabled bool
return VMState{}, NewError(ErrConflict, "persistent_vm_required", "service state can only be changed for a persistent VM", nil)
}
if enabled {
if err := domain.SetAutostart(true); err != nil {
return VMState{}, mutationLibvirtError("enable domain autostart", err)
if err := setServiceAutostart(domain, true); err != nil {
return VMState{}, err
}
active, err := domain.IsActive()
if err != nil {
return VMState{}, translateLibvirtError("check domain activity", err)
return VMState{}, operation.MarkUncertain(translateLibvirtError("check domain activity after enabling service", err))
}
if request.StartIfSuspended && !active {
if err := domain.Create(); err != nil {
if confirmed, confirmErr := domain.IsActive(); confirmErr != nil || !confirmed {
return VMState{}, operation.MarkUncertain(mutationLibvirtError("start service-resumed domain", err))
return VMState{}, operation.MarkUncertain(errors.Join(
mutationLibvirtError("start service-resumed domain", err),
translateOptionalLibvirtError("confirm service-resumed domain", confirmErr),
))
}
}
}
} else {
if err := domain.SetAutostart(false); err != nil {
return VMState{}, mutationLibvirtError("disable domain autostart", err)
if err := setServiceAutostart(domain, false); err != nil {
return VMState{}, err
}
active, err := domain.IsActive()
if err != nil {
return VMState{}, translateLibvirtError("check domain activity", err)
return VMState{}, operation.MarkUncertain(translateLibvirtError("check domain activity after disabling service", err))
}
if active {
shutdownErr := domain.ShutdownFlags(libvirt.DOMAIN_SHUTDOWN_ACPI_POWER_BTN)
@ -395,6 +408,9 @@ func (l *Libvirt) SetServiceState(ctx context.Context, uuid string, enabled bool
}
}
}
if _, err := confirmServiceTargetState(domain, enabled, request.StartIfSuspended); err != nil {
return VMState{}, err
}
state, reason, err := domain.GetState()
if err != nil {
return VMState{}, operation.MarkUncertain(translateLibvirtError("confirm service state", err))
@ -403,7 +419,64 @@ func (l *Libvirt) SetServiceState(ctx context.Context, uuid string, enabled bool
return VMState{UUID: uuid, Name: name, State: mapDomainState(state), Reason: reason}, nil
}
type serviceStateDomainControl interface {
SetAutostart(bool) error
GetAutostart() (bool, error)
IsActive() (bool, error)
}
func setServiceAutostart(domain serviceStateDomainControl, enabled bool) error {
if err := domain.SetAutostart(enabled); err != nil {
label := "enable domain autostart"
if !enabled {
label = "disable domain autostart"
}
return operation.MarkUncertain(mutationLibvirtError(label, err))
}
return nil
}
func confirmServiceTargetState(domain serviceStateDomainControl, enabled,
startIfSuspended bool) (bool, error) {
autostart, err := domain.GetAutostart()
if err != nil {
return false, operation.MarkUncertain(translateLibvirtError(
"confirm service autostart", err,
))
}
active, err := domain.IsActive()
if err != nil {
return false, operation.MarkUncertain(translateLibvirtError(
"confirm service activity", err,
))
}
if autostart != enabled || (!enabled && active) ||
(enabled && startIfSuspended && !active) {
return active, operation.MarkUncertain(NewError(
ErrConflict, "service_state_unconfirmed",
"service state did not reach the requested target", nil,
))
}
return active, nil
}
func translateOptionalLibvirtError(label string, err error) error {
if err == nil {
return nil
}
return translateLibvirtError(label, err)
}
func optionalMutationLibvirtError(label string, err error) error {
if err == nil {
return nil
}
return mutationLibvirtError(label, err)
}
func (l *Libvirt) GetMetrics(ctx context.Context, uuid string) (Metrics, error) {
unlockSample := l.traffic.lockSample(uuid)
defer unlockSample()
domain, err := l.domainByUUID(ctx, uuid)
if err != nil {
return Metrics{}, err
@ -413,13 +486,15 @@ func (l *Libvirt) GetMetrics(ctx context.Context, uuid string) (Metrics, error)
if err != nil {
return Metrics{}, translateLibvirtError("read domain metrics", err)
}
result := Metrics{UUID: uuid, CollectedAt: time.Now().UTC(), CPUTimeNS: info.CpuTime, MemoryUsedKiB: info.Memory}
result := Metrics{UUID: uuid, CollectedAt: time.Now().UTC(), CPUTimeNS: info.CpuTime}
active, err := domain.IsActive()
if err != nil {
return Metrics{}, translateLibvirtError("check domain activity for metrics", err)
}
if !active {
totalRX, totalTX, observeErr := l.traffic.observe(uuid, result.CollectedAt, 0, 0)
totalRX, totalTX, observeErr := l.traffic.observe(
uuid, result.CollectedAt, availableTrafficObservation(0, 0),
)
if observeErr != nil {
return Metrics{}, NewError(ErrUnavailable, "traffic_state_unavailable", "durable traffic counters could not be updated", observeErr)
}
@ -434,6 +509,21 @@ func (l *Libvirt) GetMetrics(ctx context.Context, uuid string) (Metrics, error)
if err := definition.Unmarshal(document); err != nil {
return Metrics{}, fmt.Errorf("parse live domain XML for metrics: %w", err)
}
memoryStats, memoryErr := domain.MemoryStats(uint32(libvirt.DOMAIN_MEMORY_STAT_NR), 0)
if memoryErr == nil {
usage := memoryUsageStats{}
for _, stat := range memoryStats {
value := stat.Val
switch libvirt.DomainMemoryStatTags(stat.Tag) {
case libvirt.DOMAIN_MEMORY_STAT_AVAILABLE:
usage.AvailableKiB = &value
case libvirt.DOMAIN_MEMORY_STAT_UNUSED:
usage.UnusedKiB = &value
}
}
result.MemoryUsedKiB = estimateMemoryUsedKiB(usage)
}
interfaceSamples := make([]interfaceTrafficSample, 0)
if definition.Devices != nil {
for _, disk := range definition.Devices.Disks {
if disk.Target == nil || disk.Device != "disk" {
@ -452,21 +542,22 @@ func (l *Libvirt) GetMetrics(ctx context.Context, uuid string) (Metrics, error)
}
for _, iface := range definition.Devices.Interfaces {
if iface.Target == nil || iface.Target.Dev == "" {
interfaceSamples = append(interfaceSamples, interfaceTrafficSample{})
continue
}
stats, statErr := domain.InterfaceStats(iface.Target.Dev)
if statErr != nil {
return Metrics{}, translateLibvirtError("read domain network metrics", statErr)
}
if stats.RxBytes > 0 {
result.RXBytes += uint64(stats.RxBytes)
}
if stats.TxBytes > 0 {
result.TXBytes += uint64(stats.TxBytes)
}
interfaceSamples = append(interfaceSamples, interfaceTrafficSample{
TargetAvailable: true,
RXSet: stats.RxBytesSet, RXBytes: stats.RxBytes,
TXSet: stats.TxBytesSet, TXBytes: stats.TxBytes,
})
}
}
totalRX, totalTX, err := l.traffic.observe(uuid, result.CollectedAt, result.RXBytes, result.TXBytes)
observation := aggregateInterfaceTraffic(interfaceSamples)
totalRX, totalTX, err := l.traffic.observe(uuid, result.CollectedAt, observation)
if err != nil {
return Metrics{}, NewError(ErrUnavailable, "traffic_state_unavailable", "durable traffic counters could not be updated", err)
}
@ -840,6 +931,10 @@ func (l *Libvirt) ExitRescue(ctx context.Context, uuid string, request ExitRescu
if err != nil {
return RescueState{}, err
}
liveLinkDocuments, err := networkInterfaceLinkDocuments(updated, !*request.NetworkSuspended)
if err != nil {
return RescueState{}, err
}
stagedOriginalStillRunning := state.Staged && active
if active && state.Active {
if _, err := stopForDefinitionChange(ctx, domain); err != nil {
@ -854,18 +949,26 @@ func (l *Libvirt) ExitRescue(ctx context.Context, uuid string, request ExitRescu
if err := defined.SetAutostart(metadata.RescueAutostart); err != nil {
return RescueState{}, operation.MarkUncertain(mutationLibvirtError("preserve normal domain autostart", err))
}
if !stagedOriginalStillRunning {
startWarning := ""
if stagedOriginalStillRunning {
for _, interfaceDocument := range liveLinkDocuments {
if err := defined.UpdateDeviceFlags(interfaceDocument, libvirt.DOMAIN_DEVICE_MODIFY_LIVE); err != nil {
return RescueState{}, operation.MarkUncertain(mutationLibvirtError("restore live normal-domain interface link state", err))
}
}
} else {
if err := defined.Create(); err != nil {
observed, inspectErr := l.rescueState(defined)
if inspectErr == nil && !observed.Active && !observed.Staged {
isActive, activeErr := defined.IsActive()
if activeErr == nil && isActive {
observed.NetworkSuspended = *request.NetworkSuspended
observed.Warning = "normal guest is running although libvirt reported a start error"
return observed, nil
startWarning = "normal guest is running although libvirt reported a start error"
} else {
return RescueState{}, operation.MarkUncertain(errors.Join(mutationLibvirtError("start domain after rescue", err), inspectErr, translateOptionalLibvirtError("inspect normal domain after start failure", activeErr)))
}
} else {
return RescueState{}, operation.MarkUncertain(errors.Join(mutationLibvirtError("start domain after rescue", err), inspectErr))
}
return RescueState{}, operation.MarkUncertain(errors.Join(mutationLibvirtError("start domain after rescue", err), inspectErr))
}
}
observed, err := l.rescueState(defined)
@ -876,7 +979,12 @@ func (l *Libvirt) ExitRescue(ctx context.Context, uuid string, request ExitRescu
if err != nil || !running {
return RescueState{}, operation.MarkUncertain(errors.Join(NewError(ErrConflict, "rescue_exit_unconfirmed", "normal guest is not running after rescue exit", nil), err))
}
live, err := defined.GetXMLDesc(0)
if err != nil || !domainNetworkLinksMatch(live, !*request.NetworkSuspended) {
return RescueState{}, operation.MarkUncertain(errors.Join(NewError(ErrConflict, "rescue_exit_network_unconfirmed", "normal guest live network state could not be confirmed after rescue exit", nil), translateOptionalLibvirtError("read live normal-domain network state", err)))
}
observed.NetworkSuspended = *request.NetworkSuspended
observed.Warning = startWarning
return observed, nil
}

@ -113,7 +113,9 @@ func (l *Libvirt) reconcileSettings(record operation.Record, domain *libvirt.Dom
}
seedMarker, markerErr := seedMetadataMarker(seed, "virt-cloud-settings-operation")
if markerErr != nil {
return resolvedExpectedFailure("settings_transition_incomplete", "host evidence confirms the settings transition is incomplete"), nil
// A rewritten or damaged seed is evidence that the first phase may
// have crossed its commit boundary. It is not proof of failure.
return operation.Resolution{}, nil
}
domainMatches := metadata.SettingsTransitionID == expected.TransitionID
seedMatches := seedMarker == expected.TransitionID
@ -121,7 +123,10 @@ func (l *Libvirt) reconcileSettings(record operation.Record, domain *libvirt.Dom
return classifyTransitionMarkers("settings", domainMatches, seedMatches), nil
}
if expected.HostnameChanged && metadata.Hostname != expected.Hostname {
return resolvedExpectedFailure("settings_state_mismatch", "host evidence does not match the expected hostname"), nil
// Both durable markers belong to this operation, so it crossed the
// commit boundary. A mismatched payload can be corruption or a later
// out-of-band edit; it is not evidence that PHP may roll state back.
return operation.Resolution{}, nil
}
result, err := metadataFromXML(document)
if err != nil {
@ -151,8 +156,11 @@ func (l *Libvirt) reconcileNetworkChange(record operation.Record, domain *libvir
return expectedEvidenceError("network", err)
}
seedMarker, markerErr := seedMetadataMarker(seed, "virt-cloud-network-operation")
if markerErr != nil {
return operation.Resolution{}, nil
}
domainMatches := metadata.NetworkTransitionID == expected.TransitionID
seedMatches := markerErr == nil && seedMarker == expected.TransitionID
seedMatches := seedMarker == expected.TransitionID
if !domainMatches || !seedMatches {
return classifyTransitionMarkers("network", domainMatches, seedMatches), nil
}
@ -164,7 +172,10 @@ func (l *Libvirt) reconcileNetworkChange(record operation.Record, domain *libvir
definition.Devices == nil || len(definition.Devices.Interfaces) != 1 || definition.Devices.Interfaces[0].MAC == nil ||
!strings.EqualFold(definition.Devices.Interfaces[0].MAC.Address, mac) ||
!domainNetworkSourceMatches(definition.Devices.Interfaces[0], expected.NetworkSourceType, expected.NetworkSourceName) {
return resolvedExpectedFailure("network_state_mismatch", "host evidence does not match the expected network state"), nil
// Matching transition markers prove that both phases wrote state for
// this operation. A payload mismatch is therefore ambiguous and must
// not authorize PHP to release or restore an address assignment.
return operation.Resolution{}, nil
}
result, err := metadataFromXML(document)
if err != nil {
@ -237,31 +248,40 @@ func (l *Libvirt) reconcileFirewall(record operation.Record, domain *libvirt.Dom
if err != nil {
return expectedEvidenceError("firewall", err)
}
domainMatches := metadata.FirewallTransitionID == expected.TransitionID && metadata.Firewall != nil &&
metadata.Firewall.Revision == expected.FirewallRevision && metadata.Firewall.Digest == expected.FirewallDigest
filterMatches := false
if metadata.Firewall != nil {
policy := firewallFromMetadata(metadata.Firewall)
validated, validateErr := validateFirewallPolicy(policy)
if validateErr == nil && validated.PolicyDigest == expected.FirewallDigest {
filter, lookupErr := l.lookupOptionalNetworkFilter(networkFilterName(record.ResourceID))
if lookupErr != nil {
return operation.Resolution{}, lookupErr
}
if filter != nil {
document, readErr := filter.GetXMLDesc(0)
filter.Free()
if readErr != nil {
return operation.Resolution{}, translateLibvirtError("read firewall filter for reconciliation", readErr)
}
filterMatches = firewallDocumentMatchesPolicy(document, validated)
}
filter, err := l.lookupOptionalNetworkFilter(networkFilterName(record.ResourceID))
if err != nil {
return operation.Resolution{}, err
}
if filter == nil {
return operation.Resolution{}, nil
}
filterDocument, err := filter.GetXMLDesc(0)
filter.Free()
if err != nil {
return operation.Resolution{}, translateLibvirtError("read firewall filter for reconciliation", err)
}
domainMarker := metadata.FirewallTransitionID == expected.TransitionID
domainMatches := domainMarker && metadata.Firewall != nil &&
metadata.Firewall.Revision == expected.FirewallRevision &&
metadata.Firewall.Digest == expected.FirewallDigest
if domainMatches {
policy, validateErr := validateFirewallPolicy(firewallFromMetadata(metadata.Firewall))
if validateErr != nil || policy.PolicyDigest != expected.FirewallDigest ||
!firewallDocumentMatchesPolicy(filterDocument, policy) {
// Domain metadata committed this operation, but the filter cannot be
// proven to match it. Never report failure and roll PHP state back.
return operation.Resolution{}, nil
}
return resolvedExpectedSuccess(policy)
}
if !domainMatches || !filterMatches {
return classifyTransitionMarkers("firewall", domainMatches, filterMatches), nil
if domainMarker || !firewallDocumentMatchesStoredState(filterDocument, metadata.Firewall) {
// Either this operation wrote only the filter, or the domain marker is
// present with malformed/stale policy metadata. Both are half-commit
// evidence, so keep the exact operation uncertain.
return operation.Resolution{}, nil
}
return resolvedExpectedSuccess(firewallFromMetadata(metadata.Firewall))
return resolvedExpectedFailure("firewall_not_committed", "host evidence confirms the operation did not commit its transition markers"), nil
}
func (l *Libvirt) managedSeedContents(uuid string) ([]byte, error) {
@ -336,22 +356,57 @@ func firewallDocumentMatchesPolicy(document string, policy FirewallPolicy) bool
return err == nil && normalized == expected
}
// firewallDocumentMatchesStoredState proves that the filter still represents
// the policy durably recorded before an operation. A nil policy means the
// untouched platform filter, which must contain no user/default policy rules.
func firewallDocumentMatchesStoredState(document string, stored *domainFirewallMetadataXML) bool {
if stored != nil {
policy, err := validateFirewallPolicy(firewallFromMetadata(stored))
return err == nil && firewallDocumentMatchesPolicy(document, policy)
}
var current libvirtxml.NWFilter
if current.Unmarshal(document) != nil {
return false
}
for _, entry := range current.Entries {
comment := nwfilterRuleComment(entry.Rule)
if strings.HasPrefix(comment, "virt-user:") || strings.HasPrefix(comment, "virt-default:") {
return false
}
}
return true
}
func classifyTransitionMarkers(kind string, primary, secondary bool) operation.Resolution {
if !primary && !secondary {
return resolvedExpectedFailure(kind+"_not_committed", "host evidence confirms the operation did not commit its transition markers")
}
return resolvedExpectedFailure(kind+"_transition_incomplete", "host evidence confirms the operation stopped during its transition")
// One matching marker proves that the mutation crossed its first commit
// boundary. It does not prove which side contains the authoritative state:
// for example, a network seed may already contain the new public address
// while the persistent domain still has the old bridge. Finalizing this as
// a failure would let PHP release or roll back resources that the guest may
// already be using. Keep the exact operation uncertain for administrator
// reconciliation; never replay the original two-phase mutation.
return operation.Resolution{}
}
func expectedStateResourceAbsent(_ operation.Record) operation.Resolution {
return resolvedExpectedFailure("expected_state_resource_absent", "host evidence confirms the target VM is absent and the expected state cannot be satisfied")
}
func expectedEvidenceError(kind string, err error) (operation.Resolution, error) {
func expectedEvidenceError(_ string, err error) (operation.Resolution, error) {
if errors.Is(err, ErrUnavailable) {
return operation.Resolution{}, err
}
return resolvedExpectedFailure(kind+"_evidence_invalid", "host evidence cannot satisfy the expected state"), nil
// Missing, malformed, or ownership-inconsistent evidence cannot prove that
// an expected-state mutation did not commit. In particular, a network
// change may already have written the requested address into either the
// domain definition or NoCloud seed. Finalizing it as failed would let the
// panel release that address while the guest may still be using it. Keep the
// exact operation uncertain until an administrator restores readable
// evidence; never infer a safe rollback from damaged host state.
return operation.Resolution{}, nil
}
func resolvedExpectedFailure(code, message string) operation.Resolution {
@ -398,6 +453,10 @@ func (l *Libvirt) reconcileRescue(record operation.Record, domain *libvirt.Domai
if activeErr != nil || !active {
return operation.Resolution{}
}
live, liveErr := domain.GetXMLDesc(0)
if liveErr != nil || !domainNetworkLinksMatch(live, !expectedSuspended) {
return operation.Resolution{}
}
state.NetworkSuspended = expectedSuspended
encoded, _ := json.Marshal(state)
return operation.Resolution{Resolved: true, Succeeded: true, Result: encoded}
@ -419,7 +478,7 @@ func (l *Libvirt) reconcileReinstall(record operation.Record, domain *libvirt.Do
if replacement != nil {
replacement.Free()
}
if metadata.RootVolumeName == replacementName && replacementExists && metadata.DiskTransitionKind == "reinstall" && metadata.DiskTransitionID == record.OperationID {
if diskTransitionCommitted(metadata, replacementName, "reinstall", record.OperationID) && replacementExists {
result, parseErr := metadataFromXML(document)
if parseErr != nil {
return operation.Resolution{}
@ -428,15 +487,30 @@ func (l *Libvirt) reconcileReinstall(record operation.Record, domain *libvirt.Do
if stateErr != nil {
return operation.Resolution{}
}
if metadata.DiskTransitionRunning && state != libvirt.DOMAIN_RUNNING && state != libvirt.DOMAIN_BLOCKED {
return operation.Resolution{}
if diskTransitionMarkerMatches(metadata, "reinstall", record.OperationID) {
if metadata.DiskTransitionRunning && state != libvirt.DOMAIN_RUNNING && state != libvirt.DOMAIN_BLOCKED {
return operation.Resolution{}
}
if !metadata.DiskTransitionRunning && state != libvirt.DOMAIN_SHUTOFF && state != libvirt.DOMAIN_SHUTDOWN {
return operation.Resolution{}
}
}
if !metadata.DiskTransitionRunning && state != libvirt.DOMAIN_SHUTOFF && state != libvirt.DOMAIN_SHUTDOWN {
return operation.Resolution{}
if metadata.PendingCleanupVolume != "" {
cleaned, cleanErr := l.completeDiskTransitionCleanup(
domain, document, metadata, "reinstall", record.OperationID,
)
if cleanErr != nil {
return operation.Resolution{}
}
document = cleaned
result, parseErr = metadataFromXML(document)
if parseErr != nil {
return operation.Resolution{}
}
}
result.Status = mapDomainState(state)
result.ReinstallCommitted = true
result.CleanupPending = metadata.PendingCleanupVolume != ""
result.CleanupPending = false
encoded, _ := json.Marshal(result)
return operation.Resolution{Resolved: true, Succeeded: true, Result: encoded}
}
@ -452,7 +526,7 @@ func (l *Libvirt) reconcileSnapshot(record operation.Record, domain *libvirt.Dom
return operation.Resolution{}
}
key := parts[1]
_, metadata, err := requireManagedDomain(domain)
document, metadata, err := requireManagedDomain(domain)
if err != nil {
return operation.Resolution{}
}
@ -488,6 +562,24 @@ func (l *Libvirt) reconcileSnapshot(record operation.Record, domain *libvirt.Dom
if stored == nil && !snapshotExists {
return operation.Resolution{Resolved: true, Succeeded: false, ErrorCode: "snapshot_not_created", ErrorMessage: "host evidence confirms the snapshot volume is absent"}
}
if stored == nil && snapshotExists {
if err := l.deleteSnapshotVolumeDuringReconcile(domain,
record.ResourceID, key, snapshot); err != nil {
return operation.Resolution{}
}
return operation.Resolution{Resolved: true, Succeeded: false,
ErrorCode: "snapshot_not_created",
ErrorMessage: "snapshot data completed without durable metadata and was rolled back"}
}
if stored != nil && !snapshotExists {
if _, err := l.removeSnapshotMetadataDuringReconcile(domain,
document, key); err != nil {
return operation.Resolution{}
}
return operation.Resolution{Resolved: true, Succeeded: false,
ErrorCode: "snapshot_not_created",
ErrorMessage: "snapshot metadata had no managed volume and was removed"}
}
case "delete-snapshot":
if len(parts) != 2 {
return operation.Resolution{}
@ -499,6 +591,22 @@ func (l *Libvirt) reconcileSnapshot(record operation.Record, domain *libvirt.Dom
if stored != nil && snapshotExists {
return operation.Resolution{Resolved: true, Succeeded: false, ErrorCode: "snapshot_not_deleted", ErrorMessage: "host evidence confirms the snapshot remains present"}
}
if stored != nil && !snapshotExists {
if _, err := l.removeSnapshotMetadataDuringReconcile(domain,
document, key); err != nil {
return operation.Resolution{}
}
result, _ := json.Marshal(SnapshotMutationResult{SnapshotKey: key, Deleted: true})
return operation.Resolution{Resolved: true, Succeeded: true, Result: result}
}
if stored == nil && snapshotExists {
if err := l.deleteSnapshotVolumeDuringReconcile(domain,
record.ResourceID, key, snapshot); err != nil {
return operation.Resolution{}
}
result, _ := json.Marshal(SnapshotMutationResult{SnapshotKey: key, Deleted: true})
return operation.Resolution{Resolved: true, Succeeded: true, Result: result}
}
case "restore-snapshot":
if len(parts) != 2 || stored == nil || !snapshotExists {
return operation.Resolution{}
@ -512,18 +620,27 @@ func (l *Libvirt) reconcileSnapshot(record operation.Record, domain *libvirt.Dom
if replacement != nil {
replacement.Free()
}
if metadata.RootVolumeName == replacementName && replacementExists && metadata.DiskTransitionKind == "snapshot_restore" && metadata.DiskTransitionID == record.OperationID {
if diskTransitionCommitted(metadata, replacementName, "snapshot_restore", record.OperationID) && replacementExists {
state, _, stateErr := domain.GetState()
if stateErr != nil {
return operation.Resolution{}
}
if metadata.DiskTransitionRunning && state != libvirt.DOMAIN_RUNNING && state != libvirt.DOMAIN_BLOCKED {
return operation.Resolution{}
if diskTransitionMarkerMatches(metadata, "snapshot_restore", record.OperationID) {
if metadata.DiskTransitionRunning && state != libvirt.DOMAIN_RUNNING && state != libvirt.DOMAIN_BLOCKED {
return operation.Resolution{}
}
if !metadata.DiskTransitionRunning && state != libvirt.DOMAIN_SHUTOFF && state != libvirt.DOMAIN_SHUTDOWN {
return operation.Resolution{}
}
}
if !metadata.DiskTransitionRunning && state != libvirt.DOMAIN_SHUTOFF && state != libvirt.DOMAIN_SHUTDOWN {
return operation.Resolution{}
if metadata.PendingCleanupVolume != "" {
if _, cleanErr := l.completeDiskTransitionCleanup(
domain, document, metadata, "snapshot_restore", record.OperationID,
); cleanErr != nil {
return operation.Resolution{}
}
}
result, _ := json.Marshal(SnapshotMutationResult{SnapshotKey: key, Restored: true, PowerState: mapDomainState(state), ActiveVolumeName: replacementName, CleanupPending: metadata.PendingCleanupVolume != ""})
result, _ := json.Marshal(SnapshotMutationResult{SnapshotKey: key, Restored: true, PowerState: mapDomainState(state), ActiveVolumeName: replacementName, CleanupPending: false})
return operation.Resolution{Resolved: true, Succeeded: true, Result: result}
}
if !replacementExists && metadata.DiskTransitionID != record.OperationID {
@ -532,3 +649,169 @@ func (l *Libvirt) reconcileSnapshot(record operation.Record, domain *libvirt.Dom
}
return operation.Resolution{}
}
func (l *Libvirt) deleteSnapshotVolumeDuringReconcile(domain *libvirt.Domain,
uuid, key string, volume *libvirt.StorageVol) error {
if volume == nil || snapshotVolumeName(uuid, key) == "" {
return NewError(ErrConflict, "snapshot_cleanup_invalid",
"snapshot cleanup target is invalid", nil)
}
if err := ensureNoActiveDomainJobIfRunning(domain); err != nil {
return err
}
if _, err := validateQCOW2Volume(volume, 0); err != nil {
return err
}
path, err := volume.GetPath()
if err != nil {
return translateLibvirtError("resolve snapshot cleanup volume", err)
}
referenced, err := l.anyDomainUsesPath(path)
if err != nil {
return err
}
if referenced {
return NewError(ErrConflict, "snapshot_in_use",
"snapshot cleanup volume is referenced by a domain", nil)
}
if err := volume.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL); err != nil {
observed, inspectErr := l.lookupOptionalManagedVolume(
l.local.ManagedStoragePool, snapshotVolumeName(uuid, key),
)
if observed != nil {
_ = observed.Free()
}
if inspectErr != nil || observed != nil {
return operation.MarkUncertain(errors.Join(
mutationLibvirtError("delete snapshot cleanup volume", err), inspectErr,
))
}
}
return nil
}
func (l *Libvirt) removeSnapshotMetadataDuringReconcile(_ *libvirt.Domain,
document, key string) (string, error) {
updated, err := mutateManagedMetadata(document, func(stored *domainMetadataXML) error {
kept := stored.Snapshots[:0]
for _, snapshot := range stored.Snapshots {
if snapshot.Key != key {
kept = append(kept, snapshot)
}
}
stored.Snapshots = kept
return nil
})
if err != nil {
return "", err
}
defined, err := l.conn.DomainDefineXML(updated)
if err != nil {
return "", operation.MarkUncertain(mutationLibvirtError(
"remove orphan snapshot metadata", err,
))
}
_ = defined.Free()
return updated, nil
}
// diskTransitionCommitted accepts both the retained completion marker used by
// current Agents and the marker-free state written by older Agents. The root
// volume name is derived from the exact operation ID, so a matching active
// root plus an existing replacement volume is durable commit evidence.
func diskTransitionCommitted(metadata *domainMetadataXML, replacementName, kind,
operationID string) bool {
if metadata == nil || metadata.RootVolumeName != replacementName {
return false
}
if diskTransitionMarkerMatches(metadata, kind, operationID) {
return true
}
return metadata.PendingCleanupVolume == "" &&
metadata.DiskTransitionKind == "" && metadata.DiskTransitionID == ""
}
func diskTransitionMarkerMatches(metadata *domainMetadataXML, kind,
operationID string) bool {
return metadata != nil && metadata.DiskTransitionKind == kind &&
metadata.DiskTransitionID == operationID
}
// completeDiskTransitionCleanup resumes only the deterministic cleanup tail
// after read-only evidence has proved the new root is committed. It never
// repeats the root switch, power action, seed write, or original restore.
func (l *Libvirt) completeDiskTransitionCleanup(domain *libvirt.Domain,
document string, metadata *domainMetadataXML, kind, operationID string) (string, error) {
pending := metadata.PendingCleanupVolume
if pending == "" {
return document, nil
}
if !isVMOwnedRootVolumeName(metadataUUID(document), pending) ||
pending == metadata.RootVolumeName {
return "", NewError(ErrConflict, "disk_transition_cleanup_invalid",
"pending disk cleanup does not identify an old VM-owned root", nil)
}
old, err := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, pending)
if err != nil {
return "", err
}
if old != nil {
if _, err := validateQCOW2Volume(old, 0); err != nil {
_ = old.Free()
return "", err
}
path, err := old.GetPath()
if err != nil {
_ = old.Free()
return "", translateLibvirtError("resolve previous root during reconciliation", err)
}
used, err := l.anyDomainUsesPath(path)
if err != nil {
_ = old.Free()
return "", err
}
if used {
_ = old.Free()
return "", NewError(ErrConflict, kind+"_cleanup_pending",
"committed root transition still references the previous root", nil)
}
deleteErr := old.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
_ = old.Free()
if deleteErr != nil {
observed, inspectErr := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, pending)
if observed != nil {
_ = observed.Free()
}
if inspectErr != nil || observed != nil {
return "", operation.MarkUncertain(errors.Join(
mutationLibvirtError("delete previous root during reconciliation", deleteErr), inspectErr,
))
}
}
}
cleaned, err := mutateManagedMetadata(document, func(stored *domainMetadataXML) error {
stored.PendingCleanupVolume = ""
stored.DiskTransitionKind = kind
stored.DiskTransitionID = operationID
return nil
})
if err != nil {
return "", err
}
defined, err := l.conn.DomainDefineXML(cleaned)
if err != nil {
return "", operation.MarkUncertain(mutationLibvirtError(
"persist completed disk cleanup", err,
))
}
_ = defined.Free()
return cleaned, nil
}
func metadataUUID(document string) string {
var definition libvirtxml.Domain
if definition.Unmarshal(document) != nil {
return ""
}
return definition.UUID
}

@ -116,11 +116,14 @@ func (l *Libvirt) Reinstall(ctx context.Context, uuid string, request ReinstallR
}
replacement, err := managedPool.StorageVolCreateXMLFrom(volumeXML, templateVolume, 0)
if err != nil {
if observed, _ := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, replacementName); observed != nil {
observed, inspectErr := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, replacementName)
artifactExists := observed != nil
if observed != nil {
observed.Free()
return VMMetadata{}, operation.MarkUncertain(mutationLibvirtError("clone reinstall system disk", err))
}
return VMMetadata{}, mutationLibvirtError("clone reinstall system disk", err)
return VMMetadata{}, deterministicVolumeCreateFailure(
"clone reinstall system disk", err, inspectErr, artifactExists,
)
}
defer replacement.Free()
if _, err := validateQCOW2Volume(replacement, oldInfo.Capacity); err != nil {
@ -168,9 +171,15 @@ func (l *Libvirt) Reinstall(ctx context.Context, uuid string, request ReinstallR
return nil
})
if err != nil {
_ = l.uploadVolume(seed, originalSeed)
_ = restartOriginalDomain(domain, wasRunning)
_ = replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
seedRollback := l.uploadVolume(seed, originalSeed)
restartErr := restartOriginalDomain(domain, wasRunning)
cleanupErr := replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
if seedRollback != nil || restartErr != nil || cleanupErr != nil {
return VMMetadata{}, operation.MarkUncertain(errors.Join(
err, seedRollback, restartErr,
optionalMutationLibvirtError("roll back reinstall volume", cleanupErr),
))
}
return VMMetadata{}, err
}
defined, err := l.conn.DomainDefineXML(updatedXML)
@ -183,7 +192,10 @@ func (l *Libvirt) Reinstall(ctx context.Context, uuid string, request ReinstallR
restartErr := restartOriginalDomain(domain, wasRunning)
cleanupErr := replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
if seedRollback != nil || restartErr != nil || cleanupErr != nil {
return VMMetadata{}, operation.MarkUncertain(errors.Join(mutationLibvirtError("switch reinstalled system disk", err), seedRollback, restartErr, mutationLibvirtError("roll back reinstall volume", cleanupErr)))
return VMMetadata{}, operation.MarkUncertain(errors.Join(
mutationLibvirtError("switch reinstalled system disk", err), seedRollback, restartErr,
optionalMutationLibvirtError("roll back reinstall volume", cleanupErr),
))
}
return VMMetadata{}, mutationLibvirtError("switch reinstalled system disk", err)
}
@ -213,9 +225,9 @@ func (l *Libvirt) Reinstall(ctx context.Context, uuid string, request ReinstallR
}
cleanXML, err := mutateManagedMetadata(observedXML, func(stored *domainMetadataXML) error {
stored.PendingCleanupVolume = ""
stored.DiskTransitionKind = ""
stored.DiskTransitionID = ""
stored.DiskTransitionRunning = false
// Retain the completed transition marker. If the Agent exits after
// redefining the domain but before persisting journal success, the
// same operation can still prove that this root switch committed.
return nil
})
if err != nil {

@ -4,17 +4,353 @@ package hypervisor
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"time"
"git.luoli.live/root/virt/agent/operation"
"libvirt.org/go/libvirt"
"libvirt.org/go/libvirtxml"
)
type fakeDeleteDomainControl struct {
active []bool
activeErrors []error
destroyErr error
undefineErr error
destroyCalls int
undefine []libvirt.DomainUndefineFlagsValues
}
type fakePowerDomainControl struct {
called string
err error
}
func (f *fakePowerDomainControl) Create() error {
f.called = "start"
return f.err
}
func (f *fakePowerDomainControl) ShutdownFlags(libvirt.DomainShutdownFlags) error {
f.called = "shutdown"
return f.err
}
func (f *fakePowerDomainControl) Reboot(libvirt.DomainRebootFlagValues) error {
f.called = "reboot"
return f.err
}
func (f *fakePowerDomainControl) Reset(uint32) error {
f.called = "reset"
return f.err
}
func (f *fakePowerDomainControl) DestroyFlags(libvirt.DomainDestroyFlags) error {
f.called = "destroy"
return f.err
}
type fakeServiceStateDomainControl struct {
setValue bool
setErr error
autostart bool
autostartErr error
active bool
activeErr error
}
func (f *fakeServiceStateDomainControl) SetAutostart(value bool) error {
f.setValue = value
return f.setErr
}
func (f *fakeServiceStateDomainControl) GetAutostart() (bool, error) {
return f.autostart, f.autostartErr
}
func (f *fakeServiceStateDomainControl) IsActive() (bool, error) {
return f.active, f.activeErr
}
func TestPowerMutationErrorsRemainReconciliable(t *testing.T) {
for _, action := range []PowerAction{
PowerStart, PowerShutdown, PowerReboot, PowerReset, PowerDestroy,
} {
t.Run(string(action), func(t *testing.T) {
cause := errors.New("libvirt response lost")
domain := &fakePowerDomainControl{err: cause}
err := dispatchPowerMutation(domain, action)
if domain.called != string(action) || !operation.IsUncertain(err) ||
!errors.Is(err, cause) {
t.Fatalf("power mutation action=%q called=%q err=%v", action, domain.called, err)
}
})
}
if err := dispatchPowerMutation(&fakePowerDomainControl{}, PowerAction("invalid")); err == nil || operation.IsUncertain(err) {
t.Fatalf("invalid preflight action error = %v", err)
}
for _, test := range []struct {
name string
action PowerAction
state VMStateName
wantOK bool
}{
{"start-running", PowerStart, VMStateRunning, true},
{"start-blocked", PowerStart, VMStateBlocked, true},
{"start-still-off", PowerStart, VMStateShutoff, false},
{"shutdown-off", PowerShutdown, VMStateShutoff, true},
{"shutdown-in-progress", PowerShutdown, VMStateShutdown, false},
{"shutdown-still-running", PowerShutdown, VMStateRunning, false},
{"destroy-off", PowerDestroy, VMStateShutoff, true},
{"destroy-still-running", PowerDestroy, VMStateRunning, false},
{"reboot-observed", PowerReboot, VMStateRunning, true},
{"reset-observed", PowerReset, VMStateRunning, true},
} {
t.Run(test.name, func(t *testing.T) {
err := confirmPowerTargetState(test.action, test.state)
if test.wantOK && err != nil {
t.Fatalf("confirmed target rejected: %v", err)
}
if !test.wantOK && !operation.IsUncertain(err) {
t.Fatalf("unconfirmed target error = %v", err)
}
})
}
}
func TestServiceMutationAndTargetObservationRemainReconciliable(t *testing.T) {
cause := errors.New("libvirt response lost")
for _, enabled := range []bool{false, true} {
domain := &fakeServiceStateDomainControl{setErr: cause}
err := setServiceAutostart(domain, enabled)
if domain.setValue != enabled || !operation.IsUncertain(err) ||
!errors.Is(err, cause) {
t.Fatalf("set autostart enabled=%v err=%v", enabled, err)
}
}
for _, test := range []struct {
name, wantCode string
domain fakeServiceStateDomainControl
enabled, startIfDown bool
wantActive bool
}{
{name: "enabled-running", domain: fakeServiceStateDomainControl{autostart: true, active: true}, enabled: true, startIfDown: true, wantActive: true},
{name: "enabled-stopped-allowed", domain: fakeServiceStateDomainControl{autostart: true}, enabled: true},
{name: "disabled-stopped", domain: fakeServiceStateDomainControl{}, enabled: false},
{name: "autostart-mismatch", wantCode: "uncertain", domain: fakeServiceStateDomainControl{}, enabled: true},
{name: "required-start-missing", wantCode: "uncertain", domain: fakeServiceStateDomainControl{autostart: true}, enabled: true, startIfDown: true},
{name: "disabled-still-active", wantCode: "uncertain", domain: fakeServiceStateDomainControl{active: true}},
{name: "autostart-read-error", wantCode: "uncertain", domain: fakeServiceStateDomainControl{autostartErr: cause}},
{name: "activity-read-error", wantCode: "uncertain", domain: fakeServiceStateDomainControl{activeErr: cause}},
} {
t.Run(test.name, func(t *testing.T) {
active, err := confirmServiceTargetState(
&test.domain, test.enabled, test.startIfDown,
)
if test.wantCode == "" {
if err != nil || active != test.wantActive {
t.Fatalf("target state active=%v err=%v", active, err)
}
return
}
if !operation.IsUncertain(err) {
t.Fatalf("unconfirmed target state error = %v", err)
}
})
}
}
func (f *fakeDeleteDomainControl) IsActive() (bool, error) {
var active bool
if len(f.active) != 0 {
active = f.active[0]
f.active = f.active[1:]
}
var err error
if len(f.activeErrors) != 0 {
err = f.activeErrors[0]
f.activeErrors = f.activeErrors[1:]
}
return active, err
}
func (f *fakeDeleteDomainControl) DestroyFlags(libvirt.DomainDestroyFlags) error {
f.destroyCalls++
return f.destroyErr
}
func (f *fakeDeleteDomainControl) UndefineFlags(flags libvirt.DomainUndefineFlagsValues) error {
f.undefine = append(f.undefine, flags)
return f.undefineErr
}
func TestDeleteDomainContinuationUsesObservedTargetState(t *testing.T) {
t.Run("destroy error but observed inactive continues", func(t *testing.T) {
domain := &fakeDeleteDomainControl{
active: []bool{true, false}, destroyErr: errors.New("destroy response lost"),
}
if err := driveDeleteDomainToAbsent(domain, func() (bool, error) { return true, nil }); err != nil {
t.Fatalf("continue delete after observed stop: %v", err)
}
if domain.destroyCalls != 1 || len(domain.undefine) != 1 {
t.Fatalf("delete stages destroy=%d undefine=%d", domain.destroyCalls, len(domain.undefine))
}
wantFlags := libvirt.DOMAIN_UNDEFINE_NVRAM |
libvirt.DOMAIN_UNDEFINE_SNAPSHOTS_METADATA |
libvirt.DOMAIN_UNDEFINE_CHECKPOINTS_METADATA
if domain.undefine[0] != wantFlags {
t.Fatalf("undefine flags = %v, want %v", domain.undefine[0], wantFlags)
}
})
t.Run("still active after destroy error remains uncertain", func(t *testing.T) {
domain := &fakeDeleteDomainControl{
active: []bool{true, true}, destroyErr: errors.New("destroy failed"),
}
err := driveDeleteDomainToAbsent(domain, func() (bool, error) { return false, nil })
if !operation.IsUncertain(err) || len(domain.undefine) != 0 {
t.Fatalf("active delete continuation err=%v undefine=%d", err, len(domain.undefine))
}
})
t.Run("ambiguous undefine with confirmed absence continues", func(t *testing.T) {
domain := &fakeDeleteDomainControl{
active: []bool{false}, undefineErr: errors.New("undefine response lost"),
}
absenceChecks := 0
err := driveDeleteDomainToAbsent(domain, func() (bool, error) {
absenceChecks++
return true, nil
})
if err != nil || domain.destroyCalls != 0 || len(domain.undefine) != 1 || absenceChecks != 1 {
t.Fatalf("confirmed undefine outcome err=%v destroy=%d undefine=%d checks=%d",
err, domain.destroyCalls, len(domain.undefine), absenceChecks)
}
})
t.Run("ambiguous undefine with remaining domain stays uncertain", func(t *testing.T) {
domain := &fakeDeleteDomainControl{
active: []bool{false}, undefineErr: errors.New("undefine failed"),
}
err := driveDeleteDomainToAbsent(domain, func() (bool, error) { return false, nil })
if !operation.IsUncertain(err) {
t.Fatalf("remaining domain delete error = %v", err)
}
})
t.Run("successful undefine must still prove absence", func(t *testing.T) {
domain := &fakeDeleteDomainControl{active: []bool{false}}
err := driveDeleteDomainToAbsent(domain, func() (bool, error) { return false, nil })
if !operation.IsUncertain(err) || len(domain.undefine) != 1 {
t.Fatalf("unconfirmed successful undefine err=%v undefine=%d", err, len(domain.undefine))
}
})
}
func TestCreateAbsenceCleanupPersistsTrafficStateRemoval(t *testing.T) {
path := filepath.Join(t.TempDir(), "traffic.json")
store, err := openTrafficStore(path)
if err != nil {
t.Fatal(err)
}
uuid := "123e4567-e89b-42d3-a456-426614174000"
if created, err := store.initialize(uuid, time.Unix(1, 0).UTC()); err != nil || !created {
t.Fatalf("initialize traffic state created=%v err=%v", created, err)
}
// Model the post-rename/fsync-error window: the durable file contains the
// entry while the caller has conservatively restored an older in-memory map.
delete(store.entries, uuid)
backend := &Libvirt{traffic: store}
if err := backend.removeAbsentVMTrafficState(uuid); err != nil {
t.Fatalf("remove absent VM traffic state: %v", err)
}
if _, exists := store.entries[uuid]; exists {
t.Fatal("traffic state remained in memory after confirmed VM absence")
}
reopened, err := openTrafficStore(path)
if err != nil {
t.Fatal(err)
}
if _, exists := reopened.entries[uuid]; exists {
t.Fatal("traffic state removal was not persisted before absence confirmation")
}
}
func TestCreateTrafficBaselineCleanupFailureRemainsUncertain(t *testing.T) {
createErr := errors.New("domain definition failed")
cleanupErr := errors.New("traffic state persistence failed")
err := markTrafficCleanupUncertain(createErr, cleanupErr)
if !operation.IsUncertain(err) || !errors.Is(err, createErr) ||
!errors.Is(err, cleanupErr) {
t.Fatalf("traffic cleanup error lost uncertainty or causes: %v", err)
}
}
func TestDomainAbsenceEvidenceRequiresNoDomainCode(t *testing.T) {
if !isNoDomain(libvirt.Error{Code: libvirt.ERR_NO_DOMAIN}) {
t.Fatal("ERR_NO_DOMAIN was not accepted as absence evidence")
}
if isNoDomain(libvirt.Error{Code: libvirt.ERR_RPC}) || isNoDomain(errors.New("lookup failed")) {
t.Fatal("ambiguous domain lookup error was accepted as absence evidence")
}
if !domainMayExistAfterDefine(nil) ||
!domainMayExistAfterDefine(libvirt.Error{Code: libvirt.ERR_RPC}) ||
domainMayExistAfterDefine(libvirt.Error{Code: libvirt.ERR_NO_DOMAIN}) {
t.Fatal("domain definition crash-window evidence was classified unsafely")
}
}
func TestDeterministicVolumeCreateFailureRequiresReliableAbsence(t *testing.T) {
cause := errors.New("clone rejected")
if err := deterministicVolumeCreateFailure("clone", cause, nil, false); operation.IsUncertain(err) {
t.Fatalf("reliably absent clone was left uncertain: %v", err)
}
for _, test := range []struct {
name string
mutationErr error
inspectErr error
artifactFound bool
}{
{name: "artifact-present", mutationErr: cause, artifactFound: true},
{name: "inspection-failed", mutationErr: cause, inspectErr: errors.New("lookup failed")},
{name: "rpc-result-lost", mutationErr: libvirt.Error{Code: libvirt.ERR_RPC}},
} {
t.Run(test.name, func(t *testing.T) {
err := deterministicVolumeCreateFailure(
"clone", test.mutationErr, test.inspectErr, test.artifactFound,
)
if !operation.IsUncertain(err) {
t.Fatalf("ambiguous clone failure = %v", err)
}
})
}
}
func TestSnapshotDeleteNotFoundRequiresMetadataAndVolumeAbsent(t *testing.T) {
absent := validateSnapshotDeletePresence(false, false)
if !errors.Is(absent, ErrNotFound) || errorPublicCode(absent) != "snapshot_not_found" {
t.Fatalf("double-absence snapshot error = %v", absent)
}
orphaned := validateSnapshotDeletePresence(false, true)
if !errors.Is(orphaned, ErrConflict) || errors.Is(orphaned, ErrNotFound) ||
errorPublicCode(orphaned) != "snapshot_artifacts_inconsistent" {
t.Fatalf("orphaned snapshot error = %v", orphaned)
}
for _, presence := range [][2]bool{{true, false}, {true, true}} {
if err := validateSnapshotDeletePresence(presence[0], presence[1]); err != nil {
t.Fatalf("deletable snapshot presence %v rejected: %v", presence, err)
}
}
}
func TestNVRAMCapabilityChecksExistenceWithoutAgentWriteProbe(t *testing.T) {
directory := filepath.Join(t.TempDir(), "nvram")
if err := os.Mkdir(directory, 0o500); err != nil {
@ -32,19 +368,158 @@ func TestNVRAMCapabilityChecksExistenceWithoutAgentWriteProbe(t *testing.T) {
}
}
func TestSnapshotCapabilityRequiresDirectFileBackedPool(t *testing.T) {
for _, test := range []struct {
name, document string
want bool
}{
{"directory", `<pool type="dir"><target><path>/var/lib/libvirt/images</path></target></pool>`, true},
{"filesystem", `<pool type="fs"><target><path>/srv/vms</path></target></pool>`, true},
{"network-filesystem", `<pool type="netfs"><target><path>/mnt/vms</path></target></pool>`, true},
{"logical", `<pool type="logical"><target><path>/dev/vg0</path></target></pool>`, false},
{"rbd", `<pool type="rbd"><source><name>vms</name></source></pool>`, false},
{"relative", `<pool type="dir"><target><path>images</path></target></pool>`, false},
{"root", `<pool type="dir"><target><path>/</path></target></pool>`, false},
{"broken", `<pool`, false},
} {
t.Run(test.name, func(t *testing.T) {
if got := snapshotStoragePoolXMLSupported(test.document); got != test.want {
t.Fatalf("snapshot pool support = %v, want %v", got, test.want)
}
})
}
}
func TestNWFilterCapabilityRequiresReadableCleanTrafficBaseline(t *testing.T) {
if !cleanTrafficFilterXMLValid(`<filter name="clean-traffic" chain="root"/>`) {
t.Fatal("valid clean-traffic baseline was rejected")
}
for _, document := range []string{
`<filter name="other" chain="root"/>`, `<filter`, ``,
} {
if cleanTrafficFilterXMLValid(document) {
t.Fatalf("invalid clean-traffic baseline accepted: %q", document)
}
}
}
func TestManagedNVRAMArtifactMustBeAbsentBeforeCreateFailureIsConfirmed(t *testing.T) {
directory := t.TempDir()
uuid := "123e4567-e89b-42d3-a456-426614174000"
absent, err := managedNVRAMArtifactAbsent(directory, uuid)
if err != nil || !absent {
t.Fatalf("empty NVRAM directory absent=%v err=%v", absent, err)
}
path := filepath.Join(directory, uuid+"_VARS.fd")
if err := os.WriteFile(path, []byte("partial firmware state"), 0o600); err != nil {
t.Fatal(err)
}
absent, err = managedNVRAMArtifactAbsent(directory, strings.ToUpper(uuid))
if err != nil || absent {
t.Fatalf("remaining NVRAM artifact absent=%v err=%v", absent, err)
}
if err := removeManagedNVRAMArtifacts(directory, strings.ToUpper(uuid)); err != nil {
t.Fatalf("remove managed NVRAM artifact: %v", err)
}
absent, err = managedNVRAMArtifactAbsent(directory, uuid)
if err != nil || !absent {
t.Fatalf("cleaned NVRAM artifact absent=%v err=%v", absent, err)
}
symlink := filepath.Join(directory, uuid+"_VARS.fd")
if err := os.Symlink(filepath.Join(directory, "outside"), symlink); err != nil {
t.Fatal(err)
}
if err := removeManagedNVRAMArtifacts(directory, uuid); err == nil {
t.Fatal("symlink NVRAM cleanup target was accepted")
}
}
func TestDomainPathReferenceIncludesFirmwareState(t *testing.T) {
path := "/var/lib/libvirt/qemu/nvram/shared_VARS.fd"
for _, document := range []string{
`<domain><os><nvram>` + path + `</nvram></os></domain>`,
`<domain><os><varstore path="` + path + `"/></os></domain>`,
} {
var definition libvirtxml.Domain
if err := definition.Unmarshal(document); err != nil {
t.Fatal(err)
}
if !domainReferencesPath(&definition, path) {
t.Fatalf("firmware or disk path reference was ignored: %s", document)
}
}
sourceBacked := libvirtxml.Domain{OS: &libvirtxml.DomainOS{
NVRam: &libvirtxml.DomainNVRam{Source: &libvirtxml.DomainDiskSource{
File: &libvirtxml.DomainDiskSourceFile{File: path},
}},
}}
if !domainReferencesPath(&sourceBacked, path) {
t.Fatal("source-backed NVRAM path reference was ignored")
}
diskBacked := libvirtxml.Domain{Devices: &libvirtxml.DomainDeviceList{
Disks: []libvirtxml.DomainDisk{{Source: &libvirtxml.DomainDiskSource{
File: &libvirtxml.DomainDiskSourceFile{File: path},
}}},
}}
if !domainReferencesPath(&diskBacked, path) {
t.Fatal("disk path reference was ignored")
}
var unrelated libvirtxml.Domain
if err := unrelated.Unmarshal(`<domain><os><nvram>/var/lib/libvirt/qemu/nvram/other_VARS.fd</nvram></os></domain>`); err != nil {
t.Fatal(err)
}
if domainReferencesPath(&unrelated, path) {
t.Fatal("unrelated firmware path was treated as a reference")
}
}
func TestDiskTransitionCommitEvidenceSurvivesJournalCrashWindows(t *testing.T) {
replacement := "vreinstall-123e4567e89b42d3a456426614174000-0123456789abcdef.qcow2"
marked := &domainMetadataXML{
RootVolumeName: replacement, PendingCleanupVolume: rootVolumeName("123e4567-e89b-42d3-a456-426614174000"),
DiskTransitionKind: "reinstall", DiskTransitionID: "operation-reinstall-one",
}
if !diskTransitionCommitted(marked, replacement, "reinstall", "operation-reinstall-one") {
t.Fatal("committed transition marker was not accepted")
}
legacyClean := &domainMetadataXML{RootVolumeName: replacement}
if !diskTransitionCommitted(legacyClean, replacement, "reinstall", "operation-reinstall-one") {
t.Fatal("legacy marker-cleared committed root was not accepted")
}
legacyClean.PendingCleanupVolume = rootVolumeName("123e4567-e89b-42d3-a456-426614174000")
if diskTransitionCommitted(legacyClean, replacement, "reinstall", "operation-reinstall-one") {
t.Fatal("marker-free transition with pending cleanup was accepted")
}
marked.RootVolumeName = rootVolumeName("123e4567-e89b-42d3-a456-426614174000")
if diskTransitionCommitted(marked, replacement, "reinstall", "operation-reinstall-one") {
t.Fatal("transition marker without the deterministic active root was accepted")
}
}
func TestPMSuspendedStateUsesPanelProtocolValue(t *testing.T) {
got := mapDomainState(libvirt.DOMAIN_PMSUSPENDED)
if got != VMStateSuspended {
t.Fatalf("PM suspended state = %q", got)
}
if string(got) != "pmsuspended" {
t.Fatalf("PM suspended state = %q", got)
}
}
func TestExpectedTransitionMarkerClassificationNeverRequestsReplay(t *testing.T) {
for _, test := range []struct {
name string
primary, secondary bool
wantCode string
wantResolved bool
}{
{"absent", false, false, "settings_not_committed"},
{"primary-only", true, false, "settings_transition_incomplete"},
{"secondary-only", false, true, "settings_transition_incomplete"},
{"absent", false, false, "settings_not_committed", true},
{"primary-only", true, false, "", false},
{"secondary-only", false, true, "", false},
} {
t.Run(test.name, func(t *testing.T) {
resolution := classifyTransitionMarkers("settings", test.primary, test.secondary)
if !resolution.Resolved || resolution.Succeeded || resolution.ErrorCode != test.wantCode {
if resolution.Resolved != test.wantResolved || resolution.Succeeded || resolution.ErrorCode != test.wantCode {
t.Fatalf("resolution = %#v", resolution)
}
})
@ -72,9 +547,21 @@ func TestMissingVMResolvesExpectedMutationAsFailureWithoutReplay(t *testing.T) {
if err == nil || transient.Resolved {
t.Fatalf("transient evidence read was finalized: resolution=%#v err=%v", transient, err)
}
invalid, err := expectedEvidenceError("settings", NewError(ErrConflict, "managed_metadata_invalid", "invalid metadata", nil))
if err != nil || !invalid.Resolved || invalid.Succeeded || invalid.ErrorCode != "settings_evidence_invalid" {
t.Fatalf("stable invalid evidence was not finalized: resolution=%#v err=%v", invalid, err)
for _, kind := range []string{"network", "settings", "service", "firewall"} {
t.Run(kind+"-invalid-evidence", func(t *testing.T) {
invalid, err := expectedEvidenceError(kind, NewError(ErrConflict,
"managed_metadata_invalid", "invalid metadata", nil))
if err != nil || invalid.Resolved || invalid.Succeeded || invalid.ErrorCode != "" {
t.Fatalf("invalid %s evidence was terminalized: resolution=%#v err=%v", kind, invalid, err)
}
})
t.Run(kind+"-missing-evidence", func(t *testing.T) {
missing, err := expectedEvidenceError(kind, NewError(ErrNotFound,
"seed_not_found", "missing evidence", nil))
if err != nil || missing.Resolved || missing.Succeeded || missing.ErrorCode != "" {
t.Fatalf("missing %s evidence was terminalized: resolution=%#v err=%v", kind, missing, err)
}
})
}
}
@ -116,6 +603,90 @@ func TestNetworkAndFirewallReadOnlyEvidenceMatchers(t *testing.T) {
if firewallDocumentMatchesPolicy(document, other) {
t.Fatal("mismatched firewall evidence was accepted")
}
if !firewallDocumentMatchesStoredState(document, firewallToMetadata(policy)) {
t.Fatal("filter matching stored firewall metadata was rejected")
}
if firewallDocumentMatchesStoredState(document, firewallToMetadata(other)) {
t.Fatal("filter mismatching stored firewall metadata was accepted")
}
baseline := `<filter name="virt-test" chain="root"><filterref filter="clean-traffic"/><rule action="accept" direction="inout" priority="900"><all/></rule></filter>`
if !firewallDocumentMatchesStoredState(baseline, nil) {
t.Fatal("untouched platform filter was rejected as the pre-policy state")
}
if firewallDocumentMatchesStoredState(document, nil) {
t.Fatal("applied user firewall was accepted as an untouched platform filter")
}
}
func TestNetworkInterfaceLinkDocumentsBuildAllUpdatesBeforeMutation(t *testing.T) {
document := `<domain><devices>` +
`<interface type="bridge"><mac address="52:54:00:00:00:01"/><source bridge="br0"/></interface>` +
`<interface type="network"><mac address="52:54:00:00:00:02"/><source network="default"/></interface>` +
`</devices></domain>`
for _, enabled := range []bool{false, true} {
documents, err := networkInterfaceLinkDocuments(document, enabled)
if err != nil || len(documents) != 2 {
t.Fatalf("enabled=%v documents=%d err=%v", enabled, len(documents), err)
}
for _, update := range documents {
var iface libvirtxml.DomainInterface
if err := iface.Unmarshal(update); err != nil {
t.Fatalf("decode interface update: %v", err)
}
want := "down"
if enabled {
want = "up"
}
if iface.Link == nil || iface.Link.State != want {
t.Fatalf("enabled=%v update=%s", enabled, update)
}
}
}
if documents, err := networkInterfaceLinkDocuments(`<domain><devices/></domain>`, false); err == nil || len(documents) != 0 {
t.Fatalf("interface-free document updates=%v err=%v", documents, err)
}
}
func TestCatalogDeleteNotFoundRequiresBothManagedArtifactsAbsent(t *testing.T) {
for _, test := range []struct {
name string
evidence catalogDeleteEvidence
}{
{"template", catalogDeleteEvidence{"template", "template_not_found", "template_artifacts_inconsistent"}},
{"rescue-template", catalogDeleteEvidence{"rescue template", "rescue_template_not_found", "rescue_template_artifacts_inconsistent"}},
{"user-iso", catalogDeleteEvidence{"user ISO", "user_iso_not_found", "user_iso_artifacts_inconsistent"}},
} {
t.Run(test.name, func(t *testing.T) {
absent := validateCatalogDeletePresence(false, false, test.evidence)
if !errors.Is(absent, ErrNotFound) || errorPublicCode(absent) != test.evidence.notFoundCode {
t.Fatalf("double-absence error = %v", absent)
}
for _, presence := range [][2]bool{{true, false}, {false, true}} {
err := validateCatalogDeletePresence(presence[0], presence[1], test.evidence)
if !errors.Is(err, ErrConflict) || errors.Is(err, ErrNotFound) || errorPublicCode(err) != test.evidence.inconsistentCode {
t.Fatalf("inconsistent presence %v error = %v", presence, err)
}
}
if err := validateCatalogDeletePresence(true, true, test.evidence); err != nil {
t.Fatalf("complete presence rejected: %v", err)
}
disappeared := catalogDeleteEvidenceChanged(
NewError(ErrNotFound, "catalog_entry_not_found", "missing", nil),
test.evidence,
)
if !errors.Is(disappeared, ErrConflict) || errors.Is(disappeared, ErrNotFound) || errorPublicCode(disappeared) != test.evidence.inconsistentCode {
t.Fatalf("post-presence disappearance error = %v", disappeared)
}
})
}
}
func errorPublicCode(err error) string {
var public interface{ PublicCode() string }
if !errors.As(err, &public) {
return ""
}
return public.PublicCode()
}
func TestVMManagedVolumeOwnershipIsUUIDScoped(t *testing.T) {
@ -217,7 +788,7 @@ func TestCollectVMManagedVolumeNamesIncludesTransitionsSnapshotsAndOrphans(t *te
func TestCapabilitiesAreDerivedFromRuntimePrerequisites(t *testing.T) {
all := capabilityPrerequisites{
firmwareLoader: true, nvramTemplate: true, nvramDirectory: true,
managedPool: true, templatePool: true, seedPool: true,
managedPool: true, snapshotPool: true, templatePool: true, seedPool: true,
networks: true, nwfilter: true, q35UEFI: true, liveBackup: true,
}
features := all.features()
@ -251,6 +822,111 @@ func TestCapabilitiesAreDerivedFromRuntimePrerequisites(t *testing.T) {
if features.Snapshots {
t.Fatalf("snapshots were advertised without qemu live backup support: %#v", features)
}
unsupportedSnapshotPool := all
unsupportedSnapshotPool.snapshotPool = false
features = unsupportedSnapshotPool.features()
if features.Snapshots || !features.CreateVM || !features.Reinstall {
t.Fatalf("non-file pool did not disable only snapshots: %#v", features)
}
}
func TestNetworkSelectorCapabilityIgnoresUnavailableOptionalSelector(t *testing.T) {
selectors := map[string]LocalNetworkSource{
"public": {Type: "bridge", Source: "br0"},
"private": {Type: "network", Source: "default"},
}
probe := func(source LocalNetworkSource) CapabilityCheck {
if source.Source == "br0" {
return availableCheck()
}
return unavailableCheck(capabilitySelectorUnusable)
}
check, usable := probeNetworkSelectorSet(selectors, probe)
if !check.Available {
t.Fatalf("one usable selector did not satisfy network capability: %#v", check)
}
if !reflect.DeepEqual(usable, []string{"public"}) {
t.Fatalf("usable selectors = %#v", usable)
}
delete(selectors, "public")
if check, usable = probeNetworkSelectorSet(selectors, probe); check.Available || check.Reason != capabilitySelectorUnusable || len(usable) != 0 {
t.Fatalf("unusable selector set = %#v", check)
}
if check, usable = probeNetworkSelectorSet(nil, probe); check.Available || check.Reason != capabilitySelectorMissing || len(usable) != 0 {
t.Fatalf("empty selector set = %#v", check)
}
}
func TestNetworkSelectorCapabilitiesAreSortedAndOmitHostSources(t *testing.T) {
selectors := map[string]LocalNetworkSource{
"zeta": {Type: "bridge", Source: "br-secret-z"},
"private": {Type: "network", Source: "inactive-secret"},
"alpha": {Type: "bridge", Source: "br-secret-a"},
}
check, usable := probeNetworkSelectorSet(selectors,
func(source LocalNetworkSource) CapabilityCheck {
if source.Source == "inactive-secret" {
return unavailableCheck(capabilitySelectorUnusable)
}
return availableCheck()
})
if !check.Available {
t.Fatalf("usable selector set was rejected: %#v", check)
}
if !reflect.DeepEqual(usable, []string{"alpha", "zeta"}) {
t.Fatalf("usable selectors = %#v", usable)
}
for _, selector := range usable {
if strings.Contains(selector, "secret") {
t.Fatalf("host network source leaked as selector: %q", selector)
}
}
}
func TestNetworkSelectorCapabilitiesAreBounded(t *testing.T) {
selectors := make(map[string]LocalNetworkSource,
maxCapabilityNetworkSelectors+1)
for index := 0; index <= maxCapabilityNetworkSelectors; index++ {
selectors[fmt.Sprintf("network-%02d", index)] = LocalNetworkSource{
Type: "bridge", Source: fmt.Sprintf("br%d", index),
}
}
check, usable := probeNetworkSelectorSet(selectors,
func(LocalNetworkSource) CapabilityCheck { return availableCheck() })
if check.Available || check.Reason != capabilityInvalid || len(usable) != 0 {
t.Fatalf("oversized selector capabilities = %#v, %#v", check, usable)
}
}
func TestRequestedNetworkSelectorMustBeUsable(t *testing.T) {
selectors := map[string]LocalNetworkSource{
"public": {Type: "bridge", Source: "br0"},
"private": {Type: "network", Source: "default"},
}
probe := func(source LocalNetworkSource) CapabilityCheck {
if source.Source == "br0" {
return availableCheck()
}
return unavailableCheck(capabilitySelectorUnusable)
}
selected, err := resolveConfiguredNetworkSelector(
selectors, "public", probe,
)
if err != nil || selected.Source != "br0" {
t.Fatalf("usable selector = %#v, %v", selected, err)
}
if _, err := resolveConfiguredNetworkSelector(
selectors, "private", probe,
); !errors.Is(err, ErrUnavailable) {
t.Fatalf("inactive requested selector error = %v", err)
}
if _, err := resolveConfiguredNetworkSelector(
selectors, "missing", probe,
); !errors.Is(err, ErrInvalid) {
t.Fatalf("missing requested selector error = %v", err)
}
}
func TestDomainCapabilitiesRequireConfiguredQ35UEFISecureBootOffCombination(t *testing.T) {

@ -28,6 +28,24 @@ func snapshotRestoreVolumeName(uuid, operationID string) string {
return "vrestore-" + compact + "-" + hex.EncodeToString(sum[:8]) + ".qcow2"
}
func deterministicVolumeCreateFailure(action string, mutationErr, inspectErr error, artifactExists bool) error {
err := mutationLibvirtError(action, mutationErr)
if inspectErr != nil || artifactExists {
return operation.MarkUncertain(errors.Join(err, inspectErr))
}
return err
}
func validateSnapshotDeletePresence(metadataExists, volumeExists bool) error {
if !metadataExists && !volumeExists {
return NewError(ErrNotFound, "snapshot_not_found", "snapshot was not found", nil)
}
if !metadataExists && volumeExists {
return NewError(ErrConflict, "snapshot_artifacts_inconsistent", "snapshot volume exists without managed metadata", nil)
}
return nil
}
func (l *Libvirt) managedRootContext(domain *libvirt.Domain) (string, *libvirtxml.Domain, *domainMetadataXML, *libvirt.StoragePool, *libvirt.StorageVol, error) {
if err := requirePersistentWithoutSnapshots(domain); err != nil {
return "", nil, nil, nil, nil, err
@ -271,7 +289,7 @@ func (l *Libvirt) CreateSnapshot(ctx context.Context, uuid string, request Snaps
}
target, err := pool.StorageVolCreateXML(volumeXML, 0)
if err != nil {
return Snapshot{}, mutationLibvirtError("reserve snapshot volume", err)
return Snapshot{}, operation.MarkUncertain(mutationLibvirtError("reserve snapshot volume", err))
}
targetOwned := true
defer func() {
@ -289,7 +307,12 @@ func (l *Libvirt) CreateSnapshot(ctx context.Context, uuid string, request Snaps
frozen := false
if request.ConsistencyMode == "filesystem" {
if err := domain.FSFreeze(nil, 0); err != nil {
return Snapshot{}, NewError(ErrConflict, "snapshot_guest_agent_unavailable", "QEMU guest agent could not freeze guest filesystems", err)
thawErr := domain.FSThaw(nil, 0)
freezeErr := NewError(ErrConflict, "snapshot_guest_agent_unavailable", "QEMU guest agent could not freeze guest filesystems", err)
if thawErr != nil {
return Snapshot{}, operation.MarkUncertain(errors.Join(freezeErr, mutationLibvirtError("thaw guest filesystems after ambiguous freeze", thawErr)))
}
return Snapshot{}, freezeErr
}
frozen = true
}
@ -300,7 +323,9 @@ func (l *Libvirt) CreateSnapshot(ctx context.Context, uuid string, request Snaps
backupXML, err := backup.Marshal()
if err != nil {
if frozen {
_ = domain.FSThaw(nil, 0)
if thawErr := domain.FSThaw(nil, 0); thawErr != nil {
return Snapshot{}, operation.MarkUncertain(errors.Join(err, mutationLibvirtError("thaw guest filesystems after snapshot preparation", thawErr)))
}
}
return Snapshot{}, err
}
@ -372,17 +397,23 @@ func (l *Libvirt) DeleteSnapshot(ctx context.Context, uuid, key string, _ Snapsh
for _, stored := range metadata.Snapshots {
found = found || stored.Key == key
}
if !found {
return SnapshotMutationResult{}, NewError(ErrNotFound, "snapshot_not_found", "snapshot was not found", nil)
}
if err := ensureNoActiveDomainJobIfRunning(domain); err != nil {
return SnapshotMutationResult{}, err
}
volumeName := snapshotVolumeName(uuid, key)
volume, err := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, volumeName)
if err != nil {
return SnapshotMutationResult{}, err
}
if err := validateSnapshotDeletePresence(found, volume != nil); err != nil {
if volume != nil {
volume.Free()
}
return SnapshotMutationResult{}, err
}
if err := ensureNoActiveDomainJobIfRunning(domain); err != nil {
if volume != nil {
volume.Free()
}
return SnapshotMutationResult{}, err
}
if volume != nil {
defer volume.Free()
if _, err := validateQCOW2Volume(volume, 0); err != nil {
@ -498,11 +529,14 @@ func (l *Libvirt) RestoreSnapshot(ctx context.Context, uuid, key string, request
}
replacement, err := pool.StorageVolCreateXMLFrom(replacementXML, snapshot, 0)
if err != nil {
if observed, _ := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, replacementName); observed != nil {
observed, inspectErr := l.lookupOptionalManagedVolume(l.local.ManagedStoragePool, replacementName)
artifactExists := observed != nil
if observed != nil {
observed.Free()
return SnapshotMutationResult{}, operation.MarkUncertain(mutationLibvirtError("clone snapshot restore volume", err))
}
return SnapshotMutationResult{}, mutationLibvirtError("clone snapshot restore volume", err)
return SnapshotMutationResult{}, deterministicVolumeCreateFailure(
"clone snapshot restore volume", err, inspectErr, artifactExists,
)
}
defer replacement.Free()
if _, err := validateQCOW2Volume(replacement, snapshotInfo.Capacity); err != nil {
@ -536,8 +570,14 @@ func (l *Libvirt) RestoreSnapshot(ctx context.Context, uuid, key string, request
return nil
})
if err != nil {
_ = restartOriginalDomain(domain, wasRunning)
_ = replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
restartErr := restartOriginalDomain(domain, wasRunning)
cleanupErr := replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
if restartErr != nil || cleanupErr != nil {
return SnapshotMutationResult{}, operation.MarkUncertain(errors.Join(
err, restartErr,
optionalMutationLibvirtError("roll back restore volume", cleanupErr),
))
}
return SnapshotMutationResult{}, err
}
defined, err := l.conn.DomainDefineXML(updatedXML)
@ -550,7 +590,10 @@ func (l *Libvirt) RestoreSnapshot(ctx context.Context, uuid, key string, request
restartErr := restartOriginalDomain(domain, wasRunning)
cleanupErr := replacement.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
if restartErr != nil || cleanupErr != nil {
return SnapshotMutationResult{}, operation.MarkUncertain(errors.Join(mutationLibvirtError("switch restored system disk", err), restartErr, mutationLibvirtError("roll back restore volume", cleanupErr)))
return SnapshotMutationResult{}, operation.MarkUncertain(errors.Join(
mutationLibvirtError("switch restored system disk", err), restartErr,
optionalMutationLibvirtError("roll back restore volume", cleanupErr),
))
}
return SnapshotMutationResult{}, mutationLibvirtError("switch restored system disk", err)
}
@ -580,9 +623,8 @@ func (l *Libvirt) RestoreSnapshot(ctx context.Context, uuid, key string, request
}
cleanXML, err := mutateManagedMetadata(observedXML, func(stored *domainMetadataXML) error {
stored.PendingCleanupVolume = ""
stored.DiskTransitionKind = ""
stored.DiskTransitionID = ""
stored.DiskTransitionRunning = false
// Keep the completed operation marker so a crash between this
// definition write and journal success remains reconcilable.
return nil
})
if err != nil {
@ -660,17 +702,46 @@ func (l *Libvirt) otherDomainUsesPath(path, excludedUUID string) (bool, error) {
domain.Free()
return false, fmt.Errorf("parse domain XML for volume reference: %w", err)
}
if definition.Devices == nil {
continue
}
for _, disk := range definition.Devices.Disks {
if disk.Source != nil && disk.Source.File != nil && filepath.Clean(disk.Source.File.File) == path {
domain.Free()
return true, nil
}
if domainReferencesPath(&definition, path) {
domain.Free()
return true, nil
}
}
domain.Free()
}
return false, nil
}
func domainReferencesPath(definition *libvirtxml.Domain, path string) bool {
if definition == nil {
return false
}
path = filepath.Clean(path)
if definition.OS != nil {
if definition.OS.NVRam != nil {
if definition.OS.NVRam.NVRam != "" &&
filepath.Clean(definition.OS.NVRam.NVRam) == path {
return true
}
if definition.OS.NVRam.Source != nil &&
definition.OS.NVRam.Source.File != nil &&
filepath.Clean(definition.OS.NVRam.Source.File.File) == path {
return true
}
}
if definition.OS.VarStore != nil && definition.OS.VarStore.Path != "" &&
filepath.Clean(definition.OS.VarStore.Path) == path {
return true
}
}
if definition.Devices == nil {
return false
}
for _, disk := range definition.Devices.Disks {
if disk.Source != nil && disk.Source.File != nil &&
filepath.Clean(disk.Source.File.File) == path {
return true
}
}
return false
}

@ -0,0 +1,15 @@
package hypervisor
type memoryUsageStats struct {
AvailableKiB *uint64
UnusedKiB *uint64
}
func estimateMemoryUsedKiB(stats memoryUsageStats) *uint64 {
if stats.AvailableKiB == nil || stats.UnusedKiB == nil ||
*stats.UnusedKiB > *stats.AvailableKiB {
return nil
}
used := *stats.AvailableKiB - *stats.UnusedKiB
return &used
}

@ -0,0 +1,38 @@
package hypervisor
import (
"encoding/json"
"strings"
"testing"
)
func TestEstimateMemoryUsedKiBRequiresAvailableAndUnused(t *testing.T) {
available := uint64(2 * 1024 * 1024)
unused := uint64(512 * 1024)
used := estimateMemoryUsedKiB(memoryUsageStats{
AvailableKiB: &available,
UnusedKiB: &unused,
})
if used == nil || *used != 1536*1024 {
t.Fatalf("used memory = %v", used)
}
if got := estimateMemoryUsedKiB(memoryUsageStats{AvailableKiB: &available}); got != nil {
t.Fatalf("missing unused field produced %d", *got)
}
invalidUnused := available + 1
if got := estimateMemoryUsedKiB(memoryUsageStats{
AvailableKiB: &available, UnusedKiB: &invalidUnused,
}); got != nil {
t.Fatalf("invalid memory statistics produced %d", *got)
}
}
func TestMetricsMarshalUnavailableMemoryAsNull(t *testing.T) {
encoded, err := json.Marshal(Metrics{})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(encoded), `"memory_used_kib":null`) {
t.Fatalf("unavailable memory did not marshal as null: %s", encoded)
}
}

@ -15,13 +15,62 @@ import (
const maxTrafficStoreBytes = 16 << 20
type trafficObservation struct {
RXBytes uint64
TXBytes uint64
RXAvailable bool
TXAvailable bool
}
func availableTrafficObservation(rx, tx uint64) trafficObservation {
return trafficObservation{
RXBytes: rx, TXBytes: tx, RXAvailable: true, TXAvailable: true,
}
}
type interfaceTrafficSample struct {
TargetAvailable bool
RXSet bool
RXBytes int64
TXSet bool
TXBytes int64
}
func aggregateInterfaceTraffic(samples []interfaceTrafficSample) trafficObservation {
result := trafficObservation{
RXAvailable: len(samples) > 0,
TXAvailable: len(samples) > 0,
}
for _, sample := range samples {
if !sample.TargetAvailable {
result.RXAvailable = false
result.TXAvailable = false
continue
}
if !sample.RXSet || sample.RXBytes < 0 {
result.RXAvailable = false
} else {
result.RXBytes += uint64(sample.RXBytes)
}
if !sample.TXSet || sample.TXBytes < 0 {
result.TXAvailable = false
} else {
result.TXBytes += uint64(sample.TXBytes)
}
}
return result
}
type trafficEntry struct {
Initialized bool `json:"initialized"`
LastRX uint64 `json:"last_rx"`
LastTX uint64 `json:"last_tx"`
TotalRX uint64 `json:"total_rx"`
TotalTX uint64 `json:"total_tx"`
Days map[string]DailyTraffic `json:"days"`
Initialized bool `json:"initialized"`
RXInitialized bool `json:"rx_initialized,omitempty"`
TXInitialized bool `json:"tx_initialized,omitempty"`
LastObservedUnixNano int64 `json:"last_observed_unix_nano,omitempty"`
LastRX uint64 `json:"last_rx"`
LastTX uint64 `json:"last_tx"`
TotalRX uint64 `json:"total_rx"`
TotalTX uint64 `json:"total_tx"`
Days map[string]DailyTraffic `json:"days"`
}
type trafficFile struct {
@ -30,9 +79,10 @@ type trafficFile struct {
}
type trafficStore struct {
mu sync.Mutex
path string
entries map[string]trafficEntry
mu sync.Mutex
path string
entries map[string]trafficEntry
sampleLocks sync.Map
}
func openTrafficStore(path string) (*trafficStore, error) {
@ -68,39 +118,106 @@ func openTrafficStore(path string) (*trafficStore, error) {
if document.Version != 1 || document.VMs == nil {
return nil, errors.New("decode traffic state: unsupported or incomplete document")
}
for uuid, entry := range document.VMs {
document.VMs[uuid] = normalizeTrafficEntry(entry)
}
store.entries = document.VMs
return store, nil
}
func (s *trafficStore) observe(uuid string, at time.Time, rx, tx uint64) (uint64, uint64, error) {
s.mu.Lock()
defer s.mu.Unlock()
entry := s.entries[uuid]
func normalizeTrafficEntry(entry trafficEntry) trafficEntry {
// Version 1 originally had a single initialization bit. Promote old
// entries to directional baselines while retaining on-disk compatibility.
if entry.Initialized && !entry.RXInitialized && !entry.TXInitialized {
entry.RXInitialized = true
entry.TXInitialized = true
}
entry.Initialized = entry.RXInitialized && entry.TXInitialized
if entry.Days == nil {
entry.Days = make(map[string]DailyTraffic)
}
if entry.Initialized {
deltaRX := rx
if rx >= entry.LastRX {
deltaRX = rx - entry.LastRX
return entry
}
func (s *trafficStore) lockSample(uuid string) func() {
value, _ := s.sampleLocks.LoadOrStore(uuid, &sync.Mutex{})
lock := value.(*sync.Mutex)
lock.Lock()
return lock.Unlock
}
func (s *trafficStore) initialize(uuid string, at time.Time) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
previous, exists := s.entries[uuid]
entry := normalizeTrafficEntry(previous)
if entry.RXInitialized || entry.TXInitialized {
return false, nil
}
entry.Initialized = true
entry.RXInitialized = true
entry.TXInitialized = true
entry.LastRX = 0
entry.LastTX = 0
entry.LastObservedUnixNano = at.UTC().UnixNano()
s.entries[uuid] = entry
if err := s.persistLocked(); err != nil {
if exists {
s.entries[uuid] = previous
} else {
delete(s.entries, uuid)
}
return false, err
}
return !exists, nil
}
func (s *trafficStore) observe(uuid string, at time.Time, sample trafficObservation) (uint64, uint64, error) {
s.mu.Lock()
defer s.mu.Unlock()
entry := normalizeTrafficEntry(s.entries[uuid])
if !sample.RXAvailable && !sample.TXAvailable {
return entry.TotalRX, entry.TotalTX, nil
}
observedAt := at.UTC().UnixNano()
duplicateRX := !sample.RXAvailable || (entry.RXInitialized && sample.RXBytes == entry.LastRX)
duplicateTX := !sample.TXAvailable || (entry.TXInitialized && sample.TXBytes == entry.LastTX)
if entry.LastObservedUnixNano != 0 && observedAt == entry.LastObservedUnixNano && duplicateRX && duplicateTX {
return entry.TotalRX, entry.TotalTX, nil
}
var deltaRX, deltaTX uint64
if sample.RXAvailable {
if entry.RXInitialized {
deltaRX = sample.RXBytes
if sample.RXBytes >= entry.LastRX {
deltaRX = sample.RXBytes - entry.LastRX
}
} else {
entry.RXInitialized = true
}
deltaTX := tx
if tx >= entry.LastTX {
deltaTX = tx - entry.LastTX
entry.LastRX = sample.RXBytes
}
if sample.TXAvailable {
if entry.TXInitialized {
deltaTX = sample.TXBytes
if sample.TXBytes >= entry.LastTX {
deltaTX = sample.TXBytes - entry.LastTX
}
} else {
entry.TXInitialized = true
}
entry.TotalRX += deltaRX
entry.TotalTX += deltaTX
day := at.UTC().Format("2006-01-02")
value := entry.Days[day]
value.Date = day
value.RXBytes += deltaRX
value.TXBytes += deltaTX
entry.Days[day] = value
} else {
entry.Initialized = true
}
entry.LastRX = rx
entry.LastTX = tx
entry.LastTX = sample.TXBytes
}
entry.Initialized = entry.RXInitialized && entry.TXInitialized
entry.LastObservedUnixNano = observedAt
entry.TotalRX += deltaRX
entry.TotalTX += deltaTX
day := at.UTC().Format("2006-01-02")
value := entry.Days[day]
value.Date = day
value.RXBytes += deltaRX
value.TXBytes += deltaTX
entry.Days[day] = value
cutoff := at.UTC().AddDate(0, 0, -400).Format("2006-01-02")
for day := range entry.Days {
if day < cutoff {
@ -138,12 +255,18 @@ func (s *trafficStore) remove(uuid string) error {
s.mu.Lock()
defer s.mu.Unlock()
previous, exists := s.entries[uuid]
if !exists {
return nil
if exists {
delete(s.entries, uuid)
}
delete(s.entries, uuid)
// Persist even when the in-memory entry is absent. A previous atomic rename
// may have reached disk before its directory fsync reported an error, while
// the caller conservatively restored only the in-memory map. Rewriting the
// authoritative map here is required before reconciliation can attest that
// no traffic artifact remains.
if err := s.persistLocked(); err != nil {
s.entries[uuid] = previous
if exists {
s.entries[uuid] = previous
}
return err
}
return nil

@ -2,6 +2,7 @@ package hypervisor
import (
"path/filepath"
"sync"
"testing"
"time"
)
@ -13,15 +14,15 @@ func TestTrafficStorePersistsDeltasAndHandlesCounterReset(t *testing.T) {
t.Fatal(err)
}
now := time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC)
rx, tx, err := store.observe("vm-1", now, 1000, 2000)
rx, tx, err := store.observe("vm-1", now, availableTrafficObservation(1000, 2000))
if err != nil || rx != 0 || tx != 0 {
t.Fatalf("baseline = %d/%d err=%v", rx, tx, err)
}
rx, tx, err = store.observe("vm-1", now.Add(time.Minute), 1300, 2600)
rx, tx, err = store.observe("vm-1", now.Add(time.Minute), availableTrafficObservation(1300, 2600))
if err != nil || rx != 300 || tx != 600 {
t.Fatalf("delta = %d/%d err=%v", rx, tx, err)
}
rx, tx, err = store.observe("vm-1", now.Add(2*time.Minute), 40, 70)
rx, tx, err = store.observe("vm-1", now.Add(2*time.Minute), availableTrafficObservation(40, 70))
if err != nil || rx != 340 || tx != 670 {
t.Fatalf("post-reset = %d/%d err=%v", rx, tx, err)
}
@ -35,6 +36,168 @@ func TestTrafficStorePersistsDeltasAndHandlesCounterReset(t *testing.T) {
}
}
func TestTrafficStoreCreateBaselineCountsFirstObservation(t *testing.T) {
store, err := openTrafficStore(filepath.Join(t.TempDir(), "traffic.json"))
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC)
created, err := store.initialize("vm-new", now)
if err != nil || !created {
t.Fatalf("initialize created=%v err=%v", created, err)
}
rx, tx, err := store.observe("vm-new", now.Add(time.Minute), availableTrafficObservation(1000, 2000))
if err != nil || rx != 1000 || tx != 2000 {
t.Fatalf("first created-VM sample = %d/%d err=%v", rx, tx, err)
}
reopened, err := openTrafficStore(store.path)
if err != nil {
t.Fatal(err)
}
rx, tx, err = reopened.observe("vm-new", now.Add(2*time.Minute), availableTrafficObservation(1100, 2200))
if err != nil || rx != 1100 || tx != 2200 {
t.Fatalf("post-restart sample = %d/%d err=%v", rx, tx, err)
}
}
func TestTrafficStoreProcessesCounterDeltasAcrossWallClockRollback(t *testing.T) {
path := filepath.Join(t.TempDir(), "traffic.json")
store, err := openTrafficStore(path)
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC)
if _, err := store.initialize("vm-1", now); err != nil {
t.Fatal(err)
}
if rx, tx, err := store.observe("vm-1", now.Add(2*time.Minute), availableTrafficObservation(1300, 2600)); err != nil || rx != 1300 || tx != 2600 {
t.Fatalf("future-clock sample = %d/%d err=%v", rx, tx, err)
}
reopened, err := openTrafficStore(path)
if err != nil {
t.Fatal(err)
}
rx, tx, err := reopened.observe("vm-1", now.Add(time.Minute), availableTrafficObservation(1400, 2800))
if err != nil || rx != 1400 || tx != 2800 {
t.Fatalf("clock-regressed sample = %d/%d err=%v", rx, tx, err)
}
rx, tx, err = reopened.observe("vm-1", now.Add(time.Minute), availableTrafficObservation(1400, 2800))
if err != nil || rx != 1400 || tx != 2800 {
t.Fatalf("duplicate sample = %d/%d err=%v", rx, tx, err)
}
}
func TestTrafficSampleLockSerializesReadThroughObserve(t *testing.T) {
store, err := openTrafficStore(filepath.Join(t.TempDir(), "traffic.json"))
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC)
if _, err := store.initialize("vm-1", now); err != nil {
t.Fatal(err)
}
raw := uint64(1200)
firstHasRead := make(chan struct{})
releaseFirst := make(chan struct{})
secondAttempting := make(chan struct{})
errors := make(chan error, 2)
var wait sync.WaitGroup
wait.Add(2)
go func() {
defer wait.Done()
unlock := store.lockSample("vm-1")
defer unlock()
read := raw
close(firstHasRead)
<-releaseFirst
_, _, observeErr := store.observe(
"vm-1", now.Add(time.Minute), availableTrafficObservation(read, read),
)
errors <- observeErr
}()
<-firstHasRead
raw = 1300
go func() {
defer wait.Done()
close(secondAttempting)
unlock := store.lockSample("vm-1")
defer unlock()
read := raw
_, _, observeErr := store.observe(
"vm-1", now.Add(2*time.Minute), availableTrafficObservation(read, read),
)
errors <- observeErr
}()
<-secondAttempting
close(releaseFirst)
wait.Wait()
close(errors)
for observeErr := range errors {
if observeErr != nil {
t.Fatal(observeErr)
}
}
rx, tx, err := store.observe(
"vm-1", now.Add(3*time.Minute), availableTrafficObservation(1400, 1400),
)
if err != nil || rx != 1400 || tx != 1400 {
t.Fatalf("serialized samples = %d/%d err=%v", rx, tx, err)
}
}
func TestTrafficStoreUnavailableDirectionDoesNotResetBaseline(t *testing.T) {
store, err := openTrafficStore(filepath.Join(t.TempDir(), "traffic.json"))
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC)
if _, err := store.initialize("vm-1", now); err != nil {
t.Fatal(err)
}
if _, _, err := store.observe("vm-1", now.Add(time.Minute), availableTrafficObservation(100, 200)); err != nil {
t.Fatal(err)
}
rx, tx, err := store.observe("vm-1", now.Add(2*time.Minute), trafficObservation{
TXBytes: 250, TXAvailable: true,
})
if err != nil || rx != 100 || tx != 250 {
t.Fatalf("partial unavailable sample = %d/%d err=%v", rx, tx, err)
}
rx, tx, err = store.observe("vm-1", now.Add(3*time.Minute), availableTrafficObservation(130, 270))
if err != nil || rx != 130 || tx != 270 {
t.Fatalf("recovered sample reset a baseline: %d/%d err=%v", rx, tx, err)
}
}
func TestAggregateInterfaceTrafficRequiresEveryField(t *testing.T) {
complete := aggregateInterfaceTraffic([]interfaceTrafficSample{
{TargetAvailable: true, RXSet: true, RXBytes: 100, TXSet: true, TXBytes: 200},
{TargetAvailable: true, RXSet: true, RXBytes: 30, TXSet: true, TXBytes: 40},
})
if !complete.RXAvailable || !complete.TXAvailable || complete.RXBytes != 130 || complete.TXBytes != 240 {
t.Fatalf("complete aggregate = %#v", complete)
}
partial := aggregateInterfaceTraffic([]interfaceTrafficSample{
{TargetAvailable: true, RXSet: true, RXBytes: -1, TXSet: true, TXBytes: 200},
})
if partial.RXAvailable || !partial.TXAvailable || partial.TXBytes != 200 {
t.Fatalf("negative field aggregate = %#v", partial)
}
missingTarget := aggregateInterfaceTraffic([]interfaceTrafficSample{
{TargetAvailable: true, RXSet: true, RXBytes: 100, TXSet: true, TXBytes: 200},
{},
})
if missingTarget.RXAvailable || missingTarget.TXAvailable {
t.Fatalf("missing target aggregate = %#v", missingTarget)
}
missingFields := aggregateInterfaceTraffic([]interfaceTrafficSample{
{TargetAvailable: true},
})
if missingFields.RXAvailable || missingFields.TXAvailable {
t.Fatalf("missing stat fields aggregate = %#v", missingFields)
}
}
func TestTrafficStoreRejectsRelativePath(t *testing.T) {
if _, err := openTrafficStore("traffic.json"); err == nil {
t.Fatal("relative traffic path was accepted")

@ -71,13 +71,14 @@ type FeatureSet struct {
}
type Capabilities struct {
Backend string `json:"backend"`
LibvirtVersion string `json:"libvirt_version,omitempty"`
QEMUVersion string `json:"qemu_version,omitempty"`
Features FeatureSet `json:"features"`
PowerActions []PowerAction `json:"power_actions"`
Firmware []string `json:"firmware"`
Checks map[string]CapabilityCheck `json:"checks,omitempty"`
Backend string `json:"backend"`
LibvirtVersion string `json:"libvirt_version,omitempty"`
QEMUVersion string `json:"qemu_version,omitempty"`
Features FeatureSet `json:"features"`
PowerActions []PowerAction `json:"power_actions"`
Firmware []string `json:"firmware"`
NetworkSelectors []string `json:"network_selectors"`
Checks map[string]CapabilityCheck `json:"checks,omitempty"`
}
// CapabilityCheck exposes bounded, non-sensitive runtime evidence for a
@ -98,7 +99,7 @@ const (
VMStateShutdown VMStateName = "shutdown"
VMStateShutoff VMStateName = "shutoff"
VMStateCrashed VMStateName = "crashed"
VMStateSuspended VMStateName = "suspended"
VMStateSuspended VMStateName = "pmsuspended"
)
type VMState struct {
@ -299,7 +300,7 @@ type Metrics struct {
UUID string `json:"uuid"`
CollectedAt time.Time `json:"collected_at"`
CPUTimeNS uint64 `json:"cpu_time_ns"`
MemoryUsedKiB uint64 `json:"memory_used_kib"`
MemoryUsedKiB *uint64 `json:"memory_used_kib"`
DiskReadBytes uint64 `json:"disk_read_bytes"`
DiskWriteBytes uint64 `json:"disk_write_bytes"`
RXBytes uint64 `json:"rx_bytes"`

@ -524,14 +524,16 @@ func ExpectedStateFromContext(ctx context.Context) (ExpectedState, bool) {
return *cloneExpectedState(expected), true
}
// Reconcile only inspects evidence through fn; it never invokes the original
// mutation. Unresolved evidence leaves the operation uncertain.
// Reconcile never resubmits the original API request. The hypervisor callback
// may inspect evidence and continue an idempotent target-state or cleanup tail
// whose targets are durably bound to this exact operation. Unresolved evidence
// leaves the operation uncertain.
func (j *Journal) Reconcile(ctx context.Context, operationID string, fn func(context.Context, Record) (Resolution, error)) (Record, error) {
record, err := j.Get(operationID)
if err != nil {
return Record{}, err
}
if record.State != StateUncertain && record.State != StateDispatching {
if !recordCanReconcile(record) {
return record, nil
}
release, err := j.acquire(ctx, lockKeyForRecord(record))
@ -541,11 +543,23 @@ func (j *Journal) Reconcile(ctx context.Context, operationID string, fn func(con
defer release()
record, err = j.Get(operationID)
if err != nil || (record.State != StateUncertain && record.State != StateDispatching) {
if err != nil || !recordCanReconcile(record) {
return record, err
}
cleanupRetry := succeededCleanupCanReconcile(record)
resolution, inspectErr := fn(ctx, record)
if inspectErr != nil || !resolution.Resolved {
// The reinstall itself is already committed and publicly succeeded.
// A transient cleanup inspection failure must not erase that durable
// result or turn a completed reinstall into an uncertain mutation. By
// retaining cleanup_pending, a later reconcile call can safely retry the
// idempotent cleanup tail with this same operation ID.
if cleanupRetry {
if inspectErr != nil {
return record, inspectErr
}
return record, ErrOperationUncertain
}
if inspectErr != nil {
updated, persistErr := j.markUncertain(operationID, inspectErr)
if persistErr != nil {
@ -553,11 +567,21 @@ func (j *Journal) Reconcile(ctx context.Context, operationID string, fn func(con
}
return updated, inspectErr
}
if record.Action == "create-vm" {
updated, persistErr := j.markUncertain(operationID, nil)
if persistErr != nil {
return updated, persistErr
}
return updated, ErrOperationUncertain
}
return record, ErrOperationUncertain
}
if resolution.Succeeded {
return j.finish(operationID, resolution.Result, nil)
}
if cleanupRetry {
return record, ErrOperationUncertain
}
code := resolution.ErrorCode
if code == "" {
code = "operation_failed"
@ -569,17 +593,73 @@ func (j *Journal) Reconcile(ctx context.Context, operationID string, fn func(con
if evidence, ok := safeFailureEvidence(record.Action, code, resolution.Result); ok {
return j.finishWithPublicErrorAndResult(operationID, code, message, evidence)
}
// A create failure is terminal only when read-only host evidence proves
// both the domain and every panel-managed artifact are absent. Any other
// failure resolution can describe a partial create and must stay uncertain;
// it never authorizes replaying the original create call.
if record.Action == "create-vm" {
updated, persistErr := j.markUncertain(operationID, nil)
if persistErr != nil {
return updated, persistErr
}
return updated, ErrOperationUncertain
}
return j.finishWithPublicError(operationID, code, message)
}
func recordCanReconcile(record Record) bool {
if record.State == StateUncertain || record.State == StateDispatching {
return true
}
if succeededCleanupCanReconcile(record) {
return true
}
if record.State != StateFailed || record.Action != "create-vm" {
return false
}
code := ""
if record.Error != nil {
code = record.Error.Code
}
_, confirmedAbsent := safeFailureEvidence(record.Action, code, record.Result)
return !confirmedAbsent
}
// Older Agents could finalize a committed reinstall while its deterministic
// old-root cleanup was still pending. Permit the same operation's reconcile
// endpoint to replace that result after the cleanup tail is confirmed.
func succeededCleanupCanReconcile(record Record) bool {
if record.State != StateSucceeded || record.Action != "reinstall-vm" || len(record.Result) == 0 {
return false
}
var result map[string]json.RawMessage
if json.Unmarshal(record.Result, &result) != nil {
return false
}
var pending bool
return json.Unmarshal(result["cleanup_pending"], &pending) == nil && pending
}
func safeFailureEvidence(action, code string, candidate json.RawMessage) (json.RawMessage, bool) {
if action != "create-vm" || code != "creation_absent" || len(candidate) == 0 {
if action != "create-vm" ||
(code != "creation_absent" && code != "operation_not_dispatched") ||
len(candidate) == 0 {
return nil, false
}
var object map[string]json.RawMessage
if err := json.Unmarshal(candidate, &object); err != nil || len(object) != 2 {
expectedFields := 2
if code == "operation_not_dispatched" {
expectedFields = 3
}
if err := json.Unmarshal(candidate, &object); err != nil || len(object) != expectedFields {
return nil, false
}
if code == "operation_not_dispatched" {
var notDispatched bool
if err := json.Unmarshal(object["not_dispatched"], &notDispatched); err != nil || !notDispatched {
return nil, false
}
}
var creationAbsent, artifactsAbsent bool
if err := json.Unmarshal(object["creation_absent"], &creationAbsent); err != nil || !creationAbsent {
return nil, false
@ -587,6 +667,9 @@ func safeFailureEvidence(action, code string, candidate json.RawMessage) (json.R
if err := json.Unmarshal(object["managed_artifacts_absent"], &artifactsAbsent); err != nil || !artifactsAbsent {
return nil, false
}
if code == "operation_not_dispatched" {
return json.RawMessage(`{"not_dispatched":true,"creation_absent":true,"managed_artifacts_absent":true}`), true
}
return json.RawMessage(`{"creation_absent":true,"managed_artifacts_absent":true}`), true
}
@ -757,7 +840,7 @@ func (j *Journal) FailNotDispatched(operationID string) (Record, error) {
func notDispatchedEvidence(action string) json.RawMessage {
if action == "create-vm" {
return json.RawMessage(`{"not_dispatched":true,"creation_absent":true}`)
return json.RawMessage(`{"not_dispatched":true,"creation_absent":true,"managed_artifacts_absent":true}`)
}
return json.RawMessage(`{"not_dispatched":true}`)
}

@ -88,6 +88,86 @@ func TestUncertainOperationIsNotReplayedAndCanBeReconciled(t *testing.T) {
}
}
func TestSucceededReinstallWithPendingCleanupCanReconcileSameOperation(t *testing.T) {
j := testJournal(t)
spec := Spec{
OperationID: "operation-reinstall-cleanup", ResourceID: "vm-reinstall",
Action: "reinstall-vm",
Fingerprint: Fingerprint("POST", "/v1/vms/vm-reinstall/reinstall", []byte(`{}`)),
Destructive: true,
}
initial, _, err := j.Execute(context.Background(), spec,
func(context.Context) (json.RawMessage, error) {
return json.RawMessage(`{"reinstall_committed":true,"cleanup_pending":true}`), nil
})
if err != nil || initial.State != StateSucceeded || !succeededCleanupCanReconcile(initial) {
t.Fatalf("initial cleanup record = %#v err=%v", initial, err)
}
calls := 0
reconciled, err := j.Reconcile(context.Background(), spec.OperationID,
func(_ context.Context, persisted Record) (Resolution, error) {
calls++
if persisted.OperationID != spec.OperationID {
t.Fatalf("reconciled wrong operation: %#v", persisted)
}
return Resolution{Resolved: true, Succeeded: true,
Result: json.RawMessage(`{"reinstall_committed":true,"cleanup_pending":false}`)}, nil
})
if err != nil || calls != 1 || reconciled.State != StateSucceeded ||
succeededCleanupCanReconcile(reconciled) {
t.Fatalf("cleanup reconcile = %#v calls=%d err=%v", reconciled, calls, err)
}
}
func TestSucceededReinstallCleanupRetryPreservesSuccessUntilResolved(t *testing.T) {
j := testJournal(t)
spec := Spec{
OperationID: "operation-reinstall-cleanup-retry", ResourceID: "vm-reinstall-retry",
Action: "reinstall-vm",
Fingerprint: Fingerprint("POST", "/v1/vms/vm-reinstall-retry/reinstall", []byte(`{}`)),
Destructive: true,
}
want := json.RawMessage(`{"reinstall_committed":true,"cleanup_pending":true}`)
initial, _, err := j.Execute(context.Background(), spec,
func(context.Context) (json.RawMessage, error) { return want, nil })
if err != nil || initial.State != StateSucceeded {
t.Fatalf("initial cleanup record = %#v err=%v", initial, err)
}
temporary := errors.New("temporary cleanup inspection failure")
afterError, err := j.Reconcile(context.Background(), spec.OperationID,
func(context.Context, Record) (Resolution, error) { return Resolution{}, temporary })
if !errors.Is(err, temporary) || afterError.State != StateSucceeded ||
string(afterError.Result) != string(want) || afterError.Error != nil {
t.Fatalf("cleanup error changed success = %#v err=%v", afterError, err)
}
afterUnresolved, err := j.Reconcile(context.Background(), spec.OperationID,
func(context.Context, Record) (Resolution, error) { return Resolution{}, nil })
if !errors.Is(err, ErrOperationUncertain) || afterUnresolved.State != StateSucceeded ||
string(afterUnresolved.Result) != string(want) || afterUnresolved.Error != nil {
t.Fatalf("unresolved cleanup changed success = %#v err=%v", afterUnresolved, err)
}
afterFailedCleanup, err := j.Reconcile(context.Background(), spec.OperationID,
func(context.Context, Record) (Resolution, error) {
return Resolution{Resolved: true, Succeeded: false, ErrorCode: "cleanup_failed"}, nil
})
if !errors.Is(err, ErrOperationUncertain) || afterFailedCleanup.State != StateSucceeded ||
string(afterFailedCleanup.Result) != string(want) || afterFailedCleanup.Error != nil {
t.Fatalf("failed cleanup changed success = %#v err=%v", afterFailedCleanup, err)
}
final, err := j.Reconcile(context.Background(), spec.OperationID,
func(context.Context, Record) (Resolution, error) {
return Resolution{Resolved: true, Succeeded: true,
Result: json.RawMessage(`{"reinstall_committed":true,"cleanup_pending":false}`)}, nil
})
if err != nil || final.State != StateSucceeded || succeededCleanupCanReconcile(final) {
t.Fatalf("cleanup retry did not finish = %#v err=%v", final, err)
}
}
func TestFailedCreateReconciliationPreservesOnlyConfirmedAbsenceEvidence(t *testing.T) {
j := testJournal(t)
spec := Spec{
@ -113,6 +193,114 @@ func TestFailedCreateReconciliationPreservesOnlyConfirmedAbsenceEvidence(t *test
}
}
func TestTerminalFailedCreateCanBeReconciledWithoutReplayingCreate(t *testing.T) {
j := testJournal(t)
spec := Spec{
OperationID: "operation-create-failed", ResourceID: "123e4567-e89b-42d3-a456-426614174000", Action: "create-vm",
Fingerprint: Fingerprint("POST", "/v1/vms", []byte(`{}`)), Destructive: true,
}
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")
})
if err == nil || record.State != StateFailed || createCalls != 1 {
t.Fatalf("initial failed create = %#v calls=%d err=%v", record, createCalls, err)
}
reconcileCalls := 0
reconciled, err := j.Reconcile(context.Background(), spec.OperationID, func(_ context.Context, persisted Record) (Resolution, error) {
reconcileCalls++
if persisted.OperationID != spec.OperationID || persisted.ResourceID != spec.ResourceID || persisted.Action != "create-vm" {
t.Fatalf("reconcile received a different operation: %#v", persisted)
}
return Resolution{
Resolved: true, Succeeded: false, ErrorCode: "creation_absent",
Result: json.RawMessage(`{"creation_absent":true,"managed_artifacts_absent":true}`),
}, nil
})
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 string(reconciled.Result) != `{"creation_absent":true,"managed_artifacts_absent":true}` {
t.Fatalf("absence evidence = %s", reconciled.Result)
}
_, replay, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) {
createCalls++
return nil, nil
})
if err != nil || !replay || createCalls != 1 {
t.Fatalf("confirmed failure replay = %v calls=%d err=%v", replay, createCalls, err)
}
}
func TestTerminalFailedCreateReconciliationCanRecoverCompleteVM(t *testing.T) {
j := testJournal(t)
spec := Spec{
OperationID: "operation-create-complete", ResourceID: "123e4567-e89b-42d3-a456-426614174001", Action: "create-vm",
Fingerprint: Fingerprint("POST", "/v1/vms", []byte(`{}`)), Destructive: true,
}
if record, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) {
return nil, errors.New("response lost after host validation")
}); err == nil || record.State != StateFailed {
t.Fatalf("initial failed create = %#v err=%v", record, err)
}
want := json.RawMessage(`{"uuid":"123e4567-e89b-42d3-a456-426614174001","state":"running"}`)
reconciled, err := j.Reconcile(context.Background(), spec.OperationID, func(context.Context, Record) (Resolution, error) {
return Resolution{Resolved: true, Succeeded: true, Result: want}, nil
})
if err != nil || reconciled.State != StateSucceeded || string(reconciled.Result) != string(want) {
t.Fatalf("complete VM reconciliation = %#v err=%v", reconciled, err)
}
}
func TestTerminalFailedCreateWithPartialArtifactsBecomesUncertain(t *testing.T) {
j := testJournal(t)
spec := Spec{
OperationID: "operation-create-partial", ResourceID: "123e4567-e89b-42d3-a456-426614174002", Action: "create-vm",
Fingerprint: Fingerprint("POST", "/v1/vms", []byte(`{}`)), Destructive: true,
}
createCalls := 0
if record, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) {
createCalls++
return nil, errors.New("create failed after a partial side effect")
}); err == nil || record.State != StateFailed {
t.Fatalf("initial failed create = %#v err=%v", record, err)
}
reconciled, err := j.Reconcile(context.Background(), spec.OperationID, func(context.Context, Record) (Resolution, error) {
return Resolution{}, nil
})
if !errors.Is(err, ErrOperationUncertain) || reconciled.State != StateUncertain {
t.Fatalf("partial create reconciliation = %#v err=%v", reconciled, err)
}
_, replay, replayErr := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) {
createCalls++
return nil, nil
})
if !replay || !errors.Is(replayErr, ErrOperationUncertain) || createCalls != 1 {
t.Fatalf("partial create was replayed: replay=%v calls=%d err=%v", replay, createCalls, replayErr)
}
}
func TestTerminalFailureForOtherActionDoesNotInvokeReconciliation(t *testing.T) {
j := testJournal(t)
spec := testSpec("operation-delete-terminal", "vm-terminal", `{}`)
if record, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) {
return nil, errors.New("definitive delete failure")
}); err == nil || record.State != StateFailed {
t.Fatalf("initial failed delete = %#v err=%v", record, err)
}
called := false
reconciled, err := j.Reconcile(context.Background(), spec.OperationID, func(context.Context, Record) (Resolution, error) {
called = true
return Resolution{Resolved: true, Succeeded: true}, nil
})
if err != nil || called || reconciled.State != StateFailed {
t.Fatalf("terminal non-create reconcile = %#v called=%v err=%v", reconciled, called, err)
}
}
func TestFailedReconciliationDropsUnapprovedEvidence(t *testing.T) {
j := testJournal(t)
spec := testSpec("operation-delete-failed", "vm-delete-failed", `{}`)
@ -214,9 +402,30 @@ func TestReservedCreateBecomesConfirmedAbsentAcrossRestart(t *testing.T) {
t.Fatalf("reserved restart record = %#v err=%v", record, err)
}
var evidence map[string]bool
if err := json.Unmarshal(record.Result, &evidence); err != nil || !evidence["not_dispatched"] || !evidence["creation_absent"] {
if err := json.Unmarshal(record.Result, &evidence); err != nil || !evidence["not_dispatched"] || !evidence["creation_absent"] || !evidence["managed_artifacts_absent"] {
t.Fatalf("reserved restart evidence = %s err=%v", record.Result, err)
}
called := false
reconciled, err := reopened.Reconcile(context.Background(), spec.OperationID, func(context.Context, Record) (Resolution, error) {
called = true
return Resolution{}, nil
})
if err != nil || called || reconciled.State != StateFailed {
t.Fatalf("confirmed not-dispatched create was reopened: record=%#v called=%v err=%v", reconciled, called, err)
}
}
func TestNotDispatchedCreateEvidenceStaysCanonicalAndClosed(t *testing.T) {
evidence, ok := safeFailureEvidence("create-vm", "operation_not_dispatched",
json.RawMessage(`{"managed_artifacts_absent":true,"not_dispatched":true,"creation_absent":true}`))
if !ok || string(evidence) != `{"not_dispatched":true,"creation_absent":true,"managed_artifacts_absent":true}` {
t.Fatalf("canonical not-dispatched evidence = %s ok=%v", evidence, ok)
}
record := Record{Action: "create-vm", State: StateFailed,
Error: &PublicError{Code: "operation_not_dispatched"}, Result: evidence}
if recordCanReconcile(record) {
t.Fatal("canonical not-dispatched create was reopened for reconciliation")
}
}
func TestResourceWaitTimeoutRecordsNotDispatched(t *testing.T) {

@ -4,5 +4,5 @@
"panel_agent_auth_url": "http://127.0.0.1/api/internal/cloud/agent-auth",
"panel_shared_secret": "REPLACE_ME",
"connect_timeout_seconds": 10,
"agent_request_timeout_seconds": 900
"agent_request_timeout_seconds": 870
}

@ -7,7 +7,7 @@
"max_body_bytes": 1048576,
"clock_skew_seconds": 300,
"nonce_ttl_seconds": 600,
"operation_timeout_seconds": 120,
"operation_timeout_seconds": 840,
"managed_storage_pool": "virt-vms",
"template_storage_pool": "virt-templates",
"seed_storage_pool": "virt-seeds",
@ -18,10 +18,6 @@
"public": {
"type": "bridge",
"source": "br0"
},
"private": {
"type": "network",
"source": "default"
}
}
}

@ -19,11 +19,12 @@ ProtectHome=true
ProtectSystem=strict
StateDirectory=virt-agent
StateDirectoryMode=0700
# The Agent writes only its Bolt journal and traffic state here. Configured
# NVRAM and libvirt storage paths are written by the separate libvirt/QEMU
# service through qemu:///system, so granting them to this mount namespace
# would broaden the Agent unnecessarily.
ReadWritePaths=/var/lib/virt-agent
# The Agent normally writes only its Bolt journal and traffic state. The
# standard libvirt NVRAM directory is also writable so reconciliation can
# remove a UUID-owned VARS file left after a domain definition disappeared.
# The leading '-' keeps the unit portable when this distro path is absent.
# If nvram_directory is configured elsewhere, replace this path in a drop-in.
ReadWritePaths=/var/lib/virt-agent -/var/lib/libvirt/qemu/nvram
LimitCORE=0
TimeoutStopSec=30

@ -79,7 +79,19 @@ RAW_X_VIRT_ACTOR
| 501 | capability 未实现,禁止静默降级 |
| 503 | libvirt/本地依赖暂不可用;变更是否可重试仍取决于派发边界 |
若操作已经越过派发边界,错误 envelope 还应返回同一 `operation_id` 和 `status: "uncertain"`;`retryable` 不能覆盖 no-replay 规则。
只有在请求明确尚未进入持久操作日志时,Gateway/Agent 才能在上述严格
`error` 对象中增加 `"dispatch_state":"not_dispatched"`。面板只接受顶层
仅含 `error`,且该对象恰好由 `code`、`message`、`retryable`、
`dispatch_state` 四个字段组成的 envelope:
不可重试的 400/413/422/501、普通 `unauthorized` 401、所有 403,以及
路由契约的 404/405 作为终态请求错误;`operation_not_found` 等资源 404
不属于该捷径。可重试的 5xx 才把同一 `operation_id` 放回持久队列。
没有该标记、字段多余或形状错误都必须按不确定处理。
`replayed_request` 与 Gateway 的 `gateway_replayed_request` 绝不能带
`not_dispatched`:相同 nonce 的首次请求可能已经越过派发边界。若操作已
越过派发边界,错误 envelope 还应返回同一 `operation_id` 和
`status: "uncertain"`;`retryable` 不能覆盖 no-replay 规则。
## 基础端点
@ -115,7 +127,7 @@ RAW_X_VIRT_ACTOR
| POST | `/v1/vms/{uuid}/rescue/force-start` | 仅对已核验的 staged rescue 冷关机并启动;必须 `ack_data_loss: true` |
| POST | `/v1/vms/{uuid}/rescue/exit` | 退出救援并保持账期网络策略 |
| GET | `/v1/operations/{operation_id}` | 读取持久操作结果 |
| POST | `/v1/operations/{operation_id}/reconcile` | 只读证据核对,绝不重放原操作 |
| POST | `/v1/operations/{operation_id}/reconcile` | 核对宿主机证据;只允许同一 operation 续作已验证归属的目标状态/清理尾段,绝不重新提交原请求 |
| GET/POST | `/v1/templates` | 管理员列出/导入经校验云镜像 |
| PATCH/DELETE | `/v1/templates/{id}` | 管理员更新/删除模板 |
| GET/POST | `/v1/user-isos?owner_id=...` | 列出/导入用户 ISO |
@ -141,7 +153,7 @@ Agent 在调用 libvirt 前将 `operation_id`、VM UUID/资源 ID、动作、指
- 进程启动时遗留 `dispatching` 必须转为 `uncertain`,不能自动继续调用。
- CGo/libvirt 调用通常不能被 Go context 真正取消。HTTP 超时后 Agent 仍必须记录晚到结果,不能丢弃唯一证据。
`reconcile` 只读取操作日志和宿主机现状,不调用原变更。证据不足就保持 `uncertain`。VM 仍在运行不证明之前的 shutdown/reboot 未执行;持久域暂时查不到也不自动证明磁盘已安全删除。
`reconcile` 不重新提交原 API 变更。通常只读取操作日志和宿主机现状;证据不足就保持 `uncertain`。只有目标可由同一 operation 和 VM UUID 唯一推出时,才允许续作幂等尾段:例如已提交的 reinstall/snapshot 旧卷清理,或 `delete-vm` 在重新核验 managed ownership、全部磁盘交叉引用后继续收敛到“域与专属工件均不存在”。delete 的 destroy/undefine 即使返回错误也必须复查实际活动/存在状态;没有观察到目标状态就继续保持 `uncertain`。VM 仍在运行不证明之前的 shutdown/reboot 未执行;持久域暂时查不到也不自动证明磁盘已安全删除。
救援进入先持久化救援 XML,再请求正常关机。若来宾没有在等待窗口内关机,操作以 `succeeded` 返回 `staged: true` 和 `pending_manual_restart: true`,不会隐式 destroy。只有随后显式提交同名的 `force-start` API、确认 `ack_data_loss`,且 Agent 重新核验持久救援定义、模板与 live 原系统状态后,才允许冷关机并启动救援环境。
@ -188,4 +200,4 @@ PHP 拥有镜像目录和脚本正文。创建请求携带已快照的 template
Agent 不能只相信 `is_admin` 布尔值;路由先验证 HMAC,再按动作验证 `can_manage`/管理员级别和资源范围。普通用户动作必须由 PHP 确认所有权后签名,Agent 仍按最小 capability 执行。
`GET /v1/capabilities` 是运行时事实,不是承诺清单。某项未实现、宿主机版本不支持或依赖缺失时对应 feature 为 false;PHP 保持既有页面布局,但把动作显示为明确不可用。
`GET /v1/capabilities` 是运行时事实,不是承诺清单。某项未实现、宿主机版本不支持或依赖缺失时对应 feature 为 false;PHP 保持既有页面布局,但把动作显示为明确不可用。响应中的 `network_selectors` 是已排序、最多 64 项且当前探测可用的稳定 selector key 列表,只能包含 Agent 配置的 key,不能暴露 bridge/libvirt network 的本机 `source`。面板只有在宿主机 `default_network` 与该列表精确匹配时才允许 Agent 进入 ready 状态。

@ -95,7 +95,7 @@ Agent 配置字段:
| `max_body_bytes` | 请求体上限,默认 1 MiB,允许 1 KiB~1 MiB;云镜像正文不经过控制通道 |
| `clock_skew_seconds` | 签名时间窗,默认 300 秒 |
| `nonce_ttl_seconds` | nonce 保留时间,默认 600 秒且不得小于 `2 × clock_skew_seconds`,以覆盖未来时间戳请求的完整有效窗 |
| `operation_timeout_seconds` | 操作等待上限,默认 120 秒;超时不等于底层调用已取消 |
| `operation_timeout_seconds` | Agent API 内层操作等待上限,默认且最大为 840 秒;Agent WSS 控制层自动保留到 855 秒,外层 Gateway 固定 870 秒、PHP Worker 900 秒、任务租约 930 秒,逐层留出回执和持久化时间;超时不等于底层调用已取消 |
| `managed_storage_pool` | Agent 创建和删除 VM 系统盘的受管 libvirt 存储池名 |
| `template_storage_pool` | 已校验云镜像模板所在的 libvirt 存储池名 |
| `seed_storage_pool` | Agent 生成 cloud-init seed 卷的 libvirt 存储池名 |
@ -104,9 +104,9 @@ Agent 配置字段:
| `nvram_directory` | 受管每 VM NVRAM 文件目录的绝对路径 |
| `network_selectors` | PHP 只能引用的本机网络映射;每项 `type` 只能是 `bridge` 或 `network`,`source` 是预先存在的 bridge/libvirt network 名 |
上表的存储、固件和网络字段都是必填项。复制样例后,必须用目标宿主机实际的存储池、`virsh domcapabilities` 支持的 loader/VARS 组合和已准备的网络替换示例值。不得选用 `*.secboot.fd`;域 XML 必须保持 Q35 UEFI 且明确关闭 Secure Boot。`network_selectors` 的 key 是面板数据库中宿主机网络接入的稳定选择器,不是允许 PHP 传入任意网桥名。
上表的存储、固件和网络字段都是必填项。复制样例后,必须用目标宿主机实际的存储池、`virsh domcapabilities` 支持的 loader/VARS 组合和已准备的网络替换示例值。不得选用 `*.secboot.fd`;域 XML 必须保持 Q35 UEFI 且明确关闭 Secure Boot。`network_selectors` 最多配置 64 项;key 是面板数据库中宿主机网络接入的稳定选择器,新安装面板默认使用 `public`,实际 `br0` 只出现在 Agent 的 `source` 映射中,PHP 不能直传任意网桥名。能力探测要求至少一个 selector 可用,不会因为未启用的可选 selector 降级全部网络能力;Agent 只在 capabilities 中按字节序上报当前可用的 key,面板要求 `default_network` 精确匹配其中一项。修改 `default_network` 会立即撤销旧的 Agent 就绪结果,必须重新执行连接测试;每次创建或换网仍会单独确认本次选中的 bridge/libvirt network 处于活动状态。
Agent 的 systemd 单元保持 `ProtectSystem=strict`,进程只获准写 `/var/lib/virt-agent`。因此使用该单元时 `journal_path` 必须位于这个目录;若确需另一个状态目录,应由运维同时通过 systemd drop-in 精确增加对应 `ReadWritePaths`。`managed_storage_pool`、`template_storage_pool`、`seed_storage_pool` 和 `nvram_directory` 的实际文件写入由独立的 libvirt/QEMU 服务完成,Agent 只通过 `qemu:///system` API 提交操作;不要把这些宿主机目录加入 Agent 的 `ReadWritePaths`。capabilities 对 `nvram_directory` 只确认路径存在且为目录,不冒充对 libvirt 服务写权限的验证;正式上线仍须用授权的创建验收确认 libvirt/QEMU 对该目录和存储池具有权限。
Agent 的 systemd 单元保持 `ProtectSystem=strict`。`journal_path` 必须位于已授权的 `/var/lib/virt-agent`;若确需另一个状态目录,应由运维通过 systemd drop-in 精确增加对应 `ReadWritePaths`。存储池内容仍只由独立的 libvirt/QEMU 服务通过 `qemu:///system` 管理,不能把受管存储池目录授权给 Agent。删除回查需要清理域定义消失后残留的 UUID 专属 VARS 文件,因此样例 unit 仅额外授权标准 `/var/lib/libvirt/qemu/nvram`;若 `nvram_directory` 使用其他路径,必须在 drop-in 中用该实际目录替换,并保持授权范围只覆盖 NVRAM 目录。capabilities 只确认该目录存在,不冒充对 systemd mount namespace 写权限的验证;正式上线仍须用授权的创建/删除验收确认权限。
`journal_path` 是 bbolt 数据库,不是可编辑 JSON。nonce 通过独立到期索引清理,不会重写 operation 历史;到期时刻本身仍视为占用,只清理严格早于当前时刻的 nonce。独立 inflight 索引使启动只恢复 `reserved`/`dispatching`,不会扫描永久历史。终态结果详情保留 90 天后压缩,释放的 bbolt 页面会被后续写入复用,但 operation_id、请求指纹、资源、动作和终态会永久保留为防重放 tombstone。禁止以“清理历史”为由删除这些 tombstone。当前为全新 Go Agent 格式,不导入旧 Python 数据或早期 JSON 原型 journal。
@ -182,6 +182,8 @@ systemctl enable --now virt-cloud-update.service virt-cloud-agent-gateway.servic
面板 Agent Gateway 只监听 `127.0.0.1:8001`。`runtime/agent-gateway.json` 的 `panel_shared_secret` 必须与 PHP `cloud_agent_gateway_secret` 一致;`panel_introspection_url` 和 `panel_agent_auth_url` 必须分别是字面 loopback IP 上的 `/api/internal/cloud/session-introspection` 与 `/api/internal/cloud/agent-auth`。Gateway 在 Agent WSS 握手以及每次普通请求或控制台打开前请 PHP 重新核验当前连接保存的 Agent 凭据;核验失败会撤销该连接。
`agent_request_timeout_seconds` 必须为 `870`。完整截止时间顺序是 Agent API 840 秒、Agent WSS 控制层 855 秒、Gateway 870 秒、PHP 900 秒,普通 worker 的 930 秒租约再包住 PHP 请求。不要把各层设置成相同值,否则外层可能先超时并丢失 Agent 已生成的结构化回执。
Gateway 用 `X-Virt-*` HMAC 以 actor `{"service":"agent-gateway"}` 调用 PHP。首次内省必须原子消费面板票据:
```json

@ -75,7 +75,7 @@ Unix 时间戳
## 虚拟机、镜像与启动脚本
- 域 XML 使用结构化类型生成并验证输入,所有变更按 UUID 定位。部署每台宿主机时先查询 domain capabilities,把该机支持的 Q35/EFI loader 与 NVRAM template 写入本机 Agent 配置;创建请求不能传入任意固件路径。域 XML 明确关闭 `secure-boot` 和 enrolled keys,不在 PHP 中硬编码单一发行版 OVMF 路径。
- Agent 配置使用 `revision`/`tested_revision` 就绪门闩。保存密钥或启用状态会将 `tested_revision` 清零;只有同一 revision 经已认证出站会话完成 `/v1/health` 与 `/v1/capabilities` 才记录为就绪。调度、Agent 客户端以及控制台路径均要求 `enabled=1`、`last_test_status=healthy` 且 `tested_revision=revision`。
- Agent 配置使用 `revision`/`tested_revision` 就绪门闩。保存密钥、启用状态或宿主机 `default_network` 会推进 revision 并将 `tested_revision` 清零;只有同一 revision 经已认证出站会话完成 `/v1/health` 与 `/v1/capabilities`,且 `default_network` 精确存在于 Agent 上报的可用 `network_selectors`,才记录为就绪。调度、Agent 客户端以及控制台路径均要求 `enabled=1`、`last_test_status=healthy` 且 `tested_revision=revision`。
- 云镜像由 PHP 保存目录元数据和启动脚本。创建任务快照镜像 generation、revision 和脚本正文后签名发送给目标 Agent;删除后重新导入的同名镜像不能继承旧脚本。
- 启动脚本仅用于新云镜像实例的首次安装,不用于普通重启、网络设置、重装、救援或用户 ISO。脚本限制 32 KiB UTF-8,拒绝 NUL,CRLF 规范化为 LF,空值表示禁用。
- Agent 将脚本以 root 私有文件写入 cloud-init seed,由一次性 runner 原子记录 started 状态。成功、失败和中断都不自动重放;VM 创建成功不等待脚本结束。

@ -30,7 +30,7 @@
## 配置与幂等顺序
1. 按全新部署文档创建空数据库、运行 `php xcat cloudInit`,并启动 worker 与 lifecycle。
2. 在 `/admin/agents` 为宿主机保存独立 HMAC 密钥,在宿主机 Agent 中配置面板 HTTPS 地址、数字 Agent ID 和同一密钥;WSS/HMAC 健康测试通过后设置地区和唯一 `default_network`,桥接网络由管理员预先在宿主机准备好。
2. 在 `/admin/agents` 为宿主机保存独立 HMAC 密钥,在宿主机 Agent 中配置面板 HTTPS 地址、数字 Agent ID 和同一密钥;WSS/HMAC 健康测试通过后,把面板 `default_network` 设为 Agent `network_selectors` 中的稳定 key(新安装默认 `public`)。实际 `br0` 或 libvirt network 只写在宿主机 Agent 映射中,不能把 `bridge:br0` 当选择器直传。
3. 在“资源调度”中加入资源池,填写 CPU、内存、磁盘、安全余量和最大实例数。面板用这些策略减去 reservation/IP 账本计算剩余资源。
4. 在“公网地址池”逐个添加实际 CIDR。创建使用稳定 `request_key`,它确定性映射到池标识;更新使用页面读取的 `expected_revision`,旧表单不能覆盖新版本。
5. 面板在事务中保存配置并生成版本,然后向目标 Agent 提交同版本。签名响应匹配后标记 `applied`,自动物化 CIDR 中未保留的具体 IP;响应超时则标记 `uncertain`。

@ -190,3 +190,21 @@ authorized host mutation test: 未执行;用户明确禁止修改指定宿主
browser/payment/SMTP test: 自动化 PHP/Node 契约测试通过;真实支付、SMTP 和浏览器人工验收未执行
known skips or risks: 生产 Linux 上的 systemd-analyze、MariaDB 全新建库、真实 libvirt 生命周期与外部服务联调仍须在获授权测试环境验收;macOS libvirt 链接测试仅有重复库警告
```
### 2026-10-16 创建/回执一致性加固提交前验收
```text
commit: 本记录所在 go 分支提交(基线 177fa24)
Go version / libvirt version / PHP version / MariaDB version: Go 1.27.1 / 本机动态链接测试沿用已安装 libvirt / PHP 8.5.11 / MariaDB 未在本机运行
go vet: Agent 默认及 libvirt+dlopen、Gateway 均通过
go test: Agent 默认、libvirt、libvirt+dlopen 与 Gateway 均通过;两个 Go 模块的 mod verify 与 tidy -diff 均通过
go test -race: Agent libvirt+dlopen 与 Gateway 均通过
Linux AMD64 build: 提交后按实际提交源码交叉编译 Agent(CGo + libvirt_dlopen)和静态 Gateway 直运行二进制
PHP tests: 389 个 PHP 文件 lint 通过,116 个测试文件通过;仅输出既有 TicketAttachmentService warning 与 Predis deprecation,退出码为 0
Node tests: 89 个 JavaScript 文件语法检查通过,4 个行为测试通过;部署 JSON 示例有效
systemd-analyze: 待在 Linux 面板/宿主机部署时执行
read-only host capability check: 待对指定 103 宿主机部署前复核
authorized host mutation test: 待部署后在用户指定的测试环境按 operation_id 串行验收
browser/payment/SMTP test: 自动化 PHP/Node 契约测试通过;真实创建付款需在最终提交动作前取得用户即时确认
known skips or risks: libvirt 调用已执行但结果不可证明时会安全保留 uncertain,必须复用原 operation_id 核对,禁止自动重放;macOS libvirt 链接仅有重复库警告
```

@ -23,6 +23,12 @@ unknown fields and trailing values. They deliberately do **not** reject a
readable configuration because of its owner, group, or mode; missing,
unreadable, malformed, or unsafe configuration still fails startup.
The Agent request deadline is deliberately fixed at 870 seconds in the
Gateway configuration. The host Agent API caps operations at 840 seconds, its
WSS control envelope waits 855 seconds, PHP waits up to 900 seconds, and the
worker lease lasts 930 seconds. These margins let each outer layer receive and
durably classify the inner layer's result instead of timing out first.
## Authentication
The update API and gateway-to-PHP requests use the shared `X-Virt-*` contract:
@ -123,6 +129,13 @@ JSON body. Control frames are bounded JSON text frames:
{"type":"response","id":"...","status":200,"body":"{...}"}
```
Failures proven to occur before the host's durable operation journal carry the
exact error field `"dispatch_state":"not_dispatched"`. The PHP worker may
requeue only retryable 5xx responses with that strict marker; terminal
authentication, route, and validation errors fail the job without polling a
record that cannot exist. Gateway or Agent nonce replay errors deliberately
omit the marker because the first request may already have been dispatched.
For a browser console, `/engine-console` requires a same-origin `Origin`, the
trusted proxy's single `X-Forwarded-Proto`, and exactly one browser subprotocol:
@ -162,8 +175,10 @@ The Agent consumes the ticket locally, then connects outward to
virt-agent-console.<session-token>
```
Only binary WebSocket messages are copied. Every 15 seconds the gateway signs a
second introspection request:
Only binary WebSocket messages are copied. The gateway sends a WebSocket Ping
control frame every 25 seconds on both the browser and reverse-Agent legs and
requires a Pong within 10 seconds; these control frames never enter the VNC
byte stream. Every 15 seconds the gateway signs a second introspection request:
```json
{"ticket":"...","connection_id":"...","consume":false}

@ -31,6 +31,7 @@ const (
maxConsoleFrame = 8 << 20
maxInFlightPerAgent = 32
maxPendingConsoles = 64
maximumRequestTimeout = 870 * time.Second
)
var (
@ -107,7 +108,7 @@ type Registry struct {
}
func NewRegistry(authenticator ConnectionAuthenticator, sharedSecret []byte, requestTimeout, consoleTimeout time.Duration) (*Registry, error) {
if authenticator == nil || len(sharedSecret) < 32 || requestTimeout <= 0 || requestTimeout > 15*time.Minute ||
if authenticator == nil || len(sharedSecret) < 32 || requestTimeout <= 0 || requestTimeout > maximumRequestTimeout ||
consoleTimeout <= 0 || consoleTimeout > 30*time.Second {
return nil, errors.New("invalid Agent registry settings")
}
@ -189,6 +190,18 @@ func (r *Registry) ServeInternalRequest(response http.ResponseWriter, request *h
return
}
actor, err := r.requestAuth.Authenticate(request, body)
if errors.Is(err, protocol.ErrReplay) {
// The first request carrying this nonce may already have reached the
// host Agent. Never attach a no-dispatch proof to a replay rejection.
writeInternalAmbiguousError(response, http.StatusForbidden,
"gateway_replayed_request", "Agent gateway request nonce was already used")
return
}
if errors.Is(err, protocol.ErrNonceStore) {
writeInternalRetryableError(response, http.StatusServiceUnavailable,
"gateway_nonce_store_unavailable", "Agent gateway authentication state is unavailable")
return
}
if err != nil || !exactServiceActor(actor, "php-panel") {
writeInternalError(response, http.StatusForbidden, "gateway_forbidden", "Agent gateway request is forbidden")
return
@ -678,6 +691,20 @@ func writeJSON(response http.ResponseWriter, status int, value any) {
}
func writeInternalError(response http.ResponseWriter, status int, code, message string) {
writeJSON(response, status, map[string]any{"error": map[string]any{
"code": code, "message": message, "retryable": false,
"dispatch_state": "not_dispatched",
}})
}
func writeInternalRetryableError(response http.ResponseWriter, status int, code, message string) {
writeJSON(response, status, map[string]any{"error": map[string]any{
"code": code, "message": message, "retryable": true,
"dispatch_state": "not_dispatched",
}})
}
func writeInternalAmbiguousError(response http.ResponseWriter, status int, code, message string) {
writeJSON(response, status, map[string]any{"error": map[string]any{
"code": code, "message": message, "retryable": false,
}})

@ -43,6 +43,12 @@ type allowConnectionAuthenticator struct {
calls int
}
type failingGatewayNonceStore struct{}
func (failingGatewayNonceStore) UseNonce(string, time.Time, time.Time) (bool, error) {
return false, errors.New("nonce store unavailable")
}
func (a *allowConnectionAuthenticator) Authenticate(_ context.Context, agentID, secret string) error {
a.mu.Lock()
defer a.mu.Unlock()
@ -188,6 +194,63 @@ func TestRegistryRejectsInternalRequestFromMixedServiceActor(t *testing.T) {
}
}
func TestRegistryReplayRejectionDoesNotClaimNotDispatched(t *testing.T) {
registry, _, shared, _ := newTestRegistry(t)
body := []byte(`{"agent_id":"12","type":"request","id":"request_12345678","method":"GET","request_target":"/v1/health","body":"","headers":{}}`)
serve := func() *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPost, InternalRequestPath,
bytes.NewReader(body))
request.RemoteAddr = "127.0.0.1:43126"
if err := protocol.Sign(request, body,
protocol.Actor{Service: "php-panel"}, shared, time.Now(),
"fixed_gateway_nonce_1234"); err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
registry.ServeInternalRequest(response, request)
return response
}
first := serve()
if first.Code != http.StatusBadGateway ||
!strings.Contains(first.Body.String(), `"dispatch_state":"not_dispatched"`) {
t.Fatalf("first response = %d %s", first.Code, first.Body.String())
}
replay := serve()
if replay.Code != http.StatusForbidden ||
!strings.Contains(replay.Body.String(), `"code":"gateway_replayed_request"`) ||
strings.Contains(replay.Body.String(), `"dispatch_state"`) {
t.Fatalf("replay response = %d %s", replay.Code, replay.Body.String())
}
}
func TestRegistryNonceStoreFailureIsRetryableNotDispatched(t *testing.T) {
registry, _, shared, _ := newTestRegistry(t)
authenticator, err := protocol.NewAuthenticator(
shared, time.Minute, 2*time.Minute, failingGatewayNonceStore{},
)
if err != nil {
t.Fatal(err)
}
registry.requestAuth = authenticator
body := []byte(`{"agent_id":"12","type":"request","id":"request_12345678","method":"GET","request_target":"/v1/health","body":"","headers":{}}`)
request := httptest.NewRequest(http.MethodPost, InternalRequestPath,
bytes.NewReader(body))
request.RemoteAddr = "127.0.0.1:43127"
nonce, _ := protocol.RandomNonce()
if err := protocol.Sign(request, body, protocol.Actor{Service: "php-panel"},
shared, time.Now(), nonce); err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
registry.ServeInternalRequest(response, request)
if response.Code != http.StatusServiceUnavailable ||
!strings.Contains(response.Body.String(), `"code":"gateway_nonce_store_unavailable"`) ||
!strings.Contains(response.Body.String(), `"retryable":true`) ||
!strings.Contains(response.Body.String(), `"dispatch_state":"not_dispatched"`) {
t.Fatalf("response = %d %s", response.Code, response.Body.String())
}
}
func TestRegistryReturnsTypedJSONForRejectedInternalRequests(t *testing.T) {
registry, _, shared, _ := newTestRegistry(t)
@ -381,9 +444,10 @@ func assertInternalError(t *testing.T, response *http.Response, status int, code
defer response.Body.Close()
var payload struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
DispatchState string `json:"dispatch_state"`
} `json:"error"`
}
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
@ -391,6 +455,7 @@ func assertInternalError(t *testing.T, response *http.Response, status int, code
}
if response.StatusCode != status || payload.Error.Code != code ||
payload.Error.Message == "" || payload.Error.Retryable ||
payload.Error.DispatchState != "not_dispatched" ||
!strings.HasPrefix(response.Header.Get("Content-Type"), "application/json") {
t.Fatalf("unexpected internal error status=%d payload=%#v headers=%v", response.StatusCode, payload, response.Header)
}
@ -530,3 +595,11 @@ func TestRegistryBoundsPendingReverseConsoles(t *testing.T) {
t.Fatalf("rejected console leaked session admission: in_flight=%d pending=%d", len(current.inFlight), len(current.pending))
}
}
func TestRegistryRejectsRequestTimeoutBeyondLayeredDeadline(t *testing.T) {
_, err := NewRegistry(&allowConnectionAuthenticator{}, []byte(strings.Repeat("p", 32)),
maximumRequestTimeout+time.Second, 2*time.Second)
if err == nil {
t.Fatal("request timeout beyond the PHP/Gateway deadline margin was accepted")
}
}

@ -15,10 +15,11 @@ import (
)
const (
RequiredListenAddress = "127.0.0.1:8001"
RequiredIntrospectionPath = "/api/internal/cloud/session-introspection"
RequiredAgentAuthPath = "/api/internal/cloud/agent-auth"
maxConfigBytes = 64 << 10
RequiredListenAddress = "127.0.0.1:8001"
RequiredIntrospectionPath = "/api/internal/cloud/session-introspection"
RequiredAgentAuthPath = "/api/internal/cloud/agent-auth"
RequiredAgentRequestTimeoutSeconds = 870
maxConfigBytes = 64 << 10
)
type Config struct {
@ -76,8 +77,10 @@ func (c Config) Validate() error {
if c.ConnectTimeoutSeconds < 1 || c.ConnectTimeoutSeconds > 30 {
problems = append(problems, "connect_timeout_seconds must be between 1 and 30")
}
if c.AgentRequestTimeoutSeconds < 1 || c.AgentRequestTimeoutSeconds > 900 {
problems = append(problems, "agent_request_timeout_seconds must be between 1 and 900")
// Keep the production request envelope strictly between the Agent's 840s
// operation cap and PHP's 900s HTTP deadline.
if c.AgentRequestTimeoutSeconds != RequiredAgentRequestTimeoutSeconds {
problems = append(problems, "agent_request_timeout_seconds must be 870")
}
if len(problems) != 0 {
return errors.New(strings.Join(problems, "; "))

@ -9,7 +9,7 @@ import (
func TestLoadConfigDoesNotAuditOwnershipOrMode(t *testing.T) {
path := filepath.Join(t.TempDir(), "agent-gateway.json")
raw := `{"listen_address":"127.0.0.1:8001","panel_introspection_url":"http://127.0.0.1/api/internal/cloud/session-introspection","panel_agent_auth_url":"http://127.0.0.1/api/internal/cloud/agent-auth","panel_shared_secret":"0123456789abcdef0123456789abcdef","connect_timeout_seconds":10,"agent_request_timeout_seconds":900}`
raw := `{"listen_address":"127.0.0.1:8001","panel_introspection_url":"http://127.0.0.1/api/internal/cloud/session-introspection","panel_agent_auth_url":"http://127.0.0.1/api/internal/cloud/agent-auth","panel_shared_secret":"0123456789abcdef0123456789abcdef","connect_timeout_seconds":10,"agent_request_timeout_seconds":870}`
if err := os.WriteFile(path, []byte(raw), 0o644); err != nil {
t.Fatal(err)
}
@ -34,12 +34,12 @@ func TestConfigRejectsRemoteIntrospectionAndUnknownFields(t *testing.T) {
PanelIntrospectionURL: "https://198.51.100.2" + RequiredIntrospectionPath,
PanelAgentAuthURL: "http://127.0.0.1" + RequiredAgentAuthPath,
PanelSharedSecret: strings.Repeat("s", 32), ConnectTimeoutSeconds: 10,
AgentRequestTimeoutSeconds: 900}
AgentRequestTimeoutSeconds: 870}
if err := config.Validate(); err == nil {
t.Fatal("remote introspection endpoint accepted")
}
path := filepath.Join(t.TempDir(), "agent-gateway.json")
raw := `{"listen_address":"127.0.0.1:8001","panel_introspection_url":"http://127.0.0.1/api/internal/cloud/session-introspection","panel_agent_auth_url":"http://127.0.0.1/api/internal/cloud/agent-auth","panel_shared_secret":"0123456789abcdef0123456789abcdef","connect_timeout_seconds":10,"agent_request_timeout_seconds":900,"unexpected":true}`
raw := `{"listen_address":"127.0.0.1:8001","panel_introspection_url":"http://127.0.0.1/api/internal/cloud/session-introspection","panel_agent_auth_url":"http://127.0.0.1/api/internal/cloud/agent-auth","panel_shared_secret":"0123456789abcdef0123456789abcdef","connect_timeout_seconds":10,"agent_request_timeout_seconds":870,"unexpected":true}`
if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
t.Fatal(err)
}
@ -53,7 +53,7 @@ func TestConfigRejectsExplicitEmptyPanelPorts(t *testing.T) {
PanelIntrospectionURL: "http://127.0.0.1:" + RequiredIntrospectionPath,
PanelAgentAuthURL: "http://127.0.0.1" + RequiredAgentAuthPath,
PanelSharedSecret: strings.Repeat("s", 32), ConnectTimeoutSeconds: 10,
AgentRequestTimeoutSeconds: 900}
AgentRequestTimeoutSeconds: 870}
if err := config.Validate(); err == nil {
t.Fatal("explicit empty introspection port was accepted")
}
@ -73,3 +73,21 @@ func TestConfigRejectsExplicitEmptyPanelPorts(t *testing.T) {
}
}
}
func TestConfigRequiresLayeredAgentRequestTimeout(t *testing.T) {
base := Config{ListenAddress: RequiredListenAddress,
PanelIntrospectionURL: "http://127.0.0.1" + RequiredIntrospectionPath,
PanelAgentAuthURL: "http://127.0.0.1" + RequiredAgentAuthPath,
PanelSharedSecret: strings.Repeat("s", 32), ConnectTimeoutSeconds: 10}
for _, timeout := range []int{1, 840, 869, 871, 900} {
config := base
config.AgentRequestTimeoutSeconds = timeout
if err := config.Validate(); err == nil || !strings.Contains(err.Error(), "must be 870") {
t.Fatalf("non-layered Agent request timeout %d error = %v", timeout, err)
}
}
base.AgentRequestTimeoutSeconds = RequiredAgentRequestTimeoutSeconds
if err := base.Validate(); err != nil {
t.Fatalf("required Agent request timeout rejected: %v", err)
}
}

@ -15,8 +15,10 @@ import (
)
const (
BrowserProtocolPrefix = "cloud-ticket."
defaultMaximumFrame = 8 << 20
BrowserProtocolPrefix = "cloud-ticket."
defaultMaximumFrame = 8 << 20
consoleHeartbeatInterval = 25 * time.Second
consoleHeartbeatTimeout = 10 * time.Second
)
var opaqueTokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`)
@ -27,25 +29,34 @@ type ReverseConsoleConnector interface {
}
type Relay struct {
introspector SessionIntrospector
connector ReverseConsoleConnector
recheckEvery time.Duration
maxFrame int64
now func() time.Time
lifecycleMu sync.Mutex
draining bool
active sync.WaitGroup
next uint64
cancels map[uint64]context.CancelFunc
introspector SessionIntrospector
connector ReverseConsoleConnector
recheckEvery time.Duration
heartbeatEvery time.Duration
heartbeatTimeout time.Duration
maxFrame int64
now func() time.Time
lifecycleMu sync.Mutex
draining bool
active sync.WaitGroup
next uint64
cancels map[uint64]context.CancelFunc
}
func NewRelay(introspector SessionIntrospector, connector ReverseConsoleConnector) (*Relay, error) {
if introspector == nil || connector == nil {
return nil, errors.New("invalid console relay settings")
}
return &Relay{introspector: introspector, connector: connector,
recheckEvery: 15 * time.Second, maxFrame: defaultMaximumFrame, now: time.Now,
cancels: make(map[uint64]context.CancelFunc)}, nil
return &Relay{
introspector: introspector,
connector: connector,
recheckEvery: 15 * time.Second,
heartbeatEvery: consoleHeartbeatInterval,
heartbeatTimeout: consoleHeartbeatTimeout,
maxFrame: defaultMaximumFrame,
now: time.Now,
cancels: make(map[uint64]context.CancelFunc),
}, nil
}
func (r *Relay) ServeHTTP(response http.ResponseWriter, request *http.Request) {
@ -178,10 +189,16 @@ func validateInitialResult(result IntrospectionResult, now time.Time) error {
func (r *Relay) relay(parent context.Context, browser, agent *websocket.Conn, ticket, connectionID string) {
ctx, cancel := context.WithCancel(parent)
errorsChannel := make(chan error, 3)
errorsChannel := make(chan error, 5)
go func() { errorsChannel <- copyBinary(ctx, browser, agent) }()
go func() { errorsChannel <- copyBinary(ctx, agent, browser) }()
go func() { errorsChannel <- r.revalidate(ctx, ticket, connectionID) }()
go func() {
errorsChannel <- maintainConsoleHeartbeat(ctx, browser, r.heartbeatEvery, r.heartbeatTimeout)
}()
go func() {
errorsChannel <- maintainConsoleHeartbeat(ctx, agent, r.heartbeatEvery, r.heartbeatTimeout)
}()
err := <-errorsChannel
cancel()
_ = err
@ -193,6 +210,41 @@ func (r *Relay) relay(parent context.Context, browser, agent *websocket.Conn, ti
}
}
type consolePinger interface {
Ping(context.Context) error
}
// maintainConsoleHeartbeat keeps an otherwise static console WebSocket alive
// through reverse proxies and detects a half-open peer. Ping and Pong are
// WebSocket control frames, so they never enter the binary-only VNC stream.
// Ping is intentionally run alongside copyBinary: coder/websocket requires an
// active Reader to process the peer's Pong and supports concurrent methods.
func maintainConsoleHeartbeat(
ctx context.Context,
connection consolePinger,
interval time.Duration,
timeout time.Duration,
) error {
if interval <= 0 || timeout <= 0 {
return errors.New("console heartbeat timing is invalid")
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
pingCtx, cancel := context.WithTimeout(ctx, timeout)
err := connection.Ping(pingCtx)
cancel()
if err != nil {
return errors.Join(errors.New("console heartbeat failed"), err)
}
}
}
}
var errSessionRevoked = errors.New("console session revoked")
func (r *Relay) revalidate(ctx context.Context, ticket, connectionID string) error {

@ -56,10 +56,24 @@ func (f *fakeConnector) OpenConsole(ctx context.Context, agentID, ticket, sessio
}
func newAgentServer(t *testing.T) *httptest.Server {
return newAgentServerWithPingBehavior(t, nil, true)
}
func newObservedAgentServer(t *testing.T, pings *atomic.Int32) *httptest.Server {
return newAgentServerWithPingBehavior(t, pings, true)
}
func newAgentServerWithPingBehavior(t *testing.T, pings *atomic.Int32, respond bool) *httptest.Server {
t.Helper()
return httptest.NewTLSServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
connection, err := websocket.Accept(response, request, &websocket.AcceptOptions{
CompressionMode: websocket.CompressionDisabled,
OnPingReceived: func(context.Context, []byte) bool {
if pings != nil {
pings.Add(1)
}
return respond
},
})
if err != nil {
return
@ -77,6 +91,101 @@ func newAgentServer(t *testing.T) *httptest.Server {
}))
}
func TestRelayHeartbeatsBothIdleConsoleWebSocketsWithoutDataFrames(t *testing.T) {
var agentPings atomic.Int32
var browserPings atomic.Int32
agentServer := newObservedAgentServer(t, &agentPings)
defer agentServer.Close()
introspector := &fakeIntrospector{}
connector := &fakeConnector{url: "wss" + strings.TrimPrefix(agentServer.URL, "https"), client: agentServer.Client()}
relay, _ := NewRelay(introspector, connector)
relay.recheckEvery = time.Hour
relay.heartbeatEvery = 5 * time.Millisecond
relay.heartbeatTimeout = 100 * time.Millisecond
server := httptest.NewServer(relay)
defer server.Close()
connection := dialBrowserWithPingHandler(t, server.URL, strings.Repeat("h", 32),
func(context.Context, []byte) bool {
browserPings.Add(1)
return true
})
defer connection.CloseNow()
type readResult struct {
messageType websocket.MessageType
body []byte
err error
}
read := make(chan readResult, 1)
go func() {
messageType, body, readErr := connection.Read(context.Background())
read <- readResult{messageType: messageType, body: body, err: readErr}
}()
deadline := time.Now().Add(time.Second)
for (agentPings.Load() == 0 || browserPings.Load() == 0) && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if agentPings.Load() == 0 || browserPings.Load() == 0 {
t.Fatalf("heartbeats not observed: agent=%d browser=%d", agentPings.Load(), browserPings.Load())
}
if err := connection.Write(t.Context(), websocket.MessageBinary, []byte("RFB-after-heartbeat")); err != nil {
t.Fatal(err)
}
select {
case result := <-read:
if result.err != nil || result.messageType != websocket.MessageBinary || string(result.body) != "RFB-after-heartbeat" {
t.Fatalf("post-heartbeat frame type=%v body=%q err=%v", result.messageType, result.body, result.err)
}
case <-time.After(time.Second):
t.Fatal("binary console data stalled after heartbeat")
}
}
func TestRelayClosesConsoleWhenBrowserDoesNotPong(t *testing.T) {
agentServer := newAgentServer(t)
defer agentServer.Close()
introspector := &fakeIntrospector{}
connector := &fakeConnector{url: "wss" + strings.TrimPrefix(agentServer.URL, "https"), client: agentServer.Client()}
relay, _ := NewRelay(introspector, connector)
relay.recheckEvery = time.Hour
relay.heartbeatEvery = 5 * time.Millisecond
relay.heartbeatTimeout = 20 * time.Millisecond
server := httptest.NewServer(relay)
defer server.Close()
connection := dialBrowserWithPingHandler(t, server.URL, strings.Repeat("i", 32),
func(context.Context, []byte) bool { return false })
defer connection.CloseNow()
readContext, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if _, _, err := connection.Read(readContext); err == nil {
t.Fatal("console remained open after the browser stopped answering Ping")
}
}
func TestRelayClosesBrowserWhenAgentDoesNotPong(t *testing.T) {
agentServer := newAgentServerWithPingBehavior(t, nil, false)
defer agentServer.Close()
introspector := &fakeIntrospector{}
connector := &fakeConnector{url: "wss" + strings.TrimPrefix(agentServer.URL, "https"), client: agentServer.Client()}
relay, _ := NewRelay(introspector, connector)
relay.recheckEvery = time.Hour
relay.heartbeatEvery = 5 * time.Millisecond
relay.heartbeatTimeout = 20 * time.Millisecond
server := httptest.NewServer(relay)
defer server.Close()
connection := dialBrowser(t, server.URL, strings.Repeat("j", 32))
defer connection.CloseNow()
readContext, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if _, _, err := connection.Read(readContext); err == nil {
t.Fatal("browser console remained open after the Agent stopped answering Ping")
}
}
func TestRelayForwardsOnlyBinaryAndConsumesTicketOnce(t *testing.T) {
agentServer := newAgentServer(t)
defer agentServer.Close()
@ -237,12 +346,22 @@ func TestValidateInitialResultRequiresLiveShortLivedAgentTicket(t *testing.T) {
}
func dialBrowser(t *testing.T, serverURL, ticket string) *websocket.Conn {
return dialBrowserWithPingHandler(t, serverURL, ticket, nil)
}
func dialBrowserWithPingHandler(
t *testing.T,
serverURL string,
ticket string,
onPingReceived func(context.Context, []byte) bool,
) *websocket.Conn {
t.Helper()
websocketURL := "ws" + strings.TrimPrefix(serverURL, "http") + "/engine-console"
host := strings.TrimPrefix(serverURL, "http://")
connection, response, err := websocket.Dial(t.Context(), websocketURL, &websocket.DialOptions{
Subprotocols: []string{BrowserProtocolPrefix + ticket},
HTTPHeader: http.Header{"Origin": []string{"http://" + host}, "X-Forwarded-Proto": []string{"http"}},
Subprotocols: []string{BrowserProtocolPrefix + ticket},
HTTPHeader: http.Header{"Origin": []string{"http://" + host}, "X-Forwarded-Proto": []string{"http"}},
OnPingReceived: onPingReceived,
})
if response != nil && response.Body != nil {
_ = response.Body.Close()

@ -68,21 +68,43 @@ final class CloudAdminController
$countryCode = CloudCountryCatalog::normalize($body['country_code'] ?? null);
$network = $body['default_network'] ?? '';
if (!is_string($network)
|| preg_match('/^(?:bridge|network):[A-Za-z0-9_.-]{1,64}$/D', $network) !== 1) {
throw new CloudError('默认网络必须使用 bridge:名称 或 network:名称');
}
$host = isset($args['id']) ? $this->host($args['id']) : new CloudHost();
if (!$host->exists) {
$host->created_at = $host->updated_at = time();
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $network) !== 1) {
throw new CloudError(
'默认网络必须填写 Agent network_selectors 中已配置的选择器 key'
);
}
$host->name = trim($name);
$host->region = $body['region'];
$host->country_code = $countryCode;
$host->default_network = $network;
$host->enabled = $enabled;
$host->updated_at = time();
$host->save();
return $response->withJson($host->toArray(), isset($args['id']) ? 200 : 201)
$isUpdate = isset($args['id']);
$hostId = $isUpdate ? (int) $args['id'] : 0;
$connection = (new CloudHost())->getConnection();
$host = $connection->transaction(static function () use (
$isUpdate, $hostId, $name, $body, $countryCode, $network, $enabled
): CloudHost {
$host = $isUpdate
? CloudHost::query()->where('id', $hostId)->lockForUpdate()->first()
: new CloudHost();
if ($host === null) {
throw new CloudError('宿主机不存在', 404);
}
$networkChanged = $host->exists
&& (string) $host->default_network !== $network;
if (!$host->exists) {
$host->created_at = $host->updated_at = time();
}
$host->name = trim($name);
$host->region = $body['region'];
$host->country_code = $countryCode;
$host->default_network = $network;
$host->enabled = $enabled;
$host->updated_at = time();
$host->save();
if ($networkChanged) {
CloudAgentSettingsService::invalidateForNetworkSelectorChange(
(int) $host->id
);
}
return $host;
});
return $response->withJson($host->toArray(), $isUpdate ? 200 : 201)
->withHeader('Cache-Control', 'no-store');
}

@ -1138,6 +1138,8 @@ final class CloudApiController
if (($body['confirmation_name'] ?? '') !== $instance->name) {
throw new CloudError('请填写虚拟机名称确认重装');
}
// Browser-only confirmation must never cross the strict Go Agent DTO.
unset($body['confirmation_name']);
$body['template_id'] = CloudInput::template($body['template_id'] ?? null);
$key = CloudSSHKeys::owned($body['ssh_key_id'] ?? null, $actor['user_id']);
unset($body['ssh_key_id']);

@ -155,8 +155,9 @@ final class CloudAdminHostNetworkService
}
$selector = trim((string) $lockedHost->default_network);
if ($selector === '' || strlen($selector) > 128
|| preg_match('/[\x00-\x1f\x7f]/', $selector) === 1) {
if (preg_match(
'/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $selector
) !== 1) {
throw new CloudError('宿主机默认网络配置无效', 409);
}
$attachmentKey = substr(hash('sha256', $selector), 0, 32);
@ -341,8 +342,7 @@ final class CloudAdminHostNetworkService
}
$attachment->line_id = (int) $resourcePool->line_id;
$attachment->name = mb_substr($selector, 0, 80);
$attachment->network_mode = str_starts_with($selector, 'bridge:')
? 'bridge' : 'network';
$attachment->network_mode = 'selector';
$attachment->network_selector = $selector;
if ($pool === null) {

@ -17,6 +17,7 @@ final class CloudAdminOperationsService
* Agent; it only prevents a worker from claiming the row again.
*/
private const CANCELLABLE_KINDS = [
'action',
'snapshot_create', 'snapshot_restore', 'snapshot_delete',
'delete', 'expiry_delete',
];

@ -311,34 +311,46 @@ final class CloudAgentClient
[$message, $panelStatus, $retryable] = match ($status) {
400, 422 => ['Agent 拒绝了请求参数', 422, false],
401 => ['Agent API 身份验证失败,请重新核对密钥', 502, false],
403 => $code === 'gateway_forbidden'
? ['Agent 网关身份验证失败,请重新核对网关密钥', 502, false]
: ['Agent 拒绝了未授权的操作请求', 403, false],
404 => ['Agent 上的目标资源不存在', 404, false],
409 => ['Agent 拒绝冲突或重复的操作请求', 409, false],
501 => ['当前 Agent 不支持此项功能', 501, false],
503 => ['宿主机 Agent 或虚拟化后端暂不可用', 503, true],
default => ['宿主机 Agent 操作未成功', 502, $status >= 500],
};
$safeCreateFailure = in_array($status, [400, 422], true)
&& count($payload) === 1
&& array_key_exists('error', $payload)
&& is_string($error['message'] ?? null)
&& is_bool($error['retryable'] ?? null)
&& $error['retryable'] === false
&& !array_key_exists('operation', $error);
$safePreDispatchFailure = in_array($status, [502, 503], true)
&& count($payload) === 1
$strictNotDispatched = count($payload) === 1
&& array_key_exists('error', $payload)
&& count($error) === 4
&& array_diff_key($error, array_flip([
'code', 'message', 'retryable', 'dispatch_state',
])) === []
&& in_array($code, [
'agent_busy', 'agent_disconnected', 'gateway_draining',
], true)
&& is_string($error['message'] ?? null)
&& ($error['retryable'] ?? null) === true
&& ($error['dispatch_state'] ?? null) === 'not_dispatched';
// Only an exact explicit dispatch_state contract may authorize a
// terminal failure/refund or a same-operation retry. In particular,
// replayed_request and gateway_replayed_request are ambiguous because
// the first request carrying that nonce may already have dispatched.
$safeValidationFailure = $strictNotDispatched
&& ($error['retryable'] ?? null) === false
&& !in_array($code,
['replayed_request', 'gateway_replayed_request'], true)
&& (
in_array($status, [400, 413, 422, 501], true)
|| ($status === 401 && $code === 'unauthorized')
|| $status === 403
|| ($status === 404 && in_array($code,
['not_found', 'gateway_route_not_found'], true))
|| ($status === 405 && $code === 'method_not_allowed')
);
$safePreDispatchFailure = $strictNotDispatched
&& ($error['retryable'] ?? null) === true
&& $status >= 500 && $status <= 504
&& !in_array($code,
['replayed_request', 'gateway_replayed_request'], true);
return new CloudAgentError($message, $panelStatus, $code,
$retryable, $status, $safeCreateFailure,
$retryable, $status, $safeValidationFailure,
$safePreDispatchFailure);
}

@ -10,9 +10,9 @@ final class CloudAgentError extends CloudError
public readonly string $agentCode,
public readonly bool $retryable = false,
public readonly ?int $agentHttpStatus = null,
/** Exact 400/422 error envelope without an Agent operation record. */
public readonly bool $safeCreateFailure = false,
/** Gateway/Agent proof that the API handler was never entered. */
/** Exact terminal no-journal envelope (validation/auth/route contract). */
public readonly bool $safeValidationFailure = false,
/** Exact retryable proof that the durable operation journal was never entered. */
public readonly bool $safePreDispatchFailure = false
) {
parent::__construct($message, $httpStatus);

@ -0,0 +1,37 @@
<?php
namespace App\Services\Cloud;
/** Read-only reconciliation for one already-persisted Agent operation. */
final class CloudAgentOperationReconciler
{
/**
* Reconcile only a matching uncertain record. A dispatching operation is
* still executing and must remain on the ordinary status-polling path.
*/
public static function ifUncertain(
$client,
string $operationId,
array $actor,
array $operation
): array {
if (($operation['operation_id'] ?? null) !== $operationId
|| strtolower(trim((string) ($operation['status'] ?? '')))
!== 'uncertain') {
return $operation;
}
try {
return $client->request(
'POST',
'/v1/operations/' . rawurlencode($operationId) . '/reconcile',
$actor,
[]
);
} catch (\Throwable) {
// The original mutation is already uncertain. A failed read-only
// reconciliation request cannot prove it failed and must never be
// allowed to downgrade catalog/import/delete state to "failed".
return $operation;
}
}
}

@ -7,6 +7,8 @@ use App\Models\CloudHostAgent;
final class CloudAgentSettingsService
{
private const MAX_NETWORK_SELECTORS = 64;
private const REQUIRED_FEATURES = [
'create_vm', 'delete_vm', 'power', 'settings', 'network',
'reinstall', 'snapshots', 'firewall', 'rescue', 'metrics',
@ -142,7 +144,9 @@ final class CloudAgentSettingsService
$capabilities = self::client($setting)->request(
'GET', '/v1/capabilities', $actor
);
$summary = self::capabilitySummary($capabilities);
$summary = self::capabilitySummary(
$capabilities, (string) $host->default_network
);
self::recordTest($hostId, $expectedRevision, 'healthy', '',
$health['version']);
$fresh = CloudHostAgent::find($hostId);
@ -161,15 +165,33 @@ final class CloudAgentSettingsService
}
}
/** Return only bounded feature flags; never pass checks or host paths on. */
private static function capabilitySummary(array $capabilities): array
/** Return bounded feature flags and stable selector keys, never host paths. */
private static function capabilitySummary(
array $capabilities,
string $requiredNetworkSelector
): array
{
$features = $capabilities['features'] ?? null;
$selectors = $capabilities['network_selectors'] ?? null;
if (($capabilities['backend'] ?? null) !== 'libvirt'
|| !is_array($features) || array_is_list($features)) {
|| !is_array($features) || array_is_list($features)
|| !is_array($selectors) || !array_is_list($selectors)
|| $selectors === []
|| count($selectors) > self::MAX_NETWORK_SELECTORS) {
throw new CloudAgentError('宿主机 Agent 后端能力响应无效', 502,
'agent_invalid_capabilities', false, 200);
}
$previous = null;
foreach ($selectors as $selector) {
if (!is_string($selector)
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D',
$selector) !== 1
|| ($previous !== null && strcmp($previous, $selector) >= 0)) {
throw new CloudAgentError('宿主机 Agent 网络选择器响应无效',
502, 'agent_invalid_capabilities', false, 200);
}
$previous = $selector;
}
$known = array_merge(self::REQUIRED_FEATURES,
['uefi', 'secure_boot']);
foreach ($known as $feature) {
@ -191,16 +213,44 @@ final class CloudAgentSettingsService
409, 'agent_capability_mismatch', false, 200
);
}
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D',
$requiredNetworkSelector) !== 1
|| !in_array($requiredNetworkSelector, $selectors, true)) {
throw new CloudAgentError(
'宿主机 Agent 未提供当前宿主机配置的网络选择器',
409, 'agent_capability_mismatch', false, 200
);
}
return [
'backend' => 'libvirt',
'uefi' => true,
'secure_boot' => false,
'network_selectors' => $selectors,
'required_network_selector' => $requiredNetworkSelector,
'required_feature_count' => count(self::REQUIRED_FEATURES),
'available_features' => self::REQUIRED_FEATURES,
'unavailable_features' => [],
];
}
/** Revoke a stale readiness result after the panel selector changes. */
public static function invalidateForNetworkSelectorChange(int $hostId): void
{
$setting = CloudHostAgent::query()->where('host_id', $hostId)
->lockForUpdate()->first();
if ($setting === null) {
return;
}
$setting->revision = (int) $setting->revision + 1;
$setting->tested_revision = 0;
$setting->last_test_status = 'never';
$setting->last_error_code = '';
$setting->last_agent_version = '';
$setting->last_tested_at = 0;
$setting->updated_at = time();
$setting->save();
}
public static function clientForHost(
int $hostId,
float $timeoutSeconds = 20.0

@ -21,6 +21,9 @@ final class CloudJobService
CloudTemplateCatalogService::assertProvisionable(
CloudInput::template($body['template_id'] ?? '')
);
// Defense in depth for internal callers: this UI confirmation
// is not part of the strict Agent ReinstallRequest schema.
unset($body['confirmation_name']);
}
if ($kind === 'network_change') {
CloudInput::only($body,

@ -6,7 +6,8 @@ use App\Models\CloudRescueTemplateDeletion;
/**
* Persists a host-local rescue-template delete before dispatch. Repeated
* browser requests may only inspect the same durable Agent operation.
* browser requests inspect the same durable Agent operation, except that an
* authenticated not_dispatched response may resend its unchanged operation ID.
*/
final class CloudRescueTemplateDeletionService
{
@ -19,27 +20,46 @@ final class CloudRescueTemplateDeletionService
return self::pollIfAllowed($record, $actor);
}
self::dispatch($record, $actor);
return self::dto(self::reload($record));
}
/** Claim and send only a durable pre-dispatch record. */
private static function dispatch(CloudRescueTemplateDeletion $record,
array $actor): void
{
$operationId = (string) $record->operation_id;
self::mark($record, 'sending', '');
if (!self::mark($record, 'sending', '')) {
return;
}
$record = self::reload($record);
$requestActor = $actor;
$requestActor['operation_id'] = $operationId;
try {
$operation = CloudAgentSettingsService::clientForHost($hostId)
->request('DELETE', '/v1/rescue-templates/'
. rawurlencode($templateId), $requestActor, [
$client = CloudAgentSettingsService::clientForHost(
(int) $record->host_id
);
$operation = $client->request('DELETE', '/v1/rescue-templates/'
. rawurlencode((string) $record->template_id),
$requestActor, [
'operation_id' => $operationId,
]);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
self::applyOperation($record, $operation);
} catch (CloudAgentError $error) {
if ($error->retryable && !$error->safePreDispatchFailure) {
self::mark($record, 'running', 'agent_unavailable');
} else {
if ($error->safePreDispatchFailure) {
// Both authenticated hops proved the Agent journal was never
// entered. Preserve the exact operation ID and return to the
// only state from which DELETE may be sent again.
self::mark($record, 'dispatching', $error->agentCode);
} elseif ($error->safeValidationFailure) {
self::mark($record, 'failed', $error->agentCode);
} else {
self::mark($record, 'running', $error->agentCode);
}
}
$record = self::reload($record);
return self::dto($record);
}
public static function job(int $hostId, string $operationId,
@ -89,22 +109,35 @@ final class CloudRescueTemplateDeletionService
array $actor): array
{
$state = (string) $record->state;
if (in_array($state, ['dispatching', 'sending'], true)) {
if ($state === 'dispatching') {
if ((int) $record->updated_at >= time() - 5) {
return self::dto($record);
}
self::dispatch($record, $actor);
return self::dto(self::reload($record));
}
if ($state === 'sending') {
if ((int) $record->updated_at >= time() - 90) {
return self::dto($record);
}
self::mark($record, 'uncertain', 'delete_dispatch_unconfirmed');
self::mark($record, 'running',
'delete_dispatch_unconfirmed');
$record = self::reload($record);
return self::dto($record);
$state = (string) $record->state;
}
if ($state !== 'running') {
return self::dto($record);
}
try {
$operation = CloudAgentSettingsService::clientForHost(
$client = CloudAgentSettingsService::clientForHost(
(int) $record->host_id
)->request('GET', '/v1/operations/'
. rawurlencode((string) $record->operation_id), $actor);
);
$operationId = (string) $record->operation_id;
$operation = $client->request('GET', '/v1/operations/'
. rawurlencode($operationId), $actor);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $actor, $operation
);
self::applyOperation($record, $operation);
} catch (CloudAgentError $error) {
if ($error->agentHttpStatus === 404) {
@ -163,17 +196,21 @@ final class CloudRescueTemplateDeletionService
}
private static function mark(CloudRescueTemplateDeletion $record,
string $state, string $errorCode): void
string $state, string $errorCode): bool
{
CloudRescueTemplateDeletion::query()
// A poll may complete out of order with another poll for the same
// durable operation. Never let a stale running/failed observation
// overwrite a terminal success (or any other newer state).
return CloudRescueTemplateDeletion::query()
->where('host_id', (int) $record->host_id)
->where('template_id', (string) $record->template_id)
->where('operation_id', (string) $record->operation_id)
->where('state', (string) $record->state)
->update([
'state' => $state,
'error_code' => substr($errorCode, 0, 64),
'updated_at' => time(),
]);
]) === 1;
}
/** Reload by the complete durable identity; this model has a composite key. */

@ -53,12 +53,16 @@ final class CloudRescueTemplateImportService
$operation = $client->request(
'POST', '/v1/rescue-templates', $requestActor, $body
);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
self::applyOperation($record, $operation);
} catch (CloudAgentError $error) {
self::mark(
$record,
$error->safePreDispatchFailure
? 'failed' : ($error->retryable ? 'running' : 'failed'),
($error->safeValidationFailure
|| $error->safePreDispatchFailure)
? 'failed' : 'running',
$error->agentCode
);
} catch (\Throwable $error) {
@ -105,6 +109,14 @@ final class CloudRescueTemplateImportService
if ((int) $record->updated_at >= time() - 90) {
return self::dto($record);
}
if ($state === 'sending') {
self::mark($record, 'running',
'import_dispatch_unconfirmed');
$record = self::reload($record);
$state = (string) $record->state;
}
}
if ($state === 'dispatching') {
self::mark($record, 'uncertain', 'import_dispatch_unconfirmed');
return self::dto(self::reload($record));
}
@ -113,10 +125,15 @@ final class CloudRescueTemplateImportService
}
try {
$operation = CloudAgentSettingsService::clientForHost(
$client = CloudAgentSettingsService::clientForHost(
(int) $record->host_id
)->request('GET', '/v1/operations/'
. rawurlencode((string) $record->operation_id), $actor);
);
$operationId = (string) $record->operation_id;
$operation = $client->request('GET', '/v1/operations/'
. rawurlencode($operationId), $actor);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $actor, $operation
);
self::applyOperation($record, $operation);
} catch (CloudAgentError $error) {
if ($error->agentHttpStatus === 404) {

@ -318,8 +318,9 @@ final class CloudRuntimeHeartbeat
usort($rows, static fn ($left, $right) => $right['last_seen'] <=> $left['last_seen']);
$latest = $rows[0] ?? null;
$active = array_values(array_filter($rows, static function ($row) use ($kind, $now): bool {
// HTTP work can last 900 seconds; policy calls have a 120s
// timeout. SMTP/lifecycle also need a generous observation window.
// The outer PHP HTTP deadline is 900 seconds (the Agent and
// Gateway finish earlier); policy calls have a 120s timeout.
// SMTP/lifecycle also need a generous observation window.
$grace = $row['state'] === 'busy' ? ($kind === 'policy' ? 180 : 1200) : 90;
return $row['mode'] === 'daemon' && $row['state'] !== 'stopped'
&& $now - $row['last_seen'] <= $grace;

@ -100,6 +100,7 @@ final class CloudTemplateCatalogService
$template = self::find($id);
if (in_array((string) $template->state,
['importing', 'error'], true)) {
self::recoverLegacyDispatchingReplica((string) $template->id);
if (CloudTemplateReplica::query()->where('template_id',
(string) $template->id)->where('state', 'pending')->exists()) {
foreach (CloudTemplateReplica::query()
@ -115,10 +116,15 @@ final class CloudTemplateCatalogService
continue;
}
try {
$operation = CloudAgentSettingsService::clientForHost(
$client = CloudAgentSettingsService::clientForHost(
(int) $replica->host_id
)->request('GET', '/v1/operations/'
. rawurlencode($operationId), $actor);
);
$operation = $client->request('GET',
'/v1/operations/' . rawurlencode($operationId),
$actor);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $actor, $operation
);
self::applyImportOperation($template,
(int) $replica->host_id, $operationId, $operation);
} catch (CloudAgentError $error) {
@ -162,18 +168,32 @@ final class CloudTemplateCatalogService
$requestActor = $actor;
$requestActor['operation_id'] = $operationId;
try {
$operation = CloudAgentSettingsService::clientForHost(
$hostId
)->request('PATCH', '/v1/templates/' . rawurlencode($id),
$client = CloudAgentSettingsService::clientForHost($hostId);
$operation = $client->request(
'PATCH', '/v1/templates/' . rawurlencode($id),
$requestActor, [
'operation_id' => $operationId,
'name' => $name,
'revision' => (int) $revision,
'generation_token' => $generation,
]);
self::successfulOperationResult($operation, '云镜像元数据同步');
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
self::successfulMetadataSync(
$operation,
$operationId,
$id,
$name,
(int) $revision,
$generation
);
CloudTemplateReplica::query()->where('host_id', $hostId)
->where('template_id', $id)->update([
->where('template_id', $id)
->where('generation_token', $generation)
// A slower response for revision N must never overwrite a
// concurrent revision N+1 response.
->where('revision', '<=', (int) $revision)->update([
'revision' => (int) $revision,
'generation_token' => $generation,
'state' => 'active',
@ -183,7 +203,11 @@ final class CloudTemplateCatalogService
]);
} catch (\Throwable $error) {
CloudTemplateReplica::query()->where('host_id', $hostId)
->where('template_id', $id)->update([
->where('template_id', $id)
->where('generation_token', $generation)
// Do not let a late failure regress a newer successful
// metadata synchronization.
->where('revision', '<=', (int) $revision)->update([
'state' => 'stale',
'operation_id' => $operationId,
'error_code' => 'agent_sync_failed',
@ -206,12 +230,14 @@ final class CloudTemplateCatalogService
$snapshot = self::beginDelete($id, $expectedRevision,
$generationToken);
if (($snapshot['dispatch'] ?? false) === true) {
self::dispatchDeleteReplicas((string) $snapshot['id'], $actor);
self::dispatchDeleteReplicas(
(string) $snapshot['id'], $actor, true
);
}
return self::deleteJob((string) $snapshot['id'], $actor);
}
/** Poll only the operation IDs reserved before the first DELETE dispatch. */
/** Poll reserved IDs; only authenticated not_dispatched rows may resend. */
public static function deleteJob(string $id, array $actor): array
{
$id = self::templateId($id);
@ -225,6 +251,12 @@ final class CloudTemplateCatalogService
if ((string) $template->state !== 'deleting') {
throw new CloudError('云镜像没有进行中的删除任务', 409);
}
// delete_dispatch is a durable pre-send state. A previous request may
// restore it only after an authenticated not_dispatched response, so
// retrying the same operation ID is safe. Fresh rows get a short
// backoff; ambiguous delete_sending/delete_running rows are never sent
// again and continue through GET/reconcile below.
self::dispatchDeleteReplicas($id, $actor, false);
self::pollDeleteReplicas($id, $actor);
return self::finalizeDelete($id);
}
@ -264,14 +296,24 @@ final class CloudTemplateCatalogService
}
private static function dispatchDeleteReplicas(string $id,
array $actor): void
array $actor, bool $includeFresh): void
{
$id = self::templateId($id);
foreach (CloudTemplateReplica::query()->where('template_id', $id)
$query = CloudTemplateReplica::query()->where('template_id', $id)
->where('state', 'delete_dispatch')
->orderBy('host_id')->get() as $replica) {
->orderBy('host_id');
if (!$includeFresh) {
$query->where('updated_at', '<=', time() - 5);
}
foreach ($query->get() as $replica) {
$hostId = (int) $replica->host_id;
$operationId = (string) $replica->operation_id;
if (preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $operationId) !== 1) {
self::markReplica($hostId, $id, $operationId,
['delete_dispatch'], 'delete_uncertain',
'operation_id_invalid');
continue;
}
$claimed = CloudTemplateReplica::query()
->where('host_id', $hostId)->where('template_id', $id)
->where('operation_id', $operationId)
@ -285,16 +327,21 @@ final class CloudTemplateCatalogService
$requestActor = $actor;
$requestActor['operation_id'] = $operationId;
try {
$operation = CloudAgentSettingsService::clientForHost(
$hostId
)->request('DELETE', '/v1/templates/' . rawurlencode($id),
$requestActor, ['operation_id' => $operationId]);
$client = CloudAgentSettingsService::clientForHost($hostId);
$operation = $client->request('DELETE',
'/v1/templates/' . rawurlencode($id), $requestActor,
['operation_id' => $operationId]);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
self::applyDeleteOperation($replica, $operation);
} catch (CloudAgentError $error) {
self::markReplica($hostId, $id, $operationId,
['delete_sending'],
$error->retryable && !$error->safePreDispatchFailure
? 'delete_running' : 'delete_failed',
$error->safePreDispatchFailure
? 'delete_dispatch'
: ($error->safeValidationFailure
? 'delete_failed' : 'delete_running'),
$error->agentCode);
}
}
@ -304,9 +351,9 @@ final class CloudTemplateCatalogService
array $actor): void
{
CloudTemplateReplica::query()->where('template_id', $id)
->whereIn('state', ['delete_dispatch', 'delete_sending'])
->where('state', 'delete_sending')
->where('updated_at', '<', time() - 90)->update([
'state' => 'delete_uncertain',
'state' => 'delete_running',
'error_code' => 'delete_dispatch_unconfirmed',
'updated_at' => time(),
]);
@ -321,10 +368,14 @@ final class CloudTemplateCatalogService
continue;
}
try {
$operation = CloudAgentSettingsService::clientForHost(
$client = CloudAgentSettingsService::clientForHost(
(int) $replica->host_id
)->request('GET', '/v1/operations/'
);
$operation = $client->request('GET', '/v1/operations/'
. rawurlencode($operationId), $actor);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $actor, $operation
);
self::applyDeleteOperation($replica, $operation);
} catch (CloudAgentError $error) {
self::markReplica((int) $replica->host_id, $id, $operationId,
@ -843,14 +894,22 @@ final class CloudTemplateCatalogService
&& $sourceSnapshot['source_token'] !== '') {
$body['source_token'] = $sourceSnapshot['source_token'];
}
$operation = CloudAgentSettingsService::clientForHost(
$hostId
)->request('POST', '/v1/templates', $requestActor, $body);
$client = CloudAgentSettingsService::clientForHost($hostId);
$operation = $client->request(
'POST', '/v1/templates', $requestActor, $body
);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
} catch (CloudAgentError $error) {
// Imports are deliberately one-shot even when the authenticated
// response proves not_dispatched: upload/source capabilities
// may expire, so an operator must create a fresh import.
self::markReplica($hostId, (string) $template->id,
$operationId, ['pending'],
$error->retryable && !$error->safePreDispatchFailure
? 'pending' : 'failed',
($error->safeValidationFailure
|| $error->safePreDispatchFailure)
? 'failed' : 'pending',
$error->agentCode);
continue;
} catch (\Throwable $error) {
@ -893,14 +952,17 @@ final class CloudTemplateCatalogService
self::operationErrorCode($operation, 'agent_import_failed'));
return;
}
if (in_array($status, ['uncertain', 'dispatching'], true)) {
if ($status === 'uncertain') {
$errorCode = self::operationErrorCode($operation,
'agent_operation_uncertain');
self::markReplica($hostId, (string) $template->id, $operationId,
['pending'], 'uncertain',
self::operationErrorCode($operation,
'agent_import_uncertain'));
$errorCode === 'agent_import_uncertain'
? 'agent_operation_uncertain' : $errorCode);
return;
}
if (in_array($status, ['reserved', 'pending', 'running'], true)) {
if (in_array($status,
['reserved', 'pending', 'running', 'dispatching'], true)) {
self::markReplica($hostId, (string) $template->id, $operationId,
['pending'], 'pending', '');
return;
@ -1064,6 +1126,23 @@ final class CloudTemplateCatalogService
]) === 1;
}
/**
* Repair only rows produced by the former dispatching-status bug. The
* operation ID is deliberately left untouched and is polled below; no
* import request is replayed.
*/
private static function recoverLegacyDispatchingReplica(
string $templateId): void
{
CloudTemplateReplica::query()->where('template_id', $templateId)
->where('state', 'uncertain')
->where('error_code', 'agent_import_uncertain')->update([
'state' => 'pending',
'error_code' => '',
'updated_at' => time(),
]);
}
private static function operationErrorCode(array $operation,
string $fallback): string
{
@ -1086,6 +1165,33 @@ final class CloudTemplateCatalogService
return $operation['result'];
}
/** Bind metadata acknowledgement to the exact request and snapshot. */
private static function successfulMetadataSync(
array $operation,
string $operationId,
string $templateId,
string $name,
int $revision,
string $generation
): void {
if (($operation['operation_id'] ?? null) !== $operationId) {
throw new CloudError(
'云镜像元数据同步操作标识不匹配,必须人工核查', 503
);
}
$result = self::successfulOperationResult(
$operation, '云镜像元数据同步'
);
if (($result['id'] ?? null) !== $templateId
|| ($result['name'] ?? null) !== $name
|| ($result['revision'] ?? null) !== $revision
|| ($result['generation_token'] ?? null) !== $generation) {
throw new CloudError(
'云镜像元数据同步结果与当前版本不一致,必须人工核查', 503
);
}
}
private static function remoteUrl($value, string $extension): string
{
if (!is_string($value) || strlen($value) > 2048

@ -99,9 +99,10 @@ final class CloudTrafficService
continue;
}
$previous = $totals->get($item['uuid']);
if ($previous !== null
&& (int) ($previous->last_observed_at ?? 0)
> $now - self::SAMPLE_MINIMUM_SECONDS) {
$lastObservedAt = $previous === null ? 0
: (int) ($previous->last_observed_at ?? 0);
if ($lastObservedAt <= $now
&& $lastObservedAt > $now - self::SAMPLE_MINIMUM_SECONDS) {
$result['skipped']++;
continue;
}
@ -233,7 +234,9 @@ final class CloudTrafficService
$collectedAt = self::metricTimestamp($metrics['collected_at'] ?? null);
$current = [
'cpu_time_ns' => self::counter($metrics, 'cpu_time_ns'),
'memory_used_kib' => self::counter($metrics, 'memory_used_kib'),
'memory_used_kib' => self::nullableCounter(
$metrics, 'memory_used_kib'
),
'disk_read_bytes' => self::counter($metrics, 'disk_read_bytes'),
'disk_write_bytes' => self::counter($metrics, 'disk_write_bytes'),
'rx_bytes' => self::counter($metrics, 'rx_bytes'),
@ -254,9 +257,6 @@ final class CloudTrafficService
!== (string) (int) $instance->host_id)) {
throw new CloudError('性能采样归属与实例不一致', 409);
}
if ($collectedAt <= (int) ($previous->last_observed_at ?? 0)) {
return;
}
}
$baseline = $previous === null ? [] : json_decode(
@ -264,8 +264,15 @@ final class CloudTrafficService
);
$baseline = is_array($baseline) && !array_is_list($baseline)
? $baseline : [];
$elapsed = $previous === null ? 0
: $collectedAt - (int) ($previous->last_observed_at ?? 0);
$previousObservedAt = $previous === null ? 0
: (int) ($previous->last_observed_at ?? 0);
$orderedSample = $previous === null
|| $collectedAt > $previousObservedAt;
// The Agent's RX/TX counters are durable cumulative totals. A host
// clock correction must not freeze quota accounting, but its old
// timestamp is not suitable for chart ordering or rate math.
$elapsed = $orderedSample && $previous !== null
? $collectedAt - $previousObservedAt : 0;
$spec = json_decode((string) $instance->spec_json, true);
$spec = is_array($spec) && !array_is_list($spec) ? $spec : [];
$vcpu = filter_var($spec['vcpu'] ?? ($spec['cpu_cores'] ?? null),
@ -333,7 +340,8 @@ final class CloudTrafficService
'user_id' => (int) $instance->user_id,
'sampled_at' => $collectedAt,
'cpu_percent' => $cpu,
'memory_used_mib' => $current['memory_used_kib'] / 1024,
'memory_used_mib' => $current['memory_used_kib'] === null
? null : $current['memory_used_kib'] / 1024,
'memory_total_mib' => $memoryTotal === false
? null : (float) $memoryTotal,
'disk_read_bps' => $delta('disk_read_bytes'),
@ -347,17 +355,19 @@ final class CloudTrafficService
'network_rx_bytes' => $networkRx,
'network_tx_bytes' => $networkTx,
];
$log->table('cloud_vm_metric_samples')->insertOrIgnore($sample);
$log->table('cloud_vm_traffic_checkpoints')->insertOrIgnore([
'host_scope' => $scope,
'vm_uuid' => $uuid,
'checkpoint_hour' => intdiv($collectedAt, 3600) * 3600,
'host_id' => (string) (int) $instance->host_id,
'user_id' => (int) $instance->user_id,
'first_observed_at' => $collectedAt,
'download_rx_bytes' => $panelRx,
'upload_tx_bytes' => $panelTx,
]);
if ($orderedSample) {
$log->table('cloud_vm_metric_samples')->insertOrIgnore($sample);
$log->table('cloud_vm_traffic_checkpoints')->insertOrIgnore([
'host_scope' => $scope,
'vm_uuid' => $uuid,
'checkpoint_hour' => intdiv($collectedAt, 3600) * 3600,
'host_id' => (string) (int) $instance->host_id,
'user_id' => (int) $instance->user_id,
'first_observed_at' => $collectedAt,
'download_rx_bytes' => $panelRx,
'upload_tx_bytes' => $panelTx,
]);
}
$encoded = json_encode([
'version' => 1,
'cpu_time_ns' => $current['cpu_time_ns'],
@ -371,7 +381,7 @@ final class CloudTrafficService
$values = [
'host_id' => (string) (int) $instance->host_id,
'user_id' => (int) $instance->user_id,
'last_observed_at' => $collectedAt,
'last_observed_at' => max($previousObservedAt, $collectedAt),
'network_signature' => hash('sha256',
'virt-agent-durable-traffic/v1'),
'network_baseline_json' => $encoded,
@ -400,6 +410,22 @@ final class CloudTrafficService
return $value;
}
private static function nullableCounter(array $metrics,
string $field): ?int
{
if (!array_key_exists($field, $metrics)) {
throw new CloudError('Agent 指标计数器格式无效', 502);
}
$value = $metrics[$field];
if ($value === null) {
return null;
}
if (!is_int($value) || $value < 0) {
throw new CloudError('Agent 指标计数器格式无效', 502);
}
return $value;
}
private static function metricTimestamp($value): int
{
if (!is_string($value) || strlen($value) < 20 || strlen($value) > 40

@ -42,6 +42,7 @@ final class CloudUserIsoService
$userId, $name, $url
): CloudUserIso {
$rows = CloudUserIso::query()->where('user_id', $userId)
->where('state', '<>', 'retired')
->lockForUpdate()->get();
if ($rows->count() >= self::MAX_ISOS) {
throw new CloudError('每个用户最多保存 5 个 ISO', 409);
@ -74,20 +75,27 @@ final class CloudUserIsoService
$requestActor = $actor;
$requestActor['can_manage'] = true;
$requestActor['operation_id'] = $operationId;
$operation = CloudAgentSettingsService::clientForHost(
$hostId
)->request('POST', '/v1/user-isos', $requestActor, [
$client = CloudAgentSettingsService::clientForHost($hostId);
$operation = $client->request('POST', '/v1/user-isos',
$requestActor, [
'operation_id' => $operationId,
'id' => (string) $iso->id,
'owner_id' => $userId,
'name' => $name,
'source_url' => $url,
]);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
} catch (CloudAgentError $error) {
// Imports are deliberately one-shot even when the authenticated
// response proves not_dispatched. A new import receives a new
// operation and a fresh source capability.
self::markReplica($hostId, (string) $iso->id,
$operationId, ['pending'],
$error->retryable && !$error->safePreDispatchFailure
? 'pending' : 'failed',
($error->safeValidationFailure
|| $error->safePreDispatchFailure)
? 'failed' : 'pending',
$error->agentCode);
continue;
} catch (\Throwable $error) {
@ -120,7 +128,17 @@ final class CloudUserIsoService
if ($iso === null) {
throw new CloudError('ISO 下载任务不存在', 404);
}
if ((string) $iso->state === 'retired') {
return [
'job_id' => (string) $iso->import_operation_id,
'status' => 'succeeded',
'phase' => 'ISO 导入曾完成,镜像现已删除',
'finished_at' => (int) $iso->updated_at,
'deleted' => true,
];
}
if (in_array((string) $iso->state, ['importing', 'failed'], true)) {
self::recoverLegacyDispatchingReplica((string) $iso->id);
if (CloudUserIsoReplica::query()->where('user_iso_id',
(string) $iso->id)->where('state', 'pending')->exists()) {
foreach (CloudUserIsoReplica::query()
@ -138,10 +156,17 @@ final class CloudUserIsoService
$requestActor = $actor;
$requestActor['can_manage'] = true;
try {
$operation = CloudAgentSettingsService::clientForHost(
$client = CloudAgentSettingsService::clientForHost(
(int) $replica->host_id
)->request('GET', '/v1/operations/'
. rawurlencode($replicaOperationId), $requestActor);
);
$operation = $client->request('GET',
'/v1/operations/'
. rawurlencode($replicaOperationId),
$requestActor);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $replicaOperationId, $requestActor,
$operation
);
self::applyImportOperation($iso,
(int) $replica->host_id, $replicaOperationId,
$operation);
@ -178,6 +203,9 @@ final class CloudUserIsoService
if ($iso === null) {
throw new CloudError('ISO 不存在或不属于当前用户', 404);
}
if ((string) $iso->state === 'retired') {
return [$iso, false];
}
if ((string) $iso->state === 'deleting') {
return [$iso, false];
}
@ -218,7 +246,7 @@ final class CloudUserIsoService
return self::deleteJob($id, $actor);
}
/** Poll only previously persisted Agent operations; never replay DELETE. */
/** Poll persisted IDs; only authenticated not_dispatched rows may resend. */
public static function deleteJob(string $id, array $actor): array
{
if (preg_match('/^[a-f0-9]{32}$/D', $id) !== 1) {
@ -229,21 +257,38 @@ final class CloudUserIsoService
if ($iso === null) {
throw new CloudError('ISO 删除任务不存在', 404);
}
if ((string) $iso->state === 'retired') {
return self::deleteSucceededDto($iso);
}
if ((string) $iso->state !== 'deleting') {
throw new CloudError('ISO 没有进行中的删除任务', 409);
}
// Only delete_dispatch is safe to send again: it either has never been
// claimed or was restored by an exact authenticated not_dispatched
// response. Ambiguous sending/running states stay lookup-only.
self::dispatchDeleteReplicas($iso, $actor, false);
self::pollDeleteReplicas($iso, $actor);
return self::finalizeDelete($iso, $actor);
}
private static function dispatchDeleteReplicas(CloudUserIso $iso,
array $actor): void
array $actor, bool $includeFresh = true): void
{
$id = (string) $iso->id;
foreach (CloudUserIsoReplica::query()->where('user_iso_id', $id)
$query = CloudUserIsoReplica::query()->where('user_iso_id', $id)
->where('state', 'delete_dispatch')
->orderBy('host_id')->get() as $replica) {
->orderBy('host_id');
if (!$includeFresh) {
$query->where('updated_at', '<=', time() - 5);
}
foreach ($query->get() as $replica) {
$operationId = (string) $replica->operation_id;
if (preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $operationId) !== 1) {
self::markReplica((int) $replica->host_id, $id,
$operationId, ['delete_dispatch'], 'delete_uncertain',
'operation_id_invalid');
continue;
}
$claimed = CloudUserIsoReplica::query()
->where('host_id', (int) $replica->host_id)
->where('user_iso_id', $id)
@ -259,17 +304,24 @@ final class CloudUserIsoService
$requestActor['can_manage'] = true;
$requestActor['operation_id'] = $operationId;
try {
$operation = CloudAgentSettingsService::clientForHost(
$client = CloudAgentSettingsService::clientForHost(
(int) $replica->host_id
)->request('DELETE', '/v1/user-isos/' . rawurlencode($id)
);
$operation = $client->request(
'DELETE', '/v1/user-isos/' . rawurlencode($id)
. '?owner_id=' . (int) $iso->user_id, $requestActor,
['operation_id' => $operationId]);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
self::applyDeleteOperation($iso, $replica, $operation);
} catch (CloudAgentError $error) {
self::markReplica((int) $replica->host_id, $id,
$operationId, ['delete_sending'],
$error->retryable && !$error->safePreDispatchFailure
? 'delete_running' : 'delete_failed',
$error->safePreDispatchFailure
? 'delete_dispatch'
: ($error->safeValidationFailure
? 'delete_failed' : 'delete_running'),
$error->agentCode);
}
}
@ -280,9 +332,9 @@ final class CloudUserIsoService
{
$id = (string) $iso->id;
CloudUserIsoReplica::query()->where('user_iso_id', $id)
->whereIn('state', ['delete_dispatch', 'delete_sending'])
->where('state', 'delete_sending')
->where('updated_at', '<', time() - 90)->update([
'state' => 'delete_uncertain',
'state' => 'delete_running',
'error_code' => 'delete_dispatch_unconfirmed',
'updated_at' => time(),
]);
@ -299,10 +351,14 @@ final class CloudUserIsoService
$requestActor = $actor;
$requestActor['can_manage'] = true;
try {
$operation = CloudAgentSettingsService::clientForHost(
$client = CloudAgentSettingsService::clientForHost(
(int) $replica->host_id
)->request('GET', '/v1/operations/'
);
$operation = $client->request('GET', '/v1/operations/'
. rawurlencode($operationId), $requestActor);
$operation = CloudAgentOperationReconciler::ifUncertain(
$client, $operationId, $requestActor, $operation
);
self::applyDeleteOperation($iso, $replica, $operation);
} catch (CloudAgentError $error) {
self::markReplica((int) $replica->host_id, $id,
@ -376,8 +432,13 @@ final class CloudUserIsoService
$locked = CloudUserIso::query()->where('id', $id)
->where('user_id', (int) ($actor['user_id'] ?? 0))
->lockForUpdate()->first();
if ($locked === null
|| (string) $locked->state !== 'deleting') {
if ($locked === null) {
throw new CloudError('ISO 删除状态无法确认', 503);
}
if ((string) $locked->state === 'retired') {
return self::deleteSucceededDto($locked);
}
if ((string) $locked->state !== 'deleting') {
throw new CloudError('ISO 删除状态无法确认', 503);
}
$replicas = CloudUserIsoReplica::query()
@ -389,21 +450,34 @@ final class CloudUserIsoService
}
CloudUserIsoReplica::query()->where('user_iso_id', $id)
->delete();
CloudUserIso::query()->where('id', $id)
->where('user_id', (int) $locked->user_id)->delete();
return [
'deleted' => true,
'id' => $id,
'job_id' => $id,
'status' => 'succeeded',
'phase' => '所有宿主机 ISO 副本及受管文件均已确认删除',
'status_url' => '/api/v1/user-isos/delete-jobs/'
. rawurlencode($id),
];
// Retain only a host-independent, owner-scoped tombstone so a
// lost HTTP response can still be polled safely. All source and
// catalog metadata is removed from the retired authority row.
$locked->name = '';
$locked->sealed_source_url = '';
$locked->size_bytes = 0;
$locked->sha256 = '';
$locked->state = 'retired';
$locked->updated_at = time();
$locked->save();
return self::deleteSucceededDto($locked);
}, 3
);
}
private static function deleteSucceededDto(CloudUserIso $iso): array
{
return [
'deleted' => true,
'id' => (string) $iso->id,
'job_id' => (string) $iso->id,
'status' => 'succeeded',
'phase' => '所有宿主机 ISO 副本及受管文件均已确认删除',
'status_url' => '/api/v1/user-isos/delete-jobs/'
. rawurlencode((string) $iso->id),
];
}
private static function deleteJobDto(CloudUserIso $iso,
$replicas): array
{
@ -453,14 +527,17 @@ final class CloudUserIsoService
self::operationErrorCode($operation, 'agent_import_failed'));
return;
}
if (in_array($status, ['uncertain', 'dispatching'], true)) {
if ($status === 'uncertain') {
$errorCode = self::operationErrorCode($operation,
'agent_operation_uncertain');
self::markReplica($hostId, (string) $iso->id, $operationId,
['pending'], 'uncertain',
self::operationErrorCode($operation,
'agent_import_uncertain'));
$errorCode === 'agent_import_uncertain'
? 'agent_operation_uncertain' : $errorCode);
return;
}
if (in_array($status, ['reserved', 'pending', 'running'], true)) {
if (in_array($status,
['reserved', 'pending', 'running', 'dispatching'], true)) {
self::markReplica($hostId, (string) $iso->id, $operationId,
['pending'], 'pending', '');
return;
@ -626,6 +703,23 @@ final class CloudUserIsoService
]) === 1;
}
/**
* Repair only rows produced by the former dispatching-status bug. The
* operation ID is deliberately left untouched and is polled below; no
* import request is replayed.
*/
private static function recoverLegacyDispatchingReplica(
string $isoId): void
{
CloudUserIsoReplica::query()->where('user_iso_id', $isoId)
->where('state', 'uncertain')
->where('error_code', 'agent_import_uncertain')->update([
'state' => 'pending',
'error_code' => '',
'updated_at' => time(),
]);
}
private static function dto(CloudUserIso $iso): array
{
return [

@ -16,7 +16,7 @@ final class CloudWorkerService
private const POLICY_KINDS = ['service_suspend',
'network_suspend', 'network_resume'];
private const REINSTALL_REVIEW_CODES = [
'reinstall_cleanup_pending', 'reinstall_result_uncertain',
'reinstall_cleanup_pending',
];
private bool $policyOnly;
@ -32,8 +32,9 @@ final class CloudWorkerService
{
$this->policyOnly = $policyOnly;
// A cloud-image clone can legitimately take minutes on remote storage.
// Keep the worker lease longer than the HTTP timeout so another worker
// cannot claim the same job while the first request is still active.
// The layered deadlines are Agent API 840s, Agent WSS control 855s,
// Gateway 870s, PHP 900s and worker lease 930s. Each outer layer has
// time to persist the inner layer's structured result before expiry.
}
private function agentForHost(int $hostId): CloudAgentClient
@ -60,8 +61,7 @@ final class CloudWorkerService
return 'succeeded';
}
if ($status === 'failed') {
if (!$creating || ($operation['safe_to_refund'] ?? false) === true
|| ($operation['result']['creation_absent'] ?? false) === true) {
if (!$creating || self::createFailureConfirmedAbsent($operation)) {
return 'failed';
}
return 'uncertain';
@ -70,6 +70,27 @@ final class CloudWorkerService
? 'running' : 'uncertain';
}
/** A create may refund only after both the VM and all managed artifacts are absent. */
private static function createFailureConfirmedAbsent(array $operation): bool
{
$result = $operation['result'] ?? null;
return is_array($result)
&& ($result['creation_absent'] ?? false) === true
&& ($result['managed_artifacts_absent'] ?? false) === true;
}
/** Exact evidence for a create request proven not to have crossed dispatch. */
private static function createNotDispatchedFailure(): array
{
return [
'status' => 'failed',
'result' => [
'creation_absent' => true,
'managed_artifacts_absent' => true,
],
];
}
/** A committed reinstall with unconfirmed cleanup is never terminal. */
private static function reinstallNeedsReview(array $operation): bool
{
@ -84,8 +105,7 @@ final class CloudWorkerService
}
$result = $operation['result'] ?? null;
return is_array($result)
&& (($result['reinstall_committed'] ?? false) === true
|| ($result['cleanup_pending'] ?? false) === true);
&& ($result['cleanup_pending'] ?? false) === true;
}
/** The replacement guest is authoritative even while old-disk cleanup waits. */
@ -167,7 +187,10 @@ final class CloudWorkerService
if (!$systemPolicy && !$systemCleanup
&& ($user === null || (int) $user->enable !== 1)) {
if ($job->dispatched_at === null) {
$this->finish($job, ['status' => 'failed', 'safe_to_refund' => true], $payload);
$operation = $job->kind === 'create'
? self::createNotDispatchedFailure()
: ['status' => 'failed'];
$this->finish($job, $operation, $payload);
return true;
}
}
@ -266,11 +289,20 @@ final class CloudWorkerService
['succeeded', 'failed'],
true
);
$failedCreateNeedsEvidence = $job->kind === 'create'
&& strtolower((string) ($operation['status'] ?? '')) === 'failed'
&& !self::createFailureConfirmedAbsent($operation);
$reinstallNeedsCleanup = $job->kind === 'reinstall'
&& self::reinstallNeedsReview($operation);
$current = $job->instance_id === null ? null
: CloudInstance::find($job->instance_id);
$desiredPolicy = !$systemPolicy
|| self::policyDesired($current, (string) $job->kind);
if (!$terminal && $desiredPolicy) {
// A terminal Agent failure without absence evidence is not a safe
// provisioning failure. Ask the same operation record for read-only
// reconciliation; never submit POST /v1/vms again.
if ((!$terminal || $failedCreateNeedsEvidence
|| $reinstallNeedsCleanup) && $desiredPolicy) {
$operation = self::operationForJob(
$job,
$client->request(
@ -298,7 +330,8 @@ final class CloudWorkerService
$payload['method'],
$payload['request_target'],
$actor,
$payload['body']
self::agentRequestBody((string) $job->kind,
$payload['body'])
)
);
}
@ -314,18 +347,25 @@ final class CloudWorkerService
$log .= ' status=' . $error->httpStatus . ' message=' . $diagnostic;
}
error_log($log);
if ($initialDispatch && $job->kind === 'create'
&& $error instanceof CloudAgentError
&& $error->safeCreateFailure) {
// The exact Agent wire shape proves validation failed before
// the durable journal and before libvirt was entered. This is
// the only post-send exception path where a refund is safe.
if ($initialDispatch && $error instanceof CloudAgentError
&& $error->safeValidationFailure) {
// The exact Agent/Gateway wire shape proves a terminal auth,
// route or validation failure happened before the durable
// journal and before libvirt was entered. A create may therefore
// refund with exact absence evidence; other kinds fail normally.
try {
$this->finish($job, [
'status' => 'failed',
'safe_to_refund' => true,
'error_code' => $error->agentCode,
], $payload);
$operation = $job->kind === 'create'
? self::createNotDispatchedFailure()
: ['status' => 'failed'];
// This is panel-generated evidence for the already
// persisted job, not an unbound Agent response. Preserve
// the durable identity so kind-specific finish handlers
// (notably firewall_apply) can enforce their operation-ID
// invariant without turning a proven pre-dispatch failure
// into uncertainty.
$operation['operation_id'] = (string) $job->operation_id;
$operation['error_code'] = $error->agentCode;
$this->finish($job, $operation, $payload);
return true;
} catch (\Throwable $finishError) {
error_log('cloud worker job ' . $job->id
@ -336,9 +376,9 @@ final class CloudWorkerService
if ($initialDispatch && $error instanceof CloudAgentError
&& $error->safePreDispatchFailure) {
// Both authenticated hops proved that the request never
// reached the Agent API handler or operation journal. Restore
// only this leased row to the persistent queue. Timeouts and
// unmarked disconnects remain uncertain and are never replayed.
// reached the durable Agent operation journal. Restore only
// this leased row to the persistent queue. Timeouts, replay
// rejections and unmarked disconnects remain uncertain.
$requeued = CloudJob::where('id', $job->id)
->where('lease_token', $job->lease_token)
->whereNotNull('dispatched_at')->update([
@ -359,8 +399,11 @@ final class CloudWorkerService
// Agent request was sent, so create did not happen and an
// order refund is safe.
try {
$this->finish($job, ['status' => 'failed', 'safe_to_refund' => true,
'error' => $diagnostic], $payload);
$operation = $job->kind === 'create'
? self::createNotDispatchedFailure()
: ['status' => 'failed'];
$operation['error'] = $diagnostic;
$this->finish($job, $operation, $payload);
return true;
} catch (\Throwable $finishError) {
error_log('cloud worker job ' . $job->id
@ -983,6 +1026,19 @@ final class CloudWorkerService
return CloudOperationCatalog::isPowerAction($action ?? '') ? $action : null;
}
/**
* Translate panel vocabulary only at the Agent wire boundary. The PHP job
* keeps "poweroff" so its audit label and user-facing history remain
* stable, while the Go protocol uses libvirt's explicit "destroy" action.
*/
private static function agentRequestBody(string $kind, array $body): array
{
if ($kind === 'action' && ($body['action'] ?? null) === 'poweroff') {
$body['action'] = 'destroy';
}
return $body;
}
/**
* Bind every journal-backed Agent response to the claimed PHP job before
* its status or result can influence durable panel state. Missing IDs and

@ -74,7 +74,7 @@ async function saveUserIsoSettings(event) {
}
function fillHost(host) {
byId('host-form').reset(); const h = host || {}; byId('host-id').value = h.id || ''; byId('host-form-title').textContent = host ? `编辑宿主机 · ${h.name}` : '添加宿主机';
const fields = { 'host-name': h.name || '', 'host-country-code': h.country_code || '', 'host-region': h.region || '', 'host-network': h.default_network || 'bridge:br0' };
const fields = { 'host-name': h.name || '', 'host-country-code': h.country_code || '', 'host-region': h.region || '', 'host-network': h.default_network || 'public' };
for (const [id, value] of Object.entries(fields)) byId(id).value = value;
byId('host-enabled').checked = h.enabled !== false; byId('host-form-error').textContent = '';
}
@ -249,7 +249,7 @@ function renderHostNetworkPools(payload, hostId, epoch) {
const host = payload?.host || {}; const line = payload?.line || null; const items = Array.isArray(payload?.items) ? payload.items : [];
byId('host-network-pools-title').textContent = `${host.name || `宿主机 #${host.id}`} · 公网地址池`;
const summary = byId('host-network-pools-summary'); summary.replaceChildren();
for (const [label, value] of [['默认网络', host.default_network || '未配置'], ['所属线路', line ? `${line.name}(${line.status})` : '尚未加入资源池'], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label === '默认网络' ? 'admin-mono' : '', value));
for (const [label, value] of [['网络选择器', host.default_network || '未配置'], ['所属线路', line ? `${line.name}(${line.status})` : '尚未加入资源池'], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label === '网络选择器' ? 'admin-mono' : '', value));
const list = byId('host-network-pools-list'); list.replaceChildren();
if (!items.length) list.append(element('p', 'text-muted py-3', '暂无公网地址池。添加后面板会生成并维护可用 IP 账本。'));
for (const pool of items) list.append(renderNetworkPoolForm(pool));

@ -1021,7 +1021,7 @@ async function rescueAction(action) {
if (action === 'load' && !byId('rescue-template-id').value) return showError('rescue-error', '请选择救援模板。');
if (action === 'force-start' && !confirm('正常关机未成功。强制断电并冷启动进入已挂载的救援环境可能丢失数据,确认继续?')) return;
state.mutationBusy = true; showError('rescue-error', '');
try { const body = { confirmation_name: vm.name }; if (action === 'load') body.template_id = byId('rescue-template-id').value; if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body }); const rescueLabels = { load: '救援', 'force-start': '强制进入救援', exit: '退出救援' }; toast(`${rescueLabels[action] || '救援'}命令发送成功`); if (result.job_id) await pollJob('rescue', result.job_id, 'rescue-status', 'rescue-error'); }
try { const body = { confirmation_name: vm.name }; if (action === 'load') { body.template_id = byId('rescue-template-id').value; body.ack_data_loss = true; } if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body }); const rescueLabels = { load: '救援', 'force-start': '强制进入救援', exit: '退出救援' }; toast(`${rescueLabels[action] || '救援'}命令发送成功`); if (result.job_id) await pollJob('rescue', result.job_id, 'rescue-status', 'rescue-error'); }
catch (error) { showError('rescue-error', error.message); }
finally { state.mutationBusy = false; try { renderRescueStatus(await api(`${vmPath(vm)}/rescue`)); } catch (error) { showError('rescue-error', error.message); } }
}

@ -92,10 +92,10 @@
<section class="cloud-admin-form-section" aria-labelledby="host-network-title">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-access-point-network"></i></span>
<div><h6 id="host-network-title">默认网络</h6><p>这里只配置宿主机默认网桥;公网 CIDR 在左侧宿主机的“公网地址池”抽屉中独立管理。</p></div>
<div><h6 id="host-network-title">默认网络选择器</h6><p>填写宿主机 Agent <code>network_selectors</code> 中预先配置的稳定 key;公网 CIDR 在“公网地址池”抽屉中管理。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div class="cloud-admin-full"><label for="host-network" class="form-label">默认网桥 / 网络</label><input id="host-network" class="form-control admin-mono" value="bridge:br0" required><div class="form-text">当前阶段所有公网地址池共用此实际网络接入;存在地址池时不能直接切换默认网络。</div></div>
<div class="cloud-admin-full"><label for="host-network" class="form-label">Agent 网络选择器 key</label><input id="host-network" class="form-control admin-mono" value="public" required maxlength="64" pattern="[A-Za-z0-9][A-Za-z0-9_.-]{ldelim}0,63{rdelim}" autocomplete="off" spellcheck="false"><div class="form-text">默认填写 <code>public</code>。实际 <code>br0</code> 或 libvirt network 只在 Agent 配置中映射;这里不能填写 <code>bridge:br0</code>。</div></div>
</div>
</section>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026100701' scope='global'}
{assign var=venix_asset_version value='2026101601' scope='global'}

@ -55,7 +55,7 @@ CREATE TABLE IF NOT EXISTS cloud_hosts (
region VARCHAR(64) NOT NULL DEFAULT '',
country_code CHAR(2) NOT NULL DEFAULT '',
enabled TINYINT(1) NOT NULL DEFAULT 0,
default_network VARCHAR(128) NOT NULL DEFAULT 'default',
default_network VARCHAR(128) NOT NULL DEFAULT 'public',
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
KEY cloud_host_name (name)
@ -99,17 +99,17 @@ CREATE TABLE IF NOT EXISTS cloud_host_resource_pool_memberships (
KEY cloud_host_membership_scheduler (host_id, scheduler_state, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- One attachment is one real host egress such as bridge:br0. Several CIDR
-- blocks may share the same attachment. Binding the attachment to a network
-- line keeps physical egress separate from compute capacity and lets a future
-- premium line use another bridge/VLAN without duplicating the host record.
-- One attachment is one stable Agent network_selectors key such as public.
-- The host-local bridge or libvirt network remains private to Agent config.
-- Several CIDR blocks may share the same attachment. Binding the attachment
-- to a network line keeps physical egress separate from compute capacity.
CREATE TABLE IF NOT EXISTS cloud_host_network_attachments (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
attachment_key CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
host_id BIGINT UNSIGNED NOT NULL,
line_id BIGINT UNSIGNED NOT NULL,
name VARCHAR(80) NOT NULL,
network_mode VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'bridge',
network_mode VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'selector',
network_selector VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
vlan_id SMALLINT UNSIGNED DEFAULT NULL,
routing_table INT UNSIGNED DEFAULT NULL,

@ -61,6 +61,9 @@ $assert(str_contains($service, 'private const MAX_POOLS = 32;')
&& str_contains($service, 'CloudHostPoolMembershipService::lockedRows')
&& str_contains($service, 'CloudHostPoolMembershipService::selected')
&& str_contains($service, "\$lockedHost->default_network")
&& str_contains($service,
"'/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D'")
&& str_contains($service, "\$attachment->network_mode = 'selector';")
&& str_contains($service, 'CloudHostNetworkAttachment')
&& str_contains($service, 'CloudPublicIpPool')
&& str_contains($service, 'desired_revision')

@ -302,6 +302,15 @@ namespace {
$assert(Operations::detail($readonlyAdmin, '211')['job']['can_cancel'] === false,
'Read-only administrators received the task cancellation control.');
$reject(static fn () => Operations::cancel($readonlyAdmin, '211'), 403);
// A reboot/reset response can be lost without any durable state that
// proves whether the pulse occurred. Administrators must be able to stop
// local polling without replaying that power action or mutating the VM.
$insertJob(223, ['status' => 'uncertain', 'kind' => 'action',
'dispatched_at' => $now - 20]);
$cancelledAction = Operations::cancel($admin, '223');
$assert(($cancelledAction['job']['status'] ?? null) === 'cancelled'
&& Capsule::table('cloud_instances')->where('id', 10)->value('status') === 'active',
'Administrator could not stop an irreducible uncertain power action safely.');
$cancelled = Operations::cancel($admin, '211');
$cancelledRow = Capsule::table('cloud_jobs')->where('id', 211)->first();
$assert(($cancelled['job']['status'] ?? null) === 'cancelled'
@ -315,7 +324,7 @@ namespace {
$cancelledAgain = Operations::cancel($admin, '211');
$assert(($cancelledAgain['job']['status'] ?? null) === 'cancelled',
'Administrator cancellation was not idempotent.');
$reject(static fn () => Operations::cancel($admin, '208'), 409);
$reject(static fn () => Operations::cancel($admin, '207'), 409);
$reject(static fn () => Operations::cancel($customer, '211'), 403);
echo "Administrator operations SQLite filtering, pagination, privacy, ownership, attention and real API authorization passed (3/3 list queries).\n";
}

@ -41,7 +41,7 @@ $schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->string('region')->default('');
$table->string('country_code', 2)->default('');
$table->integer('enabled')->default(0);
$table->string('default_network')->default('default');
$table->string('default_network')->default('public');
$table->integer('created_at');
$table->integer('updated_at');
});
@ -65,7 +65,7 @@ $host->name = 'Activation Gate Host';
$host->region = 'test';
$host->country_code = 'US';
$host->enabled = true;
$host->default_network = 'bridge:br0';
$host->default_network = 'public';
$host->created_at = $now;
$host->updated_at = $now;
$host->save();
@ -97,20 +97,32 @@ $assert($ready['ready'] === true && $ready['tested_revision'] === 1
instanceof CloudAgentClient,
'The exact successfully tested Agent revision did not become ready.');
CloudAgentSettingsService::invalidateForNetworkSelectorChange(
(int) $host->id
);
$invalidated = CloudAgentSettingsService::read((int) $host->id);
$assert($invalidated['revision'] === 2
&& $invalidated['tested_revision'] === 0
&& $invalidated['last_test_status'] === 'never'
&& $invalidated['ready'] === false
&& CloudAgentSettingsService::enabledHostIds() === [],
'Changing the host selector did not revoke the prior Agent readiness.');
$recordTest->invoke(null, (int) $host->id, 2, 'healthy', '', 'test-2');
$changed = CloudAgentSettingsService::save((int) $host->id, [
'enabled' => false,
'api_secret' => '',
'expected_revision' => 1,
'expected_revision' => 2,
]);
$assert($changed['revision'] === 2 && $changed['enabled'] === false
$assert($changed['revision'] === 3 && $changed['enabled'] === false
&& $changed['tested_revision'] === 0
&& $changed['last_test_status'] === 'never'
&& $changed['ready'] === false
&& CloudAgentSettingsService::enabledHostIds() === [],
'Changing an Agent setting retained the prior revision readiness.');
$recordTest->invoke(null, (int) $host->id, 2, 'healthy', '', 'test-2');
$recordTest->invoke(null, (int) $host->id, 2, 'unhealthy',
$recordTest->invoke(null, (int) $host->id, 3, 'healthy', '', 'test-3');
$recordTest->invoke(null, (int) $host->id, 3, 'unhealthy',
'agent_unavailable', '');
$failed = CloudHostAgent::find((int) $host->id);
$assert($failed !== null && !$failed->isReady()

@ -20,6 +20,7 @@ $gatewayEndpoint = $read('app/Services/Cloud/CloudAgentGatewayEndpoint.php');
$page = $read('resources/views/venix/admin/cloud/agents.tpl');
$sidebar = $read('resources/views/venix/admin/static_header.tpl');
$browser = $read('public/cloud/agent-settings.js');
$runtime = $read('public/cloud/runtime.js');
$assert(str_contains($schema, 'CREATE TABLE IF NOT EXISTS cloud_host_agents')
&& str_contains($schema, 'sealed_api_secret LONGTEXT NOT NULL')
@ -42,8 +43,12 @@ $assert(str_contains($routes,
$assert(str_contains($routes, "'/vms/{id}/rescue/force-start'")
&& str_contains($apiController, "elseif (\$action === '/force-start')")
&& str_contains($apiController, "\$suffix = '/rescue/force-start'")
&& str_contains($apiController, "\$body = ['ack_data_loss' => true]"),
'Rescue force-start no longer maps to the dedicated acknowledged Agent operation.');
&& str_contains($apiController, "\$body = ['ack_data_loss' => true]")
&& str_contains($runtime,
"if (action === 'load') { body.template_id = byId('rescue-template-id').value; body.ack_data_loss = true; }")
&& str_contains($runtime,
"if (action === 'force-start') body.ack_data_loss = true"),
'Rescue entry or force-start lost its explicit data-loss acknowledgement contract.');
$assert(str_contains($controller, '$this->actor($request, false)')
&& substr_count($controller, '$this->actor($request, true)') >= 1
&& str_contains($controller, 'CloudAccess::manage($actor)'),

@ -94,13 +94,24 @@ $handler = new MockHandler([
json_encode(['status' => 'ok', 'service' => 'virt-host-agent',
'version' => 'test'], JSON_THROW_ON_ERROR)),
new Response(401, ['Content-Type' => 'application/json'],
json_encode(['error' => ['code' => 'unauthorized',
'message' => 'secret details']], JSON_THROW_ON_ERROR)),
json_encode(['error' => [
'code' => 'unauthorized',
'message' => 'secret details',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(401, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'replayed_request',
'message' => 'request nonce has already been used',
'retryable' => false,
]], JSON_THROW_ON_ERROR)),
new Response(400, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'gateway_request_invalid',
'message' => 'Agent gateway request is invalid',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(503, ['Content-Type' => 'application/json'],
json_encode(['error' => [
@ -109,6 +120,55 @@ $handler = new MockHandler([
'retryable' => true,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(403, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'gateway_forbidden',
'message' => 'Agent gateway request is forbidden',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(403, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'forbidden',
'message' => 'administrator privileges are required',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(404, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'not_found',
'message' => 'endpoint not found',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(405, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'method_not_allowed',
'message' => 'method is not allowed',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(503, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'nonce_store_unavailable',
'message' => 'authentication state is unavailable',
'retryable' => true,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(422, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'invalid_request',
'message' => 'request is invalid',
'retryable' => false,
]], JSON_THROW_ON_ERROR)),
new Response(422, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'invalid_request',
'message' => 'request is invalid',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
'unexpected' => true,
]], JSON_THROW_ON_ERROR)),
]);
$stack = HandlerStack::create($handler);
$stack->push(Middleware::history($history));
@ -143,16 +203,28 @@ try {
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'unauthorized'
&& $error->httpStatus === 502 && !$error->retryable
&& $error->safeValidationFailure
&& !$error->safePreDispatchFailure
&& !str_contains($error->getMessage(), 'secret details'),
'Agent errors lost typed handling or exposed upstream detail.');
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Agent replay rejection was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'replayed_request'
&& !$error->safeValidationFailure
&& !$error->safePreDispatchFailure,
'Agent replay rejection incorrectly claimed the original request was not dispatched.');
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Gateway validation failure was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'gateway_request_invalid'
&& !$error->retryable && $error->safeCreateFailure
&& !$error->retryable && $error->safeValidationFailure
&& $error->agentHttpStatus === 400,
'Typed local gateway rejection was treated as an ambiguous dispatch.');
}
@ -162,10 +234,60 @@ try {
throw new RuntimeException('Definitive pre-dispatch busy response was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'agent_busy'
&& $error->retryable && !$error->safeCreateFailure
&& $error->retryable && !$error->safeValidationFailure
&& $error->safePreDispatchFailure
&& $error->agentHttpStatus === 503,
'Authenticated not-dispatched proof was not preserved for the durable queue.');
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Gateway authentication failure was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'gateway_forbidden'
&& !$error->retryable && $error->safeValidationFailure
&& !$error->safePreDispatchFailure
&& $error->agentHttpStatus === 403,
'Gateway authentication rejection was not terminal pre-dispatch.');
}
foreach ([
['forbidden', 403],
['not_found', 404],
['method_not_allowed', 405],
] as [$code, $status]) {
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException("Terminal {$code} response was accepted.");
} catch (CloudAgentError $error) {
$assert($error->agentCode === $code
&& $error->agentHttpStatus === $status
&& $error->safeValidationFailure
&& !$error->safePreDispatchFailure,
"Terminal {$code} response lost its strict no-journal proof.");
}
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Nonce-store outage was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'nonce_store_unavailable'
&& $error->retryable && !$error->safeValidationFailure
&& $error->safePreDispatchFailure,
'Retryable Agent authentication-state failure lost its no-journal proof.');
}
foreach (['missing marker', 'unexpected field'] as $case) {
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException("Loose {$case} response was accepted.");
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'invalid_request'
&& !$error->safeValidationFailure
&& !$error->safePreDispatchFailure,
"A {$case} envelope was accepted as definitive no-journal proof.");
}
}
echo "Agent outbound gateway and nested HMAC protocol contract passed.\n";

@ -54,19 +54,24 @@ $features['uefi'] = true;
$features['secure_boot'] = false;
$summary = $capabilitySummary->invoke(null, [
'backend' => 'libvirt', 'features' => $features,
]);
'network_selectors' => ['private', 'public'],
], 'public');
$assert($summary === [
'backend' => 'libvirt',
'uefi' => true,
'secure_boot' => false,
'network_selectors' => ['private', 'public'],
'required_network_selector' => 'public',
'required_feature_count' => 14,
'available_features' => $required,
'unavailable_features' => [],
], 'Valid libvirt/UEFI/no-Secure-Boot capability response changed.');
$expectCapabilityError = static function (array $capabilities,
string $code, int $status) use ($assert, $capabilitySummary): void {
string $code, int $status, string $requiredSelector = 'public') use (
$assert, $capabilitySummary
): void {
try {
$capabilitySummary->invoke(null, $capabilities);
$capabilitySummary->invoke(null, $capabilities, $requiredSelector);
} catch (\App\Services\Cloud\CloudAgentError $error) {
$assert($error->agentCode === $code && $error->httpStatus === $status,
'Capability mismatch returned the wrong stable error contract.');
@ -74,20 +79,42 @@ $expectCapabilityError = static function (array $capabilities,
}
throw new RuntimeException('Invalid Agent capabilities were accepted.');
};
$invalidBackend = ['backend' => 'qemu', 'features' => $features];
$validSelectors = ['network_selectors' => ['public']];
$invalidBackend = ['backend' => 'qemu', 'features' => $features]
+ $validSelectors;
$expectCapabilityError($invalidBackend, 'agent_invalid_capabilities', 502);
$missingFeature = $features;
unset($missingFeature['metrics']);
$expectCapabilityError(['backend' => 'libvirt', 'features' => $missingFeature],
$expectCapabilityError(['backend' => 'libvirt', 'features' => $missingFeature]
+ $validSelectors,
'agent_invalid_capabilities', 502);
foreach ([
array_replace($features, ['metrics' => false]),
array_replace($features, ['uefi' => false]),
array_replace($features, ['secure_boot' => true]),
] as $mismatch) {
$expectCapabilityError(['backend' => 'libvirt', 'features' => $mismatch],
$expectCapabilityError(['backend' => 'libvirt', 'features' => $mismatch]
+ $validSelectors,
'agent_capability_mismatch', 409);
}
foreach ([
null,
[],
['public', 'private'],
['public', 'public'],
[str_repeat('a', 65)],
array_fill(0, 65, 'public'),
] as $invalidSelectors) {
$payload = ['backend' => 'libvirt', 'features' => $features];
if ($invalidSelectors !== null) {
$payload['network_selectors'] = $invalidSelectors;
}
$expectCapabilityError($payload, 'agent_invalid_capabilities', 502);
}
$expectCapabilityError([
'backend' => 'libvirt', 'features' => $features,
'network_selectors' => ['private'],
], 'agent_capability_mismatch', 409);
foreach ([$worker, $lifecycle] as $source) {
$assert(is_string($source)

@ -8,12 +8,23 @@ namespace App\Services\Cloud {
public array $requests = [];
public array $operations = [];
public string $mode = 'running';
public ?string $reconcileMode = null;
public function request(string $method, string $target, array $actor,
?array $payload = null): array
{
$method = strtoupper($method);
$this->requests[] = compact('method', 'target', 'actor', 'payload');
if ($method === 'DELETE'
&& in_array($this->mode,
['pre_dispatch_busy', 'pre_dispatch_draining'], true)) {
$code = $this->mode === 'pre_dispatch_busy'
? 'agent_busy' : 'gateway_draining';
throw new CloudAgentError(
'request was not dispatched', 503, $code, true, 503,
false, true
);
}
if ($method === 'DELETE') {
$operationId = (string) ($payload['operation_id'] ?? '');
if (preg_match('#^/v1/templates/([^?]+)$#D', $target, $match)) {
@ -32,51 +43,64 @@ namespace App\Services\Cloud {
throw new \RuntimeException('Unexpected fake Agent DELETE: ' . $target);
}
$this->operations[$operationId] = $resource;
} elseif ($method === 'POST'
&& preg_match(
'#^/v1/operations/([A-Za-z0-9_-]+)/reconcile$#D',
$target, $match)) {
$operationId = rawurldecode($match[1]);
$resource = $this->operations[$operationId] ?? null;
if (!is_array($resource)) {
throw new CloudAgentError('operation missing', 404,
'operation_not_found', false, 404);
}
return $this->response($operationId, $resource,
$this->reconcileMode ?? $this->mode);
} elseif ($method === 'GET'
&& preg_match('#^/v1/operations/([A-Za-z0-9_-]+)$#D',
$target, $match)) {
$operationId = rawurldecode($match[1]);
$resource = $this->operations[$operationId] ?? null;
if (!is_array($resource)) {
throw new \RuntimeException('Unknown fake Agent operation: '
. $operationId);
throw new CloudAgentError('operation missing', 404,
'operation_not_found', false, 404);
}
} else {
throw new \RuntimeException('Unexpected fake Agent request: '
. $method . ' ' . $target);
}
return $this->response($operationId, $resource);
return $this->response($operationId, $resource, $this->mode);
}
private function response(string $operationId, array $resource): array
private function response(string $operationId, array $resource,
string $mode): array
{
$notFoundCode = $resource['resource_type'] . '_not_found';
if ($this->mode === 'direct_not_found') {
if ($mode === 'direct_not_found') {
throw new CloudAgentError('Direct Agent 404 without operation',
502, $notFoundCode, false, 404);
}
if ($this->mode === 'durable_not_found') {
if ($mode === 'durable_not_found') {
return ['operation_id' => $operationId, 'status' => 'failed',
'retryable' => false,
'error' => ['code' => $notFoundCode]];
}
if ($this->mode === 'running') {
if ($mode === 'running') {
return ['operation_id' => $operationId, 'status' => 'running'];
}
if ($this->mode === 'failed') {
if ($mode === 'failed') {
return ['operation_id' => $operationId, 'status' => 'failed',
'error' => ['code' => 'resource_busy']];
}
if ($this->mode === 'uncertain') {
if ($mode === 'uncertain') {
return ['operation_id' => $operationId, 'status' => 'uncertain',
'error' => ['code' => 'delete_uncertain']];
}
if ($this->mode === 'missing_evidence') {
if ($mode === 'missing_evidence') {
return ['operation_id' => $operationId, 'status' => 'succeeded',
'result' => ['deleted' => true]];
}
if (!in_array($this->mode, ['success', 'wrong_owner'], true)) {
throw new \RuntimeException('Unknown fake Agent mode: ' . $this->mode);
if (!in_array($mode, ['success', 'wrong_owner'], true)) {
throw new \RuntimeException('Unknown fake Agent mode: ' . $mode);
}
$result = [
'resource_type' => $resource['resource_type'],
@ -88,7 +112,7 @@ namespace App\Services\Cloud {
];
if ($resource['resource_type'] === 'user_iso') {
$result['owner_id'] = $resource['owner_id']
+ ($this->mode === 'wrong_owner' ? 1 : 0);
+ ($mode === 'wrong_owner' ? 1 : 0);
}
return ['operation_id' => $operationId, 'status' => 'succeeded',
'retryable' => false,
@ -353,6 +377,44 @@ namespace {
&& count($templateAgent->requests) === $requestsBeforeLockCheck,
'Template missing-proof outcome was not latched without replay.');
// Exact not_dispatched backpressure is the only case where DELETE may be
// sent again. It must retain and reuse the already-persisted operation ID.
$busyTemplateId = 'debian-12-delete-busy';
$busyTemplateAgent = new CatalogDeletionFakeAgent();
$busyTemplateAgent->mode = 'pre_dispatch_busy';
CloudAgentSettingsService::$clients[17] = $busyTemplateAgent;
$busyTemplateGeneration = str_repeat('1', 32);
$seedTemplate($busyTemplateId, 17, $busyTemplateGeneration);
$busyTemplate = CloudTemplateCatalogService::delete(
$busyTemplateId, 1, $busyTemplateGeneration,
['user_id' => 1, 'can_manage' => true]
);
$busyTemplateReplica = CloudTemplateReplica::query()
->where('template_id', $busyTemplateId)->first();
$busyTemplateOperation = (string) $busyTemplateReplica->operation_id;
$assert($busyTemplate['status'] === 'running'
&& (string) $busyTemplateReplica->state === 'delete_dispatch'
&& $busyTemplateAgent->operations === []
&& $requestCount($busyTemplateAgent, 'DELETE') === 1,
'Pre-dispatch template backpressure became a terminal deletion.');
$busyTemplateReplica->updated_at = time() - 6;
$busyTemplateReplica->save();
$busyTemplateAgent->mode = 'success';
$retriedBusyTemplate = CloudTemplateCatalogService::deleteJob(
$busyTemplateId, ['user_id' => 1, 'can_manage' => true]
);
$busyTemplateDeletes = array_values(array_filter(
$busyTemplateAgent->requests,
static fn (array $request): bool => $request['method'] === 'DELETE'
));
$assert($retriedBusyTemplate['status'] === 'succeeded'
&& count($busyTemplateDeletes) === 2
&& ($busyTemplateDeletes[0]['payload']['operation_id'] ?? null)
=== $busyTemplateOperation
&& ($busyTemplateDeletes[1]['payload']['operation_id'] ?? null)
=== $busyTemplateOperation,
'Template backpressure retry changed operation ID or did not finish.');
$sendingTemplateId = 'debian-12-delete-sending';
$sendingTemplateAgent = new CatalogDeletionFakeAgent();
CloudAgentSettingsService::$clients[12] = $sendingTemplateAgent;
@ -382,9 +444,75 @@ namespace {
->where('template_id', $sendingTemplateId)->first();
$assert($staleSendingTemplate['status'] === 'uncertain'
&& (string) $sendingTemplateReplica->error_code
=== 'delete_dispatch_unconfirmed'
&& $sendingTemplateAgent->requests === [],
'Stale template dispatch claim was queried or left replayable.');
=== 'operation_not_found'
&& count($sendingTemplateAgent->requests) === 1
&& $sendingTemplateAgent->requests[0]['method'] === 'GET'
&& $sendingTemplateAgent->requests[0]['target']
=== '/v1/operations/'
. (string) $sendingTemplateReplica->operation_id
&& $requestCount($sendingTemplateAgent, 'DELETE') === 0,
'Stale template sending claim was not queried safely by operation ID.');
$reconcileTemplateId = 'debian-12-delete-reconcile';
$reconcileTemplateAgent = new CatalogDeletionFakeAgent();
CloudAgentSettingsService::$clients[15] = $reconcileTemplateAgent;
$reconcileTemplateGeneration = str_repeat('f', 32);
$seedTemplate($reconcileTemplateId, 15, $reconcileTemplateGeneration);
CloudTemplateCatalogService::delete(
$reconcileTemplateId, 1, $reconcileTemplateGeneration,
['user_id' => 1, 'can_manage' => true]
);
$reconcileTemplateReplica = CloudTemplateReplica::query()
->where('template_id', $reconcileTemplateId)->first();
$reconcileTemplateOperation =
(string) $reconcileTemplateReplica->operation_id;
$reconcileTemplateAgent->mode = 'uncertain';
$reconcileTemplateAgent->reconcileMode = 'success';
$beforeTemplateReconcile = count($reconcileTemplateAgent->requests);
$reconciledTemplateDelete = CloudTemplateCatalogService::deleteJob(
$reconcileTemplateId, ['user_id' => 1, 'can_manage' => true]
);
$templateReconcileRequests = array_slice(
$reconcileTemplateAgent->requests, $beforeTemplateReconcile
);
$assert($reconciledTemplateDelete['status'] === 'succeeded'
&& $requestCount($reconcileTemplateAgent, 'DELETE') === 1
&& count($templateReconcileRequests) === 2
&& $templateReconcileRequests[0]['method'] === 'GET'
&& $templateReconcileRequests[0]['target']
=== '/v1/operations/' . $reconcileTemplateOperation
&& $templateReconcileRequests[1]['method'] === 'POST'
&& $templateReconcileRequests[1]['target']
=== '/v1/operations/' . $reconcileTemplateOperation
. '/reconcile',
'Template delete uncertainty replayed DELETE or changed operation ID.');
$trueUncertainTemplateId = 'debian-12-delete-uncertain';
$trueUncertainTemplateAgent = new CatalogDeletionFakeAgent();
CloudAgentSettingsService::$clients[16] = $trueUncertainTemplateAgent;
$trueUncertainGeneration = str_repeat('0', 32);
$seedTemplate(
$trueUncertainTemplateId, 16, $trueUncertainGeneration
);
CloudTemplateCatalogService::delete(
$trueUncertainTemplateId, 1, $trueUncertainGeneration,
['user_id' => 1, 'can_manage' => true]
);
$trueUncertainTemplateAgent->mode = 'uncertain';
$trueUncertainTemplateAgent->reconcileMode = 'uncertain';
$trueUncertainDelete = CloudTemplateCatalogService::deleteJob(
$trueUncertainTemplateId, ['user_id' => 1, 'can_manage' => true]
);
$requestsAtTrueUncertain = count($trueUncertainTemplateAgent->requests);
$trueUncertainDeleteAgain = CloudTemplateCatalogService::deleteJob(
$trueUncertainTemplateId, ['user_id' => 1, 'can_manage' => true]
);
$assert($trueUncertainDelete['status'] === 'uncertain'
&& $trueUncertainDeleteAgain['status'] === 'uncertain'
&& $requestCount($trueUncertainTemplateAgent, 'DELETE') === 1
&& count($trueUncertainTemplateAgent->requests)
=== $requestsAtTrueUncertain,
'A genuinely uncertain template delete was replayed or left pollable.');
$successfulTemplateId = 'debian-12-delete-success';
$successfulTemplateAgent = new CatalogDeletionFakeAgent();
@ -417,11 +545,11 @@ namespace {
$directTemplateReplica = CloudTemplateReplica::query()
->where('template_id', $directTemplateId)->first();
$assert($directTemplate['deleted'] === false
&& $directTemplate['status'] === 'failed'
&& $directTemplate['status'] === 'uncertain'
&& (string) CloudTemplate::find($directTemplateId)->state === 'deleting'
&& (string) $directTemplateReplica->state === 'delete_failed'
&& (string) $directTemplateReplica->error_code === 'template_not_found',
'Direct template 404 without a durable operation falsely completed deletion.');
&& (string) $directTemplateReplica->state === 'delete_uncertain'
&& (string) $directTemplateReplica->error_code === 'operation_not_found',
'Unmarked template 404 was made terminal without no-dispatch proof.');
$durableTemplateId = 'debian-12-durable-404';
$durableTemplateAgent = new CatalogDeletionFakeAgent();
$durableTemplateAgent->mode = 'durable_not_found';
@ -478,6 +606,40 @@ namespace {
&& count($isoAgent->requests) === $requestsBeforeIsoLockCheck,
'ISO owner mismatch was not latched without destructive replay.');
$busyIsoId = str_repeat('b', 32);
$busyIsoAgent = new CatalogDeletionFakeAgent();
$busyIsoAgent->mode = 'pre_dispatch_draining';
CloudAgentSettingsService::$clients[26] = $busyIsoAgent;
$seedIso($busyIsoId, 26, 42);
$busyIso = CloudUserIsoService::delete(
$busyIsoId, ['user_id' => 42, 'can_manage' => false]
);
$busyIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', $busyIsoId)->first();
$busyIsoOperation = (string) $busyIsoReplica->operation_id;
$assert($busyIso['status'] === 'running'
&& (string) $busyIsoReplica->state === 'delete_dispatch'
&& $busyIsoAgent->operations === []
&& $requestCount($busyIsoAgent, 'DELETE') === 1,
'Pre-dispatch ISO backpressure became a terminal deletion.');
$busyIsoReplica->updated_at = time() - 6;
$busyIsoReplica->save();
$busyIsoAgent->mode = 'success';
$retriedBusyIso = CloudUserIsoService::deleteJob(
$busyIsoId, ['user_id' => 42, 'can_manage' => false]
);
$busyIsoDeletes = array_values(array_filter(
$busyIsoAgent->requests,
static fn (array $request): bool => $request['method'] === 'DELETE'
));
$assert($retriedBusyIso['status'] === 'succeeded'
&& count($busyIsoDeletes) === 2
&& ($busyIsoDeletes[0]['payload']['operation_id'] ?? null)
=== $busyIsoOperation
&& ($busyIsoDeletes[1]['payload']['operation_id'] ?? null)
=== $busyIsoOperation,
'ISO backpressure retry changed operation ID or did not finish.');
$sendingIsoId = str_repeat('6', 32);
$sendingIsoAgent = new CatalogDeletionFakeAgent();
CloudAgentSettingsService::$clients[22] = $sendingIsoAgent;
@ -505,10 +667,43 @@ namespace {
$sendingIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', $sendingIsoId)->first();
$assert($staleSendingIso['status'] === 'uncertain'
&& (string) $sendingIsoReplica->error_code
=== 'delete_dispatch_unconfirmed'
&& $sendingIsoAgent->requests === [],
'Stale ISO dispatch claim was queried or left replayable.');
&& (string) $sendingIsoReplica->error_code === 'operation_not_found'
&& count($sendingIsoAgent->requests) === 1
&& $sendingIsoAgent->requests[0]['method'] === 'GET'
&& $sendingIsoAgent->requests[0]['target']
=== '/v1/operations/' . (string) $sendingIsoReplica->operation_id
&& $requestCount($sendingIsoAgent, 'DELETE') === 0,
'Stale ISO sending claim was not queried safely by operation ID.');
$reconcileIsoId = str_repeat('d', 32);
$reconcileIsoAgent = new CatalogDeletionFakeAgent();
CloudAgentSettingsService::$clients[25] = $reconcileIsoAgent;
$seedIso($reconcileIsoId, 25, 42);
CloudUserIsoService::delete(
$reconcileIsoId, ['user_id' => 42, 'can_manage' => false]
);
$reconcileIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', $reconcileIsoId)->first();
$reconcileIsoOperation = (string) $reconcileIsoReplica->operation_id;
$reconcileIsoAgent->mode = 'uncertain';
$reconcileIsoAgent->reconcileMode = 'success';
$beforeIsoReconcile = count($reconcileIsoAgent->requests);
$reconciledIsoDelete = CloudUserIsoService::deleteJob(
$reconcileIsoId, ['user_id' => 42, 'can_manage' => false]
);
$isoReconcileRequests = array_slice(
$reconcileIsoAgent->requests, $beforeIsoReconcile
);
$assert($reconciledIsoDelete['status'] === 'succeeded'
&& $requestCount($reconcileIsoAgent, 'DELETE') === 1
&& count($isoReconcileRequests) === 2
&& $isoReconcileRequests[0]['method'] === 'GET'
&& $isoReconcileRequests[0]['target']
=== '/v1/operations/' . $reconcileIsoOperation
&& $isoReconcileRequests[1]['method'] === 'POST'
&& $isoReconcileRequests[1]['target']
=== '/v1/operations/' . $reconcileIsoOperation . '/reconcile',
'User ISO delete uncertainty replayed DELETE or changed operation ID.');
$successfulIsoId = str_repeat('3', 32);
$successfulIsoAgent = new CatalogDeletionFakeAgent();
@ -517,13 +712,35 @@ namespace {
$seedIso($successfulIsoId, 21, 42);
$deletedIso = CloudUserIsoService::delete($successfulIsoId,
['user_id' => 42, 'can_manage' => false]);
$successfulIsoTombstone = CloudUserIso::find($successfulIsoId);
$polledDeletedIso = CloudUserIsoService::deleteJob($successfulIsoId,
['user_id' => 42, 'can_manage' => false]);
$repeatedDeletedIso = CloudUserIsoService::delete($successfulIsoId,
['user_id' => 42, 'can_manage' => false]);
$historicalImport = CloudUserIsoService::job(
(string) $successfulIsoTombstone->import_operation_id,
['user_id' => 42, 'can_manage' => false]
);
$listedAfterDelete = CloudUserIsoService::listing(42);
$assert($deletedIso['deleted'] === true
&& $deletedIso['status'] === 'succeeded'
&& CloudUserIso::find($successfulIsoId) === null
&& $polledDeletedIso['status'] === 'succeeded'
&& $repeatedDeletedIso['status'] === 'succeeded'
&& $historicalImport['status'] === 'succeeded'
&& $historicalImport['deleted'] === true
&& !in_array($successfulIsoId, array_column(
$listedAfterDelete['isos'], 'id'
), true)
&& $successfulIsoTombstone !== null
&& (string) $successfulIsoTombstone->state === 'retired'
&& (string) $successfulIsoTombstone->name === ''
&& (string) $successfulIsoTombstone->sealed_source_url === ''
&& (string) $successfulIsoTombstone->sha256 === ''
&& (int) $successfulIsoTombstone->size_bytes === 0
&& !CloudUserIsoReplica::query()->where('user_iso_id',
$successfulIsoId)->exists()
&& $requestCount($successfulIsoAgent, 'DELETE') === 1,
'Exact user ISO cleanup proof did not finalize owner data removal.');
'Exact ISO cleanup did not leave a pollable, data-free tombstone.');
$directIsoId = str_repeat('7', 32);
$directIsoAgent = new CatalogDeletionFakeAgent();
@ -535,11 +752,11 @@ namespace {
$directIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', $directIsoId)->first();
$assert($directIso['deleted'] === false
&& $directIso['status'] === 'failed'
&& $directIso['status'] === 'uncertain'
&& (string) CloudUserIso::find($directIsoId)->state === 'deleting'
&& (string) $directIsoReplica->state === 'delete_failed'
&& (string) $directIsoReplica->error_code === 'user_iso_not_found',
'Direct ISO 404 without a durable operation falsely completed deletion.');
&& (string) $directIsoReplica->state === 'delete_uncertain'
&& (string) $directIsoReplica->error_code === 'operation_not_found',
'Unmarked ISO 404 was made terminal without no-dispatch proof.');
$durableIsoId = str_repeat('8', 32);
$durableIsoAgent = new CatalogDeletionFakeAgent();
$durableIsoAgent->mode = 'durable_not_found';
@ -547,11 +764,49 @@ namespace {
$seedIso($durableIsoId, 24, 42);
$durableIso = CloudUserIsoService::delete($durableIsoId,
['user_id' => 42, 'can_manage' => false]);
$durableIsoTombstone = CloudUserIso::find($durableIsoId);
$assert($durableIso['deleted'] === true
&& CloudUserIso::find($durableIsoId) === null,
&& (string) $durableIsoTombstone->state === 'retired',
'Durable non-retryable user_iso_not_found operation did not complete deletion.');
// Rescue: terminal tombstones survive retries and prevent redispatch.
$busyRescueId = str_repeat('c', 32);
$busyRescueAgent = new CatalogDeletionFakeAgent();
$busyRescueAgent->mode = 'pre_dispatch_busy';
CloudAgentSettingsService::$clients[35] = $busyRescueAgent;
$busyRescue = CloudRescueTemplateDeletionService::delete(
35, $busyRescueId, ['user_id' => 1, 'can_manage' => true]
);
$busyRescueRecord = CloudRescueTemplateDeletion::query()
->where('host_id', 35)->where('template_id', $busyRescueId)->first();
$busyRescueOperation = (string) $busyRescueRecord->operation_id;
$assert($busyRescue['status'] === 'running'
&& (string) $busyRescueRecord->state === 'dispatching'
&& $busyRescueAgent->operations === []
&& $requestCount($busyRescueAgent, 'DELETE') === 1,
'Pre-dispatch rescue backpressure became a terminal deletion.');
// This model has a composite key and deliberately must not use save().
Capsule::table('cloud_rescue_template_deletions')
->where('host_id', 35)->where('template_id', $busyRescueId)
->where('operation_id', $busyRescueOperation)
->update(['updated_at' => time() - 6]);
$busyRescueAgent->mode = 'success';
$retriedBusyRescue = CloudRescueTemplateDeletionService::job(
35, $busyRescueOperation,
['user_id' => 1, 'can_manage' => true]
);
$busyRescueDeletes = array_values(array_filter(
$busyRescueAgent->requests,
static fn (array $request): bool => $request['method'] === 'DELETE'
));
$assert($retriedBusyRescue['status'] === 'succeeded'
&& count($busyRescueDeletes) === 2
&& ($busyRescueDeletes[0]['payload']['operation_id'] ?? null)
=== $busyRescueOperation
&& ($busyRescueDeletes[1]['payload']['operation_id'] ?? null)
=== $busyRescueOperation,
'Rescue backpressure retry changed operation ID or did not finish.');
$rescueId = str_repeat('4', 32);
$rescueAgent = new CatalogDeletionFakeAgent();
CloudAgentSettingsService::$clients[30] = $rescueAgent;
@ -593,6 +848,34 @@ namespace {
&& count($rescueAgent->requests) === $requestsBeforeRescueLockCheck,
'Rescue missing-proof result was not retained as a no-replay tombstone.');
$reconcileRescueId = str_repeat('e', 32);
$reconcileRescueAgent = new CatalogDeletionFakeAgent();
CloudAgentSettingsService::$clients[34] = $reconcileRescueAgent;
$reconcileRescue = CloudRescueTemplateDeletionService::delete(
34, $reconcileRescueId, ['user_id' => 1, 'can_manage' => true]
);
$reconcileRescueOperation = (string) $reconcileRescue['operation_id'];
$reconcileRescueAgent->mode = 'uncertain';
$reconcileRescueAgent->reconcileMode = 'success';
$beforeRescueReconcile = count($reconcileRescueAgent->requests);
$reconciledRescueDelete = CloudRescueTemplateDeletionService::job(
34, $reconcileRescueOperation,
['user_id' => 1, 'can_manage' => true]
);
$rescueReconcileRequests = array_slice(
$reconcileRescueAgent->requests, $beforeRescueReconcile
);
$assert($reconciledRescueDelete['status'] === 'succeeded'
&& $requestCount($reconcileRescueAgent, 'DELETE') === 1
&& count($rescueReconcileRequests) === 2
&& $rescueReconcileRequests[0]['method'] === 'GET'
&& $rescueReconcileRequests[0]['target']
=== '/v1/operations/' . $reconcileRescueOperation
&& $rescueReconcileRequests[1]['method'] === 'POST'
&& $rescueReconcileRequests[1]['target']
=== '/v1/operations/' . $reconcileRescueOperation . '/reconcile',
'Rescue-template delete uncertainty replayed DELETE or changed operation ID.');
$successfulRescueId = str_repeat('5', 32);
$successfulRescueAgent = new CatalogDeletionFakeAgent();
$successfulRescueAgent->mode = 'success';
@ -618,6 +901,25 @@ namespace {
=== $requestsAfterRescueSuccess,
'Successful rescue tombstone did not make every retry read-only.');
// A slower status poll may carry a stale pre-terminal model snapshot.
// Its result must not move the durable success tombstone backwards.
$staleRescueRecord = clone CloudRescueTemplateDeletion::query()
->where('host_id', 31)->where('template_id', $successfulRescueId)
->first();
$staleRescueRecord->state = 'running';
$markRescueDeletion = new ReflectionMethod(
CloudRescueTemplateDeletionService::class, 'mark'
);
$markRescueDeletion->invoke(
null, $staleRescueRecord, 'running', 'late_poll_result'
);
$successfulRescueRecord = CloudRescueTemplateDeletion::query()
->where('host_id', 31)->where('template_id', $successfulRescueId)
->first();
$assert((string) $successfulRescueRecord->state === 'succeeded'
&& (string) $successfulRescueRecord->error_code === '',
'A stale rescue deletion poll overwrote its terminal tombstone.');
$directRescueId = str_repeat('9', 32);
$directRescueAgent = new CatalogDeletionFakeAgent();
$directRescueAgent->mode = 'direct_not_found';
@ -628,11 +930,11 @@ namespace {
$directRescueRecord = CloudRescueTemplateDeletion::query()
->where('host_id', 32)->where('template_id', $directRescueId)->first();
$assert($directRescue['deleted'] === false
&& $directRescue['status'] === 'failed'
&& (string) $directRescueRecord->state === 'failed'
&& $directRescue['status'] === 'running'
&& (string) $directRescueRecord->state === 'running'
&& (string) $directRescueRecord->error_code
=== 'rescue_template_not_found',
'Direct rescue-template 404 without a durable operation falsely completed deletion.');
'Unmarked rescue-template 404 was made terminal without no-dispatch proof.');
$durableRescueId = str_repeat('a', 32);
$durableRescueAgent = new CatalogDeletionFakeAgent();
$durableRescueAgent->mode = 'durable_not_found';

@ -17,6 +17,10 @@ namespace App\Services\Cloud {
/** @var null|callable */
public $beforeResponse = null;
public ?array $getResponse = null;
public ?array $postResponse = null;
public ?array $reconcileResponse = null;
public bool $ambiguousReplay = false;
public bool $preDispatchBusy = false;
public function request(string $method, string $target, array $actor,
?array $payload = null): array
@ -27,10 +31,35 @@ namespace App\Services\Cloud {
}
$operationId = (string) ($payload['operation_id']
?? $actor['operation_id'] ?? basename($target));
if (preg_match('#^/v1/operations/([A-Za-z0-9_-]+)/reconcile$#D',
$target, $match) === 1) {
$operationId = rawurldecode($match[1]);
}
if ($method === 'GET') {
return ['operation_id' => $operationId]
+ ($this->getResponse ?? ['status' => 'running']);
}
if ($method === 'POST'
&& preg_match('#^/v1/operations/[A-Za-z0-9_-]+/reconcile$#D',
$target) === 1) {
return ['operation_id' => $operationId]
+ ($this->reconcileResponse ?? $this->postResponse
?? ['status' => 'uncertain']);
}
if ($method === 'POST' && $this->preDispatchBusy
&& in_array($target,
['/v1/templates', '/v1/user-isos'], true)) {
throw new CloudAgentError('request was not dispatched', 503,
'agent_busy', true, 503, false, true);
}
if ($method === 'POST' && $this->ambiguousReplay) {
throw new CloudAgentError('nonce may have dispatched', 502,
'replayed_request', false, 401);
}
if ($this->postResponse !== null) {
return ['operation_id' => $operationId]
+ $this->postResponse;
}
if ($target === '/v1/templates') {
return [
'operation_id' => $operationId,
@ -266,6 +295,331 @@ namespace {
&& count($agent->requests) === $requestsBeforeIsoRepair,
'ISO aggregate state did not self-heal without pending replicas.');
// `dispatching` is a normal durable Agent state. It must remain pollable
// rather than being surfaced as an ambiguous import result.
$agent->postResponse = ['status' => 'dispatching'];
$dispatchTemplateJob = CloudTemplateCatalogService::importRemote([
'name' => 'Debian 13 dispatching template',
'url' => 'https://images.example/debian-13.qcow2',
'sha256' => '',
], ['user_id' => 1, 'can_manage' => true]);
$dispatchTemplate = CloudTemplate::find(
(string) $dispatchTemplateJob['job_id']
);
$dispatchTemplateReplica = CloudTemplateReplica::query()
->where('template_id', (string) $dispatchTemplate->id)->first();
$assert($dispatchTemplateJob['status'] === 'running'
&& (string) $dispatchTemplate->state === 'importing'
&& (string) $dispatchTemplateReplica->state === 'pending'
&& (string) $dispatchTemplateReplica->error_code === '',
'Template Agent dispatching response was made uncertain.');
$dispatchIsoJob = CloudUserIsoService::import([
'name' => 'Dispatching ISO',
'url' => 'https://images.example/dispatching.iso',
], ['user_id' => 52, 'can_manage' => false]);
$dispatchIso = CloudUserIso::query()->where('import_operation_id',
(string) $dispatchIsoJob['job_id'])->first();
$dispatchIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', (string) $dispatchIso->id)->first();
$assert($dispatchIsoJob['status'] === 'running'
&& (string) $dispatchIso->state === 'importing'
&& (string) $dispatchIsoReplica->state === 'pending'
&& (string) $dispatchIsoReplica->error_code === '',
'ISO Agent dispatching response was made uncertain.');
$agent->postResponse = null;
// Catalog imports intentionally get one POST only. Even exact
// not_dispatched backpressure is terminal so expiring upload/source
// capabilities are never reused by an automatic retry; an administrator
// must create a fresh import with a fresh operation and source snapshot.
$agent->preDispatchBusy = true;
$preDispatchTemplate = CloudTemplateCatalogService::importRemote([
'name' => 'Debian 12 pre-dispatch terminal template',
'url' => 'https://images.example/debian-12-predispatch.qcow2',
'sha256' => '',
], ['user_id' => 1, 'can_manage' => true]);
$preDispatchTemplateRow = CloudTemplate::find(
(string) $preDispatchTemplate['job_id']
);
$preDispatchTemplateReplica = CloudTemplateReplica::query()
->where('template_id', (string) $preDispatchTemplateRow->id)->first();
$preDispatchIso = CloudUserIsoService::import([
'name' => 'Pre-dispatch terminal ISO',
'url' => 'https://images.example/predispatch.iso',
], ['user_id' => 72, 'can_manage' => false]);
$preDispatchIsoRow = CloudUserIso::query()->where('import_operation_id',
(string) $preDispatchIso['job_id'])->first();
$preDispatchIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', (string) $preDispatchIsoRow->id)->first();
$requestsAfterPreDispatch = count($agent->requests);
CloudTemplateCatalogService::importJob(
(string) $preDispatchTemplateRow->id,
['user_id' => 1, 'can_manage' => true]
);
CloudUserIsoService::job((string) $preDispatchIsoRow->import_operation_id,
['user_id' => 72, 'can_manage' => false]);
$assert($preDispatchTemplate['status'] === 'failed'
&& (string) $preDispatchTemplateReplica->state === 'failed'
&& (string) $preDispatchTemplateReplica->error_code === 'agent_busy'
&& $preDispatchIso['status'] === 'failed'
&& (string) $preDispatchIsoReplica->state === 'failed'
&& (string) $preDispatchIsoReplica->error_code === 'agent_busy'
&& count($agent->requests) === $requestsAfterPreDispatch,
'Definitive pre-dispatch catalog import was retried automatically.');
$agent->preDispatchBusy = false;
// A non-retryable response without explicit not-dispatched proof is still
// ambiguous. Retain both imports under their original operation IDs so a
// later status lookup can reconcile them; never label them failed here.
$agent->ambiguousReplay = true;
$replayedTemplateJob = CloudTemplateCatalogService::importRemote([
'name' => 'Debian 12 ambiguous replay template',
'url' => 'https://images.example/debian-12-ambiguous-replay.qcow2',
'sha256' => '',
], ['user_id' => 1, 'can_manage' => true]);
$replayedTemplate = CloudTemplate::find(
(string) $replayedTemplateJob['job_id']
);
$replayedTemplateReplica = CloudTemplateReplica::query()
->where('template_id', (string) $replayedTemplate->id)->first();
$replayedIsoJob = CloudUserIsoService::import([
'name' => 'Ambiguous replay ISO',
'url' => 'https://images.example/ambiguous-replay.iso',
], ['user_id' => 62, 'can_manage' => false]);
$replayedIso = CloudUserIso::query()->where('import_operation_id',
(string) $replayedIsoJob['job_id'])->first();
$replayedIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', (string) $replayedIso->id)->first();
$assert($replayedTemplateJob['status'] === 'running'
&& (string) $replayedTemplateReplica->state === 'pending'
&& (string) $replayedTemplateReplica->error_code
=== 'replayed_request'
&& $replayedIsoJob['status'] === 'running'
&& (string) $replayedIsoReplica->state === 'pending'
&& (string) $replayedIsoReplica->error_code === 'replayed_request',
'Ambiguous non-retryable catalog import was made terminal.');
$agent->ambiguousReplay = false;
// An uncertain GET is inspected through the same operation's read-only
// reconcile route. Neither catalog import may be replayed.
$agent->postResponse = ['status' => 'dispatching'];
$reconcileTemplateJob = CloudTemplateCatalogService::importRemote([
'name' => 'Debian 12 template reconcile test',
'url' => 'https://images.example/debian-12-reconcile.qcow2',
'sha256' => '',
], ['user_id' => 1, 'can_manage' => true]);
$reconcileTemplate = CloudTemplate::find(
(string) $reconcileTemplateJob['job_id']
);
$reconcileTemplateReplica = CloudTemplateReplica::query()
->where('template_id', (string) $reconcileTemplate->id)->first();
$agent->postResponse = null;
$agent->getResponse = [
'status' => 'uncertain',
'error' => ['code' => 'operation_uncertain'],
];
$agent->reconcileResponse = [
'status' => 'succeeded',
'result' => [
'id' => (string) $reconcileTemplate->id,
'revision' => (int) $reconcileTemplate->revision,
'generation_token' =>
(string) $reconcileTemplate->generation_token,
'size_bytes' => 4096,
'sha256' => str_repeat('a', 64),
],
];
$templateRequestsBeforeReconcile = count($agent->requests);
$reconciledTemplate = CloudTemplateCatalogService::importJob(
(string) $reconcileTemplate->id,
['user_id' => 1, 'can_manage' => true]
);
$templateReconcileRequests = array_slice(
$agent->requests, $templateRequestsBeforeReconcile
);
$assert($reconciledTemplate['status'] === 'succeeded'
&& count($templateReconcileRequests) === 2
&& $templateReconcileRequests[0]['method'] === 'GET'
&& $templateReconcileRequests[0]['target']
=== '/v1/operations/'
. (string) $reconcileTemplateReplica->operation_id
&& $templateReconcileRequests[1]['method'] === 'POST'
&& $templateReconcileRequests[1]['target']
=== '/v1/operations/'
. (string) $reconcileTemplateReplica->operation_id
. '/reconcile',
'Template uncertainty did not reconcile the same operation without replay.');
$agent->postResponse = ['status' => 'dispatching'];
$reconcileIsoJob = CloudUserIsoService::import([
'name' => 'ISO reconcile test',
'url' => 'https://images.example/iso-reconcile.iso',
], ['user_id' => 54, 'can_manage' => false]);
$reconcileIso = CloudUserIso::query()->where('import_operation_id',
(string) $reconcileIsoJob['job_id'])->first();
$reconcileIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', (string) $reconcileIso->id)->first();
$agent->postResponse = null;
$agent->reconcileResponse = [
'status' => 'succeeded',
'result' => [
'id' => (string) $reconcileIso->id,
'owner_id' => (int) $reconcileIso->user_id,
'size_bytes' => 8192,
'sha256' => str_repeat('b', 64),
],
];
$isoRequestsBeforeReconcile = count($agent->requests);
$reconciledIso = CloudUserIsoService::job(
(string) $reconcileIso->import_operation_id,
['user_id' => 54, 'can_manage' => false]
);
$isoReconcileRequests = array_slice(
$agent->requests, $isoRequestsBeforeReconcile
);
$assert($reconciledIso['status'] === 'succeeded'
&& count($isoReconcileRequests) === 2
&& $isoReconcileRequests[0]['method'] === 'GET'
&& $isoReconcileRequests[0]['target']
=== '/v1/operations/' . (string) $reconcileIsoReplica->operation_id
&& $isoReconcileRequests[1]['method'] === 'POST'
&& $isoReconcileRequests[1]['target']
=== '/v1/operations/' . (string) $reconcileIsoReplica->operation_id
. '/reconcile',
'User ISO uncertainty did not reconcile the same operation without replay.');
$agent->reconcileResponse = null;
// Repair only the historical false-positive marker. The old operation ID
// is polled exactly once; the import POST is never replayed.
$templateOperationId = (string) $dispatchTemplateReplica->operation_id;
Capsule::table('cloud_templates')->where('id',
(string) $dispatchTemplate->id)->update(['state' => 'error']);
Capsule::table('cloud_template_replicas')->where('template_id',
(string) $dispatchTemplate->id)->update([
'state' => 'uncertain',
'error_code' => 'agent_import_uncertain',
]);
$agent->getResponse = [
'status' => 'succeeded',
'result' => [
'id' => (string) $dispatchTemplate->id,
'revision' => (int) $dispatchTemplate->revision,
'generation_token' => (string) $dispatchTemplate->generation_token,
'size_bytes' => 4096,
'sha256' => str_repeat('a', 64),
],
];
$requestsBeforeTemplateRecovery = count($agent->requests);
$recoveredTemplate = CloudTemplateCatalogService::importJob(
(string) $dispatchTemplate->id,
['user_id' => 1, 'can_manage' => true]
);
$templateRecoveryRequest = $agent->requests[
$requestsBeforeTemplateRecovery
] ?? [];
$dispatchTemplateReplica->refresh();
$assert($recoveredTemplate['status'] === 'succeeded'
&& count($agent->requests) === $requestsBeforeTemplateRecovery + 1
&& ($templateRecoveryRequest['method'] ?? null) === 'GET'
&& ($templateRecoveryRequest['target'] ?? null)
=== '/v1/operations/' . $templateOperationId
&& (string) $dispatchTemplateReplica->operation_id
=== $templateOperationId
&& (string) $dispatchTemplateReplica->state === 'active',
'Historical template uncertainty did not reconcile its saved operation.');
$isoOperationId = (string) $dispatchIsoReplica->operation_id;
Capsule::table('cloud_user_isos')->where('id',
(string) $dispatchIso->id)->update(['state' => 'failed']);
Capsule::table('cloud_user_iso_replicas')->where('user_iso_id',
(string) $dispatchIso->id)->update([
'state' => 'uncertain',
'error_code' => 'agent_import_uncertain',
]);
$agent->getResponse = [
'status' => 'succeeded',
'result' => [
'id' => (string) $dispatchIso->id,
'owner_id' => (int) $dispatchIso->user_id,
'size_bytes' => 8192,
'sha256' => str_repeat('b', 64),
],
];
$requestsBeforeIsoRecovery = count($agent->requests);
$recoveredIso = CloudUserIsoService::job(
(string) $dispatchIso->import_operation_id,
['user_id' => 52, 'can_manage' => false]
);
$isoRecoveryRequest = $agent->requests[$requestsBeforeIsoRecovery] ?? [];
$dispatchIsoReplica->refresh();
$assert($recoveredIso['status'] === 'succeeded'
&& count($agent->requests) === $requestsBeforeIsoRecovery + 1
&& ($isoRecoveryRequest['method'] ?? null) === 'GET'
&& ($isoRecoveryRequest['target'] ?? null)
=== '/v1/operations/' . $isoOperationId
&& (string) $dispatchIsoReplica->operation_id === $isoOperationId
&& (string) $dispatchIsoReplica->state === 'active',
'Historical ISO uncertainty did not reconcile its saved operation.');
// A genuine Agent uncertainty gets a new marker and stays terminal. Only
// the exact legacy dispatching marker is eligible for recovery.
$agent->postResponse = [
'status' => 'uncertain',
'error' => ['code' => 'agent_import_uncertain'],
];
$lockedTemplateJob = CloudTemplateCatalogService::importRemote([
'name' => 'Debian 11 genuinely uncertain template',
'url' => 'https://images.example/debian-11.qcow2',
'sha256' => '',
], ['user_id' => 1, 'can_manage' => true]);
$lockedTemplate = CloudTemplate::find(
(string) $lockedTemplateJob['job_id']
);
$lockedTemplateReplica = CloudTemplateReplica::query()
->where('template_id', (string) $lockedTemplate->id)->first();
$agent->postResponse = null;
$requestsBeforeLockedTemplate = count($agent->requests);
$lockedTemplateAgain = CloudTemplateCatalogService::importJob(
(string) $lockedTemplate->id,
['user_id' => 1, 'can_manage' => true]
);
$lockedTemplateReplica->refresh();
$assert($lockedTemplateJob['status'] === 'uncertain'
&& $lockedTemplateAgain['status'] === 'uncertain'
&& count($agent->requests) === $requestsBeforeLockedTemplate
&& (string) $lockedTemplateReplica->state === 'uncertain'
&& (string) $lockedTemplateReplica->error_code
=== 'agent_operation_uncertain',
'A genuine template uncertainty was unlocked as legacy dispatching.');
$agent->postResponse = [
'status' => 'uncertain',
'error' => ['code' => 'agent_import_uncertain'],
];
$lockedIsoJob = CloudUserIsoService::import([
'name' => 'Genuinely uncertain ISO',
'url' => 'https://images.example/genuinely-uncertain.iso',
], ['user_id' => 53, 'can_manage' => false]);
$lockedIso = CloudUserIso::query()->where('import_operation_id',
(string) $lockedIsoJob['job_id'])->first();
$lockedIsoReplica = CloudUserIsoReplica::query()
->where('user_iso_id', (string) $lockedIso->id)->first();
$agent->postResponse = null;
$requestsBeforeLockedIso = count($agent->requests);
$lockedIsoAgain = CloudUserIsoService::job(
(string) $lockedIso->import_operation_id,
['user_id' => 53, 'can_manage' => false]
);
$lockedIsoReplica->refresh();
$assert($lockedIsoJob['status'] === 'uncertain'
&& $lockedIsoAgain['status'] === 'uncertain'
&& count($agent->requests) === $requestsBeforeLockedIso
&& (string) $lockedIsoReplica->state === 'uncertain'
&& (string) $lockedIsoReplica->error_code
=== 'agent_operation_uncertain',
'A genuine ISO uncertainty was unlocked as legacy dispatching.');
// Quota aggregation must use the bytes committed through the locked model,
// not the stale outer object that existed before the Agent response.
$quotaOwner = 77;

@ -158,7 +158,7 @@ namespace {
$schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->string('country_code')->default(''); $t->integer('enabled'); $t->integer('resource_pool_id')->nullable(); $t->string('scheduler_state')->default('disabled'); $t->string('default_network'); $t->integer('created_at')->default(0); $t->integer('updated_at')->default(0); });
$schema->create('cloud_host_agents', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->text('sealed_api_secret'); $t->integer('enabled')->default(0); $t->integer('revision')->default(1); $t->integer('tested_revision')->default(0); $t->string('last_test_status')->default('never'); $t->string('last_error_code')->default(''); $t->string('last_agent_version')->default(''); $t->integer('last_tested_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_resource_pool_memberships', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('resource_pool_id'); $t->string('scheduler_state')->default('disabled'); $t->integer('priority')->default(0); $t->integer('weight')->default(100); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['host_id', 'resource_pool_id']); });
$schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('bridge'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('selector'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->string('cidr'); $t->string('gateway'); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id')->nullable(); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); });
@ -186,7 +186,7 @@ namespace {
$region = new CloudRegion(); $region->code = 'test-region'; $region->name = 'Test Region'; $region->country_code = 'US'; $region->status = 'active'; $region->sort = 0; $region->created_at = $region->updated_at = $now; $region->save();
$line = new CloudNetworkLine(); $line->region_id = $region->id; $line->code = 'default'; $line->name = 'Default'; $line->is_default = true; $line->status = 'active'; $line->sort = 0; $line->created_at = $line->updated_at = $now; $line->save();
$pool = new CloudResourcePool(); $pool->line_id = $line->id; $pool->code = 'general'; $pool->name = 'General'; $pool->status = 'active'; $pool->scheduling_policy = 'balanced'; $pool->sort = 0; $pool->created_at = $pool->updated_at = $now; $pool->save();
$host = new CloudHost(); $host->name = 'host'; $host->enabled = true; $host->resource_pool_id = $pool->id; $host->scheduler_state = 'active'; $host->default_network = 'bridge:br0'; $host->created_at = $host->updated_at = $now; $host->save();
$host = new CloudHost(); $host->name = 'host'; $host->enabled = true; $host->resource_pool_id = $pool->id; $host->scheduler_state = 'active'; $host->default_network = 'public'; $host->created_at = $host->updated_at = $now; $host->save();
$capsule->connection('default')->table('cloud_host_agents')->insert([
'host_id' => $host->id,
'sealed_api_secret' => 'test-only-agent-secret',
@ -201,7 +201,7 @@ namespace {
'updated_at' => $now,
]);
$membership = new CloudHostResourcePoolMembership(); $membership->host_id = $host->id; $membership->resource_pool_id = $pool->id; $membership->scheduler_state = 'active'; $membership->priority = 0; $membership->weight = 100; $membership->created_at = $membership->updated_at = $now; $membership->save();
$attachment = new CloudHostNetworkAttachment(); $attachment->attachment_key = str_repeat('a', 32); $attachment->host_id = $host->id; $attachment->line_id = $line->id; $attachment->name = 'Primary bridge'; $attachment->network_mode = 'bridge'; $attachment->network_selector = 'bridge:br0'; $attachment->state = 'active'; $attachment->priority = 0; $attachment->desired_revision = 1; $attachment->observed_revision = 1; $attachment->sync_state = 'applied'; $attachment->last_error_code = ''; $attachment->created_at = $attachment->updated_at = $now; $attachment->save();
$attachment = new CloudHostNetworkAttachment(); $attachment->attachment_key = str_repeat('a', 32); $attachment->host_id = $host->id; $attachment->line_id = $line->id; $attachment->name = 'Primary selector'; $attachment->network_mode = 'selector'; $attachment->network_selector = 'public'; $attachment->state = 'active'; $attachment->priority = 0; $attachment->desired_revision = 1; $attachment->observed_revision = 1; $attachment->sync_state = 'applied'; $attachment->last_error_code = ''; $attachment->created_at = $attachment->updated_at = $now; $attachment->save();
$sourcePoolKey = str_repeat('1', 32); $targetPoolKey = str_repeat('2', 32);
$sourcePublicPool = new CloudPublicIpPool(); $sourcePublicPool->pool_key = $sourcePoolKey; $sourcePublicPool->host_id = $host->id; $sourcePublicPool->network_attachment_id = $attachment->id; $sourcePublicPool->name = 'Primary public pool'; $sourcePublicPool->cidr = '203.0.113.16/29'; $sourcePublicPool->gateway = '203.0.113.17'; $sourcePublicPool->guest_prefix_length = 28; $sourcePublicPool->dns_servers_json = '["1.1.1.1"]'; $sourcePublicPool->reserved_ips_json = '[]'; $sourcePublicPool->state = 'active'; $sourcePublicPool->priority = 0; $sourcePublicPool->desired_revision = 1; $sourcePublicPool->observed_revision = 1; $sourcePublicPool->sync_state = 'applied'; $sourcePublicPool->last_error_code = ''; $sourcePublicPool->created_at = $sourcePublicPool->updated_at = $now; $sourcePublicPool->save();
$targetPublicPool = new CloudPublicIpPool(); $targetPublicPool->pool_key = $targetPoolKey; $targetPublicPool->host_id = $host->id; $targetPublicPool->network_attachment_id = $attachment->id; $targetPublicPool->name = 'Secondary public pool'; $targetPublicPool->cidr = '203.0.113.32/29'; $targetPublicPool->gateway = '203.0.113.33'; $targetPublicPool->guest_prefix_length = 28; $targetPublicPool->dns_servers_json = '["1.0.0.1"]'; $targetPublicPool->reserved_ips_json = '[]'; $targetPublicPool->state = 'active'; $targetPublicPool->priority = 10; $targetPublicPool->desired_revision = 1; $targetPublicPool->observed_revision = 1; $targetPublicPool->sync_state = 'applied'; $targetPublicPool->last_error_code = ''; $targetPublicPool->created_at = $targetPublicPool->updated_at = $now; $targetPublicPool->save();
@ -529,7 +529,7 @@ namespace {
$openingAgentRequest['headers']['X-Virt-Actor'], '-_', '+/'
)), true);
$assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100
&& $posted['network'] === 'bridge:br0'
&& $posted['network'] === 'public'
&& $posted['public_pool_key'] === $sourcePoolKey
&& ($posted['platform_network_policy_snapshot'] ?? null)
=== $queuedPolicy
@ -599,6 +599,7 @@ namespace {
'code' => 'invalid_request',
'message' => '虚拟机参数校验失败',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]])));
$worker->tick(); $worker->tick();
$failedDisplay = CloudOrderService::display(CloudOrder::find($failed->id));
@ -661,17 +662,43 @@ namespace {
'public_ip_cidr' => (string) $uncertainIp->address . '/'
. (int) $uncertainIp->prefix_length,
]);
$mock->append(new Response(200, [], json_encode([
'operation_id' => $uncertainJob->operation_id,
'status' => 'succeeded', 'result' => $reconciledVm,
])));
$beforeFailedCreateReconcile = count($history);
$mock->append(
new Response(200, [], json_encode([
'operation_id' => $uncertainJob->operation_id,
'status' => 'failed',
'error' => [
'code' => 'network_not_found',
'message' => 'host network selector is not configured',
],
])),
new Response(200, [], json_encode([
'operation_id' => $uncertainJob->operation_id,
'status' => 'succeeded', 'result' => $reconciledVm,
]))
);
$worker->tick();
$failedCreateReconcileRequests = array_slice(
$history, $beforeFailedCreateReconcile
);
$failedCreateLookup = count($failedCreateReconcileRequests) === 2
? $agentRequest($failedCreateReconcileRequests[0]) : [];
$failedCreateReconcile = count($failedCreateReconcileRequests) === 2
? $agentRequest($failedCreateReconcileRequests[1]) : [];
$assert(CloudInstance::count() === 2
&& CloudOrder::find($uncertain->id)->status === 'succeeded'
&& CloudResourceReservation::where('order_id', $uncertain->id)->first()->state === 'committed'
&& User::find(1)->money === '80.02'
&& CloudMailOutbox::where('kind', 'provision_succeeded')->count() === 2,
'Reconciliation did not recover exactly once or queue its success email.');
$assert(count($failedCreateReconcileRequests) === 2
&& ($failedCreateLookup['method'] ?? null) === 'GET'
&& ($failedCreateLookup['request_target'] ?? null)
=== '/v1/operations/' . $uncertainJob->operation_id
&& ($failedCreateReconcile['method'] ?? null) === 'POST'
&& ($failedCreateReconcile['request_target'] ?? null)
=== '/v1/operations/' . $uncertainJob->operation_id . '/reconcile',
'A failed create was replayed or reconciled with a different operation ID.');
$actionJob = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', ['action' => 'reboot']);
$mock->append(new Response(200, [], json_encode([
'operation_id' => $actionJob->operation_id,
@ -690,6 +717,33 @@ namespace {
&& ($signedActor['operation_id'] ?? null) === $actionJob->operation_id,
'Power task lost its typed Agent authority or did not complete.');
// Keep the panel/audit vocabulary stable while translating the force-off
// command to the Go Agent's strict PowerAction wire value.
$poweroffJob = CloudJobService::enqueue(
$instance, $actor, 'action', 'POST', '/actions', ['action' => 'poweroff']
);
$storedPoweroff = \App\Services\Cloud\CloudSecrets::decrypt(
(string) $poweroffJob->sealed_payload, 'job-payload'
);
$mock->append(new Response(200, [], json_encode([
'operation_id' => $poweroffJob->operation_id,
'status' => 'succeeded',
'result' => [
'uuid' => (string) $instance->uuid,
'state' => 'stopped',
],
])));
$worker->tick();
$poweroffRequest = $agentRequest(end($history));
$poweroffBody = json_decode(
(string) ($poweroffRequest['body'] ?? ''), true, 8,
JSON_THROW_ON_ERROR
);
$assert(CloudJob::find($poweroffJob->id)->status === 'succeeded'
&& ($storedPoweroff['body']['action'] ?? null) === 'poweroff'
&& $poweroffBody === ['action' => 'destroy'],
'Panel poweroff was not translated exactly once at the Agent wire boundary.');
// 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.
@ -728,6 +782,50 @@ namespace {
&& $agentRequest($requeueRequests[1])['method'] === 'POST',
'Safe pre-dispatch retry did not reuse and complete the durable job.');
// A strict DTO rejection happens before the Agent operation journal for
// every mutation kind, not only provisioning. It is terminal validation
// failure and must not strand a non-create task in uncertain/404 polling.
$invalidActionJob = CloudJobService::enqueue(
$instance, $actor, 'action', 'POST', '/actions', ['action' => 'reboot']
);
$beforeInvalidAction = count($history);
$mock->append(new Response(422, [], json_encode(['error' => [
'code' => 'invalid_json',
'message' => 'request contains an unknown field',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]])));
$worker->tick();
$invalidActionJob->refresh();
$assert($invalidActionJob->status === 'failed'
&& $invalidActionJob->dispatched_at !== null
&& count($history) === $beforeInvalidAction + 1,
'Definitive non-create validation failure became permanently uncertain.');
// A gateway secret mismatch is a terminal configuration/authentication
// rejection before WSS dispatch. It must not strand the task in uncertain
// polling or loop forever in the queue.
$gatewayAuthJob = CloudJobService::enqueue(
$instance, $actor, 'action', 'POST', '/actions', ['action' => 'reboot']
);
$beforeGatewayAuth = count($history);
$mock->append(new Response(403, [], json_encode(['error' => [
'code' => 'gateway_forbidden',
'message' => 'Agent gateway request is forbidden',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]])));
$worker->tick();
$gatewayAuthJob->refresh();
$assert($gatewayAuthJob->status === 'failed'
&& $gatewayAuthJob->dispatched_at !== null
&& $gatewayAuthJob->lease_token === null,
'Gateway authentication failure did not terminate before journal dispatch.');
$gatewayAuthRequests = array_slice($history, $beforeGatewayAuth);
$assert(count($gatewayAuthRequests) === 1
&& $agentRequest($gatewayAuthRequests[0])['method'] === 'POST',
'Gateway authentication failure was replayed after a terminal response.');
// A journal-backed error envelope for another operation must never finish
// this job, even when the foreign record itself is terminal.
$crossBoundJob = CloudJobService::enqueue(
@ -1272,7 +1370,22 @@ namespace {
'replayed' => false,
'retryable' => false,
]))); $worker->tick();
$reinstallRequest = $agentRequest(end($history));
$reinstallBody = json_decode(
(string) ($reinstallRequest['body'] ?? ''), true, 16,
JSON_THROW_ON_ERROR
);
$reinstallKeys = array_keys($reinstallBody);
sort($reinstallKeys);
$expectedReinstallKeys = [
'root_password', 'template_generation_token', 'template_id',
'template_revision',
];
sort($expectedReinstallKeys);
$assert(CloudJob::find($reinstall->id)->status === 'running' && $instance->fresh()->sealed_credential === $oldCredential, 'Pending reinstall replaced password prematurely.');
$assert($reinstallKeys === $expectedReinstallKeys
&& !array_key_exists('confirmation_name', $reinstallBody),
'Browser reinstall confirmation leaked into the strict Agent DTO.');
CloudJob::where('id', $reinstall->id)->update(['available_at' => 0]);
$mock->append(new Response(200, [], json_encode([
'operation_id' => $reinstall->operation_id,
@ -1317,9 +1430,12 @@ namespace {
$beforePartialReconcile = count($history);
$partialOperation = json_encode([
'operation_id' => $partialReinstall->operation_id,
'status' => 'uncertain',
// Older Agents could persist a terminal success before deterministic
// old-root cleanup completed. PHP must still call reconciliation for
// that same operation instead of looping on GET or replaying reinstall.
'status' => 'succeeded',
'replayed' => false,
'retryable' => true,
'retryable' => false,
'error' => [
'code' => 'reinstall_cleanup_pending',
'message' => 'replacement committed; cleanup pending',
@ -1464,7 +1580,7 @@ namespace {
$assert($networkBody === [
'public_ip_cidr' => '203.0.113.34/28',
'public_pool_key' => $targetPoolKey, 'confirm_restart' => true,
'network' => 'bridge:br0',
'network' => 'public',
'public_pool_cidr' => '203.0.113.32/29',
'gateway' => '203.0.113.33',
'dns_servers' => ['1.0.0.1'],

@ -160,7 +160,7 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
foreach ([10, 20, 30] as $userId) {
foreach ([10, 20, 30, 40] as $userId) {
$user = new User();
$user->id = $userId;
$user->money = '0.00';
@ -549,5 +549,97 @@ namespace {
&& $missingPolicy['can_mutate'] === false,
'A missing Agent operation was replayed or closed as terminal failure.');
// A strict Agent validation response carrying the exact not-dispatched
// marker is terminal for firewall work as well. The panel-generated
// failure remains bound to the original operation so the firewall
// projection does not reject it and strand the job as uncertain.
$validationInstance = $newInstance(40);
$validationActor = ['user_id' => 40, 'is_admin' => false,
'is_super_admin' => false, 'can_manage' => false];
$validationApply = CloudFirewallService::apply(
$validationInstance, $validationActor, [
'enabled' => true, 'expected_revision' => 0,
'idempotency_key' => 'fw-request-validation-0001',
'rules' => [[
'protocol' => 'tcp', 'source_cidr' => '192.0.2.40/32',
'port_from' => 22, 'port_to' => 22,
'description' => 'Strict validation failure',
]],
]
);
$validationJob = $validationApply['job'];
$validationHistory = [];
$validationStack = HandlerStack::create(new MockHandler([
new Response(422, [], json_encode(['error' => [
'code' => 'invalid_json',
'message' => 'request contains an unknown field',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
]));
$validationStack->push(Middleware::history($validationHistory));
$validationAgent = new CloudAgentClient(
'1',
'test-secret-which-is-at-least-32-bytes',
new Client(['handler' => $validationStack]),
20.0,
'http://127.0.0.1:8001/internal/agent/request',
'test-gateway-secret-at-least-32-bytes'
);
(new CloudWorkerService($validationAgent))->tick();
$validationJob->refresh();
$validationPolicy = CloudFirewallService::listing(
$validationInstance, $validationActor
);
$assert(count($validationHistory) === 1
&& (string) $validationJob->status === 'failed'
&& (string) $validationJob->error_code === 'firewall_apply_failed'
&& $validationPolicy['sync_state'] === 'failed'
&& $validationPolicy['can_mutate'] === true
&& (string) CloudInstanceFirewallVersion::where(
'instance_id', (int) $validationInstance->id
)->value('state') === 'failed',
'A proven pre-dispatch firewall rejection was stranded as uncertain.');
$gatewayApply = CloudFirewallService::apply(
$validationInstance, $validationActor, [
'enabled' => false, 'expected_revision' => 1,
'idempotency_key' => 'fw-request-gateway-auth-0001',
'rules' => [],
]
);
$gatewayJob = $gatewayApply['job'];
$gatewayHistory = [];
$gatewayStack = HandlerStack::create(new MockHandler([
new Response(403, [], json_encode(['error' => [
'code' => 'gateway_forbidden',
'message' => 'Agent gateway request is forbidden',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
]));
$gatewayStack->push(Middleware::history($gatewayHistory));
$gatewayAgent = new CloudAgentClient(
'1',
'test-secret-which-is-at-least-32-bytes',
new Client(['handler' => $gatewayStack]),
20.0,
'http://127.0.0.1:8001/internal/agent/request',
'test-gateway-secret-at-least-32-bytes'
);
(new CloudWorkerService($gatewayAgent))->tick();
$gatewayJob->refresh();
$gatewayPolicy = CloudFirewallService::listing(
$validationInstance, $validationActor
);
$assert(count($gatewayHistory) === 1
&& (string) $gatewayJob->status === 'failed'
&& $gatewayPolicy['sync_state'] === 'failed'
&& $gatewayPolicy['can_mutate'] === true
&& (string) CloudInstanceFirewallVersion::where(
'instance_id', (int) $validationInstance->id
)->where('revision', 2)->value('state') === 'failed',
'A pre-dispatch gateway rejection stranded firewall work as uncertain.');
echo "Cloud firewall desired/applied, idempotency and queue workflow passed.\n";
}

@ -19,6 +19,8 @@ $cases = [
[400, 'invalid_request', 422, false, 'Agent 拒绝了请求参数'],
[422, 'validation_failed', 422, false, 'Agent 拒绝了请求参数'],
[401, 'unauthorized', 502, false, 'Agent API 身份验证失败,请重新核对密钥'],
[403, 'forbidden', 403, false, 'Agent 拒绝了未授权的操作请求'],
[403, 'gateway_forbidden', 502, false, 'Agent 网关身份验证失败,请重新核对网关密钥'],
[404, 'vm_not_found', 404, false, 'Agent 上的目标资源不存在'],
[409, 'operation_conflict', 409, false, 'Agent 拒绝冲突或重复的操作请求'],
[501, 'not_implemented', 501, false, '当前 Agent 不支持此项功能'],

@ -21,17 +21,20 @@ $assert = static function ($condition, string $message): void {
};
$assert(str_contains($schema, "country_code CHAR(2) NOT NULL DEFAULT ''")
&& str_contains($schema,
"default_network VARCHAR(128) NOT NULL DEFAULT 'public'")
&& !preg_match('/\b(?:ALTER|DROP)\s+TABLE\b/i', $schema),
'Fresh cloud_hosts schema must contain the structured country code without upgrade DDL.');
'Fresh cloud_hosts schema must contain structured location and the public selector default without upgrade DDL.');
$assert(str_contains($controller, "'region', 'country_code'")
&& str_contains($controller,
"CloudCountryCatalog::normalize(\$body['country_code'] ?? null)")
&& !str_contains($controller, 'HOST_COUNTRY_CODES')
&& str_contains($controller, '$host->country_code = $countryCode;')
&& $hostWrite !== ''
&& !str_contains($hostWrite, 'CloudAgentSettingsService')
&& str_contains($hostWrite,
'CloudAgentSettingsService::invalidateForNetworkSelectorChange(')
&& !str_contains($hostWrite, '->request('),
'Host writes must validate and persist country_code without contacting the Agent.');
'Host writes must persist country_code and invalidate stale selector readiness without contacting the Agent.');
$assert(str_contains($catalog, "'CN' => ['name' => '中国'")
&& str_contains($catalog, "'HK' => ['name' => '中国香港'")
&& str_contains($catalog, "'JP' => ['name' => '日本'")
@ -56,6 +59,14 @@ $assert(str_contains($client, "'host-country-code': h.country_code || ''")
&& str_contains($client,
"country_code: byId('host-country-code').value"),
'Host editor must round-trip country_code through the admin API.');
$assert(str_contains($controller,
"preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', \$network)")
&& str_contains($controller, 'Agent network_selectors')
&& str_contains($client, "'host-network': h.default_network || 'public'")
&& str_contains($template, 'value="public"')
&& str_contains($template, 'Agent 网络选择器 key')
&& str_contains($template, '不能填写 <code>bridge:br0</code>'),
'Host network input must use the stable public Agent selector instead of a raw bridge name.');
$legacyPublicInputs = [
'host-public-pool', 'host-gateway', 'host-dns', 'host-reserved',
'host-vm-prefix',

@ -15,7 +15,9 @@ $assert = static function ($condition, string $message): void {
};
$assert(CloudInstanceMetadata::state('shutdown') === 'shutdown'
&& CloudInstanceRuntimeService::normalizeState('shutdown') === 'shutdown',
&& CloudInstanceRuntimeService::normalizeState('shutdown') === 'shutdown'
&& CloudInstanceMetadata::state('pmsuspended') === 'pmsuspended'
&& CloudInstanceRuntimeService::normalizeState('pmsuspended') === 'pmsuspended',
'Graceful shutdown was collapsed into an unknown or terminal state.');
$assert(CloudInstanceRuntimeService::stateAfterSuccessfulAction('running', 'shutdown')
=== 'shutdown'

@ -5,6 +5,8 @@ namespace {
use App\Services\Cloud\CloudMoney;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudOperationErrorCatalog;
use App\Services\Cloud\CloudAgentError;
use App\Services\Cloud\CloudAgentOperationReconciler;
use App\Services\Cloud\CloudWorkerService;
$assert = function ($condition, $message) { if (!$condition) { throw new RuntimeException($message); } };
$assert(CloudMoney::cents('9.99') + CloudMoney::cents('0.01') === 1000, 'Money arithmetic must be exact.');
@ -14,7 +16,20 @@ namespace {
}
$assert(CloudWorkerService::disposition(['status' => 'failed'], true) === 'uncertain', 'Unknown creation failure must not refund.');
$assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => false], true) === 'uncertain', 'Explicitly unsafe creation failure must not refund.');
$assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => true], true) === 'failed', 'Confirmed absent creation must refund.');
$assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => true], true) === 'uncertain', 'A legacy refund hint bypassed managed-artifact absence evidence.');
$assert(CloudWorkerService::disposition([
'status' => 'failed',
'result' => ['creation_absent' => true],
], true) === 'uncertain',
'Create failure without managed-artifact evidence was refundable.');
$assert(CloudWorkerService::disposition([
'status' => 'failed',
'result' => [
'creation_absent' => true,
'managed_artifacts_absent' => true,
],
], true) === 'failed',
'Confirmed create absence did not become a terminal failure.');
$assert(CloudWorkerService::disposition([
'status' => 'succeeded', 'error_code' => 'reinstall_cleanup_pending',
'result' => ['reinstall_committed' => true, 'cleanup_pending' => true],
@ -24,12 +39,47 @@ namespace {
'status' => 'succeeded', 'result' => ['vm' => ['state' => 'running']],
], false, 'reinstall') === 'succeeded',
'A normal reinstall was changed to uncertain.');
$assert(CloudWorkerService::disposition([
'status' => 'succeeded',
'result' => [
'reinstall_committed' => true,
'cleanup_pending' => false,
],
], false, 'reinstall') === 'succeeded',
'A clean Agent reinstall result was changed to uncertain.');
$assert(CloudWorkerService::disposition([
'status' => 'failed',
'error_code' => 'reinstall_cleanup_pending',
'result' => ['reinstall_committed' => true, 'cleanup_pending' => true],
], false, 'reinstall') === 'uncertain',
'A failed envelope with a committed reinstall marker was replayable.');
$uncertainOperation = [
'operation_id' => 'operation-reconcile-failure',
'status' => 'uncertain',
];
$failingReconcilerClient = new class {
public function request(): array
{
throw new CloudAgentError(
'reconcile unavailable', 503, 'agent_disconnected', true, 503
);
}
};
$assert(CloudAgentOperationReconciler::ifUncertain(
$failingReconcilerClient,
'operation-reconcile-failure',
['user_id' => 1],
$uncertainOperation
) === $uncertainOperation,
'A failed reconciliation request downgraded an uncertain operation.');
foreach (['delete', 'reinstall', 'instance_settings',
'network_change', 'firewall_apply'] as $uncertainKind) {
$assert(CloudWorkerService::disposition([
'status' => 'uncertain', 'safe_to_refund' => true,
], false, $uncertainKind) === 'uncertain',
'An ambiguous ' . $uncertainKind
. ' operation was converted to a terminal failure.');
}
foreach (['shortA1!', 'longwithoutupper1!', 'ALLUPPERCASE!123', 'LongWithoutSymbol123',
'NoDigitsLong!Aa', "StrongPassword!1\n", 'Strong Password!123',
'StrongPassword!123含中文', str_repeat('a', 126) . 'A1!'] as $bad) {

@ -8,6 +8,7 @@ namespace App\Services\Cloud {
public array $requests = [];
public array $operations = [];
public string $mode = 'running';
public ?array $reconcileResponse = null;
public $onRequest = null;
public function request(string $method, string $target, array $actor,
@ -27,6 +28,10 @@ namespace App\Services\Cloud {
'agent_busy', true, 503, false, true);
}
$this->operations[$operationId] = $templateId;
if ($this->mode === 'ambiguous_replay') {
throw new CloudAgentError('nonce may have dispatched', 502,
'replayed_request', false, 401);
}
if ($this->mode === 'transport') {
throw new CloudAgentError('transport uncertain', 502,
'agent_transport_error', true);
@ -44,6 +49,21 @@ namespace App\Services\Cloud {
throw new CloudAgentError('transport uncertain', 502,
'agent_transport_error', true);
}
} elseif ($method === 'POST'
&& preg_match(
'#^/v1/operations/([A-Za-z0-9_-]+)/reconcile$#D',
$target, $match)) {
$operationId = rawurldecode($match[1]);
$templateId = $this->operations[$operationId] ?? '';
if ($templateId === '') {
throw new CloudAgentError('operation missing', 404,
'operation_not_found', false, 404);
}
return ['operation_id' => $operationId]
+ ($this->reconcileResponse ?? [
'status' => 'uncertain',
'error' => ['code' => 'operation_uncertain'],
]);
} else {
throw new \RuntimeException('Unexpected fake Agent request: '
. $method . ' ' . $target);
@ -69,6 +89,13 @@ namespace App\Services\Cloud {
],
];
}
if ($this->mode === 'uncertain') {
return [
'operation_id' => $operationId,
'status' => 'uncertain',
'error' => ['code' => 'operation_uncertain'],
];
}
return ['operation_id' => $operationId, 'status' => 'running'];
}
}
@ -189,6 +216,28 @@ namespace {
&& $busyAgent->operations === [],
'Definitive pre-dispatch rescue import was left for impossible reconciliation.');
$replayedAgent = new RescueImportFakeAgent();
$replayedAgent->mode = 'ambiguous_replay';
CloudAgentSettingsService::$clients[14] = $replayedAgent;
$replayed = CloudRescueTemplateImportService::start(
14, 'remote', 'Replay ambiguous rescue',
'https://images.example.com/replay-ambiguous.iso', '', '', $actor
);
$replayedRow = CloudRescueTemplateImport::query()
->where('operation_id', (string) $replayed['operation_id'])->first();
$assert($replayed['status'] === 'running'
&& (string) $replayedRow->state === 'running'
&& (string) $replayedRow->error_code === 'replayed_request'
&& $requestCount($replayedAgent, 'POST') === 1,
'Ambiguous non-retryable rescue import was made terminal.');
$replayedAgent->mode = 'success';
$replayedCompleted = CloudRescueTemplateImportService::job(
14, (string) $replayed['operation_id'], $actor
);
$assert($replayedCompleted['status'] === 'succeeded'
&& $requestCount($replayedAgent, 'POST') === 1,
'Ambiguous rescue import was replayed instead of polled by operation ID.');
// Reconciliation uses the exact saved operation and terminal rows are
// read-only; no later call is allowed to issue another import POST.
$remoteAgent->mode = 'success';
@ -209,6 +258,72 @@ namespace {
. $remote['operation_id'],
'Rescue import reconciliation changed or replayed its operation.');
// GET uncertainty is resolved only through POST /reconcile for the same
// operation. The original rescue import POST remains single-shot.
$reconcileAgent = new RescueImportFakeAgent();
CloudAgentSettingsService::$clients[12] = $reconcileAgent;
$reconcileImport = CloudRescueTemplateImportService::start(
12, 'remote', 'Reconcile rescue',
'https://images.example.com/reconcile.iso', '', '', $actor
);
$reconcileAgent->mode = 'uncertain';
$reconcileAgent->reconcileResponse = [
'status' => 'succeeded',
'result' => [
'id' => (string) $reconcileImport['template_id'],
'name' => 'Reconcile rescue',
'size_bytes' => 1048576,
'sha256' => str_repeat('a', 64),
],
];
$beforeReconcilePoll = count($reconcileAgent->requests);
$reconcileCompleted = CloudRescueTemplateImportService::job(
12, (string) $reconcileImport['operation_id'], $actor
);
$reconcileRequests = array_slice(
$reconcileAgent->requests, $beforeReconcilePoll
);
$importPosts = array_filter($reconcileAgent->requests,
static fn (array $request): bool => $request['method'] === 'POST'
&& $request['target'] === '/v1/rescue-templates');
$assert($reconcileCompleted['status'] === 'succeeded'
&& count($importPosts) === 1
&& count($reconcileRequests) === 2
&& $reconcileRequests[0]['method'] === 'GET'
&& $reconcileRequests[0]['target'] === '/v1/operations/'
. $reconcileImport['operation_id']
&& $reconcileRequests[1]['method'] === 'POST'
&& $reconcileRequests[1]['target'] === '/v1/operations/'
. $reconcileImport['operation_id'] . '/reconcile',
'Rescue import uncertainty was replayed or reconciled under another operation.');
$trueUncertainAgent = new RescueImportFakeAgent();
CloudAgentSettingsService::$clients[13] = $trueUncertainAgent;
$trueUncertainImport = CloudRescueTemplateImportService::start(
13, 'remote', 'Uncertain rescue',
'https://images.example.com/uncertain.iso', '', '', $actor
);
$trueUncertainAgent->mode = 'uncertain';
$trueUncertainAgent->reconcileResponse = [
'status' => 'uncertain',
'error' => ['code' => 'operation_uncertain'],
];
$trueUncertain = CloudRescueTemplateImportService::job(
13, (string) $trueUncertainImport['operation_id'], $actor
);
$requestsAtUncertain = count($trueUncertainAgent->requests);
$trueUncertainAgain = CloudRescueTemplateImportService::job(
13, (string) $trueUncertainImport['operation_id'], $actor
);
$trueUncertainPosts = array_filter($trueUncertainAgent->requests,
static fn (array $request): bool => $request['method'] === 'POST'
&& $request['target'] === '/v1/rescue-templates');
$assert($trueUncertain['status'] === 'uncertain'
&& $trueUncertainAgain['status'] === 'uncertain'
&& count($trueUncertainPosts) === 1
&& count($trueUncertainAgent->requests) === $requestsAtUncertain,
'A genuinely uncertain rescue import was retried or left pollable.');
// A retryable transport failure may have crossed the boundary. Preserve
// the upload operation, then lock it uncertain if Agent has no record.
$uploadAgent = new RescueImportFakeAgent();
@ -289,9 +404,13 @@ namespace {
40, $staleOperation, $actor
);
$assert($stale['status'] === 'uncertain'
&& $stale['error_code'] === 'import_dispatch_unconfirmed'
&& $staleAgent->requests === [],
'Stale dispatch boundary caused an unsafe import replay.');
&& $stale['error_code'] === 'operation_not_found'
&& count($staleAgent->requests) === 1
&& $staleAgent->requests[0]['method'] === 'GET'
&& $staleAgent->requests[0]['target']
=== '/v1/operations/' . $staleOperation
&& $requestCount($staleAgent, 'POST') === 0,
'Stale sending boundary was not checked by operation ID without replay.');
// A response produced from a stale concurrent poll must not overwrite a
// terminal state committed while that request was in flight.

@ -80,7 +80,7 @@ try {
'Expired policy observations must request investigation without claiming a live process.');
$now += 700;
$assert($checks($directory)['worker']['status'] === 'busy',
'A normal 900-second Agent call was incorrectly declared stopped.');
'A normal long PHP-to-Agent request was incorrectly declared stopped.');
$normal->busy('notification');
$now += 300;
$assert(str_contains($checks($directory)['worker']['message'], '邮件通知'),

@ -32,7 +32,7 @@ $assert(is_string($catalog)
&& str_contains($catalog, 'public static function deleteJob(')
&& str_contains($catalog, "->where('state', 'delete_dispatch')")
&& str_contains($catalog, "'state' => 'delete_sending'")
&& str_contains($catalog, "->whereIn('state', ['delete_dispatch', 'delete_sending'])")
&& str_contains($catalog, "->where('state', 'delete_sending')")
&& str_contains($catalog, "'error_code' => 'delete_dispatch_unconfirmed'")
&& str_contains($catalog, "->where('state', 'delete_running')")
&& str_contains($catalog, 'CloudAgentCatalogDeletion::confirms(')

@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
namespace App\Services\Cloud {
final class TemplateMetadataSyncFakeAgent
{
public array $requests = [];
public string $mode = 'success';
/** @var null|callable */
public $beforeResponse = null;
public function request(string $method, string $target, array $actor,
?array $payload = null): array
{
$this->requests[] = compact('method', 'target', 'actor', 'payload');
if (is_callable($this->beforeResponse)) {
($this->beforeResponse)($method, $target, $actor, $payload);
}
$operationId = (string) ($payload['operation_id']
?? $actor['operation_id'] ?? basename($target));
if ($method === 'POST') {
return ['operation_id' => basename(dirname($target)),
'status' => 'succeeded', 'result' => $this->result];
}
if ($this->mode === 'wrong_operation') {
$operationId = 'wrong-operation-id';
}
return [
'operation_id' => $operationId,
'status' => $this->mode === 'uncertain'
? 'uncertain' : 'succeeded',
'result' => $this->result,
];
}
public array $result = [];
}
final class CloudAgentSettingsService
{
public static ?TemplateMetadataSyncFakeAgent $client = null;
public static function clientForHost(int $hostId,
float $timeoutSeconds = 20.0): TemplateMetadataSyncFakeAgent
{
if ($hostId !== 7 || self::$client === null) {
throw new \RuntimeException('Missing fake Agent');
}
return self::$client;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudTemplateReplica;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudTemplateCatalogService;
use App\Services\Cloud\TemplateMetadataSyncFakeAgent;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'],
'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('cloud_template_replicas',
static function (Blueprint $table): void {
$table->integer('host_id');
$table->string('template_id');
$table->integer('revision');
$table->string('generation_token');
$table->string('state');
$table->integer('image_bytes')->default(0);
$table->string('sha256')->default('');
$table->string('operation_id')->default('');
$table->string('error_code')->default('');
$table->integer('created_at');
$table->integer('updated_at');
$table->primary(['host_id', 'template_id']);
});
$generation = str_repeat('a', 32);
$id = 'debian-13-metadata-sync';
$now = time();
Capsule::table('cloud_template_replicas')->insert([
'host_id' => 7,
'template_id' => $id,
'revision' => 1,
'generation_token' => $generation,
'state' => 'active',
'image_bytes' => 4096,
'sha256' => str_repeat('b', 64),
'operation_id' => bin2hex(random_bytes(16)),
'error_code' => '',
'created_at' => $now,
'updated_at' => $now,
]);
$snapshot = static fn (int $revision, string $name): array => [
'id' => $id,
'name' => $name,
'revision' => $revision,
'generation_token' => $generation,
];
$result = static fn (int $revision, string $name): array => [
'id' => $id,
'name' => $name,
'revision' => $revision,
'generation_token' => $generation,
];
$actor = ['user_id' => 1, 'can_manage' => true];
$agent = new TemplateMetadataSyncFakeAgent();
CloudAgentSettingsService::$client = $agent;
$agent->result = $result(2, 'Debian 13 renamed');
$synced = CloudTemplateCatalogService::synchronizeMetadata(
$snapshot(2, 'Debian 13 renamed'), $actor
);
$row = CloudTemplateReplica::query()->where('host_id', 7)
->where('template_id', $id)->first();
$operationId = (string) $row->operation_id;
$assert($synced['replication_pending'] === false
&& (int) $row->revision === 2
&& (string) $row->state === 'active'
&& ($agent->requests[0]['actor']['operation_id'] ?? null)
=== $operationId
&& ($agent->requests[0]['payload']['operation_id'] ?? null)
=== $operationId,
'Metadata synchronization did not bind success to its operation ID.');
$agent->mode = 'wrong_operation';
$agent->result = $result(3, 'Debian 13 wrong operation');
$mismatch = CloudTemplateCatalogService::synchronizeMetadata(
$snapshot(3, 'Debian 13 wrong operation'), $actor
);
$row->refresh();
$assert($mismatch['replication_pending'] === true
&& (int) $row->revision === 2
&& (string) $row->state === 'stale'
&& (string) $row->error_code === 'agent_sync_failed',
'Mismatched metadata operation was accepted as a successful replica.');
// A later revision may commit while an older request is still in flight.
// Neither its late failure nor late success may regress that newer row.
$agent->beforeResponse = static function () use ($id, $generation): void {
Capsule::table('cloud_template_replicas')->where('host_id', 7)
->where('template_id', $id)->update([
'revision' => 5,
'generation_token' => $generation,
'state' => 'active',
'operation_id' => 'newer-operation-id',
'error_code' => '',
'updated_at' => time(),
]);
};
$agent->result = $result(4, 'Debian 13 older response');
CloudTemplateCatalogService::synchronizeMetadata(
$snapshot(4, 'Debian 13 older response'), $actor
);
$row->refresh();
$assert((int) $row->revision === 5
&& (string) $row->state === 'active'
&& (string) $row->operation_id === 'newer-operation-id',
'Late metadata failure regressed a newer replica revision.');
$agent->mode = 'uncertain';
$agent->beforeResponse = null;
$agent->result = $result(6, 'Debian 13 reconciled');
$before = count($agent->requests);
$reconciled = CloudTemplateCatalogService::synchronizeMetadata(
$snapshot(6, 'Debian 13 reconciled'), $actor
);
$requests = array_slice($agent->requests, $before);
$row->refresh();
$assert($reconciled['replication_pending'] === false
&& (int) $row->revision === 6
&& count($requests) === 2
&& $requests[0]['method'] === 'PATCH'
&& $requests[1]['method'] === 'POST'
&& str_ends_with($requests[1]['target'], '/reconcile'),
'Uncertain metadata synchronization was replayed or not reconciled.');
echo "Template metadata operation binding and CAS tests passed.\n";
}

@ -148,7 +148,7 @@ namespace {
$instance->created_at = $instance->updated_at = $now;
$instance->save();
$metrics = static function (int $timestamp, int $cpu, int $memory,
$metrics = static function (int $timestamp, int $cpu, ?int $memory,
int $read, int $write, int $rx, int $tx) use ($uuid): array {
return [
'uuid' => $uuid,
@ -167,6 +167,10 @@ namespace {
106_000, 53_000, 112_000, 56_000);
$resetMetrics = $metrics($resetAt, 100_000_000, 524_288,
100, 50, 1_000, 500);
$unavailableMemoryAt = $resetAt + 1;
$unavailableMemoryMetrics = $metrics(
$unavailableMemoryAt, 100_000_000, null, 100, 50, 1_000, 500
);
$log = $capsule->connection('log');
$log->table('cloud_vm_metric_samples')->insert([
@ -256,14 +260,62 @@ namespace {
&& $resetSample->network_tx_bps === null,
'Raw Agent counter reset lowered PHP billing totals or emitted a false rate spike.');
$store->invoke(null, $log, $instance, $unavailableMemoryMetrics);
$unavailableMemorySample = $log->table('cloud_vm_metric_samples')
->where('sampled_at', $unavailableMemoryAt)->first();
$total = $log->table('cloud_vm_traffic_totals')->first();
$assert($unavailableMemorySample !== null
&& $unavailableMemorySample->memory_used_mib === null
&& (int) $total->download_rx_bytes === 113_000
&& (int) $total->upload_tx_bytes === 56_500,
'Unavailable balloon statistics fabricated memory usage or disrupted traffic totals.');
$duplicate = $metrics($resetAt, 999_000_000, 999_999,
999_999, 999_999, 999_999, 999_999);
999_999, 999_999, 1_000, 500);
$store->invoke(null, $log, $instance, $duplicate);
$total = $log->table('cloud_vm_traffic_totals')->first();
$assert((int) $total->download_rx_bytes === 113_000
&& (int) $total->upload_tx_bytes === 56_500
&& $log->table('cloud_vm_metric_samples')->count() === 3,
'Duplicate or older collected_at data overwrote the durable totals.');
&& $log->table('cloud_vm_metric_samples')->count() === 4,
'A repeated durable Agent counter was charged twice.');
$futureObservedAt = $now + 120;
$log->table('cloud_vm_traffic_totals')->update([
'last_observed_at' => $futureObservedAt,
]);
$rollbackMetrics = $metrics($now, 1_000_000_000, 786_432,
1_000, 500, 1_500, 700);
$rollbackHistory = [];
$rollbackMock = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'],
json_encode($rollbackMetrics, JSON_THROW_ON_ERROR)),
new Response(200, ['Content-Type' => 'application/json'],
json_encode($rollbackMetrics, JSON_THROW_ON_ERROR)),
]);
$rollbackStack = HandlerStack::create($rollbackMock);
$rollbackStack->push(Middleware::history($rollbackHistory));
$rollbackAgent = new CloudAgentClient('7',
'metric-test-secret-at-least-32-bytes', new Client([
'handler' => $rollbackStack, 'http_errors' => false,
]), 20.0, 'http://127.0.0.1:8001/internal/agent/request',
'test-gateway-secret-at-least-32-bytes');
$rollbackFirst = CloudTrafficService::collect(1, $rollbackAgent);
$rollbackSecond = CloudTrafficService::collect(1, $rollbackAgent);
$total = $log->table('cloud_vm_traffic_totals')->first();
$rollbackBaseline = json_decode(
(string) $total->network_baseline_json, true,
flags: JSON_THROW_ON_ERROR
);
$assert($rollbackFirst['observed'] === 1
&& $rollbackSecond['observed'] === 1
&& count($rollbackHistory) === 2
&& (int) $total->download_rx_bytes === 113_500
&& (int) $total->upload_tx_bytes === 56_700
&& (int) $total->last_observed_at === $futureObservedAt
&& ($rollbackBaseline['last_agent_rx_bytes'] ?? null) === 1_500
&& ($rollbackBaseline['last_agent_tx_bytes'] ?? null) === 700
&& $log->table('cloud_vm_metric_samples')->count() === 4,
'A future observation blocked clock-rollback collection, duplicated billing, or inserted an out-of-order chart point.');
$wrongUuid = $resetMetrics;
$wrongUuid['uuid'] = '22222222-2222-4222-8222-222222222222';
@ -272,7 +324,7 @@ namespace {
), 502, 'Metrics for another VM UUID were accepted.');
$log->table('cloud_vm_traffic_totals')->update(['user_id' => 18]);
$newer = $resetMetrics;
$newer['collected_at'] = gmdate('Y-m-d\TH:i:s\Z', $resetAt + 1);
$newer['collected_at'] = gmdate('Y-m-d\TH:i:s\Z', $resetAt + 2);
$expect(static fn () => $store->invoke(
null, $log, $instance, $newer
), 409, 'A traffic total owned by another user was overwritten.');
@ -299,8 +351,8 @@ namespace {
$instance->traffic_synced_at = 0;
$instance->save();
$assert(CloudTrafficService::sync(10) === 1
&& (int) $instance->fresh()->lifetime_download_bytes === 113_000
&& (int) $instance->fresh()->lifetime_upload_bytes === 56_500,
&& (int) $instance->fresh()->lifetime_download_bytes === 113_500
&& (int) $instance->fresh()->lifetime_upload_bytes === 56_700,
'Owner/host/UUID-bound PHP totals were not synchronized to billing state.');
$log->table('cloud_vm_metric_samples')->insert([

@ -67,10 +67,10 @@ $assert(str_contains($service, 'final class CloudUserIsoService')
&& str_contains($service, 'CloudAgentSettingsService::enabledHostIds()')
&& str_contains($service, "->request('POST', '/v1/user-isos'")
&& str_contains($service, "->request('GET', '/v1/operations/'")
&& str_contains($service, "->request('DELETE', '/v1/user-isos/'")
&& str_contains($service, "'DELETE', '/v1/user-isos/'")
&& str_contains($service, "->where('state', 'delete_dispatch')")
&& str_contains($service, "'state' => 'delete_sending'")
&& str_contains($service, "->whereIn('state', ['delete_dispatch', 'delete_sending'])")
&& str_contains($service, "->where('state', 'delete_sending')")
&& str_contains($service, "'error_code' => 'delete_dispatch_unconfirmed'")
&& str_contains($service, "->where('state', 'delete_running')")
&& str_contains($service, "CloudAgentCatalogDeletion::confirms(")

Loading…
Cancel
Save