8000 🐛 Tighten close-call caching, timeouts and evidence merging by abahmed · Pull Request #608 · abahmed/kwatch · GitHub
[go: up one dir, main page]

Skip to content
8000
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8000
39 changes: 29 additions & 10 deletions internal/inventory/kube/close_call.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import (
// other, one read-only check can tell them apart: does the endpoint's
// name resolve, and does it accept a connection. The check is the
// ones kwatch already runs on an endpoint, once, on demand: one DNS
// lookup and one TCP connect, each bounded by CloseCallTimeout, to an
// lookup and one TCP connect, together bounded by CloseCallTimeout, to an
// address that is not private (privateAddress). It changes nothing and
// sends no payload.
const (
// CloseCallTimeout bounds each of the two operations of a check.
// CloseCallTimeout bounds a whole check: the lookup and the connect
// share it.
CloseCallTimeout = 5 * time.Second
// closeCallRemember is how long a result stands, so that incidents
// investigated again do not dial the endpoint again.
Expand Down Expand Up @@ -90,9 +91,9 @@ func (c *CloseCall) Check(
return CloseCallResult{Endpoint: endpoint, Error: "not a host:port"}
}
result := CloseCallResult{Endpoint: endpoint, Host: host}
lookupCtx, cancel := context.WithTimeout(ctx, CloseCallTimeout)
checkCtx, cancel := context.WithTimeout(ctx, CloseCallTimeout)
defer cancel()
addrs, err := c.resolver.LookupHost(lookupCtx, host)
addrs, err := c.resolver.LookupHost(checkCtx, host)
switch {
case err != nil:
result.TimedOut = timedOut(err)
Expand All @@ -101,7 +102,7 @@ func (c *CloseCall) Check(
result.Error = "no address"
default:
result.Resolved = true
c.connect(ctx, &result)
c.connect(checkCtx, &result)
}
// A caller that gave up cut the check short; that is not a result.
if ctx.Err() == nil {
Expand All @@ -112,9 +113,7 @@ func (c *CloseCall) Check(

// connect opens one TCP connection and records how it went.
func (c *CloseCall) connect(ctx context.Context, result *CloseCallResult) {
dialCtx, cancel := context.WithTimeout(ctx, CloseCallTimeout)
defer cancel()
err := closeDialed(c.dial(dialCtx, "tcp", result.Endpoint))
err := closeDialed(c.dial(ctx, "tcp", result.Endpoint))
switch {
case err == nil:
result.Connected = true
Expand Down Expand Up @@ -157,8 +156,28 @@ func (c *CloseCall) remembered(endpoint string) (CloseCallResult, bool) {
func (c *CloseCall) remember(endpoint string, result CloseCallResult) {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.last) >= maxCloseCallMemory {
c.last = map[string]closeCallMemory{}
if _, kept := c.last[endpoint]; !kept &&
len(c.last) >= maxCloseCallMemory {
c.evict()
}
c.last[endpoint] = closeCallMemory{at: c.now(), result: result}
}

// evict makes room for one result: it drops the expired ones, and when
// none expired, the oldest. Callers hold c.mu.
func (c *CloseCall) evict() {
now := c.now()
oldest, oldestAt := "", time.Time{}
for k, m := range c.last {
if now.Sub(m.at) >= closeCallRemember {
delete(c.last, k)
continue
}
if oldest == "" || m.at.Before(oldestAt) {
oldest, oldestAt = k, m.at
}
}
if len(c.last) >= maxCloseCallMemory {
delete(c.last, oldest)
}
}
44 changes: 44 additions & 0 deletions internal/inventory/kube/close_call_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kube_test
import (
"context"
"errors"
"fmt"
"net"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -110,3 +111,46 @@ func TestCloseCallDoesNotRememberACheckTheCallerCutShort(t *testing.T) {
check.Check(context.Background(), "db.example.com:5432")
assert.EqualValues(t, 2, resolver.calls.Load())
}

func TestCloseCallSharesOneDeadlineAcrossLookupAndConnect(t *testing.T) {
var lookup, connect time.Time
resolver := &deadlineResolver{at: &lookup}
dial := func(ctx context.Context, _, _ string) (net.Conn, error) {
connect, _ = ctx.Deadline()
return nil, errors.New("connection refused")
}
check := kube.NewCloseCall(resolver, dial, time.Now)
check.Check(context.Background(), "db.example.com:5432")
assert.False(t, lookup.IsZero())
assert.Equal(t, lookup, connect)
assert.WithinDuration(t, time.Now().Add(kube.CloseCallTimeout),
connect, time.Second)
}

type deadlineResolver struct{ at *time.Time }

func (r *deadlineResolver) LookupHost(
ctx context.Context, _ string,
) ([]string, error) {
*r.at, _ = ctx.Deadline()
return []string{"203.0.113.9"}, nil
}

func TestCloseCallEvictsOnlyTheOldestWhenFull(t *testing.T) {
now := time.Unix(100, 0)
resolver := &closeResolver{addrs: []string{"203.0.113.9"}}
check := kube.NewCloseCall(resolver, dialing(nil),
func() time.Time { return now })
for i := 0; i < 64; i++ {
check.Check(context.Background(), fmt.Sprintf("h%d.example.com:1", i))
now = now.Add(time.Second)
}
check.Check(context.Background(), "new.example.com:1")
assert.EqualValues(t, 65, resolver.calls.Load())
// Everything but the oldest is still remembered.
check.Check(context.Background(), "h1.example.com:1")
check.Check(context.Background(), "h63.example.com:1")
assert.EqualValues(t, 65, resolver.calls.Load())
check.Check(context.Background(), "h0.example.com:1")
assert.EqualValues(t, 66, resolver.calls.Load())
}
23 changes: 23 additions & 0 deletions internal/pipeline/investigate/assemble_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package investigate

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/abahmed/kwatch/internal/incident"
)

func TestAssembleJoinsEvidenceWithoutWritingIntoTheLead(t *testing.T) {
backing := make([]incident.Fact, 1, 4)
backing[0] = incident.Fact{Text: "lead"}
planned := []check{{name: "a", adds: true}, {name: "b"}}
outputs := []*checkOutput{
{summary: Result{Evidence: []incident.Fact{{Text: "extra"}}}},
{summary: Result{Evidence: backing}},
}
out := assemble(planned, outputs, 1)
assert.Equal(t, []string{"lead", "extra"},
[]string{out.Evidence[0].Text, out.Evidence[1].Text})
assert.Empty(t, backing[:cap(backing)][1].Text)
}
6 changes: 4 additions & 2 deletions internal/pipeline/investigate/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package investigate
import (
"context"
"fmt"
"slices"
"time"

"k8s.io/klog/v2"
Expand Down Expand Up @@ -75,8 +76,9 @@ func assemble(planned []check, outputs []*checkOutput, lead int) Result {
}
switch {
case i == lead:
out.Output, out.Evidence = got.summary.Output,
append(got.summary.Evidence, out.Evidence...)
out.Output = got.summary.Output
out.Evidence = slices.Concat(
got.summary.Evidence, out.Evidence)
case c.adds:
out.Evidence = append(out.Evidence, got.summary.Evidence...)
}
Expand Down
0