001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.management;
018    
019    import java.util.ArrayList;
020    import java.util.Collection;
021    import java.util.HashMap;
022    import java.util.List;
023    import java.util.Map;
024    
025    import javax.management.JMException;
026    import javax.management.MalformedObjectNameException;
027    import javax.management.ObjectName;
028    
029    import org.apache.camel.CamelContext;
030    import org.apache.camel.Endpoint;
031    import org.apache.camel.Exchange;
032    import org.apache.camel.Route;
033    import org.apache.camel.Service;
034    import org.apache.camel.impl.DefaultCamelContext;
035    import org.apache.camel.impl.ServiceSupport;
036    import org.apache.camel.model.ExceptionType;
037    import org.apache.camel.model.ProcessorType;
038    import org.apache.camel.model.RouteType;
039    import org.apache.camel.spi.InstrumentationAgent;
040    import org.apache.camel.spi.LifecycleStrategy;
041    import org.apache.camel.spi.RouteContext;
042    import org.apache.commons.logging.Log;
043    import org.apache.commons.logging.LogFactory;
044    
045    /**
046     * JMX agent that registeres Camel lifecycle events in JMX.
047     *
048     * @version $Revision: 47144 $
049     */
050    public class InstrumentationLifecycleStrategy implements LifecycleStrategy {
051        private static final transient Log LOG = LogFactory.getLog(InstrumentationProcessor.class);
052    
053        private InstrumentationAgent agent;
054        private CamelNamingStrategy namingStrategy;
055        private boolean initialized;
056    
057        // A map (Endpoint -> InstrumentationProcessor) to facilitate
058        // adding per-route interceptor and registering ManagedRoute MBean
059        private Map<Endpoint, InstrumentationProcessor> interceptorMap =
060            new HashMap<Endpoint, InstrumentationProcessor>();
061    
062        public InstrumentationLifecycleStrategy() {
063            this(new DefaultInstrumentationAgent());
064        }
065    
066        public InstrumentationLifecycleStrategy(InstrumentationAgent agent) {
067            this.agent = agent;
068        }
069        /**
070         * Constructor for camel context that has been started.
071         *
072         * @param agent    the agent
073         * @param context  the camel context
074         */
075        public InstrumentationLifecycleStrategy(InstrumentationAgent agent, CamelContext context) {
076            this.agent = agent;
077            onContextStart(context);
078        }
079    
080        public void onContextStart(CamelContext context) {
081            if (context instanceof DefaultCamelContext) {
082                try {
083                    initialized = true;
084                    DefaultCamelContext dc = (DefaultCamelContext)context;
085                    // call addService so that context will start and stop the agent
086                    dc.addService(agent);
087                    namingStrategy = new CamelNamingStrategy(agent.getMBeanObjectDomainName());
088                    ManagedService ms = new ManagedService(dc);
089                    agent.register(ms, getNamingStrategy().getObjectName(dc));
090                } catch (Exception e) {
091                    LOG.warn("Could not register CamelContext MBean", e);
092                }
093            }
094        }
095    
096        public void onEndpointAdd(Endpoint<? extends Exchange> endpoint) {
097            // the agent hasn't been started
098            if (!initialized) {
099                return;
100            }
101    
102            try {
103                ManagedEndpoint me = new ManagedEndpoint(endpoint);
104                agent.register(me, getNamingStrategy().getObjectName(me));
105            } catch (JMException e) {
106                LOG.warn("Could not register Endpoint MBean", e);
107            }
108        }
109    
110        public void onRoutesAdd(Collection<Route> routes) {
111            // the agent hasn't been started
112            if (!initialized) {
113                return;
114            }
115    
116            for (Route route : routes) {
117                try {
118                    ManagedRoute mr = new ManagedRoute(route);
119                    // retrieve the per-route intercept for this route
120                    InstrumentationProcessor interceptor = interceptorMap.get(route.getEndpoint());
121                    if (interceptor == null) {
122                        LOG.warn("Instrumentation processor not found for route endpoint "
123                                 + route.getEndpoint());
124                    } else {
125                        interceptor.setCounter(mr);
126                    }
127                    agent.register(mr, getNamingStrategy().getObjectName(mr));
128                } catch (JMException e) {
129                    LOG.warn("Could not register Route MBean", e);
130                }
131            }
132        }
133    
134        public void onServiceAdd(CamelContext context, Service service) {
135            // the agent hasn't been started
136            if (!initialized) {
137                return;
138            }
139            if (service instanceof ServiceSupport) {
140                try {
141                    ManagedService ms = new ManagedService((ServiceSupport)service);
142                    agent.register(ms, getNamingStrategy().getObjectName(context, ms));
143                } catch (JMException e) {
144                    LOG.warn("Could not register Service MBean", e);
145                }
146            }
147        }
148    
149        public void onRouteContextCreate(RouteContext routeContext) {
150            // the agent hasn't been started
151            if (!initialized) {
152                return;
153            }
154    
155            // Create a map (ProcessorType -> PerformanceCounter)
156            // to be passed to InstrumentationInterceptStrategy.
157            Map<ProcessorType, PerformanceCounter> counterMap =
158                new HashMap<ProcessorType, PerformanceCounter>();
159    
160            // Each processor in a route will have its own performance counter
161            // The performance counter are MBeans that we register with MBeanServer.
162            // These performance counter will be embedded
163            // to InstrumentationProcessor and wrap the appropriate processor
164            // by InstrumentationInterceptStrategy.
165            RouteType route = routeContext.getRoute();
166            
167            for (ProcessorType processor : route.getOutputs()) {
168                ObjectName name = null;
169                try {
170                    // get the mbean name
171                    name = getNamingStrategy().getObjectName(routeContext, processor);
172    
173                    // register mbean wrapped in the performance counter mbean
174                    PerformanceCounter pc = new PerformanceCounter();
175                    agent.register(pc, name);
176    
177                    // add to map now that it has been registered
178                    counterMap.put(processor, pc);
179                } catch (MalformedObjectNameException e) {
180                    LOG.warn("Could not create MBean name: " + name, e);
181                } catch (JMException e) {
182                    LOG.warn("Could not register PerformanceCounter MBean: " + name, e);
183                }
184            }
185            
186            routeContext.addInterceptStrategy(new InstrumentationInterceptStrategy(counterMap));
187    
188            routeContext.setErrorHandlerWrappingStrategy(
189                    new InstrumentationErrorHandlerWrappingStrategy(counterMap));
190    
191            // Add an InstrumentationProcessor at the beginning of each route and
192            // set up the interceptorMap for onRoutesAdd() method to register the
193            // ManagedRoute MBeans.
194    
195            RouteType routeType = routeContext.getRoute();
196            if (routeType.getInputs() != null && !routeType.getInputs().isEmpty()) {
197                if (routeType.getInputs().size() > 1) {
198                    LOG.warn("Add InstrumentationProcessor to first input only.");
199                }
200    
201                Endpoint endpoint  = routeType.getInputs().get(0).getEndpoint();
202    
203                List<ProcessorType<?>> exceptionHandlers = new ArrayList<ProcessorType<?>>();
204                List<ProcessorType<?>> outputs = new ArrayList<ProcessorType<?>>();
205    
206                // separate out the exception handers in the outputs
207                for (ProcessorType output : routeType.getOutputs()) {
208                    if (output instanceof ExceptionType) {
209                        exceptionHandlers.add(output);
210                    } else {
211                        outputs.add(output);
212                    }
213                }
214    
215                // clearing the outputs
216                routeType.clearOutput();
217    
218                // add exception handlers as top children
219                routeType.getOutputs().addAll(exceptionHandlers);
220    
221                // add an interceptor
222                InstrumentationProcessor processor = new InstrumentationProcessor();
223                routeType.intercept(processor);
224    
225                // add the output
226                for (ProcessorType<?> processorType : outputs) {
227                    routeType.addOutput(processorType);
228                }
229    
230                interceptorMap.put(endpoint, processor);
231            }
232    
233        }
234    
235        public CamelNamingStrategy getNamingStrategy() {
236            return namingStrategy;
237        }
238    
239        public void setNamingStrategy(CamelNamingStrategy strategy) {
240            this.namingStrategy = strategy;
241        }
242    
243        public void setAgent(InstrumentationAgent agent) {
244            this.agent = agent;
245        }
246    
247    }