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.openecomp.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.regex.Matcher;
44 import java.util.regex.Pattern;
45 import java.util.stream.Stream;
47 import org.apache.log4j.Logger;
48 import org.openecomp.policy.common.im.AdministrativeStateException;
49 import org.openecomp.policy.common.im.IntegrityMonitor;
50 import org.openecomp.policy.common.im.StandbyStatusException;
51 import org.openecomp.xacml.parser.LogEntryObject.LOGTYPE;
54 * Parse log files and store the information in a H2 database.
58 public class ParseLog {
60 private static final Logger logger = Logger.getLogger(ParseLog.class.getName());
62 private static String system;
63 private static int lastNumberRead = 0;
64 private static String type;
65 private static long startFileSize;
66 private static String systemLogFile;
67 private static String logFile;
69 private static String JDBC_URL;
70 private static String JDBC_USER;
71 private static String JDBC_PASSWORD = "";
72 private static String JDBC_DRIVER;
73 private static int maxLength = 255; //Max length that is allowed in the DB table
74 private static String resourceName;
75 private static long sleepTimer = 50000;
76 static IntegrityMonitor im;
78 private static RandomAccessFile randomAccessFile;
80 public static void main(String[] args) throws Exception {
82 Properties logProperties = getPropertiesValue("parserlog.properties");
83 Path filePath = Paths.get(logFile);
84 File file = new File(logFile);
85 File fileLog = new File(systemLogFile);
86 startFileSize = file.length();
88 im = IntegrityMonitor.getInstance(resourceName,logProperties );
90 logger.info("System: " + system );
91 logger.info("System type: " + type );
92 logger.info("Logging File: " + systemLogFile );
93 logger.info("log file: " + logFile);
94 logger.info("JDBC_URL: " + JDBC_URL);
95 logger.info("JDBC_DRIVER: " + JDBC_DRIVER);
97 String filesRead = PullLastLineRead(fileLog);
98 if (filesRead!= null){
99 filesRead = filesRead.replaceAll("(\\r\\n|\\n)", "<br />");
100 lastNumberRead= Integer.parseInt(filesRead.trim());
104 startFileSize = countLines(logFile);
105 logger.info("File Line Count: " + startFileSize + " value read in: " + lastNumberRead);
106 if (startFileSize < lastNumberRead ){
107 logger.error("Filed Rolled: set Last number read to 0");
110 Runnable runnable = new Runnable (){
115 try (Stream<String> lines = Files.lines(filePath, Charset.defaultCharset()).onClose(() -> logger.info("Last line Read: " + lastNumberRead)).skip(lastNumberRead)) {
117 lines.forEachOrdered(line -> process(line, type));
119 } catch (IOException e) {
120 logger.error("Error processing line in log file: " + e);
124 Thread.sleep(sleepTimer);
125 startFileSize = countLines(logFile);
126 } catch (InterruptedException | IOException e) {
127 logger.error("Error: " + e);
130 logger.info("File Line Count: " + startFileSize + " value read in: " + lastNumberRead);
131 if (startFileSize < lastNumberRead ){
132 logger.info("Failed Rolled: set Last number read to 0");
139 Thread thread = new Thread(runnable);
144 public static int countLines(String filename) throws IOException {
145 LineNumberReader reader = new LineNumberReader(new FileReader(filename));
147 while ((reader.readLine()) != null);
148 cnt = reader.getLineNumber();
153 public static String PullLastLineRead(File file) throws IOException {
155 file.createNewFile();
158 randomAccessFile = new RandomAccessFile(file, "r");
159 StringBuilder builder = new StringBuilder();
160 long length = file.length();
162 randomAccessFile.seek(length);
163 for(long seek = length; seek >= 0; --seek){
164 randomAccessFile.seek(seek);
165 char c = (char)randomAccessFile.read();
168 builder = builder.reverse();
169 if (builder.toString().contains("Last line Read:")){
170 String[] parseString = builder.toString().split("Last line Read:");
171 String returnValue = parseString[1].replace("\r", "");
172 return returnValue.trim();
175 builder = new StringBuilder();
182 public static LogEntryObject pullOutLogValues(String line, String type){
184 LogEntryObject logEntry = new LogEntryObject();
185 logEntry.setSystemType(type);
186 String description = null;
188 logEntry.setSystem(system);
190 //Values for PDP/PAP log file
191 if(line.contains("||INFO||") || line.contains("||ERROR||")){
192 String[] splitString = line.split("[||]");
193 String dateString = splitString[0].substring(0, 19);
194 logEntry.setDescription(splitString[splitString.length-1]);
197 date = parseDate(dateString.replace("T", " "), "yyyy-MM-dd HH:mm:ss", false);
198 logEntry.setDate(date);
200 logEntry.setRemote(parseRemoteSystem(line));
201 if (line.contains("||INFO||")){
202 logEntry.setLogType(LOGTYPE.INFO);
204 logEntry.setLogType(LOGTYPE.ERROR);
206 }else if (line.contains("INFO") && line.contains(")-")){
207 //parse out description
208 logEntry.setDescription(line.substring(line.indexOf(")-")+3));
210 date = parseDate(line, "yy_MM_dd_HH_mm_ss", true);
211 logEntry.setDate(date);
213 logEntry.setRemote(parseRemoteSystem(line));
214 logEntry.setLogType(LOGTYPE.INFO);
215 } else if (line.contains("INFO") && line.contains("--- [")){
216 //parse out description
217 String temp = line.substring(line.indexOf("---")+1);
218 String[] split = temp.split(":");
220 logEntry.setDescription(split[1]);
223 date = parseDate(line, "yyyy-MM-dd HH:mm:ss", false);
224 logEntry.setDate(date);
227 logEntry.setRemote(parseRemoteSystem(line));
228 logEntry.setLogType(LOGTYPE.INFO);
229 }else if (line.contains("SEVERE") && line.contains("[main]")){
230 String[] splitString = line.split(" ");
232 for (int i = 5; i < splitString.length; i++){
233 description = description + " " + splitString[i];
236 logEntry.setDescription(description);
238 date = parseDate(line, "dd-MMM-yyyy HH:mm:ss", false);
239 logEntry.setDate(date);
240 logEntry.setLogType(LOGTYPE.SEVERE);
241 } else if (line.contains("WARN") && line.contains(")-")){
242 //parse out description
244 logEntry.setDescription(line.substring(line.indexOf(")-")+3));
247 date = parseDate(line, "yy_MM_dd_HH_mm_ss", true);
248 logEntry.setDate(date);
251 logEntry.setRemote(parseRemoteSystem(line));
252 logEntry.setLogType(LOGTYPE.WARN);
253 }else if (line.contains("WARNING") && type =="PyPDP"){
254 String[] splitString = line.split(" ");
255 for (int i = 5; i < splitString.length; i++){
256 description = description + " " + splitString[i];
260 date = parseDate(line, "dd-MMM-yyyy HH:mm:ss", false);
261 logEntry.setDate(date);
262 logEntry.setLogType(LOGTYPE.WARN);
263 }else if (line.contains("ERROR") && line.contains(")-")){
264 //parse out description
265 description = line.substring(line.indexOf(")-")+3);
268 date = parseDate(line, "yy_MM_dd_HH_mm_ss", true);
269 logEntry.setDate(date);
271 logEntry.setRemote(parseRemoteSystem(line));
272 logEntry.setLogType(LOGTYPE.ERROR);
281 private static void DBClose(Connection conn) {
284 } catch (SQLException e) {
285 logger.error("Error closing DB Connection: " + e);
290 public static void process(String line, String type) {
291 LogEntryObject returnLogValue = null;
294 im.startTransaction();
295 } catch (AdministrativeStateException e) {
296 logger.error("Error received" + e);
298 } catch (StandbyStatusException e) {
299 logger.error("Error received" + e);
302 returnLogValue = pullOutLogValues(line, type);
304 if (returnLogValue!=null){
305 writeDB(returnLogValue);
312 private static void writeDB(LogEntryObject returnLogValue) {
313 Connection conn = DBConnection(JDBC_DRIVER, JDBC_URL, JDBC_USER,JDBC_PASSWORD);
314 DBAccesss(conn, returnLogValue.getSystem(), returnLogValue.getDescription(),
315 returnLogValue.getDate(), returnLogValue.getRemote(),
316 returnLogValue.getSystemType(), returnLogValue.getLogType().toString());
320 private static Connection DBConnection(String driver, String jdbc, String user, String pass){
323 Class.forName(driver);
324 Connection conn = DriverManager.getConnection(jdbc, user, pass);
326 } catch ( Exception e) {
327 logger.error("Error connecting to DB: " + e);
331 private static void DBAccesss(Connection conn, String system, String description, Date date, String remote, String type, String logType) {
336 Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
337 sdate = formatter.format(date);
340 //ensure the length of description is less than the maximumm db char length
341 if (description.length() > maxLength) {
342 description = description.substring(0, maxLength);
346 PreparedStatement prep = conn.prepareStatement("insert into SYSTEMLOGDB values (NULL, ?, ?, ?, ?, ?, ?);");
347 prep.setString(1, system);
348 prep.setString(2, description);
349 prep.setString(3, remote);
350 prep.setString(4, type);
351 prep.setString(5, sdate);
352 prep.setString(6, logType);
354 prep.executeUpdate();
357 } catch (SQLException e1) {
358 logger.error("Error trying to excute SQL Statment: " + e1);
362 public static Date parseDate(String dateline, String pattern, boolean singleSplit) {
365 String[] splitString = dateline.split(" ");
366 SimpleDateFormat formatter = new SimpleDateFormat(pattern);
369 returnDate = formatter.parse(splitString[0]);
370 } catch (ParseException e) {
371 logger.error("Unable to parse date for line: " + dateline);
375 String tmpString = splitString[0] + " " + splitString[1];
377 returnDate = formatter.parse(tmpString);
378 } catch (ParseException e) {
379 logger.error("Unable to parse date for line: " + dateline);
388 public static String parseRemoteSystem(String line) {
390 if (line.contains("http") && !(line.contains("www.w3.org"))){
392 Pattern pattern = Pattern.compile("://(.+?)/");
393 Matcher remote = pattern.matcher(line);
396 return remote.group(1);
402 public static Properties getPropertiesValue(String fileName) {
403 Properties config = new Properties();
404 Path file = Paths.get(fileName);
405 if (Files.notExists(file)) {
406 logger.info("File doesn't exist in the specified Path " + file.toString());
408 if (file.toString().endsWith(".properties")) {
411 in = new FileInputStream(file.toFile());
414 resourceName = config.getProperty("RESOURCE_NAME");
415 system = config.getProperty("SERVER");
416 type = config.getProperty("LOGTYPE");
417 systemLogFile = config.getProperty("PARSERLOGPATH");
418 logFile = config.getProperty("LOGPATH");
419 JDBC_URL = config.getProperty("JDBC_URL").replace("'", "");
420 JDBC_USER = config.getProperty("JDBC_USER");
421 JDBC_DRIVER = config.getProperty("JDBC_DRIVER");
422 JDBC_PASSWORD = config.getProperty("JDBC_PASSWORD");
425 } catch (IOException e) {
426 logger.info("Error porcessing Cofnig file will be unable to create Health Check");