1 /*******************************************************************************
2 * ============LICENSE_START==================================================
4 * * ===========================================================================
5 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
25 package org.onap.dmaap.datarouter.provisioning.utils;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
30 import java.io.FileInputStream;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.io.LineNumberReader;
35 import java.io.Reader;
36 import java.nio.file.Files;
37 import java.sql.Connection;
38 import java.sql.PreparedStatement;
39 import java.sql.ResultSet;
40 import java.sql.SQLException;
41 import java.sql.Statement;
42 import java.text.ParseException;
43 import java.util.Date;
44 import java.util.HashMap;
45 import java.util.Iterator;
47 import java.util.TreeSet;
48 import java.util.zip.GZIPInputStream;
49 import org.onap.dmaap.datarouter.provisioning.BaseServlet;
50 import org.onap.dmaap.datarouter.provisioning.beans.DeliveryExtraRecord;
51 import org.onap.dmaap.datarouter.provisioning.beans.DeliveryRecord;
52 import org.onap.dmaap.datarouter.provisioning.beans.ExpiryRecord;
53 import org.onap.dmaap.datarouter.provisioning.beans.Loadable;
54 import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
55 import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
56 import org.onap.dmaap.datarouter.provisioning.beans.PubFailRecord;
57 import org.onap.dmaap.datarouter.provisioning.beans.PublishRecord;
60 * This class provides methods that run in a separate thread, in order to process logfiles uploaded into the spooldir.
61 * These logfiles are loaded into the MariaDB LOG_RECORDS table. In a running provisioning server, there should only be
62 * two places where records can be loaded into this table; here, and in the method DB.retroFit4() which may be run at
63 * startup to load the old (1.0) style log tables into LOG_RECORDS;
64 * <p>This method maintains an {@link RLEBitSet} which can be used to easily see what records are presently in the
66 * This bit set is used to synchronize between provisioning servers.</p>
69 * @version $Id: LogfileLoader.java,v 1.22 2014/03/12 19:45:41 eby Exp $
71 public class LogfileLoader extends Thread {
73 * NOT USED: Percentage of free space required before old records are removed.
75 public static final int REQUIRED_FREE_PCT = 20;
78 * This is a singleton -- there is only one LogfileLoader object in the server.
80 private static LogfileLoader logfileLoader;
83 * The PreparedStatement which is loaded by a <i>Loadable</i>.
85 private static final String INSERT_SQL = "insert into LOG_RECORDS values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
87 * Each server can assign this many IDs.
89 private static final long SET_SIZE = (1L << 56);
91 private final EELFLogger logger;
93 private final String spooldir;
94 private final long setStart;
95 private final long setEnd;
96 private RLEBitSet seqSet;
101 * Get the singleton LogfileLoader object, and start it if it is not running.
103 * @return the LogfileLoader
105 public static synchronized LogfileLoader getLoader() {
106 if (logfileLoader == null) {
107 logfileLoader = new LogfileLoader();
109 if (!logfileLoader.isAlive()) {
110 logfileLoader.start();
112 return logfileLoader;
116 private LogfileLoader() {
117 this.logger = EELFManager.getInstance().getLogger("InternalLog");
119 this.spooldir = db.getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
120 this.setStart = getIdRange();
121 this.setEnd = setStart + SET_SIZE - 1;
122 this.seqSet = new RLEBitSet();
125 this.setDaemon(true);
126 this.setName("LogfileLoader");
129 private long getIdRange() {
131 if (BaseServlet.isInitialActivePOD()) {
133 } else if (BaseServlet.isInitialStandbyPOD()) {
138 String r = String.format("[%X .. %X]", n, n + SET_SIZE - 1);
139 logger.debug("This server shall assign RECORD_IDs in the range " + r);
144 * Return the bit set representing the record ID's that are loaded in this database.
146 * @return the bit set
148 public RLEBitSet getBitSet() {
153 * True if the LogfileLoader is currently waiting for work.
155 * @return true if idle
157 public boolean isIdle() {
162 * Run continuously to look for new logfiles in the spool directory and import them into the DB.
163 * The spool is checked once per second. If free space on the MariaDB filesystem falls below
164 * REQUIRED_FREE_PCT (normally 20%) then the oldest logfile entries are removed and the LOG_RECORDS
165 * table is compacted until free space rises above the threshold.
172 File dirfile = new File(spooldir);
174 runLogFileLoad(dirfile);
176 } catch (Exception e) {
177 logger.warn("PROV0020: Caught exception in LogfileLoader: " + e);
182 private void runLogFileLoad(File filesDir) {
183 File[] inFiles = filesDir.listFiles((dir, name) -> name.startsWith("IN."));
184 if (inFiles != null) {
185 if (inFiles.length == 0) {
189 } catch (InterruptedException e) {
190 Thread.currentThread().interrupt();
195 if (pruneRecords()) {
196 // Removed at least some entries, recompute the bit map
199 for (File file : inFiles) {
206 private void processFile(File infile) {
207 if (logger.isDebugEnabled()) {
208 logger.debug("PROV8001 Starting " + infile + " ...");
210 long time = System.currentTimeMillis();
211 int[] n = process(infile);
212 time = System.currentTimeMillis() - time;
213 logger.info(String.format("PROV8000 Processed %s in %d ms; %d of %d records.",
214 infile.toString(), time, n[0], n[1]));
216 Files.delete(infile.toPath());
217 } catch (IOException e) {
218 logger.info("PROV8001 failed to delete file " + infile.getName(), e);
222 boolean pruneRecords() {
223 boolean did1 = false;
224 long count = countRecords();
225 Parameters defaultLogRetention = Parameters.getParameter(Parameters.DEFAULT_LOG_RETENTION);
226 long threshold = (defaultLogRetention != null) ? Long.parseLong(defaultLogRetention.getValue()) : 1000000L;
227 Parameters provLogRetention = Parameters.getParameter(Parameters.PROV_LOG_RETENTION);
228 if (provLogRetention != null) {
230 long n = Long.parseLong(provLogRetention.getValue());
231 // This check is to prevent inadvertent errors from wiping the table out
235 } catch (NumberFormatException e) {
239 logger.debug("Pruning LOG_RECORD table: records in DB=" + count + ", threshold=" + threshold);
240 if (count > threshold) {
241 // we need to remove this many records
243 // histogram of records per day
244 Map<Long, Long> hist = getHistogram();
245 // Determine the cutoff point to remove the needed number of records
248 for (Long day : new TreeSet<>(hist.keySet())) {
249 sum += hist.get(day);
258 logger.debug(" Pruning records older than=" + (cutoff / 86400000L) + " (" + new Date(cutoff) + ")");
260 Connection conn = null;
262 // Limit to a million at a time to avoid typing up the DB for too long.
263 conn = db.getConnection();
264 try (PreparedStatement ps = conn.prepareStatement("DELETE from LOG_RECORDS where EVENT_TIME < ? limit 1000000")) {
265 ps.setLong(1, cutoff);
268 int dcount = ps.getUpdateCount();
270 logger.debug(" " + dcount + " rows deleted.");
271 did1 |= (dcount != 0);
273 count = 0; // prevent inf. loops
276 count = 0; // shouldn't happen!
280 try (Statement stmt = conn.createStatement()) {
281 stmt.execute("OPTIMIZE TABLE LOG_RECORDS");
283 } catch (SQLException e) {
284 logger.error(e.toString());
292 long countRecords() {
294 Connection conn = null;
296 conn = db.getConnection();
297 try (Statement stmt = conn.createStatement()) {
298 try (ResultSet rs = stmt.executeQuery("SELECT COUNT(*) as COUNT from LOG_RECORDS")) {
300 count = rs.getLong("COUNT");
304 } catch (SQLException e) {
305 logger.error(e.toString());
312 Map<Long, Long> getHistogram() {
313 Map<Long, Long> map = new HashMap<>();
314 Connection conn = null;
316 logger.debug(" LOG_RECORD table histogram...");
317 conn = db.getConnection();
318 try (Statement stmt = conn.createStatement()) {
319 try (ResultSet rs = stmt.executeQuery("SELECT FLOOR(EVENT_TIME/86400000) AS DAY, COUNT(*) AS COUNT FROM LOG_RECORDS GROUP BY DAY")) {
321 long day = rs.getLong("DAY");
322 long cnt = rs.getLong("COUNT");
324 logger.debug(" " + day + " " + cnt);
328 } catch (SQLException e) {
329 logger.error(e.toString());
336 private void initializeNextid() {
337 Connection conn = null;
339 conn = db.getConnection();
340 RLEBitSet nbs = new RLEBitSet();
341 try (Statement stmt = conn.createStatement()) {
342 // Build a bitset of all records in the LOG_RECORDS table
343 // We need to run this SELECT in stages, because otherwise we run out of memory!
344 final long stepsize = 6000000L;
345 boolean goAgain = true;
346 for (long i = 0; goAgain; i += stepsize) {
347 String sql = String.format("select RECORD_ID from LOG_RECORDS LIMIT %d,%d", i, stepsize);
348 try (ResultSet rs = stmt.executeQuery(sql)) {
351 long n = rs.getLong("RECORD_ID");
359 // Compare with the range for this server
360 // Determine the next ID for this set of record IDs
361 RLEBitSet tbs = (RLEBitSet) nbs.clone();
362 RLEBitSet idset = new RLEBitSet();
363 idset.set(setStart, setStart + SET_SIZE);
365 long t = tbs.length();
366 nextId = (t == 0) ? setStart : (t - 1);
367 if (nextId >= setStart + SET_SIZE) {
368 // Handle wraparound, when the IDs reach the end of our "range"
370 Iterator<Long[]> li = tbs.getRangeIterator();
371 while (li.hasNext()) {
375 tbs.clear(last[0], last[1] + 1);
377 nextId = (t == 0) ? setStart : (t - 1);
380 logger.debug(String.format("initializeNextid, next ID is %d (%x)", nextId, nextId));
381 } catch (SQLException e) {
382 logger.error(e.toString());
388 @SuppressWarnings("resource")
389 int[] process(File f) {
393 Connection conn = db.getConnection();
394 PreparedStatement ps = conn.prepareStatement(INSERT_SQL);
395 Reader r = f.getPath().endsWith(".gz")
396 ? new InputStreamReader(new GZIPInputStream(new FileInputStream(f)))
398 try (LineNumberReader in = new LineNumberReader(r)) {
400 while ((line = in.readLine()) != null) {
402 for (Loadable rec : buildRecords(line)) {
404 if (rec instanceof LogRecord) {
405 LogRecord lr = ((LogRecord) rec);
406 if (!seqSet.get(lr.getRecordId())) {
408 seqSet.set(lr.getRecordId());
410 logger.debug("Duplicate record ignored: " + lr.getRecordId());
413 if (++nextId > setEnd) {
416 ps.setLong(18, nextId);
420 ps.clearParameters();
423 } catch (SQLException e) {
424 logger.warn("PROV8003 Invalid value in record: " + line, e);
425 } catch (NumberFormatException e) {
426 logger.warn("PROV8004 Invalid number in record: " + line, e);
427 } catch (ParseException e) {
428 logger.warn("PROV8005 Invalid date in record: " + line, e);
429 } catch (Exception e) {
430 logger.warn("PROV8006 Invalid pattern in record: " + line, e);
437 } catch (SQLException | IOException e) {
438 logger.warn("PROV8007 Exception reading " + f + ": " + e);
440 return new int[]{ok, total};
443 Loadable[] buildRecords(String line) throws ParseException {
444 String[] pp = line.split("\\|");
445 if (pp != null && pp.length >= 7) {
446 String rtype = pp[1].toUpperCase();
447 if ("PUB".equals(rtype) && pp.length == 11) {
448 // Fields are: date|PUB|pubid|feedid|requrl|method|ctype|clen|srcip|user|status
449 return new Loadable[]{new PublishRecord(pp)};
451 if ("DEL".equals(rtype) && pp.length == 12) {
452 // Fields are: date|DEL|pubid|feedid|subid|requrl|method|ctype|clen|user|status|xpubid
453 String[] subs = pp[4].split("\\s+");
455 Loadable[] rv = new Loadable[subs.length];
456 for (int i = 0; i < subs.length; i++) {
457 // create a new record for each individual sub
459 rv[i] = new DeliveryRecord(pp);
464 if ("EXP".equals(rtype) && pp.length == 11) {
465 // Fields are: date|EXP|pubid|feedid|subid|requrl|method|ctype|clen|reason|attempts
466 ExpiryRecord e = new ExpiryRecord(pp);
467 if ("other".equals(e.getReason())) {
468 logger.info("Invalid reason '" + pp[9] + "' changed to 'other' for record: " + e.getPublishId());
470 return new Loadable[]{e};
472 if ("PBF".equals(rtype) && pp.length == 12) {
473 // Fields are: date|PBF|pubid|feedid|requrl|method|ctype|clen-expected|clen-received|srcip|user|error
474 return new Loadable[]{new PubFailRecord(pp)};
476 if ("DLX".equals(rtype) && pp.length == 7) {
477 // Fields are: date|DLX|pubid|feedid|subid|clen-tosend|clen-sent
478 return new Loadable[]{new DeliveryExtraRecord(pp)};
480 if ("LOG".equals(rtype) && (pp.length == 19 || pp.length == 20)) {
481 // Fields are: date|LOG|pubid|feedid|requrl|method|ctype|clen|type|feedFileid|remoteAddr|user|status|subid|fileid|result|attempts|reason|record_id
482 return new Loadable[]{new LogRecord(pp)};
485 logger.warn("PROV8002 bad record: " + line);
486 return new Loadable[0];
490 * The LogfileLoader can be run stand-alone by invoking the main() method of this class.
494 public static void main(String[] a) throws InterruptedException {
495 LogfileLoader.getLoader();
496 Thread.sleep(200000L);