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
115 changes: 115 additions & 0 deletions src/main/java/com/datadog/NamedPipeNames.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package com.datadog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

/** The settings that name one of a function's two pipes. */
enum NamedPipe {
TRACE("DD_APM_WINDOWS_PIPE_NAME", "dd.trace.pipe.name", "DD_TRACE_PIPE_NAME", "dd_trace_"),
DOGSTATSD("DD_DOGSTATSD_WINDOWS_PIPE_NAME", "dd.dogstatsd.pipe.name", "DD_DOGSTATSD_PIPE_NAME",
"dd_dogstatsd_");

/** The binary's setting. */
final String windowsPipeNameEnv;
/** The tracer's JVM option, which it reads before {@link #tracerEnv}. */
final String tracerProperty;
final String tracerEnv;
final String generatedPrefix;

NamedPipe(String windowsPipeNameEnv, String tracerProperty, String tracerEnv, String generatedPrefix) {
this.windowsPipeNameEnv = windowsPipeNameEnv;
this.tracerProperty = tracerProperty;
this.tracerEnv = tracerEnv;
this.generatedPrefix = generatedPrefix;
}
}

/**
* Chooses the trace and DogStatsD pipe names for one function: the binary's
* *_WINDOWS_PIPE_NAME setting, then a name the customer already set for the tracer, then a
* generated per-function name.
*/
final class NamedPipeNames {
static final int MAX_PIPE_NAME_LENGTH = 256;

final String tracePipeName;
final String dogstatsdPipeName;
final List<String> warnings;

private NamedPipeNames(String tracePipeName, String dogstatsdPipeName, List<String> warnings) {
this.tracePipeName = tracePipeName;
this.dogstatsdPipeName = dogstatsdPipeName;
this.warnings = Collections.unmodifiableList(warnings);
}

/**
* @param tracerGetsPipes whether dd-java-agent will be given the chosen names, which only
* changes the wording of the warnings
*/
static NamedPipeNames choose(Map<String, String> env, Properties systemProperties, boolean tracerGetsPipes) {
List<String> warnings = new ArrayList<>();
String tracePipeName = choosePipeName(NamedPipe.TRACE, env, systemProperties, tracerGetsPipes, warnings);
String dogstatsdPipeName =
choosePipeName(NamedPipe.DOGSTATSD, env, systemProperties, tracerGetsPipes, warnings);
return new NamedPipeNames(tracePipeName, dogstatsdPipeName, warnings);
}

private static String choosePipeName(NamedPipe pipe, Map<String, String> env, Properties systemProperties,
boolean tracerGetsPipes, List<String> warnings) {
// The tracer reads system properties before environment variables, so a JVM option
// the customer passed is the customer-set name when both are present.
String customerSetName = nonEmpty(systemProperties.getProperty(pipe.tracerProperty));
String customerSetSource = pipe.tracerProperty;
if (customerSetName == null) {
customerSetName = nonEmpty(env.get(pipe.tracerEnv));
customerSetSource = pipe.tracerEnv;
}

String windowsPipeName = nonEmpty(env.get(pipe.windowsPipeNameEnv));

// The binary's *_WINDOWS_PIPE_NAME setting wins over the customer-set tracer name, so
// warn when the customer set two different names. When dd-java-agent gets the chosen
// name, its own setting is replaced. Otherwise it keeps its own setting, and the two
// sides use different pipes.
if (windowsPipeName != null && customerSetName != null && !customerSetName.equals(windowsPipeName)) {
String outcome = tracerGetsPipes
? String.format("Both the binary and dd-java-agent use %s.", pipe.windowsPipeNameEnv)
: String.format("The binary uses %s, and dd-java-agent keeps %s.", pipe.windowsPipeNameEnv,
customerSetSource);
warnings.add(String.format("%s ('%s') differs from %s ('%s'). %s", customerSetSource,
customerSetName, pipe.windowsPipeNameEnv, windowsPipeName, outcome));
}

// Use the first name that is set: the binary's setting, then the customer-set tracer name.
String pipeName = windowsPipeName;
String source = pipe.windowsPipeNameEnv;
if (pipeName == null) {
pipeName = customerSetName;
source = customerSetSource;
}

// With neither set, generate a name that is unique to this function. Generated names
// are always short enough, so only a name the customer set needs the length check.
if (pipeName == null) {
return pipe.generatedPrefix + UUID.randomUUID().toString().replace("-", "");
}
warnIfTooLong(source, pipeName, warnings);
return pipeName;
}

private static void warnIfTooLong(String source, String pipeName, List<String> warnings) {
if (pipeName.length() > MAX_PIPE_NAME_LENGTH) {
warnings.add(String.format(
"%s is %d characters long. Windows pipe names can be at most %d characters.",
source, pipeName.length(), MAX_PIPE_NAME_LENGTH));
}
}

private static String nonEmpty(String value) {
return value == null || value.isEmpty() ? null : value;
}
}
66 changes: 66 additions & 0 deletions src/main/java/com/datadog/ServerlessCompatAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.NOPLogger;
Expand Down Expand Up @@ -43,6 +44,8 @@ private static String mapDdLogLevelToSlf4jLogLevel(String ddLogLevel) {

private static final String os = System.getProperty("os.name").toLowerCase();
private static final String binaryPath = System.getenv("DD_SERVERLESS_COMPAT_PATH");
static final String DOGSTATSD_PORT_ENV = "DD_DOGSTATSD_PORT";
static final String DEFAULT_DOGSTATSD_PORT = "8125";

public static boolean isWindows() {
return os.contains("win");
Expand Down Expand Up @@ -106,6 +109,66 @@ public static boolean isAzureFlexWithoutDDAzureResourceGroup() {
&& System.getenv("DD_AZURE_RESOURCE_GROUP") == null;
}

/**
* Chooses this function's named pipes. Always gives the binary its own pipes, so binaries on a
* shared instance don't fight over one port.
*
* <p>Sets dd-java-agent's pipe system properties only when the gate passes, and before the
* tracer's premain runs. An older tracer never sees the generated names.
*
* @return the chosen pipe names for the binary
*/
static NamedPipeNames configureNamedPipes() {
return configureNamedPipes(TracerVersionGate.check(), System.getenv(), System.getProperties());
}

static NamedPipeNames configureNamedPipes(TracerVersionGate gate, Map<String, String> env,
Properties systemProperties) {
NamedPipeNames pipeNames = NamedPipeNames.choose(env, systemProperties, gate.passed);

if (!gate.passed) {
log.info("Not giving dd-java-agent named pipes because {}. The binary listens on pipes {} and {}, "
+ "and also tries the usual TCP and UDP ports.",
gate.reason, pipeNames.tracePipeName, pipeNames.dogstatsdPipeName);
logWarnings(pipeNames);
return pipeNames;
}
log.debug("Giving dd-java-agent named pipes because {}", gate.reason);
if (gate.tracerListedBeforeCompat) {
log.warn("dd-java-agent is listed before the Datadog Serverless Compatibility Layer in the JVM's "
+ "-javaagent options, so it may have read its settings before the named pipes were set and "
+ "keep sending traces and its own metrics over TCP and UDP. List the Compatibility Layer's "
+ "-javaagent option first.");
}

systemProperties.setProperty(NamedPipe.TRACE.tracerProperty, pipeNames.tracePipeName);
systemProperties.setProperty(NamedPipe.DOGSTATSD.tracerProperty, pipeNames.dogstatsdPipeName);
log.info("Configured named pipes - Trace: {}, DogStatsD: {}",
pipeNames.tracePipeName, pipeNames.dogstatsdPipeName);
logWarnings(pipeNames);
return pipeNames;
}

// Logged after the gate decision, so the warnings follow the log line that says whether
// dd-java-agent got the pipes.
private static void logWarnings(NamedPipeNames pipeNames) {
for (String warning : pipeNames.warnings) {
log.warn(warning);
}
}

/**
* Passes the pipe names to the binary and asks it to keep UDP too. With a pipe, the binary
* listens on UDP only when {@code DD_DOGSTATSD_PORT} is set. A JVM can't change its own
* environment, so DogStatsD clients that don't read {@code dd.dogstatsd.pipe.name}, or can't
* open the pipe, still send to UDP 8125. A port the customer set wins.
*/
static void addPipeSettings(Map<String, String> binaryEnvironment, NamedPipeNames pipeNames) {
binaryEnvironment.put(NamedPipe.TRACE.windowsPipeNameEnv, pipeNames.tracePipeName);
binaryEnvironment.put(NamedPipe.DOGSTATSD.windowsPipeNameEnv, pipeNames.dogstatsdPipeName);
binaryEnvironment.putIfAbsent(DOGSTATSD_PORT_ENV, DEFAULT_DOGSTATSD_PORT);
}

public static void premain(String agentArgs, Instrumentation instrumentation) {
CloudEnvironment environment = getEnvironment();
log.debug("Environment detected: {}", environment);
Expand Down Expand Up @@ -170,6 +233,9 @@ public static void premain(String agentArgs, Instrumentation instrumentation) {
log.debug("Found package version {}", packageVersion);

ProcessBuilder processBuilder = createProcessBuilder(executableFile, packageVersion);
if (environment == CloudEnvironment.AZURE_FUNCTION && isWindows()) {
addPipeSettings(processBuilder.environment(), configureNamedPipes());
}
processBuilder.inheritIO();
processBuilder.start();
} catch (Exception e) {
Expand Down
138 changes: 138 additions & 0 deletions src/main/java/com/datadog/TracerVersionGate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package com.datadog;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Decides whether the dd-java-agent in this JVM supports named pipes. Older tracers hang
* uploading traces over a pipe and never send their own metrics over one, so pipe names are
* only handed out when the tracer is at least {@link #MINIMUM_TRACER_VERSION}.
*/
final class TracerVersionGate {
static final String TRACER_PREMAIN_CLASS = "datadog.trace.bootstrap.AgentPreCheck";
static final String COMPAT_PREMAIN_CLASS = ServerlessCompatAgent.class.getName();

// First dd-trace-java release with the named-pipe fixes (DataDog/dd-trace-java#12898).
private static final int[] MINIMUM_VERSION = {1, 69, 0};
static final String MINIMUM_TRACER_VERSION =
MINIMUM_VERSION[0] + "." + MINIMUM_VERSION[1] + "." + MINIMUM_VERSION[2];

private static final String JAVAAGENT_PREFIX = "-javaagent:";
private static final Pattern VERSION_PATTERN = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(\\D.*)?$");

final boolean passed;
final String reason;
// The JVM runs -javaagent premains in command-line order, so a tracer listed first reads its
// settings before this agent sets the pipe system properties.
final boolean tracerListedBeforeCompat;

TracerVersionGate(boolean passed, String reason, boolean tracerListedBeforeCompat) {
this.passed = passed;
this.reason = reason;
this.tracerListedBeforeCompat = tracerListedBeforeCompat;
}

static TracerVersionGate failed(String reason) {
return new TracerVersionGate(false, reason, false);
}

static TracerVersionGate check() {
List<String> jvmArguments;
try {
jvmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
} catch (Exception e) {
return failed("the JVM arguments could not be read to find dd-java-agent: " + e);
}
return check(jvmArguments);
}

static TracerVersionGate check(List<String> jvmArguments) {
String jarPath = null;
Manifest tracerManifest = null;
boolean tracerListedBeforeCompat = false;
for (String argument : jvmArguments) {
if (!argument.startsWith(JAVAAGENT_PREFIX)) {
continue;
}
String agentJarPath = javaagentJarPath(argument);
Manifest manifest = readManifest(agentJarPath);
if (manifest == null) {
continue;
}
String premainClass = manifest.getMainAttributes().getValue("Premain-Class");
if (COMPAT_PREMAIN_CLASS.equals(premainClass) && tracerManifest != null) {
tracerListedBeforeCompat = true;
} else if (TRACER_PREMAIN_CLASS.equals(premainClass) && tracerManifest == null) {
jarPath = agentJarPath;
tracerManifest = manifest;
}
}

if (tracerManifest == null) {
return failed("no readable dd-java-agent is among the -javaagent options (Premain-Class "
+ TRACER_PREMAIN_CLASS + ")");
}

String version = tracerManifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (version == null || version.isEmpty()) {
return failed("dd-java-agent at " + jarPath + " has no Implementation-Version in its manifest");
}
int[] tracer = parseVersion(version);
if (tracer == null) {
return failed("dd-java-agent at " + jarPath + " has an unreadable version '" + version + "'");
}
if (compare(tracer, MINIMUM_VERSION) < 0) {
return failed("dd-java-agent " + version + " at " + jarPath + " is older than "
+ MINIMUM_TRACER_VERSION + ", the first version that supports named pipes");
}
return new TracerVersionGate(true, "dd-java-agent " + version + " at " + jarPath
+ " supports named pipes (minimum " + MINIMUM_TRACER_VERSION + ")", tracerListedBeforeCompat);
}

// The JVM treats everything after the first '=' as agent options.
private static String javaagentJarPath(String argument) {
String value = argument.substring(JAVAAGENT_PREFIX.length());
int optionsStart = value.indexOf('=');
return optionsStart >= 0 ? value.substring(0, optionsStart) : value;
}

private static Manifest readManifest(String jarPath) {
try (JarFile jarFile = new JarFile(jarPath, false)) {
return jarFile.getManifest();
} catch (IOException | RuntimeException e) {
return null;
}
}

// Reads major.minor.patch and ignores any suffix, so 1.69.0-SNAPSHOT counts as 1.69.0.
private static int[] parseVersion(String version) {
Matcher matcher = VERSION_PATTERN.matcher(version);
if (!matcher.matches()) {
return null;
}
try {
return new int[] {
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3))
};
} catch (NumberFormatException e) {
return null;
}
}

private static int compare(int[] left, int[] right) {
for (int i = 0; i < left.length; i++) {
if (left[i] != right[i]) {
return Integer.compare(left[i], right[i]);
}
}
return 0;
}
}
Loading