Search in sources :

Example 1 with ManagedProcessorMBean

use of org.apache.camel.api.management.mbean.ManagedProcessorMBean in project camel by apache.

the class ManagedRoute method dumpRouteStatsAsXml.

public String dumpRouteStatsAsXml(boolean fullStats, boolean includeProcessors) throws Exception {
    // in this logic we need to calculate the accumulated processing time for the processor in the route
    // and hence why the logic is a bit more complicated to do this, as we need to calculate that from
    // the bottom -> top of the route but this information is valuable for profiling routes
    StringBuilder sb = new StringBuilder();
    // need to calculate this value first, as we need that value for the route stat
    Long processorAccumulatedTime = 0L;
    // gather all the processors for this route, which requires JMX
    if (includeProcessors) {
        sb.append("  <processorStats>\n");
        MBeanServer server = getContext().getManagementStrategy().getManagementAgent().getMBeanServer();
        if (server != null) {
            // get all the processor mbeans and sort them accordingly to their index
            String prefix = getContext().getManagementStrategy().getManagementAgent().getIncludeHostName() ? "*/" : "";
            ObjectName query = ObjectName.getInstance(jmxDomain + ":context=" + prefix + getContext().getManagementName() + ",type=processors,*");
            Set<ObjectName> names = server.queryNames(query, null);
            List<ManagedProcessorMBean> mps = new ArrayList<ManagedProcessorMBean>();
            for (ObjectName on : names) {
                ManagedProcessorMBean processor = context.getManagementStrategy().getManagementAgent().newProxyClient(on, ManagedProcessorMBean.class);
                // the processor must belong to this route
                if (getRouteId().equals(processor.getRouteId())) {
                    mps.add(processor);
                }
            }
            mps.sort(new OrderProcessorMBeans());
            // walk the processors in reverse order, and calculate the accumulated total time
            Map<String, Long> accumulatedTimes = new HashMap<String, Long>();
            Collections.reverse(mps);
            for (ManagedProcessorMBean processor : mps) {
                processorAccumulatedTime += processor.getTotalProcessingTime();
                accumulatedTimes.put(processor.getProcessorId(), processorAccumulatedTime);
            }
            // and reverse back again
            Collections.reverse(mps);
            // and now add the sorted list of processors to the xml output
            for (ManagedProcessorMBean processor : mps) {
                sb.append("    <processorStat").append(String.format(" id=\"%s\" index=\"%s\" state=\"%s\"", processor.getProcessorId(), processor.getIndex(), processor.getState()));
                // do we have an accumulated time then append that
                Long accTime = accumulatedTimes.get(processor.getProcessorId());
                if (accTime != null) {
                    sb.append(" accumulatedProcessingTime=\"").append(accTime).append("\"");
                }
                // use substring as we only want the attributes
                sb.append(" ").append(processor.dumpStatsAsXml(fullStats).substring(7)).append("\n");
            }
        }
        sb.append("  </processorStats>\n");
    }
    // route self time is route total - processor accumulated total)
    long routeSelfTime = getTotalProcessingTime() - processorAccumulatedTime;
    if (routeSelfTime < 0) {
        // ensure we don't calculate that as negative
        routeSelfTime = 0;
    }
    StringBuilder answer = new StringBuilder();
    answer.append("<routeStat").append(String.format(" id=\"%s\"", route.getId())).append(String.format(" state=\"%s\"", getState()));
    // use substring as we only want the attributes
    String stat = dumpStatsAsXml(fullStats);
    answer.append(" exchangesInflight=\"").append(getInflightExchanges()).append("\"");
    answer.append(" selfProcessingTime=\"").append(routeSelfTime).append("\"");
    InFlightKey oldestInflightEntry = getOldestInflightEntry();
    if (oldestInflightEntry == null) {
        answer.append(" oldestInflightExchangeId=\"\"");
        answer.append(" oldestInflightDuration=\"\"");
    } else {
        answer.append(" oldestInflightExchangeId=\"").append(oldestInflightEntry.exchangeId).append("\"");
        answer.append(" oldestInflightDuration=\"").append(System.currentTimeMillis() - oldestInflightEntry.timeStamp).append("\"");
    }
    answer.append(" ").append(stat.substring(7, stat.length() - 2)).append(">\n");
    if (includeProcessors) {
        answer.append(sb);
    }
    answer.append("</routeStat>");
    return answer.toString();
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) ManagedProcessorMBean(org.apache.camel.api.management.mbean.ManagedProcessorMBean) ObjectName(javax.management.ObjectName) MBeanServer(javax.management.MBeanServer)

