日本黄色一级经典视频|伊人久久精品视频|亚洲黄色色周成人视频九九九|av免费网址黄色小短片|黄色Av无码亚洲成年人|亚洲1区2区3区无码|真人黄片免费观看|无码一级小说欧美日免费三级|日韩中文字幕91在线看|精品久久久无码中文字幕边打电话

當(dāng)前位置:首頁(yè) > 單片機(jī) > 架構(gòu)師社區(qū)
[導(dǎo)讀]作者:未完成交響曲,資深Java工程師!目前在某一線互聯(lián)網(wǎng)公司任職,架構(gòu)師社區(qū)合伙人! 本文源碼基于Pinpoint 2.0.3-SNAPSHOT版本 官方開(kāi)源地址:https://github.com/naver/pinpoint Pinpoint Agent Pinpoint通過(guò)字節(jié)碼增強(qiáng)技術(shù)來(lái)實(shí)現(xiàn)無(wú)侵入式的調(diào)用鏈采集。

分布式系統(tǒng)性能監(jiān)控工具,初探Pinpoint Agent啟動(dòng)源碼

作者:未完成交響曲,資深Java工程師!目前在某一線互聯(lián)網(wǎng)公司任職,架構(gòu)師社區(qū)合伙人!


本文源碼基于Pinpoint 2.0.3-SNAPSHOT版本
官方開(kāi)源地址:https://github.com/naver/pinpoint

Pinpoint Agent

Pinpoint通過(guò)字節(jié)碼增強(qiáng)技術(shù)來(lái)實(shí)現(xiàn)無(wú)侵入式的調(diào)用鏈采集。其核心實(shí)現(xiàn)是基于JVM的Java Agent機(jī)制。

我們使用Pinpoint時(shí),需要在Java應(yīng)用啟動(dòng)參數(shù)上加上-javaagent:$AGENT_PATH/pinpoint-bootstrap-$VERSION.jar參數(shù),這樣,當(dāng)我們的Java應(yīng)用啟動(dòng)時(shí),會(huì)同時(shí)啟動(dòng)Agent。

Pinpoint Agent在啟動(dòng)的時(shí)候,會(huì)加載plugin文件夾下所有的插件,這些插件會(huì)對(duì)特定class類修改字節(jié)碼,在一些指定的方法調(diào)用前后加上鏈路采集邏輯(比如Dubbo中AbstractProxyInvokerinvoke()方法),這樣就實(shí)現(xiàn)了調(diào)用鏈監(jiān)控功能。

Pinpoint官方文檔中的原理描述:

分布式系統(tǒng)性能監(jiān)控工具,初探Pinpoint Agent啟動(dòng)源碼
在這里插入圖片描述

在pintpoin-bootstrap模塊中,我們可以在pom文件中看到maven插件里有MANIFEST相關(guān)的配置,指定了 Premain-Class,這個(gè)配置在打包時(shí)也會(huì)生成到MANIFEST.MF文件中:
分布式系統(tǒng)性能監(jiān)控工具,初探Pinpoint Agent啟動(dòng)源碼
在這里插入圖片描述

執(zhí)行premain()方法

通過(guò)上述配置可知,當(dāng)我們啟動(dòng)接入了pinpoint的Java應(yīng)用時(shí),會(huì)先執(zhí)行PinpointBootStrap.premain()方法:

去掉了日志等非核心邏輯代碼

public static void premain(String agentArgs, Instrumentation instrumentation) {
    // 1.設(shè)置啟動(dòng)狀態(tài),避免重復(fù)初始化
    final boolean success = STATE.start();
    if (!success) {
        return;
    }

    // 2.初始化和解析啟動(dòng)參數(shù)
    final JavaAgentPathResolver javaAgentPathResolver = JavaAgentPathResolver.newJavaAgentPathResolver();
    final String agentPath = javaAgentPathResolver.resolveJavaAgentPath();
    final Map<String, String> agentArgsMap = argsToMap(agentArgs);
    final ClassPathResolver classPathResolver = new AgentDirBaseClassPathResolver(agentPath);

    // 3.查找核心jar包
    final AgentDirectory agentDirectory = resolveAgentDir(classPathResolver);
    BootDir bootDir = agentDirectory.getBootDir();
    appendToBootstrapClassLoader(instrumentation, bootDir);

    // 4.獲取類加載器,加載核心jar中的類
    ClassLoader parentClassLoader = getParentClassLoader();
    final ModuleBootLoader moduleBootLoader = loadModuleBootLoader(instrumentation, parentClassLoader);
    PinpointStarter bootStrap = new PinpointStarter(parentClassLoader, agentArgsMap, agentDirectory, instrumentation, moduleBootLoader);

    // 5.啟動(dòng)bootStrap
    if (!bootStrap.start()) {
        logPinpointAgentLoadFail();
    }
}

