More bug fix and refactoring
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / Delivery.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.File;
29 import java.io.IOException;
30 import java.nio.file.Files;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.HashMap;
34 import java.util.Objects;
35
36 /**
37  * Main control point for delivering files to destinations.
38  *
39  * <p>The Delivery class manages assignment of delivery threads to delivery queues and creation and destruction of
40  * delivery queues as configuration changes. DeliveryQueues are assigned threads based on a modified round-robin
41  * approach giving priority to queues with more work as measured by both bytes to deliver and files to deliver and lower
42  * priority to queues that already have delivery threads working. A delivery thread continues to work for a delivery
43  * queue as long as that queue has more files to deliver.
44  */
45 public class Delivery {
46
47     private static final String TOTAL = " total=";
48     private static final String YELLOW = " yellow=";
49     private static EELFLogger logger = EELFManager.getInstance().getLogger(Delivery.class);
50     private double fdstart;
51     private double fdstop;
52     private int threads;
53     private int curthreads;
54     private NodeConfigManager config;
55     private HashMap<String, DeliveryQueue> dqs = new HashMap<>();
56     private DeliveryQueue[] queues = new DeliveryQueue[0];
57     private int qpos = 0;
58     private long nextcheck;
59
60     /**
61      * Constructs a new Delivery system using the specified configuration manager.
62      *
63      * @param config The configuration manager for this delivery system.
64      */
65     public Delivery(NodeConfigManager config) {
66         this.config = config;
67         Runnable cmon = this::checkconfig;
68         config.registerConfigTask(cmon);
69     }
70
71     /**
72      * Reset the retry timer for a delivery queue.
73      */
74     public synchronized void resetQueue(String spool) {
75         if (spool != null) {
76             DeliveryQueue dq = dqs.get(spool);
77             if (dq != null) {
78                 dq.resetQueue();
79             }
80         }
81     }
82
83     /**
84      * Mark the task in spool a success.
85      */
86     public synchronized boolean markTaskSuccess(String spool, String pubId) {
87         boolean succeeded = false;
88         if (spool != null) {
89             DeliveryQueue dq = dqs.get(spool);
90             if (dq != null) {
91                 succeeded = dq.markTaskSuccess(pubId);
92             }
93         }
94         return succeeded;
95     }
96
97     private void cleardir(String dir) {
98         if (dqs.get(dir) != null) {
99             return;
100         }
101         File fdir = new File(dir);
102         try {
103             for (File junk : fdir.listFiles()) {
104                 if (junk.isFile()) {
105                     Files.delete(fdir.toPath());
106                 }
107             }
108             Files.delete(fdir.toPath());
109         } catch (IOException e) {
110             logger.error("Failed to delete file: " + fdir.getPath(), e);
111         }
112     }
113
114     private void freeDiskCheck() {
115         File spoolfile = new File(config.getSpoolBase());
116         long tspace = spoolfile.getTotalSpace();
117         long start = (long) (tspace * fdstart);
118         long cur = spoolfile.getUsableSpace();
119         if (cur >= start) {
120             return;
121         }
122         ArrayList<DelItem> cv = new ArrayList<>();
123         for (String sdir : dqs.keySet()) {
124             for (String meta : (new File(sdir)).list()) {
125                 if (!meta.endsWith(".M") || meta.charAt(0) == '.') {
126                     continue;
127                 }
128                 cv.add(new DelItem(meta.substring(0, meta.length() - 2), sdir));
129             }
130         }
131         DelItem[] items = cv.toArray(new DelItem[cv.size()]);
132         Arrays.sort(items);
133         long stop = (long) (tspace * fdstop);
134         logger.warn(
135             "NODE0501 Free disk space below red threshold.  current=" + cur + " red=" + start + TOTAL + tspace);
136         if (determineFreeDiskSpace(spoolfile, tspace, stop, cur, items)) {
137             return;
138         }
139         cur = spoolfile.getUsableSpace();
140         if (cur >= stop) {
141             logger.warn("NODE0503 Free disk space at or above yellow threshold.  current=" + cur + YELLOW + stop
142                 + TOTAL + tspace);
143             return;
144         }
145         logger.warn(
146             "NODE0504 Unable to recover sufficient disk space to reach green status.  current=" + cur + YELLOW
147                 + stop + TOTAL + tspace);
148     }
149
150     private void cleardirs() {
151         String basedir = config.getSpoolBase();
152         String nbase = basedir + "/n";
153         for (String nodedir : (new File(nbase)).list()) {
154             if (!nodedir.startsWith(".")) {
155                 cleardir(nbase + "/" + nodedir);
156             }
157         }
158         String sxbase = basedir + "/s";
159         for (String sxdir : (new File(sxbase)).list()) {
160             if (sxdir.startsWith(".")) {
161                 continue;
162             }
163             File sxf = new File(sxbase + "/" + sxdir);
164             for (String sdir : sxf.list()) {
165                 if (!sdir.startsWith(".")) {
166                     cleardir(sxbase + "/" + sxdir + "/" + sdir);
167                 }
168             }
169             try {
170                 if (sxf.list().length == 0) {
171                     Files.delete(sxf.toPath());  // won't if anything still in it
172                 }
173             } catch (IOException e) {
174                 logger.error("Failed to delete file: " + sxf.getPath(), e);
175             }
176         }
177     }
178
179     private synchronized void checkconfig() {
180         if (!config.isConfigured()) {
181             return;
182         }
183         fdstart = config.getFreeDiskStart();
184         fdstop = config.getFreeDiskStop();
185         threads = config.getDeliveryThreads();
186         if (threads < 1) {
187             threads = 1;
188         }
189         DestInfo[] alldis = config.getAllDests();
190         DeliveryQueue[] nqs = new DeliveryQueue[alldis.length];
191         qpos = 0;
192         HashMap<String, DeliveryQueue> ndqs = new HashMap<>();
193         for (DestInfo di : alldis) {
194             String spl = di.getSpool();
195             DeliveryQueue dq = dqs.get(spl);
196             if (dq == null) {
197                 dq = new DeliveryQueue(config, di);
198             } else {
199                 dq.config(di);
200             }
201             ndqs.put(spl, dq);
202             nqs[qpos++] = dq;
203         }
204         queues = nqs;
205         dqs = ndqs;
206         cleardirs();
207         while (curthreads < threads) {
208             curthreads++;
209             (new Thread("del-thread-" + curthreads) {
210                 @Override
211                 public void run() {
212                     dodelivery();
213                 }
214             }).start();
215         }
216         nextcheck = 0;
217         notifyAll();
218     }
219
220     private void dodelivery() {
221         DeliveryQueue dq;
222         while ((dq = getNextQueue()) != null) {
223             dq.run();
224         }
225     }
226
227     private synchronized DeliveryQueue getNextQueue() {
228         while (true) {
229             if (curthreads > threads) {
230                 curthreads--;
231                 return (null);
232             }
233             if (qpos < queues.length) {
234                 DeliveryQueue dq = queues[qpos++];
235                 if (dq.isSkipSet()) {
236                     continue;
237                 }
238                 nextcheck = 0;
239                 notifyAll();
240                 return (dq);
241             }
242             long now = System.currentTimeMillis();
243             if (now < nextcheck) {
244                 try {
245                     wait(nextcheck + 500 - now);
246                 } catch (Exception e) {
247                     logger.error("InterruptedException", e);
248                 }
249                 now = System.currentTimeMillis();
250             }
251             if (now >= nextcheck) {
252                 nextcheck = now + 5000;
253                 qpos = 0;
254                 freeDiskCheck();
255             }
256         }
257     }
258
259     private boolean determineFreeDiskSpace(File spoolfile, long tspace, long stop, long cur, DelItem[] items) {
260         for (DelItem item : items) {
261             long amount = dqs.get(item.getSpool()).cancelTask(item.getPublishId());
262             logger.debug("NODE0502 Attempting to discard " + item.getSpool() + "/" + item.getPublishId()
263                 + " to free up disk");
264             if (amount > 0) {
265                 cur += amount;
266                 if (cur >= stop) {
267                     cur = spoolfile.getUsableSpace();
268                 }
269                 if (cur >= stop) {
270                     logger.warn(
271                         "NODE0503 Free disk space at or above yellow threshold.  current=" + cur + YELLOW + stop
272                             + TOTAL + tspace);
273                     return true;
274                 }
275             }
276         }
277         return false;
278     }
279
280     static class DelItem implements Comparable<DelItem> {
281
282         private String pubid;
283         private String spool;
284
285         public DelItem(String pubid, String spool) {
286             this.pubid = pubid;
287             this.spool = spool;
288         }
289
290         public int compareTo(DelItem other) {
291             int diff = pubid.compareTo(other.pubid);
292             if (diff == 0) {
293                 diff = spool.compareTo(other.spool);
294             }
295             return (diff);
296         }
297
298         public String getPublishId() {
299             return (pubid);
300         }
301
302         public String getSpool() {
303             return (spool);
304         }
305
306         @Override
307         public boolean equals(Object object) {
308             if (this == object) {
309                 return true;
310             }
311             if (object == null || getClass() != object.getClass()) {
312                 return false;
313             }
314             DelItem delItem = (DelItem) object;
315             return Objects.equals(pubid, delItem.pubid)
316                 && Objects.equals(getSpool(), delItem.getSpool());
317         }
318
319         @Override
320         public int hashCode() {
321             return Objects.hash(pubid, getSpool());
322         }
323     }
324 }