Example 2 with ManagedProcessorMBean

use of org.apache.camel.api.management.mbean.ManagedProcessorMBean in project camel by apache.

the class CamelTestSupport method logCoverageSummary.

/**
     * Logs route coverage summary:
     * - which routes are uncovered
     * - what is the coverage of each processor in each route
     */
private void logCoverageSummary(ManagedCamelContextMBean managedCamelContext) throws Exception {
    StringBuilder builder = new StringBuilder("\nCoverage summary\n");
    int routes = managedCamelContext.getTotalRoutes();
    long contextExchangesTotal = managedCamelContext.getExchangesTotal();
    List<String> uncoveredRoutes = new ArrayList<>();
    StringBuilder routesSummary = new StringBuilder();
    routesSummary.append("\tProcessor coverage\n");
    MBeanServer server = context.getManagementStrategy().getManagementAgent().getMBeanServer();
    Map<String, List<ManagedProcessorMBean>> processorsForRoute = findProcessorsForEachRoute(server);
    // log processor coverage for each route
    for (Route route : context.getRoutes()) {
        ManagedRouteMBean managedRoute = context.getManagedRoute(route.getId(), ManagedRouteMBean.class);
        if (managedRoute.getExchangesTotal() == 0) {
            uncoveredRoutes.add(route.getId());
        }
        long routeCoveragePercentage = Math.round((double) managedRoute.getExchangesTotal() / contextExchangesTotal * 100);
        routesSummary.append("\t\tRoute ").append(route.getId()).append(" total: ").append(managedRoute.getExchangesTotal()).append(" (").append(routeCoveragePercentage).append("%)\n");
        if (server != null) {
            for (ManagedProcessorMBean managedProcessor : processorsForRoute.get(route.getId())) {
                String processorId = managedProcessor.getProcessorId();
                long processorExchangesTotal = managedProcessor.getExchangesTotal();
                long processorCoveragePercentage = Math.round((double) processorExchangesTotal / contextExchangesTotal * 100);
                routesSummary.append("\t\t\tProcessor ").append(processorId).append(" total: ").append(processorExchangesTotal).append(" (").append(processorCoveragePercentage).append("%)\n");
            }
        }
    }
    int used = routes - uncoveredRoutes.size();
    long contextPercentage = Math.round((double) used / routes * 100);
    builder.append("\tRoute coverage: ").append(used).append(" out of ").append(routes).append(" routes used (").append(contextPercentage).append("%)\n");
    builder.append("\t\tCamelContext (").append(managedCamelContext.getCamelId()).append(") total: ").append(contextExchangesTotal).append("\n");
    if (uncoveredRoutes.size() > 0) {
        builder.append("\t\tUncovered routes: ").append(uncoveredRoutes.stream().collect(Collectors.joining(", "))).append("\n");
    }
    builder.append(routesSummary);
    log.info(builder.toString());
}
Also used : ManagedRouteMBean(org.apache.camel.api.management.mbean.ManagedRouteMBean) ArrayList(java.util.ArrayList) ManagedProcessorMBean(org.apache.camel.api.management.mbean.ManagedProcessorMBean) List(java.util.List) ArrayList(java.util.ArrayList) Endpoint(org.apache.camel.Endpoint) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Route(org.apache.camel.Route) MBeanServer(javax.management.MBeanServer)

Example 3 with ManagedProcessorMBean

use of org.apache.camel.api.management.mbean.ManagedProcessorMBean in project camel by apache.

the class CamelTestSupport method findProcessorsForEachRoute.

/**
     * Groups all processors from Camel context by route id
     */
private Map<String, List<ManagedProcessorMBean>> findProcessorsForEachRoute(MBeanServer server) throws MalformedObjectNameException, MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
    String domain = context.getManagementStrategy().getManagementAgent().getMBeanServerDefaultDomain();
    Map<String, List<ManagedProcessorMBean>> processorsForRoute = new HashMap<>();
    ObjectName processorsObjectName = new ObjectName(domain + ":context=" + context.getManagementName() + ",type=processors,name=*");
    Set<ObjectName> objectNames = server.queryNames(processorsObjectName, null);
    if (server != null) {
        for (ObjectName objectName : objectNames) {
            String routeId = server.getAttribute(objectName, "RouteId").toString();
            String name = objectName.getKeyProperty("name");
            name = ObjectName.unquote(name);
            ManagedProcessorMBean managedProcessor = context.getManagedProcessor(name, ManagedProcessorMBean.class);
            if (managedProcessor != null) {
                if (processorsForRoute.get(routeId) == null) {
                    List<ManagedProcessorMBean> processorsList = new ArrayList<>();
                    processorsList.add(managedProcessor);
                    processorsForRoute.put(routeId, processorsList);
                } else {
                    processorsForRoute.get(routeId).add(managedProcessor);
                }
            }
        }
    }
    // sort processors by position in route definition
    for (Map.Entry<String, List<ManagedProcessorMBean>> entry : processorsForRoute.entrySet()) {
        Collections.sort(entry.getValue(), (o1, o2) -> o1.getIndex().compareTo(o2.getIndex()));
    }
    return processorsForRoute;
}
Also used : HashMap(java.util.HashMap) ManagedProcessorMBean(org.apache.camel.api.management.mbean.ManagedProcessorMBean) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) ObjectName(javax.management.ObjectName)

