Search in sources :

Example 1 with WeavePackage

use of com.newrelic.weave.weavepackage.WeavePackage in project newrelic-java-agent by newrelic.

the class WeavingClassLoader method processClassPath.

private void processClassPath() throws IOException {
    // scan for @Weave or @SkipIfPresent classes and the classes they shadow
    Set<String> weaveResourceNames = new HashSet<>();
    List<byte[]> weavePackageClasses = new ArrayList<>();
    Set<URL> weavePackageURLs = new HashSet<>();
    // also scan for NewRelic classes and AgentBridge class
    // we use this later to prevent the API JAR's NewRelic class from shadowing the bridge JAR's NewRelic class
    Set<ClassResource> newRelicApiClasses = new HashSet<>();
    URL agentBridgeSourceURL = null;
    List<ClassResource> classResources = ClassResource.fromClassLoader((URLClassLoader) getParent());
    for (ClassResource classResource : classResources) {
        String resourceName = classResource.resourceName;
        String className = resourceName.replace('/', '.').replace(".class", "");
        if (weaveIncludes.isIncluded(className)) {
            byte[] bytes = classResource.read();
            if (usesWeaver(bytes) || isInstrumentationUtilityClass(classResource)) {
                weaveResourceNames.add(resourceName);
                weavePackageClasses.add(bytes);
                weavePackageURLs.add(classResource.sourceURL);
            } else {
                // Everything else
                shadowedClassResources.put(resourceName, classResource);
            }
        } else if (weaveIncludes.classUnderTestName.startsWith(className)) {
            weavePackageURLs.add(classResource.sourceURL);
        } else if (className.equals(NEWRELIC_API_CLASS)) {
            newRelicApiClasses.add(classResource);
        } else if (className.equals(AGENT_BRIDGE_CLASS)) {
            agentBridgeSourceURL = classResource.sourceURL;
        }
    }
    // remove resources that aren't actually shadowed
    shadowedClassResources.keySet().retainAll(weaveResourceNames);
    // this is necessary to support @SkipIfPresent
    for (String name : weaveResourceNames) {
        if (!shadowedClassResources.containsKey(name)) {
            shadowedClassResources.put(name, NO_RESOURCE);
        }
    }
    // create weave package for testing
    // @formatter:off
    WeavePackageConfig config = WeavePackageConfig.builder().name(TEST_WEAVE_PACKAGE_NAME).source(TEST_WEAVE_PACKAGE_SOURCE).errorHandleClassNode(errorTrapClassNode).weavePreprocessor(weavePreprocessor).weavePostprocessor(weavePostprocessor).build();
    // @formatter:on
    WeavePackage weavePackage = new WeavePackage(config, weavePackageClasses);
    weavePackageManager.register(weavePackage);
    // handle NewRelic API class shadowing
    if (agentBridgeSourceURL != null) {
        for (ClassResource newRelicApiClass : newRelicApiClasses) {
            if (agentBridgeSourceURL.equals(newRelicApiClass.sourceURL)) {
                shadowedClassResources.put(newRelicApiClass.resourceName, newRelicApiClass);
            }
        }
    }
}
Also used : WeavePackageConfig(com.newrelic.weave.weavepackage.WeavePackageConfig) ArrayList(java.util.ArrayList) WeavePackage(com.newrelic.weave.weavepackage.WeavePackage) URL(java.net.URL) HashSet(java.util.HashSet)

Example 2 with WeavePackage

use of com.newrelic.weave.weavepackage.WeavePackage in project newrelic-java-agent by newrelic.

the class CacheWeaveAttributesInManifest method main.

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        help();
        System.exit(1);
    }
    WeavePackage pkg = weavePackageFactory.createWeavePackage(Arrays.copyOfRange(args, 1, args.length));
    manifestAppender.copyAttributesToManifest(pkg);
    File outputDirectory = new File(args[0]).getParentFile();
    if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
        throw new Exception("Unable to create " + outputDirectory);
    }
    try (OutputStream stream = new FileOutputStream(args[0])) {
        manifestAppender.getManifest().write(stream);
    }
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) WeavePackage(com.newrelic.weave.weavepackage.WeavePackage) File(java.io.File)

Example 3 with WeavePackage

use of com.newrelic.weave.weavepackage.WeavePackage in project newrelic-java-agent by newrelic.

the class EnumNoNewFieldsTest method testEnumInvalidNewFields.

@Test
public void testEnumInvalidNewFields() throws IOException {
    List<byte[]> weaveBytes = new ArrayList<>();
    WeavePackageConfig config = WeavePackageConfig.builder().name("weave_unittest").source("com.newrelic.weave.weavepackage.testclasses").build();
    weaveBytes.add(WeaveTestUtils.getClassBytes("com.newrelic.weave.EnumNoNewFieldsTest$Day_Weave"));
    WeavePackage weavePackage = new WeavePackage(config, weaveBytes);
    ClassCache cache = new ClassCache(new ClassLoaderFinder(EnumNoNewFieldsTest.class.getClassLoader()));
    PackageValidationResult result = weavePackage.validate(cache);
    WeaveTestUtils.expectViolations(result, new WeaveViolation(WeaveViolationType.ENUM_NEW_FIELD, "com/newrelic/weave/EnumNoNewFieldsTest$Day"));
}
Also used : WeavePackageConfig(com.newrelic.weave.weavepackage.WeavePackageConfig) ClassLoaderFinder(com.newrelic.weave.utils.ClassLoaderFinder) ArrayList(java.util.ArrayList) WeavePackage(com.newrelic.weave.weavepackage.WeavePackage) WeaveViolation(com.newrelic.weave.violation.WeaveViolation) ClassCache(com.newrelic.weave.utils.ClassCache) PackageValidationResult(com.newrelic.weave.weavepackage.PackageValidationResult) Test(org.junit.Test)

