687 lines
23 KiB
Go
687 lines
23 KiB
Go
package logshipper
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"strings"
|
|
"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.
|
|
func captureStd(t *testing.T, fn func()) (stdout, stderr string) {
|
|
t.Helper()
|
|
oldOut, oldErr := os.Stdout, os.Stderr
|
|
outR, outW, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
errR, errW, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
os.Stdout, os.Stderr = outW, errW
|
|
defer func() { os.Stdout, os.Stderr = oldOut, oldErr }()
|
|
|
|
fn()
|
|
|
|
outW.Close()
|
|
errW.Close()
|
|
os.Stdout, os.Stderr = oldOut, oldErr
|
|
outBytes, _ := io.ReadAll(outR)
|
|
errBytes, _ := io.ReadAll(errR)
|
|
return string(outBytes), string(errBytes)
|
|
}
|
|
|
|
// ingest is a stand-in OmniLogger that records every batch it is sent.
|
|
type ingest struct {
|
|
mu sync.Mutex
|
|
batches [][]wireEntry
|
|
auth []string
|
|
status int
|
|
server *httptest.Server
|
|
}
|
|
|
|
func newIngest(t *testing.T, status int) *ingest {
|
|
t.Helper()
|
|
in := &ingest{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()
|
|
in.batches = append(in.batches, batch)
|
|
in.auth = append(in.auth, r.Method+" "+r.URL.Path+" "+r.Header.Get("Authorization"))
|
|
in.mu.Unlock()
|
|
w.WriteHeader(in.status)
|
|
}))
|
|
t.Cleanup(in.server.Close)
|
|
return in
|
|
}
|
|
|
|
func (in *ingest) entries() []wireEntry {
|
|
in.mu.Lock()
|
|
defer in.mu.Unlock()
|
|
var all []wireEntry
|
|
for _, batch := range in.batches {
|
|
all = append(all, batch...)
|
|
}
|
|
return all
|
|
}
|
|
|
|
// newTestShipper keeps the background loop quiet so a test decides when entries are sent, and
|
|
// points a shipper that names no sink at a throwaway one so closing it prints nothing.
|
|
func newTestShipper(t *testing.T, cfg Config) *Shipper {
|
|
t.Helper()
|
|
if cfg.FlushInterval == 0 {
|
|
cfg.FlushInterval = time.Hour
|
|
}
|
|
if cfg.BaseURL == "" {
|
|
cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL
|
|
}
|
|
if cfg.IngestToken == "" {
|
|
cfg.IngestToken = "test-token"
|
|
}
|
|
return New(cfg)
|
|
}
|
|
|
|
func TestLevelOfAcceptsTheSharedLogVocabulary(t *testing.T) {
|
|
cases := map[string]Level{
|
|
"debug": LevelDebug, " DEBUG ": LevelDebug, "info": LevelInfo, "": LevelInfo, "bogus": LevelInfo,
|
|
"warn": LevelWarn, "warning": LevelWarn, "error": LevelError, "critical": LevelCritical,
|
|
"silent": LevelSilent, "none": LevelSilent, "off": LevelSilent,
|
|
}
|
|
for input, want := range cases {
|
|
if got := levelOf(input); got != want {
|
|
t.Errorf("levelOf(%q) = %d, want %d", input, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSevNameGivesTheLowercaseNameOmniLoggerExpects(t *testing.T) {
|
|
for sev, want := range map[Level][2]string{
|
|
LevelDebug: {"DEBUG", "debug"}, LevelInfo: {"INFO", "info"}, LevelWarn: {"WARN", "warn"},
|
|
LevelError: {"ERROR", "error"}, LevelCritical: {"CRITICAL", "critical"},
|
|
} {
|
|
if upper, lower := sevName(sev); upper != want[0] || lower != want[1] {
|
|
t.Errorf("sevName(%d) = %q, %q; want %q, %q", sev, upper, lower, want[0], want[1])
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestFormatArgsJoinsErrorsStringsAndValues(t *testing.T) {
|
|
got := formatArgs([]any{"failed:", errors.New("boom"), 42, map[string]int{"a": 1}, make(chan int)})
|
|
if !strings.HasPrefix(got, `failed: boom 42 {"a":1} `) {
|
|
t.Fatalf("formatArgs = %q", got)
|
|
}
|
|
if formatArgs(nil) != "" {
|
|
t.Fatal("formatArgs(nil) is not empty")
|
|
}
|
|
}
|
|
|
|
func TestScrubIDsDropsIdentifierFieldsFromTheLocalDump(t *testing.T) {
|
|
ctx := map[string]any{
|
|
"id": 1, "userId": 2, "user_id": 3, "requestID": "r", "path": "/x", "status": 200, "ok": true,
|
|
}
|
|
got := scrubIDs(ctx)
|
|
if len(got) != 3 || got["path"] != "/x" || got["status"] != 200 || got["ok"] != true {
|
|
t.Fatalf("scrubIDs = %v, want only path, status and ok", got)
|
|
}
|
|
if len(ctx) != 7 {
|
|
t.Fatal("scrubIDs modified its input")
|
|
}
|
|
}
|
|
|
|
func TestEmitGatesOnTheThresholdAndWritesTheLocalLine(t *testing.T) {
|
|
shipper := newTestShipper(t, Config{Service: "svc", Module: "mod", Level: "warn"})
|
|
defer shipper.Close()
|
|
stdout, stderr := captureStd(t, func() {
|
|
shipper.Info("below threshold")
|
|
shipper.Warn("warned")
|
|
shipper.Error("failed", errors.New("boom"))
|
|
})
|
|
if stdout != "" {
|
|
t.Fatalf("stdout = %q, want nothing", stdout)
|
|
}
|
|
if strings.Contains(stderr, "below threshold") || !strings.Contains(stderr, "[WARN] [mod] warned") || !strings.Contains(stderr, "[ERROR] [mod] failed boom") {
|
|
t.Fatalf("stderr = %q", stderr)
|
|
}
|
|
if got := len(shipper.buffer); got != 2 {
|
|
t.Fatalf("buffered %d entries, want the 2 at or above the threshold", got)
|
|
}
|
|
}
|
|
|
|
func TestSilentLevelWritesAndBuffersNothing(t *testing.T) {
|
|
shipper := newTestShipper(t, Config{Service: "svc", Level: "silent"})
|
|
defer shipper.Close()
|
|
stdout, stderr := captureStd(t, func() {
|
|
shipper.Critical("never shown")
|
|
})
|
|
if stdout != "" || stderr != "" || len(shipper.buffer) != 0 {
|
|
t.Fatalf("silent shipper wrote %q / %q and buffered %d entries", stdout, stderr, len(shipper.buffer))
|
|
}
|
|
}
|
|
|
|
func TestLogAllScrubsIDsLocallyButShipsTheFullContext(t *testing.T) {
|
|
in := newIngest(t, http.StatusAccepted)
|
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", LogAll: true})
|
|
defer shipper.Close()
|
|
stdout, _ := captureStd(t, func() {
|
|
shipper.InfoCtx(map[string]any{"userId": 7, "path": "/x"}, "request")
|
|
})
|
|
if !strings.Contains(stdout, `[DETAILS] {"path":"/x"}`) || strings.Contains(stdout, "userId") {
|
|
t.Fatalf("local dump = %q, want the ID scrubbed", stdout)
|
|
}
|
|
shipper.Flush()
|
|
entries := in.entries()
|
|
if len(entries) != 1 || !strings.Contains(string(entries[0].Context), `"userId":7`) {
|
|
t.Fatalf("shipped entries = %+v, want the unscrubbed context", entries)
|
|
}
|
|
}
|
|
|
|
func TestAuditShipsAnInfoEntryWithTheDetails(t *testing.T) {
|
|
in := newIngest(t, http.StatusAccepted)
|
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
|
|
defer shipper.Close()
|
|
captureStd(t, func() { shipper.Audit("login", map[string]any{"user": "a"}) })
|
|
shipper.Flush()
|
|
entries := in.entries()
|
|
if len(entries) != 1 || entries[0].Level != "info" || !strings.HasPrefix(entries[0].Message, "audit:login") {
|
|
t.Fatalf("entries = %+v", entries)
|
|
}
|
|
}
|
|
|
|
func TestFlushSendsOneAuthenticatedBatchAndEmptiesTheBuffer(t *testing.T) {
|
|
in := newIngest(t, http.StatusAccepted)
|
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL + "/", IngestToken: "secret", Service: "svc"})
|
|
defer shipper.Close()
|
|
captureStd(t, func() {
|
|
shipper.Info("one")
|
|
shipper.Error("two")
|
|
})
|
|
shipper.Flush()
|
|
shipper.Flush() // nothing left: no second request
|
|
in.mu.Lock()
|
|
defer in.mu.Unlock()
|
|
if len(in.batches) != 1 || len(in.batches[0]) != 2 {
|
|
t.Fatalf("batches = %+v, want one batch of two entries", in.batches)
|
|
}
|
|
if in.auth[0] != "POST /api/logs Bearer secret" {
|
|
t.Fatalf("request = %q", in.auth[0])
|
|
}
|
|
first := in.batches[0][0]
|
|
if first.Service != "svc" || first.Level != "info" || first.Message != "one" || first.OccurredAt.IsZero() {
|
|
t.Fatalf("first entry = %+v", first)
|
|
}
|
|
}
|
|
|
|
func TestBufferDropsNewEntriesOnceFullInsteadOfBlocking(t *testing.T) {
|
|
shipper := newTestShipper(t, Config{Service: "svc", BufferCapacity: 3, MaxBatchSize: 1000})
|
|
defer shipper.Close()
|
|
_, stderr := captureStd(t, func() {
|
|
for i := 0; i < 10; i++ {
|
|
shipper.enqueue(wireEntry{Message: "m"})
|
|
}
|
|
})
|
|
if len(shipper.buffer) != 3 {
|
|
t.Fatalf("buffer holds %d entries, want the capacity of 3", len(shipper.buffer))
|
|
}
|
|
if strings.Count(stderr, "buffer full") != 1 {
|
|
t.Fatalf("stderr = %q, want the full-buffer warning exactly once", stderr)
|
|
}
|
|
}
|
|
|
|
func TestReachingTheBatchSizeFlushesWithoutWaitingForTheInterval(t *testing.T) {
|
|
in := newIngest(t, http.StatusAccepted)
|
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", MaxBatchSize: 2})
|
|
defer shipper.Close()
|
|
captureStd(t, func() {
|
|
shipper.Info("a")
|
|
shipper.Info("b")
|
|
})
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for len(in.entries()) < 2 {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("a full batch was not flushed ahead of the interval")
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
func TestCloseFlushesWhatIsLeft(t *testing.T) {
|
|
in := newIngest(t, http.StatusAccepted)
|
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
|
|
captureStd(t, func() { shipper.Info("last words") })
|
|
if err := shipper.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := shipper.Close(); err != nil {
|
|
t.Fatalf("second Close error = %v", err)
|
|
}
|
|
if entries := in.entries(); len(entries) != 1 || entries[0].Message != "last words" {
|
|
t.Fatalf("entries after Close = %+v", entries)
|
|
}
|
|
}
|
|
|
|
func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) {
|
|
in := newIngest(t, http.StatusInternalServerError)
|
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
|
|
defer shipper.Close()
|
|
_, stderr := captureStd(t, func() {
|
|
shipper.Info("one")
|
|
shipper.Flush()
|
|
shipper.Info("two")
|
|
shipper.Flush()
|
|
})
|
|
if strings.Count(stderr, "answered HTTP 500") != 1 {
|
|
t.Fatalf("stderr = %q, want one rate-limited warning", stderr)
|
|
}
|
|
|
|
in.server.Close()
|
|
_, stderr = captureStd(t, func() {
|
|
shipper.Info("three")
|
|
shipper.Flush() // the sink is gone: swallowed, and still inside the warning interval
|
|
})
|
|
if strings.Contains(stderr, "send 1 entries") {
|
|
t.Fatalf("stderr = %q, want the second warning suppressed", stderr)
|
|
}
|
|
}
|
|
|
|
func TestNewAppliesDefaults(t *testing.T) {
|
|
shipper := New(Config{BaseURL: "http://omni:8090///", IngestToken: "t", Service: "svc"})
|
|
defer shipper.Close()
|
|
if shipper.url != "http://omni:8090/api/logs" || shipper.module != "svc" || shipper.threshold != LevelInfo {
|
|
t.Fatalf("url = %q, module = %q, threshold = %d", shipper.url, shipper.module, shipper.threshold)
|
|
}
|
|
if shipper.maxBatch != defaultMaxBatchSize || shipper.bufCap != defaultBufferCapacity || shipper.client == nil {
|
|
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)
|
|
}
|
|
}
|