Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moves ServiceInfo to tracer module and reduce dependency exposure to core module of plugins. #3272

Merged
merged 2 commits into from
Sep 13, 2023
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package co.elastic.apm.agent.configuration;

import co.elastic.apm.agent.sdk.internal.util.PrivilegedActionUtils;
import co.elastic.apm.agent.tracer.service.ServiceInfo;

import javax.annotation.Nullable;
import java.util.Map;
import java.util.Properties;
import java.util.jar.JarFile;

public class AutoDetectedServiceInfo {

private static final String JAR_VERSION_SUFFIX = "-(\\d+\\.)+(\\d+)(.*)?$";

private static final ServiceInfo AUTO_DETECTED = AutoDetectedServiceInfo.autoDetect(System.getProperties(), PrivilegedActionUtils.getEnv());

private AutoDetectedServiceInfo() {
}

public static ServiceInfo autoDetected() {
return AUTO_DETECTED;
}

public static ServiceInfo autoDetect(Properties sysProperties, Map<String,String> sysEnv) {
String lambdaFunctionName = sysEnv.get("AWS_LAMBDA_FUNCTION_NAME");
if (lambdaFunctionName != null) {
return ServiceInfo.of(lambdaFunctionName, sysEnv.get("AWS_LAMBDA_FUNCTION_VERSION"));
} else {
ServiceInfo serviceInfo = createFromSunJavaCommand(sysProperties.getProperty("sun.java.command"));
if (serviceInfo != null) {
return serviceInfo;
}
return ServiceInfo.empty();
}
}

@Nullable
private static ServiceInfo createFromSunJavaCommand(@Nullable String command) {
if (command == null) {
return null;
}
command = command.trim();
String serviceName = getContainerServiceName(command);
if (serviceName != null) {
return ServiceInfo.ofMultiServiceContainer(serviceName);
}
if (command.contains(".jar")) {
return fromJarCommand(command);
} else {
return fromMainClassCommand(command);
}
}

@Nullable
private static String getContainerServiceName(String command) {
if (command.startsWith("org.apache.catalina.startup.Bootstrap")) {
return "tomcat-application";
} else if (command.startsWith("org.eclipse.jetty")) {
return "jetty-application";
} else if (command.startsWith("com.sun.enterprise.glassfish")) {
return "glassfish-application";
} else if (command.contains("ws-server.jar")) {
return "websphere-application";
} else if (command.contains("jboss-modules.jar")) {
return "jboss-application";
} else if (command.contains("weblogic")) {
return "weblogic-application";
}
return null;
}

private static ServiceInfo fromJarCommand(String command) {
final String[] commandParts = command.split(" ");
ServiceInfo serviceInfoFromManifest = ServiceInfo.empty();
ServiceInfo serviceInfoFromJarName = ServiceInfo.empty();
for (String commandPart : commandParts) {
if (commandPart.endsWith(".jar")) {
try (JarFile jarFile = new JarFile(commandPart)) {
serviceInfoFromManifest = ServiceInfo.fromManifest(jarFile.getManifest());
} catch (Exception ignored) {
}

serviceInfoFromJarName = ServiceInfo.of(removeVersionFromJar(removePath(removeJarExtension(commandPart))));
break;
}
}
return serviceInfoFromManifest.withFallback(serviceInfoFromJarName);
}

private static String removeJarExtension(String commandPart) {
return commandPart.substring(0, commandPart.indexOf(".jar"));
}

private static String removePath(String path) {
return path.substring(path.lastIndexOf("/") + 1).substring(path.lastIndexOf("\\") + 1);
}

private static String removeVersionFromJar(String jarFileName) {
return jarFileName.replaceFirst(JAR_VERSION_SUFFIX, "");
}

private static ServiceInfo fromMainClassCommand(String command) {
final String mainClassName;
int indexOfSpace = command.indexOf(' ');
if (indexOfSpace != -1) {
mainClassName = command.substring(0, indexOfSpace);
} else {
mainClassName = command;
}
return ServiceInfo.of(mainClassName.substring(mainClassName.lastIndexOf('.') + 1));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public class CoreConfiguration extends ConfigurationOptionProvider implements co
"NOTE: Service name auto discovery mechanisms require APM Server 7.0+.")
.addValidator(RegexValidator.of("^[a-zA-Z0-9 _-]+$", "Your service name \"{0}\" must only contain characters " +
"from the ASCII alphabet, numbers, dashes, underscores and spaces"))
.buildWithDefault(ServiceInfo.autoDetected().getServiceName());
.buildWithDefault(AutoDetectedServiceInfo.autoDetected().getServiceName());

private final ConfigurationOption<String> serviceNodeName = ConfigurationOption.stringOption()
.key(SERVICE_NODE_NAME)
Expand Down Expand Up @@ -203,7 +203,7 @@ public class CoreConfiguration extends ConfigurationOptionProvider implements co
"the agent can auto-detect the service version based on the `Implementation-Title` attribute in `META-INF/MANIFEST.MF`.\n" +
"See <<config-service-name>> on how to set this attribute.\n" +
"\n")
.defaultValue(ServiceInfo.autoDetected().getServiceVersion())
.defaultValue(AutoDetectedServiceInfo.autoDetected().getServiceVersion())
.build();

