Merge "Unit test base"
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / DeliveryQueue.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
25 package org.onap.dmaap.datarouter.node;
26
27 import java.io.*;
28 import java.util.*;
29
30 /**
31  * Mechanism for monitoring and controlling delivery of files to a destination.
32  * <p>
33  * The DeliveryQueue class maintains lists of DeliveryTasks for a single
34  * destination (a subscription or another data router node) and assigns
35  * delivery threads to try to deliver them.  It also maintains a delivery
36  * status that causes it to back off on delivery attempts after a failure.
37  * <p>
38  * If the most recent delivery result was a failure, then no more attempts
39  * will be made for a period of time.  Initially, and on the first failure
40  * following a success, this delay will be DeliveryQueueHelper.getInitFailureTimer() (milliseconds).
41  * If, after this delay, additional failures occur, each failure will
42  * multiply the delay by DeliveryQueueHelper.getFailureBackoff() up to a
43  * maximum delay specified by DeliveryQueueHelper.getMaxFailureTimer().
44  * Note that this behavior applies to the delivery queue as a whole and not
45  * to individual files in the queue.  If multiple files are being
46  * delivered and one fails, the delay will be started.  If a second
47  * delivery fails while the delay was active, it will not change the delay
48  * or change the duration of any subsequent delay.
49  * If, however, it succeeds, it will cancel the delay.
50  * <p>
51  * The queue maintains 3 collections of files to deliver: A todo list of
52  * files that will be attempted, a working set of files that are being
53  * attempted, and a retry set of files that were attempted and failed.
54  * Whenever the todo list is empty and needs to be refilled, a scan of the
55  * spool directory is made and the file names sorted.  Any files in the working set are ignored.
56  * If a DeliveryTask for the file is in the retry set, then that delivery
57  * task is placed on the todo list.  Otherwise, a new DeliveryTask for the
58  * file is created and placed on the todo list.
59  * If, when a DeliveryTask is about to be removed from the todo list, its
60  * age exceeds DeliveryQueueHelper.getExpirationTimer(), then it is instead
61  * marked as expired.
62  * <p>
63  * A delivery queue also maintains a skip flag.  This flag is true if the
64  * failure timer is active or if no files are found in a directory scan.
65  */
66 public class DeliveryQueue implements Runnable, DeliveryTaskHelper {
67     private DeliveryQueueHelper dqh;
68     private DestInfo di;
69     private Hashtable<String, DeliveryTask> working = new Hashtable<String, DeliveryTask>();
70     private Hashtable<String, DeliveryTask> retry = new Hashtable<String, DeliveryTask>();
71     private int todoindex;
72     private boolean failed;
73     private long failduration;
74     private long resumetime;
75     File dir;
76     private Vector<DeliveryTask> todo = new Vector<DeliveryTask>();
77
78     /**
79      * Try to cancel a delivery task.
80      *
81      * @return The length of the task in bytes or 0 if the task cannot be cancelled.
82      */
83     public synchronized long cancelTask(String pubid) {
84         if (working.get(pubid) != null) {
85             return (0);
86         }
87         DeliveryTask dt = retry.get(pubid);
88         if (dt == null) {
89             for (int i = todoindex; i < todo.size(); i++) {
90                 DeliveryTask xdt = todo.get(i);
91                 if (xdt.getPublishId().equals(pubid)) {
92                     dt = xdt;
93                     break;
94                 }
95             }
96         }
97         if (dt == null) {
98             dt = new DeliveryTask(this, pubid);
99             if (dt.getFileId() == null) {
100                 return (0);
101             }
102         }
103         if (dt.isCleaned()) {
104             return (0);
105         }
106         StatusLog.logExp(dt.getPublishId(), dt.getFeedId(), dt.getSubId(), dt.getURL(), dt.getMethod(), dt.getCType(), dt.getLength(), "diskFull", dt.getAttempts());
107         dt.clean();
108         return (dt.getLength());
109     }
110
111     /**
112      * Mark that a delivery task has succeeded.
113      */
114     public synchronized void markSuccess(DeliveryTask task) {
115         working.remove(task.getPublishId());
116         task.clean();
117         failed = false;
118         failduration = 0;
119     }
120
121     /**
122      * Mark that a delivery task has expired.
123      */
124     public synchronized void markExpired(DeliveryTask task) {
125         task.clean();
126     }
127
128     /**
129      * Mark that a delivery task has failed permanently.
130      */
131     public synchronized void markFailNoRetry(DeliveryTask task) {
132         working.remove(task.getPublishId());
133         task.clean();
134         failed = false;
135         failduration = 0;
136     }
137
138     private void fdupdate() {
139         if (!failed) {
140             failed = true;
141             if (failduration == 0) {
142                 failduration = dqh.getInitFailureTimer();
143             }
144             resumetime = System.currentTimeMillis() + failduration;
145             long maxdur = dqh.getMaxFailureTimer();
146             failduration = (long) (failduration * dqh.getFailureBackoff());
147             if (failduration > maxdur) {
148                 failduration = maxdur;
149             }
150         }
151     }
152
153     /**
154      * Mark that a delivery task has been redirected.
155      */
156     public synchronized void markRedirect(DeliveryTask task) {
157         working.remove(task.getPublishId());
158         retry.put(task.getPublishId(), task);
159     }
160
161     /**
162      * Mark that a delivery task has temporarily failed.
163      */
164     public synchronized void markFailWithRetry(DeliveryTask task) {
165         working.remove(task.getPublishId());
166         retry.put(task.getPublishId(), task);
167         fdupdate();
168     }
169
170     /**
171      * Get the next task.
172      */
173     public synchronized DeliveryTask getNext() {
174         DeliveryTask ret = peekNext();
175         if (ret != null) {
176             todoindex++;
177             working.put(ret.getPublishId(), ret);
178         }
179         return (ret);
180     }
181
182     /**
183      * Peek at the next task.
184      */
185     public synchronized DeliveryTask peekNext() {
186         long now = System.currentTimeMillis();
187         long mindate = now - dqh.getExpirationTimer();
188         if (failed) {
189             if (now > resumetime) {
190                 failed = false;
191             } else {
192                 return (null);
193             }
194         }
195         while (true) {
196             if (todoindex >= todo.size()) {
197                 todoindex = 0;
198                 todo = new Vector<DeliveryTask>();
199                 String[] files = dir.list();
200                 Arrays.sort(files);
201                 for (String fname : files) {
202                     if (!fname.endsWith(".M")) {
203                         continue;
204                     }
205                     String fname2 = fname.substring(0, fname.length() - 2);
206                     long pidtime = 0;
207                     int dot = fname2.indexOf('.');
208                     if (dot < 1) {
209                         continue;
210                     }
211                     try {
212                         pidtime = Long.parseLong(fname2.substring(0, dot));
213                     } catch (Exception e) {
214                     }
215                     if (pidtime < 1000000000000L) {
216                         continue;
217                     }
218                     if (working.get(fname2) != null) {
219                         continue;
220                     }
221                     DeliveryTask dt = retry.get(fname2);
222                     if (dt == null) {
223                         dt = new DeliveryTask(this, fname2);
224                     }
225                     todo.add(dt);
226                 }
227                 retry = new Hashtable<String, DeliveryTask>();
228             }
229             if (todoindex < todo.size()) {
230                 DeliveryTask dt = todo.get(todoindex);
231                 if (dt.isCleaned()) {
232                     todoindex++;
233                     continue;
234                 }
235                 if (dt.getDate() >= mindate) {
236                     return (dt);
237                 }
238                 todoindex++;
239                 reportExpiry(dt);
240                 continue;
241             }
242             return (null);
243         }
244     }
245
246     /**
247      * Create a delivery queue for a given destination info
248      */
249     public DeliveryQueue(DeliveryQueueHelper dqh, DestInfo di) {
250         this.dqh = dqh;
251         this.di = di;
252         dir = new File(di.getSpool());
253         dir.mkdirs();
254     }
255
256     /**
257      * Update the destination info for this delivery queue
258      */
259     public void config(DestInfo di) {
260         this.di = di;
261     }
262
263     /**
264      * Get the dest info
265      */
266     public DestInfo getDestInfo() {
267         return (di);
268     }
269
270     /**
271      * Get the config manager
272      */
273     public DeliveryQueueHelper getConfig() {
274         return (dqh);
275     }
276
277     /**
278      * Exceptional condition occurred during delivery
279      */
280     public void reportDeliveryExtra(DeliveryTask task, long sent) {
281         StatusLog.logDelExtra(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getLength(), sent);
282     }
283
284     /**
285      * Message too old to deliver
286      */
287     public void reportExpiry(DeliveryTask task) {
288         StatusLog.logExp(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), "retriesExhausted", task.getAttempts());
289         markExpired(task);
290     }
291
292     /**
293      * Completed a delivery attempt
294      */
295     public void reportStatus(DeliveryTask task, int status, String xpubid, String location) {
296         if (status < 300) {
297             StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), di.getAuthUser(), status, xpubid);
298             markSuccess(task);
299         } else if (status < 400 && dqh.isFollowRedirects()) {
300             StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), di.getAuthUser(), status, location);
301             if (dqh.handleRedirection(di, location, task.getFileId())) {
302                 markRedirect(task);
303             } else {
304                 StatusLog.logExp(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), "notRetryable", task.getAttempts());
305                 markFailNoRetry(task);
306             }
307         } else if (status < 500) {
308             StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), di.getAuthUser(), status, location);
309             StatusLog.logExp(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), "notRetryable", task.getAttempts());
310             markFailNoRetry(task);
311         } else {
312             StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), di.getAuthUser(), status, location);
313             markFailWithRetry(task);
314         }
315     }
316
317     /**
318      * Delivery failed by reason of an exception
319      */
320     public void reportException(DeliveryTask task, Exception exception) {
321         StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(), task.getCType(), task.getLength(), di.getAuthUser(), -1, exception.toString());
322         dqh.handleUnreachable(di);
323         markFailWithRetry(task);
324     }
325
326     /**
327      * Get the feed ID for a subscription
328      *
329      * @param subid The subscription ID
330      * @return The feed ID
331      */
332     public String getFeedId(String subid) {
333         return (dqh.getFeedId(subid));
334     }
335
336     /**
337      * Get the URL to deliver a message to given the file ID
338      */
339     public String getDestURL(String fileid) {
340         return (dqh.getDestURL(di, fileid));
341     }
342
343     /**
344      * Deliver files until there's a failure or there are no more
345      * files to deliver
346      */
347     public void run() {
348         DeliveryTask t;
349         long endtime = System.currentTimeMillis() + dqh.getFairTimeLimit();
350         int filestogo = dqh.getFairFileLimit();
351         while ((t = getNext()) != null) {
352             t.run();
353             if (--filestogo <= 0 || System.currentTimeMillis() > endtime) {
354                 break;
355             }
356         }
357     }
358
359     /**
360      * Is there no work to do for this queue right now?
361      */
362     public synchronized boolean isSkipSet() {
363         return (peekNext() == null);
364     }
365
366     /**
367      * Reset the retry timer
368      */
369     public void resetQueue() {
370         resumetime = System.currentTimeMillis();
371     }
372 }