Search in sources :

Example 21 with Command

use of com.shulie.instrument.simulator.api.annotation.Command in project LinkAgent by shulieTech.

the class TraceModule method trace.

@Command(value = "info", description = "方法追踪")
public CommandResponse trace(final Map<String, String> param) {
    final String classPatternStr = param.get("classPatterns");
    if (StringUtil.isEmpty(classPatternStr)) {
        return CommandResponse.failure("classPatterns must not be empty.");
    }
    final String[] classPatterns = classPatternStr.split(",");
    /**
     * 如果 wait 和 count 都没有填写,则默认统计20条
     */
    final int wait = ParameterUtils.getInt(param, "wait", 5000);
    /**
     * 最多层数
     */
    final int level = ParameterUtils.getInt(param, "level", 0);
    /**
     * 条数限定
     */
    final int limits = ParameterUtils.getInt(param, "limits", 100);
    Set<EventWatcher> childrenWatchers = new ConcurrentHashSet<EventWatcher>();
    List<EventWatcher> watchers = new ArrayList<EventWatcher>();
    try {
        if (wait > 10 * 60 * 1000) {
            return CommandResponse.failure("wait 最大等待时间不能超过10分钟");
        }
        if (limits > 5000) {
            return CommandResponse.failure("limits 最大不能超过5000");
        }
        /**
         * 多少毫秒以下停止
         */
        final int stopInMills = ParameterUtils.getInt(param, "stop", -1);
        Map<String, Queue<TraceView>> traceViews = new ConcurrentHashMap<String, Queue<TraceView>>();
        Set<String> traceMethods = new ConcurrentHashSet<String>();
        Set<Class<?>> classes = findClasses(classPatterns);
        Set<Class<?>> instrumentClasses = new HashSet<Class<?>>();
        boolean foundInterface = false;
        boolean foundEnum = false;
        boolean foundAnnotation = false;
        for (Class clazz : classes) {
            if (clazz.isInterface()) {
                Set<Class<?>> implClasses = findImplClasses(clazz);
                instrumentClasses.addAll(implClasses);
            } else if (!clazz.isEnum() && !clazz.isAnnotation()) {
                instrumentClasses.addAll(getProxyInterfaceImplClasses(clazz));
            } else if (clazz.isEnum()) {
                foundEnum = true;
            } else if (clazz.isAnnotation()) {
                foundAnnotation = true;
            }
        }
        if (instrumentClasses.isEmpty()) {
            String errorMsg = "can't found class:" + classPatternStr;
            if (foundInterface) {
                errorMsg = "can't found impl class with interface:" + classPatternStr;
            } else if (foundEnum) {
                errorMsg = "can't trace class because of it is a enum:" + classPatternStr;
            } else if (foundAnnotation) {
                errorMsg = "can't trace class because of it is a annotation:" + classPatternStr;
            }
            return CommandResponse.failure(errorMsg);
        }
        final CountDownLatch latch = new CountDownLatch(1);
        for (Class clazz : instrumentClasses) {
            EventWatcher watcher = new EventWatchBuilder(moduleEventWatcher).onClass(clazz.getName()).includeSubClasses().onAnyBehavior().withInvoke().withCall().onListener(Listeners.of(TraceListener.class, new Object[] { classPatterns, latch, traceViews, traceMethods, childrenWatchers, level, limits, stopInMills, wait })).onClass().onWatch();
            watchers.add(watcher);
        }
        if (wait > 0) {
            latch.await(wait, TimeUnit.MILLISECONDS);
        } else if (limits > 0) {
            latch.await();
        }
        return CommandResponse.success(traceViews);
    } catch (Throwable e) {
        logger.error("SIMULATOR: trace module err! class={},limits={}, wait={}", limits, wait, e);
        return CommandResponse.failure(e);
    } finally {
        for (EventWatcher watcher : watchers) {
            try {
                watcher.onUnWatched();
            } catch (Throwable e) {
                logger.error("SIMULATOR: trace module unwatched failed! class={},limits={}, wait={}", limits, wait, e);
            }
        }
        for (EventWatcher eventWatcher : childrenWatchers) {
            try {
                eventWatcher.onUnWatched();
            } catch (Throwable e) {
                logger.error("SIMULATOR: trace module unwatched failed! class={},limits={}, wait={}", limits, wait, e);
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) EventWatcher(com.shulie.instrument.simulator.api.listener.ext.EventWatcher) ModuleEventWatcher(com.shulie.instrument.simulator.api.resource.ModuleEventWatcher) CountDownLatch(java.util.concurrent.CountDownLatch) TraceView(com.shulie.instrument.simulator.module.model.trace2.TraceView) ConcurrentHashSet(com.shulie.instrument.simulator.module.stack.trace.util.ConcurrentHashSet) EventWatchBuilder(com.shulie.instrument.simulator.api.listener.ext.EventWatchBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Queue(java.util.Queue) HashSet(java.util.HashSet) ConcurrentHashSet(com.shulie.instrument.simulator.module.stack.trace.util.ConcurrentHashSet) Command(com.shulie.instrument.simulator.api.annotation.Command)

Example 22 with Command

use of com.shulie.instrument.simulator.api.annotation.Command in project LinkAgent by shulieTech.

the class ModuleManagementModule method list.

@Command(value = "list", description = "模块列表")
public CommandResponse list() throws IOException {
    try {
        List<ModuleInf> moduleInfoList = new ArrayList<ModuleInf>();
        for (final ModuleSpec moduleSpec : moduleManager.listModuleSpecs()) {
            ModuleInf moduleInf = new ModuleInf();
            moduleInf.setModuleId(moduleSpec.getModuleId());
            moduleInf.setSystemModule(moduleSpec.isSystemModule());
            moduleInf.setPath(moduleSpec.getFile() != null ? moduleSpec.getFile().getCanonicalPath() : null);
            moduleInf.setSwitchControl(moduleSpec.getDependencies());
            moduleInf.setExportClasses(moduleSpec.getExportClasses());
            moduleInf.setExportExactlyPackages(moduleSpec.getExportExactlyPackages());
            moduleInf.setExportExactlyResources(moduleSpec.getExportExactlyResources());
            moduleInf.setExportPackages(moduleSpec.getExportPackages());
            moduleInf.setExportPrefixPackages(moduleSpec.getExportPrefixPackages());
            moduleInf.setExportPrefixResources(moduleSpec.getExportPrefixResources());
            moduleInf.setExportResources(moduleSpec.getExportResources());
            moduleInf.setExportSuffixPackages(moduleSpec.getExportSuffixPackages());
            moduleInf.setExportSuffixResources(moduleSpec.getExportSuffixResources());
            moduleInf.setAuthor(moduleSpec.getAuthor());
            moduleInf.setVersion(moduleSpec.getVersion());
            moduleInf.setPriority(moduleSpec.getPriority());
            moduleInf.setSupportedModes(moduleSpec.getSupportedModes());
            moduleInf.setActiveOnLoad(moduleSpec.isActiveOnLoad());
            moduleInf.setDescription(moduleSpec.getDescription());
            moduleInfoList.add(moduleInf);
        }
        return CommandResponse.success(moduleInfoList);
    } catch (Throwable e) {
        logger.error("SIMULATOR: module management list module err.", e);
        return CommandResponse.failure(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ModuleInf(com.shulie.instrument.simulator.module.mgr.model.ModuleInf) Command(com.shulie.instrument.simulator.api.annotation.Command)

Example 23 with Command

use of com.shulie.instrument.simulator.api.annotation.Command in project LinkAgent by shulieTech.

the class ModuleManagementModule method load.

@Command(value = "load", description = "模块加载")
public CommandResponse load(final Map<String, String> args) throws ModuleException {
    String path = args.get("path");
    File file = new File(path);
    if (!file.exists()) {
        return CommandResponse.failure("module file is not exits" + path);
    }
    try {
        moduleManager.load(file);
        return CommandResponse.success(true);
    } catch (Throwable e) {
        logger.error("SIMULATOR: module management load module err. {}", path, e);
        return CommandResponse.failure(e);
    }
}
Also used : File(java.io.File) Command(com.shulie.instrument.simulator.api.annotation.Command)

Example 24 with Command

use of com.shulie.instrument.simulator.api.annotation.Command in project LinkAgent by shulieTech.

the class TomcatModule method info.

@Command(value = "info", description = "查看 tomcat 信息")
public CommandResponse info(final Map<String, String> args) {
    try {
        int port = ParameterUtils.getInt(args, "port", 8006);
        // 如果请求tomcat信息失败,则不显示tomcat信息
        final String url = "http://localhost:" + port;
        if (!NetUtils.request(url).isSuccess()) {
            return CommandResponse.failure("tomcat unreachable with port:" + url);
        }
        TomcatInfo tomcatInfo = new TomcatInfo();
        String threadPoolPath = url + "/connector/threadpool";
        String connectorStatPath = url + "/connector/stats";
        NetUtils.Response connectorStatResponse = NetUtils.request(connectorStatPath);
        if (connectorStatResponse.isSuccess()) {
            List<TomcatInfo.ConnectorStats> connectorStats = new ArrayList<TomcatInfo.ConnectorStats>();
            List<JSONObject> tomcatConnectorStats = JSON.parseArray(connectorStatResponse.getContent(), JSONObject.class);
            for (JSONObject stat : tomcatConnectorStats) {
                String connectorName = stat.getString("name").replace("\"", "");
                long bytesReceived = stat.getLongValue("bytesReceived");
                long bytesSent = stat.getLongValue("bytesSent");
                long processingTime = stat.getLongValue("processingTime");
                long requestCount = stat.getLongValue("requestCount");
                long errorCount = stat.getLongValue("errorCount");
                tomcatRequestCounter.update(requestCount);
                tomcatErrorCounter.update(errorCount);
                tomcatReceivedBytesCounter.update(bytesReceived);
                tomcatSentBytesCounter.update(bytesSent);
                double qps = tomcatRequestCounter.rate();
                double rt = processingTime / (double) requestCount;
                double errorRate = tomcatErrorCounter.rate();
                long receivedBytesRate = new Double(tomcatReceivedBytesCounter.rate()).longValue();
                long sentBytesRate = new Double(tomcatSentBytesCounter.rate()).longValue();
                TomcatInfo.ConnectorStats connectorStat = new TomcatInfo.ConnectorStats();
                connectorStat.setName(connectorName);
                connectorStat.setQps(qps);
                connectorStat.setRt(rt);
                connectorStat.setError(errorRate);
                connectorStat.setReceived(receivedBytesRate);
                connectorStat.setSent(sentBytesRate);
                connectorStats.add(connectorStat);
            }
            tomcatInfo.setConnectorStats(connectorStats);
        }
        NetUtils.Response threadPoolResponse = NetUtils.request(threadPoolPath);
        if (threadPoolResponse.isSuccess()) {
            List<TomcatInfo.ThreadPool> threadPools = new ArrayList<TomcatInfo.ThreadPool>();
            List<JSONObject> threadPoolInfos = JSON.parseArray(threadPoolResponse.getContent(), JSONObject.class);
            for (JSONObject info : threadPoolInfos) {
                String name = info.getString("name").replace("\"", "");
                long busy = info.getLongValue("threadBusy");
                long total = info.getLongValue("threadCount");
                threadPools.add(new TomcatInfo.ThreadPool(name, busy, total));
            }
            tomcatInfo.setThreadPools(threadPools);
        }
        return CommandResponse.success(tomcatInfo);
    } catch (Throwable e) {
        return CommandResponse.failure(e);
    }
}
Also used : ArrayList(java.util.ArrayList) TomcatInfo(com.shulie.instrument.simulator.module.model.tomcat.TomcatInfo) NetUtils(com.shulie.instrument.simulator.module.util.NetUtils) JSONObject(com.alibaba.fastjson.JSONObject) Command(com.shulie.instrument.simulator.api.annotation.Command)

Example 25 with Command

use of com.shulie.instrument.simulator.api.annotation.Command in project LinkAgent by shulieTech.

the class OgnlModule method info.

@Command(value = "info", description = "执行 ognl 表达式")
public CommandResponse info(final Map<String, String> args) {
    String express = args.get("express");
    String hashCode = args.get("classLoader");
    if (StringUtils.isBlank(express)) {
        return CommandResponse.failure("express can't be null or empty.");
    }
    try {
        Instrumentation inst = simulatorConfig.getInstrumentation();
        ClassLoader classLoader = null;
        if (hashCode == null) {
            classLoader = ClassLoader.getSystemClassLoader();
        } else {
            classLoader = ClassLoaderUtils.getClassLoader(inst, hashCode);
        }
        if (classLoader == null) {
            return CommandResponse.failure("Can not find classloader with classloader<hashCode>: " + hashCode + ".");
        }
        Express unpooledExpress = ExpressFactory.unpooledExpress(classLoader);
        Object value = unpooledExpress.get(express);
        return CommandResponse.success(value);
    } catch (ExpressException e) {
        logger.warn("ognl: failed execute express: " + express, e);
        return CommandResponse.failure("Failed to execute ognl, exception message: " + e.getMessage() + ", please check $HOME/logs/simulator/simulator.log for more details. ");
    } catch (Throwable t) {
        logger.warn("ognl: failed execute express: " + express, t);
        return CommandResponse.failure(t);
    }
}
Also used : ExpressException(com.shulie.instrument.simulator.module.express.ExpressException) Express(com.shulie.instrument.simulator.module.express.Express) Instrumentation(java.lang.instrument.Instrumentation) Command(com.shulie.instrument.simulator.api.annotation.Command)

Aggregations

Command (com.shulie.instrument.simulator.api.annotation.Command)27 ArrayList (java.util.ArrayList)10 EventWatchBuilder (com.shulie.instrument.simulator.api.listener.ext.EventWatchBuilder)5 EventWatcher (com.shulie.instrument.simulator.api.listener.ext.EventWatcher)5 ModuleEventWatcher (com.shulie.instrument.simulator.api.resource.ModuleEventWatcher)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 File (java.io.File)4 Method (java.lang.reflect.Method)3 List (java.util.List)3 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)3 PullLogResponse (com.shulie.instrument.module.log.data.pusher.log.PullLogResponse)2 NameRegexFilter (com.shulie.instrument.simulator.api.filter.NameRegexFilter)2 ModuleInf (com.shulie.instrument.simulator.module.mgr.model.ModuleInf)2 GcInfo (com.shulie.instrument.simulator.module.model.gc.GcInfo)2 MemoryInfo (com.shulie.instrument.simulator.module.model.memory.MemoryInfo)2 HotSpotDiagnosticMXBean (com.sun.management.HotSpotDiagnosticMXBean)2 VMOption (com.sun.management.VMOption)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 JSONObject (com.alibaba.fastjson.JSONObject)1