[SDNC-5] Rebase sdnc-core
[sdnc/core.git] / dblib / common / src / main / java / org / apache / tomcat / jdbc / pool / interceptor / SlowQueryReportJmx.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openecomp
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 /*
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
28  *
29  *      http://www.apache.org/licenses/LICENSE-2.0
30  *
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.
36  */
37 package org.apache.tomcat.jdbc.pool.interceptor;
38
39 import java.lang.management.ManagementFactory;
40 import java.util.Iterator;
41 import java.util.Map;
42 import java.util.Set;
43 import java.util.concurrent.ConcurrentHashMap;
44 import java.util.concurrent.atomic.AtomicLong;
45
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;
65
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;
71 /**
72  * Publishes data to JMX and provides notifications
73  * when failures happen.
74  *
75  */
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";
79
80     public static final String objectNameAttribute = "objectName";
81
82     protected static volatile CompositeType SLOW_QUERY_TYPE;
83
84     private static final Log log = LogFactory.getLog(SlowQueryReportJmx.class);
85
86
87     protected static final ConcurrentHashMap<String,SlowQueryReportJmxMBean> mbeans =
88         new ConcurrentHashMap<>();
89
90
91     //==============================JMX STUFF========================
92     protected volatile NotificationBroadcasterSupport notifier = new NotificationBroadcasterSupport();
93
94     @Override
95     public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException {
96         notifier.addNotificationListener(listener, filter, handback);
97     }
98
99
100     @Override
101     public MBeanNotificationInfo[] getNotificationInfo() {
102         return notifier.getNotificationInfo();
103     }
104
105     @Override
106     public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
107         notifier.removeNotificationListener(listener);
108
109     }
110
111     @Override
112     public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException {
113         notifier.removeNotificationListener(listener, filter, handback);
114
115     }
116
117
118     //==============================JMX STUFF========================
119
120     protected String poolName = null;
121
122     protected static final AtomicLong notifySequence = new AtomicLong(0);
123
124     protected boolean notifyPool = true;
125
126     protected ConnectionPool pool = null;
127
128     protected static CompositeType getCompositeType() {
129         if (SLOW_QUERY_TYPE==null) {
130             try {
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);
139             }
140         }
141         return SLOW_QUERY_TYPE;
142     }
143
144     @Override
145     public void reset(ConnectionPool parent, PooledConnection con) {
146         super.reset(parent, con);
147         if (parent!=null) {
148             poolName = parent.getName();
149             pool = parent;
150             registerJmx();
151         }
152     }
153
154
155     @Override
156     public void poolClosed(ConnectionPool pool) {
157         this.poolName = pool.getName();
158         deregisterJmx();
159         super.poolClosed(pool);
160     }
161
162     @Override
163     public void poolStarted(ConnectionPool pool) {
164         this.pool = pool;
165         super.poolStarted(pool);
166         this.poolName = pool.getName();
167     }
168
169     @Override
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);
173         return query;
174     }
175
176     protected void notifyJmx(String query, String type) {
177         try {
178             long sequence = notifySequence.incrementAndGet();
179
180             if (isNotifyPool()) {
181                 if (this.pool!=null && this.pool.getJmxPool()!=null) {
182                     this.pool.getJmxPool().notify(type, query);
183                 }
184             } else {
185                 if (notifier!=null) {
186                     Notification notification =
187                         new Notification(type,
188                                          this,
189                                          sequence,
190                                          System.currentTimeMillis(),
191                                          query);
192
193                     notifier.sendNotification(notification);
194                 }
195             }
196         } catch (RuntimeOperationsException e) {
197             if (log.isDebugEnabled()) {
198                 log.debug("Unable to send failed query notification.",e);
199             }
200         }
201     }
202
203     @Override
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);
207         return query;
208     }
209
210     /**
211      * JMX operation - return the names of all the pools
212      * @return - all the names of pools that we have stored data for
213      */
214     public String[] getPoolNames() {
215         Set<String> keys = perPoolStats.keySet();
216         return keys.toArray(new String[0]);
217     }
218
219     /**
220      * JMX operation - return the name of the pool
221      * @return the name of the pool, unique within the JVM
222      */
223     public String getPoolName() {
224         return poolName;
225     }
226
227
228     public boolean isNotifyPool() {
229         return notifyPool;
230     }
231
232     public void setNotifyPool(boolean notifyPool) {
233         this.notifyPool = notifyPool;
234     }
235
236     /**
237      * JMX operation - remove all stats for this connection pool
238      */
239     public void resetStats() {
240         ConcurrentHashMap<String,QueryStats> queries = perPoolStats.get(poolName);
241         if (queries!=null) {
242             Iterator<String> it = queries.keySet().iterator();
243             while (it.hasNext()) it.remove();
244         }
245     }
246
247     /**
248      * JMX operation - returns all the queries we have collected.
249      * @return - the slow query report as composite data.
250      */
251     @Override
252     public CompositeData[] getSlowQueriesCD() throws OpenDataException {
253         CompositeDataSupport[] result = null;
254         ConcurrentHashMap<String,QueryStats> queries = perPoolStats.get(poolName);
255         if (queries!=null) {
256             Set<Map.Entry<String,QueryStats>> stats = queries.entrySet();
257             if (stats!=null) {
258                 result = new CompositeDataSupport[stats.size()];
259                 Iterator<Map.Entry<String,QueryStats>> it = stats.iterator();
260                 int pos = 0;
261                 while (it.hasNext()) {
262                     Map.Entry<String,QueryStats> entry = it.next();
263                     QueryStats qs = entry.getValue();
264                     result[pos++] = qs.getCompositeData(getCompositeType());
265                 }
266             }
267         }
268         return result;
269     }
270
271     protected void deregisterJmx() {
272         try {
273             if (mbeans.remove(poolName)!=null) {
274                 ObjectName oname = getObjectName(getClass(),poolName);
275                 ManagementFactory.getPlatformMBeanServer().unregisterMBean(oname);
276             }
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);
285         }
286
287     }
288
289
290     public ObjectName getObjectName(Class<?> clazz, String poolName) throws MalformedObjectNameException {
291         ObjectName oname;
292         Map<String,InterceptorProperty> properties = getProperties();
293         if (properties != null && properties.containsKey(objectNameAttribute)) {
294             oname = new ObjectName(properties.get(objectNameAttribute).getValue());
295         } else {
296             oname = new ObjectName(ConnectionPool.POOL_JMX_TYPE_PREFIX+clazz.getName()+",name=" + poolName);
297         }
298         return oname;
299     }
300
301     protected void registerJmx() {
302         try {
303             //only if we notify the pool itself
304             if (isNotifyPool()) {
305
306             } else if (getCompositeType()!=null) {
307                 ObjectName oname = getObjectName(getClass(),poolName);
308                 if (mbeans.putIfAbsent(poolName, this)==null) {
309                     ManagementFactory.getPlatformMBeanServer().registerMBean(this, oname);
310                 }
311             } else {
312                 log.warn(SlowQueryReport.class.getName()+ "- No JMX support, composite type was not found.");
313             }
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);
324         }
325     }
326
327     @Override
328     public void setProperties(Map<String, InterceptorProperty> properties) {
329         super.setProperties(properties);
330         final String threshold = "notifyPool";
331         InterceptorProperty p1 = properties.get(threshold);
332         if (p1!=null) {
333             this.setNotifyPool(Boolean.parseBoolean(p1.getValue()));
334         }
335     }
336
337
338 }