Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion deploy/pilot/proxy/corvus-config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ ca_file = ""
[game_context]
default = "unknown"
# CloudNet services are named <Task>-<n> (Lobby-1, Team-Build-2). Lookup: exact server name, then the name without
# one trailing "-<digits>" (Lobby-2 -> lobby), then default; case-insensitive. false = exact names only.
# one trailing "-<digits>" (Lobby-2 -> lobby), then the CloudNet task (when CloudNet is present; Slender-Staging-1 ->
# task Slender-Staging -> entry or "slender"), then default; case-insensitive. false = exact names only.
strip_instance_suffix = true

# server name (see velocity.toml) or CloudNet task name = game context tag
Expand Down
7 changes: 6 additions & 1 deletion docs/pilot.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,12 @@ ones the plugin reads (`PilotConfigTest` fails if it contains a key the plugin i
mapping `lobby -> lobby`, `pvp -> pvp` (a backend named `<Task>-<n>`, as CloudNet services are, falls back to
its task name: `Lobby-2` maps via `lobby`; exact names win, only one trailing `-<digits>` is removed, and
`game_context.strip_instance_suffix = false` turns this off), pseudonym key id `pilot-1`, and the payload policy below. The
HMAC key itself is read from the environment variable `CORVUS_PSEUDONYM_KEY` (base64, at least 16
pilot runs without CloudNet on the plugin's class path, so only this list applies and `stage` stays empty. On a proxy
that runs as a CloudNet v4 service, a server missing from the list falls back to its CloudNet task: the list may
name the task (`[game_context.servers]`), otherwise the task in lower case without a `-Staging` suffix is the context
(`Slender-Staging-1` -> `slender`). The segment then records `stage` = `staging` when the task ends with `-Staging` or
a CloudNet group is named `Staging`, and `production` otherwise. The CloudNet task, groups, node and environment are
recorded per segment as well. The HMAC key itself is read from the environment variable `CORVUS_PSEUDONYM_KEY` (base64, at least 16
bytes). The plugin writes `plugins/corvus/captures/<yyyy-MM-dd>/<session-id>.cvc`, which is bind
mounted from `deploy/pilot/data/captures`; the one-shot `stage-corvus` service makes that directory
writable for the proxy user (uid 1000).
Expand Down
3 changes: 3 additions & 0 deletions plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ dependencies {
compileOnly("com.google.code.gson:gson:2.15.0")
compileOnly("io.netty:netty-buffer:$nettyVersion")
compileOnly("io.netty:netty-transport:$nettyVersion")
// Optional: CloudNet service metadata when the proxy runs as a CloudNet v4 service. Matches the production
// CloudNet version. compileOnly keeps it out of the shaded jar; cloudnet/CloudNetAvailability detects it at runtime.
compileOnly("eu.cloudnetservice.cloudnet:driver-api:4.0.0-RC17")

testImplementation("com.velocitypowered:velocity-api:$velocityVersion")
testImplementation("com.github.retrooper:packetevents-api:$packetEventsVersion")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package net.onelitefeather.corvus.plugin.capture;

/**
* The game context and stage of one backend connection. {@code stage} is "production", "staging" or empty when the
* orchestrator does not know the server.
*/
public record BackendContext(String gameContext, String stage) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package net.onelitefeather.corvus.plugin.capture;

import net.onelitefeather.corvus.plugin.score.RateLimitedLog;
import net.onelitefeather.corvus.plugin.time.NanoClock;

import java.time.Duration;
import java.time.InstantSource;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

/**
* Caches lookups of a {@link ServiceMetadataSource} for a fixed time, negative answers included, so that a server
* which is not an orchestrator service costs one lookup per interval. A failing delegate is treated as "unknown"
* and logged at most once per minute. Never throws.
*/
public final class CachedServiceMetadataSource implements ServiceMetadataSource {

private record Entry(Optional<ServiceMetadata> value, long expiresAtMillis) {
}

private final ServiceMetadataSource delegate;
private final InstantSource clock;
private final long ttlMillis;
private final RateLimitedLog failures;
private final Map<String, Entry> entries = new ConcurrentHashMap<>();

public CachedServiceMetadataSource(ServiceMetadataSource delegate, InstantSource clock, Duration ttl,
Consumer<String> warn) {
this(delegate, clock, ttl, warn, NanoClock.system());
}

public CachedServiceMetadataSource(ServiceMetadataSource delegate, InstantSource clock, Duration ttl,
Consumer<String> warn, NanoClock nanoClock) {
this.delegate = delegate;
this.clock = clock;
this.ttlMillis = ttl.toMillis();
this.failures = new RateLimitedLog(nanoClock, warn, RateLimitedLog.DEFAULT_INTERVAL_NANOS);
}

@Override
public Optional<ServiceMetadata> lookup(String serverName) {
if (serverName == null || serverName.isEmpty()) {
return Optional.empty();
}
long now = clock.millis();
Entry cached = entries.get(serverName);
if (cached != null && now < cached.expiresAtMillis()) {
return cached.value();
}
Optional<ServiceMetadata> value;
try {
value = delegate.lookup(serverName);
if (value == null) {
value = Optional.empty();
}
} catch (Throwable t) {
failures.warn("orchestrator lookup failed, game context falls back to the list: "
+ t.getClass().getSimpleName());
value = Optional.empty();
}
entries.put(serverName, new Entry(value, now + ttlMillis));
return value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.time.InstantSource;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
Expand All @@ -42,6 +43,7 @@ public Settings(PayloadMode payloadMode, int maxPayloadBytes, String proxyId, St
private final Pseudonymizer pseudonymizer; // null: fail closed, nothing is captured
private final PlayerFilter playerFilter;
private final GameContextMapper contexts;
private final ServiceMetadataSource serviceMetadata;
private final CaptureSink sink;
private final NanoClock nanoClock;
private final InstantSource wallClock;
Expand All @@ -52,13 +54,15 @@ public Settings(PayloadMode payloadMode, int maxPayloadBytes, String proxyId, St
private volatile boolean shutdown;

public CaptureEngine(Settings settings, Pseudonymizer pseudonymizer, PlayerFilter playerFilter,
GameContextMapper contexts, CaptureSink sink, NanoClock nanoClock, InstantSource wallClock,
Supplier<byte[]> sessionIds, Metrics metrics, Consumer<String> info) {
GameContextMapper contexts, ServiceMetadataSource serviceMetadata, CaptureSink sink,
NanoClock nanoClock, InstantSource wallClock, Supplier<byte[]> sessionIds, Metrics metrics,
Consumer<String> info) {
this.settings = settings;
this.payloadPolicy = new PayloadPolicy(settings.payloadMode(), settings.privacy());
this.pseudonymizer = pseudonymizer;
this.playerFilter = playerFilter;
this.contexts = contexts;
this.serviceMetadata = serviceMetadata;
this.sink = sink;
this.nanoClock = nanoClock;
this.wallClock = wallClock;
Expand Down Expand Up @@ -194,20 +198,37 @@ public void onBackendConnected(UUID player, String serverName, String clientBran
if (session == null || !isCapturing()) {
return;
}
SegmentStart segment = SegmentStart.newBuilder()
Optional<ServiceMetadata> meta = lookupServiceMetadata(serverName);
BackendContext backend = contexts.resolve(serverName, meta);
SegmentStart.Builder segmentBuilder = SegmentStart.newBuilder()
.setSessionId(session.idBytes())
.setSegment(session.nextSegment())
.setBackendServer(serverName == null ? "" : serverName)
.setGameContext(contexts.contextFor(serverName))
.setGameContext(backend.gameContext())
.setClientBrand(clientBrand == null ? "" : clientBrand)
.setStartedAtUnixMillis(wallClock.millis())
.build();
.setStage(backend.stage());
meta.ifPresent(m -> segmentBuilder.setCloudnetTask(m.task())
.addAllCloudnetGroups(m.groups())
.setCloudnetNode(m.node())
.setCloudnetEnvironment(m.environment()));
SegmentStart segment = segmentBuilder.build();
sink.offerControl(new WriteItem.Segment(session, Envelope.newBuilder().setSegmentStart(segment).build()));
} catch (Throwable t) {
recordListenerError(player);
}
}

/** Empty when the source is unknown or fails; the connect path must not depend on the orchestrator. */
private Optional<ServiceMetadata> lookupServiceMetadata(String serverName) {
try {
Optional<ServiceMetadata> found = serviceMetadata.lookup(serverName);
return found == null ? Optional.empty() : found;
} catch (Throwable t) {
return Optional.empty();
}
}

/** The player disconnected: ends the session. Never throws. */
public void onDisconnect(UUID player) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,29 @@

import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

/**
* Maps backend server names to game-context tags. Lookup order: exact (lower-cased) name, then the name without one
* trailing CloudNet instance suffix {@code -<digits>} (when enabled), then the default.
* Maps backend servers to game-context tags and stages. Resolution order:
* <ol>
* <li>the explicit entry for the server name: exact (lower-cased) name, then the name without one trailing
* CloudNet instance suffix {@code -<digits>} (when enabled)</li>
* <li>the explicit entry for the CloudNet task name</li>
* <li>the CloudNet task name, lower-cased, without a trailing {@value #STAGING_SUFFIX}</li>
* <li>the configured default</li>
* </ol>
* Steps 2 and 3 need CloudNet metadata; without it the mapper is the plain server-name list.
*/
public final class GameContextMapper {

private static final Pattern INSTANCE_SUFFIX = Pattern.compile("-\\d+$");

/** Task names ending with this (case-insensitive) are staging services. Fixed; not configurable. */
static final String STAGING_SUFFIX = "-staging";
/** A CloudNet group with this name (case-insensitive) marks staging services. Fixed; not configurable. */
static final String STAGING_GROUP = "Staging";

private final Map<String, String> servers;
private final String defaultContext;
private final boolean stripInstanceSuffix;
Expand All @@ -26,9 +39,30 @@ public GameContextMapper(Map<String, String> servers, String defaultContext, boo
this.stripInstanceSuffix = stripInstanceSuffix;
}

/** The list-only resolution (no orchestrator metadata). */
public String contextFor(String serverName) {
String context = explicitContext(serverName);
return context == null ? defaultContext : context;
}

/**
* Resolves the game context and stage of one backend connection.
*
* @param metadata the orchestrator's view of the server, empty when unknown
*/
public BackendContext resolve(String serverName, Optional<ServiceMetadata> metadata) {
ServiceMetadata meta = metadata == null ? null : metadata.orElse(null);
String context = explicitContext(serverName);
if (context == null && meta != null) {
context = contextForTask(meta.task());
}
return new BackendContext(context == null ? defaultContext : context, stageOf(meta));
}

/** @return the explicit entry for the server name, or {@code null} when the list has none */
private String explicitContext(String serverName) {
if (serverName == null) {
return defaultContext;
return null;
}
String name = serverName.toLowerCase(Locale.ROOT);
String exact = servers.get(name);
Expand All @@ -38,9 +72,33 @@ public String contextFor(String serverName) {
if (stripInstanceSuffix) {
String task = INSTANCE_SUFFIX.matcher(name).replaceFirst("");
if (!task.equals(name) && !task.isEmpty()) {
return servers.getOrDefault(task, defaultContext);
return servers.get(task);
}
}
return defaultContext;
return null;
}

/** @return the explicit entry for the task, else the task without a staging suffix, or {@code null} */
private String contextForTask(String task) {
if (task == null || task.isEmpty()) {
return null;
}
String name = task.toLowerCase(Locale.ROOT);
String explicit = servers.get(name);
if (explicit != null) {
return explicit;
}
String base = name.endsWith(STAGING_SUFFIX) ? name.substring(0, name.length() - STAGING_SUFFIX.length()) : name;
return base.isEmpty() ? null : base;
}

/** "staging" for a staging task or group, "production" for any other known service, empty when unknown. */
static String stageOf(ServiceMetadata meta) {
if (meta == null) {
return "";
}
boolean staging = meta.task().toLowerCase(Locale.ROOT).endsWith(STAGING_SUFFIX)
|| meta.groups().stream().anyMatch(STAGING_GROUP::equalsIgnoreCase);
return staging ? "staging" : "production";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package net.onelitefeather.corvus.plugin.capture;

import java.util.List;
import java.util.Objects;

/**
* What the orchestrator knows about a backend server: task, groups, node and environment of the service. Built by a
* {@link ServiceMetadataSource}; the plugin never depends on the orchestrator's classes outside that source.
*/
public record ServiceMetadata(String task, List<String> groups, String node, String environment) {

public ServiceMetadata {
task = Objects.requireNonNullElse(task, "");
groups = groups == null ? List.of() : groups.stream().filter(Objects::nonNull).toList();
node = Objects.requireNonNullElse(node, "");
environment = Objects.requireNonNullElse(environment, "");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package net.onelitefeather.corvus.plugin.capture;

import java.util.Optional;

/**
* Looks up the orchestrator's view of a backend server by its Velocity server name. Implementations must never
* throw and should answer from memory: this is called on the proxy's connect path.
*/
@FunctionalInterface
public interface ServiceMetadataSource {

/** Used when no orchestrator is available: every server is unknown. */
ServiceMetadataSource NONE = serverName -> Optional.empty();

Optional<ServiceMetadata> lookup(String serverName);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package net.onelitefeather.corvus.plugin.cloudnet;

import net.onelitefeather.corvus.plugin.capture.CachedServiceMetadataSource;
import net.onelitefeather.corvus.plugin.capture.ServiceMetadataSource;

import java.time.Duration;
import java.time.InstantSource;
import java.util.function.Consumer;

/**
* Chooses the service metadata source at startup. CloudNet is optional: without its classes on the class path (the
* pilot runs without it) the source is {@link ServiceMetadataSource#NONE}. The CloudNet classes are compiled against
* but never shaded into the plugin jar, so the implementation is only instantiated by reflection here.
*/
public final class CloudNetAvailability {

/** Answers are reused this long; a server that CloudNet does not know is looked up once per interval. */
public static final Duration CACHE_TTL = Duration.ofSeconds(30);

static final String DRIVER_MARKER = "eu.cloudnetservice.driver.registry.ServiceRegistry";
static final String SOURCE_CLASS = "net.onelitefeather.corvus.plugin.cloudnet.CloudNetServiceMetadataSource";

private CloudNetAvailability() {
}

/** @return {@code true} when the CloudNet driver classes are visible to the given class loader */
public static boolean present(ClassLoader loader) {
try {
Class.forName(DRIVER_MARKER, false, loader);
return true;
} catch (ClassNotFoundException | LinkageError e) {
return false;
}
}

/**
* @return a cached CloudNet source when CloudNet is present and usable, otherwise {@link ServiceMetadataSource#NONE}.
* Never throws.
*/
public static ServiceMetadataSource load(ClassLoader loader, InstantSource clock, Consumer<String> info,
Consumer<String> warn) {
if (!present(loader)) {
info.accept("CloudNet is not on the class path: game context comes from [game_context.servers] only");
return ServiceMetadataSource.NONE;
}
try {
Class<?> type = Class.forName(SOURCE_CLASS, true, loader);
ServiceMetadataSource source = (ServiceMetadataSource) type.getDeclaredConstructor().newInstance();
info.accept("CloudNet detected: game context and stage fall back to CloudNet service metadata");
return new CachedServiceMetadataSource(source, clock, CACHE_TTL, warn);
} catch (Throwable t) {
warn.accept("CloudNet is on the class path but unusable (" + t.getClass().getSimpleName()
+ "); game context comes from [game_context.servers] only");
return ServiceMetadataSource.NONE;
}
}
}
Loading
Loading