APM - 零侵入监控JDBC服务

本文涉及的产品
应用实时监控服务-应用监控,每月50GB免费额度
应用实时监控服务-用户体验监控,每月100OCU免费额度
简介: APM - 零侵入监控JDBC服务

20201008121406705.png


Code

public class JdbcCommonCollects extends AbstractByteTransformCollect implements ICollect {
  public static  JdbcCommonCollects INSTANCE;
  private ApmContext context;
  public JdbcCommonCollects(ApmContext context, Instrumentation instrumentation) {
    super(instrumentation);
    INSTANCE=this;
    this.context=context;
  }
    private final static String[] connection_agent_methods = new String[]{"prepareStatement"};
    private final static String[] prepared_statement_methods = new String[]{"execute", "executeUpdate", "executeQuery"};
    private static final String beginSrc;
    private static final String endSrc;
    private static final String errorSrc;
    static {
        // connect
        beginSrc = "com.artisan.collects.JdbcCommonCollects inst=com.artisan.collects.JdbcCommonCollects.INSTANCE;";
        errorSrc = "inst.error(null,e);";
        endSrc = "result=inst.proxyConnection((java.sql.Connection)result);";
    }
    public JdbcStatistics begin(String className, String method) {
        JdbcStatistics jdbcStat = new JdbcStatistics();
        jdbcStat.begin=System.currentTimeMillis();
        jdbcStat.setModelType("jdbc");
        return jdbcStat;
    }
    public void end(JdbcStatistics stat) {
        JdbcStatistics jdbcStat= (JdbcStatistics) stat;
        jdbcStat.end=System.currentTimeMillis();
        jdbcStat.useTime =jdbcStat.end-jdbcStat.begin;
        if (jdbcStat.jdbcUrl != null) {
            jdbcStat.databaseName = getDbName(jdbcStat.jdbcUrl);
        }
        this.context.submitCollectResult(stat);
    }
    public void error(JdbcStatistics stat, Throwable throwable) {
        if (stat != null) {
            stat.error = throwable.getMessage();
            stat.errorType = throwable.getClass().getName();
            if (throwable instanceof InvocationTargetException) {
                stat.errorType = ((InvocationTargetException) throwable).getTargetException().getClass().getName();
                stat.error = ((InvocationTargetException) throwable).getTargetException().getMessage();
            }
        }
    }
    public void sendStatistics(JdbcStatistics stat) {
    }
    public Connection proxyConnection(final Connection connection) {
        Object c = Proxy.newProxyInstance(JdbcCommonCollects.class.getClassLoader()
                , new Class[]{Connection.class}, new ConnectionHandler(connection));
        return (Connection) c;
    }
    public PreparedStatement proxyPreparedStatement(final PreparedStatement statement, JdbcStatistics jdbcStat) {
        Object c = Proxy.newProxyInstance(JdbcCommonCollects.class.getClassLoader()
                , new Class[]{PreparedStatement.class}, new PreparedStatementHandler(statement, jdbcStat));
        return (PreparedStatement) c;
    }
    public byte[] transform(ClassLoader loader, String className) throws Exception {
        // System.out.println("JDBC className:" + className);
        // 如果更換數據庫,需要替換改類  這裡目前僅適配了MySQL
       if (!className.equals("com.mysql.cj.jdbc.NonRegisteringDriver")) {
             return null;
         }
      CtClass ctclass = super.toCtClass(loader, className);
      AgentByteBuild byteLoade = new AgentByteBuild(className, loader, ctclass);
        CtMethod connectMethod = ctclass.getMethod("connect", "(Ljava/lang/String;Ljava/util/Properties;)Ljava/sql/Connection;");
//      connectMethod.getMethodInfo().getDescriptor();
        AgentByteBuild.MethodSrcBuild build = new AgentByteBuild.MethodSrcBuild();
        build.setBeginSrc(beginSrc);
        build.setErrorSrc(errorSrc);
        build.setEndSrc(endSrc);
        byteLoade.updateMethod(connectMethod, build);
        return byteLoade.toBytecote();
    }
    /**
     * connection 代理处理
     */
    public class ConnectionHandler implements InvocationHandler {
        private final Connection connection;
        private ConnectionHandler(Connection connection) {
            this.connection = connection;
        }
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            boolean isTargetMethod = false;
            for (String agentm : connection_agent_methods) {
                if (agentm.equals(method.getName())) {
                    isTargetMethod = true;
                }
            }
            Object result = null;
            JdbcStatistics jdbcStat = null;
            try {
                if (isTargetMethod) { // 获取PreparedStatement 开始统计
                    jdbcStat = (JdbcStatistics) JdbcCommonCollects.this.begin(null, null);
                    jdbcStat.jdbcUrl = connection.getMetaData().getURL();
                    jdbcStat.sql = (String) args[0];
                }
                result = method.invoke(connection, args);
                // 代理 PreparedStatement
                if (isTargetMethod && result instanceof PreparedStatement) {
                    PreparedStatement ps = (PreparedStatement) result;
                    result = proxyPreparedStatement(ps, jdbcStat);
                }
            } catch (Throwable e) {
                JdbcCommonCollects.this.error(jdbcStat, e);
                JdbcCommonCollects.this.end(jdbcStat);
                throw e;
            }
            return result;
        }
    }
    /**
     * PreparedStatement 代理处理
     */
    public class PreparedStatementHandler implements InvocationHandler {
        private final PreparedStatement statement;
        private final JdbcStatistics jdbcStat;
        public PreparedStatementHandler(PreparedStatement statement, JdbcStatistics jdbcStat) {
            this.statement = statement;
            this.jdbcStat = jdbcStat;
        }
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
            boolean isTargetMethod = false;
            for (String agentm : prepared_statement_methods) {
                if (agentm.equals(method.getName())) {
                    isTargetMethod = true;
                    break;
                }
            }
            Object result = null;
            try {
                // SQL的參數 輸出  TODO  只能输出一个,后面的会把前面的参数覆盖掉
                if (args != null ){
                    List<JdbcStatistics.ParamValues> paramValues = SplitUtils.split2Parts(args, 2);
                    jdbcStat.setParams(paramValues);
                    //System.out.println("KKKKKKK:" + JsonWriter.objectToJson(jdbcStat));
                }
                result = method.invoke(statement, args);
            } catch (Throwable e) {
                if (isTargetMethod) {
                    JdbcCommonCollects.this.error(jdbcStat, e);
                }
                throw e;
            } finally {
                if (isTargetMethod) {
                    JdbcCommonCollects.this.end(jdbcStat);
                }
            }
            return result;
        }
    }
    private static String getDbName(String url) {
        int index = url.indexOf("?"); //$NON-NLS-1$
        if (index != -1) {
            String paramString = url.substring(index + 1, url.length());
            url = url.substring(0, index);
        }
        String dbName = url.substring(url.lastIndexOf("/") + 1);
        return dbName;
    }
}



