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
@@ -28,9 +28,16 @@ from .authclient import (
|
||||
token_from_request,
|
||||
)
|
||||
from .config import DatabaseConfig, database_url_from_env
|
||||
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches, internal_secret_usable
|
||||
from .coreconfig import (
|
||||
MIN_INTERNAL_SECRET_LENGTH,
|
||||
follow_omnilogger,
|
||||
handle_core_services_push,
|
||||
internal_secret_matches,
|
||||
internal_secret_usable,
|
||||
)
|
||||
from .coreconfig import Info as CoreConfigInfo
|
||||
from .coreconfig import Store as CoreConfigStore
|
||||
from .logshipper import OmniLoggerHandler, Shipper
|
||||
from .postgres import Database
|
||||
from .tokens import hash_token, new_session_token
|
||||
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step
|
||||
@@ -46,6 +53,8 @@ __all__ = [
|
||||
"token_from_request",
|
||||
"CoreConfigInfo",
|
||||
"CoreConfigStore",
|
||||
"follow_omnilogger",
|
||||
"handle_core_services_push",
|
||||
"internal_secret_matches",
|
||||
"internal_secret_usable",
|
||||
"MIN_INTERNAL_SECRET_LENGTH",
|
||||
@@ -65,6 +74,8 @@ __all__ = [
|
||||
"hash_token",
|
||||
"new_session_token",
|
||||
"normalize_role",
|
||||
"OmniLoggerHandler",
|
||||
"Shipper",
|
||||
"password_hash_needs_upgrade",
|
||||
"totp_provisioning_uri",
|
||||
"verify_and_upgrade_password",
|
||||
|
||||
@@ -7,22 +7,28 @@ ProjectConfigurator/README.md's "Pushing core service info to other
|
||||
projects" section for the wire contract this module implements the
|
||||
receiving end of.
|
||||
|
||||
It also carries OmniLogger's URL and this service's ingest token (see `Info`).
|
||||
`follow_omnilogger` keeps a log shipper's credentials in step with those pushes,
|
||||
and `handle_core_services_push` is the framework-neutral body of the
|
||||
PUT /api/core-services/internal route.
|
||||
|
||||
Framework-agnostic, like the rest of this package (see the top-level
|
||||
README's "HTTP framework adapters stay in each service" note): this module
|
||||
has no HTTP server of its own. A service wires the actual
|
||||
has no HTTP server of its own. A service mounts the actual
|
||||
PUT /api/core-services/internal route in its own framework (FastAPI,
|
||||
aiohttp, ...), gated behind its own SECRET check the same
|
||||
way its other internal-service routes already are, decodes the JSON body
|
||||
into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment
|
||||
for a minimal FastAPI example.
|
||||
aiohttp, ...) and passes the raw body to `handle_core_services_push`, which
|
||||
returns (status, body) for the service to send -- see that function's doc
|
||||
comment for a minimal FastAPI example.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import hmac
|
||||
import json
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, Optional
|
||||
from typing import Callable, Optional, Protocol
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
MIN_INTERNAL_SECRET_LENGTH = 16
|
||||
@@ -76,6 +82,12 @@ class Info:
|
||||
# registered, in priority order (the first entry is the same as
|
||||
# carrier_node_url).
|
||||
carrier_node_urls: list = field(default_factory=list)
|
||||
# omni_logger_url is OmniLogger's base URL, the instance that receives this
|
||||
# service's log entries (Go: coreconfig.Info.OmniLoggerURL).
|
||||
omni_logger_url: str = ""
|
||||
# omni_logger_ingest_token is this service's OmniLogger ingest token. repr=False
|
||||
# keeps it out of logs and reprs. to_json never includes it (see below).
|
||||
omni_logger_ingest_token: str = field(default="", repr=False)
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, data: dict) -> "Info":
|
||||
@@ -88,13 +100,18 @@ class Info:
|
||||
auth_guard_url=str(data.get("authGuardUrl") or "").strip(),
|
||||
carrier_node_url=urls[0] if urls else "",
|
||||
carrier_node_urls=urls,
|
||||
omni_logger_url=str(data.get("omniLoggerUrl") or "").strip(),
|
||||
omni_logger_ingest_token=str(data.get("omniLoggerIngestToken") or "").strip(),
|
||||
)
|
||||
|
||||
def to_json(self) -> dict:
|
||||
# omniLoggerIngestToken is deliberately left out: a to_json result may be sent back
|
||||
# to a caller, and the token must never be echoed.
|
||||
return {
|
||||
"authGuardUrl": self.auth_guard_url,
|
||||
"carrierNodeUrl": self.carrier_node_url,
|
||||
"carrierNodeUrls": list(self.carrier_node_urls),
|
||||
"omniLoggerUrl": self.omni_logger_url,
|
||||
}
|
||||
|
||||
|
||||
@@ -110,6 +127,7 @@ class Store:
|
||||
self._lock = threading.Lock()
|
||||
self._info = _normalize(fallback or Info())
|
||||
self._on_update: Optional[Callable[[Info], None]] = None
|
||||
self._subscribers: list[Callable[[Info], None]] = []
|
||||
|
||||
def get(self) -> Info:
|
||||
with self._lock:
|
||||
@@ -136,26 +154,25 @@ class Store:
|
||||
with self._lock:
|
||||
self._on_update = fn
|
||||
|
||||
def subscribe(self, fn: Callable[[Info], None]) -> None:
|
||||
"""Registers fn to be called (synchronously, so keep it fast) with the new Info after every
|
||||
set(), in addition to on_update's single callback, which it does not replace. Use it when
|
||||
more than one component follows the pushed values, such as an AuthClient and a log shipper
|
||||
(see follow_omnilogger). Subscribers cannot be removed; they live as long as the Store."""
|
||||
with self._lock:
|
||||
self._subscribers.append(fn)
|
||||
|
||||
def set(self, next_info: Info) -> Info:
|
||||
"""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. Returns the resulting
|
||||
Info. Every URL must be an http or https URL with a host; otherwise
|
||||
nothing is changed and ValueError is raised. Minimal FastAPI usage:
|
||||
|
||||
@app.put("/api/core-services/internal")
|
||||
async def push_core_services(request: Request):
|
||||
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
|
||||
raise HTTPException(status_code=401)
|
||||
body = await request.json()
|
||||
try:
|
||||
info = core_config_store.set(Info.from_json(body))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
return {"ok": True, "info": info.to_json()}
|
||||
"""
|
||||
Info (a copy). Every URL must be an http or https URL with a host;
|
||||
otherwise nothing is changed and ValueError is raised. The receiving
|
||||
route is normally handle_core_services_push, which calls this; see its
|
||||
doc comment for the FastAPI wiring."""
|
||||
next_info = _normalize(next_info)
|
||||
for url in [next_info.auth_guard_url, *next_info.carrier_node_urls]:
|
||||
urls = [next_info.auth_guard_url, next_info.omni_logger_url, *next_info.carrier_node_urls]
|
||||
for url in urls:
|
||||
if url and not _is_service_url(url):
|
||||
raise ValueError(
|
||||
f"core service URL must be an http or https URL with a host: {url}"
|
||||
@@ -166,10 +183,19 @@ class Store:
|
||||
if next_info.carrier_node_urls:
|
||||
self._info.carrier_node_urls = next_info.carrier_node_urls
|
||||
self._info.carrier_node_url = next_info.carrier_node_urls[0]
|
||||
current = self._info
|
||||
if next_info.omni_logger_url:
|
||||
self._info.omni_logger_url = next_info.omni_logger_url
|
||||
if next_info.omni_logger_ingest_token:
|
||||
self._info.omni_logger_ingest_token = next_info.omni_logger_ingest_token
|
||||
current = dataclasses.replace(
|
||||
self._info, carrier_node_urls=list(self._info.carrier_node_urls)
|
||||
)
|
||||
callback = self._on_update
|
||||
subscribers = list(self._subscribers)
|
||||
if callback is not None:
|
||||
callback(current)
|
||||
for fn in subscribers:
|
||||
fn(current)
|
||||
return current
|
||||
|
||||
|
||||
@@ -181,4 +207,89 @@ def _normalize(info: Info) -> Info:
|
||||
auth_guard_url=info.auth_guard_url.strip(),
|
||||
carrier_node_url=cleaned[0] if cleaned else "",
|
||||
carrier_node_urls=cleaned,
|
||||
omni_logger_url=info.omni_logger_url.strip().rstrip("/"),
|
||||
omni_logger_ingest_token=info.omni_logger_ingest_token.strip(),
|
||||
)
|
||||
|
||||
|
||||
class SupportsSetCredentials(Protocol):
|
||||
"""What follow_omnilogger needs from a log shipper: logshipper.Shipper satisfies it."""
|
||||
|
||||
def set_credentials(self, base_url: str, token: str) -> None: ...
|
||||
|
||||
|
||||
def follow_omnilogger(store: Store, shipper: SupportsSetCredentials) -> None:
|
||||
"""Keeps shipper's OmniLogger endpoint and ingest token in step with pushes, as Go's
|
||||
logshipper.Shipper.Follow does. Whenever a set() leaves both omniLoggerUrl and
|
||||
omniLoggerIngestToken non-empty in the store, shipper.set_credentials(url, token) is called.
|
||||
Until both are stored, the shipper is left alone, so a push with a token but no URL never
|
||||
disables or re-points an environment-configured shipper.
|
||||
|
||||
Call it once at startup, after creating the shipper. The Store must not be seeded with
|
||||
OmniLogger values from the environment: those belong to the shipper, and seeding them would
|
||||
make a token-only push re-point it."""
|
||||
|
||||
def apply(info: Info) -> None:
|
||||
if info.omni_logger_url and info.omni_logger_ingest_token:
|
||||
shipper.set_credentials(info.omni_logger_url, info.omni_logger_ingest_token)
|
||||
|
||||
apply(store.get())
|
||||
store.subscribe(apply)
|
||||
|
||||
|
||||
MAX_PUSH_BODY_BYTES = 4096
|
||||
"""Largest PUT /api/core-services/internal body that handle_core_services_push reads."""
|
||||
|
||||
PUSH_AUTH_ERROR = "internal service authentication required"
|
||||
PUSH_INVALID_JSON_ERROR = "invalid JSON body"
|
||||
PUSH_INVALID_URL_ERROR = "core service URL must be an http or https URL with a host"
|
||||
|
||||
|
||||
def handle_core_services_push(
|
||||
store: Store,
|
||||
secret: Optional[str],
|
||||
provided_auth: Optional[str],
|
||||
body: bytes,
|
||||
) -> tuple[int, dict]:
|
||||
"""The framework-neutral body of PUT /api/core-services/internal, the route
|
||||
ProjectConfigurator pushes to. It returns (status, json_body) for the service to send.
|
||||
|
||||
- provided_auth is the X-Internal-Auth header (None when absent). A provided value that does
|
||||
not equal secret, or any secret that is not usable (see internal_secret_usable), gets 401.
|
||||
- body is the raw request body. Over MAX_PUSH_BODY_BYTES, or not a JSON object, gets 400.
|
||||
- A non-empty omniLoggerUrl, authGuardUrl or carrierNodeUrl(s) value that is not an http or
|
||||
https URL with a host gets 400 (Store.set validates them). Other fields are ignored.
|
||||
- Success is 200 {"ok": True}. The response never includes the ingest token.
|
||||
|
||||
Mount it at PUT /api/core-services/internal, for example in FastAPI:
|
||||
|
||||
@app.put("/api/core-services/internal")
|
||||
async def push_core_services(request: Request):
|
||||
status, body = handle_core_services_push(
|
||||
core_config_store, SECRET, request.headers.get("X-Internal-Auth"),
|
||||
await request.body(),
|
||||
)
|
||||
return JSONResponse(body, status_code=status)
|
||||
"""
|
||||
if not internal_secret_matches(provided_auth, secret):
|
||||
return 401, {"error": PUSH_AUTH_ERROR}
|
||||
if len(body) > MAX_PUSH_BODY_BYTES:
|
||||
return 400, {"error": PUSH_INVALID_JSON_ERROR}
|
||||
try:
|
||||
data = json.loads(body)
|
||||
except (ValueError, RecursionError): # JSONDecodeError and UnicodeDecodeError are ValueErrors
|
||||
return 400, {"error": PUSH_INVALID_JSON_ERROR}
|
||||
if not isinstance(data, dict):
|
||||
return 400, {"error": PUSH_INVALID_JSON_ERROR}
|
||||
# Info.from_json reads these fields; a wrong type gets 400 here instead of an error inside it.
|
||||
for key in ("authGuardUrl", "carrierNodeUrl", "omniLoggerUrl", "omniLoggerIngestToken"):
|
||||
if data.get(key) is not None and not isinstance(data[key], str):
|
||||
return 400, {"error": PUSH_INVALID_JSON_ERROR}
|
||||
urls = data.get("carrierNodeUrls")
|
||||
if urls is not None and not isinstance(urls, list):
|
||||
return 400, {"error": PUSH_INVALID_JSON_ERROR}
|
||||
try:
|
||||
store.set(Info.from_json(data))
|
||||
except ValueError:
|
||||
return 400, {"error": PUSH_INVALID_URL_ERROR}
|
||||
return 200, {"ok": True}
|
||||
@@ -0,0 +1,415 @@
|
||||
"""Client-side adapter for OmniLogger, the workspace's central log sink. Python counterpart of
|
||||
shared/backend/logshipper (Go), and it follows the same wire contract.
|
||||
|
||||
Shipping is additive. A service keeps its own console logging unchanged and adds an
|
||||
`OmniLoggerHandler` next to its existing handlers, so each record also reaches OmniLogger.
|
||||
`Shipper` never prints anything itself.
|
||||
|
||||
Shipping is enabled only when both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are set; see
|
||||
`Shipper.from_env`, which returns None otherwise.
|
||||
|
||||
Entries are clamped to OmniLogger's limits before they are buffered, because OmniLogger rejects
|
||||
a whole batch when any one entry breaks a limit. A batch that fails with a network error, an HTTP
|
||||
5xx or 429 is kept and sent again on a later flush, while any other rejection is dropped. Nothing
|
||||
here raises into the caller or blocks it: failures and a full buffer are reported with a
|
||||
rate-limited line on stderr.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections.abc import Iterator, Mapping
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
__all__ = ["OmniLoggerHandler", "Shipper", "to_omnilogger_level"]
|
||||
|
||||
ENV_URL = "OMNILOGGER_URL"
|
||||
ENV_TOKEN = "OMNILOGGER_INGEST_TOKEN"
|
||||
|
||||
FLUSH_INTERVAL = 2.0 # seconds between background flushes
|
||||
MAX_BATCH_SIZE = 100 # buffering this many entries flushes early
|
||||
BUFFER_CAPACITY = 2000 # beyond this, new entries are dropped
|
||||
HTTP_TIMEOUT = 5.0
|
||||
WARN_INTERVAL = 60.0 # at most one stderr warning per this many seconds
|
||||
|
||||
# OmniLogger's limits (Central/OmniLogger/internal/httpapi/validate.go).
|
||||
MAX_BATCH_ENTRIES = 1000
|
||||
MAX_BODY_BYTES = 2 * 1024 * 1024
|
||||
MAX_MESSAGE_BYTES = 8 * 1024
|
||||
MAX_CONTEXT_BYTES = 16 * 1024
|
||||
TRUNCATED_MARKER = " [truncated]"
|
||||
DROPPED_CONTEXT = '{"context_dropped":true}'
|
||||
|
||||
# Severity ranks, matching the Go shipper's scale (debug 10 ... critical 50).
|
||||
_RANKS = {"debug": 10, "info": 20, "warn": 30, "error": 40, "critical": 50}
|
||||
_SILENT = 100
|
||||
_LEVEL_NAMES = {
|
||||
"debug": "debug",
|
||||
"info": "info",
|
||||
"warn": "warn",
|
||||
"warning": "warn",
|
||||
"error": "error",
|
||||
"critical": "critical",
|
||||
}
|
||||
_THRESHOLD_RANKS = {**_RANKS, "silent": _SILENT, "none": _SILENT, "off": _SILENT}
|
||||
|
||||
|
||||
def to_omnilogger_level(levelno: int) -> str:
|
||||
"""Maps a standard-library logging level number to OmniLogger's level name.
|
||||
|
||||
DEBUG, INFO, WARNING, ERROR and CRITICAL map to debug, info, warn, error and critical. A level
|
||||
between two of them takes the name of the lower one, and anything below INFO is debug.
|
||||
"""
|
||||
if levelno >= logging.CRITICAL:
|
||||
return "critical"
|
||||
if levelno >= logging.ERROR:
|
||||
return "error"
|
||||
if levelno >= logging.WARNING:
|
||||
return "warn"
|
||||
if levelno >= logging.INFO:
|
||||
return "info"
|
||||
return "debug"
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""Refuses redirects, so the bearer token only ever goes to the configured URL."""
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001, ARG002
|
||||
return None
|
||||
|
||||
|
||||
_OPENER = urllib.request.build_opener(_NoRedirect)
|
||||
|
||||
|
||||
def _json_text(value: str) -> str:
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
|
||||
|
||||
def _clean_message(message: object) -> str:
|
||||
# OmniLogger rejects a message with a NUL byte (PostgreSQL cannot store it) and then rejects the
|
||||
# whole batch, so NUL is written as its escape text. Lone surrogates cannot be encoded as UTF-8.
|
||||
text = message if isinstance(message, str) else str(message)
|
||||
text = text.replace("\x00", "\\u0000")
|
||||
return text.encode("utf-8", "replace").decode("utf-8")
|
||||
|
||||
|
||||
def _clamp_message(text: str) -> str:
|
||||
data = text.encode("utf-8")
|
||||
if len(data) <= MAX_MESSAGE_BYTES:
|
||||
return text
|
||||
cut = MAX_MESSAGE_BYTES - len(TRUNCATED_MARKER.encode("utf-8"))
|
||||
# Decoding with "ignore" drops a character that the cut split in half, so the cut lands on a
|
||||
# character boundary.
|
||||
return data[:cut].decode("utf-8", "ignore") + TRUNCATED_MARKER
|
||||
|
||||
|
||||
def _clamp_context(context: Mapping[str, Any]) -> str:
|
||||
try:
|
||||
raw = json.dumps(
|
||||
dict(context), ensure_ascii=False, separators=(",", ":"), default=str, allow_nan=False
|
||||
)
|
||||
except (TypeError, ValueError, RecursionError):
|
||||
return DROPPED_CONTEXT
|
||||
# json.dumps writes a NUL as the escape \u0000, which OmniLogger refuses in context.
|
||||
if "\\u0000" in raw or len(raw.encode("utf-8", "replace")) > MAX_CONTEXT_BYTES:
|
||||
return DROPPED_CONTEXT
|
||||
return raw
|
||||
|
||||
|
||||
def _timestamp() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _encode_entry(
|
||||
service: str, level: str, message: object, context: Mapping[str, Any] | None
|
||||
) -> bytes:
|
||||
fields = [
|
||||
f'"service":{_json_text(service)}',
|
||||
f'"level":"{level}"',
|
||||
f'"message":{_json_text(_clamp_message(_clean_message(message)))}',
|
||||
]
|
||||
if context is not None:
|
||||
fields.append(f'"context":{_clamp_context(context)}')
|
||||
fields.append(f'"occurred_at":"{_timestamp()}"')
|
||||
return ("{" + ",".join(fields) + "}").encode("utf-8", "replace")
|
||||
|
||||
|
||||
def _batch_bodies(entries: list[bytes]) -> Iterator[tuple[bytes, int]]:
|
||||
"""Groups encoded entries into request bodies of at most MAX_BATCH_ENTRIES entries and under
|
||||
MAX_BODY_BYTES bytes each. Yields (body, entry count)."""
|
||||
group: list[bytes] = []
|
||||
size = 2 # the enclosing brackets
|
||||
for entry in entries:
|
||||
extra = len(entry) + (1 if group else 0) # the comma before it, if any
|
||||
if group and (len(group) >= MAX_BATCH_ENTRIES or size + extra >= MAX_BODY_BYTES):
|
||||
yield b"[" + b",".join(group) + b"]", len(group)
|
||||
group, size, extra = [], 2, len(entry)
|
||||
group.append(entry)
|
||||
size += extra
|
||||
if group:
|
||||
yield b"[" + b",".join(group) + b"]", len(group)
|
||||
|
||||
|
||||
class Shipper:
|
||||
"""Buffers log entries and sends them to OmniLogger in batches from a background thread.
|
||||
|
||||
Create one at startup with `Shipper.from_env(service)` and call `close()` on graceful shutdown.
|
||||
`close()` also runs at interpreter exit (atexit), so a final flush happens even without it.
|
||||
A Shipper is safe to use from many threads.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
base_url: str,
|
||||
ingest_token: str,
|
||||
service: str,
|
||||
level: str | None = None,
|
||||
flush_interval: float = FLUSH_INTERVAL,
|
||||
max_batch_size: int = MAX_BATCH_SIZE,
|
||||
buffer_capacity: int = BUFFER_CAPACITY,
|
||||
http_timeout: float = HTTP_TIMEOUT,
|
||||
) -> None:
|
||||
"""`level` is the threshold, using the same names as the services' LOG setting (debug, info,
|
||||
warn, error, critical, silent). It defaults to info."""
|
||||
self._service = service
|
||||
self._threshold = _THRESHOLD_RANKS.get((level or "info").strip().lower(), _RANKS["info"])
|
||||
self._flush_interval = flush_interval if flush_interval > 0 else FLUSH_INTERVAL
|
||||
self._max_batch_size = max_batch_size
|
||||
self._buffer_capacity = buffer_capacity
|
||||
self._http_timeout = http_timeout
|
||||
|
||||
self._buffer: list[bytes] = []
|
||||
self._buffer_lock = threading.Lock()
|
||||
self._cred_lock = threading.Lock()
|
||||
self._url: str | None = None # None while shipping is disabled
|
||||
self._token = ""
|
||||
self.set_credentials(base_url, ingest_token)
|
||||
self._wake = threading.Event()
|
||||
self._stop = threading.Event()
|
||||
self._close_lock = threading.Lock()
|
||||
self._closed = False
|
||||
self._warn_lock = threading.Lock()
|
||||
self._last_warn: float | None = None
|
||||
|
||||
self._thread = threading.Thread(target=self._run, name=f"logshipper-{service}", daemon=True)
|
||||
self._thread.start()
|
||||
atexit.register(self.close)
|
||||
|
||||
@classmethod
|
||||
def from_env(
|
||||
cls,
|
||||
service: str,
|
||||
*,
|
||||
level: str | None = None,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
) -> Shipper | None:
|
||||
"""Returns a Shipper configured from OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN, or None
|
||||
when either is unset or empty, which leaves the service with no shipping at all."""
|
||||
env = os.environ if environ is None else environ
|
||||
url = (env.get(ENV_URL) or "").strip()
|
||||
token = (env.get(ENV_TOKEN) or "").strip()
|
||||
if not url or not token:
|
||||
return None
|
||||
return cls(base_url=url, ingest_token=token, service=service, level=level)
|
||||
|
||||
def handler(self, level: int = logging.NOTSET) -> OmniLoggerHandler:
|
||||
"""Returns a logging handler that ships records to this Shipper."""
|
||||
return OmniLoggerHandler(self, level)
|
||||
|
||||
def set_credentials(self, base_url: str, token: str) -> None:
|
||||
"""Sets where, and as which ingest token, entries are sent. It is thread-safe, takes effect
|
||||
from the next flush, and does not restart the background thread.
|
||||
|
||||
An empty base URL or token disables shipping: entries are no longer buffered, anything
|
||||
already buffered is dropped, and the service's own console output carries on unchanged.
|
||||
Otherwise entries go to `base_url` + "/api/logs" with `token` as the bearer token."""
|
||||
base = (base_url or "").strip().rstrip("/")
|
||||
token = (token or "").strip()
|
||||
url = base + "/api/logs" if base and token else None
|
||||
with self._cred_lock:
|
||||
self._url = url
|
||||
self._token = token
|
||||
if url is None:
|
||||
with self._buffer_lock:
|
||||
self._buffer = []
|
||||
|
||||
def _enabled(self) -> bool:
|
||||
with self._cred_lock:
|
||||
return self._url is not None
|
||||
|
||||
def log(self, level: str, message: str, context: Mapping[str, Any] | None = None) -> None:
|
||||
"""Queues one entry. `level` is debug, info, warn (or warning), error or critical; any
|
||||
other value is sent as info. `context` is an optional mapping sent as JSON."""
|
||||
name = _LEVEL_NAMES.get(str(level).strip().lower(), "info")
|
||||
if _RANKS[name] < self._threshold or not self._enabled():
|
||||
return
|
||||
try:
|
||||
entry = _encode_entry(self._service, name, message, context)
|
||||
except Exception: # noqa: BLE001 - a log sink must never fail its host
|
||||
return
|
||||
self._buffer_entry(entry)
|
||||
|
||||
def debug(self, message: str, context: Mapping[str, Any] | None = None) -> None:
|
||||
self.log("debug", message, context)
|
||||
|
||||
def info(self, message: str, context: Mapping[str, Any] | None = None) -> None:
|
||||
self.log("info", message, context)
|
||||
|
||||
def warning(self, message: str, context: Mapping[str, Any] | None = None) -> None:
|
||||
self.log("warn", message, context)
|
||||
|
||||
def error(self, message: str, context: Mapping[str, Any] | None = None) -> None:
|
||||
self.log("error", message, context)
|
||||
|
||||
def critical(self, message: str, context: Mapping[str, Any] | None = None) -> None:
|
||||
self.log("critical", message, context)
|
||||
|
||||
def flush(self) -> None:
|
||||
"""Sends everything buffered now, in the calling thread. A batch that fails for a reason
|
||||
that may pass (no connection, HTTP 5xx or 429) stays in the buffer with every later entry of
|
||||
this flush, in order, and the rest of the flush waits for the next one. Other failures are
|
||||
only reported on stderr, and at most once a minute."""
|
||||
with self._buffer_lock:
|
||||
if not self._buffer:
|
||||
return
|
||||
pending, self._buffer = self._buffer, []
|
||||
sent = 0
|
||||
for body, count in _batch_bodies(pending):
|
||||
if self._post(body, count):
|
||||
self._requeue(pending[sent:])
|
||||
return
|
||||
sent += count
|
||||
|
||||
def _requeue(self, entries: list[bytes]) -> None:
|
||||
"""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 its capacity: when the waiting
|
||||
entries and the buffer do not all fit, the newest entries are dropped, as _buffer_entry
|
||||
drops them."""
|
||||
with self._buffer_lock:
|
||||
if not self._enabled():
|
||||
return # shipping was disabled during the flush, so these go with the buffer
|
||||
combined = entries + self._buffer
|
||||
dropped = max(0, len(combined) - self._buffer_capacity)
|
||||
self._buffer = combined[: self._buffer_capacity]
|
||||
if dropped:
|
||||
self._warn(
|
||||
f"buffer full while retrying, dropping {dropped} log entries for service "
|
||||
f"{self._service!r}"
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Stops the background thread after a final flush of whatever is buffered. Safe to call
|
||||
more than once."""
|
||||
with self._close_lock:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self._stop.set()
|
||||
self._wake.set()
|
||||
if threading.current_thread() is not self._thread:
|
||||
self._thread.join()
|
||||
self.flush()
|
||||
atexit.unregister(self.close)
|
||||
|
||||
def _buffer_entry(self, entry: bytes) -> None:
|
||||
if self._closed or not self._enabled():
|
||||
return
|
||||
with self._buffer_lock:
|
||||
full = len(self._buffer) >= self._buffer_capacity
|
||||
if not full:
|
||||
self._buffer.append(entry)
|
||||
ready = len(self._buffer) >= self._max_batch_size
|
||||
if full:
|
||||
self._warn(
|
||||
f"buffer full (cap={self._buffer_capacity}), dropping log entries for service "
|
||||
f"{self._service!r}"
|
||||
)
|
||||
elif ready:
|
||||
self._wake.set()
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.is_set():
|
||||
self._wake.wait(self._flush_interval)
|
||||
# Cleared before the flush takes its snapshot, so an entry that arrives during the
|
||||
# flush sets the event again and is not left waiting for the next interval.
|
||||
self._wake.clear()
|
||||
if self._stop.is_set():
|
||||
break
|
||||
try:
|
||||
self.flush()
|
||||
except Exception: # noqa: BLE001 - keep the background thread alive
|
||||
pass
|
||||
|
||||
def _post(self, body: bytes, count: int) -> bool:
|
||||
"""Sends one request body. Returns True when it failed for a reason that may pass (no
|
||||
connection, HTTP 5xx or 429), so the caller keeps its entries for a later flush. A request
|
||||
OmniLogger rejects with any other status is reported and dropped, and returns False."""
|
||||
with self._cred_lock:
|
||||
url, token = self._url, self._token
|
||||
if url is None:
|
||||
return False # shipping was disabled after these entries were taken for a flush
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=body,
|
||||
method="POST",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {token}",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with _OPENER.open(request, timeout=self._http_timeout):
|
||||
return False
|
||||
except urllib.error.HTTPError as exc:
|
||||
exc.close()
|
||||
if exc.code == 429 or exc.code >= 500:
|
||||
self._warn(f"OmniLogger answered HTTP {exc.code} for {count} entries, will retry")
|
||||
return True
|
||||
self._warn(f"OmniLogger rejected {count} entries: HTTP {exc.code}")
|
||||
return False
|
||||
except Exception as exc: # noqa: BLE001 - unreachable or misconfigured sink
|
||||
self._warn(f"send {count} entries to {url}: {exc}")
|
||||
return True
|
||||
|
||||
def _warn(self, detail: str) -> None:
|
||||
now = time.monotonic()
|
||||
with self._warn_lock:
|
||||
if self._last_warn is not None and now - self._last_warn < WARN_INTERVAL:
|
||||
return
|
||||
self._last_warn = now
|
||||
try:
|
||||
stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
sys.stderr.write(f"[{stamp}] [logshipper] logshipper: {detail}\n")
|
||||
sys.stderr.flush()
|
||||
except Exception: # noqa: BLE001 - stderr may be closed or missing
|
||||
pass
|
||||
|
||||
|
||||
class OmniLoggerHandler(logging.Handler):
|
||||
"""A logging handler that ships each record to a Shipper and writes nothing locally.
|
||||
|
||||
Keep the service's own console handler and add this one beside it, so the console output is
|
||||
unchanged. The shipped message is the record's formatted message, with any traceback appended.
|
||||
The record's logger name goes in the entry's context.
|
||||
"""
|
||||
|
||||
def __init__(self, shipper: Shipper, level: int = logging.NOTSET) -> None:
|
||||
super().__init__(level)
|
||||
self._shipper = shipper
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
try:
|
||||
message = self.format(record)
|
||||
self._shipper.log(to_omnilogger_level(record.levelno), message, {"logger": record.name})
|
||||
except Exception: # noqa: BLE001 - a log sink must never fail its host
|
||||
pass
|
||||
Reference in new issue
Block a user