Example 4 with ManagedProcessorMBean

use of org.apache.camel.api.management.mbean.ManagedProcessorMBean in project camel by apache.

the class ManagedCamelContext method dumpRoutesStatsAsXml.

public String dumpRoutesStatsAsXml(boolean fullStats, boolean includeProcessors) throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.append("<camelContextStat").append(String.format(" id=\"%s\" state=\"%s\"", getCamelId(), getState()));
    // use substring as we only want the attributes
    String stat = dumpStatsAsXml(fullStats);
    sb.append(" exchangesInflight=\"").append(getInflightExchanges()).append("\"");
    sb.append(" ").append(stat.substring(7, stat.length() - 2)).append(">\n");
    MBeanServer server = getContext().getManagementStrategy().getManagementAgent().getMBeanServer();
    if (server != null) {
        // gather all the routes for this CamelContext, which requires JMX
        String prefix = getContext().getManagementStrategy().getManagementAgent().getIncludeHostName() ? "*/" : "";
        ObjectName query = ObjectName.getInstance(jmxDomain + ":context=" + prefix + getContext().getManagementName() + ",type=routes,*");
        Set<ObjectName> routes = server.queryNames(query, null);
        List<ManagedProcessorMBean> processors = new ArrayList<ManagedProcessorMBean>();
        if (includeProcessors) {
            // gather all the processors for this CamelContext, which requires JMX
            query = ObjectName.getInstance(jmxDomain + ":context=" + prefix + getContext().getManagementName() + ",type=processors,*");
            Set<ObjectName> names = server.queryNames(query, null);
            for (ObjectName on : names) {
                ManagedProcessorMBean processor = context.getManagementStrategy().getManagementAgent().newProxyClient(on, ManagedProcessorMBean.class);
                processors.add(processor);
            }
        }
        processors.sort(new OrderProcessorMBeans());
        // loop the routes, and append the processor stats if needed
        sb.append("  <routeStats>\n");
        for (ObjectName on : routes) {
            ManagedRouteMBean route = context.getManagementStrategy().getManagementAgent().newProxyClient(on, ManagedRouteMBean.class);
            sb.append("    <routeStat").append(String.format(" id=\"%s\" state=\"%s\"", route.getRouteId(), route.getState()));
            // use substring as we only want the attributes
            stat = route.dumpStatsAsXml(fullStats);
            sb.append(" exchangesInflight=\"").append(route.getExchangesInflight()).append("\"");
            sb.append(" ").append(stat.substring(7, stat.length() - 2)).append(">\n");
            // add processor details if needed
            if (includeProcessors) {
                sb.append("      <processorStats>\n");
                for (ManagedProcessorMBean processor : processors) {
                    // the processor must belong to this route
                    if (route.getRouteId().equals(processor.getRouteId())) {
                        sb.append("        <processorStat").append(String.format(" id=\"%s\" index=\"%s\" state=\"%s\"", processor.getProcessorId(), processor.getIndex(), processor.getState()));
                        // use substring as we only want the attributes
                        stat = processor.dumpStatsAsXml(fullStats);
                        sb.append(" exchangesInflight=\"").append(processor.getExchangesInflight()).append("\"");
                        sb.append(" ").append(stat.substring(7)).append("\n");
                    }
                }
                sb.append("      </processorStats>\n");
            }
            sb.append("    </routeStat>\n");
        }
        sb.append("  </routeStats>\n");
    }
    sb.append("</camelContextStat>");
    return sb.toString();
}
Also used : ManagedRouteMBean(org.apache.camel.api.management.mbean.ManagedRouteMBean) ArrayList(java.util.ArrayList) ManagedProcessorMBean(org.apache.camel.api.management.mbean.ManagedProcessorMBean) MBeanServer(javax.management.MBeanServer) ObjectName(javax.management.ObjectName)