private final ConfigurationOption<String> hostname = ConfigurationOption.stringOption()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
import co.elastic.apm.agent.collections.WeakReferenceCountedMap;
import co.elastic.apm.agent.common.JvmRuntimeInfo;
import co.elastic.apm.agent.common.util.WildcardMatcher;
import co.elastic.apm.agent.configuration.AutoDetectedServiceInfo;
import co.elastic.apm.agent.configuration.CoreConfiguration;
import co.elastic.apm.agent.configuration.MetricsConfiguration;
import co.elastic.apm.agent.configuration.ServerlessConfiguration;
import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.configuration.SpanConfiguration;
import co.elastic.apm.agent.context.ClosableLifecycleListenerAdapter;
import co.elastic.apm.agent.context.LifecycleListener;
Expand Down Expand Up @@ -93,6 +94,7 @@ public class ElasticApmTracer implements Tracer {
private static final WeakMap<ClassLoader, ServiceInfo> serviceInfoByClassLoader = WeakConcurrent.buildMap();

private static final Map<Class<?>, Class<? extends ConfigurationOptionProvider>> configs = new HashMap<>();

public static final Set<String> TRACE_HEADER_NAMES;

static {
Expand Down Expand Up @@ -350,7 +352,7 @@ public Transaction currentTransaction() {

@Nullable
@Override
public co.elastic.apm.agent.tracer.ErrorCapture getActiveError() {
public ErrorCapture getActiveError() {
return ErrorCapture.getActive();
}

Expand Down Expand Up @@ -973,4 +975,9 @@ public <T extends co.elastic.apm.agent.tracer.Tracer> T require(Class<T> type) {
public Set<String> getTraceHeaderNames() {
return TRACE_HEADER_NAMES;
}

@Override
public ServiceInfo autoDetectedServiceInfo() {
return AutoDetectedServiceInfo.autoDetected();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/
package co.elastic.apm.agent.impl;

import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.impl.baggage.Baggage;
import co.elastic.apm.agent.impl.error.ErrorCapture;
import co.elastic.apm.agent.impl.sampling.Sampler;
Expand All @@ -30,7 +30,7 @@

import javax.annotation.Nullable;

public interface Tracer extends co.elastic.apm.agent.tracer.Tracer {
public interface Tracer extends co.elastic.apm.agent.tracer.service.ServiceAwareTracer, co.elastic.apm.agent.tracer.Tracer {

@Nullable
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import co.elastic.apm.agent.bci.ElasticApmAgent;
import co.elastic.apm.agent.common.util.SystemStandardOutputLogger;
import co.elastic.apm.agent.configuration.CoreConfiguration;
import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.configuration.AutoDetectedServiceInfo;
import co.elastic.apm.agent.tracer.configuration.ByteValue;
import co.elastic.apm.agent.report.ApmServerReporter;
import org.apache.logging.log4j.Level;
Expand Down Expand Up @@ -186,7 +186,7 @@ private LayoutComponentBuilder createLayout(ConfigurationBuilder<BuiltConfigurat
.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%thread] %-5level %logger{36} - %msg{nolookups}%n");
} else {
String serviceName = getValue(CoreConfiguration.SERVICE_NAME, sources, ServiceInfo.autoDetected().getServiceName());
String serviceName = getValue(CoreConfiguration.SERVICE_NAME, sources, AutoDetectedServiceInfo.autoDetected().getServiceName());
return builder.newLayout("EcsLayout")
.addAttribute("eventDataset", serviceName + ".apm-agent");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/
package co.elastic.apm.agent.report.serialize;

import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.context.AbstractLifecycleListener;
import co.elastic.apm.agent.impl.ElasticApmTracer;
import co.elastic.apm.agent.metrics.Labels;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/
package co.elastic.apm.agent.report.serialize;

import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.metrics.DoubleSupplier;
import co.elastic.apm.agent.metrics.MetricSet;
import co.elastic.apm.agent.metrics.Timer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package co.elastic.apm.agent.configuration;

import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.util.CustomEnvVariables;
import org.junit.jupiter.api.Test;

Expand All @@ -31,15 +32,15 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.SoftAssertions.assertSoftly;

class ServiceInfoTest extends CustomEnvVariables {
class AutoDetectedServiceInfoTest extends CustomEnvVariables {

private static String getDefaultServiceName(@Nullable String sunJavaCommand) {
Properties properties = new Properties();
if (sunJavaCommand != null) {
properties.setProperty("sun.java.command", sunJavaCommand);
}

return ServiceInfo.autoDetect(properties, Map.of()).getServiceName();
return AutoDetectedServiceInfo.autoDetect(properties, Map.of()).getServiceName();
}

@Test
Expand Down Expand Up @@ -81,7 +82,7 @@ void testDefaultsWithLambda() throws Exception {
final Map<String, String> awsLambdaEnvVariables = new HashMap<>();
awsLambdaEnvVariables.put("AWS_LAMBDA_FUNCTION_NAME", "my-lambda-function");
awsLambdaEnvVariables.put("AWS_LAMBDA_FUNCTION_VERSION", "24");
ServiceInfo serviceInfo = callWithCustomEnvVariables(awsLambdaEnvVariables, () -> ServiceInfo.autoDetect(System.getProperties(), System.getenv()));
ServiceInfo serviceInfo = callWithCustomEnvVariables(awsLambdaEnvVariables, () -> AutoDetectedServiceInfo.autoDetect(System.getProperties(), System.getenv()));
assertSoftly(softly -> {
softly.assertThat(serviceInfo.getServiceName()).isEqualTo("my-lambda-function");
softly.assertThat(serviceInfo.getServiceVersion()).isEqualTo("24");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@

import co.elastic.apm.agent.MockReporter;
import co.elastic.apm.agent.common.util.WildcardMatcher;
import co.elastic.apm.agent.configuration.AutoDetectedServiceInfo;
import co.elastic.apm.agent.configuration.CoreConfiguration;
import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.configuration.SpyConfiguration;
import co.elastic.apm.agent.configuration.source.ConfigSources;
import co.elastic.apm.agent.impl.baggage.Baggage;
Expand Down Expand Up @@ -619,7 +620,7 @@ void testNotOverrideServiceNameWhenDefaultServiceNameConfigured() {

CoreConfiguration coreConfig = localConfig.getConfig(CoreConfiguration.class);

assertThat(ServiceInfo.autoDetect(System.getProperties(), System.getenv()))
assertThat(AutoDetectedServiceInfo.autoDetect(System.getProperties(), System.getenv()))
.isEqualTo(ServiceInfo.of(coreConfig.getServiceName()));

assertThat(reporter.getFirstTransaction().getTraceContext().getServiceName()).isNull();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
package co.elastic.apm.agent.report.serialize;

import co.elastic.apm.agent.MockReporter;
import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.configuration.SpyConfiguration;
import co.elastic.apm.agent.impl.ElasticApmTracer;
import co.elastic.apm.agent.impl.ElasticApmTracerBuilder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
package co.elastic.apm.agent.report.serialize;

import co.elastic.apm.agent.configuration.MetricsConfiguration;
import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.metrics.Labels;
import co.elastic.apm.agent.metrics.MetricCollector;
import co.elastic.apm.agent.metrics.MetricRegistry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
*/
package co.elastic.apm.agent.pluginapi;

import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceAwareTracer;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.impl.ElasticApmTracer;
import co.elastic.apm.agent.impl.Tracer;
import co.elastic.apm.agent.tracer.ErrorCapture;
Expand Down Expand Up @@ -166,7 +167,7 @@ public SetServiceInfoForClassLoaderInstrumentation() {
public static class AdviceClass {
@Advice.OnMethodExit(suppress = Throwable.class, inline = false)
public static void setServiceInfoForClassLoader(@Advice.Argument(0) @Nullable ClassLoader classLoader, @Advice.Argument(1) String serviceName, @Advice.Argument(2) @Nullable String serviceVersion) {
tracer.require(Tracer.class).setServiceInfoForClassLoader(classLoader, ServiceInfo.of(serviceName, serviceVersion));
tracer.require(ServiceAwareTracer.class).setServiceInfoForClassLoader(classLoader, ServiceInfo.of(serviceName, serviceVersion));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
*/
package co.elastic.apm.agent.pluginapi;

import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceAwareTracer;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.impl.Tracer;
import co.elastic.apm.agent.impl.transaction.Id;
import co.elastic.apm.agent.impl.transaction.TraceContext;
Expand Down Expand Up @@ -176,7 +177,7 @@ public static class AdviceClass {
public static void useServiceInfoForClassLoader(@Advice.FieldValue(value = "span", typing = Assigner.Typing.DYNAMIC) Object transaction,
@Advice.Argument(0) ClassLoader classLoader) {
if (transaction instanceof Transaction) {
ServiceInfo serviceInfo = tracer.require(Tracer.class).getServiceInfoForClassLoader(classLoader);
ServiceInfo serviceInfo = tracer.require(ServiceAwareTracer.class).getServiceInfoForClassLoader(classLoader);
if (serviceInfo != null) {
((Transaction) transaction).getTraceContext().setServiceInfo(serviceInfo.getServiceName(), serviceInfo.getServiceVersion());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
package co.elastic.apm.agent.pluginapi;

import co.elastic.apm.AbstractApiTest;
import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.impl.TracerInternalApiUtils;
import co.elastic.apm.api.AbstractSpanImplAccessor;
import co.elastic.apm.api.ElasticApm;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
package co.elastic.apm.api;

import co.elastic.apm.AbstractApiTest;
import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.impl.TextHeaderMapAccessor;
import co.elastic.apm.agent.impl.TracerInternalApiUtils;
import co.elastic.apm.agent.impl.transaction.AbstractSpan;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
*/
package co.elastic.apm.agent.ecs_logging;

import co.elastic.apm.agent.configuration.ServiceInfo;
import co.elastic.apm.agent.impl.ElasticApmTracer;
import co.elastic.apm.agent.tracer.service.ServiceAwareTracer;
import co.elastic.apm.agent.tracer.service.ServiceInfo;
import co.elastic.apm.agent.sdk.logging.Logger;
import co.elastic.apm.agent.sdk.logging.LoggerFactory;
import co.elastic.apm.agent.sdk.weakconcurrent.WeakConcurrent;
Expand All @@ -38,7 +38,7 @@ public class EcsLoggingUtils {
private static final WeakSet<Object> versionChecked = WeakConcurrent.buildSet();
private static final WeakSet<Object> environmentChecked = WeakConcurrent.buildSet();

private static final ElasticApmTracer tracer = GlobalTracer.get().require(ElasticApmTracer.class);
private static final ServiceAwareTracer tracer = GlobalTracer.get().require(ServiceAwareTracer.class);

@Nullable
public static String getServiceName() {
Expand Down
Loading