可以看到premain()方法有兩個(gè)參數(shù),最重要的是這個(gè)instrumentation對(duì)象

Instrumentation是Java提供的一個(gè)來(lái)自JVM的接口,該接口提供了一系列查看和操作Java類定義的方法,例如修改類的字節(jié)碼、向classLoader的classpath下加入jar文件等,

PinpointBootStrap.premain()方法中,主要完成了相關(guān)jar包的查找和加載,然后將一系列配置以及instrumentation對(duì)象構(gòu)造成PinpointStarter對(duì)象,并執(zhí)行start()方法完成后續(xù)的啟動(dòng):

boolean start() {
    // 1.讀取agentId和applicationName
    final AgentIds agentIds = resolveAgentIds();
    final String agentId = agentIds.getAgentId();
    final String applicationName = agentIds.getApplicationName();
    final boolean isContainer = new ContainerResolver().isContainer();

    try {
        // 2.解析并加載配置
        final Properties properties = loadProperties();
        ProfilerConfig profilerConfig = new DefaultProfilerConfig(properties);

        // 3.設(shè)置日志路徑和版本信息到systemProperty
        saveLogFilePath(agentDirectory);
        savePinpointVersion();

        // 4.創(chuàng)建AgentClassLoader
        URL[] urls = resolveLib(agentDirectory);
        final ClassLoader agentClassLoader = createClassLoader("pinpoint.agent", urls, parentClassLoader);
        if (moduleBootLoader != null) {
            moduleBootLoader.defineAgentModule(agentClassLoader, urls);
        }
        final String bootClass = getBootClass();
        AgentBootLoader agentBootLoader = new AgentBootLoader(bootClass, agentClassLoader);

        final List<String> pluginJars = agentDirectory.getPlugins();

        // 5.構(gòu)建AgentOption,并作為參數(shù)通過(guò)反射機(jī)制構(gòu)建Agent(DefaultAgent)
        AgentOption option = createAgentOption(agentId, applicationName, isContainer, profilerConfig, instrumentation, pluginJars, agentDirectory);
        Agent pinpointAgent = agentBootLoader.boot(option);

        // 6.啟動(dòng)死鎖監(jiān)控線程、agent數(shù)據(jù)上報(bào)線程、注冊(cè)ShutdownHook
        pinpointAgent.start();
        pinpointAgent.registerStopHandler();

    } catch (Exception e) {
        return false;
    }
    return true;
}

初始化上下文

上面過(guò)程其實(shí)還是加載配置并構(gòu)建一些對(duì)象,這里面最核心的邏輯是構(gòu)建Agent對(duì)象,執(zhí)行了DefaultAgent類的構(gòu)造器,初始化了上下文:

new DefaultAgent()

┆┈ DefaultAgent.newApplicationContext()

┆┈┈┈ new DefaultApplicationContext()

這里我們直接看DefaultApplicationContext類的構(gòu)造器中的關(guān)鍵邏輯:

public DefaultApplicationContext(AgentOption agentOption, ModuleFactory moduleFactory) {
    // 1.獲取Instrumentation對(duì)象
    final Instrumentation instrumentation = agentOption.getInstrumentation();

    // 2.構(gòu)建Guice ioc容器,用于依賴注入
    final Module applicationContextModule = moduleFactory.newModule(agentOption);
    this.injector = Guice.createInjector(Stage.PRODUCTION, applicationContextModule);

    // 3.通過(guò)Guice注入一系列對(duì)象
    this.profilerConfig = injector.getInstance(ProfilerConfig.class);
    this.interceptorRegistryBinder = injector.getInstance(InterceptorRegistryBinder.class);
    this.instrumentEngine = injector.getInstance(InstrumentEngine.class);
    this.classFileTransformer = injector.getInstance(ClassFileTransformer.class);
    this.dynamicTransformTrigger = injector.getInstance(DynamicTransformTrigger.class);

    // 4.通過(guò)instrumentation對(duì)象注冊(cè)類轉(zhuǎn)換器
    instrumentation.addTransformer(classFileTransformer, true);

    ...
}

綁定TransformCallback

Guice是谷歌開(kāi)源的一個(gè)輕量級(jí)的依賴注入框架,pinpoint依靠Guice管理各種對(duì)象。

在初始化ioc容器的過(guò)程中,會(huì)遍歷plugin目錄下的所有插件對(duì)其進(jìn)行初始化,調(diào)用過(guò)程如下:

