adding FILENAME value to LOG_RECORDS table.
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / LogManager.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
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
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
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====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23 package org.onap.dmaap.datarouter.node;
24
25 import java.io.BufferedReader;
26 import java.io.File;
27 import java.io.FileReader;
28 import java.io.FileWriter;
29 import java.io.Writer;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.util.Arrays;
33 import java.util.TimerTask;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36
37 /**
38  * Cleanup of old log files.
39  * <p>
40  * Periodically scan the log directory for log files that are older than the log file retention interval, and delete
41  * them.  In a future release, This class will also be responsible for uploading events logs to the log server to
42  * support the log query APIs.
43  */
44
45 public class LogManager extends TimerTask {
46
47     private NodeConfigManager config;
48     private Matcher isnodelog;
49     private Matcher iseventlog;
50     private Uploader worker;
51     private String uploaddir;
52     private String logdir;
53
54     private class Uploader extends Thread implements DeliveryQueueHelper {
55
56         public long getInitFailureTimer() {
57             return (10000L);
58         }
59
60         public double getFailureBackoff() {
61             return (2.0);
62         }
63
64         public long getMaxFailureTimer() {
65             return (150000L);
66         }
67
68         public long getExpirationTimer() {
69             return (604800000L);
70         }
71
72         public int getFairFileLimit() {
73             return (10000);
74         }
75
76         public long getFairTimeLimit() {
77             return (86400000);
78         }
79
80         public String getDestURL(DestInfo dest, String fileid) {
81             return (config.getEventLogUrl());
82         }
83
84         public void handleUnreachable(DestInfo dest) {
85         }
86
87         public boolean handleRedirection(DestInfo dest, String location, String fileid) {
88             return (false);
89         }
90
91         public boolean isFollowRedirects() {
92             return (false);
93         }
94
95         public String getFeedId(String subid) {
96             return (null);
97         }
98
99         private DeliveryQueue dq;
100
101         public Uploader() {
102             dq = new DeliveryQueue(this,
103                 new DestInfo("LogUpload", uploaddir, null, null, null, config.getMyName(), config.getMyAuth(), false,
104                     false));
105             setDaemon(true);
106             setName("Log Uploader");
107             start();
108         }
109
110         private synchronized void snooze() {
111             try {
112                 wait(10000);
113             } catch (Exception e) {
114             }
115         }
116
117         private synchronized void poke() {
118             notify();
119         }
120
121         public void run() {
122             while (true) {
123                 scan();
124                 dq.run();
125                 snooze();
126             }
127         }
128
129         private void scan() {
130             long threshold = System.currentTimeMillis() - config.getLogRetention();
131             File dir = new File(logdir);
132             String[] fns = dir.list();
133             Arrays.sort(fns);
134             String lastqueued = "events-000000000000.log";
135             String curlog = StatusLog.getCurLogFile();
136             curlog = curlog.substring(curlog.lastIndexOf('/') + 1);
137             try {
138                 Writer w = new FileWriter(uploaddir + "/.meta");
139                 w.write("POST\tlogdata\nContent-Type\ttext/plain\n");
140                 w.close();
141                 BufferedReader br = new BufferedReader(new FileReader(uploaddir + "/.lastqueued"));
142                 lastqueued = br.readLine();
143                 br.close();
144             } catch (Exception e) {
145             }
146             for (String fn : fns) {
147                 if (!isnodelog.reset(fn).matches()) {
148                     if (!iseventlog.reset(fn).matches()) {
149                         continue;
150                     }
151                     if (lastqueued.compareTo(fn) < 0 && curlog.compareTo(fn) > 0) {
152                         lastqueued = fn;
153                         try {
154                             String pid = config.getPublishId();
155                             Files.createLink(Paths.get(uploaddir + "/" + pid), Paths.get(logdir + "/" + fn));
156                             Files.createLink(Paths.get(uploaddir + "/" + pid + ".M"), Paths.get(uploaddir + "/.meta"));
157                         } catch (Exception e) {
158                         }
159                     }
160                 }
161                 File f = new File(dir, fn);
162                 if (f.lastModified() < threshold) {
163                     f.delete();
164                 }
165             }
166             try (Writer w = new FileWriter(uploaddir + "/.lastqueued")) {
167                 (new File(uploaddir + "/.meta")).delete();
168                 w.write(lastqueued + "\n");
169             } catch (Exception e) {
170             }
171         }
172     }
173
174     /**
175      * Construct a log manager
176      * <p>
177      * The log manager will check for expired log files every 5 minutes at 20 seconds after the 5 minute boundary.
178      * (Actually, the interval is the event log rollover interval, which defaults to 5 minutes).
179      */
180     public LogManager(NodeConfigManager config) {
181         this.config = config;
182         try {
183             isnodelog = Pattern.compile("node\\.log\\.\\d{8}").matcher("");
184             iseventlog = Pattern.compile("events-\\d{12}\\.log").matcher("");
185         } catch (Exception e) {
186         }
187         logdir = config.getLogDir();
188         uploaddir = logdir + "/.spool";
189         (new File(uploaddir)).mkdirs();
190         long now = System.currentTimeMillis();
191         long intvl = StatusLog.parseInterval(config.getEventLogInterval(), 30000);
192         long when = now - now % intvl + intvl + 20000L;
193         config.getTimer().scheduleAtFixedRate(this, when - now, intvl);
194         worker = new Uploader();
195     }
196
197     /**
198      * Trigger check for expired log files and log files to upload
199      */
200     public void run() {
201         worker.poke();
202     }
203 }