InstrumentationModuleInstaller.java 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package io.opentelemetry.javaagent.tooling.instrumentation;
  6. import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.failSafe;
  7. import static net.bytebuddy.dynamic.loading.ClassLoadingStrategy.BOOTSTRAP_LOADER;
  8. import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith;
  9. import static net.bytebuddy.matcher.ElementMatchers.named;
  10. import static net.bytebuddy.matcher.ElementMatchers.not;
  11. import io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;
  12. import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
  13. import io.opentelemetry.javaagent.tooling.HelperInjector;
  14. import io.opentelemetry.javaagent.tooling.TransformSafeLogger;
  15. import io.opentelemetry.javaagent.tooling.Utils;
  16. import io.opentelemetry.javaagent.tooling.context.FieldBackedProvider;
  17. import io.opentelemetry.javaagent.tooling.context.InstrumentationContextProvider;
  18. import io.opentelemetry.javaagent.tooling.context.NoopContextProvider;
  19. import io.opentelemetry.javaagent.tooling.muzzle.matcher.Mismatch;
  20. import io.opentelemetry.javaagent.tooling.muzzle.matcher.ReferenceMatcher;
  21. import java.lang.instrument.Instrumentation;
  22. import java.security.ProtectionDomain;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.concurrent.atomic.AtomicBoolean;
  26. import net.bytebuddy.agent.builder.AgentBuilder;
  27. import net.bytebuddy.description.annotation.AnnotationSource;
  28. import net.bytebuddy.description.type.TypeDescription;
  29. import net.bytebuddy.matcher.ElementMatcher;
  30. import net.bytebuddy.utility.JavaModule;
  31. import org.slf4j.Logger;
  32. import org.slf4j.LoggerFactory;
  33. public final class InstrumentationModuleInstaller {
  34. private static final TransformSafeLogger log =
  35. TransformSafeLogger.getLogger(InstrumentationModule.class);
  36. private static final Logger muzzleLog = LoggerFactory.getLogger("muzzleMatcher");
  37. private final Instrumentation instrumentation;
  38. // Added here instead of AgentInstaller's ignores because it's relatively
  39. // expensive. https://github.com/DataDog/dd-trace-java/pull/1045
  40. public static final ElementMatcher.Junction<AnnotationSource> NOT_DECORATOR_MATCHER =
  41. not(isAnnotatedWith(named("javax.decorator.Decorator")));
  42. public InstrumentationModuleInstaller(Instrumentation instrumentation) {
  43. this.instrumentation = instrumentation;
  44. }
  45. AgentBuilder install(
  46. InstrumentationModule instrumentationModule, AgentBuilder parentAgentBuilder) {
  47. if (!instrumentationModule.isEnabled()) {
  48. log.debug("Instrumentation {} is disabled", instrumentationModule.instrumentationName());
  49. return parentAgentBuilder;
  50. }
  51. List<String> helperClassNames = instrumentationModule.getMuzzleHelperClassNames();
  52. List<String> helperResourceNames = instrumentationModule.helperResourceNames();
  53. List<TypeInstrumentation> typeInstrumentations = instrumentationModule.typeInstrumentations();
  54. if (typeInstrumentations.isEmpty()) {
  55. if (!helperClassNames.isEmpty() || !helperResourceNames.isEmpty()) {
  56. log.warn(
  57. "Helper classes and resources won't be injected if no types are instrumented: {}",
  58. instrumentationModule.instrumentationName());
  59. }
  60. return parentAgentBuilder;
  61. }
  62. ElementMatcher.Junction<ClassLoader> moduleClassLoaderMatcher =
  63. instrumentationModule.classLoaderMatcher();
  64. MuzzleMatcher muzzleMatcher = new MuzzleMatcher(instrumentationModule, helperClassNames);
  65. AgentBuilder.Transformer helperInjector =
  66. new HelperInjector(
  67. instrumentationModule.instrumentationName(),
  68. helperClassNames,
  69. helperResourceNames,
  70. Utils.getExtensionsClassLoader(),
  71. instrumentation);
  72. InstrumentationContextProvider contextProvider =
  73. createInstrumentationContextProvider(instrumentationModule);
  74. AgentBuilder agentBuilder = parentAgentBuilder;
  75. for (TypeInstrumentation typeInstrumentation : typeInstrumentations) {
  76. AgentBuilder.Identified.Extendable extendableAgentBuilder =
  77. agentBuilder
  78. .type(
  79. failSafe(
  80. typeInstrumentation.typeMatcher(),
  81. "Instrumentation type matcher unexpected exception: " + getClass().getName()),
  82. failSafe(
  83. moduleClassLoaderMatcher.and(typeInstrumentation.classLoaderOptimization()),
  84. "Instrumentation class loader matcher unexpected exception: "
  85. + getClass().getName()))
  86. .and(NOT_DECORATOR_MATCHER)
  87. .and(muzzleMatcher)
  88. .transform(ConstantAdjuster.instance())
  89. .transform(helperInjector);
  90. extendableAgentBuilder = contextProvider.instrumentationTransformer(extendableAgentBuilder);
  91. TypeTransformerImpl typeTransformer = new TypeTransformerImpl(extendableAgentBuilder);
  92. typeInstrumentation.transform(typeTransformer);
  93. extendableAgentBuilder = typeTransformer.getAgentBuilder();
  94. extendableAgentBuilder = contextProvider.additionalInstrumentation(extendableAgentBuilder);
  95. agentBuilder = extendableAgentBuilder;
  96. }
  97. return agentBuilder;
  98. }
  99. private static InstrumentationContextProvider createInstrumentationContextProvider(
  100. InstrumentationModule instrumentationModule) {
  101. Map<String, String> contextStore = instrumentationModule.getMuzzleContextStoreClasses();
  102. if (!contextStore.isEmpty()) {
  103. return new FieldBackedProvider(instrumentationModule.getClass(), contextStore);
  104. } else {
  105. return NoopContextProvider.INSTANCE;
  106. }
  107. }
  108. /**
  109. * A ByteBuddy matcher that decides whether this instrumentation should be applied. Calls
  110. * generated {@link ReferenceMatcher}: if any mismatch with the passed {@code classLoader} is
  111. * found this instrumentation is skipped.
  112. */
  113. private static class MuzzleMatcher implements AgentBuilder.RawMatcher {
  114. private final InstrumentationModule instrumentationModule;
  115. private final List<String> helperClassNames;
  116. private final AtomicBoolean initialized = new AtomicBoolean(false);
  117. private volatile ReferenceMatcher referenceMatcher;
  118. private MuzzleMatcher(
  119. InstrumentationModule instrumentationModule, List<String> helperClassNames) {
  120. this.instrumentationModule = instrumentationModule;
  121. this.helperClassNames = helperClassNames;
  122. }
  123. @Override
  124. public boolean matches(
  125. TypeDescription typeDescription,
  126. ClassLoader classLoader,
  127. JavaModule module,
  128. Class<?> classBeingRedefined,
  129. ProtectionDomain protectionDomain) {
  130. ReferenceMatcher muzzle = getReferenceMatcher();
  131. if (classLoader == BOOTSTRAP_LOADER) {
  132. classLoader = Utils.getBootstrapProxy();
  133. }
  134. boolean isMatch = muzzle.matches(classLoader);
  135. if (!isMatch) {
  136. if (muzzleLog.isWarnEnabled()) {
  137. muzzleLog.warn(
  138. "Instrumentation skipped, mismatched references were found: {} [class {}] on {}",
  139. instrumentationModule.instrumentationName(),
  140. instrumentationModule.getClass().getName(),
  141. classLoader);
  142. List<Mismatch> mismatches = muzzle.getMismatchedReferenceSources(classLoader);
  143. for (Mismatch mismatch : mismatches) {
  144. muzzleLog.warn("-- {}", mismatch);
  145. }
  146. }
  147. } else {
  148. if (log.isDebugEnabled()) {
  149. log.debug(
  150. "Applying instrumentation: {} [class {}] on {}",
  151. instrumentationModule.instrumentationName(),
  152. instrumentationModule.getClass().getName(),
  153. classLoader);
  154. }
  155. }
  156. return isMatch;
  157. }
  158. // ReferenceMatcher internally caches the muzzle check results per classloader, that's why we
  159. // keep its instance in a field
  160. // it is lazily created to avoid unnecessarily loading the muzzle references from the module
  161. // during the agent setup
  162. private ReferenceMatcher getReferenceMatcher() {
  163. if (initialized.compareAndSet(false, true)) {
  164. referenceMatcher =
  165. new ReferenceMatcher(
  166. helperClassNames,
  167. instrumentationModule.getMuzzleReferences(),
  168. instrumentationModule::isHelperClass);
  169. }
  170. return referenceMatcher;
  171. }
  172. }
  173. }