HelperInjector.java 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package io.opentelemetry.auto.tooling;
  17. import static io.opentelemetry.auto.tooling.ClassLoaderMatcher.BOOTSTRAP_CLASSLOADER;
  18. import static io.opentelemetry.instrumentation.auto.api.WeakMap.Provider.newWeakMap;
  19. import io.opentelemetry.instrumentation.auto.api.WeakMap;
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.lang.ref.WeakReference;
  23. import java.nio.file.Files;
  24. import java.security.SecureClassLoader;
  25. import java.util.Arrays;
  26. import java.util.Collection;
  27. import java.util.Collections;
  28. import java.util.HashMap;
  29. import java.util.LinkedHashMap;
  30. import java.util.LinkedHashSet;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Set;
  34. import java.util.concurrent.CopyOnWriteArrayList;
  35. import net.bytebuddy.agent.builder.AgentBuilder.Transformer;
  36. import net.bytebuddy.description.type.TypeDescription;
  37. import net.bytebuddy.dynamic.ClassFileLocator;
  38. import net.bytebuddy.dynamic.DynamicType;
  39. import net.bytebuddy.dynamic.loading.ClassInjector;
  40. import net.bytebuddy.utility.JavaModule;
  41. import org.slf4j.Logger;
  42. import org.slf4j.LoggerFactory;
  43. /** Injects instrumentation helper classes into the user's classloader. */
  44. public class HelperInjector implements Transformer {
  45. private static final Logger log = LoggerFactory.getLogger(HelperInjector.class);
  46. // Need this because we can't put null into the injectedClassLoaders map.
  47. private static final ClassLoader BOOTSTRAP_CLASSLOADER_PLACEHOLDER =
  48. new SecureClassLoader(null) {
  49. @Override
  50. public String toString() {
  51. return "<bootstrap>";
  52. }
  53. };
  54. private final String requestingName;
  55. private final Set<String> helperClassNames;
  56. private final Map<String, byte[]> dynamicTypeMap = new LinkedHashMap<>();
  57. private final WeakMap<ClassLoader, Boolean> injectedClassLoaders = newWeakMap();
  58. private final List<WeakReference<Object>> helperModules = new CopyOnWriteArrayList<>();
  59. /**
  60. * Construct HelperInjector.
  61. *
  62. * @param helperClassNames binary names of the helper classes to inject. These class names must be
  63. * resolvable by the classloader returned by
  64. * io.opentelemetry.auto.tooling.Utils#getAgentClassLoader(). Classes are injected in the
  65. * order provided. This is important if there is interdependency between helper classes that
  66. * requires them to be injected in a specific order.
  67. */
  68. public HelperInjector(final String requestingName, final String... helperClassNames) {
  69. this.requestingName = requestingName;
  70. this.helperClassNames = new LinkedHashSet<>(Arrays.asList(helperClassNames));
  71. }
  72. public HelperInjector(final String requestingName, final Map<String, byte[]> helperMap) {
  73. this.requestingName = requestingName;
  74. helperClassNames = helperMap.keySet();
  75. dynamicTypeMap.putAll(helperMap);
  76. }
  77. public static HelperInjector forDynamicTypes(
  78. final String requestingName, final Collection<DynamicType.Unloaded<?>> helpers) {
  79. Map<String, byte[]> bytes = new HashMap<>(helpers.size());
  80. for (DynamicType.Unloaded<?> helper : helpers) {
  81. bytes.put(helper.getTypeDescription().getName(), helper.getBytes());
  82. }
  83. return new HelperInjector(requestingName, bytes);
  84. }
  85. private Map<String, byte[]> getHelperMap() throws IOException {
  86. if (dynamicTypeMap.isEmpty()) {
  87. Map<String, byte[]> classnameToBytes = new LinkedHashMap<>();
  88. ClassFileLocator locator = ClassFileLocator.ForClassLoader.of(Utils.getAgentClassLoader());
  89. for (String helperClassName : helperClassNames) {
  90. byte[] classBytes = locator.locate(helperClassName).resolve();
  91. classnameToBytes.put(helperClassName, classBytes);
  92. }
  93. return classnameToBytes;
  94. } else {
  95. return dynamicTypeMap;
  96. }
  97. }
  98. @Override
  99. public DynamicType.Builder<?> transform(
  100. final DynamicType.Builder<?> builder,
  101. final TypeDescription typeDescription,
  102. ClassLoader classLoader,
  103. final JavaModule module) {
  104. if (!helperClassNames.isEmpty()) {
  105. if (classLoader == BOOTSTRAP_CLASSLOADER) {
  106. classLoader = BOOTSTRAP_CLASSLOADER_PLACEHOLDER;
  107. }
  108. if (!injectedClassLoaders.containsKey(classLoader)) {
  109. try {
  110. log.debug("Injecting classes onto classloader {} -> {}", classLoader, helperClassNames);
  111. Map<String, byte[]> classnameToBytes = getHelperMap();
  112. Map<String, Class<?>> classes;
  113. if (classLoader == BOOTSTRAP_CLASSLOADER_PLACEHOLDER) {
  114. classes = injectBootstrapClassLoader(classnameToBytes);
  115. } else {
  116. classes = injectClassLoader(classLoader, classnameToBytes);
  117. }
  118. // All agent helper classes are in the unnamed module
  119. // And there's exactly one unnamed module per classloader
  120. // Use the module of the first class for convenience
  121. if (JavaModule.isSupported()) {
  122. JavaModule javaModule = JavaModule.ofType(classes.values().iterator().next());
  123. helperModules.add(new WeakReference<>(javaModule.unwrap()));
  124. }
  125. } catch (final Exception e) {
  126. if (log.isErrorEnabled()) {
  127. log.error(
  128. "Error preparing helpers while processing {} for {}. Failed to inject helper classes into instance {}",
  129. typeDescription,
  130. requestingName,
  131. classLoader,
  132. e);
  133. }
  134. throw new RuntimeException(e);
  135. }
  136. injectedClassLoaders.put(classLoader, true);
  137. }
  138. ensureModuleCanReadHelperModules(module);
  139. }
  140. return builder;
  141. }
  142. private Map<String, Class<?>> injectBootstrapClassLoader(
  143. final Map<String, byte[]> classnameToBytes) throws IOException {
  144. // Mar 2020: Since we're proactively cleaning up tempDirs, we cannot share dirs per thread.
  145. // If this proves expensive, we could do a per-process tempDir with
  146. // a reference count -- but for now, starting simple.
  147. // Failures to create a tempDir are propagated as IOException and handled by transform
  148. File tempDir = createTempDir();
  149. try {
  150. return ClassInjector.UsingInstrumentation.of(
  151. tempDir,
  152. ClassInjector.UsingInstrumentation.Target.BOOTSTRAP,
  153. AgentInstaller.getInstrumentation())
  154. .injectRaw(classnameToBytes);
  155. } finally {
  156. // Delete fails silently
  157. deleteTempDir(tempDir);
  158. }
  159. }
  160. private Map<String, Class<?>> injectClassLoader(
  161. final ClassLoader classLoader, final Map<String, byte[]> classnameToBytes) {
  162. return new ClassInjector.UsingReflection(classLoader).injectRaw(classnameToBytes);
  163. }
  164. private void ensureModuleCanReadHelperModules(final JavaModule target) {
  165. if (JavaModule.isSupported() && target != JavaModule.UNSUPPORTED && target.isNamed()) {
  166. for (WeakReference<Object> helperModuleReference : helperModules) {
  167. Object realModule = helperModuleReference.get();
  168. if (realModule != null) {
  169. JavaModule helperModule = JavaModule.of(realModule);
  170. if (!target.canRead(helperModule)) {
  171. log.debug("Adding module read from {} to {}", target, helperModule);
  172. target.modify(
  173. AgentInstaller.getInstrumentation(),
  174. Collections.singleton(helperModule),
  175. Collections.<String, Set<JavaModule>>emptyMap(),
  176. Collections.<String, Set<JavaModule>>emptyMap(),
  177. Collections.<Class<?>>emptySet(),
  178. Collections.<Class<?>, List<Class<?>>>emptyMap());
  179. }
  180. }
  181. }
  182. }
  183. }
  184. private static File createTempDir() throws IOException {
  185. return Files.createTempDirectory("opentelemetry-temp-jars").toFile();
  186. }
  187. private static void deleteTempDir(final File file) {
  188. // Not using Files.delete for deleting the directory because failures
  189. // create Exceptions which may prove expensive. Instead using the
  190. // older File API which simply returns a boolean.
  191. boolean deleted = file.delete();
  192. if (!deleted) {
  193. file.deleteOnExit();
  194. }
  195. }
  196. }