1 /*******************************************************************************
2 * ============LICENSE_START==================================================
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
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
24 package org.onap.dmaap.datarouter.node;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import java.io.BufferedReader;
30 import java.io.FileReader;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.nio.file.Files;
35 import java.nio.file.Paths;
36 import java.util.Arrays;
37 import java.util.TimerTask;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40 import org.jetbrains.annotations.NotNull;
43 * Cleanup of old log files.
45 * <p>Periodically scan the log directory for log files that are older than the log file retention interval, and delete
46 * them. In a future release, This class will also be responsible for uploading events logs to the log server to
47 * support the log query APIs.
50 public class LogManager extends TimerTask {
52 private static final String EXCEPTION = "Exception";
53 private EELFLogger logger = EELFManager.getInstance().getLogger(LogManager.class);
54 private NodeConfigManager config;
55 private Matcher isnodelog;
56 private Matcher iseventlog;
57 private Uploader worker;
58 private String uploaddir;
59 private String logdir;
62 * Construct a log manager
64 * <p>The log manager will check for expired log files every 5 minutes at 20 seconds after the 5 minute boundary.
65 * (Actually, the interval is the event log rollover interval, which defaults to 5 minutes).
67 public LogManager(NodeConfigManager config) {
70 isnodelog = Pattern.compile("node\\.log\\.\\d{8}").matcher("");
71 iseventlog = Pattern.compile("events-\\d{12}\\.log").matcher("");
72 } catch (Exception e) {
73 logger.error(EXCEPTION, e);
75 logdir = config.getLogDir();
76 uploaddir = logdir + "/.spool";
77 (new File(uploaddir)).mkdirs();
78 long now = System.currentTimeMillis();
79 long intvl = StatusLog.parseInterval(config.getEventLogInterval(), 30000);
80 long when = now - now % intvl + intvl + 20000L;
81 config.getTimer().scheduleAtFixedRate(this, when - now, intvl);
82 worker = new Uploader();
86 * Trigger check for expired log files and log files to upload.
92 public Uploader getWorker() {
96 class Uploader extends Thread implements DeliveryQueueHelper {
98 private static final String META = "/.meta";
99 private EELFLogger logger = EELFManager.getInstance().getLogger(Uploader.class);
100 private DeliveryQueue dq;
103 dq = new DeliveryQueue(this,
104 new DestInfoBuilder().setName("LogUpload").setSpool(uploaddir).setSubid(null).setLogdata(null)
105 .setUrl(null).setAuthuser(config.getMyName()).setAuthentication(config.getMyAuth())
106 .setMetaonly(false).setUse100(false).setPrivilegedSubscriber(false)
107 .setFollowRedirects(false)
108 .setDecompress(false).createDestInfo());
110 setName("Log Uploader");
114 public long getInitFailureTimer() {
118 public long getWaitForFileProcessFailureTimer() {
122 public double getFailureBackoff() {
126 public long getMaxFailureTimer() {
130 public long getExpirationTimer() {
134 public int getFairFileLimit() {
138 public long getFairTimeLimit() {
142 public String getDestURL(DestInfo destinationInfo, String fileid) {
143 return (config.getEventLogUrl());
146 public void handleUnreachable(DestInfo destinationInfo) {
147 throw new UnsupportedOperationException();
150 public boolean handleRedirection(DestInfo destinationInfo, String location, String fileid) {
154 public boolean isFollowRedirects() {
158 public String getFeedId(String subid) {
162 private synchronized void snooze() {
165 } catch (Exception e) {
166 logger.error(EXCEPTION, e);
170 private synchronized void poke() {
183 private void scan() {
184 long threshold = System.currentTimeMillis() - config.getLogRetention();
185 File dir = new File(logdir);
186 String[] fns = dir.list();
188 String lastqueued = "events-000000000000.log";
189 String curlog = StatusLog.getCurLogFile();
190 curlog = curlog.substring(curlog.lastIndexOf('/') + 1);
192 Writer writer = new FileWriter(uploaddir + META);
193 writer.write("POST\tlogdata\nContent-Type\ttext/plain\n");
195 BufferedReader br = new BufferedReader(new FileReader(uploaddir + "/.lastqueued"));
196 lastqueued = br.readLine();
198 } catch (Exception e) {
199 logger.error(EXCEPTION, e);
201 for (String fn : fns) {
202 if (!isnodelog.reset(fn).matches()) {
203 if (!iseventlog.reset(fn).matches()) {
206 lastqueued = setLastQueued(lastqueued, curlog, fn);
208 File file = new File(dir, fn);
209 if (file.lastModified() < threshold) {
211 Files.deleteIfExists(file.toPath());
212 } catch (IOException e) {
213 logger.error("Failed to delete file: " + file.getPath(), e);
217 try (Writer w = new FileWriter(uploaddir + "/.lastqueued")) {
218 Files.deleteIfExists(new File(uploaddir + META).toPath());
219 w.write(lastqueued + "\n");
220 } catch (Exception e) {
221 logger.error(EXCEPTION, e);
226 private String setLastQueued(String lastqueued, String curlog, String fn) {
227 if (lastqueued.compareTo(fn) < 0 && curlog.compareTo(fn) > 0) {
230 String pid = config.getPublishId();
231 Files.createLink(Paths.get(uploaddir + "/" + pid), Paths.get(logdir + "/" + fn));
232 Files.createLink(Paths.get(uploaddir + "/" + pid + ".M"), Paths.get(uploaddir + META));
233 } catch (Exception e) {
234 logger.error(EXCEPTION, e);