2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 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=========================================================
21 package org.onap.xacml.parser;
24 import java.io.FileInputStream;
25 import java.io.FileReader;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.LineNumberReader;
29 import java.io.RandomAccessFile;
30 import java.nio.charset.Charset;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.sql.Connection;
35 import java.sql.DriverManager;
36 import java.sql.PreparedStatement;
37 import java.sql.SQLException;
38 import java.text.Format;
39 import java.text.ParseException;
40 import java.text.SimpleDateFormat;
41 import java.util.Date;
42 import java.util.Properties;
43 import java.util.Timer;
44 import java.util.regex.Matcher;
45 import java.util.regex.Pattern;
46 import java.util.stream.Stream;
48 import org.apache.log4j.Logger;
49 import org.onap.policy.common.im.AdministrativeStateException;
50 import org.onap.policy.common.im.IntegrityMonitor;
51 import org.onap.policy.common.im.StandbyStatusException;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.xacml.parser.LogEntryObject.LOGTYPE;
56 * Parse log files and store the information in a H2 database.
60 public class ParseLog {
62 // only logging last line of each log file processed to the log4j log file defined by property - PARSERLOGPATH
63 private static final Logger log4jlogger = Logger.getLogger(ParseLog.class.getName());
66 private static org.onap.policy.common.logging.flexlogger.Logger logger = FlexLogger.getLogger(ParseLog.class.getName());
68 private static String system;
69 private static int lastNumberRead = 0;
70 private static int debuglastNumberRead = 0;
71 private static int errorlastNumberRead = 0;
72 private static String type;
73 private static long startFileSize;
74 private static long debugStartFileSize;
75 private static long errorStartFileSize;
76 private static String systemLogFile;
77 private static String logFile;
78 private static String debuglogFile;
79 private static String errorlogFile;
80 private static String JDBC_URL;
81 private static String JDBC_USER;
82 private static String JDBC_PASSWORD;
83 private static String JDBC_DRIVER;
84 private static int maxLength = 255; //Max length that is allowed in the DB table
85 private static String resourceName;
86 private static long sleepTimer = 50000;
87 static IntegrityMonitor im;
88 private static boolean isMissingLogFile;
89 //Default:Timer initial delay and the delay between in milliseconds before task is to be execute
90 private static int TIMER_DELAY_TIME = 1000;
91 //Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task executions
92 private static int CHECK_INTERVAL = 86400000; // run this clean up once a day
93 private static RandomAccessFile randomAccessFile;
94 private static String loggingProcess = "Error processing line in ";
95 private static int TIME_FRAME = 5;
96 private static String message =" value read in: ";
97 private static String lineFormat = "(\\r\\n|\\n)";
98 private static String lineRead = "-line-Read:";
99 private static String br= "<br />";
100 private static String last = "Last-";
101 private static String breakLoop = "break the loop.";
102 private static String dateFormat = "yyyy-MM-dd HH:mm:ss";
104 public static void main(String[] args) throws Exception {
106 Properties logProperties = getPropertiesValue("parserlog.properties");
108 if(logProperties == null || isMissingLogFile){
109 // missing the path of log file in the properties file, so stop the process
110 logger.error("logProperties is null or LOGPATH is missing in parserlog.properties, so stop the process.");
114 //trigger the cleanup systemLogDb timer
117 File fileLog = new File(systemLogFile);
119 im = IntegrityMonitor.getInstance(resourceName,logProperties );
121 startDebugLogParser(fileLog);
122 startErrorLogParser(fileLog);
123 startAPIRestLogParser(fileLog);
127 private static boolean processLine(Path debugfilePath, String dataFileName, int lastNmRead, LOGTYPE logType){
128 // log4jlogger must use .info
129 try(Stream<String> lines = Files.lines(debugfilePath, Charset.defaultCharset()).onClose(() -> log4jlogger.info(last+dataFileName+ lineRead + lastNmRead)).skip(lastNmRead)){
130 lines.forEachOrdered(line -> process(line, type, logType));
131 } catch (IOException e) {
132 logger.error(loggingProcess + dataFileName, e);
133 logger.error(breakLoop);
138 private static void processDebugLogParser(File debugfile, Path debugfilePath, String dataFileName){
140 Runnable runnable = new Runnable (){
141 boolean isStop = false;
144 if (debugfile.isFile()){
145 isStop = processLine(debugfilePath, dataFileName, debuglastNumberRead, LOGTYPE.DEBUG);
148 Thread.sleep(sleepTimer);
149 debugStartFileSize = countLines(debuglogFile);
150 } catch (Exception e) {
151 logger.error(loggingProcess + dataFileName, e);
152 logger.error(breakLoop);
155 logger.debug("File Line Count of debug.log: " + debugStartFileSize + message + debuglastNumberRead);
156 if (debugStartFileSize < debuglastNumberRead ){
157 logger.debug("Failed Rolled: set Last number read to 0");
158 debuglastNumberRead = 0;
164 Thread thread = new Thread(runnable);
168 private static void startDebugLogParser(File fileLog) throws IOException{
170 if(debuglogFile != null && !debuglogFile.isEmpty()){
172 // pull the last line number
173 String dataFileName = "debug.log";
174 String filesRead = pullLastLineRead(fileLog, dataFileName);
175 if (filesRead!= null){
176 filesRead = filesRead.replaceAll(lineFormat, br);
177 debuglastNumberRead= Integer.parseInt(filesRead.trim());
179 debuglastNumberRead = 0;
182 debugStartFileSize = countLines(debuglogFile);
183 if (debugStartFileSize < debuglastNumberRead ){
184 logger.error("Filed Rolled: set Last debug number read to 0");
185 debuglastNumberRead = 0;
188 isMissingLogFile = false;
189 Path debugfilePath = Paths.get(debuglogFile);
190 File debugfile = new File(debuglogFile);
191 debugStartFileSize = debugfile.length();
193 // start process debug.log file
194 processDebugLogParser(debugfile, debugfilePath, dataFileName);
199 private static void processErrorLogParser(File errorfile, Path errorfilePath, String dataFileName){
200 Runnable runnable = new Runnable (){
201 boolean isStop = false;
205 if (errorfile.isFile()){
206 isStop = processLine(errorfilePath, dataFileName, errorlastNumberRead, LOGTYPE.ERROR);
209 Thread.sleep(sleepTimer);
210 errorStartFileSize = countLines(errorlogFile);
211 } catch (Exception e) {
212 logger.error(loggingProcess + dataFileName, e);
213 logger.error(breakLoop);
217 logger.debug("File Line Count of error.log: " + errorStartFileSize + message + errorlastNumberRead);
218 if (errorStartFileSize < errorlastNumberRead ){
219 logger.debug("Failed Rolled: set Last error number read to 0");
220 errorlastNumberRead = 0;
226 Thread thread = new Thread(runnable);
230 private static void startErrorLogParser(File fileLog) throws IOException{
232 if(errorlogFile != null && !errorlogFile.isEmpty()){
234 // pull the last line number
235 String dataFileName = "error.log";
236 String filesRead = pullLastLineRead(fileLog, dataFileName);
237 if (filesRead!= null){
238 filesRead = filesRead.replaceAll(lineFormat, br);
239 errorlastNumberRead= Integer.parseInt(filesRead.trim());
241 errorlastNumberRead = 0;
244 errorStartFileSize = countLines(errorlogFile);
245 if (errorStartFileSize < errorlastNumberRead ){
246 logger.error("Filed Rolled: set Last error number read to 0");
247 errorlastNumberRead = 0;
250 isMissingLogFile = false;
251 Path errorfilePath = Paths.get(errorlogFile);
252 File errorfile = new File(errorlogFile);
253 errorStartFileSize = errorfile.length();
254 // start process error.log file
255 processErrorLogParser(errorfile, errorfilePath, dataFileName);
260 private static void processAPIRestLog(File file, Path filePath, String dataFileName){
262 Runnable runnable = new Runnable () {
263 boolean isStop = false;
268 isStop = processLine(filePath, dataFileName, lastNumberRead, LOGTYPE.INFO);
271 Thread.sleep(sleepTimer);
272 startFileSize = countLines(logFile);
273 } catch (Exception e) {
274 logger.error(loggingProcess + dataFileName, e);
275 logger.error(breakLoop);
279 logger.debug("File Line Count of " + dataFileName+": " + startFileSize + message + lastNumberRead);
280 if (startFileSize < lastNumberRead ){
281 logger.debug("Failed Rolled: set Last number read to 0");
288 Thread thread = new Thread(runnable);
292 private static void startAPIRestLogParser(File fileLog) throws IOException{
294 if(logFile != null && !logFile.isEmpty()){
296 // pull the last line number
297 String dataFileName = type.toLowerCase()+"-rest.log";
298 String filesRead = pullLastLineRead(fileLog, dataFileName);
299 if (filesRead!= null){
300 filesRead = filesRead.replaceAll(lineFormat, br);
301 lastNumberRead= Integer.parseInt(filesRead.trim());
305 startFileSize = countLines(logFile);
306 if (startFileSize < lastNumberRead ){
307 logger.error("Filed Rolled: set Last number read to 0");
311 isMissingLogFile = false;
312 Path filePath = Paths.get(logFile);
313 File file = new File(logFile);
314 startFileSize = file.length();
315 // start process pap/pdp-rest.log file
316 processAPIRestLog(file, filePath, dataFileName);
320 public static int countLines(String filename){
323 FileReader freader = new FileReader(filename);
324 LineNumberReader reader = new LineNumberReader(freader);
327 while ((line = reader.readLine()) != null) {
328 logger.debug("Reading the Logs"+line);
330 cnt = reader.getLineNumber();
331 logger.info("Line number:"+cnt);
342 public static String pullLastLineRead(File file, String dataFileName) throws IOException {
344 file.createNewFile();
347 randomAccessFile = new RandomAccessFile(file, "r");
348 StringBuilder builder = new StringBuilder();
349 long length = file.length();
350 logger.debug("dataFileName: " +dataFileName);
353 randomAccessFile.seek(length);
354 for(long seek = length; seek >= 0; --seek){
355 randomAccessFile.seek(seek);
356 char c = (char)randomAccessFile.read();
359 builder = builder.reverse();
360 logger.debug("builder.toString(): " +builder.toString());
361 if (builder.toString().contains(last+dataFileName+lineRead)){
362 String[] parseString = builder.toString().split(last+dataFileName+lineRead);
363 String returnValue = parseString[1].replace("\r", "");
364 return returnValue.trim();
366 builder = new StringBuilder();
374 private static LogEntryObject getDebugOutLogValue (String line, String type){
377 LogEntryObject logEntry = new LogEntryObject();
378 logEntry.setSystemType(type);
379 logEntry.setSystem(system);
380 String info1 = "||INFO||";
381 String info2 = "INFO:";
382 String error1 = "||ERROR||";
383 String error2 = "ERROR:";
385 if(line.contains(info1) || line.contains(error1) || line.contains(info2) || line.contains(error2)){
386 String[] splitString = null;
387 if(line.contains(info1) || line.contains(error1)){
388 splitString = line.split("[||]");
389 }else if(line.contains(info2)){
390 splitString = line.split(info2);
392 splitString = line.split(error2);
394 String dateString = splitString[0].substring(0, 19);
395 logEntry.setDescription(splitString[splitString.length-1]);
398 date = parseDate(dateString.replace("T", " "), dateFormat, false);
399 logEntry.setDate(date);
401 logEntry.setRemote(parseRemoteSystem(line));
402 if (line.contains(info2) || line.contains(info1)){
403 logEntry.setLogType(LOGTYPE.INFO);
405 logEntry.setLogType(LOGTYPE.ERROR);
414 private static LogEntryObject getRestAPIOutLogValue (String line, String type){
416 LogEntryObject logEntry = new LogEntryObject();
417 logEntry.setSystemType(type);
418 logEntry.setSystem(system);
419 String info3 = "INFO";
421 // from PDP/PAP rest log file below
422 if (line.contains(info3) && line.contains(")-")){
423 //parse out description
424 logEntry.setDescription(line.substring(line.indexOf(")-")+3));
426 date = parseDate(line, dateFormat, true);
427 logEntry.setDate(date);
429 logEntry.setRemote(parseRemoteSystem(line));
430 logEntry.setLogType(LOGTYPE.INFO);
438 private static LogEntryObject getInfoOutLogValue (String line, String type){
440 LogEntryObject logEntry = new LogEntryObject();
441 logEntry.setSystemType(type);
442 logEntry.setSystem(system);
443 String info3 = "INFO";
445 if (line.contains(info3) && line.contains("--- [")){
446 //parse out description
447 String temp = line.substring(line.indexOf("---")+1);
448 String[] split = temp.split(":");
450 logEntry.setDescription(split[1]);
453 date = parseDate(line, dateFormat, false);
454 logEntry.setDate(date);
457 logEntry.setRemote(parseRemoteSystem(line));
458 logEntry.setLogType(LOGTYPE.INFO);
466 private static LogEntryObject getSevereOutLogValue (String line, String type){
468 LogEntryObject logEntry = new LogEntryObject();
469 logEntry.setSystemType(type);
470 logEntry.setSystem(system);
471 if (line.contains("SEVERE") && line.contains("[main]")){
472 String[] splitString = line.split(" ");
473 StringBuilder description = new StringBuilder();
474 for (int i = 5; i < splitString.length; i++){
475 description.append(" " + splitString[i]);
478 logEntry.setDescription(description.toString());
480 date = parseDate(line, dateFormat, false);
481 logEntry.setDate(date);
482 logEntry.setLogType(LOGTYPE.SEVERE);
487 if (line.contains("ERROR") && line.contains(")-")){
488 //parse out description
489 StringBuilder description = new StringBuilder();
490 description.append(line.substring(line.indexOf(")-")+3));
492 date = parseDate(line, dateFormat, true);
493 logEntry.setDate(date);
494 logEntry.setDescription(description.toString());
496 logEntry.setRemote(parseRemoteSystem(line));
497 logEntry.setLogType(LOGTYPE.ERROR);
505 private static LogEntryObject getWarnOutLogValue (String line, String type){
507 LogEntryObject logEntry = new LogEntryObject();
508 logEntry.setSystemType(type);
509 logEntry.setSystem(system);
510 if (line.contains("WARN") && line.contains(")-")){
511 //parse out description
513 logEntry.setDescription(line.substring(line.indexOf(")-")+3));
516 date = parseDate(line, dateFormat, true);
517 logEntry.setDate(date);
520 logEntry.setRemote(parseRemoteSystem(line));
521 logEntry.setLogType(LOGTYPE.WARN);
526 if (line.contains("WARNING") && type =="PyPDP"){
527 String[] splitString = line.split(" ");
528 StringBuilder description = new StringBuilder();
530 for (int i = 5; i < splitString.length; i++){
531 description.append(" " + splitString[i]);
535 date = parseDate(line, dateFormat, false);
536 logEntry.setDate(date);
537 logEntry.setLogType(LOGTYPE.WARN);
538 logEntry.setDescription(description.toString());
545 public static LogEntryObject pullOutLogValues(String line, String type){
547 LogEntryObject logEntry = getDebugOutLogValue(line, type);
549 if(logEntry == null){
550 logEntry = getRestAPIOutLogValue(line, type);
552 if(logEntry == null){
553 logEntry = getInfoOutLogValue(line, type);
555 if(logEntry == null){
556 logEntry = getSevereOutLogValue(line, type);
558 if(logEntry == null){
559 logEntry = getWarnOutLogValue(line, type);
565 private static void dbClose(Connection conn) {
568 } catch (SQLException e) {
569 logger.error("Error closing DB Connection: " + e);
574 public static void process(String line, String type, LOGTYPE logFile) {
576 LogEntryObject returnLogValue = null;
579 im.startTransaction();
580 } catch (AdministrativeStateException e) {
581 logger.error("Error received" + e);
582 } catch (StandbyStatusException ex) {
583 logger.error("Error received" + ex);
586 returnLogValue = pullOutLogValues(line, type);
588 if(logFile.equals(LOGTYPE.DEBUG)){
589 debuglastNumberRead++;
590 }else if(logFile.equals(LOGTYPE.ERROR)){
591 errorlastNumberRead++;
592 }else if(logFile.equals(LOGTYPE.INFO)){
595 if (returnLogValue!=null){
596 writeDB(returnLogValue);
603 private static void writeDB(LogEntryObject returnLogValue) {
605 Connection conn = dbConnection(JDBC_DRIVER, JDBC_URL, JDBC_USER,JDBC_PASSWORD);
606 dbAccesss(conn, returnLogValue.getSystem(), returnLogValue.getDescription(),
607 returnLogValue.getDate(), returnLogValue.getRemote(),
608 returnLogValue.getSystemType(), returnLogValue.getLogType().toString());
612 private static Connection dbConnection(String driver, String jdbc, String user, String pass){
615 Class.forName(driver);
616 Connection conn = DriverManager.getConnection(jdbc, user, pass);
618 } catch ( Exception e) {
619 logger.error("Error connecting to DB: " + e);
623 private static void dbAccesss(Connection conn, String system, String description, Date date, String remote, String type, String logType) {
627 Format formatter = new SimpleDateFormat(dateFormat);
628 sdate = formatter.format(date);
629 logger.debug("DBAccesss : sdate : " + sdate);
631 logger.debug("DBAccesss : sdate is null");
634 //ensure the length of description is less than the maximumm db char length
635 if (description.length() > maxLength) {
636 description = description.substring(0, maxLength);
640 PreparedStatement prep = conn.prepareStatement("insert into SYSTEMLOGDB values (NULL, ?, ?, ?, ?, ?, ?);");
643 prep.setString(1, system);
644 prep.setString(2, description);
645 prep.setString(3, remote);
646 prep.setString(4, type);
647 prep.setString(5, sdate);
648 prep.setString(6, logType);
650 prep.executeUpdate();
653 } catch (SQLException e1) {
654 logger.error("Error trying to excute SQL Statment: " + e1);
658 public static Date parseDate(String dateline, String pattern, boolean singleSplit) {
661 String[] splitString = dateline.split(" ");
662 SimpleDateFormat formatter = new SimpleDateFormat(pattern);
665 returnDate = formatter.parse(dateline);
666 } catch (ParseException e) {
667 logger.error("Unable to parse date for line: " + dateline);
671 String tmpString = splitString[0] + " " + splitString[1];
673 returnDate = formatter.parse(tmpString);
674 } catch (ParseException e) {
675 logger.error("Unable to parse date for line: " + dateline);
684 public static String parseRemoteSystem(String line) {
686 if (line.contains("http") && !(line.contains("www.w3.org"))){
688 Pattern pattern = Pattern.compile("://(.+?)/");
689 Matcher remote = pattern.matcher(line);
692 return remote.group(1);
698 public static String[] getPaths(String logPath){
699 String[] oneFile = null;
700 if(logPath != null && !logPath.isEmpty()){
701 if(logPath.contains(";")){
702 return logPath.split(";");
704 oneFile = new String[1];
705 oneFile[0] = logPath;
712 private static void setCleanUpProperties(String cleanupInterval, String timeFrame){
713 if(cleanupInterval != null && !cleanupInterval.isEmpty()){
714 int intCheckInterval = Integer.parseInt(cleanupInterval);
715 if(intCheckInterval > 300000) {//must be longer than 5 minutes
716 CHECK_INTERVAL = intCheckInterval;
719 logger.debug("No value defined for CHECK_INTERVAL in parserlog.properties, so use its default value:" + CHECK_INTERVAL + " milliseconds");
722 if(timeFrame != null && !timeFrame.isEmpty()){
723 int intTimeFrame = Integer.parseInt(timeFrame);
724 if(intTimeFrame > 0){
725 TIME_FRAME = intTimeFrame;
728 logger.debug("No value defined for TIME_FRAME in parserlog.properties, so use its default value:" + TIME_FRAME + " days");
732 private static void setDebuglogFile(String fileName){
733 debuglogFile = fileName;
734 if(debuglogFile != null && !debuglogFile.isEmpty()){
735 debuglogFile = debuglogFile.trim();
741 private static void setErrorlogFile(String fileName){
742 errorlogFile = fileName;
743 if(errorlogFile != null && !errorlogFile.isEmpty()){
744 errorlogFile = errorlogFile.trim();
750 private static void setLogFileProperties(String[] splitString){
751 if(splitString != null){
752 for(int i=0; i < splitString.length; i++){
754 if(splitString[i].contains("debug")){
755 // get path of debug.log file
756 setDebuglogFile(splitString[i]);
757 }else if(splitString[i].contains("error")){
758 // get path of error.log file
759 setErrorlogFile(splitString[i]);
761 // get path of default file
762 logFile = splitString[i];
763 if(logFile != null && !logFile.isEmpty()){
764 logFile = logFile.trim();
773 public static Properties getPropertiesValue(String fileName) {
774 Properties config = new Properties();
775 Path file = Paths.get(fileName);
776 if (file.toFile().exists()) {
778 if (file.toString().endsWith(".properties")) {
781 in = new FileInputStream(file.toFile());
784 resourceName = config.getProperty("RESOURCE_NAME");
785 system = config.getProperty("SERVER");
786 type = config.getProperty("LOGTYPE");
787 systemLogFile = config.getProperty("PARSERLOGPATH");
788 String logFiles = config.getProperty("LOGPATH");
789 String cleanupInterval= config.getProperty("CHECK_INTERVAL");
790 String timeFrame = config.getProperty("TIME_FRAME");
792 setCleanUpProperties(cleanupInterval, timeFrame);
794 if(logFiles == null || logFiles.isEmpty()){
795 isMissingLogFile = true;
799 String[] splitString = getPaths(logFiles);
801 setLogFileProperties(splitString);
803 JDBC_URL = config.getProperty("JDBC_URL").replace("'", "");
804 JDBC_USER = config.getProperty("JDBC_USER");
805 JDBC_DRIVER = config.getProperty("JDBC_DRIVER");
806 JDBC_PASSWORD = config.getProperty("JDBC_PASSWORD");
809 } catch (IOException e) {
810 logger.error("Error porcessing Config file will be unable to create Health Check" + e);
812 logger.error("Error getPropertiesValue on TIME_FRAME", e);
813 logger.debug("Error getPropertiesValue on TIME_FRAME, so use its default value:" + TIME_FRAME + " days");
819 logger.debug("File doesn't exist in the specified Path " + file.toString());
824 public static Connection getDbConnection(){
825 return dbConnection(JDBC_DRIVER, JDBC_URL, JDBC_USER,JDBC_PASSWORD);
827 private static void startCleanUp(){
828 Connection conn = dbConnection(JDBC_DRIVER, JDBC_URL, JDBC_USER,JDBC_PASSWORD);
829 CleanUpSystemLogDB cleanUp = new CleanUpSystemLogDB(conn, TIME_FRAME);
830 Timer timer = new Timer(true);
831 timer.scheduleAtFixedRate(cleanUp, TIMER_DELAY_TIME, CHECK_INTERVAL);
832 logger.info("startCleanUp begins! : " + new Date());