Example 4 with WeavePackage

use of com.newrelic.weave.weavepackage.WeavePackage in project newrelic-java-agent by newrelic.

the class AgentWeaverListener method validated.

@Override
public void validated(PackageValidationResult packageResult, ClassLoader classloader) {
    final String weavePackageName = packageResult.getWeavePackage().getName();
    final float weavePackageVersion = packageResult.getWeavePackage().getVersion();
    if (packageResult.succeeded()) {
        String supportabilityLoadedMetric;
        if (packageResult.getWeavePackage().getConfig().isCustom()) {
            supportabilityLoadedMetric = MetricNames.SUPPORTABILITY_WEAVE_CUSTOM_LOADED;
        } else {
            supportabilityLoadedMetric = MetricNames.SUPPORTABILITY_WEAVE_LOADED;
        }
        ServiceFactory.getStatsService().doStatsWork(StatsWorks.getRecordMetricWork(MessageFormat.format(supportabilityLoadedMetric, weavePackageName, weavePackageVersion), 1), supportabilityLoadedMetric);
        Agent.LOG.log(Level.FINE, "{0} - validated classloader {1}", weavePackageName, classloader);
    } else {
        WeavePackage weavePackage = packageResult.getWeavePackage();
        if (Agent.LOG.isFinestEnabled() && weavePackage.weavesBootstrap()) {
            Map<String, MatchType> matchTypes = weavePackage.getMatchTypes();
            for (Map.Entry<String, MatchType> entry : matchTypes.entrySet()) {
                if (entry.getValue() != null) {
                    Agent.LOG.log(Level.FINEST, "Bootstrap class {0} : {1}", entry.getKey(), weavePackage.isBootstrapClassName(Collections.singleton(entry.getKey())));
                }
            }
        }
        boolean isCustom = weavePackage.getConfig().isCustom();
        String supportabilitySkippedMetric = isCustom ? MetricNames.SUPPORTABILITY_WEAVE_CUSTOM_SKIPPED : MetricNames.SUPPORTABILITY_WEAVE_SKIPPED;
        ServiceFactory.getStatsService().doStatsWork(StatsWorks.getRecordMetricWork(MessageFormat.format(supportabilitySkippedMetric, weavePackageName, weavePackageVersion), 1), supportabilitySkippedMetric);
        weaveViolationLogger.logWeaveViolations(packageResult, classloader, isCustom);
    }
}
Also used : MatchType(com.newrelic.api.agent.weaver.MatchType) WeavePackage(com.newrelic.weave.weavepackage.WeavePackage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Example 5 with WeavePackage

use of com.newrelic.weave.weavepackage.WeavePackage in project newrelic-java-agent by newrelic.

the class ClassLoaderClassTransformer method buildClassLoaderPatcherPackage.

private WeavePackage buildClassLoaderPatcherPackage() {
    WeavePackageConfig classloaderPatcher = WeavePackageConfig.builder().name("agent-classloader-patcher").errorHandleClassNode(LogAndReturnOriginal.ERROR_HANDLER_NODE).extensionClassTemplate(extensionTemplate).build();
    List<byte[]> weavePackageBytes = new ArrayList<>();
    try {
        // Grab the bytes of our Agent Classloader instrumentation class. Note: This call uses "findResource" but
        // this is ok because we are not under a classloader lock at this point, we are still in the premain()
        byte[] classloaderPatcherInstrumentationBytes = WeaveUtils.getClassBytesFromClassLoaderResource(AgentClassLoaderInstrumentation.class.getName(), ClassLoaderClassTransformer.class.getClassLoader());
        weavePackageBytes.add(classloaderPatcherInstrumentationBytes);
    } catch (IOException e) {
        Agent.LOG.log(Level.FINE, e, "Unable to initialize agent classloader instrumentation");
    }
    return new WeavePackage(classloaderPatcher, weavePackageBytes);
}
Also used : WeavePackageConfig(com.newrelic.weave.weavepackage.WeavePackageConfig) AgentClassLoaderInstrumentation(com.newrelic.agent.instrumentation.builtin.AgentClassLoaderInstrumentation) ArrayList(java.util.ArrayList) WeavePackage(com.newrelic.weave.weavepackage.WeavePackage) IOException(java.io.IOException)

Aggregations

WeavePackage (com.newrelic.weave.weavepackage.WeavePackage)18 WeavePackageConfig (com.newrelic.weave.weavepackage.WeavePackageConfig)9 CachedWeavePackage (com.newrelic.weave.weavepackage.CachedWeavePackage)8 ArrayList (java.util.ArrayList)7 WeaveViolation (com.newrelic.weave.violation.WeaveViolation)4 IOException (java.io.IOException)4 ClassTransformerConfig (com.newrelic.agent.config.ClassTransformerConfig)3 ClassMatchVisitorFactory (com.newrelic.agent.instrumentation.context.ClassMatchVisitorFactory)3 ClassCache (com.newrelic.weave.utils.ClassCache)3 ClassLoaderFinder (com.newrelic.weave.utils.ClassLoaderFinder)3 PackageValidationResult (com.newrelic.weave.weavepackage.PackageValidationResult)3 URL (java.net.URL)3 HashSet (java.util.HashSet)3 JarInputStream (java.util.jar.JarInputStream)3 AgentConfig (com.newrelic.agent.config.AgentConfig)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 Map (java.util.Map)2 Test (org.junit.Test)2 AgentClassLoaderBaseInstrumentation (com.newrelic.agent.instrumentation.builtin.AgentClassLoaderBaseInstrumentation)1