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