Sonar fix too many method param
[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 long getWaitForFileProcessFailureTimer() {
61             return (600000L);
62         }
63
64         public double getFailureBackoff() {
65             return (2.0);
66         }
67
68         public long getMaxFailureTimer() {
69             return (150000L);
70         }
71
72         public long getExpirationTimer() {
73             return (604800000L);
74         }
75
76         public int getFairFileLimit() {
77             return (10000);
78         }
79
80         public long getFairTimeLimit() {
81             return (86400000);
82         }
83
84         public String getDestURL(DestInfo destinationInfo, String fileid) {
85             return (config.getEventLogUrl());
86         }
87
88         public void handleUnreachable(DestInfo destinationInfo) {
89         }
90
91         public boolean handleRedirection(DestInfo destinationInfo, String location, String fileid) {
92             return (false);
93         }
94
95         public boolean isFollowRedirects() {
96             return (false);
97         }
98
99         public String getFeedId(String subid) {
100             return (null);
101         }
102
103         private DeliveryQueue dq;
104
105         public Uploader() {
106             dq = new DeliveryQueue(this,
107                 new DestInfo.DestInfoBuilder().setName("LogUpload").setSpool(uploaddir).setSubid(null).setLogdata(null)
108                     .setUrl(null).setAuthuser(config.getMyName()).setAuthentication(config.getMyAuth())
109                     .setMetaonly(false).setUse100(false).setPrivilegedSubscriber(false).setFollowRedirects(false)
110                     .setDecompress(false).createDestInfo());
111             setDaemon(true);
112             setName("Log Uploader");
113             start();
114         }
115
116         private synchronized void snooze() {
117             try {
118                 wait(10000);
119             } catch (Exception e) {
120             }
121         }
122
123         private synchronized void poke() {
124             notify();
125         }
126
127         public void run() {
128             while (true) {
129                 scan();
130                 dq.run();
131                 snooze();
132             }
133         }
134
135         private void scan() {
136             long threshold = System.currentTimeMillis() - config.getLogRetention();
137             File dir = new File(logdir);
138             String[] fns = dir.list();
139             Arrays.sort(fns);
140             String lastqueued = "events-000000000000.log";
141             String curlog = StatusLog.getCurLogFile();
142             curlog = curlog.substring(curlog.lastIndexOf('/') + 1);
143             try {
144                 Writer w = new FileWriter(uploaddir + "/.meta");
145                 w.write("POST\tlogdata\nContent-Type\ttext/plain\n");
146                 w.close();
147                 BufferedReader br = new BufferedReader(new FileReader(uploaddir + "/.lastqueued"));
148                 lastqueued = br.readLine();
149                 br.close();
150             } catch (Exception e) {
151             }
152             for (String fn : fns) {
153                 if (!isnodelog.reset(fn).matches()) {
154                     if (!iseventlog.reset(fn).matches()) {
155                         continue;
156                     }
157                     if (lastqueued.compareTo(fn) < 0 && curlog.compareTo(fn) > 0) {
158                         lastqueued = fn;
159                         try {
160                             String pid = config.getPublishId();
161                             Files.createLink(Paths.get(uploaddir + "/" + pid), Paths.get(logdir + "/" + fn));
162                             Files.createLink(Paths.get(uploaddir + "/" + pid + ".M"), Paths.get(uploaddir + "/.meta"));
163                         } catch (Exception e) {
164                         }
165                     }
166                 }
167                 File f = new File(dir, fn);
168                 if (f.lastModified() < threshold) {
169                     f.delete();
170                 }
171             }
172             try (Writer w = new FileWriter(uploaddir + "/.lastqueued")) {
173                 (new File(uploaddir + "/.meta")).delete();
174                 w.write(lastqueued + "\n");
175             } catch (Exception e) {
176             }
177         }
178     }
179
180     /**
181      * Construct a log manager
182      * <p>
183      * The log manager will check for expired log files every 5 minutes at 20 seconds after the 5 minute boundary.
184      * (Actually, the interval is the event log rollover interval, which defaults to 5 minutes).
185      */
186     public LogManager(NodeConfigManager config) {
187         this.config = config;
188         try {
189             isnodelog = Pattern.compile("node\\.log\\.\\d{8}").matcher("");
190             iseventlog = Pattern.compile("events-\\d{12}\\.log").matcher("");
191         } catch (Exception e) {
192         }
193         logdir = config.getLogDir();
194         uploaddir = logdir + "/.spool";
195         (new File(uploaddir)).mkdirs();
196         long now = System.currentTimeMillis();
197         long intvl = StatusLog.parseInterval(config.getEventLogInterval(), 30000);
198         long when = now - now % intvl + intvl + 20000L;
199         config.getTimer().scheduleAtFixedRate(this, when - now, intvl);
200         worker = new Uploader();
201     }
202
203     /**
204      * Trigger check for expired log files and log files to upload
205      */
206     public void run() {
207         worker.poke();
208     }
209 }