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
@@ -6,6 +6,7 @@ Shared account-management, TOTP, admin reset-code, and AuthGuard client primitiv
|
||||
- `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification;
|
||||
- `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console;
|
||||
- `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists. `setBaseUrl(url)` retargets an existing client's AuthGuard URL in place - the natural target for a ProjectConfigurator core-services push handler - so a client can be constructed with `new AuthClient("")` (usable right away, failing closed with `IllegalStateException` until a real URL arrives) rather than needing one known up front. Unlike the Go/Python/Node siblings, this package has no `coreconfig` module of its own: MegaBasterd, its only consumer, wires the `PUT /api/core-services/internal` route directly against a plain field holding the current `AuthGuardUrl`.
|
||||
- `LogShipper` (`com.gabriel20xx.shared.logs`) - the client shipper for OmniLogger, the central log sink. It batches entries and POSTs them to `{OMNILOGGER_URL}/api/logs` from a daemon thread. `LogShipper.fromEnv(service)` returns null unless both `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are set, so shipping stays off by default. Mirrors `shared/backend/logshipper` (Go) - keep the two in sync. Additive: it never prints, so the consumer's own logger remains the console output. JDK only (Java 8, `HttpURLConnection`).
|
||||
|
||||
## How this package is actually consumed
|
||||
|
||||
|
||||
@@ -0,0 +1,752 @@
|
||||
package com.gabriel20xx.shared.logs;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Client-side shipper for OmniLogger, the workspace's central log sink.
|
||||
*
|
||||
* <p>This is the Java port of {@code shared/backend/logshipper/shipper.go}. Keep the two in sync: the
|
||||
* limits, the wire format and the level names all come from the shared OmniLogger log-shipping contract.
|
||||
* The class batches entries in memory and POSTs them to {@code {OMNILOGGER_URL}/api/logs} from a daemon
|
||||
* thread. It never writes to the console, so a service keeps its existing logger and mirrors each line
|
||||
* into {@link #log(Level, String)}. Nothing here throws, blocks the caller on the network, or exits the
|
||||
* process because OmniLogger is unreachable or misconfigured.
|
||||
*
|
||||
* <p>Deliberate differences from the Go reference:
|
||||
* <ul>
|
||||
* <li>No local printing, and no Audit/Ctx/Writer surface. Shipping is additive, so the consumer's own
|
||||
* console output stays as it was.</li>
|
||||
* <li>A flush sends at most 1000 entries and a body under 2 MiB, split across requests when needed. The
|
||||
* contract's limits require this. The Go reference sends the whole buffer in one request.</li>
|
||||
* <li>Targets Java 8: it uses {@link HttpURLConnection} (java.net.http needs Java 11), and the JSON is
|
||||
* hand-encoded so the module needs no JSON library on the classpath.</li>
|
||||
* <li>The 5-second timeout applies to the connect and to the read separately. Go applies one total
|
||||
* deadline per request.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class LogShipper implements AutoCloseable {
|
||||
|
||||
/** Environment variable holding OmniLogger's base URL, for example {@code http://omnilogger:8080}. */
|
||||
public static final String ENV_URL = "OMNILOGGER_URL";
|
||||
/** Environment variable holding this service's OmniLogger ingest bearer token. */
|
||||
public static final String ENV_TOKEN = "OMNILOGGER_INGEST_TOKEN";
|
||||
|
||||
static final int MAX_MESSAGE_BYTES = 8 * 1024;
|
||||
static final int MAX_CONTEXT_BYTES = 16 * 1024;
|
||||
static final int MAX_BATCH_ENTRIES = 1000;
|
||||
/** A request body must stay under 2 MiB, so the limit is one byte below that. */
|
||||
static final int MAX_BODY_BYTES = 2 * 1024 * 1024 - 1;
|
||||
static final String TRUNCATED_MARKER = " [truncated]";
|
||||
static final String DROPPED_CONTEXT = "{\"context_dropped\":true}";
|
||||
|
||||
private static final long DEFAULT_FLUSH_INTERVAL_MILLIS = 2_000L;
|
||||
private static final int DEFAULT_MAX_BATCH_SIZE = 100;
|
||||
private static final int DEFAULT_BUFFER_CAPACITY = 2_000;
|
||||
private static final int HTTP_TIMEOUT_MILLIS = 5_000;
|
||||
private static final int HTTP_TOO_MANY_REQUESTS = 429;
|
||||
private static final long WARN_INTERVAL_MILLIS = 60_000L;
|
||||
private static final int MAX_CONTEXT_DEPTH = 32;
|
||||
private static final int MAX_DRAINED_RESPONSE_BYTES = 64 * 1024;
|
||||
|
||||
private static final DateTimeFormatter TIMESTAMP =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT).withZone(ZoneOffset.UTC);
|
||||
private static final DateTimeFormatter WARN_TIME =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT);
|
||||
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
|
||||
|
||||
/** Severity scale. Names and aliases follow the shared LOG vocabulary; the wire names are OmniLogger's. */
|
||||
public enum Level {
|
||||
DEBUG(10, "debug"),
|
||||
INFO(20, "info"),
|
||||
WARN(30, "warn"),
|
||||
ERROR(40, "error"),
|
||||
CRITICAL(50, "critical"),
|
||||
/** Threshold only: suppresses everything. An entry is never logged at this level. */
|
||||
SILENT(100, null);
|
||||
|
||||
private final int severity;
|
||||
private final String wireName;
|
||||
|
||||
Level(int severity, String wireName) {
|
||||
this.severity = severity;
|
||||
this.wireName = wireName;
|
||||
}
|
||||
|
||||
/** The lowercase level name OmniLogger's ingest API expects, or null for {@link #SILENT}. */
|
||||
public String wireName() {
|
||||
return wireName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a threshold such as a LOG env value. Matching is trimmed and case-insensitive. Unknown or
|
||||
* empty input means {@link #INFO}.
|
||||
*/
|
||||
public static Level parse(String value) {
|
||||
String normalized = value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
|
||||
switch (normalized) {
|
||||
case "debug":
|
||||
return DEBUG;
|
||||
case "warn":
|
||||
case "warning":
|
||||
return WARN;
|
||||
case "error":
|
||||
return ERROR;
|
||||
case "critical":
|
||||
return CRITICAL;
|
||||
case "silent":
|
||||
case "none":
|
||||
case "off":
|
||||
return SILENT;
|
||||
default:
|
||||
return INFO;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a java.util.logging level: SEVERE becomes error, WARNING becomes warn, INFO becomes info, and
|
||||
* anything finer becomes debug. JUL has no critical level, so nothing maps to critical.
|
||||
*/
|
||||
public static Level fromJavaUtilLogging(java.util.logging.Level level) {
|
||||
if (level == null) {
|
||||
return INFO;
|
||||
}
|
||||
int value = level.intValue();
|
||||
if (value >= java.util.logging.Level.SEVERE.intValue()) {
|
||||
return ERROR;
|
||||
}
|
||||
if (value >= java.util.logging.Level.WARNING.intValue()) {
|
||||
return WARN;
|
||||
}
|
||||
if (value >= java.util.logging.Level.INFO.intValue()) {
|
||||
return INFO;
|
||||
}
|
||||
return DEBUG;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a shipper from {@code OMNILOGGER_URL} and {@code OMNILOGGER_INGEST_TOKEN}, with threshold INFO.
|
||||
*
|
||||
* @return the shipper, or null when either variable is unset or blank. A null result means shipping is
|
||||
* disabled, and the service must behave exactly as it did without it.
|
||||
*/
|
||||
public static LogShipper fromEnv(String service) {
|
||||
return fromEnv(service, Level.INFO);
|
||||
}
|
||||
|
||||
/** Like {@link #fromEnv(String)}, with an explicit threshold. */
|
||||
public static LogShipper fromEnv(String service, Level threshold) {
|
||||
return fromEnv(service, threshold, name -> System.getenv(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #fromEnv(String, Level)}, but reads the variables through {@code environment}. Pass a
|
||||
* lookup such as {@code name -> map.get(name)} to make the disabled path testable.
|
||||
*/
|
||||
public static LogShipper fromEnv(String service, Level threshold, Function<String, String> environment) {
|
||||
String url = trimOrEmpty(environment.apply(ENV_URL));
|
||||
String token = trimOrEmpty(environment.apply(ENV_TOKEN));
|
||||
if (url.isEmpty() || token.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new LogShipper(url, token, service, threshold);
|
||||
}
|
||||
|
||||
/** Creates a shipper that sends entries at INFO and above, flushing every 2 seconds. */
|
||||
public LogShipper(String baseUrl, String ingestToken, String service) {
|
||||
this(baseUrl, ingestToken, service, Level.INFO);
|
||||
}
|
||||
|
||||
/** Creates a shipper with the given threshold. It starts its background flush thread immediately. */
|
||||
public LogShipper(String baseUrl, String ingestToken, String service, Level threshold) {
|
||||
this(baseUrl, ingestToken, service, threshold, DEFAULT_FLUSH_INTERVAL_MILLIS,
|
||||
DEFAULT_MAX_BATCH_SIZE, DEFAULT_BUFFER_CAPACITY);
|
||||
}
|
||||
|
||||
LogShipper(String baseUrl, String ingestToken, String service, Level threshold,
|
||||
long flushIntervalMillis, int maxBatchSize, int bufferCapacity) {
|
||||
this.credentials = credentialsFor(baseUrl, ingestToken);
|
||||
this.service = service == null ? "" : service;
|
||||
this.threshold = threshold == null ? Level.INFO : threshold;
|
||||
this.maxBatchSize = maxBatchSize > 0 ? maxBatchSize : DEFAULT_MAX_BATCH_SIZE;
|
||||
this.bufferCapacity = bufferCapacity > 0 ? bufferCapacity : DEFAULT_BUFFER_CAPACITY;
|
||||
this.executor = Executors.newSingleThreadScheduledExecutor(daemonThreads("logshipper-" + this.service));
|
||||
long interval = flushIntervalMillis > 0 ? flushIntervalMillis : DEFAULT_FLUSH_INTERVAL_MILLIS;
|
||||
this.executor.scheduleWithFixedDelay(this::runScheduledFlush, interval, interval, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/** The endpoint and bearer token in use, or null while shipping is disabled. See {@link #setCredentials}. */
|
||||
private volatile Credentials credentials;
|
||||
private final Object credentialsLock = new Object();
|
||||
private final String service;
|
||||
private final Level threshold;
|
||||
private final int maxBatchSize;
|
||||
private final int bufferCapacity;
|
||||
/** Encoded entries waiting to be sent, oldest first. Guarded by bufferLock, which is never held across I/O. */
|
||||
private final ArrayDeque<byte[]> buffer = new ArrayDeque<>();
|
||||
private final Object bufferLock = new Object();
|
||||
private final ScheduledExecutorService executor;
|
||||
private final AtomicBoolean flushQueued = new AtomicBoolean(false);
|
||||
private final AtomicBoolean closed = new AtomicBoolean(false);
|
||||
private final Object warnLock = new Object();
|
||||
private boolean warned;
|
||||
private long lastWarnAtMillis;
|
||||
|
||||
/** Logs {@code message} at {@code level}. Never blocks on the network. */
|
||||
public void log(Level level, String message) {
|
||||
log(level, message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs {@code message} with an optional structured {@code context}. The context must be a map of
|
||||
* strings to plain values (strings, numbers, booleans, null, maps, iterables and arrays). Other values
|
||||
* are sent as their {@code toString()}. The context is not scrubbed.
|
||||
*/
|
||||
public void log(Level level, String message, Map<String, ?> context) {
|
||||
if (level == null || level == Level.SILENT || level.severity < threshold.severity || closed.get()
|
||||
|| credentials == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String clampedMessage = clampMessage(String.valueOf(message));
|
||||
String entry = encodeEntry(service, level.wireName(), clampedMessage, clampContext(context),
|
||||
TIMESTAMP.format(Instant.now()));
|
||||
byte[] bytes = entry.getBytes(StandardCharsets.UTF_8);
|
||||
boolean full;
|
||||
int size;
|
||||
synchronized (bufferLock) {
|
||||
full = buffer.size() >= bufferCapacity;
|
||||
if (!full) {
|
||||
buffer.addLast(bytes);
|
||||
}
|
||||
size = buffer.size();
|
||||
}
|
||||
if (full) {
|
||||
warnOnce("buffer full (cap=" + bufferCapacity + "), dropping log entries for service \""
|
||||
+ service + "\"");
|
||||
return;
|
||||
}
|
||||
if (size >= maxBatchSize) {
|
||||
requestFlush();
|
||||
}
|
||||
} catch (RuntimeException ex) {
|
||||
// Logging must never fail the caller.
|
||||
warnOnce("could not queue an entry: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void debug(String message) {
|
||||
log(Level.DEBUG, message, null);
|
||||
}
|
||||
|
||||
public void info(String message) {
|
||||
log(Level.INFO, message, null);
|
||||
}
|
||||
|
||||
public void warn(String message) {
|
||||
log(Level.WARN, message, null);
|
||||
}
|
||||
|
||||
public void error(String message) {
|
||||
log(Level.ERROR, message, null);
|
||||
}
|
||||
|
||||
public void critical(String message) {
|
||||
log(Level.CRITICAL, message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously sends everything buffered when the call starts, in requests of at most 1000 entries and 2 MiB.
|
||||
* When a request fails for a reason that may pass, its entries and every later entry of this flush go back to
|
||||
* the front of the buffer, and the rest of the flush waits for the next one. A request OmniLogger rejects is
|
||||
* dropped. Failures never reach the caller, only a rate-limited warning on stderr. Calls are serialized with the
|
||||
* background flush.
|
||||
*/
|
||||
public synchronized void flush() {
|
||||
Credentials target = credentials;
|
||||
List<byte[]> batch = takeBuffered();
|
||||
if (target == null || batch.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int start = 0;
|
||||
while (start < batch.size()) {
|
||||
int end = batchEnd(batch, start);
|
||||
if (post(target, batch.subList(start, end))) {
|
||||
requeue(batch.subList(start, batch.size()));
|
||||
return;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the OmniLogger base URL and ingest token, as ProjectConfigurator pushes them. The next flush uses the new
|
||||
* values. A blank base URL or token disables shipping: nothing more is buffered, and anything already buffered is
|
||||
* dropped. The background flusher keeps running in every case, so this never restarts it. Safe to call from any
|
||||
* thread, and it never waits for a flush in progress.
|
||||
*/
|
||||
public void setCredentials(String baseUrl, String ingestToken) {
|
||||
synchronized (credentialsLock) {
|
||||
Credentials next = credentialsFor(baseUrl, ingestToken);
|
||||
credentials = next;
|
||||
if (next == null) {
|
||||
synchronized (bufferLock) {
|
||||
buffer.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the background thread after a final flush of whatever is buffered. Call it during graceful
|
||||
* shutdown. Closing again is a no-op, and entries logged after close are discarded.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
executor.shutdown();
|
||||
flush();
|
||||
}
|
||||
|
||||
private void runScheduledFlush() {
|
||||
try {
|
||||
flush();
|
||||
} catch (RuntimeException ex) {
|
||||
// Never let one failed flush cancel the periodic task.
|
||||
warnOnce("flush failed: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks the background thread to flush soon. The request is dropped if one is already pending. */
|
||||
private void requestFlush() {
|
||||
if (!flushQueued.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
executor.execute(() -> {
|
||||
flushQueued.set(false);
|
||||
runScheduledFlush();
|
||||
});
|
||||
} catch (RejectedExecutionException ex) {
|
||||
flushQueued.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes and returns every buffered entry, oldest first. */
|
||||
private List<byte[]> takeBuffered() {
|
||||
synchronized (bufferLock) {
|
||||
List<byte[]> taken = new ArrayList<>(buffer);
|
||||
buffer.clear();
|
||||
return taken;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index just past the last entry of the request that starts at {@code start}. A request holds at
|
||||
* most MAX_BATCH_ENTRIES entries and a body of at most MAX_BODY_BYTES, and always at least one entry.
|
||||
*/
|
||||
private static int batchEnd(List<byte[]> entries, int start) {
|
||||
int bodyBytes = 2;
|
||||
int end = start;
|
||||
while (end < entries.size() && end - start < MAX_BATCH_ENTRIES) {
|
||||
int added = entries.get(end).length + (end == start ? 0 : 1);
|
||||
if (end > start && bodyBytes + added > MAX_BODY_BYTES) {
|
||||
break;
|
||||
}
|
||||
bodyBytes += added;
|
||||
end++;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 entries and the buffer do not all fit, the newest are
|
||||
* dropped, as {@link #log(Level, String, Map)} drops them when the buffer is full.
|
||||
*/
|
||||
private void requeue(List<byte[]> entries) {
|
||||
int dropped = 0;
|
||||
synchronized (bufferLock) {
|
||||
for (int i = entries.size() - 1; i >= 0; i--) {
|
||||
buffer.addFirst(entries.get(i));
|
||||
}
|
||||
while (buffer.size() > bufferCapacity) {
|
||||
buffer.removeLast();
|
||||
dropped++;
|
||||
}
|
||||
}
|
||||
if (dropped > 0) {
|
||||
warnOnce("buffer full while retrying, dropping " + dropped + " log entries for service \""
|
||||
+ service + "\"");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one request and reports whether it failed for a reason that may pass, in which case the caller keeps
|
||||
* the entries for a later flush. An IO error, HTTP 429 or any 5xx is retried. Any other non-2xx status is a
|
||||
* rejection, which is warned about and dropped without a retry.
|
||||
*/
|
||||
private boolean post(Credentials target, List<byte[]> entries) {
|
||||
byte[] body = joinJsonArray(entries);
|
||||
try {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(target.endpoint).openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setUseCaches(false);
|
||||
connection.setConnectTimeout(HTTP_TIMEOUT_MILLIS);
|
||||
connection.setReadTimeout(HTTP_TIMEOUT_MILLIS);
|
||||
connection.setDoOutput(true);
|
||||
connection.setFixedLengthStreamingMode(body.length);
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("Authorization", "Bearer " + target.token);
|
||||
try (OutputStream out = connection.getOutputStream()) {
|
||||
out.write(body);
|
||||
}
|
||||
int status = connection.getResponseCode();
|
||||
drain(connection, status);
|
||||
if (status >= 200 && status < 300) {
|
||||
return false;
|
||||
}
|
||||
if (status == HTTP_TOO_MANY_REQUESTS || status >= 500) {
|
||||
warnOnce("OmniLogger answered HTTP " + status + " for " + entries.size() + " entries, will retry");
|
||||
return true;
|
||||
}
|
||||
warnOnce("OmniLogger rejected " + entries.size() + " entries: HTTP " + status);
|
||||
return false;
|
||||
} catch (MalformedURLException ex) {
|
||||
// The request cannot be built, and sending it again would fail the same way.
|
||||
warnOnce("could not build the request for " + entries.size() + " entries: " + ex);
|
||||
return false;
|
||||
} catch (IOException ex) {
|
||||
warnOnce("send " + entries.size() + " entries to " + target.endpoint + ", will retry: " + ex);
|
||||
return true;
|
||||
} catch (RuntimeException ex) {
|
||||
warnOnce("send " + entries.size() + " entries to " + target.endpoint + ": " + ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a bounded part of the response so the connection can be reused, then closes it. This is best effort:
|
||||
* the status is already known, so a failed read must not turn an accepted request into a retry.
|
||||
*/
|
||||
private static void drain(HttpURLConnection connection, int status) {
|
||||
try {
|
||||
InputStream in = status >= 200 && status < 300 ? connection.getInputStream() : connection.getErrorStream();
|
||||
if (in == null) {
|
||||
return;
|
||||
}
|
||||
try (InputStream stream = in) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int remaining = MAX_DRAINED_RESPONSE_BYTES;
|
||||
while (remaining > 0 && stream.read(buffer) != -1) {
|
||||
remaining -= buffer.length;
|
||||
}
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
// Nothing more to do: the status has already been read.
|
||||
}
|
||||
}
|
||||
|
||||
/** Prints a local stderr warning at most once a minute, so an unreachable OmniLogger cannot spam logs. */
|
||||
private void warnOnce(String message) {
|
||||
synchronized (warnLock) {
|
||||
long now = System.currentTimeMillis();
|
||||
if (warned && now - lastWarnAtMillis < WARN_INTERVAL_MILLIS) {
|
||||
return;
|
||||
}
|
||||
warned = true;
|
||||
lastWarnAtMillis = now;
|
||||
}
|
||||
System.err.println("[" + WARN_TIME.format(LocalDateTime.now()) + "] [logshipper] " + message);
|
||||
}
|
||||
|
||||
// ---- Limits and encoding. Package-private so the tests can check them directly. ----
|
||||
|
||||
/**
|
||||
* Cuts a message longer than 8192 UTF-8 bytes on a code point boundary and appends the truncation marker.
|
||||
* The result is at most 8192 bytes.
|
||||
*/
|
||||
static String clampMessage(String message) {
|
||||
if (utf8Length(message) <= MAX_MESSAGE_BYTES) {
|
||||
return message;
|
||||
}
|
||||
int budget = MAX_MESSAGE_BYTES - TRUNCATED_MARKER.length();
|
||||
int used = 0;
|
||||
int end = 0;
|
||||
while (end < message.length()) {
|
||||
int codePoint = message.codePointAt(end);
|
||||
int bytes = utf8Bytes(codePoint);
|
||||
if (used + bytes > budget) {
|
||||
break;
|
||||
}
|
||||
used += bytes;
|
||||
end += Character.charCount(codePoint);
|
||||
}
|
||||
return message.substring(0, end) + TRUNCATED_MARKER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes the context to JSON. It is replaced by {@link #DROPPED_CONTEXT} when it is over 16384 bytes
|
||||
* or contains an escaped NUL. It is omitted (null) when it cannot be encoded at all, for example because it
|
||||
* holds NaN or is nested too deeply.
|
||||
*/
|
||||
static String clampContext(Map<String, ?> context) {
|
||||
if (context == null) {
|
||||
return null;
|
||||
}
|
||||
String json;
|
||||
try {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
writeValue(builder, context, 0);
|
||||
json = builder.toString();
|
||||
} catch (RuntimeException ex) {
|
||||
return null;
|
||||
}
|
||||
if (utf8Length(json) > MAX_CONTEXT_BYTES || json.contains("\\u0000")) {
|
||||
return DROPPED_CONTEXT;
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
/** Encodes one OmniLogger entry. The field order matches the Go reference's wire struct. */
|
||||
static String encodeEntry(String service, String level, String message, String contextJson, String occurredAt) {
|
||||
StringBuilder builder = new StringBuilder(message.length() + 128);
|
||||
builder.append("{\"service\":");
|
||||
writeString(builder, service);
|
||||
builder.append(",\"level\":");
|
||||
writeString(builder, level);
|
||||
builder.append(",\"message\":");
|
||||
writeString(builder, message);
|
||||
if (contextJson != null) {
|
||||
builder.append(",\"context\":").append(contextJson);
|
||||
}
|
||||
builder.append(",\"occurred_at\":");
|
||||
writeString(builder, occurredAt);
|
||||
return builder.append('}').toString();
|
||||
}
|
||||
|
||||
static byte[] joinJsonArray(List<byte[]> entries) {
|
||||
int size = 2 + Math.max(0, entries.size() - 1);
|
||||
for (byte[] entry : entries) {
|
||||
size += entry.length;
|
||||
}
|
||||
byte[] body = new byte[size];
|
||||
int position = 0;
|
||||
body[position++] = '[';
|
||||
for (int i = 0; i < entries.size(); i++) {
|
||||
if (i > 0) {
|
||||
body[position++] = ',';
|
||||
}
|
||||
byte[] entry = entries.get(i);
|
||||
System.arraycopy(entry, 0, body, position, entry.length);
|
||||
position += entry.length;
|
||||
}
|
||||
body[position] = ']';
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts UTF-8 bytes the way the encoder writes them. A lone surrogate is written as U+FFFD, which is three
|
||||
* bytes.
|
||||
*/
|
||||
static int utf8Length(String value) {
|
||||
int length = 0;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if (c < 0x80) {
|
||||
length += 1;
|
||||
} else if (c < 0x800) {
|
||||
length += 2;
|
||||
} else if (Character.isHighSurrogate(c) && i + 1 < value.length()
|
||||
&& Character.isLowSurrogate(value.charAt(i + 1))) {
|
||||
length += 4;
|
||||
i++;
|
||||
} else {
|
||||
length += 3;
|
||||
}
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
private static int utf8Bytes(int codePoint) {
|
||||
if (codePoint < 0x80) {
|
||||
return 1;
|
||||
}
|
||||
if (codePoint < 0x800) {
|
||||
return 2;
|
||||
}
|
||||
return codePoint < 0x10000 ? 3 : 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a JSON string literal. Quotes, backslashes and control characters are escaped, and so are lone
|
||||
* surrogates (written as U+FFFD). Everything else is written as-is, so the output is valid UTF-8 JSON.
|
||||
*/
|
||||
private static void writeString(StringBuilder out, String value) {
|
||||
out.append('"');
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
switch (c) {
|
||||
case '"':
|
||||
out.append("\\\"");
|
||||
break;
|
||||
case '\\':
|
||||
out.append("\\\\");
|
||||
break;
|
||||
case '\n':
|
||||
out.append("\\n");
|
||||
break;
|
||||
case '\r':
|
||||
out.append("\\r");
|
||||
break;
|
||||
case '\t':
|
||||
out.append("\\t");
|
||||
break;
|
||||
case '\b':
|
||||
out.append("\\b");
|
||||
break;
|
||||
case '\f':
|
||||
out.append("\\f");
|
||||
break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
out.append("\\u00").append(HEX_DIGITS[c >> 4]).append(HEX_DIGITS[c & 0xF]);
|
||||
} else if (Character.isHighSurrogate(c)) {
|
||||
if (i + 1 < value.length() && Character.isLowSurrogate(value.charAt(i + 1))) {
|
||||
out.append(c).append(value.charAt(++i));
|
||||
} else {
|
||||
out.append("\\ufffd");
|
||||
}
|
||||
} else if (Character.isLowSurrogate(c)) {
|
||||
out.append("\\ufffd");
|
||||
} else {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.append('"');
|
||||
}
|
||||
|
||||
private static void writeValue(StringBuilder out, Object value, int depth) {
|
||||
if (depth > MAX_CONTEXT_DEPTH) {
|
||||
throw new IllegalArgumentException("context is nested too deeply");
|
||||
}
|
||||
if (value == null) {
|
||||
out.append("null");
|
||||
} else if (value instanceof String) {
|
||||
writeString(out, (String) value);
|
||||
} else if (value instanceof Boolean || value instanceof Integer || value instanceof Long
|
||||
|| value instanceof Short || value instanceof Byte
|
||||
|| value instanceof BigInteger || value instanceof BigDecimal) {
|
||||
out.append(value.toString());
|
||||
} else if (value instanceof Double || value instanceof Float) {
|
||||
double number = ((Number) value).doubleValue();
|
||||
if (Double.isNaN(number) || Double.isInfinite(number)) {
|
||||
throw new IllegalArgumentException("non-finite number in context");
|
||||
}
|
||||
out.append(value.toString());
|
||||
} else if (value instanceof Map) {
|
||||
out.append('{');
|
||||
boolean first = true;
|
||||
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
|
||||
if (!first) {
|
||||
out.append(',');
|
||||
}
|
||||
first = false;
|
||||
writeString(out, String.valueOf(entry.getKey()));
|
||||
out.append(':');
|
||||
writeValue(out, entry.getValue(), depth + 1);
|
||||
}
|
||||
out.append('}');
|
||||
} else if (value instanceof Iterable) {
|
||||
writeArray(out, ((Iterable<?>) value).iterator(), depth);
|
||||
} else if (value instanceof Object[]) {
|
||||
writeArray(out, Arrays.asList((Object[]) value).iterator(), depth);
|
||||
} else {
|
||||
writeString(out, value.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeArray(StringBuilder out, Iterator<?> items, int depth) {
|
||||
out.append('[');
|
||||
boolean first = true;
|
||||
while (items.hasNext()) {
|
||||
if (!first) {
|
||||
out.append(',');
|
||||
}
|
||||
first = false;
|
||||
writeValue(out, items.next(), depth + 1);
|
||||
}
|
||||
out.append(']');
|
||||
}
|
||||
|
||||
private static ThreadFactory daemonThreads(String name) {
|
||||
return runnable -> {
|
||||
Thread thread = new Thread(runnable, name);
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
};
|
||||
}
|
||||
|
||||
private static String trimOrEmpty(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
private static String trimTrailingSlashes(String value) {
|
||||
int end = value.length();
|
||||
while (end > 0 && value.charAt(end - 1) == '/') {
|
||||
end--;
|
||||
}
|
||||
return value.substring(0, end);
|
||||
}
|
||||
|
||||
/** The credentials for a base URL and token, or null when either is blank, which disables shipping. */
|
||||
private static Credentials credentialsFor(String baseUrl, String ingestToken) {
|
||||
String base = trimTrailingSlashes(trimOrEmpty(baseUrl));
|
||||
String token = trimOrEmpty(ingestToken);
|
||||
if (base.isEmpty() || token.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new Credentials(base + "/api/logs", token);
|
||||
}
|
||||
|
||||
/** An endpoint and bearer token, read together so one flush never pairs an old URL with a new token. */
|
||||
private static final class Credentials {
|
||||
final String endpoint;
|
||||
final String token;
|
||||
|
||||
Credentials(String endpoint, String token) {
|
||||
this.endpoint = endpoint;
|
||||
this.token = token;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,833 @@
|
||||
package com.gabriel20xx.shared.logs;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.gabriel20xx.shared.logs.LogShipper.Level;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Covers LogShipper against a local com.sun.net.httpserver.HttpServer standing in for OmniLogger. Nothing here
|
||||
* talks to a real OmniLogger. Mirrors the behaviour the Go reference's shipper_test.go checks.
|
||||
*/
|
||||
class LogShipperTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final String OCCURRED_AT_PATTERN = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z";
|
||||
/** Large enough that the 1-hour interval and the batch trigger never fire on their own in a test. */
|
||||
private static final long NEVER_MILLIS = 3_600_000L;
|
||||
private static final int NO_AUTO_BATCH = 5_000;
|
||||
private static final int DEFAULT_CAPACITY = 2_000;
|
||||
|
||||
private final List<LogShipper> shippers = new ArrayList<>();
|
||||
private FakeOmniLogger fake;
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
for (LogShipper shipper : shippers) {
|
||||
shipper.close();
|
||||
}
|
||||
shippers.clear();
|
||||
if (fake != null) {
|
||||
fake.stop();
|
||||
fake = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void levelParseAcceptsTheSharedLogVocabulary() {
|
||||
assertEquals(Level.DEBUG, Level.parse("debug"));
|
||||
assertEquals(Level.DEBUG, Level.parse(" DEBUG "));
|
||||
assertEquals(Level.INFO, Level.parse("info"));
|
||||
assertEquals(Level.INFO, Level.parse(""));
|
||||
assertEquals(Level.INFO, Level.parse(null));
|
||||
assertEquals(Level.INFO, Level.parse("bogus"));
|
||||
assertEquals(Level.WARN, Level.parse("warn"));
|
||||
assertEquals(Level.WARN, Level.parse("warning"));
|
||||
assertEquals(Level.ERROR, Level.parse("error"));
|
||||
assertEquals(Level.CRITICAL, Level.parse("critical"));
|
||||
assertEquals(Level.SILENT, Level.parse("silent"));
|
||||
assertEquals(Level.SILENT, Level.parse("none"));
|
||||
assertEquals(Level.SILENT, Level.parse("off"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wireNamesAreTheLowercaseNamesOmniLoggerExpects() {
|
||||
assertEquals("debug", Level.DEBUG.wireName());
|
||||
assertEquals("info", Level.INFO.wireName());
|
||||
assertEquals("warn", Level.WARN.wireName());
|
||||
assertEquals("error", Level.ERROR.wireName());
|
||||
assertEquals("critical", Level.CRITICAL.wireName());
|
||||
assertNull(Level.SILENT.wireName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void javaUtilLoggingLevelsMapOntoTheWireScale() {
|
||||
assertEquals(Level.ERROR, Level.fromJavaUtilLogging(java.util.logging.Level.SEVERE));
|
||||
assertEquals(Level.WARN, Level.fromJavaUtilLogging(java.util.logging.Level.WARNING));
|
||||
assertEquals(Level.INFO, Level.fromJavaUtilLogging(java.util.logging.Level.INFO));
|
||||
assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.CONFIG));
|
||||
assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.FINE));
|
||||
assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.FINEST));
|
||||
assertEquals(Level.INFO, Level.fromJavaUtilLogging(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fromEnvIsDisabledUnlessBothVariablesAreNonBlank() {
|
||||
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(null, null)::get));
|
||||
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080", null)::get));
|
||||
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(null, "token")::get));
|
||||
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(" ", "token")::get));
|
||||
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080", " ")::get));
|
||||
|
||||
LogShipper shipper = LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080/", "token")::get);
|
||||
assertNotNull(shipper);
|
||||
shipper.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledModeWritesNothingToTheConsole() {
|
||||
// With shipping disabled there is no shipper at all, so there is nothing that could print. A shipper
|
||||
// created but pointed at a dead sink must still leave the console alone on every call.
|
||||
String stderr = captureStderr(() -> {
|
||||
LogShipper shipper = shipper("http://127.0.0.1:1", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
shipper.info("quiet");
|
||||
});
|
||||
assertEquals("", stderr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void entriesAreBatchedAndSentWithBearerAuthToTheIngestPath() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl() + "/", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
captureStdout(() -> captureStderr(() -> {
|
||||
shipper.info("one");
|
||||
shipper.warn("two");
|
||||
shipper.error("three");
|
||||
shipper.critical("four");
|
||||
}));
|
||||
shipper.flush();
|
||||
|
||||
assertEquals(1, fake.requests().size(), "one flush of four entries is one request");
|
||||
Request request = fake.requests().get(0);
|
||||
assertEquals("POST", request.method);
|
||||
assertEquals("/api/logs", request.path);
|
||||
assertEquals("Bearer secret", request.authorization);
|
||||
assertEquals("application/json", request.contentType);
|
||||
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals(4, entries.size());
|
||||
assertEquals("one", entries.get(0).get("message").asText());
|
||||
assertEquals("info", entries.get(0).get("level").asText());
|
||||
assertEquals("warn", entries.get(1).get("level").asText());
|
||||
assertEquals("error", entries.get(2).get("level").asText());
|
||||
assertEquals("critical", entries.get(3).get("level").asText());
|
||||
for (JsonNode entry : entries) {
|
||||
assertEquals("megabasterd", entry.get("service").asText());
|
||||
assertTrue(entry.get("occurred_at").asText().matches(OCCURRED_AT_PATTERN),
|
||||
"occurred_at must be RFC 3339 UTC with milliseconds: " + entry.get("occurred_at").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void flushWithNothingBufferedSendsNoSecondRequest() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
shipper.info("only");
|
||||
|
||||
shipper.flush();
|
||||
shipper.flush();
|
||||
|
||||
assertEquals(1, fake.requests().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBackgroundThreadFlushesOnItsOwnInterval() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, 50L, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
shipper.info("without an explicit flush");
|
||||
|
||||
waitUntil(() -> fake.entries().size() == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reachingTheBatchSizeFlushesWithoutWaitingForTheInterval() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, 2, DEFAULT_CAPACITY);
|
||||
|
||||
shipper.info("a");
|
||||
shipper.info("b");
|
||||
|
||||
waitUntil(() -> fake.entries().size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeDrainsTheBufferAndIsIdempotent() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
shipper.info("last words");
|
||||
|
||||
shipper.close();
|
||||
shipper.close();
|
||||
shipper.info("after close is discarded");
|
||||
shipper.flush();
|
||||
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals(1, entries.size());
|
||||
assertEquals("last words", entries.get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thresholdFiltersEntriesBelowIt() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.WARN, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
shipper.info("below");
|
||||
shipper.warn("at");
|
||||
shipper.flush();
|
||||
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals(1, entries.size());
|
||||
assertEquals("at", entries.get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentThresholdShipsNothing() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.SILENT, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
shipper.critical("never shipped");
|
||||
shipper.flush();
|
||||
|
||||
assertTrue(fake.requests().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loggingNeverWritesToTheLocalConsole() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.DEBUG, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
String stdout = captureStdout(() -> captureStderr(() -> {
|
||||
shipper.debug("d");
|
||||
shipper.info("i");
|
||||
shipper.warn("w");
|
||||
shipper.error("e");
|
||||
shipper.critical("c");
|
||||
}));
|
||||
shipper.flush();
|
||||
|
||||
assertEquals("", stdout);
|
||||
assertEquals(5, fake.entries().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void messagesWithSpecialCharactersStayValidJson() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
String message = "quote \" backslash \\ newline \n cr \r tab \t bell \u0007 nul \u0000 "
|
||||
+ "unit \u0001 unicode é emoji 😀 end";
|
||||
|
||||
shipper.info(message);
|
||||
shipper.flush();
|
||||
|
||||
assertEquals(message, fake.entries().get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void structuredContextRoundTrips() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
Map<String, Object> context = new LinkedHashMap<>();
|
||||
context.put("userId", 7);
|
||||
context.put("path", "/x\"y");
|
||||
context.put("ok", true);
|
||||
context.put("ratio", 1.5);
|
||||
context.put("none", null);
|
||||
context.put("tags", java.util.Arrays.asList("a", "b"));
|
||||
Map<String, Object> nested = new LinkedHashMap<>();
|
||||
nested.put("k", "v");
|
||||
context.put("nested", nested);
|
||||
|
||||
shipper.log(Level.INFO, "with context", context);
|
||||
shipper.flush();
|
||||
|
||||
JsonNode entryContext = fake.entries().get(0).get("context");
|
||||
assertEquals(7, entryContext.get("userId").asInt());
|
||||
assertEquals("/x\"y", entryContext.get("path").asText());
|
||||
assertTrue(entryContext.get("ok").asBoolean());
|
||||
assertEquals(1.5, entryContext.get("ratio").asDouble());
|
||||
assertTrue(entryContext.get("none").isNull());
|
||||
assertEquals("b", entryContext.get("tags").get(1).asText());
|
||||
assertEquals("v", entryContext.get("nested").get("k").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnencodableContextIsOmittedAndTheEntryStillShips() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put("bad", Double.NaN);
|
||||
|
||||
shipper.log(Level.INFO, "still here", context);
|
||||
shipper.flush();
|
||||
|
||||
JsonNode entry = fake.entries().get(0);
|
||||
assertEquals("still here", entry.get("message").asText());
|
||||
assertFalse(entry.has("context"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOversizedMessageIsClampedWithTheMarker() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
shipper.info(repeat("a", 10_000));
|
||||
shipper.flush();
|
||||
|
||||
String message = fake.entries().get(0).get("message").asText();
|
||||
assertTrue(message.getBytes(StandardCharsets.UTF_8).length <= 8192);
|
||||
assertTrue(message.endsWith(" [truncated]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMultiByteMessageIsCutOnACharacterBoundary() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
// Two bytes per character, so the 8180-byte cut lands exactly on a character boundary here.
|
||||
shipper.info(repeat("é", 8192));
|
||||
shipper.flush();
|
||||
|
||||
String message = fake.entries().get(0).get("message").asText();
|
||||
assertTrue(message.getBytes(StandardCharsets.UTF_8).length <= 8192);
|
||||
assertTrue(message.endsWith(" [truncated]"));
|
||||
assertFalse(message.contains("�"), "truncation must not split a UTF-8 character");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clampMessageLeavesAShortMessageUntouched() {
|
||||
assertEquals("short", LogShipper.clampMessage("short"));
|
||||
String exactlyLimit = repeat("b", 8192);
|
||||
assertEquals(exactlyLimit, LogShipper.clampMessage(exactlyLimit));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOversizedContextIsReplacedWithTheDroppedMarker() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put("blob", repeat("x", 17_000));
|
||||
|
||||
shipper.log(Level.INFO, "big", context);
|
||||
shipper.flush();
|
||||
|
||||
JsonNode entry = fake.entries().get(0);
|
||||
assertEquals("big", entry.get("message").asText());
|
||||
assertTrue(entry.get("context").get("context_dropped").asBoolean());
|
||||
assertEquals(1, entry.get("context").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContextWithAnEscapedNulIsReplacedWithTheDroppedMarker() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put("s", "a\u0000b");
|
||||
|
||||
shipper.log(Level.INFO, "nul", context);
|
||||
shipper.flush();
|
||||
|
||||
assertTrue(fake.entries().get(0).get("context").get("context_dropped").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clampContextKeepsAnOrdinaryContextAsItIs() {
|
||||
Map<String, Object> context = new LinkedHashMap<>();
|
||||
context.put("ok", true);
|
||||
assertEquals("{\"ok\":true}", LogShipper.clampContext(context));
|
||||
assertNull(LogShipper.clampContext(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchesNeverExceedOneThousandEntries() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3_000);
|
||||
for (int i = 0; i < 1_500; i++) {
|
||||
shipper.info("entry " + i);
|
||||
}
|
||||
|
||||
shipper.flush();
|
||||
|
||||
assertEquals(1_500, fake.entries().size());
|
||||
for (Request request : fake.requests()) {
|
||||
assertTrue(JSON.readTree(request.body).size() <= 1_000);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchesStayUnderTheRequestBodyLimit() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
// Control characters are escaped to six bytes each, so every entry is about 48 KiB on the wire.
|
||||
String largeMessage = repeat("\u0001", 8192);
|
||||
for (int i = 0; i < 60; i++) {
|
||||
shipper.info(largeMessage);
|
||||
}
|
||||
|
||||
shipper.flush();
|
||||
|
||||
assertEquals(60, fake.entries().size());
|
||||
assertTrue(fake.requests().size() > 1, "60 entries of this size cannot fit one body under 2 MiB");
|
||||
for (Request request : fake.requests()) {
|
||||
assertTrue(request.body.length < 2 * 1024 * 1024, "body is " + request.body.length + " bytes");
|
||||
}
|
||||
assertEquals(8192, fake.entries().get(0).get("message").asText().length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreachableOmniLoggerNeverThrowsAndWarnsOnce() throws Exception {
|
||||
LogShipper shipper = shipper("http://127.0.0.1:1", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
shipper.info("one");
|
||||
|
||||
String stderr = captureStderr(() -> {
|
||||
shipper.flush();
|
||||
shipper.info("two");
|
||||
shipper.flush();
|
||||
});
|
||||
|
||||
assertEquals(1, countOccurrences(stderr, "[logshipper]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRejectedBatchIsDroppedAndWarnedAboutOnce() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
fake.setStatus(400);
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
String stderr = captureStderr(() -> {
|
||||
shipper.info("one");
|
||||
shipper.flush();
|
||||
shipper.info("two");
|
||||
shipper.flush();
|
||||
});
|
||||
|
||||
assertEquals(1, countOccurrences(stderr, "OmniLogger rejected"));
|
||||
assertEquals(2, fake.requests().size(), "rejected batches are not retried");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerErrorIsRetriedAndEachEntryArrivesOnceInOrder() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
fake.respondNext(503);
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
|
||||
String stderr = captureStderr(() -> {
|
||||
shipper.info("a");
|
||||
shipper.info("b");
|
||||
shipper.flush(); // refused with 503: kept for the next flush
|
||||
shipper.flush(); // accepted
|
||||
shipper.flush(); // nothing left to send
|
||||
});
|
||||
|
||||
assertEquals(1, countOccurrences(stderr, "will retry"));
|
||||
assertEquals(2, fake.requests().size(), "the refused request is sent again, and nothing else is");
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals(2, entries.size());
|
||||
assertEquals("a", entries.get(0).get("message").asText());
|
||||
assertEquals("b", entries.get(1).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedRequestEndsTheFlushAndTheRestWaitsForTheNextFlush() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
fake.respondNext(202, 503);
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3_000);
|
||||
for (int i = 0; i < 1_500; i++) {
|
||||
shipper.info("entry " + i);
|
||||
}
|
||||
|
||||
captureStderr(shipper::flush); // 1000 accepted, then 500 refused: the flush stops there
|
||||
assertEquals(2, fake.requests().size());
|
||||
assertEquals(1_000, fake.entries().size());
|
||||
|
||||
shipper.flush();
|
||||
assertEquals(3, fake.requests().size());
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals(1_500, entries.size());
|
||||
for (int i = 0; i < entries.size(); i++) {
|
||||
assertEquals("entry " + i, entries.get(i).get("message").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duringAnOutageTheBufferKeepsTheOldestEntriesUpToItsCapacity() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
fake.setStatus(503);
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3);
|
||||
|
||||
captureStderr(() -> {
|
||||
for (String message : new String[] {"a", "b", "c"}) {
|
||||
shipper.info(message);
|
||||
}
|
||||
shipper.flush(); // refused with 503: kept for retry
|
||||
shipper.info("d"); // the buffer is full, so d is dropped
|
||||
shipper.info("e"); // and e is dropped
|
||||
shipper.flush(); // still refused
|
||||
});
|
||||
|
||||
fake.setStatus(202);
|
||||
shipper.flush();
|
||||
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals(3, entries.size(), "the buffer held only its capacity");
|
||||
assertEquals("a", entries.get(0).get("message").asText());
|
||||
assertEquals("b", entries.get(1).get("message").asText());
|
||||
assertEquals("c", entries.get(2).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFullBufferDropsTheNewestEntryAndWarnsOnce() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3);
|
||||
|
||||
String stderr = captureStderr(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
shipper.info("m" + i);
|
||||
}
|
||||
});
|
||||
shipper.flush();
|
||||
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals(3, entries.size());
|
||||
assertEquals("m0", entries.get(0).get("message").asText());
|
||||
assertEquals("m2", entries.get(2).get("message").asText());
|
||||
assertEquals(1, countOccurrences(stderr, "buffer full"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fromEnvShipsToTheConfiguredServiceAndToken() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = LogShipper.fromEnv("gamestream", Level.INFO,
|
||||
env(fake.baseUrl(), "env-token")::get);
|
||||
assertNotNull(shipper);
|
||||
shippers.add(shipper);
|
||||
|
||||
shipper.error("boom");
|
||||
shipper.flush();
|
||||
|
||||
assertEquals("Bearer env-token", fake.requests().get(0).authorization);
|
||||
assertEquals("gamestream", fake.entries().get(0).get("service").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setCredentialsSendsTheNextFlushToTheNewEndpointAndToken() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = neverFlushing("http://127.0.0.1:1", "old-token");
|
||||
|
||||
shipper.setCredentials(fake.baseUrl() + "/", "new-token");
|
||||
shipper.info("after the push");
|
||||
shipper.flush();
|
||||
|
||||
assertEquals(1, fake.requests().size());
|
||||
assertEquals("/api/logs", fake.requests().get(0).path);
|
||||
assertEquals("Bearer new-token", fake.requests().get(0).authorization);
|
||||
assertEquals("after the push", fake.entries().get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankCredentialDisablesShippingAndDropsTheBuffer() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = neverFlushing(fake.baseUrl(), "token");
|
||||
shipper.info("buffered before the disable");
|
||||
|
||||
shipper.setCredentials("", "token");
|
||||
shipper.info("logged while disabled");
|
||||
shipper.flush();
|
||||
assertTrue(fake.requests().isEmpty());
|
||||
|
||||
shipper.setCredentials(fake.baseUrl(), " ");
|
||||
shipper.info("logged with a blank token");
|
||||
shipper.flush();
|
||||
assertTrue(fake.requests().isEmpty());
|
||||
|
||||
shipper.setCredentials(fake.baseUrl(), "token");
|
||||
shipper.info("after re-enabling");
|
||||
shipper.flush();
|
||||
assertEquals(1, fake.requests().size());
|
||||
assertEquals("after re-enabling", fake.entries().get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShipperBuiltWithoutCredentialsStartsDisabled() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = neverFlushing(null, "token");
|
||||
|
||||
shipper.info("dropped");
|
||||
shipper.flush();
|
||||
|
||||
assertTrue(fake.requests().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBackgroundFlusherKeepsRunningAcrossCredentialChanges() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = new LogShipper("http://127.0.0.1:1", "token", "megabasterd", Level.INFO,
|
||||
50L, NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
shippers.add(shipper);
|
||||
shipper.setCredentials("", "");
|
||||
shipper.setCredentials(fake.baseUrl(), "token");
|
||||
|
||||
shipper.info("sent by the interval, with no explicit flush");
|
||||
|
||||
waitUntil(() -> !fake.requests().isEmpty());
|
||||
assertEquals("sent by the interval, with no explicit flush",
|
||||
fake.entries().get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentCredentialChangesAreSafeAndTheLastValuesWin() throws Exception {
|
||||
fake = new FakeOmniLogger();
|
||||
LogShipper shipper = neverFlushing(fake.baseUrl(), "token");
|
||||
ExecutorService pool = Executors.newFixedThreadPool(4);
|
||||
try {
|
||||
List<Future<?>> writers = new ArrayList<>();
|
||||
for (int t = 0; t < 4; t++) {
|
||||
writers.add(pool.submit(() -> {
|
||||
for (int i = 0; i < 200; i++) {
|
||||
shipper.setCredentials(i % 2 == 0 ? "" : fake.baseUrl(), "token");
|
||||
shipper.info("noise");
|
||||
}
|
||||
}));
|
||||
}
|
||||
for (Future<?> writer : writers) {
|
||||
writer.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
|
||||
shipper.setCredentials(fake.baseUrl(), "final-token");
|
||||
shipper.info("final");
|
||||
shipper.flush();
|
||||
|
||||
List<Request> requests = fake.requests();
|
||||
assertFalse(requests.isEmpty());
|
||||
assertEquals("Bearer final-token", requests.get(requests.size() - 1).authorization);
|
||||
List<JsonNode> entries = fake.entries();
|
||||
assertEquals("final", entries.get(entries.size() - 1).get("message").asText());
|
||||
}
|
||||
|
||||
private LogShipper neverFlushing(String baseUrl, String token) {
|
||||
LogShipper shipper = new LogShipper(baseUrl, token, "megabasterd", Level.INFO, NEVER_MILLIS,
|
||||
NO_AUTO_BATCH, DEFAULT_CAPACITY);
|
||||
shippers.add(shipper);
|
||||
return shipper;
|
||||
}
|
||||
|
||||
private static Map<String, String> env(String url, String token) {
|
||||
Map<String, String> values = new HashMap<>();
|
||||
if (url != null) {
|
||||
values.put(LogShipper.ENV_URL, url);
|
||||
}
|
||||
if (token != null) {
|
||||
values.put(LogShipper.ENV_TOKEN, token);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private LogShipper shipper(String baseUrl, Level threshold, long intervalMillis, int maxBatch, int capacity) {
|
||||
LogShipper shipper = new LogShipper(baseUrl, "secret", "megabasterd", threshold, intervalMillis, maxBatch, capacity);
|
||||
shippers.add(shipper);
|
||||
return shipper;
|
||||
}
|
||||
|
||||
private static String repeat(String unit, int times) {
|
||||
StringBuilder builder = new StringBuilder(unit.length() * times);
|
||||
for (int i = 0; i < times; i++) {
|
||||
builder.append(unit);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private static int countOccurrences(String haystack, String needle) {
|
||||
int count = 0;
|
||||
int index = haystack.indexOf(needle);
|
||||
while (index >= 0) {
|
||||
count++;
|
||||
index = haystack.indexOf(needle, index + needle.length());
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void waitUntil(BooleanSupplier condition) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + 5_000L;
|
||||
while (!condition.getAsBoolean()) {
|
||||
if (System.currentTimeMillis() > deadline) {
|
||||
fail("condition not met within 5 seconds");
|
||||
}
|
||||
Thread.sleep(10L);
|
||||
}
|
||||
}
|
||||
|
||||
private static String captureStderr(Runnable action) {
|
||||
return capture(action, true);
|
||||
}
|
||||
|
||||
private static String captureStdout(Runnable action) {
|
||||
return capture(action, false);
|
||||
}
|
||||
|
||||
private static String capture(Runnable action, boolean stderr) {
|
||||
PrintStream original = stderr ? System.err : System.out;
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
PrintStream replacement = new PrintStream(buffer, true);
|
||||
if (stderr) {
|
||||
System.setErr(replacement);
|
||||
} else {
|
||||
System.setOut(replacement);
|
||||
}
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
if (stderr) {
|
||||
System.setErr(original);
|
||||
} else {
|
||||
System.setOut(original);
|
||||
}
|
||||
}
|
||||
return new String(buffer.toByteArray(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** One request received by the fake OmniLogger, and the status it answered with. */
|
||||
private static final class Request {
|
||||
final String method;
|
||||
final String path;
|
||||
final String authorization;
|
||||
final String contentType;
|
||||
final byte[] body;
|
||||
final int status;
|
||||
|
||||
Request(String method, String path, String authorization, String contentType, byte[] body, int status) {
|
||||
this.method = method;
|
||||
this.path = path;
|
||||
this.authorization = authorization;
|
||||
this.contentType = contentType;
|
||||
this.body = body;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** A stand-in OmniLogger that records every POST to it. */
|
||||
private static final class FakeOmniLogger {
|
||||
private final HttpServer server;
|
||||
private final List<Request> requests = Collections.synchronizedList(new ArrayList<Request>());
|
||||
private final Deque<Integer> nextStatuses = new ArrayDeque<>();
|
||||
private volatile int status = 202;
|
||||
|
||||
FakeOmniLogger() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
byte[] body = readAll(exchange.getRequestBody());
|
||||
int answer = nextStatus();
|
||||
requests.add(new Request(exchange.getRequestMethod(), exchange.getRequestURI().getPath(),
|
||||
exchange.getRequestHeaders().getFirst("Authorization"),
|
||||
exchange.getRequestHeaders().getFirst("Content-Type"), body, answer));
|
||||
exchange.sendResponseHeaders(answer, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
}
|
||||
|
||||
String baseUrl() {
|
||||
return "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
}
|
||||
|
||||
/** The status answered to every request that respondNext does not script. */
|
||||
void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
/** Answers the next requests with these statuses, in order, before the status from setStatus applies. */
|
||||
void respondNext(int... statuses) {
|
||||
synchronized (nextStatuses) {
|
||||
for (int answer : statuses) {
|
||||
nextStatuses.addLast(answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int nextStatus() {
|
||||
synchronized (nextStatuses) {
|
||||
Integer scripted = nextStatuses.pollFirst();
|
||||
return scripted != null ? scripted : status;
|
||||
}
|
||||
}
|
||||
|
||||
void stop() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
List<Request> requests() {
|
||||
synchronized (requests) {
|
||||
return new ArrayList<>(requests);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every entry from every batch OmniLogger accepted so far, in arrival order. */
|
||||
List<JsonNode> entries() {
|
||||
List<JsonNode> all = new ArrayList<>();
|
||||
for (Request request : requests()) {
|
||||
if (request.status < 200 || request.status >= 300) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
for (JsonNode entry : JSON.readTree(request.body)) {
|
||||
all.add(entry);
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
throw new IllegalStateException("request body is not JSON: " + ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
private static byte[] readAll(InputStream in) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[8192];
|
||||
int read;
|
||||
while ((read = in.read(buffer)) != -1) {
|
||||
out.write(buffer, 0, read);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user