Skip to content

Wildcard ignores #39

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

Merged
merged 11 commits into from
Mar 17, 2025
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## Version: [v1.0.6](https://github.com/newrelic/newrelic-java-kotlin-coroutines/releases/tag/v1.0.6) | Created: 2025-03-17


## Version: [v1.0.5](https://github.com/newrelic/newrelic-java-kotlin-coroutines/releases/tag/v1.0.5) | Created: 2024-10-21


Expand Down
32 changes: 32 additions & 0 deletions Kotlin-Coroutines-Suspends/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

// Build.gradle generated for instrumentation module Kotlin-Coroutines-Core

apply plugin: 'java'

dependencies {
implementation group: 'org.jetbrains.kotlinx', name: 'kotlinx-coroutines-core', version: '1.4.0'

// New Relic Java Agent dependencies
implementation 'com.newrelic.agent.java:newrelic-agent:6.4.1'
implementation 'com.newrelic.agent.java:newrelic-api:6.4.1'
implementation fileTree(include: ['*.jar'], dir: '../libs')
implementation fileTree(include: ['*.jar'], dir: '../test-lib')
}

jar {
manifest {
attributes 'Implementation-Title': 'com.newrelic.instrumentation.labs.Kotlin-Coroutines-Suspends'
attributes 'Implementation-Vendor': 'New Relic Labs'
attributes 'Implementation-Vendor-Id': 'com.newrelic.labs'
attributes 'Implementation-Version': 2.0
attributes 'Agent-Class': 'com.newrelic.instrumentation.kotlin.coroutines.tracing.CoroutinesPreMain'
}
}

