kylixs commented on a change in pull request #4858:
URL: https://github.com/apache/skywalking/pull/4858#discussion_r439905059



##########
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:
       class cache dir is a randomly generated random directory, different 
agents will isolate their respective class cache.
   `cacheDir = new File(this.cacheDirBase + "/class-cache-" + 
RandomString.make());`
   




----------------------------------------------------------------
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:
us...@infra.apache.org


Reply via email to