相关实践学习
通过云拨测对指定服务器进行Ping/DNS监测
本实验将通过云拨测对指定服务器进行Ping/DNS监测,评估网站服务质量和用户体验。
相关文章
|
1月前
|
移动开发 监控 Android开发
Android & iOS 使用 ARMS 用户体验监控(RUM)的最佳实践
本文主要介绍了 ARMS 用户体验监控的基本功能特性,并介绍了在几种常见场景下的最佳实践。
211 12
|
3月前
|
运维 监控 数据可视化
ARMS的微服务监控
【8月更文挑战第23天】
74 6
|
6月前
|
监控 Java 索引
APM Server监控
APM Server监控
|
3月前
|
监控 前端开发 JavaScript
ARMS的Web应用监控
【8月更文挑战第23天】
64 8
|
3月前
|
监控 JavaScript 前端开发
ARMS的移动应用监控
【8月更文挑战第23天】
70 6
|
6月前
|
Kubernetes 监控 安全
Kustomize 生产实战 - 注入监控 APM Agent
Kustomize 生产实战 - 注入监控 APM Agent
|
3月前
|
Prometheus 监控 前端开发
ARMS设置监控规则
【8月更文挑战第24天】
106 9
|
3月前
|
监控 前端开发 JavaScript
ARMS集成监控代码
【8月更文挑战第24天】
75 6
|
3月前
|
数据采集 运维 监控
ARMS自定义监控
【8月更文挑战第25天】
87 3
|
3月前
|
SQL 运维 监控
ARMS全链路监控
【8月更文挑战第22天】
99 3

热门文章

最新文章