verifyInstrumentation {
// Verifier plugin documentation:
// https://github.com/newrelic/newrelic-gradle-verify-instrumentation
// Example:
// passes 'javax.servlet:servlet-api:[2.2,2.5]'
// exclude 'javax.servlet:servlet-api:2.4.public_draft'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.newrelic.instrumentation.kotlin.coroutines;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.newrelic.api.agent.Config;
import com.newrelic.api.agent.NewRelic;

public class SuspendIgnores {

private static final List<String> ignoredSuspends = new ArrayList<String>();
private static final String SUSPENDSIGNORECONFIG = "Coroutines.ignores.suspends";
private static final List<String> ignoredPackages = new ArrayList<>();

static {
Config config = NewRelic.getAgent().getConfig();
String value = config.getValue(SUSPENDSIGNORECONFIG);
init(value);
ignoredPackages.add("kotlin.coroutines");
ignoredPackages.add("kotlinx.coroutines");
}

private static void init(String value) {
if(value != null && !value.isEmpty()) {
String[] ignores = value.split(",");
for(String ignore : ignores) {
addIgnore(ignore);
}
}
}

public static void reset(Config config) {
ignoredSuspends.clear();
String value = config.getValue(SUSPENDSIGNORECONFIG);
init(value);
}

public static void addIgnore(String s) {
if(!ignoredSuspends.contains(s)) {
ignoredSuspends.add(s);
NewRelic.getAgent().getLogger().log(Level.FINE, "Will ignore suspends named {0}", s);
}
}

public static boolean ignoreSuspend(Object obj) {
String objString = obj.toString();
Class<?> clazz = obj.getClass();
String className = clazz.getName();
String packageName = clazz.getPackage().getName();

for(String ignored : ignoredPackages) {
if(packageName.startsWith(ignored)) {
return true;
}
}

boolean objStringMatch = ignoredSuspends.contains(objString);
boolean classNameMatch = ignoredSuspends.contains(className);

if(objStringMatch || classNameMatch) {
return true;
}

for(String s : ignoredSuspends) {
Pattern pattern = Pattern.compile(s);
Matcher matcher1 = pattern.matcher(objString);
Matcher matcher2 = pattern.matcher(className);
if(matcher1.matches() || matcher2.matches()) return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.newrelic.instrumentation.kotlin.coroutines;

import com.newrelic.agent.config.AgentConfig;
import com.newrelic.agent.config.AgentConfigListener;
import com.newrelic.agent.service.ServiceFactory;
import com.newrelic.api.agent.Config;
import com.newrelic.api.agent.NewRelic;

public class Utils implements AgentConfigListener {

private static final Utils INSTANCE = new Utils();
public static final String CREATEMETHOD1 = "Continuation at kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt$createCoroutineUnintercepted$$inlined$createCoroutineFromSuspendFunction$IntrinsicsKt__IntrinsicsJvmKt$4";
public static final String CREATEMETHOD2 = "Continuation at kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt$createCoroutineUnintercepted$$inlined$createCoroutineFromSuspendFunction$IntrinsicsKt__IntrinsicsJvmKt$3";
public static String sub = "createCoroutineFromSuspendFunction";
private static final String CONT_LOC = "Continuation at";

static {
ServiceFactory.getConfigService().addIAgentConfigListener(INSTANCE);
Config config = NewRelic.getAgent().getConfig();
SuspendIgnores.reset(config);
}

@Override
public void configChanged(String appName, AgentConfig agentConfig) {
SuspendIgnores.reset(agentConfig);
}

public static String getSuspendString(String cont_string, Object obj) {
if(cont_string.equals(CREATEMETHOD1) || cont_string.equals(CREATEMETHOD2)) return sub;
if(cont_string.startsWith(CONT_LOC)) {
return cont_string;
}

int index = cont_string.indexOf('@');
if(index > -1) {
return cont_string.substring(0, index);
}

return obj.getClass().getName();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package com.newrelic.instrumentation.kotlin.coroutines.tracing;

import java.lang.instrument.Instrumentation;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import com.newrelic.agent.TracerService;
import com.newrelic.agent.core.CoreService;
import com.newrelic.agent.instrumentation.ClassTransformerService;
import com.newrelic.agent.instrumentation.context.ClassMatchVisitorFactory;
import com.newrelic.agent.instrumentation.context.InstrumentationContextManager;
import com.newrelic.agent.service.ServiceFactory;
import com.newrelic.api.agent.NewRelic;

public class CoroutinesPreMain {

private static int max_retries = 20;
private static ScheduledExecutorService executor = null;

public static void premain(String args, Instrumentation inst) {
boolean b = setup();
if(!b) {
executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(new Setup(), 100L, TimeUnit.MILLISECONDS);
}

}

public static boolean setup() {

TracerService tracerService = ServiceFactory.getTracerService();
ClassTransformerService classTransformerService = ServiceFactory.getClassTransformerService();
CoreService coreService = ServiceFactory.getCoreService();

if(tracerService != null && classTransformerService != null && coreService != null) {
tracerService.registerTracerFactory(SuspendTracerFactory.TRACER_FACTORY_NAME, new SuspendTracerFactory());
InstrumentationContextManager contextMgr = classTransformerService.getContextManager();

if(contextMgr != null) {
SuspendClassTransformer suspendTransformer = new SuspendClassTransformer(contextMgr);
SuspendClassAndMethod suspendMatcher = new SuspendClassAndMethod();
ClassMatchVisitorFactory suspendMatchVistor = suspendTransformer.addMatcher(suspendMatcher);

Set<ClassMatchVisitorFactory> factories = new HashSet<>();
factories.add(suspendMatchVistor);
Class<?>[] allLoadedClasses = coreService.getInstrumentation().getAllLoadedClasses();

classTransformerService.retransformMatchingClassesImmediately(allLoadedClasses, factories);

return true;
}
}

return false;
}

private static class Setup implements Runnable {

private static int count = 0;

@Override
public void run() {
count++;
NewRelic.getAgent().getLogger().log(Level.FINE, "Call {0} to attempt setting up Suspend ClassTransformer",count);
boolean b = setup();

if(!b) {
if(count < max_retries) {
executor.schedule(this, 2L, TimeUnit.SECONDS);
} else {
NewRelic.getAgent().getLogger().log(Level.FINE, "Failed to initiate Suspend Client Transformer after {0} tries", max_retries);
executor.shutdownNow();
}
}

}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.newrelic.instrumentation.kotlin.coroutines.tracing;

import com.newrelic.agent.instrumentation.classmatchers.ClassAndMethodMatcher;
import com.newrelic.agent.instrumentation.classmatchers.ClassMatcher;
import com.newrelic.agent.instrumentation.methodmatchers.MethodMatcher;

public class SuspendClassAndMethod implements ClassAndMethodMatcher {

private ClassMatcher classMatcher;
private MethodMatcher methodMatcher;

public SuspendClassAndMethod() {
classMatcher = new SuspendClassMatcher();
methodMatcher = new SuspendMethodMatcher();
}

@Override
public ClassMatcher getClassMatcher() {
return classMatcher;
}

@Override
public MethodMatcher getMethodMatcher() {
return methodMatcher;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.newrelic.instrumentation.kotlin.coroutines.tracing;

import java.util.ArrayList;
import java.util.Collection;

import com.newrelic.agent.deps.org.objectweb.asm.ClassReader;
import com.newrelic.agent.instrumentation.classmatchers.ChildClassMatcher;
import com.newrelic.agent.instrumentation.classmatchers.ClassMatcher;
import com.newrelic.agent.instrumentation.classmatchers.ExactClassMatcher;
import com.newrelic.agent.instrumentation.classmatchers.NotMatcher;

public class SuspendClassMatcher extends ClassMatcher {

ChildClassMatcher matcher;
NotMatcher nrMatcher;

public SuspendClassMatcher() {
matcher = new ChildClassMatcher("kotlin.coroutines.jvm.internal.BaseContinuationImpl",false);
nrMatcher = new NotMatcher(new ExactClassMatcher("com.newrelic.instrumentation.kotlin.coroutines.NRWrappedSuspend"));
}

@Override
public boolean isMatch(ClassLoader loader, ClassReader cr) {
return matcher.isMatch(loader, cr) && nrMatcher.isMatch(loader, cr);
}

@Override
public boolean isMatch(Class<?> clazz) {
return matcher.isMatch(clazz) && nrMatcher.isMatch(clazz);
}

@Override
public Collection<String> getClassNames() {
Collection<String> childClasses = matcher.getClassNames();
Collection<String> nrClasses = nrMatcher.getClassNames();
if(childClasses == null && nrClasses == null) return null;

ArrayList<String> list = new ArrayList<>();
if(childClasses != null) {
list.addAll(childClasses);
}
if(nrClasses != null) {
list.addAll(nrClasses);
}

return list;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.newrelic.instrumentation.kotlin.coroutines.tracing;

import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import com.newrelic.agent.deps.org.objectweb.asm.commons.Method;
import com.newrelic.agent.instrumentation.InstrumentationType;
import com.newrelic.agent.instrumentation.classmatchers.ClassAndMethodMatcher;
import com.newrelic.agent.instrumentation.classmatchers.OptimizedClassMatcher.Match;
import com.newrelic.agent.instrumentation.classmatchers.OptimizedClassMatcherBuilder;
import com.newrelic.agent.instrumentation.context.ClassMatchVisitorFactory;
import com.newrelic.agent.instrumentation.context.ContextClassTransformer;
import com.newrelic.agent.instrumentation.context.InstrumentationContext;
import com.newrelic.agent.instrumentation.context.InstrumentationContextManager;
import com.newrelic.agent.instrumentation.methodmatchers.MethodMatcher;
import com.newrelic.agent.instrumentation.tracing.TraceDetailsBuilder;
import com.newrelic.api.agent.NewRelic;

public class SuspendClassTransformer implements ContextClassTransformer {

private Map<String, ClassMatchVisitorFactory> matchers = null;
private final InstrumentationContextManager contextMgr;

public SuspendClassTransformer(InstrumentationContextManager mgr) {
contextMgr = mgr;
matchers = new HashMap<>();
}

protected ClassMatchVisitorFactory addMatcher(ClassAndMethodMatcher matcher) {
NewRelic.getAgent().getLogger().log(Level.FINE, "Adding matcher {0} to service classtransformer", matcher);
OptimizedClassMatcherBuilder builder = OptimizedClassMatcherBuilder.newBuilder();
builder.addClassMethodMatcher(matcher);
ClassMatchVisitorFactory matchVistor = builder.build();
matchers.put(matcher.getClass().getSimpleName(), matchVistor);
contextMgr.addContextClassTransformer(matchVistor, this);
return matchVistor;
}

protected void removeMatcher(ClassAndMethodMatcher matcher) {
ClassMatchVisitorFactory matchVisitor = matchers.remove(matcher.getClass().getSimpleName());
if(matchVisitor != null) {
contextMgr.removeMatchVisitor(matchVisitor);
}
}

@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer, InstrumentationContext context, Match match)
throws IllegalClassFormatException {
for(Method method : match.getMethods()) {
for(ClassAndMethodMatcher matcher : match.getClassMatches().keySet()) {
if (matcher.getMethodMatcher().matches(MethodMatcher.UNSPECIFIED_ACCESS, method.getName(),
method.getDescriptor(), match.getMethodAnnotations(method))) {
context.putTraceAnnotation(method, TraceDetailsBuilder.newBuilder().setTracerFactoryName(SuspendTracerFactory.TRACER_FACTORY_NAME).setDispatcher(true).setInstrumentationSourceName("CoroutinesCore").setInstrumentationType(InstrumentationType.TraceAnnotation).build());
}

}
}
return null;
}

}
Loading
Loading