2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2016 - 2017 AT&T
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
22 * Licensed to the Apache Software Foundation (ASF) under one or more
23 * contributor license agreements. See the NOTICE file distributed with
24 * this work for additional information regarding copyright ownership.
25 * The ASF licenses this file to You under the Apache License, Version 2.0
26 * (the "License"); you may not use this file except in compliance with
27 * the License. You may obtain a copy of the License at
29 * http://www.apache.org/licenses/LICENSE-2.0
31 * Unless required by applicable law or agreed to in writing, software
32 * distributed under the License is distributed on an "AS IS" BASIS,
33 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
34 * See the License for the specific language governing permissions and
35 * limitations under the License.
37 package org.apache.tomcat.jdbc.pool.interceptor;
39 import java.lang.management.ManagementFactory;
40 import java.util.Iterator;
43 import java.util.concurrent.ConcurrentHashMap;
44 import java.util.concurrent.atomic.AtomicLong;
46 import javax.management.InstanceAlreadyExistsException;
47 import javax.management.InstanceNotFoundException;
48 import javax.management.ListenerNotFoundException;
49 import javax.management.MBeanException;
50 import javax.management.MBeanNotificationInfo;
51 import javax.management.MBeanRegistrationException;
52 import javax.management.MalformedObjectNameException;
53 import javax.management.NotCompliantMBeanException;
54 import javax.management.Notification;
55 import javax.management.NotificationBroadcasterSupport;
56 import javax.management.NotificationEmitter;
57 import javax.management.NotificationFilter;
58 import javax.management.NotificationListener;
59 import javax.management.ObjectName;
60 import javax.management.RuntimeOperationsException;
61 import javax.management.openmbean.CompositeData;
62 import javax.management.openmbean.CompositeDataSupport;
63 import javax.management.openmbean.CompositeType;
64 import javax.management.openmbean.OpenDataException;
66 import org.apache.juli.logging.Log;
67 import org.apache.juli.logging.LogFactory;
68 import org.apache.tomcat.jdbc.pool.ConnectionPool;
69 import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorProperty;
70 import org.apache.tomcat.jdbc.pool.PooledConnection;
72 * Publishes data to JMX and provides notifications
73 * when failures happen.
76 public class SlowQueryReportJmx extends SlowQueryReport implements NotificationEmitter, SlowQueryReportJmxMBean{
77 public static final String SLOW_QUERY_NOTIFICATION = "SLOW QUERY";
78 public static final String FAILED_QUERY_NOTIFICATION = "FAILED QUERY";
80 public static final String objectNameAttribute = "objectName";
82 protected static volatile CompositeType SLOW_QUERY_TYPE;
84 private static final Log log = LogFactory.getLog(SlowQueryReportJmx.class);
87 protected static final ConcurrentHashMap<String,SlowQueryReportJmxMBean> mbeans =
88 new ConcurrentHashMap<>();
91 //==============================JMX STUFF========================
92 protected volatile NotificationBroadcasterSupport notifier = new NotificationBroadcasterSupport();
95 public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException {
96 notifier.addNotificationListener(listener, filter, handback);
101 public MBeanNotificationInfo[] getNotificationInfo() {
102 return notifier.getNotificationInfo();
106 public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
107 notifier.removeNotificationListener(listener);
112 public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException {
113 notifier.removeNotificationListener(listener, filter, handback);
118 //==============================JMX STUFF========================
120 protected String poolName = null;
122 protected static final AtomicLong notifySequence = new AtomicLong(0);
124 protected boolean notifyPool = true;
126 protected ConnectionPool pool = null;
128 protected static CompositeType getCompositeType() {
129 if (SLOW_QUERY_TYPE==null) {
131 SLOW_QUERY_TYPE = new CompositeType(
132 SlowQueryReportJmx.class.getName(),
133 "Composite data type for query statistics",
134 QueryStats.getFieldNames(),
135 QueryStats.getFieldDescriptions(),
136 QueryStats.getFieldTypes());
137 }catch (OpenDataException x) {
138 log.warn("Unable to initialize composite data type for JMX stats and notifications.",x);
141 return SLOW_QUERY_TYPE;
145 public void reset(ConnectionPool parent, PooledConnection con) {
146 super.reset(parent, con);
148 poolName = parent.getName();
156 public void poolClosed(ConnectionPool pool) {
157 this.poolName = pool.getName();
159 super.poolClosed(pool);
163 public void poolStarted(ConnectionPool pool) {
165 super.poolStarted(pool);
166 this.poolName = pool.getName();
170 protected String reportFailedQuery(String query, Object[] args, String name, long start, Throwable t) {
171 query = super.reportFailedQuery(query, args, name, start, t);
172 if (isLogFailed()) notifyJmx(query,FAILED_QUERY_NOTIFICATION);
176 protected void notifyJmx(String query, String type) {
178 long sequence = notifySequence.incrementAndGet();
180 if (isNotifyPool()) {
181 if (this.pool!=null && this.pool.getJmxPool()!=null) {
182 this.pool.getJmxPool().notify(type, query);
185 if (notifier!=null) {
186 Notification notification =
187 new Notification(type,
190 System.currentTimeMillis(),
193 notifier.sendNotification(notification);
196 } catch (RuntimeOperationsException e) {
197 if (log.isDebugEnabled()) {
198 log.debug("Unable to send failed query notification.",e);
204 protected String reportSlowQuery(String query, Object[] args, String name, long start, long delta) {
205 query = super.reportSlowQuery(query, args, name, start, delta);
206 if (isLogSlow()) notifyJmx(query,SLOW_QUERY_NOTIFICATION);
211 * JMX operation - return the names of all the pools
212 * @return - all the names of pools that we have stored data for
214 public String[] getPoolNames() {
215 Set<String> keys = perPoolStats.keySet();
216 return keys.toArray(new String[0]);
220 * JMX operation - return the name of the pool
221 * @return the name of the pool, unique within the JVM
223 public String getPoolName() {
228 public boolean isNotifyPool() {
232 public void setNotifyPool(boolean notifyPool) {
233 this.notifyPool = notifyPool;
237 * JMX operation - remove all stats for this connection pool
239 public void resetStats() {
240 ConcurrentHashMap<String,QueryStats> queries = perPoolStats.get(poolName);
242 Iterator<String> it = queries.keySet().iterator();
243 while (it.hasNext()) it.remove();
248 * JMX operation - returns all the queries we have collected.
249 * @return - the slow query report as composite data.
252 public CompositeData[] getSlowQueriesCD() throws OpenDataException {
253 CompositeDataSupport[] result = null;
254 ConcurrentHashMap<String,QueryStats> queries = perPoolStats.get(poolName);
256 Set<Map.Entry<String,QueryStats>> stats = queries.entrySet();
258 result = new CompositeDataSupport[stats.size()];
259 Iterator<Map.Entry<String,QueryStats>> it = stats.iterator();
261 while (it.hasNext()) {
262 Map.Entry<String,QueryStats> entry = it.next();
263 QueryStats qs = entry.getValue();
264 result[pos++] = qs.getCompositeData(getCompositeType());
271 protected void deregisterJmx() {
273 if (mbeans.remove(poolName)!=null) {
274 ObjectName oname = getObjectName(getClass(),poolName);
275 ManagementFactory.getPlatformMBeanServer().unregisterMBean(oname);
277 } catch (MBeanRegistrationException e) {
278 log.debug("Jmx deregistration failed.",e);
279 } catch (InstanceNotFoundException e) {
280 log.debug("Jmx deregistration failed.",e);
281 } catch (MalformedObjectNameException e) {
282 log.warn("Jmx deregistration failed.",e);
283 } catch (RuntimeOperationsException e) {
284 log.warn("Jmx deregistration failed.",e);
290 public ObjectName getObjectName(Class<?> clazz, String poolName) throws MalformedObjectNameException {
292 Map<String,InterceptorProperty> properties = getProperties();
293 if (properties != null && properties.containsKey(objectNameAttribute)) {
294 oname = new ObjectName(properties.get(objectNameAttribute).getValue());
296 oname = new ObjectName(ConnectionPool.POOL_JMX_TYPE_PREFIX+clazz.getName()+",name=" + poolName);
301 protected void registerJmx() {
303 //only if we notify the pool itself
304 if (isNotifyPool()) {
306 } else if (getCompositeType()!=null) {
307 ObjectName oname = getObjectName(getClass(),poolName);
308 if (mbeans.putIfAbsent(poolName, this)==null) {
309 ManagementFactory.getPlatformMBeanServer().registerMBean(this, oname);
312 log.warn(SlowQueryReport.class.getName()+ "- No JMX support, composite type was not found.");
314 } catch (MalformedObjectNameException e) {
315 log.error("Jmx registration failed, no JMX data will be exposed for the query stats.",e);
316 } catch (RuntimeOperationsException e) {
317 log.error("Jmx registration failed, no JMX data will be exposed for the query stats.",e);
318 } catch (MBeanException e) {
319 log.error("Jmx registration failed, no JMX data will be exposed for the query stats.",e);
320 } catch (InstanceAlreadyExistsException e) {
321 log.error("Jmx registration failed, no JMX data will be exposed for the query stats.",e);
322 } catch (NotCompliantMBeanException e) {
323 log.error("Jmx registration failed, no JMX data will be exposed for the query stats.",e);
328 public void setProperties(Map<String, InterceptorProperty> properties) {
329 super.setProperties(properties);
330 final String threshold = "notifyPool";
331 InterceptorProperty p1 = properties.get(threshold);
333 this.setNotifyPool(Boolean.parseBoolean(p1.getValue()));