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
+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 {
|
||||
|
||||
Reference in new issue
Block a user