ApplicationServerTypeProvider.get()

|— PluginContextLoadResultProvider.get()

|—— new DefaultPluginContextLoadResult()

|——— DefaultProfilerPluginContextLoader.load()

|———— DefaultProfilerPluginContextLoader.setupPlugin()

|————— DefaultPluginSetup.setupPlugin()

|—————— XxxPlugin.setup()(具體Plugin實(shí)現(xiàn))

DubboPlugin為例,在setup()方法中主要對(duì)dubbo中的核心類進(jìn)行轉(zhuǎn)換器綁定:

@Override
public void setup(ProfilerPluginSetupContext context) {
    DubboConfiguration config = new DubboConfiguration(context.getConfig());
    ...
    this.addTransformers();
}

private void addTransformers() {
    // 為dubbo核心rpc調(diào)用類綁定Transform關(guān)系
    transformTemplate.transform("com.alibaba.dubbo.rpc.protocol.AbstractInvoker", AbstractInvokerTransform.class);
    transformTemplate.transform("com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker", AbstractProxyInvokerTransform.class);
}

再來(lái)看看其中一個(gè)Transform類都做了些什么:

public static class AbstractInvokerTransform implements TransformCallback {
   @Override
    public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
        // 指定目標(biāo)類(上一步綁定的類)
        final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
        // 指定目標(biāo)方法(方法名、參數(shù))
        InstrumentMethod invokeMethod = target.getDeclaredMethod("invoke""com.alibaba.dubbo.rpc.Invocation");
        if (invokeMethod != null) {
            // 為此方法添加攔截器
            invokeMethod.addInterceptor(DubboConsumerInterceptor.class);
        }
        return target.toBytecode();
    }
}

可以看到,這個(gè)類實(shí)現(xiàn)了TransformCallback接口,這個(gè)接口從名字上可以看出是一個(gè)回調(diào)接口,而在其doInTransform()方法中,是通過(guò)字節(jié)碼增強(qiáng)的方式,為com.alibaba.dubbo.rpc.protocol.AbstractInvoker類的invoke()方法添加了一個(gè)攔截器DubboConsumerInterceptor。

DubboConsumerInterceptor實(shí)現(xiàn)了AroundInterceptor接口的before()after()方法,這里可以看出和Spring AOP很相似了,而在攔截器中,主要是對(duì)dubbo的RPC調(diào)用進(jìn)行trace、span等鏈路追蹤信息的記錄。

動(dòng)態(tài)類加載

在上下文初始化時(shí),Pinpointinstrumentation注冊(cè)了一個(gè)Transformer,該接口只定義個(gè)一個(gè)方法transform(),該方法會(huì)在加載新class類或者重新加載class類時(shí)調(diào)用,其調(diào)用路徑如下:

DefaultClassFileTransformerDispatcher.transform()

|— BaseClassFileTransformer.transform()

|—— MatchableClassFileTransformerDelegate.transform()

|——— TransformCallback.doInTransform()

可以看到,最后執(zhí)行的就是我們?cè)谏厦鎴?zhí)行XxxPlugin.setup()方法時(shí)配置的回調(diào)接口,即對(duì)指定的方法進(jìn)行字節(jié)碼增強(qiáng)。而Java應(yīng)用啟動(dòng)后,加載的就是我們?cè)鰪?qiáng)后的類,從而實(shí)現(xiàn)鏈路監(jiān)控或其他的功能。

特別推薦一個(gè)分享架構(gòu)+算法的優(yōu)質(zhì)內(nèi)容,還沒(méi)關(guān)注的小伙伴,可以長(zhǎng)按關(guān)注一下:

分布式系統(tǒng)性能監(jiān)控工具,初探Pinpoint Agent啟動(dòng)源碼

長(zhǎng)按訂閱更多精彩▼

分布式系統(tǒng)性能監(jiān)控工具,初探Pinpoint Agent啟動(dòng)源碼

如有收獲,點(diǎn)個(gè)在看,誠(chéng)摯感謝

免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺(tái)僅提供信息存儲(chǔ)服務(wù)。文章僅代表作者個(gè)人觀點(diǎn),不代表本平臺(tái)立場(chǎng),如有問(wèn)題,請(qǐng)聯(lián)系我們,謝謝!

本站聲明: 本文章由作者或相關(guān)機(jī)構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點(diǎn),本站亦不保證或承諾內(nèi)容真實(shí)性等。需要轉(zhuǎn)載請(qǐng)聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請(qǐng)及時(shí)聯(lián)系本站刪除( 郵箱:macysun@21ic.com )。
換一批
延伸閱讀
關(guān)閉