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
@@ -78,6 +78,16 @@ type Info struct {
|
||||
// ProjectConfigurator includes it so consumers with independent databases can
|
||||
// authenticate storage requests without falling back to their own SECRET.
|
||||
CarrierNodeSecret string `json:"carrierNodeSecret,omitempty"`
|
||||
|
||||
// OmniLoggerURL is the OmniLogger instance that receives this service's log entries. Services
|
||||
// that ship logs use it with OmniLoggerIngestToken; both are optional, so a service that does not
|
||||
// ship logs ignores them.
|
||||
OmniLoggerURL string `json:"omniLoggerUrl,omitempty"`
|
||||
|
||||
// OmniLoggerIngestToken is the ingest token ProjectConfigurator minted for this receiving service.
|
||||
// OmniLogger binds it to the service's name, so it can only write this service's own entries.
|
||||
// It is a per-service credential, not a SECRET, and is never echoed back in the response.
|
||||
OmniLoggerIngestToken string `json:"omniLoggerIngestToken,omitempty"`
|
||||
}
|
||||
|
||||
// Store holds the most recently pushed Info, defaulting to whatever fallback NewStore was given
|
||||
@@ -85,9 +95,10 @@ type Info struct {
|
||||
// first push arrives - or forever, if this deployment isn't registered with a ProjectConfigurator
|
||||
// instance at all, in which case those env vars keep working exactly as before.
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
info Info
|
||||
onUpdate func(Info)
|
||||
mu sync.RWMutex
|
||||
info Info
|
||||
onUpdate func(Info)
|
||||
listeners []func(Info)
|
||||
}
|
||||
|
||||
// NewStore returns a Store seeded with fallback.
|
||||
@@ -132,6 +143,12 @@ func (s *Store) CarrierNodeURLs() []string { return s.Get().CarrierNodeURLs }
|
||||
// CarrierNodeSecret is a convenience accessor for Get().CarrierNodeSecret.
|
||||
func (s *Store) CarrierNodeSecret() string { return s.Get().CarrierNodeSecret }
|
||||
|
||||
// OmniLoggerURL is a convenience accessor for Get().OmniLoggerURL.
|
||||
func (s *Store) OmniLoggerURL() string { return s.Get().OmniLoggerURL }
|
||||
|
||||
// OmniLoggerIngestToken is a convenience accessor for Get().OmniLoggerIngestToken.
|
||||
func (s *Store) OmniLoggerIngestToken() string { return s.Get().OmniLoggerIngestToken }
|
||||
|
||||
// OnUpdate registers fn to be called (synchronously, so keep it fast) with the new Info after
|
||||
// every Set - e.g. client.SetBaseURL for an authclient.Client that isn't already reading through
|
||||
// Store on every call. Only one callback is kept; a second registration replaces the first, which
|
||||
@@ -142,6 +159,16 @@ func (s *Store) OnUpdate(fn func(Info)) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// Subscribe registers fn to be called (synchronously, so keep it fast) with the new Info after every
|
||||
// Set, in addition to OnUpdate's single callback, which it does not replace. Use it when a service
|
||||
// has more than one component that follows the pushed values, such as an authclient.Client and a
|
||||
// log shipper. Subscribers cannot be removed; they live as long as the Store.
|
||||
func (s *Store) Subscribe(fn func(Info)) {
|
||||
s.mu.Lock()
|
||||
s.listeners = append(s.listeners, fn)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// Set replaces the current Info, field by field, ignoring a blank/empty field so a partial push
|
||||
// (e.g. only carrierNodeUrl(s) changed) never clobbers the other value.
|
||||
func (s *Store) Set(next Info) {
|
||||
@@ -165,16 +192,26 @@ func (s *Store) Set(next Info) {
|
||||
if secret := strings.TrimSpace(next.CarrierNodeSecret); secret != "" {
|
||||
s.info.CarrierNodeSecret = secret
|
||||
}
|
||||
if url := strings.TrimRight(strings.TrimSpace(next.OmniLoggerURL), "/"); url != "" {
|
||||
s.info.OmniLoggerURL = url
|
||||
}
|
||||
if token := strings.TrimSpace(next.OmniLoggerIngestToken); token != "" {
|
||||
s.info.OmniLoggerIngestToken = token
|
||||
}
|
||||
if len(next.CarrierNodeURLs) > 0 {
|
||||
s.info.CarrierNodeURLs = next.CarrierNodeURLs
|
||||
s.info.CarrierNodeURL = next.CarrierNodeURLs[0]
|
||||
}
|
||||
current := s.info
|
||||
callback := s.onUpdate
|
||||
listeners := append([]func(Info){}, s.listeners...)
|
||||
s.mu.Unlock()
|
||||
if callback != nil {
|
||||
callback(current)
|
||||
}
|
||||
for _, fn := range listeners {
|
||||
fn(current)
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeInfo trims/drops blank CarrierNodeURLs entries and fills in CarrierNodeURLs from a
|
||||
@@ -228,6 +265,7 @@ func Handler(secret string, store *Store) http.HandlerFunc {
|
||||
info := store.Get()
|
||||
info.CarrierNodeSecret = ""
|
||||
info.ContentScannerSecret = ""
|
||||
info.OmniLoggerIngestToken = ""
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "info": info})
|
||||
}
|
||||
}
|
||||
@@ -235,7 +273,7 @@ func Handler(secret string, store *Store) http.HandlerFunc {
|
||||
// validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push
|
||||
// cannot point this service's clients at another scheme or at an empty host.
|
||||
func validateServiceURLs(info Info) error {
|
||||
urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL}, info.CarrierNodeURLs...)
|
||||
urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL, info.OmniLoggerURL}, info.CarrierNodeURLs...)
|
||||
for _, raw := range urls {
|
||||
value := strings.TrimSpace(raw)
|
||||
if value == "" {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package coreconfig
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const omniTestSecret = "omnilogger-fields-test-secret-0123456789"
|
||||
|
||||
func TestOmniLoggerFieldsKeepTheirValueAcrossPartialPushes(t *testing.T) {
|
||||
store := NewStore(Info{})
|
||||
store.Set(Info{OmniLoggerURL: "https://logs.example.com/", OmniLoggerIngestToken: "token-one"})
|
||||
if store.OmniLoggerURL() != "https://logs.example.com" || store.OmniLoggerIngestToken() != "token-one" {
|
||||
t.Fatalf("got url=%q token=%q", store.OmniLoggerURL(), store.OmniLoggerIngestToken())
|
||||
}
|
||||
store.Set(Info{AuthGuardURL: "https://auth.example.com"})
|
||||
if store.OmniLoggerIngestToken() != "token-one" {
|
||||
t.Fatal("a push without a token cleared the stored token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerNeverEchoesTheOmniLoggerIngestToken(t *testing.T) {
|
||||
store := NewStore(Info{})
|
||||
handler := Handler(omniTestSecret, store)
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/core-services/internal",
|
||||
strings.NewReader(`{"omniLoggerUrl":"https://logs.example.com","omniLoggerIngestToken":"token-two"}`))
|
||||
request.Header.Set("X-Internal-Auth", omniTestSecret)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d: %s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "token-two") {
|
||||
t.Fatalf("response echoed the ingest token: %s", response.Body.String())
|
||||
}
|
||||
if store.OmniLoggerIngestToken() != "token-two" {
|
||||
t.Fatal("the pushed token was not stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOmniLoggerURLMustBeHTTPWithAHost(t *testing.T) {
|
||||
if err := validateServiceURLs(Info{OmniLoggerURL: "ftp://logs.example.com"}); err == nil {
|
||||
t.Fatal("accepted a non-http OmniLogger URL")
|
||||
}
|
||||
if err := validateServiceURLs(Info{OmniLoggerURL: "https://"}); err == nil {
|
||||
t.Fatal("accepted an OmniLogger URL without a host")
|
||||
}
|
||||
if err := validateServiceURLs(Info{OmniLoggerURL: "http://omnilogger:8080"}); err != nil {
|
||||
t.Fatalf("rejected a valid OmniLogger URL: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package logshipper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Logger writes each line to the console exactly as the standard log package would, and ships it to
|
||||
// OmniLogger at the severity the caller names. Use it where the caller knows the severity, instead of
|
||||
// Writer, which has to guess the severity from the wording of the line.
|
||||
//
|
||||
// The console writer must be the writer the service logs to without the shipper, such as os.Stderr, so a
|
||||
// line is never shipped twice. Create the Logger after the service has set its log flags and prefix, which
|
||||
// NewLogger copies. A nil shipper makes the Logger console-only.
|
||||
type Logger struct {
|
||||
console *log.Logger
|
||||
shipper *Shipper
|
||||
}
|
||||
|
||||
// NewLogger returns a Logger that writes to console with the standard log flags and prefix in effect now.
|
||||
func NewLogger(console io.Writer, shipper *Shipper) *Logger {
|
||||
return &Logger{console: log.New(console, log.Prefix(), log.Flags()), shipper: shipper}
|
||||
}
|
||||
|
||||
// output writes one line to the console and ships it. The call depth of 3 makes the console's file and line
|
||||
// flags name the caller of Debugf, Infof, and the other methods, not this file.
|
||||
func (l *Logger) output(sev Level, format string, args ...any) {
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
_ = l.console.Output(3, msg)
|
||||
if l.shipper != nil {
|
||||
l.shipper.Ship(sev, nil, strings.TrimRight(msg, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// Debugf logs at debug severity.
|
||||
func (l *Logger) Debugf(format string, args ...any) { l.output(LevelDebug, format, args...) }
|
||||
|
||||
// Infof logs at info severity.
|
||||
func (l *Logger) Infof(format string, args ...any) { l.output(LevelInfo, format, args...) }
|
||||
|
||||
// Warnf logs at warn severity.
|
||||
func (l *Logger) Warnf(format string, args ...any) { l.output(LevelWarn, format, args...) }
|
||||
|
||||
// Errorf logs at error severity.
|
||||
func (l *Logger) Errorf(format string, args ...any) { l.output(LevelError, format, args...) }
|
||||
|
||||
// Criticalf logs at critical severity.
|
||||
func (l *Logger) Criticalf(format string, args ...any) { l.output(LevelCritical, format, args...) }
|
||||
@@ -0,0 +1,86 @@
|
||||
package logshipper
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var timestampPattern = regexp.MustCompile(`\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} `)
|
||||
|
||||
// The console output must match what the standard log package writes with the same flags and prefix.
|
||||
func TestLoggerConsoleOutputMatchesTheStandardLogger(t *testing.T) {
|
||||
oldFlags, oldPrefix := log.Flags(), log.Prefix()
|
||||
log.SetFlags(log.LstdFlags)
|
||||
log.SetPrefix("svc: ")
|
||||
defer log.SetFlags(oldFlags)
|
||||
defer log.SetPrefix(oldPrefix)
|
||||
|
||||
var console, reference bytes.Buffer
|
||||
logger := NewLogger(&console, nil)
|
||||
logger.Infof("started on %s", ":8080")
|
||||
logger.Errorf("push failed: %v", "boom")
|
||||
std := log.New(&reference, log.Prefix(), log.Flags())
|
||||
std.Printf("started on %s", ":8080")
|
||||
std.Printf("push failed: %v", "boom")
|
||||
|
||||
stripTimes := func(s string) string {
|
||||
return timestampPattern.ReplaceAllString(s, "")
|
||||
}
|
||||
if stripTimes(console.String()) != stripTimes(reference.String()) {
|
||||
t.Fatalf("console = %q, want the standard logger's %q (apart from timestamps)", console.String(), reference.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Each method ships at its own severity, and nothing reaches the console twice.
|
||||
func TestLoggerShipsEachLineAtItsSeverityOnce(t *testing.T) {
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "debug"})
|
||||
defer shipper.Close()
|
||||
|
||||
var console bytes.Buffer
|
||||
logger := NewLogger(&console, shipper)
|
||||
logger.Debugf("d")
|
||||
logger.Infof("i")
|
||||
logger.Warnf("w")
|
||||
logger.Errorf("e")
|
||||
logger.Criticalf("c")
|
||||
shipper.Flush()
|
||||
|
||||
if n := strings.Count(console.String(), "\n"); n != 5 {
|
||||
t.Fatalf("console got %d lines, want 5: %q", n, console.String())
|
||||
}
|
||||
entries := in.entries()
|
||||
want := map[string]string{"d": "debug", "i": "info", "w": "warn", "e": "error", "c": "critical"}
|
||||
if len(entries) != len(want) {
|
||||
t.Fatalf("shipped %d entries, want %d: %+v", len(entries), len(want), entries)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if want[e.Message] != e.Level {
|
||||
t.Errorf("%q shipped at %q, want %q", e.Message, e.Level, want[e.Message])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A nil shipper keeps the Logger console-only, and the threshold still applies to what is shipped.
|
||||
func TestLoggerWithoutShipperIsConsoleOnlyAndThresholdApplies(t *testing.T) {
|
||||
var console bytes.Buffer
|
||||
NewLogger(&console, nil).Debugf("still printed")
|
||||
if !strings.Contains(console.String(), "still printed") {
|
||||
t.Fatalf("console-only logger dropped a line: %q", console.String())
|
||||
}
|
||||
|
||||
in := newIngest(t, http.StatusAccepted)
|
||||
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"})
|
||||
defer shipper.Close()
|
||||
NewLogger(&bytes.Buffer{}, shipper).Warnf("below threshold")
|
||||
shipper.Flush()
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if n := len(in.entries()); n != 0 {
|
||||
t.Fatalf("shipped %d entries below the threshold", n)
|
||||
}
|
||||
}
|
||||
+271
-23
@@ -25,11 +25,16 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||
)
|
||||
|
||||
// Level mirrors internal/logging's severity scale in every service's local
|
||||
@@ -95,8 +100,10 @@ type Config struct {
|
||||
// BaseURL is OmniLogger's base URL, e.g. "http://omnilogger:8090".
|
||||
// Required.
|
||||
BaseURL string
|
||||
// IngestToken is the shared INGEST_TOKEN bearer secret OmniLogger
|
||||
// requires (see OmniLogger/README.md). Required.
|
||||
// IngestToken is this service's OmniLogger ingest token: a per-service
|
||||
// bearer secret an administrator creates in OmniLogger and bound to
|
||||
// Service (see OmniLogger/README.md). OmniLogger rejects entries whose
|
||||
// service differs from the token's bound service. Required.
|
||||
IngestToken string
|
||||
// Service is this process's service name as reported to OmniLogger,
|
||||
// e.g. "playhouse" or "outdoorgames-server-go". Required.
|
||||
@@ -152,10 +159,14 @@ type Shipper struct {
|
||||
logAll bool
|
||||
|
||||
service string
|
||||
url string
|
||||
token string
|
||||
client *http.Client
|
||||
|
||||
// credMu guards url and token, which SetCredentials can replace while the Shipper runs. An empty
|
||||
// url means shipping is disabled.
|
||||
credMu sync.RWMutex
|
||||
url string
|
||||
token string
|
||||
|
||||
maxBatch int
|
||||
bufCap int
|
||||
|
||||
@@ -201,8 +212,6 @@ func New(cfg Config) *Shipper {
|
||||
threshold: levelOf(cfg.Level),
|
||||
logAll: cfg.LogAll,
|
||||
service: cfg.Service,
|
||||
url: strings.TrimRight(cfg.BaseURL, "/") + "/api/logs",
|
||||
token: cfg.IngestToken,
|
||||
client: client,
|
||||
maxBatch: maxBatch,
|
||||
bufCap: bufCap,
|
||||
@@ -211,10 +220,53 @@ func New(cfg Config) *Shipper {
|
||||
doneCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
s.SetCredentials(cfg.BaseURL, cfg.IngestToken)
|
||||
go s.loop(flushInterval)
|
||||
return s
|
||||
}
|
||||
|
||||
// SetCredentials sets where, and as which ingest token, the Shipper sends entries. It can be called at
|
||||
// any time, for example when ProjectConfigurator pushes a new token, and takes effect from the next
|
||||
// flush. An empty baseURL or token disables shipping: entries are no longer buffered, anything already
|
||||
// buffered is discarded, and the local console output carries on as before.
|
||||
func (s *Shipper) SetCredentials(baseURL, token string) {
|
||||
token = strings.TrimSpace(token)
|
||||
url := ""
|
||||
if base := strings.TrimRight(strings.TrimSpace(baseURL), "/"); base != "" && token != "" {
|
||||
url = base + "/api/logs"
|
||||
}
|
||||
s.credMu.Lock()
|
||||
s.url = url
|
||||
s.token = token
|
||||
s.credMu.Unlock()
|
||||
if url == "" {
|
||||
s.mu.Lock()
|
||||
s.buffer = nil
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Follow keeps the Shipper's endpoint and ingest token in step with ProjectConfigurator's pushes. A
|
||||
// push that carries both an OmniLogger URL and an ingest token replaces the endpoint and token. Any other
|
||||
// push, including the first one after a restart, leaves the current settings alone, so a service that was
|
||||
// configured from its environment keeps shipping until ProjectConfigurator supplies both values.
|
||||
func (s *Shipper) Follow(store *coreconfig.Store) {
|
||||
apply := func(info coreconfig.Info) {
|
||||
if info.OmniLoggerURL != "" && info.OmniLoggerIngestToken != "" {
|
||||
s.SetCredentials(info.OmniLoggerURL, info.OmniLoggerIngestToken)
|
||||
}
|
||||
}
|
||||
apply(store.Get())
|
||||
store.Subscribe(apply)
|
||||
}
|
||||
|
||||
// credentials returns the current endpoint and token.
|
||||
func (s *Shipper) credentials() (url, token string) {
|
||||
s.credMu.RLock()
|
||||
defer s.credMu.RUnlock()
|
||||
return s.url, s.token
|
||||
}
|
||||
|
||||
func (s *Shipper) loop(flushInterval time.Duration) {
|
||||
defer close(s.doneCh)
|
||||
ticker := time.NewTicker(flushInterval)
|
||||
@@ -241,11 +293,41 @@ func (s *Shipper) requestFlush() {
|
||||
}
|
||||
}
|
||||
|
||||
// OmniLogger rejects a whole POST /api/logs batch when any one entry breaks its limits, so every
|
||||
// entry is clamped to them before it is buffered. These mirror OmniLogger's MaxMessageBytes and
|
||||
// MaxContextBytes; a message is cut with a marker, and an oversized or unshippable context is dropped
|
||||
// and replaced with a marker object, so the entry itself still reaches OmniLogger.
|
||||
const (
|
||||
maxMessageBytes = 8 * 1024
|
||||
maxContextBytes = 16 * 1024
|
||||
truncatedMarker = " [truncated]"
|
||||
droppedContext = `{"context_dropped":true}`
|
||||
)
|
||||
|
||||
func clampEntry(e wireEntry) wireEntry {
|
||||
if len(e.Message) > maxMessageBytes {
|
||||
cut := maxMessageBytes - len(truncatedMarker)
|
||||
for cut > 0 && !utf8.RuneStart(e.Message[cut]) {
|
||||
cut--
|
||||
}
|
||||
e.Message = e.Message[:cut] + truncatedMarker
|
||||
}
|
||||
// OmniLogger refuses a NUL in context, which json.Marshal writes as \u0000.
|
||||
if len(e.Context) > maxContextBytes || bytes.Contains(e.Context, []byte(`\u0000`)) {
|
||||
e.Context = json.RawMessage(droppedContext)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// enqueue appends one entry to the buffer, dropping the incoming entry
|
||||
// (rather than blocking the caller or evicting older entries) once the
|
||||
// buffer is full. This is the sole non-blocking guarantee this package
|
||||
// makes: a caller's Debug/Info/... call never waits on network I/O.
|
||||
func (s *Shipper) enqueue(entry wireEntry) {
|
||||
if url, _ := s.credentials(); url == "" {
|
||||
return
|
||||
}
|
||||
entry = clampEntry(entry)
|
||||
s.mu.Lock()
|
||||
full := len(s.buffer) >= s.bufCap
|
||||
if !full {
|
||||
@@ -268,6 +350,7 @@ func (s *Shipper) enqueue(entry wireEntry) {
|
||||
// design: a host application must never fail, panic, or slow down because
|
||||
// its log sink is unreachable.
|
||||
func (s *Shipper) flush() {
|
||||
url, token := s.credentials()
|
||||
s.mu.Lock()
|
||||
if len(s.buffer) == 0 {
|
||||
s.mu.Unlock()
|
||||
@@ -276,34 +359,129 @@ func (s *Shipper) flush() {
|
||||
batch := s.buffer
|
||||
s.buffer = nil
|
||||
s.mu.Unlock()
|
||||
|
||||
body, err := json.Marshal(batch)
|
||||
if err != nil {
|
||||
s.warnOnce(fmt.Errorf("logshipper: marshal batch: %w", err))
|
||||
if url == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// A backlog can hold up to bufCap entries, far more than OmniLogger accepts in one request, so the
|
||||
// buffer is sent as several requests, each within maxRequestEntries and maxRequestBytes. When a request
|
||||
// fails for a reason that may pass (no connection, a server error, or too many requests), the failed
|
||||
// entries and everything after them go back to the buffer and are sent again on the next flush. A request
|
||||
// OmniLogger rejects outright is dropped, because sending it again would fail the same way.
|
||||
for _, chunk := range encodeBatches(batch) {
|
||||
if s.send(url, token, chunk.payload, chunk.entries) {
|
||||
s.requeue(batch[chunk.start:])
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Request limits for one POST /api/logs. OmniLogger refuses a request with more than 1000 entries or a
|
||||
// body over 2 MiB, and it refuses the whole request when one entry is out of bounds, so every request
|
||||
// stays well inside both.
|
||||
const (
|
||||
maxRequestEntries = 100
|
||||
maxRequestBytes = 1 << 20
|
||||
)
|
||||
|
||||
type encodedBatch struct {
|
||||
payload []byte
|
||||
entries int
|
||||
// start is the index in the flushed batch of this request's first entry.
|
||||
start int
|
||||
}
|
||||
|
||||
// encodeBatches marshals each entry once and packs the results into JSON array bodies, starting a new
|
||||
// body when the current one reaches maxRequestEntries or would pass maxRequestBytes. An entry that
|
||||
// cannot be marshaled is dropped, so one bad entry never blocks the rest.
|
||||
func encodeBatches(batch []wireEntry) []encodedBatch {
|
||||
var out []encodedBatch
|
||||
var body bytes.Buffer
|
||||
count := 0
|
||||
start := 0
|
||||
closeBody := func() {
|
||||
if count == 0 {
|
||||
return
|
||||
}
|
||||
body.WriteByte(']')
|
||||
out = append(out, encodedBatch{payload: append([]byte(nil), body.Bytes()...), entries: count, start: start})
|
||||
body.Reset()
|
||||
count = 0
|
||||
}
|
||||
for i, entry := range batch {
|
||||
raw, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if count > 0 && (count >= maxRequestEntries || body.Len()+len(raw)+2 > maxRequestBytes) {
|
||||
closeBody()
|
||||
}
|
||||
if count == 0 {
|
||||
body.WriteByte('[')
|
||||
start = i
|
||||
} else {
|
||||
body.WriteByte(',')
|
||||
}
|
||||
body.Write(raw)
|
||||
count++
|
||||
}
|
||||
closeBody()
|
||||
return out
|
||||
}
|
||||
|
||||
// requeue puts entries that failed to send back at the front of the buffer, so the next flush sends them
|
||||
// before newer entries. The buffer stays within bufCap: when the requeued entries and the buffer do not all
|
||||
// fit, the newest entries are dropped, as enqueue drops them when the buffer is full.
|
||||
func (s *Shipper) requeue(entries []wireEntry) {
|
||||
s.mu.Lock()
|
||||
combined := make([]wireEntry, 0, len(entries)+len(s.buffer))
|
||||
combined = append(combined, entries...)
|
||||
combined = append(combined, s.buffer...)
|
||||
dropped := 0
|
||||
if len(combined) > s.bufCap {
|
||||
dropped = len(combined) - s.bufCap
|
||||
combined = combined[:s.bufCap]
|
||||
}
|
||||
s.buffer = combined
|
||||
s.mu.Unlock()
|
||||
if dropped > 0 {
|
||||
s.warnOnce(fmt.Errorf("logshipper: buffer full while retrying, dropping %d log entries for service %q", dropped, s.service))
|
||||
}
|
||||
}
|
||||
|
||||
// send posts one encoded batch and reports whether it failed for a reason that may pass, in which case the
|
||||
// caller keeps the entries for a later retry. A request OmniLogger rejects is reported and dropped. Failures are
|
||||
// otherwise swallowed by design: a host application must never fail, panic, or slow down because its log sink
|
||||
// is unreachable.
|
||||
func (s *Shipper) send(url, token string, body []byte, entries int) (retry bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
s.warnOnce(fmt.Errorf("logshipper: build request: %w", err))
|
||||
return
|
||||
return false
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+s.token)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s: %w", len(batch), s.url, err))
|
||||
return
|
||||
s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s, will retry: %w", entries, url, err))
|
||||
return true
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
s.warnOnce(fmt.Errorf("logshipper: OmniLogger rejected %d entries: HTTP %d", len(batch), resp.StatusCode))
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
return false
|
||||
}
|
||||
retry = resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500
|
||||
if retry {
|
||||
s.warnOnce(fmt.Errorf("logshipper: OmniLogger answered HTTP %d for %d entries, will retry", resp.StatusCode, entries))
|
||||
} else {
|
||||
s.warnOnce(fmt.Errorf("logshipper: OmniLogger rejected %d entries: HTTP %d", entries, resp.StatusCode))
|
||||
}
|
||||
return retry
|
||||
}
|
||||
|
||||
// warnOnce prints a local stderr warning at most once per minute, no matter
|
||||
@@ -350,7 +528,7 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
|
||||
}
|
||||
now := time.Now()
|
||||
msg := formatArgs(args)
|
||||
upper, lower := sevName(sev)
|
||||
upper, _ := sevName(sev)
|
||||
|
||||
line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s",
|
||||
now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg)
|
||||
@@ -368,10 +546,26 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
|
||||
}
|
||||
}
|
||||
|
||||
// Unlike the local-only verbose dump above (which scrubs IDs for
|
||||
// readability), the context shipped to OmniLogger is sent unscrubbed:
|
||||
// the whole point of centralizing logs is cross-service correlation by
|
||||
// request/user/entity ID, so stripping IDs here would defeat that.
|
||||
s.shipEntry(sev, ctx, msg, now)
|
||||
}
|
||||
|
||||
// Ship queues one entry for OmniLogger at severity sev without printing it locally. Use it where the host
|
||||
// already prints its own lines, such as a zap or slog core that tees to OmniLogger: the console is not
|
||||
// doubled, and the entry keeps its real severity, where Writer ships everything as info. The threshold
|
||||
// applies. Context is sent unscrubbed, as in emit.
|
||||
func (s *Shipper) Ship(sev Level, ctx map[string]any, args ...any) {
|
||||
if sev < s.threshold {
|
||||
return
|
||||
}
|
||||
s.shipEntry(sev, ctx, formatArgs(args), time.Now())
|
||||
}
|
||||
|
||||
// shipEntry buffers one already-formatted entry for OmniLogger.
|
||||
func (s *Shipper) shipEntry(sev Level, ctx map[string]any, msg string, now time.Time) {
|
||||
_, lower := sevName(sev)
|
||||
// The context shipped to OmniLogger is sent unscrubbed: the whole point of centralizing logs is
|
||||
// cross-service correlation by request/user/entity ID, so stripping IDs here would defeat that. Only
|
||||
// the local verbose dump scrubs them.
|
||||
var rawCtx json.RawMessage
|
||||
if ctx != nil {
|
||||
if b, err := json.Marshal(ctx); err == nil {
|
||||
@@ -383,10 +577,64 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
|
||||
Level: lower,
|
||||
Message: msg,
|
||||
Context: rawCtx,
|
||||
OccurredAt: now,
|
||||
OccurredAt: now.UTC().Truncate(time.Millisecond),
|
||||
})
|
||||
}
|
||||
|
||||
// Writer returns an io.Writer that ships every non-empty line written to it to OmniLogger for this
|
||||
// Shipper's service. It prints nothing locally, so it is meant to be paired with the console writer, e.g.
|
||||
// log.SetOutput(io.MultiWriter(os.Stderr, shipper.Writer())), which keeps the existing stdout/stderr
|
||||
// output and mirrors the lines to OmniLogger. The standard library log package carries no severity, so
|
||||
// each line's level comes from InferLevel. Where a host knows the real level, use Ship instead.
|
||||
func (s *Shipper) Writer() io.Writer {
|
||||
return lineWriter{s: s}
|
||||
}
|
||||
|
||||
type lineWriter struct {
|
||||
s *Shipper
|
||||
}
|
||||
|
||||
func (w lineWriter) Write(p []byte) (int, error) {
|
||||
now := time.Now()
|
||||
for _, line := range strings.Split(string(p), "\n") {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
if strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
}
|
||||
sev := InferLevel(line)
|
||||
if sev < w.s.threshold {
|
||||
continue
|
||||
}
|
||||
w.s.shipEntry(sev, nil, line, now)
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// severityRules are checked in order, and the first rule whose words appear in a line sets its level.
|
||||
// Each word matches as a whole word, case-insensitively.
|
||||
var severityRules = []struct {
|
||||
level Level
|
||||
pattern *regexp.Regexp
|
||||
}{
|
||||
{LevelCritical, regexp.MustCompile(`(?i)\b(panic|fatal|critical)\b`)},
|
||||
{LevelError, regexp.MustCompile(`(?i)\b(error|errors|failed|failure|failures|could not|cannot|unable to)\b`)},
|
||||
{LevelWarn, regexp.MustCompile(`(?i)\b(warn|warning|skipped|unavailable|retry|retrying|timed out|timeout)\b`)},
|
||||
}
|
||||
|
||||
// InferLevel guesses the severity of a plain text line from its wording, for hosts whose logging carries no
|
||||
// level, such as the standard library log package. Words such as "panic" or "fatal" give critical; "error",
|
||||
// "failed", "could not", and "cannot" give error; "warning", "skipped", "unavailable", "retry", and "timeout"
|
||||
// give warn; any other line is info. A line that mentions an error without failing, such as "no errors
|
||||
// found", is classified as an error too. Use Ship where the real level is known.
|
||||
func InferLevel(line string) Level {
|
||||
for _, rule := range severityRules {
|
||||
if rule.pattern.MatchString(line) {
|
||||
return rule.level
|
||||
}
|
||||
}
|
||||
return LevelInfo
|
||||
}
|
||||
|
||||
func formatArgs(args []any) string {
|
||||
parts := make([]string, 0, len(args))
|
||||
for _, a := range args {
|
||||
|
||||
@@ -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