Example 5 with ManagedProcessorMBean

use of org.apache.camel.api.management.mbean.ManagedProcessorMBean in project camel by apache.

the class RouteCoverageXmlParser method parseXml.

/**
     * Parses the XML.
     *
     * @param camelContext the CamelContext
     * @param is           the XML content as an input stream
     * @return the DOM model of the routes with coverage information stored as attributes
     * @throws Exception is thrown if error parsing
     */
public static Document parseXml(final CamelContext camelContext, final InputStream is) throws Exception {
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    final SAXParser parser = factory.newSAXParser();
    final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    final Document doc = docBuilder.newDocument();
    final Stack<Element> elementStack = new Stack<Element>();
    final StringBuilder textBuffer = new StringBuilder();
    final DefaultHandler handler = new DefaultHandler() {

        @Override
        public void setDocumentLocator(final Locator locator) {
        // noop
        }

        @Override
        public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
            addTextIfNeeded();
            final Element el = doc.createElement(qName);
            // add other elements
            for (int i = 0; i < attributes.getLength(); i++) {
                el.setAttribute(attributes.getQName(i), attributes.getValue(i));
            }
            String id = el.getAttribute("id");
            if (id != null) {
                try {
                    if ("route".equals(qName)) {
                        ManagedRouteMBean route = camelContext.getManagedRoute(id, ManagedRouteMBean.class);
                        if (route != null) {
                            long total = route.getExchangesTotal();
                            el.setAttribute("exchangesTotal", "" + total);
                            long totalTime = route.getTotalProcessingTime();
                            el.setAttribute("totalProcessingTime", "" + totalTime);
                        }
                    } else if ("from".equals(qName)) {
                    // TODO: include the stats from the route mbean as that would be the same
                    } else {
                        ManagedProcessorMBean processor = camelContext.getManagedProcessor(id, ManagedProcessorMBean.class);
                        if (processor != null) {
                            long total = processor.getExchangesTotal();
                            el.setAttribute("exchangesTotal", "" + total);
                            long totalTime = processor.getTotalProcessingTime();
                            el.setAttribute("totalProcessingTime", "" + totalTime);
                        }
                    }
                } catch (Exception e) {
                // ignore
                }
            }
            // we do not want customId in output
            el.removeAttribute("customId");
            elementStack.push(el);
        }

        @Override
        public void endElement(final String uri, final String localName, final String qName) {
            addTextIfNeeded();
            final Element closedEl = elementStack.pop();
            if (elementStack.isEmpty()) {
                // is this the root element?
                doc.appendChild(closedEl);
            } else {
                final Element parentEl = elementStack.peek();
                parentEl.appendChild(closedEl);
            }
        }

        @Override
        public void characters(final char[] ch, final int start, final int length) throws SAXException {
            textBuffer.append(ch, start, length);
        }

        /**
             * outputs text accumulated under the current node
             */
        private void addTextIfNeeded() {
            if (textBuffer.length() > 0) {
                final Element el = elementStack.peek();
                final Node textNode = doc.createTextNode(textBuffer.toString());
                el.appendChild(textNode);
                textBuffer.delete(0, textBuffer.length());
            }
        }
    };
    parser.parse(is, handler);
    return doc;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ManagedRouteMBean(org.apache.camel.api.management.mbean.ManagedRouteMBean) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Attributes(org.xml.sax.Attributes) ManagedProcessorMBean(org.apache.camel.api.management.mbean.ManagedProcessorMBean) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) Stack(java.util.Stack) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Locator(org.xml.sax.Locator) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParser(javax.xml.parsers.SAXParser) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

ManagedProcessorMBean (org.apache.camel.api.management.mbean.ManagedProcessorMBean)5 ArrayList (java.util.ArrayList)4 MBeanServer (javax.management.MBeanServer)3 ObjectName (javax.management.ObjectName)3 ManagedRouteMBean (org.apache.camel.api.management.mbean.ManagedRouteMBean)3 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)1 Stack (java.util.Stack)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 DocumentBuilder (javax.xml.parsers.DocumentBuilder)1 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)1 SAXParser (javax.xml.parsers.SAXParser)1 SAXParserFactory (javax.xml.parsers.SAXParserFactory)1 Endpoint (org.apache.camel.Endpoint)1 Route (org.apache.camel.Route)1 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)1 Document (org.w3c.dom.Document)1 Element (org.w3c.dom.Element)1 Node (org.w3c.dom.Node)1