diff --git a/internal/api/action_executor.go b/internal/api/action_executor.go index 196004f104..ef2f0d9304 100644 --- a/internal/api/action_executor.go +++ b/internal/api/action_executor.go @@ -174,24 +174,32 @@ type agentLookupResult struct { version int } -type agentLookupMemo map[agentLookupKey]agentLookupResult +type agentLookupMemo struct { + answers map[agentLookupKey]agentLookupResult + dockerInventories map[dockerReadinessInventoryKey]*dockerReadinessInventory +} type agentLookupMemoContextKey struct{} func withAgentLookupMemo(ctx context.Context) context.Context { - return context.WithValue(ctx, agentLookupMemoContextKey{}, agentLookupMemo{}) + return context.WithValue(ctx, agentLookupMemoContextKey{}, &agentLookupMemo{answers: make(map[agentLookupKey]agentLookupResult)}) +} + +func agentLookupMemoForContext(ctx context.Context) *agentLookupMemo { + memo, _ := ctx.Value(agentLookupMemoContextKey{}).(*agentLookupMemo) + return memo } func memoizedAgentLookup(ctx context.Context, key agentLookupKey, lookup func() agentLookupResult) agentLookupResult { - memo, _ := ctx.Value(agentLookupMemoContextKey{}).(agentLookupMemo) + memo := agentLookupMemoForContext(ctx) if memo == nil { return lookup() } - if result, ok := memo[key]; ok { + if result, ok := memo.answers[key]; ok { return result } result := lookup() - memo[key] = result + memo.answers[key] = result return result } diff --git a/internal/api/docker_container_action_executor.go b/internal/api/docker_container_action_executor.go index b5f53a4d49..8062536438 100644 --- a/internal/api/docker_container_action_executor.go +++ b/internal/api/docker_container_action_executor.go @@ -612,11 +612,8 @@ func (e dockerContainerActionExecutor) dockerReportTokenReachesCommandSession(ct // agent's ID itself, so the row is its own record of which token reports for // that machine. func (e dockerContainerActionExecutor) hostAgentReportsUnderToken(ctx context.Context, tokenID, agentID, hostname string) bool { - if e.resources == nil { - return false - } - registry, err := e.resources.buildRegistry(GetOrgID(ctx)) - if err != nil { + registry, _ := e.dockerReadinessRegistry(ctx) + if registry == nil { return false } for _, host := range registry.Hosts() { @@ -635,32 +632,20 @@ func (e dockerContainerActionExecutor) hostAgentReportsUnderToken(ctx context.Co // same token must not borrow the real host's session to act on containers // outside the operator lock on the real container resource. func (e dockerContainerActionExecutor) dockerTokenHasAmbiguousHosts(ctx context.Context, tokenID, agentID string, singleTokenSession bool) bool { - if e.resources == nil || tokenID == "" { + if tokenID == "" { return false } - registry, err := e.resources.buildRegistry(GetOrgID(ctx)) - if err != nil { + registry, batch := e.dockerReadinessRegistry(ctx) + if registry == nil { return false } - hostsForToken := make(map[string]struct{}) - hostsForAgent := make(map[string]struct{}) - for _, res := range registry.List() { - if res.Docker == nil || strings.TrimSpace(res.Docker.TokenID) != tokenID { - continue - } - hostSourceID := strings.TrimSpace(res.Docker.HostSourceID) - if hostSourceID == "" { - continue - } - hostsForToken[hostSourceID] = struct{}{} - if agentID != "" && strings.TrimSpace(res.Docker.AgentID) == agentID { - hostsForAgent[hostSourceID] = struct{}{} - } + if batch == nil { + return indexDockerReportHosts(registry.List(), tokenID).ambiguous(tokenID, agentID, singleTokenSession) } - if len(hostsForAgent) > 1 { - return true + if batch.reportHosts == nil { + batch.reportHosts = indexDockerReportHosts(registry.List(), "") } - return singleTokenSession && len(hostsForToken) > 1 + return batch.reportHosts.ambiguous(tokenID, agentID, singleTokenSession) } // agentLookupHostCommandsDisabled memoizes one host's answer for a pass. It sits @@ -680,8 +665,8 @@ func (e dockerContainerActionExecutor) dockerHostCommandsDisabled(ctx context.Co return false } return memoizedAgentLookup(ctx, agentLookupKey{kind: agentLookupHostCommandsDisabled, first: hostID}, func() agentLookupResult { - registry, err := e.resources.buildRegistry(GetOrgID(ctx)) - if err != nil { + registry, _ := e.dockerReadinessRegistry(ctx) + if registry == nil { return agentLookupResult{} } host, ok := registry.Get(hostID) diff --git a/internal/api/docker_readiness_inventory.go b/internal/api/docker_readiness_inventory.go new file mode 100644 index 0000000000..085d4f9192 --- /dev/null +++ b/internal/api/docker_readiness_inventory.go @@ -0,0 +1,97 @@ +package api + +import ( + "context" + "strings" + + unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources" +) + +type dockerReadinessInventoryKey struct { + resources *ResourceHandlers + orgID string +} + +type dockerReadinessInventory struct { + registry *unified.ResourceRegistry + reportHosts dockerReportHostIndex +} + +// Only the read-only availability projection supplies a memo. Planning, +// preflight, and dispatch use the current registry on every check as before. +func (e dockerContainerActionExecutor) dockerReadinessRegistry(ctx context.Context) (*unified.ResourceRegistry, *dockerReadinessInventory) { + if e.resources == nil { + return nil, nil + } + key := dockerReadinessInventoryKey{resources: e.resources, orgID: GetOrgID(ctx)} + memo := agentLookupMemoForContext(ctx) + if memo != nil { + if inventory := memo.dockerInventories[key]; inventory != nil { + return inventory.registry, inventory + } + } + registry, err := e.resources.buildRegistry(key.orgID) + if err != nil { + return nil, nil // Do not freeze a failed lookup for the rest of the pass. + } + if memo == nil { + return registry, nil + } + if memo.dockerInventories == nil { + memo.dockerInventories = make(map[dockerReadinessInventoryKey]*dockerReadinessInventory) + } + inventory := &dockerReadinessInventory{registry: registry} + memo.dockerInventories[key] = inventory + return registry, inventory +} + +type dockerReportHostKey struct { + tokenID string + agentID string // Empty for the token-wide entry. +} + +// Readiness needs to know only whether a second distinct host was observed, +// not how many rows (including containers) reported for each host. +type dockerReportHostCount struct { + first string + multiple bool +} + +type dockerReportHostIndex map[dockerReportHostKey]dockerReportHostCount + +func (index dockerReportHostIndex) add(key dockerReportHostKey, host string) { + entry := index[key] + if entry.first == "" { + entry.first = host + } else if entry.first != host { + entry.multiple = true + } + index[key] = entry +} + +// Build from the canonical tenant registry, not from the filtered or +// coalesced rows being presented. Rows outside the projection still count. +func indexDockerReportHosts(resources []unified.Resource, onlyToken string) dockerReportHostIndex { + index := make(dockerReportHostIndex) + for i := range resources { + docker := resources[i].Docker + if docker == nil { + continue + } + tokenID := strings.TrimSpace(docker.TokenID) + hostID := strings.TrimSpace(docker.HostSourceID) + if tokenID == "" || hostID == "" || (onlyToken != "" && tokenID != onlyToken) { + continue + } + index.add(dockerReportHostKey{tokenID: tokenID}, hostID) + if agentID := strings.TrimSpace(docker.AgentID); agentID != "" { + index.add(dockerReportHostKey{tokenID: tokenID, agentID: agentID}, hostID) + } + } + return index +} + +func (index dockerReportHostIndex) ambiguous(tokenID, agentID string, singleTokenSession bool) bool { + return (agentID != "" && index[dockerReportHostKey{tokenID: tokenID, agentID: agentID}].multiple) || + (singleTokenSession && index[dockerReportHostKey{tokenID: tokenID}].multiple) +} diff --git a/internal/api/docker_readiness_inventory_test.go b/internal/api/docker_readiness_inventory_test.go new file mode 100644 index 0000000000..33d3e59f40 --- /dev/null +++ b/internal/api/docker_readiness_inventory_test.go @@ -0,0 +1,149 @@ +package api + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/rcourtman/pulse-go-rewrite/internal/config" + "github.com/rcourtman/pulse-go-rewrite/internal/models" + unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources" +) + +func TestDockerReportHostIndexKeepsTokenAndAgentScopes(t *testing.T) { + rows := []unified.Resource{ + {Docker: &unified.DockerData{TokenID: " shared ", AgentID: " agent-a ", HostSourceID: " host-a "}}, + {Docker: &unified.DockerData{TokenID: "shared", AgentID: "agent-a", HostSourceID: "host-a"}}, // Another row on the same host. + {Docker: &unified.DockerData{TokenID: "shared", AgentID: "agent-a", HostSourceID: " "}}, + {Docker: &unified.DockerData{TokenID: "shared", AgentID: "agent-b", HostSourceID: "host-b"}}, + {Docker: &unified.DockerData{TokenID: " shared ", AgentID: "agent-b", HostSourceID: "host-c"}}, + {Docker: &unified.DockerData{TokenID: "different", AgentID: "agent-a", HostSourceID: "host-d"}}, + {Docker: &unified.DockerData{TokenID: "shared", HostSourceID: "host-e"}}, + {Docker: &unified.DockerData{TokenID: "no-agent", HostSourceID: "host-a"}}, + {Docker: &unified.DockerData{TokenID: "no-agent", HostSourceID: "host-b"}}, + {}, + } + batch := indexDockerReportHosts(rows, "") + for _, tt := range []struct { + token, agent string + singleSession, want bool + }{ + {"shared", "agent-a", false, false}, + {"shared", "agent-a", true, true}, + {"shared", "agent-b", false, true}, + {"different", "agent-a", true, false}, + {"no-agent", "", false, false}, + {"no-agent", "", true, true}, + {"absent", "agent-a", true, false}, + } { + if got := batch.ambiguous(tt.token, tt.agent, tt.singleSession); got != tt.want { + t.Errorf("batch(%q, %q, %t) = %t, want %t", tt.token, tt.agent, tt.singleSession, got, tt.want) + } + direct := indexDockerReportHosts(rows, tt.token) + if got := direct.ambiguous(tt.token, tt.agent, tt.singleSession); got != tt.want { + t.Errorf("direct(%q, %q, %t) = %t, want %t", tt.token, tt.agent, tt.singleSession, got, tt.want) + } + } +} + +type countingDockerReadinessSeeds struct { + seeds map[string]resourceUnifiedSeedProvider + reads map[string]int +} + +func (p *countingDockerReadinessSeeds) ReadSnapshot() models.StateSnapshot { + return p.seeds["default"].snapshot +} + +func (p *countingDockerReadinessSeeds) UnifiedResourceSnapshot() ([]unified.Resource, time.Time) { + return p.UnifiedResourceSnapshotForTenant("default") +} + +func (p *countingDockerReadinessSeeds) UnifiedReadStateForTenant(orgID string) unified.ReadState { + return SnapshotReadState(p.seeds[orgID].snapshot) +} + +func (p *countingDockerReadinessSeeds) UnifiedResourceSnapshotForTenant(orgID string) ([]unified.Resource, time.Time) { + p.reads[orgID]++ + return p.seeds[orgID].UnifiedResourceSnapshot() +} + +func TestDockerReadinessUsesOneTenantInventoryPerPassAndFreshDispatch(t *testing.T) { + now := time.Now().UTC() + rows := []unified.Resource{ + dockerContainerActionResource("app-container:web", "docker", "running", now), + dockerContainerActionResource("app-container:worker", "docker", "running", now), + } + for i := range rows { + rows[i].Docker.TokenID = "shared" + rows[i].Docker.HostSourceID = "primary-host" + rows[i].Docker.Hostname = "primary" + } + otherHost := unified.Resource{ + ID: "docker-host:other", Name: "Other host", Type: unified.ResourceTypeAgent, + LastSeen: now, Sources: []unified.DataSource{unified.SourceDocker}, + Docker: &unified.DockerData{TokenID: "shared", AgentID: "agent-2", HostSourceID: "other-host"}, + } + twoHosts := append(append([]unified.Resource(nil), rows...), otherHost) + seeds := &countingDockerReadinessSeeds{ + seeds: map[string]resourceUnifiedSeedProvider{ + "default": {snapshot: models.StateSnapshot{LastUpdate: now}, resources: rows}, + "other": {snapshot: models.StateSnapshot{LastUpdate: now}, resources: twoHosts}, + }, + reads: make(map[string]int), + } + h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()}) + t.Cleanup(func() { _ = h.CloseStores() }) + h.SetStateProvider(seeds) + h.SetTenantStateProvider(seeds) + agents := &scopedFakeDockerActionAgentCommander{ + fakeDockerActionAgentCommander: &fakeDockerActionAgentCommander{connected: map[string]bool{"agent-1": true}}, + tokenAgents: map[string]string{"shared": "agent-1"}, + } + executor := newDockerContainerActionExecutor(h, agents).(dockerContainerActionExecutor) + h.SetActionExecutor(newRoutedActionExecutor(h, executor)) + + checkPass := func(orgID string, wantRefusal bool) { + t.Helper() + work := append([]unified.Resource(nil), rows...) + readsBefore := seeds.reads[orgID] + h.AttachBroadcastActionRefusals(orgID, work) + for _, row := range work { + readiness, refused := dockerActionReadinessByName(row.ActionReadiness, "restart") + if refused != wantRefusal || (refused && (readiness.Available || readiness.ReasonCode != "command_agent_disconnected")) { + t.Fatalf("%s: readiness for %s = %#v, want refusal %t", orgID, row.ID, row.ActionReadiness, wantRefusal) + } + if len(row.Capabilities) != 1 || row.Capabilities[0].Name != "restart" { + t.Fatalf("broadcast changed advertised capability: %#v", row.Capabilities) + } + } + if got := seeds.reads[orgID] - readsBefore; got != 1 { + t.Fatalf("%s: registry source read %d times in one pass, want 1", orgID, got) + } + } + checkPass("default", false) + checkPass("other", true) // The second host is not in the projected rows. + checkPass("default", false) + + record := dockerContainerActionRecord("fixture-action", rows[0].ID, "restart") + dockerActionDispatchContext(t, executor, record) // Binding works before the inventory changes. + seeds.seeds["default"] = resourceUnifiedSeedProvider{ + snapshot: models.StateSnapshot{LastUpdate: now.Add(time.Second)}, resources: twoHosts, + } + // Do not perform a new display pass before dispatch: an earlier ready row + // must not let a pending action reuse the old registry or agent answer. + attempt, err := unified.NewActionDispatchAttempt(record.ID, time.Now()) + if err != nil { + t.Fatal(err) + } + _, err = executor.BindActionDispatch(context.Background(), record, attempt) + if err == nil || !strings.Contains(err.Error(), "is reporting multiple Docker hosts") { + t.Fatalf("dispatch binding after inventory changed = %v, want ambiguity refusal", err) + } + checkPass("default", true) + seeds.seeds["default"] = resourceUnifiedSeedProvider{ + snapshot: models.StateSnapshot{LastUpdate: now.Add(2 * time.Second)}, resources: rows, + } + checkPass("default", false) +}