Files
Pulse/internal/api/availability_docker_suggestions_handlers_test.go
T
pulse-triage[bot] ea842411b4 Bind new Docker checks to the exact reviewed container endpoint
Require nonempty explicit creation selections and revalidate the complete host, container and published endpoint before probing and against fresh inventory before saving. Return a no-write conflict when the offer changed, and reject malformed or cross-host selections before probing. Preserve saved source keys, reattachment, tenant persistence and outbound policy. Adapt the retained withdrawn repair to current main and document its exact request contract.

Change-source: pulse-maintainer
2026-11-16 00:54:09 +00:00

615 lines
29 KiB
Go

package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/availabilityprobe"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
)
// dockerPortProbeScript answers probes by "protocol port", so a test states
// what each published port does without opening sockets.
type dockerPortProbeScript struct {
mu sync.Mutex
answers map[string]error
calls []string
// duringProbes runs once, on the first probe, to stand in for an
// operator changing checks while the request is still probing.
duringProbes func()
}
func (s *dockerPortProbeScript) probe(_ context.Context, target config.AvailabilityTarget) (availabilityprobe.ProbeResult, error) {
key := fmt.Sprintf("%s %s:%d", target.Protocol, target.Address, target.Port)
s.mu.Lock()
s.calls = append(s.calls, key)
err, known := s.answers[key]
hook := s.duringProbes
s.duringProbes = nil
s.mu.Unlock()
if hook != nil {
hook()
}
if !known {
err = errors.New("connection refused")
}
if err != nil {
result := availabilityprobe.ProbeResult{Outcome: availabilityprobe.OutcomeUnreachable, TransportOutcome: availabilityprobe.OutcomeUnreachable}
if strings.HasPrefix(err.Error(), "http probe returned status") {
result.TransportOutcome = availabilityprobe.OutcomeReachable
}
return result, err
}
return availabilityprobe.ProbeResult{Outcome: availabilityprobe.OutcomeReachable, TransportOutcome: availabilityprobe.OutcomeReachable}, nil
}
func dockerPortSuggestionHandlers(t *testing.T, script *dockerPortProbeScript) (*AvailabilityHandlers, *config.ConfigPersistence) {
t.Helper()
persistence := config.NewConfigPersistence(t.TempDir())
host := models.DockerHost{
ID: "host-1",
Hostname: "docker-vm",
NetworkInterfaces: []models.HostNetworkInterface{
{Name: "eth0", Addresses: []string{"192.168.1.20/24"}},
},
Containers: []models.DockerContainer{
{ID: "c-web", Name: "web", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 80, PublicPort: 8081, Protocol: "tcp", IP: "0.0.0.0"}}},
{ID: "c-tls", Name: "secure", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 443, PublicPort: 8443, Protocol: "tcp", IP: "0.0.0.0"}}},
{ID: "c-cache", Name: "cache", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 6379, PublicPort: 6379, Protocol: "tcp", IP: "0.0.0.0"}}},
{ID: "c-raw", Name: "raw", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 9999, PublicPort: 9999, Protocol: "tcp", IP: "0.0.0.0"}}},
{ID: "c-sick", Name: "sick", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 3000, PublicPort: 3000, Protocol: "tcp", IP: "0.0.0.0"}}},
{ID: "c-dead", Name: "dead", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 80, PublicPort: 8082, Protocol: "tcp", IP: "0.0.0.0"}}},
{ID: "c-local", Name: "local", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 80, PublicPort: 8083, Protocol: "tcp", IP: "127.0.0.1"}}},
},
}
handler := NewAvailabilityHandlers(
func(context.Context) *config.ConfigPersistence { return persistence },
func(context.Context) *monitoring.Monitor { return nil },
nil,
)
handler.dockerHosts = func(context.Context) []models.DockerHost { return []models.DockerHost{host} }
handler.dockerContainerResources = func(context.Context) map[string]string {
return map[string]string{dockerContainerResourceKey("host-1", "c-web"): "res-web"}
}
handler.dockerPortProbe = script.probe
return handler, persistence
}
// Submit the actual listing, as the browser does, instead of reconstructing a
// name-based identity that could silently select a different endpoint.
func dockerPortSelectionBody(t *testing.T, handler *AvailabilityHandlers, names ...string) string {
t.Helper()
rec := httptest.NewRecorder()
handler.HandleDockerPortSuggestions(rec, httptest.NewRequest(http.MethodGet, "/api/availability-targets/docker-suggestions", nil))
if rec.Code != http.StatusOK {
t.Fatalf("list status = %d: %s", rec.Code, rec.Body.String())
}
var payload dockerPortSuggestionsResponse
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
var selected []monitoring.DockerPortCheckCandidate
for _, candidate := range payload.Suggestions {
if len(names) == 0 {
selected = append(selected, candidate)
continue
}
for _, name := range names {
if candidate.ContainerName == name {
selected = append(selected, candidate)
}
}
}
body, err := json.Marshal(map[string]any{"ports": selected})
if err != nil {
t.Fatal(err)
}
return string(body)
}
func TestDockerPortSuggestionsListWhatHasNoCheck(t *testing.T) {
handler, _ := dockerPortSuggestionHandlers(t, &dockerPortProbeScript{})
rec := httptest.NewRecorder()
handler.HandleDockerPortSuggestions(rec, httptest.NewRequest(http.MethodGet, "/api/availability-targets/docker-suggestions", nil))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
var payload dockerPortSuggestionsResponse
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode: %v", err)
}
if len(payload.Suggestions) != 7 {
t.Fatalf("suggestions = %d, want all 7 published ports: %s", len(payload.Suggestions), rec.Body.String())
}
for _, suggestion := range payload.Suggestions {
if suggestion.ContainerName == "local" {
if suggestion.SkipReason != monitoring.DockerPortSkipLoopbackOnly || suggestion.Address != "" {
t.Fatalf("loopback-only port = %+v", suggestion)
}
} else if suggestion.ContainerName == "cache" {
if suggestion.SkipReason != monitoring.DockerPortSkipNotHTTP {
t.Fatalf("Redis port = %+v, want it marked as not a web port", suggestion)
}
} else if suggestion.Address != "192.168.1.20" || suggestion.SkipReason != "" {
t.Fatalf("suggestion = %+v, want the host's LAN address", suggestion)
}
}
}
func TestApplyDockerPortSuggestionsAddsOnlyWhatAnswers(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{
"tcp 192.168.1.20:8081": nil,
"http 192.168.1.20:8081": nil,
"tcp 192.168.1.20:8443": nil,
"https 192.168.1.20:8443": nil,
"tcp 192.168.1.20:6379": nil,
"tcp 192.168.1.20:9999": nil,
"tcp 192.168.1.20:3000": nil,
"http 192.168.1.20:3000": errors.New("http probe returned status 503"),
}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(dockerPortSelectionBody(t, handler))))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
var payload dockerPortApplyResponse
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode: %v", err)
}
saved, err := persistence.LoadAvailabilityTargets()
if err != nil {
t.Fatalf("LoadAvailabilityTargets() error = %v", err)
}
protocols := map[string]config.AvailabilityProbeProtocol{}
for _, target := range saved {
protocols[target.Name] = target.Protocol
if target.DockerPort == nil || target.DockerPort.HostID != "host-1" {
t.Errorf("%s saved without its source: %+v", target.Name, target.DockerPort)
}
if target.Address != "192.168.1.20" || !target.Enabled || !target.IncludesLocalObservation() {
t.Errorf("%s = %+v, want an enabled check from this server on the host address", target.Name, target)
}
}
want := map[string]config.AvailabilityProbeProtocol{
"web:8081": config.AvailabilityProbeHTTP,
"secure:8443": config.AvailabilityProbeHTTPS,
}
if len(protocols) != len(want) {
t.Fatalf("saved checks = %v, want %v", protocols, want)
}
for name, protocol := range want {
if protocols[name] != protocol {
t.Errorf("%s saved as %q, want %q", name, protocols[name], protocol)
}
}
if len(payload.Created) != len(want) {
t.Fatalf("created = %d, want %d", len(payload.Created), len(want))
}
for _, target := range saved {
if target.Name == "web:8081" && target.LinkedResourceID != "res-web" {
t.Errorf("web check linked to %q, want its container resource", target.LinkedResourceID)
}
}
// A port that refuses, and one that answers HTTP 503, get no check: it
// would alert from its first run. A port that only accepts a connection
// gets none either: Docker's proxy accepts for a dead service when Pulse
// shares the host, so a connection check there would pass for good.
unanswered := map[string]string{}
for _, item := range payload.Unanswered {
unanswered[item.ContainerName] = item.Error
}
if len(unanswered) != 3 || unanswered["dead"] == "" || !strings.Contains(unanswered["sick"], "503") ||
!strings.Contains(unanswered["raw"], "did not answer over HTTP or HTTPS") {
t.Fatalf("unanswered = %v, want dead (refused), sick (503) and raw (not HTTP)", unanswered)
}
skipped := map[string]string{}
for _, item := range payload.Skipped {
skipped[item.ContainerName] = item.SkipReason
}
if len(skipped) != 2 || skipped["local"] != monitoring.DockerPortSkipLoopbackOnly || skipped["cache"] != monitoring.DockerPortSkipNotHTTP {
t.Fatalf("skipped = %v, want the loopback-only port and the Redis port", skipped)
}
for _, call := range script.calls {
if strings.HasSuffix(call, ":6379") {
t.Fatalf("Redis port was probed: %q", call)
}
if strings.HasSuffix(call, ":8083") {
t.Fatalf("loopback-only port was probed: %q", call)
}
}
// A second request offers only what is still unchecked and adds nothing
// twice.
rec = httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(dockerPortSelectionBody(t, handler))))
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode second apply: %v", err)
}
if len(payload.Created) != 0 || len(payload.Unanswered) != 3 {
t.Fatalf("second apply = %+v, want nothing new", payload)
}
again, _ := persistence.LoadAvailabilityTargets()
if len(again) != len(saved) {
t.Fatalf("second apply changed the saved checks: %d -> %d", len(saved), len(again))
}
}
func TestApplyDockerPortSuggestionsRejectsAConflictingRequestedHost(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{"tcp 192.168.1.20:8081": nil, "http 192.168.1.20:8081": nil}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(strings.Replace(dockerPortSelectionBody(t, handler), `{"ports":`, `{"hostId":"another-host","ports":`, 1))))
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
if saved, _ := persistence.LoadAvailabilityTargets(); len(saved) != 0 {
t.Fatalf("checks added for a host that was not asked for: %+v", saved)
}
if len(script.calls) != 0 {
t.Fatalf("probed %v for a host that was not asked for", script.calls)
}
}
// The operator is shown a list and adds exactly that: a port they dismissed
// earlier, or one published since, is not added behind their back.
func TestApplyDockerPortSuggestionsAddsOnlyTheSelectedPorts(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{
"tcp 192.168.1.20:8081": nil, "http 192.168.1.20:8081": nil,
"tcp 192.168.1.20:8443": nil, "https 192.168.1.20:8443": nil,
}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
body := dockerPortSelectionBody(t, handler, "web")
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
saved, _ := persistence.LoadAvailabilityTargets()
if len(saved) != 1 || saved[0].Name != "web:8081" {
t.Fatalf("saved = %+v, want only the selected web port", saved)
}
for _, call := range script.calls {
if !strings.HasSuffix(call, ":8081") {
t.Fatalf("probed a port that was not selected: %q", call)
}
}
}
// Probing takes seconds. A check the operator adds or removes meanwhile must
// survive the save, and a port they covered by hand must not get a second check.
func TestApplyDockerPortSuggestionsKeepsChangesMadeWhileProbing(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{
"tcp 192.168.1.20:8081": nil, "http 192.168.1.20:8081": nil,
"tcp 192.168.1.20:8443": nil, "https 192.168.1.20:8443": nil,
}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
existing := config.NormalizeAvailabilityTarget(config.AvailabilityTarget{ID: "doomed", Name: "old router", Protocol: config.AvailabilityProbeICMP, Address: "192.168.1.1", TargetKind: config.AvailabilityTargetDevice})
if err := persistence.SaveAvailabilityTargets([]config.AvailabilityTarget{existing}); err != nil {
t.Fatalf("seed: %v", err)
}
script.duringProbes = func() {
// Meanwhile: the operator deletes "doomed" and adds their own check
// for the web port.
byHand := config.NormalizeAvailabilityTarget(config.AvailabilityTarget{ID: "by-hand", Name: "my web check", Protocol: config.AvailabilityProbeTCP, Address: "192.168.1.20", Port: 8081, TargetKind: config.AvailabilityTargetService})
if err := persistence.SaveAvailabilityTargets([]config.AvailabilityTarget{byHand}); err != nil {
t.Errorf("concurrent save: %v", err)
}
}
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(dockerPortSelectionBody(t, handler))))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
saved, _ := persistence.LoadAvailabilityTargets()
names := map[string]bool{}
for _, target := range saved {
names[target.Name] = true
}
if names["old router"] {
t.Fatalf("a check deleted while probing came back: %+v", names)
}
if !names["my web check"] || names["web:8081"] {
t.Fatalf("saved = %v, want the operator's web check kept and no second one", names)
}
if !names["secure:8443"] {
t.Fatalf("saved = %v, want the untouched port still added", names)
}
}
// A host reachable only over IPv6 gets a working HTTP check: a bare IPv6
// literal is not a valid URL host.
func TestApplyDockerPortSuggestionsBracketsAnIPv6Address(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{
"tcp 2001:db8::20:8081": nil,
"http [2001:db8::20]:8081": nil,
}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
handler.dockerHosts = func(context.Context) []models.DockerHost {
return []models.DockerHost{{
ID: "host-6", Hostname: "v6-only",
NetworkInterfaces: []models.HostNetworkInterface{{Name: "eth0", Addresses: []string{"2001:db8::20/64"}}},
Containers: []models.DockerContainer{
{ID: "c-web", Name: "web", State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 80, PublicPort: 8081, Protocol: "tcp", IP: "::"}}},
},
}}
}
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(dockerPortSelectionBody(t, handler))))
saved, _ := persistence.LoadAvailabilityTargets()
if len(saved) != 1 || saved[0].Protocol != config.AvailabilityProbeHTTP {
t.Fatalf("saved = %+v, body=%s", saved, rec.Body.String())
}
u, err := saved[0].HTTPURL()
if err != nil || u.String() != "http://[2001:db8::20]:8081" {
t.Fatalf("saved URL = %v (%v), want http://[2001:db8::20]:8081", u, err)
}
// It still counts as covered, so it is not offered twice.
rec = httptest.NewRecorder()
handler.HandleDockerPortSuggestions(rec, httptest.NewRequest(http.MethodGet, "/api/availability-targets/docker-suggestions", nil))
if !strings.Contains(rec.Body.String(), `"suggestions":[]`) {
t.Fatalf("an IPv6 port with a check was offered again: %s", rec.Body.String())
}
}
func TestApplyDockerPortSuggestionsRejectsChangedOffersBeforeAnyProbe(t *testing.T) {
for name, change := range map[string]func(*models.DockerHost){
"host address": func(h *models.DockerHost) { h.NetworkInterfaces[0].Addresses = []string{"192.168.1.21/24"} },
"public port": func(h *models.DockerHost) { h.Containers[0].Ports[0].PublicPort = 9081 },
"container replacement at same endpoint": func(h *models.DockerHost) { h.Containers[0].ID = "replacement" },
"container name": func(h *models.DockerHost) { h.Containers[0].Name = "renamed" },
"private port": func(h *models.DockerHost) { h.Containers[0].Ports[0].PrivatePort = 81 },
"bind address": func(h *models.DockerHost) { h.Containers[0].Ports[0].IP = "192.168.1.21" },
"loopback only": func(h *models.DockerHost) { h.Containers[0].Ports[0].IP = "127.0.0.1" },
"link local only": func(h *models.DockerHost) { h.Containers[0].Ports[0].IP = "169.254.169.254" },
"stopped": func(h *models.DockerHost) { h.Containers[0].State = "exited" },
"removed port": func(h *models.DockerHost) { h.Containers[0].Ports = nil },
"removed address": func(h *models.DockerHost) { h.NetworkInterfaces = nil },
"different host": func(h *models.DockerHost) { h.ID = "host-2" },
} {
t.Run(name, func(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{"tcp 192.168.1.20:8443": nil, "https 192.168.1.20:8443": nil}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
// An unchanged secure port is in the same selection. A stale item
// refuses the whole batch before even that valid port is probed.
body := dockerPortSelectionBody(t, handler, "web", "secure")
host := handler.dockerHosts(context.Background())[0]
change(&host)
handler.dockerHosts = func(context.Context) []models.DockerHost { return []models.DockerHost{host} }
existing := config.NormalizeAvailabilityTarget(config.AvailabilityTarget{ID: "keep", Name: "router", Protocol: config.AvailabilityProbeICMP, Address: "192.168.1.1"})
if err := persistence.SaveAvailabilityTargets([]config.AvailabilityTarget{existing}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), `"code":"docker_ports_changed"`) || !strings.Contains(rec.Body.String(), "Refresh the page") {
t.Fatalf("stale apply = %d %s", rec.Code, rec.Body.String())
}
if len(script.calls) != 0 {
t.Fatalf("stale selection probed %v", script.calls)
}
saved, err := persistence.LoadAvailabilityTargets()
if err != nil || len(saved) != 1 || saved[0].ID != existing.ID {
t.Fatalf("existing checks changed: %+v, %v", saved, err)
}
})
}
}
func TestApplyDockerPortSuggestionsRequiresExplicitBoundSelection(t *testing.T) {
for _, body := range []string{
``, `{}`, `{"hostId":"host-1"}`, `{"ports":null}`, `{"ports":[]}`,
`{"ports":[{"hostId":"host-1","containerName":"web","privatePort":80}]}`,
`{"ports":[{"hostId":"host-1","containerId":"c-web","containerName":"web","privatePort":80}]}`,
`{"ports":[{"hostId":"host-1","containerName":"web","privatePort":80,"publicPort":8081,"address":"192.168.1.20"}]}`,
`{"ports":[{"hostId":"host-1","containerId":"c-web","containerName":"web","privatePort":80,"publicPort":65536,"address":"192.168.1.20"}]}`,
`{"ports":[{"hostId":"host-1","containerId":"c-web","containerName":"web","privatePort":0,"publicPort":8081,"address":"192.168.1.20"}]}`,
`{"ports":[{"hostId":" host-1","containerId":"c-web","containerName":"web","privatePort":80,"publicPort":8081,"address":"192.168.1.20"}]}`,
`{"ports":[{"hostId":"host-1","containerId":"c-web ","containerName":"web","privatePort":80,"publicPort":8081,"address":"192.168.1.20"}]}`,
`{"ports":[{"hostId":"host-1","containerId":"c-web","containerName":"/web","privatePort":80,"publicPort":8081,"address":"192.168.1.20"}]}`,
`{"ports":[{"hostId":"host-1","containerId":"c-web","containerName":"web","privatePort":80,"publicPort":8081,"address":"192.168.1.20 "}]}`,
} {
t.Run(body, func(t *testing.T) {
script := &dockerPortProbeScript{}
handler, persistence := dockerPortSuggestionHandlers(t, script)
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
if rec.Code != http.StatusBadRequest {
t.Fatalf("unbound apply = %d %s", rec.Code, rec.Body.String())
}
if len(script.calls) != 0 {
t.Fatalf("unbound selection probed %v", script.calls)
}
if saved, _ := persistence.LoadAvailabilityTargets(); len(saved) != 0 {
t.Fatalf("unbound selection saved %+v", saved)
}
})
}
}
func TestApplyDockerPortSuggestionsDoesNotSelectANewMappingOfTheSamePort(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{
"tcp 192.168.1.20:8081": nil, "http 192.168.1.20:8081": nil,
"tcp 192.168.1.20:9081": nil, "http 192.168.1.20:9081": nil,
}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
body := dockerPortSelectionBody(t, handler, "web")
host := handler.dockerHosts(context.Background())[0]
host.Containers[0].Ports = append(host.Containers[0].Ports, models.DockerContainerPort{PrivatePort: 80, PublicPort: 9081, Protocol: "tcp", IP: "0.0.0.0"})
handler.dockerHosts = func(context.Context) []models.DockerHost { return []models.DockerHost{host} }
for repeat := 0; repeat < 2; repeat++ {
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
if rec.Code != http.StatusOK {
t.Fatalf("apply = %d %s", rec.Code, rec.Body.String())
}
}
saved, _ := persistence.LoadAvailabilityTargets()
if len(saved) != 1 || saved[0].Port != 8081 {
t.Fatalf("selected one endpoint, saved %+v", saved)
}
for _, call := range script.calls {
if !strings.HasSuffix(call, ":8081") {
t.Fatalf("probed new unreviewed mapping: %s", call)
}
}
if len(script.calls) != 3 {
t.Fatalf("exact retry should not probe again: %v", script.calls)
}
}
func TestApplyDockerPortSuggestionsRejectsInventoryChangeDuringProbes(t *testing.T) {
for _, replacement := range []bool{false, true} {
t.Run(fmt.Sprintf("replacement=%t", replacement), func(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{"tcp 192.168.1.20:8081": nil, "http 192.168.1.20:8081": nil}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
body := dockerPortSelectionBody(t, handler, "web")
host := handler.dockerHosts(context.Background())[0]
handler.dockerHosts = func(context.Context) []models.DockerHost { return []models.DockerHost{host} }
script.duringProbes = func() {
if replacement {
host.Containers[0].ID = "replacement"
} else {
host.Containers[0].Ports[0].PublicPort = 9081
}
}
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
if rec.Code != http.StatusConflict {
t.Fatalf("changed during probes = %d %s", rec.Code, rec.Body.String())
}
if saved, _ := persistence.LoadAvailabilityTargets(); len(saved) != 0 {
t.Fatalf("stale check saved: %+v", saved)
}
for _, call := range script.calls {
if !strings.HasSuffix(call, ":8081") {
t.Fatalf("substituted endpoint during probes: %s", call)
}
}
})
}
}
func TestApplyDockerPortSuggestionsBoundsSelectionAndDeduplicates(t *testing.T) {
for _, count := range []int{2, maxDockerPortSelection + 1} {
t.Run(fmt.Sprintf("count=%d", count), func(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{"tcp 192.168.1.20:8081": nil, "http 192.168.1.20:8081": nil}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
var request struct {
Ports []monitoring.DockerPortCheckCandidate `json:"ports"`
}
if err := json.Unmarshal([]byte(dockerPortSelectionBody(t, handler, "web")), &request); err != nil {
t.Fatal(err)
}
first := request.Ports[0]
request.Ports = make([]monitoring.DockerPortCheckCandidate, count)
for i := range request.Ports {
request.Ports[i] = first
}
body, _ := json.Marshal(request)
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(string(body))))
saved, _ := persistence.LoadAvailabilityTargets()
if count > maxDockerPortSelection {
if rec.Code != http.StatusBadRequest || len(script.calls) != 0 || len(saved) != 0 {
t.Fatalf("oversized = %d, probes=%v, saved=%+v", rec.Code, script.calls, saved)
}
} else if rec.Code != http.StatusOK || len(saved) != 1 || len(script.calls) != 3 {
t.Fatalf("duplicate = %d, probes=%v, saved=%+v", rec.Code, script.calls, saved)
}
})
}
}
func TestApplyDockerPortSuggestionsNeverPromotesASkippedSelection(t *testing.T) {
for _, address := range []string{"192.168.1.20/24", "2001:db8::20/64"} {
t.Run(address, func(t *testing.T) {
script := &dockerPortProbeScript{}
handler, persistence := dockerPortSuggestionHandlers(t, script)
host := handler.dockerHosts(context.Background())[0]
host.NetworkInterfaces = nil
handler.dockerHosts = func(context.Context) []models.DockerHost { return []models.DockerHost{host} }
body := dockerPortSelectionBody(t, handler, "web")
host.NetworkInterfaces = []models.HostNetworkInterface{{Name: "eth0", Addresses: []string{address}}}
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
if rec.Code != http.StatusConflict || len(script.calls) != 0 {
t.Fatalf("previously uncheckable selection = %d %s, probes=%v", rec.Code, rec.Body.String(), script.calls)
}
if saved, err := persistence.LoadAvailabilityTargets(); err != nil || len(saved) != 0 {
t.Fatalf("unreviewed endpoint saved: %+v (%v)", saved, err)
}
})
}
}
func TestApplyDockerPortSuggestionsDoesNotSelectAnotherAddressOfTheSamePort(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{"tcp 192.168.1.20:8081": nil, "http 192.168.1.20:8081": nil}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
body := dockerPortSelectionBody(t, handler, "web")
host := handler.dockerHosts(context.Background())[0]
host.Containers[0].Ports = append(host.Containers[0].Ports, models.DockerContainerPort{PrivatePort: 80, PublicPort: 9081, Protocol: "tcp", IP: "192.168.1.21"})
handler.dockerHosts = func(context.Context) []models.DockerHost { return []models.DockerHost{host} }
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
if rec.Code != http.StatusOK || len(script.calls) != 3 {
t.Fatalf("exact mapping = %d %s, probes=%v", rec.Code, rec.Body.String(), script.calls)
}
saved, err := persistence.LoadAvailabilityTargets()
if err != nil || len(saved) != 1 || saved[0].Address != "192.168.1.20" || saved[0].Port != 8081 {
t.Fatalf("another address selected: %+v (%v)", saved, err)
}
}
func TestApplyDockerPortSuggestionsRetainsThePerRequestLimit(t *testing.T) {
script := &dockerPortProbeScript{answers: map[string]error{}}
handler, persistence := dockerPortSuggestionHandlers(t, script)
host := handler.dockerHosts(context.Background())[0]
host.Containers = nil
for i := 0; i < maxDockerPortChecksPerRequest+1; i++ {
port := 8000 + i
host.Containers = append(host.Containers, models.DockerContainer{ID: fmt.Sprintf("container-%d", i), Name: fmt.Sprintf("web-%d", i), State: "running", Ports: []models.DockerContainerPort{{PrivatePort: 80, PublicPort: port, Protocol: "tcp", IP: "0.0.0.0"}}})
script.answers[fmt.Sprintf("tcp 192.168.1.20:%d", port)] = nil
script.answers[fmt.Sprintf("https 192.168.1.20:%d", port)] = nil
}
handler.dockerHosts = func(context.Context) []models.DockerHost { return []models.DockerHost{host} }
body := dockerPortSelectionBody(t, handler)
for _, want := range []int{maxDockerPortChecksPerRequest, 1} {
rec := httptest.NewRecorder()
handler.HandleApplyDockerPortSuggestions(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets/docker-suggestions", strings.NewReader(body)))
var response dockerPortApplyResponse
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if rec.Code != http.StatusOK || len(response.Created) != want {
t.Fatalf("capped apply=%d %+v", rec.Code, response)
}
if want == maxDockerPortChecksPerRequest && response.Remaining != 1 {
t.Fatalf("remaining=%d", response.Remaining)
}
}
saved, err := persistence.LoadAvailabilityTargets()
if err != nil || len(saved) != maxDockerPortChecksPerRequest+1 || len(script.calls) != 2*len(saved) {
t.Fatalf("incremental selection lost or repeated checks: count=%d probes=%d err=%v", len(saved), len(script.calls), err)
}
}