Refactor Prov DB handling
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / reports / DailyLatencyReport.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.reports;\r
26 \r
27 import java.io.FileNotFoundException;\r
28 import java.io.PrintWriter;\r
29 import java.sql.Connection;\r
30 import java.sql.PreparedStatement;\r
31 import java.sql.ResultSet;\r
32 import java.sql.SQLException;\r
33 import java.text.SimpleDateFormat;\r
34 import java.util.ArrayList;\r
35 import java.util.Date;\r
36 import java.util.HashMap;\r
37 import java.util.List;\r
38 import java.util.Map;\r
39 import java.util.TreeSet;\r
40 import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
41 \r
42 /**\r
43  * Generate a daily per feed latency report.  The report is a .csv file containing the following columns:\r
44  * <table>\r
45  * <tr><td>date</td><td>the date for this record</td></tr>\r
46  * <tr><td>feedid</td><td>the Feed ID for this record</td></tr>\r
47  * <tr><td>minsize</td><td>the minimum size of all files published on this feed and date</td></tr>\r
48  * <tr><td>maxsize</td><td>the maximum size of all files published on this feed and date</td></tr>\r
49  * <tr><td>avgsize</td><td>the average size of all files published on this feed and date</td></tr>\r
50  * <tr><td>minlat</td><td>the minimum latency in delivering this feed to all subscribers (in ms)</td></tr>\r
51  * <tr><td>maxlat</td><td>the maximum latency in delivering this feed to all subscribers (in ms)</td></tr>\r
52  * <tr><td>avglat</td><td>the average latency in delivering this feed to all subscribers (in ms)</td></tr>\r
53  * <tr><td>fanout</td><td>the average number of subscribers this feed was delivered to</td></tr>\r
54  * </table>\r
55  * <p>\r
56  * In the context of this report, latency is defined as the value\r
57  * <i>(D<sub>e</sub> - P<sub>s</sub>)</i>\r
58  * where:\r
59  * </p>\r
60  * <p>P<sub>s</sub> is the time that the publication of the file to the node starts.</p>\r
61  * <p>D<sub>e</sub> is the time that the delivery of the file to the subscriber ends.</p>\r
62  *\r
63  * @author Robert P. Eby\r
64  * @version $Id: DailyLatencyReport.java,v 1.2 2013/11/06 16:23:54 eby Exp $\r
65  */\r
66 public class DailyLatencyReport extends ReportBase {\r
67 \r
68     private class Job {\r
69         private long pubtime = 0;\r
70         private long clen = 0;\r
71         private List<Long> deltime = new ArrayList<>();\r
72         public long minLatency() {\r
73             long n = deltime.isEmpty() ? 0 : Long.MAX_VALUE;\r
74             for (Long l : deltime) {\r
75                 n = Math.min(n, l - pubtime);\r
76             }\r
77             return n;\r
78         }\r
79 \r
80         public long maxLatency() {\r
81             long n = 0;\r
82             for (Long l : deltime) {\r
83                 n = Math.max(n, l - pubtime);\r
84             }\r
85             return n;\r
86         }\r
87 \r
88         public long totalLatency() {\r
89             long n = 0;\r
90             for (Long l : deltime) {\r
91                 n += (l - pubtime);\r
92             }\r
93             return n;\r
94         }\r
95     }\r
96 \r
97     private class Counters {\r
98 \r
99         public final String date;\r
100         public final int feedid;\r
101         public final Map<String, Job> jobs;\r
102 \r
103         public Counters(String d, int fid) {\r
104             date = d;\r
105             feedid = fid;\r
106             jobs = new HashMap<>();\r
107         }\r
108 \r
109         public void addEvent(long etime, String type, String id, String fid, long clen) {\r
110             Job j = jobs.get(id);\r
111             if (j == null) {\r
112                 j = new Job();\r
113                 jobs.put(id, j);\r
114             }\r
115             if (type.equals("pub")) {\r
116                 j.pubtime = getPstart(id);\r
117                 j.clen = clen;\r
118             } else if (type.equals("del")) {\r
119                 j.deltime.add(etime);\r
120             }\r
121         }\r
122 \r
123         @Override\r
124         public String toString() {\r
125             long minsize = Long.MAX_VALUE, maxsize = 0, avgsize = 0;\r
126             long minl = Long.MAX_VALUE, maxl = 0;\r
127             long fanout = 0, totall = 0, totaln = 0;\r
128             for (Job j : jobs.values()) {\r
129                 minsize = Math.min(minsize, j.clen);\r
130                 maxsize = Math.max(maxsize, j.clen);\r
131                 avgsize += j.clen;\r
132                 minl = Math.min(minl, j.minLatency());\r
133                 maxl = Math.max(maxl, j.maxLatency());\r
134                 totall += j.totalLatency();\r
135                 totaln += j.deltime.size();\r
136                 fanout += j.deltime.size();\r
137             }\r
138             if (jobs.size() > 0) {\r
139                 avgsize /= jobs.size();\r
140                 fanout /= jobs.size();\r
141             }\r
142             long avgl = (totaln > 0) ? (totall / totaln) : 0;\r
143             return date + "," + feedid + "," + minsize + "," + maxsize + "," + avgsize + "," + minl + "," + maxl + ","\r
144                 + avgl + "," + fanout;\r
145         }\r
146     }\r
147 \r
148     private long getPstart(String t) {\r
149         if (t.indexOf('.') >= 0) {\r
150             t = t.substring(0, t.indexOf('.'));\r
151         }\r
152         return Long.parseLong(t);\r
153     }\r
154 \r
155     @Override\r
156     public void run() {\r
157         Map<String, Counters> map = new HashMap<>();\r
158         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");\r
159         long start = System.currentTimeMillis();\r
160         try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
161             PreparedStatement ps = conn.prepareStatement(\r
162                 "select EVENT_TIME, TYPE, PUBLISH_ID, FEED_FILEID, FEEDID, "\r
163                     + "CONTENT_LENGTH from LOG_RECORDS where EVENT_TIME >= ? and EVENT_TIME <= ?")) {\r
164             ps.setLong(1, from);\r
165             ps.setLong(2, to);\r
166             try (ResultSet rs = ps.executeQuery()) {\r
167                 while (rs.next()) {\r
168                     String id = rs.getString("PUBLISH_ID");\r
169                     int feed = rs.getInt("FEEDID");\r
170                     long etime = rs.getLong("EVENT_TIME");\r
171                     String type = rs.getString("TYPE");\r
172                     String fid = rs.getString("FEED_FILEID");\r
173                     long clen = rs.getLong("CONTENT_LENGTH");\r
174                     String date = sdf.format(new Date(getPstart(id)));\r
175                     String key = date + "," + feed;\r
176                     Counters c = map.get(key);\r
177                     if (c == null) {\r
178                         c = new Counters(date, feed);\r
179                         map.put(key, c);\r
180                     }\r
181                     c.addEvent(etime, type, id, fid, clen);\r
182                 }\r
183             }\r
184         } catch (SQLException e) {\r
185             logger.error("SQLException: " + e.getMessage());\r
186         }\r
187         logger.debug("Query time: " + (System.currentTimeMillis() - start) + " ms");\r
188         try (PrintWriter os = new PrintWriter(outfile)) {\r
189             os.println("date,feedid,minsize,maxsize,avgsize,minlat,maxlat,avglat,fanout");\r
190             for (String key : new TreeSet<>(map.keySet())) {\r
191                 Counters c = map.get(key);\r
192                 os.println(c.toString());\r
193             }\r
194         } catch (FileNotFoundException e) {\r
195             System.err.println("File cannot be written: " + outfile);\r
196             logger.error("FileNotFoundException: " + e.getMessage());\r
197         }\r
198     }\r
199 }\r