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 ******************************************************************************/
25 package org.onap.dmaap.datarouter.node;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.HashMap;
33 import java.util.List;
34 import org.jetbrains.annotations.Nullable;
37 * Mechanism for monitoring and controlling delivery of files to a destination.
39 * <p>The DeliveryQueue class maintains lists of DeliveryTasks for a single
40 * destination (a subscription or another data router node) and assigns
41 * delivery threads to try to deliver them. It also maintains a delivery
42 * status that causes it to back off on delivery attempts after a failure.
44 * <p>If the most recent delivery result was a failure, then no more attempts
45 * will be made for a period of time. Initially, and on the first failure
46 * following a success, this delay will be DeliveryQueueHelper.getInitFailureTimer() (milliseconds).
47 * If, after this delay, additional failures occur, each failure will
48 * multiply the delay by DeliveryQueueHelper.getFailureBackoff() up to a
49 * maximum delay specified by DeliveryQueueHelper.getMaxFailureTimer().
50 * Note that this behavior applies to the delivery queue as a whole and not
51 * to individual files in the queue. If multiple files are being
52 * delivered and one fails, the delay will be started. If a second
53 * delivery fails while the delay was active, it will not change the delay
54 * or change the duration of any subsequent delay.
55 * If, however, it succeeds, it will cancel the delay.
56 * The queue maintains 3 collections of files to deliver: A todoList of
57 * files that will be attempted, a working set of files that are being
58 * attempted, and a retry set of files that were attempted and failed.
59 * Whenever the todoList is empty and needs to be refilled, a scan of the
60 * spool directory is made and the file names sorted. Any files in the working set are ignored.
61 * If a DeliveryTask for the file is in the retry set, then that delivery
62 * task is placed on the todoList. Otherwise, a new DeliveryTask for the
63 * file is created and placed on the todoList.
64 * If, when a DeliveryTask is about to be removed from the todoList, its
65 * age exceeds DeliveryQueueHelper.getExpirationTimer(), then it is instead
68 * <p>A delivery queue also maintains a skip flag. This flag is true if the
69 * failure timer is active or if no files are found in a directory scan.
71 public class DeliveryQueue implements Runnable, DeliveryTaskHelper {
72 private static EELFLogger logger = EELFManager.getInstance().getLogger(DeliveryQueue.class);
73 private DeliveryQueueHelper deliveryQueueHelper;
75 private DestInfo destinationInfo;
76 private HashMap<String, DeliveryTask> working = new HashMap<>();
77 private HashMap<String, DeliveryTask> retry = new HashMap<>();
78 private int todoindex;
79 private boolean failed;
80 private long failduration;
81 private long resumetime;
83 private List<DeliveryTask> todoList = new ArrayList<>();
86 * Create a delivery queue for a given destination info.
88 DeliveryQueue(DeliveryQueueHelper deliveryQueueHelper, DestInfo destinationInfo) {
89 this.deliveryQueueHelper = deliveryQueueHelper;
90 this.destinationInfo = destinationInfo;
91 dir = new File(destinationInfo.getSpool());
96 * Try to cancel a delivery task.
98 * @return The length of the task in bytes or 0 if the task cannot be cancelled.
100 synchronized long cancelTask(String pubid) {
101 if (working.get(pubid) != null) {
104 DeliveryTask dt = retry.get(pubid);
106 for (int i = todoindex; i < todoList.size(); i++) {
107 DeliveryTask xdt = todoList.get(i);
108 if (xdt.getPublishId().equals(pubid)) {
115 dt = new DeliveryTask(this, pubid);
116 if (dt.getFileId() == null) {
120 if (dt.isCleaned()) {
123 StatusLog.logExp(dt.getPublishId(), dt.getFeedId(), dt.getSubId(), dt.getURL(),
124 dt.getMethod(), dt.getCType(), dt.getLength(), "diskFull", dt.getAttempts());
126 return (dt.getLength());
130 * Mark that a delivery task has succeeded.
132 private synchronized void markSuccess(DeliveryTask task) {
133 working.remove(task.getPublishId());
134 logger.info(task.getPublishId() + " marked as success.");
141 * Mark that a delivery task has expired.
143 private synchronized void markExpired(DeliveryTask task) {
144 logger.info(task.getPublishId() + " marked as expired.");
149 * Mark that a delivery task has failed permanently.
151 private synchronized void markFailNoRetry(DeliveryTask task) {
152 working.remove(task.getPublishId());
153 logger.info(task.getPublishId() + " marked as failed permanently");
159 private void fdupdate() {
162 if (failduration == 0) {
163 if (destinationInfo.isPrivilegedSubscriber()) {
164 failduration = deliveryQueueHelper.getWaitForFileProcessFailureTimer();
166 failduration = deliveryQueueHelper.getInitFailureTimer();
169 resumetime = System.currentTimeMillis() + failduration;
170 long maxdur = deliveryQueueHelper.getMaxFailureTimer();
171 failduration = (long) (failduration * deliveryQueueHelper.getFailureBackoff());
172 if (failduration > maxdur) {
173 failduration = maxdur;
179 * Mark that a delivery task has been redirected.
181 private synchronized void markRedirect(DeliveryTask task) {
182 working.remove(task.getPublishId());
183 logger.info(task.getPublishId() + " marked as redirected.");
184 retry.put(task.getPublishId(), task);
188 * Mark that a delivery task has temporarily failed.
190 private synchronized void markFailWithRetry(DeliveryTask task) {
191 working.remove(task.getPublishId());
192 logger.info(task.getPublishId() + " marked as temporarily failed.");
193 retry.put(task.getPublishId(), task);
200 synchronized DeliveryTask getNext() {
201 DeliveryTask ret = peekNext();
204 working.put(ret.getPublishId(), ret);
210 * Peek at the next task.
212 synchronized DeliveryTask peekNext() {
213 long now = System.currentTimeMillis();
214 long mindate = now - deliveryQueueHelper.getExpirationTimer();
216 if (now > resumetime) {
223 if (todoindex >= todoList.size()) {
225 todoList = new ArrayList<>();
226 String[] files = dir.list();
228 scanForNextTask(files);
229 retry = new HashMap<>();
231 DeliveryTask dt = getDeliveryTask(mindate);
241 * Update the destination info for this delivery queue.
243 public void config(DestInfo destinationInfo) {
244 this.destinationInfo = destinationInfo;
250 public DestInfo getDestinationInfo() {
251 return (destinationInfo);
255 * Get the config manager.
257 public DeliveryQueueHelper getConfig() {
258 return (deliveryQueueHelper);
262 * Exceptional condition occurred during delivery.
264 public void reportDeliveryExtra(DeliveryTask task, long sent) {
265 StatusLog.logDelExtra(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getLength(), sent);
269 * Message too old to deliver.
271 void reportExpiry(DeliveryTask task) {
272 StatusLog.logExp(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(),
273 task.getCType(), task.getLength(), "retriesExhausted", task.getAttempts());
278 * Completed a delivery attempt.
280 public void reportStatus(DeliveryTask task, int status, String xpubid, String location) {
282 StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(),
283 task.getCType(), task.getLength(), destinationInfo.getAuthUser(), status, xpubid);
284 if (destinationInfo.isPrivilegedSubscriber()) {
285 task.setResumeTime(System.currentTimeMillis()
286 + deliveryQueueHelper.getWaitForFileProcessFailureTimer());
287 markFailWithRetry(task);
291 } else if (status < 400 && deliveryQueueHelper.isFollowRedirects()) {
292 StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(),
293 task.getCType(), task.getLength(), destinationInfo.getAuthUser(), status, location);
294 if (deliveryQueueHelper.handleRedirection(destinationInfo, location, task.getFileId())) {
297 StatusLog.logExp(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(),
298 task.getMethod(), task.getCType(), task.getLength(), "notRetryable", task.getAttempts());
299 markFailNoRetry(task);
301 } else if (status < 500 && status != 429) {
302 // Status 429 is the standard response for Too Many Requests and indicates
303 // that a file needs to be delivered again at a later time.
304 StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(),
305 task.getCType(), task.getLength(), destinationInfo.getAuthUser(), status, location);
306 StatusLog.logExp(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(),
307 task.getCType(), task.getLength(), "notRetryable", task.getAttempts());
308 markFailNoRetry(task);
310 StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(),
311 task.getCType(), task.getLength(), destinationInfo.getAuthUser(), status, location);
312 markFailWithRetry(task);
317 * Delivery failed by reason of an exception.
319 public void reportException(DeliveryTask task, Exception exception) {
320 StatusLog.logDel(task.getPublishId(), task.getFeedId(), task.getSubId(), task.getURL(), task.getMethod(),
321 task.getCType(), task.getLength(), destinationInfo.getAuthUser(), -1, exception.toString());
322 deliveryQueueHelper.handleUnreachable(destinationInfo);
323 markFailWithRetry(task);
327 * Get the feed ID for a subscription.
329 * @param subid The subscription ID
330 * @return The feed ID
332 public String getFeedId(String subid) {
333 return (deliveryQueueHelper.getFeedId(subid));
337 * Get the URL to deliver a message to given the file ID.
339 public String getDestURL(String fileid) {
340 return (deliveryQueueHelper.getDestURL(destinationInfo, fileid));
344 * Deliver files until there's a failure or there are no more.
349 long endtime = System.currentTimeMillis() + deliveryQueueHelper.getFairTimeLimit();
350 int filestogo = deliveryQueueHelper.getFairFileLimit();
351 while ((task = getNext()) != null) {
352 logger.info("Processing file: " + task.getPublishId());
354 if (--filestogo <= 0 || System.currentTimeMillis() > endtime) {
361 * Is there no work to do for this queue right now?.
363 synchronized boolean isSkipSet() {
364 return (peekNext() == null);
368 * Reset the retry timer.
371 resumetime = System.currentTimeMillis();
375 * Get task if in queue and mark as success.
377 boolean markTaskSuccess(String pubId) {
378 DeliveryTask task = working.get(pubId);
383 task = retry.get(pubId);
394 private void scanForNextTask(String[] files) {
395 for (String fname : files) {
396 String pubId = getPubId(fname);
400 DeliveryTask dt = retry.get(pubId);
402 dt = new DeliveryTask(this, pubId);
409 private DeliveryTask getDeliveryTask(long mindate) {
410 if (todoindex < todoList.size()) {
411 DeliveryTask dt = todoList.get(todoindex);
412 if (dt.isCleaned()) {
415 if (destinationInfo.isPrivilegedSubscriber() && dt.getResumeTime() > System.currentTimeMillis()) {
416 retry.put(dt.getPublishId(), dt);
419 if (dt.getDate() >= mindate) {
429 private String getPubId(String fname) {
430 if (!fname.endsWith(".M")) {
433 String fname2 = fname.substring(0, fname.length() - 2);
435 int dot = fname2.indexOf('.');
440 pidtime = Long.parseLong(fname2.substring(0, dot));
441 } catch (Exception e) {
442 logger.error("Exception", e);
444 if (pidtime < 1000000000000L) {
447 if (working.get(fname2) != null) {