Add RequestId and InvocationId to DR
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / LogServlet.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * *\r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * *\r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 \r
24 \r
25 package org.onap.dmaap.datarouter.provisioning;\r
26 \r
27 import java.io.IOException;\r
28 import java.sql.Connection;\r
29 import java.sql.ResultSet;\r
30 import java.sql.SQLException;\r
31 import java.sql.Statement;\r
32 import java.text.ParseException;\r
33 import java.text.SimpleDateFormat;\r
34 import java.util.Date;\r
35 import java.util.HashMap;\r
36 import java.util.Map;\r
37 \r
38 import javax.servlet.ServletOutputStream;\r
39 import javax.servlet.http.HttpServletRequest;\r
40 import javax.servlet.http.HttpServletResponse;\r
41 \r
42 import org.onap.dmaap.datarouter.provisioning.beans.DeliveryRecord;\r
43 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
44 import org.onap.dmaap.datarouter.provisioning.beans.ExpiryRecord;\r
45 import org.onap.dmaap.datarouter.provisioning.beans.LOGJSONable;\r
46 import org.onap.dmaap.datarouter.provisioning.beans.PublishRecord;\r
47 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;\r
48 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;\r
49 import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
50 import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;\r
51 \r
52 import com.att.eelf.configuration.EELFLogger;\r
53 import com.att.eelf.configuration.EELFManager;\r
54 \r
55 import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;\r
56 \r
57 /**\r
58  * This servlet handles requests to the <feedLogURL> and  <subLogURL>,\r
59  * which are generated by the provisioning server to handle the log query API.\r
60  *\r
61  * @author Robert Eby\r
62  * @version $Id: LogServlet.java,v 1.11 2014/03/28 17:27:02 eby Exp $\r
63  */\r
64 @SuppressWarnings("serial")\r
65 public class LogServlet extends BaseServlet {\r
66     //Adding EELF Logger Rally:US664892\r
67     private static EELFLogger eelflogger = EELFManager.getInstance().getLogger(LogServlet.class);\r
68     private static final long TWENTYFOUR_HOURS = (24 * 60 * 60 * 1000L);\r
69     private static final String FMT_1 = "yyyy-MM-dd'T'HH:mm:ss'Z'";\r
70     private static final String FMT_2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";\r
71 \r
72     private static  boolean isfeedlog;\r
73 \r
74     public abstract class RowHandler {\r
75         private final ServletOutputStream out;\r
76         private final String[] fields;\r
77         private boolean firstrow;\r
78 \r
79         public RowHandler(ServletOutputStream out, String fieldparam, boolean b) {\r
80             this.out = out;\r
81             this.firstrow = b;\r
82             this.fields = (fieldparam != null) ? fieldparam.split(":") : null;\r
83         }\r
84         public void handleRow(ResultSet rs) {\r
85             try {\r
86                 LOGJSONable js = buildJSONable(rs);\r
87                 LOGJSONObject jo = js.asJSONObject();\r
88                 if (fields != null) {\r
89                     // filter out unwanted fields\r
90                     LOGJSONObject j2 = new LOGJSONObject();\r
91                     for (String key : fields) {\r
92                         Object v = jo.opt(key);\r
93                         if (v != null)\r
94                             j2.put(key, v);\r
95                     }\r
96                     jo = j2;\r
97                 }\r
98                 String t = firstrow ? "\n" : ",\n";\r
99                 t += jo.toString();\r
100                 out.print(t);\r
101                 firstrow = false;\r
102             } catch (Exception exception) {\r
103                 intlogger.info("Failed to handle row. Exception = " + exception.getMessage(),exception);\r
104             }\r
105         }\r
106         public abstract LOGJSONable buildJSONable(ResultSet rs) throws SQLException;\r
107     }\r
108     public class PublishRecordRowHandler extends RowHandler {\r
109         public PublishRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
110             super(out, fields, b);\r
111         }\r
112         @Override\r
113         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
114             return new PublishRecord(rs);\r
115         }\r
116     }\r
117     public class DeliveryRecordRowHandler extends RowHandler {\r
118         public DeliveryRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
119             super(out, fields, b);\r
120         }\r
121         @Override\r
122         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
123             return new DeliveryRecord(rs);\r
124         }\r
125     }\r
126     public class ExpiryRecordRowHandler extends RowHandler {\r
127         public ExpiryRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
128             super(out, fields, b);\r
129         }\r
130         @Override\r
131         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
132             return new ExpiryRecord(rs);\r
133         }\r
134     }\r
135 \r
136     /**\r
137      * This class must be created from either a {@link FeedLogServlet} or a {@link SubLogServlet}.\r
138      * @param isFeedLog boolean to handle those places where a feedlog request is different from\r
139      * a sublog request\r
140      */\r
141     protected LogServlet(boolean isFeedLog) {\r
142         this.isfeedlog = isFeedLog;\r
143     }\r
144 \r
145     /**\r
146      * DELETE a logging URL -- not supported.\r
147      */\r
148     @Override\r
149     public void doDelete(HttpServletRequest req, HttpServletResponse resp) {\r
150         setIpFqdnRequestIDandInvocationIDForEelf("doDelete", req);\r
151         eelflogger.info(EelfMsgs.ENTRY);\r
152         try {\r
153             eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
154             String message = "DELETE not allowed for the logURL.";\r
155             EventLogRecord elr = new EventLogRecord(req);\r
156             elr.setMessage(message);\r
157             elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
158             eventlogger.info(elr);\r
159             sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
160         } finally {\r
161         eelflogger.info(EelfMsgs.EXIT);\r
162     }\r
163     }\r
164     /**\r
165      * GET a logging URL -- retrieve logging data for a feed or subscription.\r
166      * See the <b>Logging API</b> document for details on how this method should be invoked.\r
167      */\r
168     @Override\r
169     public void doGet(HttpServletRequest req, HttpServletResponse resp) {\r
170         setIpFqdnRequestIDandInvocationIDForEelf("doGet", req);\r
171         eelflogger.info(EelfMsgs.ENTRY);\r
172         try {\r
173             eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
174             int id = getIdFromPath(req);\r
175             if (id < 0) {\r
176                 sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Missing or bad feed/subscription number.", eventlogger);\r
177                 return;\r
178             }\r
179             Map<String, String> map = buildMapFromRequest(req);\r
180             if (map.get("err") != null) {\r
181                 sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid arguments: " + map.get("err"), eventlogger);\r
182                 return;\r
183             }\r
184             // check Accept: header??\r
185 \r
186             resp.setStatus(HttpServletResponse.SC_OK);\r
187             resp.setContentType(LOGLIST_CONTENT_TYPE);\r
188 \r
189             try (ServletOutputStream out = resp.getOutputStream()) {\r
190                 final String fields = req.getParameter("fields");\r
191 \r
192                 out.print("[");\r
193                 if (isfeedlog) {\r
194                     // Handle /feedlog/feedid request\r
195                     boolean firstrow = true;\r
196 \r
197                     // 1. Collect publish records for this feed\r
198                     RowHandler rh = new PublishRecordRowHandler(out, fields, firstrow);\r
199                     getPublishRecordsForFeed(id, rh, map);\r
200                     firstrow = rh.firstrow;\r
201 \r
202                     // 2. Collect delivery records for subscriptions to this feed\r
203                     rh = new DeliveryRecordRowHandler(out, fields, firstrow);\r
204                     getDeliveryRecordsForFeed(id, rh, map);\r
205                     firstrow = rh.firstrow;\r
206 \r
207                     // 3. Collect expiry records for subscriptions to this feed\r
208                     rh = new ExpiryRecordRowHandler(out, fields, firstrow);\r
209                     getExpiryRecordsForFeed(id, rh, map);\r
210                 } else {\r
211                     // Handle /sublog/subid request\r
212                     Subscription sub = Subscription.getSubscriptionById(id);\r
213                     if (sub != null) {\r
214                         // 1. Collect publish records for the feed this subscription feeds\r
215                         RowHandler rh = new PublishRecordRowHandler(out, fields, true);\r
216                         getPublishRecordsForFeed(sub.getFeedid(), rh, map);\r
217 \r
218                         // 2. Collect delivery records for this subscription\r
219                         rh = new DeliveryRecordRowHandler(out, fields, rh.firstrow);\r
220                         getDeliveryRecordsForSubscription(id, rh, map);\r
221 \r
222                         // 3. Collect expiry records for this subscription\r
223                         rh = new ExpiryRecordRowHandler(out, fields, rh.firstrow);\r
224                         getExpiryRecordsForSubscription(id, rh, map);\r
225                     }\r
226                 }\r
227                 out.print("]");\r
228             } catch (IOException ioe) {\r
229                 eventlogger.error("IOException: " + ioe.getMessage());\r
230             }\r
231         } finally {\r
232             eelflogger.info(EelfMsgs.EXIT);\r
233         }\r
234     }\r
235     /**\r
236      * PUT a logging URL -- not supported.\r
237      */\r
238     @Override\r
239     public void doPut(HttpServletRequest req, HttpServletResponse resp) {\r
240         setIpFqdnRequestIDandInvocationIDForEelf("doPut", req);\r
241         eelflogger.info(EelfMsgs.ENTRY);\r
242         try {\r
243         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
244         String message = "PUT not allowed for the logURL.";\r
245         EventLogRecord elr = new EventLogRecord(req);\r
246         elr.setMessage(message);\r
247         elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
248         eventlogger.info(elr);\r
249         sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
250         } finally {\r
251             eelflogger.info(EelfMsgs.EXIT);\r
252         }\r
253     }\r
254     /**\r
255      * POST a logging URL -- not supported.\r
256      */\r
257     @Override\r
258     public void doPost(HttpServletRequest req, HttpServletResponse resp) {\r
259         setIpFqdnRequestIDandInvocationIDForEelf("doPost", req);\r
260         eelflogger.info(EelfMsgs.ENTRY);\r
261         try {\r
262         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));\r
263         String message = "POST not allowed for the logURL.";\r
264         EventLogRecord elr = new EventLogRecord(req);\r
265         elr.setMessage(message);\r
266         elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
267         eventlogger.info(elr);\r
268         sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
269         } finally {\r
270             eelflogger.info(EelfMsgs.EXIT);\r
271         }\r
272     }\r
273 \r
274     private Map<String, String> buildMapFromRequest(HttpServletRequest req) {\r
275         Map<String, String> map = new HashMap<>();\r
276         String s = req.getParameter("type");\r
277         if (s != null) {\r
278             if (s.equals("pub") || s.equals("del") || s.equals("exp")) {\r
279                 map.put("type", s);\r
280             } else {\r
281                 map.put("err", "bad type");\r
282                 return map;\r
283             }\r
284         } else\r
285             map.put("type", "all");\r
286         map.put("publishSQL", "");\r
287         map.put("statusSQL", "");\r
288         map.put("resultSQL", "");\r
289         map.put("reasonSQL", "");\r
290 \r
291         s = req.getParameter("publishId");\r
292         if (s != null) {\r
293             if (s.indexOf("'") >= 0) {\r
294                 map.put("err", "bad publishId");\r
295                 return map;\r
296             }\r
297             map.put("publishSQL", " AND PUBLISH_ID = '"+s+"'");\r
298         }\r
299 \r
300         s = req.getParameter("statusCode");\r
301         if (s != null) {\r
302             String sql = null;\r
303             if (s.equals("success")) {\r
304                 sql = " AND STATUS >= 200 AND STATUS < 300";\r
305             } else if (s.equals("redirect")) {\r
306                 sql = " AND STATUS >= 300 AND STATUS < 400";\r
307             } else if (s.equals("failure")) {\r
308                 sql = " AND STATUS >= 400";\r
309             } else {\r
310                 try {\r
311                     Integer n = Integer.parseInt(s);\r
312                     if ((n >= 100 && n < 600) || (n == -1))\r
313                         sql = " AND STATUS = " + n;\r
314                 } catch (NumberFormatException e) {\r
315                 }\r
316             }\r
317             if (sql == null) {\r
318                 map.put("err", "bad statusCode");\r
319                 return map;\r
320             }\r
321             map.put("statusSQL", sql);\r
322             map.put("resultSQL", sql.replaceAll("STATUS", "RESULT"));\r
323         }\r
324 \r
325         s = req.getParameter("expiryReason");\r
326         if (s != null) {\r
327             map.put("type", "exp");\r
328             if (s.equals("notRetryable")) {\r
329                 map.put("reasonSQL", " AND REASON = 'notRetryable'");\r
330             } else if (s.equals("retriesExhausted")) {\r
331                 map.put("reasonSQL", " AND REASON = 'retriesExhausted'");\r
332             } else if (s.equals("diskFull")) {\r
333                 map.put("reasonSQL", " AND REASON = 'diskFull'");\r
334             } else if (s.equals("other")) {\r
335                 map.put("reasonSQL", " AND REASON = 'other'");\r
336             } else {\r
337                 map.put("err", "bad expiryReason");\r
338                 return map;\r
339             }\r
340         }\r
341 \r
342         long stime = getTimeFromParam(req.getParameter("start"));\r
343         if (stime < 0) {\r
344             map.put("err", "bad start");\r
345             return map;\r
346         }\r
347         long etime = getTimeFromParam(req.getParameter("end"));\r
348         if (etime < 0) {\r
349             map.put("err", "bad end");\r
350             return map;\r
351         }\r
352         if (stime == 0 && etime == 0) {\r
353             etime = System.currentTimeMillis();\r
354             stime = etime - TWENTYFOUR_HOURS;\r
355         } else if (stime == 0) {\r
356             stime = etime - TWENTYFOUR_HOURS;\r
357         } else if (etime == 0) {\r
358             etime = stime + TWENTYFOUR_HOURS;\r
359         }\r
360         map.put("timeSQL", String.format(" AND EVENT_TIME >= %d AND EVENT_TIME <= %d", stime, etime));\r
361         return map;\r
362     }\r
363     private long getTimeFromParam(final String s) {\r
364         if (s == null)\r
365             return 0;\r
366         try {\r
367             // First, look for an RFC 3339 date\r
368             String fmt = (s.indexOf('.') > 0) ? FMT_2 : FMT_1;\r
369             SimpleDateFormat sdf = new SimpleDateFormat(fmt);\r
370             Date d = sdf.parse(s);\r
371             return d.getTime();\r
372         } catch (ParseException parseException) {\r
373             intlogger.error("Exception in getting Time :- "+parseException.getMessage(),parseException);\r
374         }\r
375         try {\r
376             // Also allow a long (in ms); useful for testing\r
377             long n = Long.parseLong(s);\r
378             return n;\r
379         } catch (NumberFormatException numberFormatException) {\r
380             intlogger.error("Exception in getting Time :- "+numberFormatException.getMessage(),numberFormatException);\r
381         }\r
382         intlogger.info("Error parsing time="+s);\r
383         return -1;\r
384     }\r
385 \r
386     private void getPublishRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
387         String type = map.get("type");\r
388         if (type.equals("all") || type.equals("pub")) {\r
389             String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
390                 + " AND TYPE = 'pub'"\r
391                 + map.get("timeSQL") + map.get("publishSQL") + map.get("statusSQL");\r
392             getRecordsForSQL(sql, rh);\r
393         }\r
394     }\r
395     private void getDeliveryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
396         String type = map.get("type");\r
397         if (type.equals("all") || type.equals("del")) {\r
398             String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
399                 + " AND TYPE = 'del'"\r
400                 + map.get("timeSQL") + map.get("publishSQL") + map.get("resultSQL");\r
401             getRecordsForSQL(sql, rh);\r
402         }\r
403     }\r
404     private void getDeliveryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
405         String type = map.get("type");\r
406         if (type.equals("all") || type.equals("del")) {\r
407             String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
408                 + " AND TYPE = 'del'"\r
409                 + map.get("timeSQL") + map.get("publishSQL") + map.get("resultSQL");\r
410             getRecordsForSQL(sql, rh);\r
411         }\r
412     }\r
413     private void getExpiryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
414         String type = map.get("type");\r
415         if (type.equals("all") || type.equals("exp")) {\r
416             String st = map.get("statusSQL");\r
417             if (st == null || st.length() == 0) {\r
418                 String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
419                     + " AND TYPE = 'exp'"\r
420                     + map.get("timeSQL") + map.get("publishSQL") + map.get("reasonSQL");\r
421                 getRecordsForSQL(sql, rh);\r
422             }\r
423         }\r
424     }\r
425     private void getExpiryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
426         String type = map.get("type");\r
427         if (type.equals("all") || type.equals("exp")) {\r
428             String st = map.get("statusSQL");\r
429             if (st == null || st.length() == 0) {\r
430                 String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
431                     + " AND TYPE = 'exp'"\r
432                     + map.get("timeSQL") + map.get("publishSQL") + map.get("reasonSQL");\r
433                 getRecordsForSQL(sql, rh);\r
434             }\r
435         }\r
436     }\r
437     private void getRecordsForSQL(String sql, RowHandler rh) {\r
438         intlogger.debug(sql);\r
439         long start = System.currentTimeMillis();\r
440         DB db = new DB();\r
441         Connection conn = null;\r
442         try {\r
443             conn = db.getConnection();\r
444            try( Statement  stmt = conn.createStatement()){\r
445              try(ResultSet rs = stmt.executeQuery(sql)){\r
446                  while (rs.next()) {\r
447                      rh.handleRow(rs);\r
448                  }\r
449              }\r
450            }\r
451         } catch (SQLException sqlException) {\r
452             intlogger.info("Failed to get Records. Exception = " +sqlException.getMessage(),sqlException);\r
453         } finally {\r
454             if (conn != null)\r
455                 db.release(conn);\r
456         }\r
457         intlogger.debug("Time: " + (System.currentTimeMillis()-start) + " ms");\r
458     }\r
459 }\r