1 /*******************************************************************************
\r
2 * ============LICENSE_START==================================================
\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
11 * * http://www.apache.org/licenses/LICENSE-2.0
\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
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
\r
22 ******************************************************************************/
\r
25 package org.onap.dmaap.datarouter.provisioning;
\r
27 import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;
\r
29 import com.att.eelf.configuration.EELFLogger;
\r
30 import com.att.eelf.configuration.EELFManager;
\r
31 import java.io.IOException;
\r
32 import java.sql.Connection;
\r
33 import java.sql.ResultSet;
\r
34 import java.sql.SQLException;
\r
35 import java.sql.Statement;
\r
36 import java.text.ParseException;
\r
37 import java.text.SimpleDateFormat;
\r
38 import java.util.Date;
\r
39 import java.util.HashMap;
\r
40 import java.util.Map;
\r
41 import javax.servlet.ServletOutputStream;
\r
42 import javax.servlet.http.HttpServletRequest;
\r
43 import javax.servlet.http.HttpServletResponse;
\r
45 import org.onap.dmaap.datarouter.provisioning.beans.DeliveryRecord;
\r
46 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;
\r
47 import org.onap.dmaap.datarouter.provisioning.beans.ExpiryRecord;
\r
48 import org.onap.dmaap.datarouter.provisioning.beans.LOGJSONable;
\r
49 import org.onap.dmaap.datarouter.provisioning.beans.PublishRecord;
\r
50 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
\r
51 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;
\r
52 import org.onap.dmaap.datarouter.provisioning.utils.DB;
\r
53 import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;
\r
60 * This servlet handles requests to the <feedLogURL> and <subLogURL>,
\r
61 * which are generated by the provisioning server to handle the log query API.
\r
63 * @author Robert Eby
\r
64 * @version $Id: LogServlet.java,v 1.11 2014/03/28 17:27:02 eby Exp $
\r
66 @SuppressWarnings("serial")
\r
68 public class LogServlet extends BaseServlet {
\r
69 //Adding EELF Logger Rally:US664892
\r
70 private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(LogServlet.class);
\r
71 private static final long TWENTYFOUR_HOURS = (24 * 60 * 60 * 1000L);
\r
72 private static final String FMT_1 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
\r
73 private static final String FMT_2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
\r
74 private static final String PUBLISHSQL = "publishSQL";
\r
75 private static final String STATUSSQL = "statusSQL";
\r
76 private static final String RESULTSQL = "resultSQL";
\r
77 private static final String FILENAMESQL = "filenameSQL";
\r
78 private static final String TIMESQL = "timeSQL";
\r
79 private static final String LOG_RECORDSSQL = "select * from LOG_RECORDS where FEEDID = ";
\r
81 private final boolean isfeedlog;
\r
83 public abstract class RowHandler {
\r
84 private final ServletOutputStream out;
\r
85 private final String[] fields;
\r
86 private boolean firstrow;
\r
90 * @param out ServletOutputStream
\r
91 * @param fieldparam String field
\r
92 * @param bool boolean
\r
94 public RowHandler(ServletOutputStream out, String fieldparam, boolean bool) {
\r
96 this.firstrow = bool;
\r
97 this.fields = (fieldparam != null) ? fieldparam.split(":") : null;
\r
101 * Handling row from DB.
\r
102 * @param rs DB Resultset
\r
104 public void handleRow(ResultSet rs) {
\r
106 LOGJSONable js = buildJSONable(rs);
\r
107 LOGJSONObject jo = js.asJSONObject();
\r
108 if (fields != null) {
\r
109 // filter out unwanted fields
\r
110 LOGJSONObject j2 = new LOGJSONObject();
\r
111 for (String key : fields) {
\r
112 Object val = jo.opt(key);
\r
119 String str = firstrow ? "\n" : ",\n";
\r
120 str += jo.toString();
\r
123 } catch (Exception exception) {
\r
124 intlogger.info("Failed to handle row. Exception = " + exception.getMessage(),exception);
\r
128 public abstract LOGJSONable buildJSONable(ResultSet rs) throws SQLException;
\r
131 public class PublishRecordRowHandler extends RowHandler {
\r
132 public PublishRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {
\r
133 super(out, fields, bool);
\r
137 public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {
\r
138 return new PublishRecord(rs);
\r
142 public class DeliveryRecordRowHandler extends RowHandler {
\r
143 public DeliveryRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {
\r
144 super(out, fields, bool);
\r
148 public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {
\r
149 return new DeliveryRecord(rs);
\r
153 public class ExpiryRecordRowHandler extends RowHandler {
\r
154 public ExpiryRecordRowHandler(ServletOutputStream out, String fields, boolean bool) {
\r
155 super(out, fields, bool);
\r
159 public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {
\r
160 return new ExpiryRecord(rs);
\r
165 * This class must be created from either a {@link FeedLogServlet} or a {@link SubLogServlet}.
\r
166 * @param isFeedLog boolean to handle those places where a feedlog request is different from
\r
169 protected LogServlet(boolean isFeedLog) {
\r
170 this.isfeedlog = isFeedLog;
\r
174 * DELETE a logging URL -- not supported.
\r
177 public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
\r
178 setIpFqdnRequestIDandInvocationIDForEelf("doDelete", req);
\r
179 eelfLogger.info(EelfMsgs.ENTRY);
\r
181 eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID,
\r
182 req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
\r
183 String message = "DELETE not allowed for the logURL.";
\r
184 EventLogRecord elr = new EventLogRecord(req);
\r
185 elr.setMessage(message);
\r
186 elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
\r
187 eventlogger.error(elr.toString());
\r
188 sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);
\r
190 eelfLogger.info(EelfMsgs.EXIT);
\r
195 * GET a logging URL -- retrieve logging data for a feed or subscription.
\r
196 * See the <b>Logging API</b> document for details on how this method should be invoked.
\r
199 public void doGet(HttpServletRequest req, HttpServletResponse resp) {
\r
200 setIpFqdnRequestIDandInvocationIDForEelf("doGet", req);
\r
201 eelfLogger.info(EelfMsgs.ENTRY);
\r
203 eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID,
\r
204 req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
\r
205 int id = getIdFromPath(req);
\r
207 sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST,
\r
208 "Missing or bad feed/subscription number.", eventlogger);
\r
211 Map<String, String> map = buildMapFromRequest(req);
\r
212 if (map.get("err") != null) {
\r
213 sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST,
\r
214 "Invalid arguments: " + map.get("err"), eventlogger);
\r
217 // check Accept: header??
\r
219 resp.setStatus(HttpServletResponse.SC_OK);
\r
220 resp.setContentType(LOGLIST_CONTENT_TYPE);
\r
222 try (ServletOutputStream out = resp.getOutputStream()) {
\r
223 final String fields = req.getParameter("fields");
\r
227 // Handle /feedlog/feedid request
\r
228 boolean firstrow = true;
\r
230 // 1. Collect publish records for this feed
\r
231 RowHandler rh = new PublishRecordRowHandler(out, fields, firstrow);
\r
232 getPublishRecordsForFeed(id, rh, map);
\r
233 firstrow = rh.firstrow;
\r
235 // 2. Collect delivery records for subscriptions to this feed
\r
236 rh = new DeliveryRecordRowHandler(out, fields, firstrow);
\r
237 getDeliveryRecordsForFeed(id, rh, map);
\r
238 firstrow = rh.firstrow;
\r
240 // 3. Collect expiry records for subscriptions to this feed
\r
241 rh = new ExpiryRecordRowHandler(out, fields, firstrow);
\r
242 getExpiryRecordsForFeed(id, rh, map);
\r
244 // Handle /sublog/subid request
\r
245 Subscription sub = Subscription.getSubscriptionById(id);
\r
247 // 1. Collect publish records for the feed this subscription feeds
\r
248 RowHandler rh = new PublishRecordRowHandler(out, fields, true);
\r
249 getPublishRecordsForFeed(sub.getFeedid(), rh, map);
\r
251 // 2. Collect delivery records for this subscription
\r
252 rh = new DeliveryRecordRowHandler(out, fields, rh.firstrow);
\r
253 getDeliveryRecordsForSubscription(id, rh, map);
\r
255 // 3. Collect expiry records for this subscription
\r
256 rh = new ExpiryRecordRowHandler(out, fields, rh.firstrow);
\r
257 getExpiryRecordsForSubscription(id, rh, map);
\r
261 } catch (IOException ioe) {
\r
262 eventlogger.error("PROV0141 LogServlet.doGet: " + ioe.getMessage(), ioe);
\r
265 eelfLogger.info(EelfMsgs.EXIT);
\r
270 * PUT a logging URL -- not supported.
\r
273 public void doPut(HttpServletRequest req, HttpServletResponse resp) {
\r
274 setIpFqdnRequestIDandInvocationIDForEelf("doPut", req);
\r
275 eelfLogger.info(EelfMsgs.ENTRY);
\r
277 eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID,
\r
278 req.getHeader(BEHALF_HEADER),getIdFromPath(req) + "");
\r
279 String message = "PUT not allowed for the logURL.";
\r
280 EventLogRecord elr = new EventLogRecord(req);
\r
281 elr.setMessage(message);
\r
282 elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
\r
283 eventlogger.error(elr.toString());
\r
284 sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);
\r
286 eelfLogger.info(EelfMsgs.EXIT);
\r
291 * POST a logging URL -- not supported.
\r
294 public void doPost(HttpServletRequest req, HttpServletResponse resp) {
\r
295 setIpFqdnRequestIDandInvocationIDForEelf("doPost", req);
\r
296 eelfLogger.info(EelfMsgs.ENTRY);
\r
298 eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
\r
299 String message = "POST not allowed for the logURL.";
\r
300 EventLogRecord elr = new EventLogRecord(req);
\r
301 elr.setMessage(message);
\r
302 elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
\r
303 eventlogger.error(elr.toString());
\r
304 sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);
\r
306 eelfLogger.info(EelfMsgs.EXIT);
\r
310 private Map<String, String> buildMapFromRequest(HttpServletRequest req) {
\r
311 Map<String, String> map = new HashMap<>();
\r
312 String str = req.getParameter("type");
\r
314 if ("pub".equals(str) || "del".equals(str) || "exp".equals(str)) {
\r
315 map.put("type", str);
\r
317 map.put("err", "bad type");
\r
321 map.put("type", "all");
\r
323 map.put(PUBLISHSQL, "");
\r
324 map.put(STATUSSQL, "");
\r
325 map.put(RESULTSQL, "");
\r
326 map.put(REASON_SQL, "");
\r
327 map.put(FILENAMESQL, "");
\r
329 str = req.getParameter("publishId");
\r
331 if (str.indexOf("'") >= 0) {
\r
332 map.put("err", "bad publishId");
\r
335 map.put(PUBLISHSQL, " AND PUBLISH_ID = '" + str + "'");
\r
338 str = req.getParameter("filename");
\r
340 map.put(FILENAMESQL, " AND FILENAME = '" + str + "'");
\r
343 str = req.getParameter("statusCode");
\r
348 sql = " AND STATUS >= 200 AND STATUS < 300";
\r
351 sql = " AND STATUS >= 300 AND STATUS < 400";
\r
354 sql = " AND STATUS >= 400";
\r
358 int statusCode = Integer.parseInt(str);
\r
359 if ((statusCode >= 100 && statusCode < 600) || (statusCode == -1)) {
\r
360 sql = " AND STATUS = " + statusCode;
\r
362 } catch (NumberFormatException e) {
\r
363 intlogger.error("Failed to parse input", e);
\r
368 map.put("err", "bad statusCode");
\r
371 map.put(STATUSSQL, sql);
\r
372 map.put(RESULTSQL, sql.replaceAll("STATUS", "RESULT"));
\r
375 str = req.getParameter("expiryReason");
\r
377 map.put("type", "exp");
\r
378 if ("notRetryable".equals(str)) {
\r
379 map.put(REASON_SQL, " AND REASON = 'notRetryable'");
\r
380 } else if ("retriesExhausted".equals(str)) {
\r
381 map.put(REASON_SQL, " AND REASON = 'retriesExhausted'");
\r
382 } else if ("diskFull".equals(str)) {
\r
383 map.put(REASON_SQL, " AND REASON = 'diskFull'");
\r
384 } else if ("other".equals(str)) {
\r
385 map.put(REASON_SQL, " AND REASON = 'other'");
\r
387 map.put("err", "bad expiryReason");
\r
392 long stime = getTimeFromParam(req.getParameter("start"));
\r
394 map.put("err", "bad start");
\r
397 long etime = getTimeFromParam(req.getParameter("end"));
\r
399 map.put("err", "bad end");
\r
402 if (stime == 0 && etime == 0) {
\r
403 etime = System.currentTimeMillis();
\r
404 stime = etime - TWENTYFOUR_HOURS;
\r
405 } else if (stime == 0) {
\r
406 stime = etime - TWENTYFOUR_HOURS;
\r
407 } else if (etime == 0) {
\r
408 etime = stime + TWENTYFOUR_HOURS;
\r
410 map.put(TIMESQL, String.format(" AND EVENT_TIME >= %d AND EVENT_TIME <= %d", stime, etime));
\r
414 private long getTimeFromParam(final String str) {
\r
419 // First, look for an RFC 3339 date
\r
420 String fmt = (str.indexOf('.') > 0) ? FMT_2 : FMT_1;
\r
421 SimpleDateFormat sdf = new SimpleDateFormat(fmt);
\r
422 Date date = sdf.parse(str);
\r
423 return date.getTime();
\r
424 } catch (ParseException parseException) {
\r
425 intlogger.error("Exception in getting Time :- " + parseException.getMessage(),parseException);
\r
428 // Also allow a long (in ms); useful for testing
\r
429 return Long.parseLong(str);
\r
430 } catch (NumberFormatException numberFormatException) {
\r
431 intlogger.error("Exception in getting Time :- " + numberFormatException.getMessage(),numberFormatException);
\r
433 intlogger.info("Error parsing time=" + str);
\r
437 private void getPublishRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {
\r
438 String type = map.get("type");
\r
439 if ("all".equals(type) || "pub".equals(type)) {
\r
440 String sql = LOG_RECORDSSQL + feedid
\r
441 + " AND TYPE = 'pub'"
\r
442 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(STATUSSQL) + map.get(FILENAMESQL);
\r
443 getRecordsForSQL(sql, rh);
\r
447 private void getDeliveryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {
\r
448 String type = map.get("type");
\r
449 if ("all".equals(type) || "del".equals(type)) {
\r
450 String sql = LOG_RECORDSSQL + feedid
\r
451 + " AND TYPE = 'del'"
\r
452 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);
\r
453 getRecordsForSQL(sql, rh);
\r
457 private void getDeliveryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {
\r
458 String type = map.get("type");
\r
459 if ("all".equals(type) || "del".equals(type)) {
\r
460 String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = " + subid
\r
461 + " AND TYPE = 'del'"
\r
462 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);
\r
463 getRecordsForSQL(sql, rh);
\r
467 private void getExpiryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {
\r
468 String type = map.get("type");
\r
469 if ("all".equals(type) || "exp".equals(type)) {
\r
470 String st = map.get(STATUSSQL);
\r
471 if (st == null || st.length() == 0) {
\r
472 String sql = LOG_RECORDSSQL + feedid
\r
473 + " AND TYPE = 'exp'"
\r
474 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);
\r
475 getRecordsForSQL(sql, rh);
\r
480 private void getExpiryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {
\r
481 String type = map.get("type");
\r
482 if ("all".equals(type) || "exp".equals(type)) {
\r
483 String st = map.get(STATUSSQL);
\r
484 if (st == null || st.length() == 0) {
\r
485 String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = " + subid
\r
486 + " AND TYPE = 'exp'"
\r
487 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);
\r
488 getRecordsForSQL(sql, rh);
\r
493 private void getRecordsForSQL(String sql, RowHandler rh) {
\r
494 intlogger.debug(sql);
\r
495 long start = System.currentTimeMillis();
\r
497 Connection conn = null;
\r
499 conn = db.getConnection();
\r
500 try (Statement stmt = conn.createStatement()) {
\r
501 try (ResultSet rs = stmt.executeQuery(sql)) {
\r
502 while (rs.next()) {
\r
507 } catch (SQLException sqlException) {
\r
508 intlogger.info("Failed to get Records. Exception = " + sqlException.getMessage(),sqlException);
\r
510 if (conn != null) {
\r
514 intlogger.debug("Time: " + (System.currentTimeMillis() - start) + " ms");
\r