feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink (#2656)

* feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink

The JobManager/TaskManager now start with a log4j-console.properties
that formats every log line as a single JSON object matching real
Managed Service for Apache Flink's CloudWatch Logs schema
(applicationARN, applicationVersionId, locationInformation, logger,
message, messageSchemaVersion, messageType, threadName,
throwableInformation), instead of the stock image's default plain-text
pattern. Applies to Flink's own framework logs and anything a deployed
JAR logs through SLF4J/Log4j2, so a JAR that expects its logs to reach
CloudWatch (or asserts on this schema) sees the same thing here as on
real MSF.

Written into the container before the JVM starts -- log4j2 reads its
config at process boot, so copying the file in after start (the way
application_properties.json already is) would be too late. Required
splitting the JobManager/TaskManager container startup from
createAndStart into create + copyFileIntoContainer + startCreated,
mirroring the create-then-inject-then-start pattern
ContainerLifecycleManager already exposed for exactly this purpose.

* fix(kinesisanalytics): escape log4j2 pattern injection and fail loudly on log4j copy failure

ApplicationName flows unvalidated into the ARN baked into the JSON log
pattern, so a name containing '%' could be interpreted as a log4j2
conversion specifier and a '"' or '\' could break the emitted JSON.
Escape both before embedding, reusing the existing %enc{}{JSON}
wrapper to JSON-encode the value at log time.

Also stop silently swallowing a failed log4j-console.properties copy:
startCluster previously reported success and ran with the stock
(non-JSON) log format if the copy failed. The copy is now required,
so a failure rolls back the cluster the same way a create() failure
already does.

* fix(kinesisanalytics): validate ApplicationName, fix NPE, and block log4j2 Lookup injection

CI failure: startClusterLabelsJobManagerContainerWithResourceIdentity
built a FlinkApplication with no ARN set, and literalForLog4j2Pattern
NPE'd on the null value. Wrap both baked-in values with
String.valueOf() so a null degrades to the literal text "null"
instead of throwing.

Also validate ApplicationName against AWS's real CreateApplication
constraint (Pattern: [a-zA-Z0-9_.-]+, 1-128 chars) instead of only
requiring it non-blank -- this is both a genuine AWS-parity fix and
what keeps '%', '"', '\', or '$' out of the generated log4j2 pattern
in the first place.

Finally, close a gap the previous escaping missed: '$' wasn't
neutralized, so a name containing a log4j2 Lookup ('${env:...}',
'${sys:...}') would have it resolved against the process environment
at config-load time and baked into every emitted log line. Doubling
'$' the way '%' is doubled only defers the lookup to render time
rather than neutralizing it, so literalForLog4j2Pattern now drops '$'
outright.

* fix(kinesisanalytics): reject legacy invalid ApplicationName at StartApplication too

Greptile follow-up: an application persisted before the
ApplicationName validation existed (e.g. one with '$' in its name)
would bypass CreateApplication's new check entirely, and
StartApplication would silently generate a CloudWatch-log
applicationARN with the '$' dropped -- mismatching the real
ApplicationARN.

I verified empirically (a standalone harness against the actual
log4j-core jar) that there's no safe way to preserve '$' here: doubling
it or backslash-escaping it both still let log4j2 resolve the Lookup
and leak the referenced environment variable, so dropping it was the
only safe option. Given that, StartApplication now re-validates the
name and fails loudly for such legacy state instead of quietly
emitting a mismatched ARN -- real AWS could never have had this state
to begin with, so refusing to start it is the more AWS-faithful
outcome anyway.

* fix(kinesisanalytics): fix test compile error from Mockito generic inference

when(storageFactory.create(...)).thenReturn(store) failed to compile:
create()'s type parameter defaults to Object with no target-type
context to unify against the pre-declared, concretely-typed 'store'
variable, so thenReturn(store) rejected it as a type mismatch.
Switch to doReturn(store).when(storageFactory).create(...), matching
the same pattern already used for this exact scenario elsewhere in
this file (readinessPollerPersistsFlinkJobIdAssignedBeforeReachingRunning).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-29 09:15:52 -05:00
1 parent ff61c2b2a5
commit aaae99282f
5 files changed
+277 -9

No files matched your search

@@ -27,6 +27,7 @@ import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Control plane for Managed Service for Apache Flink (Kinesis Analytics V2). Holds the
@@ -43,6 +44,9 @@ public class KinesisAnalyticsV2Service {
private static final Logger LOG = Logger.getLogger(KinesisAnalyticsV2Service.class);
// AWS: ApplicationName Length Constraints: 1-128, Pattern: [a-zA-Z0-9_.-]+
private static final Pattern APPLICATION_NAME = Pattern.compile("[a-zA-Z0-9_.-]{1,128}");
// AWS: "the maximum number of user-defined application tags is 50" (the stated 200-tag ceiling
// on the Tags/TagKeys shapes includes AWS-managed system tags, which floci does not model).
private static final int MAX_USER_TAGS = 50;
@@ -137,6 +141,11 @@ public class KinesisAnalyticsV2Service {
if (applicationName == null || applicationName.isBlank()) {
throw new AwsException("InvalidArgumentException", "ApplicationName is required", 400);
}
if (!APPLICATION_NAME.matcher(applicationName).matches()) {
throw new AwsException("InvalidArgumentException",
"ApplicationName '" + applicationName
+ "' does not match the required pattern [a-zA-Z0-9_.-]{1,128}", 400);
}
if (runtimeEnvironment == null || runtimeEnvironment.isBlank()) {
throw new AwsException("InvalidArgumentException", "RuntimeEnvironment is required", 400);
}
@@ -197,6 +206,20 @@ public class KinesisAnalyticsV2Service {
public FlinkApplication startApplication(String applicationName) {
FlinkApplication app = describeApplication(applicationName);
// Defends state persisted by a floci build older than the ApplicationName check in
// createApplication: applicationARN is baked as literal text into the CloudWatch-log-format
// config FlinkContainerManager writes on startup, and a name outside AWS's charset (most
// notably '$', which can't be escaped to a safe literal there -- see
// FlinkContainerManager#literalForLog4j2Pattern) either gets dropped from every emitted
// applicationARN (breaking correlation with the real ApplicationARN) or, if ever un-dropped,
// risks leaking an environment variable/system property via a log4j2 Lookup. Failing loudly
// here beats either outcome, and real AWS could never have had this state to begin with.
if (!APPLICATION_NAME.matcher(applicationName).matches()) {
throw new AwsException("InvalidArgumentException",
"ApplicationName '" + applicationName + "' does not match the required pattern "
+ "[a-zA-Z0-9_.-]{1,128}; this application predates that validation and "
+ "must be deleted and recreated with a valid name", 400);
}
if (app.getApplicationStatus() != ApplicationStatus.READY) {
throw new AwsException("ResourceInUseException",
"Application " + applicationName + " cannot be started while in state "
@@ -170,9 +170,17 @@ public class FlinkContainerManager {
jmSpec.withExposedPort(JOBMANAGER_REST_PORT);
}
ContainerSpec jmBuiltSpec = jmSpec.build();
ContainerInfo jm;
try {
jm = lifecycleManager.createAndStart(jmSpec.build());
String jmContainerId = lifecycleManager.create(jmBuiltSpec);
// Written before start (not via the post-start copyFileIntoContainer used for
// application_properties.json below) because log4j2 reads its config file at JVM
// startup -- copying it in after the process is already running would be too late for
// anything the JobManager logs from its own boot onward.
copyFileIntoContainer(jmContainerId, "/opt/flink/conf", "log4j-console.properties",
msfStyleLog4j2Config(app), true);
jm = lifecycleManager.startCreated(jmContainerId, jmBuiltSpec);
} catch (RuntimeException e) {
lifecycleManager.removeIfExists(jmName);
throw e;
@@ -202,7 +210,10 @@ public class FlinkContainerManager {
regionResolver.getDefaultRegion()))
.build();
try {
ContainerInfo tm = lifecycleManager.createAndStart(tmSpec);
String tmContainerId = lifecycleManager.create(tmSpec);
copyFileIntoContainer(tmContainerId, "/opt/flink/conf", "log4j-console.properties",
msfStyleLog4j2Config(app), true);
ContainerInfo tm = lifecycleManager.startCreated(tmContainerId, tmSpec);
app.setTaskManagerContainerId(tm.containerId());
taskManagerIds.put(app.getApplicationName(), tm.containerId());
} catch (RuntimeException e) {
@@ -249,7 +260,88 @@ public class FlinkContainerManager {
}
}
/** Builds a log4j2 {@code log4j-console.properties} that makes the JobManager/TaskManager emit
* one JSON object per log line, matching the schema real Managed Service for Apache Flink
* writes to CloudWatch Logs (applicationARN/applicationVersionId/locationInformation/logger/
* message/messageSchemaVersion/messageType/threadName/throwableInformation) -- so a JAR relying
* on that shape for its own log-based tests sees the same thing here as on real MSF. Overwrites
* the stock image's default (non-JSON) config entirely; not re-applied on {@link #redeployCode},
* so applicationVersionId in already-emitted log lines does not advance across an in-place code
* update (the JobManager/TaskManager JVMs, and therefore log4j2, are not restarted for that --
* matching real MSF, which also keeps the same processes running across an UpdateApplication).
* Package-private (not private) so FlinkContainerManagerTest can assert on the pattern shape
* directly. */
byte[] msfStyleLog4j2Config(FlinkApplication app) {
String pattern = "{"
+ "\"applicationARN\":\"%enc{"
+ literalForLog4j2Pattern(String.valueOf(app.getApplicationArn())) + "}{JSON}\","
+ "\"applicationVersionId\":\"%enc{"
+ literalForLog4j2Pattern(String.valueOf(app.getApplicationVersionId())) + "}{JSON}\","
+ "\"locationInformation\":\"%C.%M(%F:%L)\","
+ "\"logger\":\"%logger\","
+ "\"message\":\"%enc{%message}{JSON}\","
+ "\"messageSchemaVersion\":\"1\","
+ "\"messageType\":\"%level\","
+ "\"threadName\":\"%enc{%thread}{JSON}\","
+ "\"throwableInformation\":\"%enc{%ex}{JSON}\""
+ "}%n";
String properties = "rootLogger.level = INFO\n"
+ "rootLogger.appenderRef.console.ref = ConsoleAppender\n"
+ "appender.console.type = Console\n"
+ "appender.console.name = ConsoleAppender\n"
+ "appender.console.layout.type = PatternLayout\n"
+ "appender.console.layout.pattern = " + pattern + "\n";
return properties.getBytes(StandardCharsets.UTF_8);
}
/** Escapes an application-supplied value (e.g. the ARN, built from the caller's ApplicationName --
* {@link io.github.hectorvent.floci.services.kinesisanalytics.KinesisAnalyticsV2Service} restricts
* that to AWS's own {@code [a-zA-Z0-9_.-]} charset, but this stays defensive in case some other
* caller ever feeds it something else) so it can be embedded as literal text inside a log4j2
* {@code PatternLayout} pattern written to a {@code .properties} file: doubles {@code %} so
* log4j2's pattern parser can't interpret it as the start of a conversion specifier, drops
* {@code $} so it can't start a {@code ${...}} Lookup (log4j2 resolves those against config
* values -- including this pattern -- at config-load time, so an unescaped one could leak an
* environment variable or system property into every log line; doubling it like {@code %} only
* defers the lookup to render time rather than neutralizing it, so it isn't a safe escape here),
* then backslash-escapes control characters so the value survives
* {@code java.util.Properties}-style parsing of the config file intact. The surrounding
* {@code %enc{...}{JSON}} wrapper (already used for %message/%thread/%ex above) then JSON-escapes
* the resulting literal at log time, so quotes/backslashes in the original value can't break the
* emitted JSON. */
private static String literalForLog4j2Pattern(String value) {
String percentEscaped = value.replace("%", "%%");
StringBuilder escaped = new StringBuilder(percentEscaped.length());
for (int i = 0; i < percentEscaped.length(); i++) {
char c = percentEscaped.charAt(i);
switch (c) {
case '\\' -> escaped.append("\\\\");
case '$' -> { /* dropped: see method Javadoc -- can't be escaped to a safe literal */ }
case '\n' -> escaped.append("\\n");
case '\r' -> escaped.append("\\r");
case '\t' -> escaped.append("\\t");
default -> {
if (c < 0x20) {
escaped.append(String.format("\\u%04x", (int) c));
} else {
escaped.append(c);
}
}
}
}
return escaped.toString();
}
private void copyFileIntoContainer(String containerId, String remoteDir, String relativePath, byte[] content) {
copyFileIntoContainer(containerId, remoteDir, relativePath, content, false);
}
/** @param required when {@code true}, a failed copy is rethrown instead of only logged, so a
* caller for whom the file is not optional (e.g. the log4j2 config that this cluster's whole
* CloudWatch-log-shape guarantee depends on) fails the start instead of silently running with
* the stock config. */
private void copyFileIntoContainer(String containerId, String remoteDir, String relativePath, byte[] content,
boolean required) {
if (containerId == null) {
return;
}
@@ -260,6 +352,10 @@ public class FlinkContainerManager {
.withRemotePath(remoteDir)
.exec();
} catch (Exception e) {
if (required) {
throw new IllegalStateException(
"Could not copy " + relativePath + " into Flink container " + containerId, e);
}
LOG.warnv("Could not copy {0} into Flink container {1}: {2}", relativePath, containerId, e.getMessage());
}
}