wu-sheng commented on a change in pull request #4858: URL: https://github.com/apache/skywalking/pull/4858#discussion_r439717563
########## File path: apm-sniffer/apm-agent-core/src/main/java/org/apache/skywalking/apm/agent/core/plugin/bytebuddy/CacheableTransformerDecorator.java ########## @@ -0,0 +1,195 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 org.apache.skywalking.apm.agent.core.plugin.bytebuddy; + +import net.bytebuddy.agent.builder.AgentBuilder; +import net.bytebuddy.agent.builder.ResettableClassFileTransformer; +import net.bytebuddy.utility.RandomString; +import org.apache.skywalking.apm.agent.core.logging.api.ILog; +import org.apache.skywalking.apm.agent.core.logging.api.LogManager; +import org.apache.skywalking.apm.agent.core.util.FileUtils; +import org.apache.skywalking.apm.agent.core.util.IOUtils; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.instrument.IllegalClassFormatException; +import java.nio.file.Files; +import java.security.ProtectionDomain; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Wrapper classFileTransformer of ByteBuddy, save the enhanced bytecode to memory cache or file cache, + * and automatically load the previously generated bytecode during the second retransform, + * to solve the problem that ByteBuddy generates auxiliary classes with different random names every time. + * Allow other javaagent to enhance those classes that enhanced by SkyWalking agent. + */ +public class CacheableTransformerDecorator implements AgentBuilder.TransformerDecorator { + + private static final ILog logger = LogManager.getLogger(CacheableTransformerDecorator.class); + + private String cacheDirBase; + private final ClassCacheMode cacheMode; + private ClassCacheResolver cacheResolver; + + public CacheableTransformerDecorator(ClassCacheMode cacheMode) throws IOException { + this.cacheMode = cacheMode; + initClassCache(); + } + + public CacheableTransformerDecorator(ClassCacheMode cacheMode, String cacheDirBase) throws IOException { + this.cacheDirBase = cacheDirBase; + this.cacheMode = cacheMode; + initClassCache(); + } + + private void initClassCache() throws IOException { + if (this.cacheMode.equals(ClassCacheMode.FILE)) { + File cacheDir; + if (this.cacheDirBase == null) { + cacheDir = Files.createTempDirectory("class-cache").toFile(); + } else { + cacheDir = new File(this.cacheDirBase + "/class-cache-" + RandomString.make()); + } + cacheResolver = new FileCacheResolver(cacheDir); + } else { + cacheResolver = new MemoryCacheResolver(); + } + } + + @Override + public ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer) { + return new ResettableClassFileTransformer.WithDelegation(classFileTransformer) { + + @Override + public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { + // load from cache + byte[] classCache = cacheResolver.getClassCache(loader, className); + if (classCache != null) { + return classCache; + } + + //transform class + classfileBuffer = classFileTransformer.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); + + // save to cache + if (classfileBuffer != null) { + cacheResolver.putClassCache(loader, className, classfileBuffer); + } + + return classfileBuffer; + } + }; + } + + private static String getClassLoaderHash(ClassLoader loader) { + String classloader; + if (loader != null) { + classloader = Integer.toHexString(loader.hashCode()); + } else { + //classloader is null for BootstrapClassLoader + classloader = "00000000"; + } + return classloader; + } + + interface ClassCacheResolver { + + byte[] getClassCache(ClassLoader loader, String className); + + void putClassCache(ClassLoader loader, String className, byte[] classfileBuffer); + } + + static class MemoryCacheResolver implements ClassCacheResolver { + // classloaderHashcode@className -> class bytes + private Map<String, byte[]> classCacheMap = new ConcurrentHashMap<String, byte[]>(); + + @Override + public byte[] getClassCache(ClassLoader loader, String className) { + String cacheKey = getCacheKey(loader, className); + return classCacheMap.get(cacheKey); + } + + @Override + public void putClassCache(ClassLoader loader, String className, byte[] classfileBuffer) { + String cacheKey = getCacheKey(loader, className); + classCacheMap.put(cacheKey, classfileBuffer); + } + + private String getCacheKey(ClassLoader loader, String className) { + return getClassLoaderHash(loader) + "@" + className; + } + } + + static class FileCacheResolver implements ClassCacheResolver { Review comment: File cache is a very sensitive and tricky thing, thinking in this way, once 2+ agents are sharing the agent.config, and open this feature, most likely they will share this dir. What will happen if they active file cache? In most cases, file cache is meaning you need a dir lock, and generate the dir automatically. ########## File path: apm-sniffer/apm-agent-core/src/main/java/org/apache/skywalking/apm/agent/core/plugin/bytebuddy/CacheableTransformerDecorator.java ########## @@ -0,0 +1,195 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 org.apache.skywalking.apm.agent.core.plugin.bytebuddy; + +import net.bytebuddy.agent.builder.AgentBuilder; +import net.bytebuddy.agent.builder.ResettableClassFileTransformer; +import net.bytebuddy.utility.RandomString; +import org.apache.skywalking.apm.agent.core.logging.api.ILog; +import org.apache.skywalking.apm.agent.core.logging.api.LogManager; +import org.apache.skywalking.apm.agent.core.util.FileUtils; +import org.apache.skywalking.apm.agent.core.util.IOUtils; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.instrument.IllegalClassFormatException; +import java.nio.file.Files; +import java.security.ProtectionDomain; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Wrapper classFileTransformer of ByteBuddy, save the enhanced bytecode to memory cache or file cache, + * and automatically load the previously generated bytecode during the second retransform, + * to solve the problem that ByteBuddy generates auxiliary classes with different random names every time. + * Allow other javaagent to enhance those classes that enhanced by SkyWalking agent. + */ +public class CacheableTransformerDecorator implements AgentBuilder.TransformerDecorator { + + private static final ILog logger = LogManager.getLogger(CacheableTransformerDecorator.class); + + private String cacheDirBase; + private final ClassCacheMode cacheMode; + private ClassCacheResolver cacheResolver; + + public CacheableTransformerDecorator(ClassCacheMode cacheMode) throws IOException { + this.cacheMode = cacheMode; + initClassCache(); + } + + public CacheableTransformerDecorator(ClassCacheMode cacheMode, String cacheDirBase) throws IOException { + this.cacheDirBase = cacheDirBase; + this.cacheMode = cacheMode; + initClassCache(); + } + + private void initClassCache() throws IOException { + if (this.cacheMode.equals(ClassCacheMode.FILE)) { + File cacheDir; + if (this.cacheDirBase == null) { + cacheDir = Files.createTempDirectory("class-cache").toFile(); + } else { + cacheDir = new File(this.cacheDirBase + "/class-cache-" + RandomString.make()); + } + cacheResolver = new FileCacheResolver(cacheDir); + } else { + cacheResolver = new MemoryCacheResolver(); + } + } + + @Override + public ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer) { + return new ResettableClassFileTransformer.WithDelegation(classFileTransformer) { + + @Override + public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { + // load from cache + byte[] classCache = cacheResolver.getClassCache(loader, className); + if (classCache != null) { + return classCache; + } + + //transform class + classfileBuffer = classFileTransformer.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); + + // save to cache + if (classfileBuffer != null) { + cacheResolver.putClassCache(loader, className, classfileBuffer); + } + + return classfileBuffer; + } + }; + } + + private static String getClassLoaderHash(ClassLoader loader) { + String classloader; + if (loader != null) { + classloader = Integer.toHexString(loader.hashCode()); + } else { + //classloader is null for BootstrapClassLoader + classloader = "00000000"; + } + return classloader; + } + + interface ClassCacheResolver { + + byte[] getClassCache(ClassLoader loader, String className); + + void putClassCache(ClassLoader loader, String className, byte[] classfileBuffer); + } + + static class MemoryCacheResolver implements ClassCacheResolver { + // classloaderHashcode@className -> class bytes + private Map<String, byte[]> classCacheMap = new ConcurrentHashMap<String, byte[]>(); + + @Override + public byte[] getClassCache(ClassLoader loader, String className) { + String cacheKey = getCacheKey(loader, className); + return classCacheMap.get(cacheKey); + } + + @Override + public void putClassCache(ClassLoader loader, String className, byte[] classfileBuffer) { + String cacheKey = getCacheKey(loader, className); + classCacheMap.put(cacheKey, classfileBuffer); + } + + private String getCacheKey(ClassLoader loader, String className) { + return getClassLoaderHash(loader) + "@" + className; + } + } + + static class FileCacheResolver implements ClassCacheResolver { + + private final File cacheDir; + + FileCacheResolver(File cacheDir) { + this.cacheDir = cacheDir; + if (!cacheDir.exists()) { + cacheDir.mkdirs(); + } + + //clean cache dir on exit + FileUtils.deleteDirectoryOnExit(cacheDir); Review comment: Deleting file shares the same issue of cache dir confliction. ########## File path: apm-sniffer/apm-agent/src/main/java/org/apache/skywalking/apm/agent/SkyWalkingAgent.java ########## @@ -99,6 +100,15 @@ public static void premain(String agentArgs, Instrumentation instrumentation) th return; } + if (Config.Agent.IS_CACHE_ENHANCED_CLASS) { + try { + agentBuilder = agentBuilder.with(new CacheableTransformerDecorator(Config.Agent.CLASS_CACHE_MODE)); + logger.info("SkyWalking agent setup class cache: {}", Config.Agent.CLASS_CACHE_MODE); Review comment: ```suggestion logger.info("SkyWalking agent class cache [{}] activated.", Config.Agent.CLASS_CACHE_MODE); ``` ########## File path: apm-sniffer/apm-agent/src/main/java/org/apache/skywalking/apm/agent/SkyWalkingAgent.java ########## @@ -99,6 +100,15 @@ public static void premain(String agentArgs, Instrumentation instrumentation) th return; } + if (Config.Agent.IS_CACHE_ENHANCED_CLASS) { + try { + agentBuilder = agentBuilder.with(new CacheableTransformerDecorator(Config.Agent.CLASS_CACHE_MODE)); + logger.info("SkyWalking agent setup class cache: {}", Config.Agent.CLASS_CACHE_MODE); + } catch (Exception e) { + logger.error(e, "SkyWalking agent setup class cache failure."); Review comment: ```suggestion logger.error(e, "SkyWalking agent can't active class cache."); ``` ########## File path: apm-sniffer/config/agent.config ########## @@ -38,6 +38,15 @@ agent.service_name=${SW_AGENT_NAME:Your_ApplicationName} # SkyWalking team may ask for these files in order to resolve compatible problem. # agent.is_open_debugging_class = ${SW_AGENT_OPEN_DEBUG:true} +# If true, SkyWalking agent will cache all instrumented classes files to memory or disk files (decided by class cache mode), Review comment: Both these are very advanced config, please keep these two in the documents only. Most users even can't understand what this is about, causing unnecessary confusion. I would like to recommend you adding a FAQ doc, including the error you were facing, and link to the agent set up the document and the config. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected]
