feat(logshipper): support dynamic OmniLogger credentials
- Add per-service OmniLogger credentials to core config and update subscriptions. - Follow config pushes and enforce entry and request size limits. - Requeue batches after transient send failures.
This commit is contained in:
1 parent
76bf5916fe
commit
8701874efb
20 files changed
+4908
-61
No files matched your search
@@ -11,6 +11,9 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||
)
|
||||
|
||||
// captureStd runs fn with os.Stdout and os.Stderr redirected, and returns what it wrote to each.
|
||||
@@ -83,6 +86,9 @@ func newTestShipper(t *testing.T, cfg Config) *Shipper {
|
||||
if cfg.BaseURL == "" {
|
||||
cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL
|
||||
}
|
||||
if cfg.IngestToken == "" {
|
||||
cfg.IngestToken = "test-token"
|
||||
}
|
||||
return New(cfg)
|
||||
}
|
||||
|
||||
@@ -274,7 +280,7 @@ func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) {
|
||||
shipper.Info("two")
|
||||
shipper.Flush()
|
||||
})
|
||||
if strings.Count(stderr, "OmniLogger rejected") != 1 {
|
||||
if strings.Count(stderr, "answered HTTP 500") != 1 {
|
||||
t.Fatalf("stderr = %q, want one rate-limited warning", stderr)
|
||||
}
|
||||
|
||||
@@ -298,3 +304,383 @@ func TestNewAppliesDefaults(t *testing.T) {
|
||||
t.Fatalf("defaults not applied: %+v", shipper)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriterShipsEachNonEmptyLineAsInfoWithoutPrintingLocally(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL})
|
||||
defer shipper.Close()
|
||||
|
||||
stdout, stderr := captureStd(t, func() {
|
||||
n, err := shipper.Writer().Write([]byte("first line\r\n\nsecond line\n"))
|
||||
if err != nil || n != len("first line\r\n\nsecond line\n") {
|
||||
t.Fatalf("Write = %d, %v", n, err)
|
||||
}
|
||||
shipper.Flush()
|
||||
})
|
||||
if stdout != "" || stderr != "" {
|
||||
t.Fatalf("Writer printed locally: stdout=%q stderr=%q", stdout, stderr)
|
||||
}
|
||||
entries := in.entries()
|
||||
if len(entries) != 2 {
|
||||
t.Fatalf("shipped %d entries, want 2: %+v", len(entries), entries)
|
||||
}
|
||||
if entries[0].Message != "first line" || entries[1].Message != "second line" {
|
||||
t.Fatalf("messages = %q, %q", entries[0].Message, entries[1].Message)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Service != "svc" || e.Level != "info" {
|
||||
t.Fatalf("entry = %+v, want service svc at level info", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriterRespectsTheThreshold(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"})
|
||||
defer shipper.Close()
|
||||
|
||||
_, _ = shipper.Writer().Write([]byte("quiet line\n"))
|
||||
shipper.Flush()
|
||||
if n := len(in.entries()); n != 0 {
|
||||
t.Fatalf("shipped %d entries below the threshold", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClampEntryKeepsEveryEntryInsideOmniLoggerLimits(t *testing.T) {
|
||||
long := strings.Repeat("é", maxMessageBytes) // 2 bytes per rune, so the cut must land on a rune boundary
|
||||
got := clampEntry(wireEntry{Message: long})
|
||||
if len(got.Message) > maxMessageBytes || !strings.HasSuffix(got.Message, truncatedMarker) {
|
||||
t.Fatalf("message length %d, want at most %d and ending in the marker", len(got.Message), maxMessageBytes)
|
||||
}
|
||||
if !utf8.ValidString(got.Message) {
|
||||
t.Fatal("truncation split a UTF-8 rune")
|
||||
}
|
||||
|
||||
big := json.RawMessage(`{"blob":"` + strings.Repeat("x", maxContextBytes) + `"}`)
|
||||
if string(clampEntry(wireEntry{Context: big}).Context) != droppedContext {
|
||||
t.Fatal("oversized context was not replaced by the dropped marker")
|
||||
}
|
||||
nul := json.RawMessage(`{"s":"a\u0000b"}`)
|
||||
if string(clampEntry(wireEntry{Context: nul}).Context) != droppedContext {
|
||||
t.Fatal("context with a NUL escape was not replaced by the dropped marker")
|
||||
}
|
||||
small := json.RawMessage(`{"ok":true}`)
|
||||
if string(clampEntry(wireEntry{Context: small}).Context) != `{"ok":true}` {
|
||||
t.Fatal("ordinary context was changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoTokenMeansShippingIsDisabled(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := New(Config{Service: "svc", BaseURL: in.server.URL, FlushInterval: time.Hour})
|
||||
defer shipper.Close()
|
||||
|
||||
shipper.Info("not shipped")
|
||||
shipper.Flush()
|
||||
if n := len(in.entries()); n != 0 {
|
||||
t.Fatalf("shipped %d entries without a token", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetCredentialsEnablesAndDisablesShippingAtRuntime(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := New(Config{Service: "svc", FlushInterval: time.Hour})
|
||||
defer shipper.Close()
|
||||
|
||||
shipper.Info("before credentials")
|
||||
shipper.SetCredentials(in.server.URL+"/", "pushed-token")
|
||||
shipper.Info("after credentials")
|
||||
shipper.Flush()
|
||||
entries := in.entries()
|
||||
if len(entries) != 1 || entries[0].Message != "after credentials" {
|
||||
t.Fatalf("entries after enabling = %+v, want only the one logged after SetCredentials", entries)
|
||||
}
|
||||
in.mu.Lock()
|
||||
gotAuth := in.auth
|
||||
in.mu.Unlock()
|
||||
if len(gotAuth) != 1 || !strings.HasSuffix(gotAuth[0], "Bearer pushed-token") || !strings.HasPrefix(gotAuth[0], "POST /api/logs") {
|
||||
t.Fatalf("request = %q, want a bearer-authenticated POST /api/logs", gotAuth)
|
||||
}
|
||||
|
||||
shipper.SetCredentials(in.server.URL, "")
|
||||
shipper.Info("after disabling")
|
||||
shipper.Flush()
|
||||
if n := len(in.entries()); n != 1 {
|
||||
t.Fatalf("shipped %d entries after shipping was disabled, want still 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFollowAppliesOnlyPushesThatCarryAToken(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
store := coreconfig.NewStore(coreconfig.Info{})
|
||||
shipper := New(Config{Service: "svc", FlushInterval: time.Hour, BaseURL: in.server.URL, IngestToken: "env-token"})
|
||||
defer shipper.Close()
|
||||
shipper.Follow(store)
|
||||
|
||||
// A push that only moves other URLs must not disable the env-configured shipper.
|
||||
store.Set(coreconfig.Info{AuthGuardURL: "https://auth.example.com"})
|
||||
shipper.Info("still shipping")
|
||||
shipper.Flush()
|
||||
if n := len(in.entries()); n != 1 {
|
||||
t.Fatalf("a push without a token changed shipping: %d entries", n)
|
||||
}
|
||||
|
||||
pushed := newIngest(t, http.StatusAccepted)
|
||||
store.Set(coreconfig.Info{OmniLoggerURL: pushed.server.URL, OmniLoggerIngestToken: "pushed-token"})
|
||||
shipper.Info("to the pushed endpoint")
|
||||
shipper.Flush()
|
||||
if n := len(pushed.entries()); n != 1 {
|
||||
t.Fatalf("pushed endpoint received %d entries, want 1", n)
|
||||
}
|
||||
if n := len(in.entries()); n != 1 {
|
||||
t.Fatalf("old endpoint still received entries after the push: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A backlog larger than one request allows is split so no request exceeds the entry or byte cap.
|
||||
func TestFlushSplitsABacklogIntoBoundedRequests(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var counts []int
|
||||
var sizes []int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var batch []wireEntry
|
||||
body := new(strings.Builder)
|
||||
_, _ = io.Copy(body, r.Body)
|
||||
_ = json.Unmarshal([]byte(body.String()), &batch)
|
||||
mu.Lock()
|
||||
counts = append(counts, len(batch))
|
||||
sizes = append(sizes, body.Len())
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
shipper := New(Config{Service: "svc", BaseURL: server.URL, IngestToken: "t", FlushInterval: time.Hour, BufferCapacity: 2000, MaxBatchSize: 2000})
|
||||
defer shipper.Close()
|
||||
big := strings.Repeat("y", maxMessageBytes)
|
||||
for i := 0; i < 300; i++ {
|
||||
shipper.Info("small")
|
||||
}
|
||||
for i := 0; i < 200; i++ {
|
||||
shipper.Info(big)
|
||||
}
|
||||
shipper.Flush()
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
total := 0
|
||||
for i, n := range counts {
|
||||
total += n
|
||||
if n > maxRequestEntries {
|
||||
t.Fatalf("request %d carried %d entries, want at most %d", i, n, maxRequestEntries)
|
||||
}
|
||||
if sizes[i] > maxRequestBytes {
|
||||
t.Fatalf("request %d was %d bytes, want at most %d", i, sizes[i], maxRequestBytes)
|
||||
}
|
||||
}
|
||||
if total != 500 {
|
||||
t.Fatalf("shipped %d entries, want all 500", total)
|
||||
}
|
||||
}
|
||||
|
||||
// Ship sends at the given severity and prints nothing locally, so a host that already prints its own lines
|
||||
// is not doubled.
|
||||
func TestShipKeepsTheSeverityAndPrintsNothingLocally(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "info"})
|
||||
defer shipper.Close()
|
||||
|
||||
stdout, stderr := captureStd(t, func() {
|
||||
shipper.Ship(LevelError, map[string]any{"request_id": "r1"}, "boom")
|
||||
shipper.Ship(LevelDebug, nil, "below the threshold")
|
||||
shipper.Flush()
|
||||
})
|
||||
if stdout != "" || stderr != "" {
|
||||
t.Fatalf("Ship printed locally: stdout=%q stderr=%q", stdout, stderr)
|
||||
}
|
||||
entries := in.entries()
|
||||
if len(entries) != 1 || entries[0].Level != "error" || entries[0].Message != "boom" {
|
||||
t.Fatalf("entries = %+v, want one error entry", entries)
|
||||
}
|
||||
if !strings.Contains(string(entries[0].Context), `"request_id":"r1"`) {
|
||||
t.Fatalf("context = %s, want the request id", entries[0].Context)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFollowIgnoresAPushWithATokenButNoURL(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
store := coreconfig.NewStore(coreconfig.Info{})
|
||||
shipper := New(Config{Service: "svc", FlushInterval: time.Hour, BaseURL: in.server.URL, IngestToken: "env-token"})
|
||||
defer shipper.Close()
|
||||
shipper.Follow(store)
|
||||
|
||||
store.Set(coreconfig.Info{OmniLoggerIngestToken: "orphan-token"})
|
||||
shipper.Info("still configured from the environment")
|
||||
shipper.Flush()
|
||||
if n := len(in.entries()); n != 1 {
|
||||
t.Fatalf("a token without a URL disabled the env-configured shipper: %d entries", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInferLevelReadsTheWordingOfPlainLines(t *testing.T) {
|
||||
cases := map[string]Level{
|
||||
"listening on :8080": LevelInfo,
|
||||
"minted an OmniLogger ingest token for mediaviewer": LevelInfo,
|
||||
"push login-required to x failed: status 401": LevelError,
|
||||
"ERROR: database unreachable": LevelError,
|
||||
"could not open the fixture": LevelError,
|
||||
"push core service info to x skipped: unreadable": LevelWarn,
|
||||
"WARNING: disk nearly full": LevelWarn,
|
||||
"retrying in 5s after a timeout": LevelWarn,
|
||||
"panic: runtime error": LevelCritical,
|
||||
"fatal: cannot start": LevelCritical,
|
||||
"warning: request failed": LevelError,
|
||||
}
|
||||
for line, want := range cases {
|
||||
if got := InferLevel(line); got != want {
|
||||
t.Errorf("InferLevel(%q) = %v, want %v", line, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Writer keeps each line's inferred severity, so an error line is not shipped as info.
|
||||
func TestWriterKeepsTheInferredSeverityOfEachLine(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL})
|
||||
defer shipper.Close()
|
||||
|
||||
_, _ = shipper.Writer().Write([]byte("listening on :8080\npush to x failed: boom\nretry skipped\n"))
|
||||
shipper.Flush()
|
||||
entries := in.entries()
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("shipped %d entries, want 3", len(entries))
|
||||
}
|
||||
want := []string{"info", "error", "warn"}
|
||||
for i, e := range entries {
|
||||
if e.Level != want[i] {
|
||||
t.Errorf("entry %d (%q) level = %s, want %s", i, e.Message, e.Level, want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Writer respects the threshold per line: warnings are dropped when the threshold is error.
|
||||
func TestWriterDropsLinesBelowTheThreshold(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"})
|
||||
defer shipper.Close()
|
||||
|
||||
_, _ = shipper.Writer().Write([]byte("hello\nfailed hard\n"))
|
||||
shipper.Flush()
|
||||
entries := in.entries()
|
||||
if len(entries) != 1 || entries[0].Level != "error" {
|
||||
t.Fatalf("entries = %+v, want only the error line", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// flakyIngest fails its first `failures` requests with the given status, then accepts every request, and
|
||||
// counts the entries it accepted.
|
||||
type flakyIngest struct {
|
||||
mu sync.Mutex
|
||||
failures int
|
||||
status int
|
||||
accepted []string
|
||||
server *httptest.Server
|
||||
}
|
||||
|
||||
func newFlakyIngest(t *testing.T, failures, status int) *flakyIngest {
|
||||
t.Helper()
|
||||
in := &flakyIngest{failures: failures, status: status}
|
||||
in.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var batch []wireEntry
|
||||
_ = json.NewDecoder(r.Body).Decode(&batch)
|
||||
in.mu.Lock()
|
||||
defer in.mu.Unlock()
|
||||
if in.failures > 0 {
|
||||
in.failures--
|
||||
w.WriteHeader(in.status)
|
||||
return
|
||||
}
|
||||
for _, e := range batch {
|
||||
in.accepted = append(in.accepted, e.Message)
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
t.Cleanup(in.server.Close)
|
||||
return in
|
||||
}
|
||||
|
||||
func (in *flakyIngest) messages() []string {
|
||||
in.mu.Lock()
|
||||
defer in.mu.Unlock()
|
||||
return append([]string(nil), in.accepted...)
|
||||
}
|
||||
|
||||
// A server error is retried on a later flush, and each entry is delivered exactly once.
|
||||
func TestRetriesAServerErrorAndDeliversEachEntryOnce(t *testing.T) {
|
||||
in := newFlakyIngest(t, 1, http.StatusServiceUnavailable)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, IngestToken: "t"})
|
||||
defer shipper.Close()
|
||||
|
||||
captureStd(t, func() {
|
||||
shipper.Info("a")
|
||||
shipper.Info("b")
|
||||
shipper.Flush() // refused with 503: kept for retry
|
||||
shipper.Flush() // accepted
|
||||
shipper.Flush() // nothing left to send
|
||||
})
|
||||
got := in.messages()
|
||||
if len(got) != 2 || got[0] != "a" || got[1] != "b" {
|
||||
t.Fatalf("delivered %v, want a and b exactly once, in order", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A request OmniLogger rejects with 4xx is dropped, not retried, because it would fail the same way again.
|
||||
func TestDropsARejectedRequestWithoutRetrying(t *testing.T) {
|
||||
in := newFlakyIngest(t, 1, http.StatusBadRequest)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, IngestToken: "t"})
|
||||
defer shipper.Close()
|
||||
|
||||
captureStd(t, func() {
|
||||
shipper.Info("rejected")
|
||||
shipper.Flush()
|
||||
shipper.Flush()
|
||||
})
|
||||
if got := in.messages(); len(got) != 0 {
|
||||
t.Fatalf("accepted %v after a 400, want nothing", got)
|
||||
}
|
||||
shipper.mu.Lock()
|
||||
pending := len(shipper.buffer)
|
||||
shipper.mu.Unlock()
|
||||
if pending != 0 {
|
||||
t.Fatalf("a rejected request stayed in the buffer: %d entries", pending)
|
||||
}
|
||||
}
|
||||
|
||||
// Entries that cannot be sent while OmniLogger is unreachable wait in the buffer, and the buffer never grows
|
||||
// past its capacity.
|
||||
func TestRetryKeepsTheBufferWithinItsCapacity(t *testing.T) {
|
||||
in := newFlakyIngest(t, 0, http.StatusAccepted)
|
||||
url := in.server.URL
|
||||
in.server.Close()
|
||||
shipper := New(Config{Service: "svc", BaseURL: url, IngestToken: "t", FlushInterval: time.Hour, BufferCapacity: 3, MaxBatchSize: 100})
|
||||
defer shipper.Close()
|
||||
|
||||
captureStd(t, func() {
|
||||
for _, m := range []string{"a", "b", "c"} {
|
||||
shipper.Info(m)
|
||||
}
|
||||
shipper.Flush() // unreachable: kept
|
||||
for _, m := range []string{"d", "e"} {
|
||||
shipper.Info(m)
|
||||
}
|
||||
shipper.Flush() // still unreachable; the buffer holds at most three entries
|
||||
})
|
||||
shipper.mu.Lock()
|
||||
defer shipper.mu.Unlock()
|
||||
if len(shipper.buffer) > 3 {
|
||||
t.Fatalf("buffer holds %d entries, capacity is 3", len(shipper.buffer))
|
||||
}
|
||||
if len(shipper.buffer) != 3 || shipper.buffer[0].Message != "a" {
|
||||
t.Fatalf("buffer = %+v, want the oldest three entries first", shipper.buffer)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user