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 static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
28 import static org.onap.dmaap.datarouter.node.NodeUtils.isFiletypeGzip;
30 import com.att.eelf.configuration.EELFLogger;
31 import com.att.eelf.configuration.EELFManager;
32 import java.io.BufferedReader;
34 import java.io.FileInputStream;
35 import java.io.FileReader;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.OutputStream;
39 import java.net.HttpURLConnection;
40 import java.net.ProtocolException;
42 import java.nio.file.Files;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.UUID;
46 import java.util.zip.GZIPInputStream;
47 import org.jetbrains.annotations.Nullable;
48 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
52 * A file to be delivered to a destination.
54 * <p>A Delivery task represents a work item for the data router - a file that needs to be delivered and provides
55 * mechanisms to get information about the file and its delivery data as well as to attempt delivery.
57 public class DeliveryTask implements Runnable, Comparable<DeliveryTask> {
59 private static final String DECOMPRESSION_STATUS = "Decompression_Status";
60 private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(DeliveryTask.class);
61 private DeliveryTaskHelper deliveryTaskHelper;
63 private DestInfo destInfo;
65 private File datafile;
66 private File metafile;
69 private String method;
70 private String fileid;
73 private String feedid;
76 private boolean followRedirects;
77 private String[][] hdrs;
78 private String newInvocationId;
79 private long resumeTime;
83 * Create a delivery task for a given delivery queue and pub ID.
85 * @param deliveryTaskHelper The delivery task helper for the queue this task is in.
86 * @param pubid The publish ID for this file. This is used as the base for the file name in the spool directory and
87 * is of the form (milliseconds since 1970).(fqdn of initial data router node)
89 DeliveryTask(DeliveryTaskHelper deliveryTaskHelper, String pubid) {
90 this.deliveryTaskHelper = deliveryTaskHelper;
92 destInfo = deliveryTaskHelper.getDestinationInfo();
93 subid = destInfo.getSubId();
94 this.followRedirects = destInfo.isFollowRedirects();
95 feedid = destInfo.getLogData();
96 spool = destInfo.getSpool();
97 String dfn = spool + "/" + pubid;
98 String mfn = dfn + ".M";
99 datafile = new File(spool + "/" + pubid);
100 metafile = new File(mfn);
101 boolean monly = destInfo.isMetaDataOnly();
102 date = Long.parseLong(pubid.substring(0, pubid.indexOf('.')));
103 resumeTime = System.currentTimeMillis();
104 ArrayList<String[]> hdrv = new ArrayList<>();
106 try (BufferedReader br = new BufferedReader(new FileReader(metafile))) {
107 String line = br.readLine();
108 int index = line.indexOf('\t');
109 method = line.substring(0, index);
110 NodeUtils.setIpAndFqdnForEelf(method);
111 if (!"DELETE".equals(method) && !monly) {
112 length = datafile.length();
114 fileid = line.substring(index + 1);
115 while ((line = br.readLine()) != null) {
116 index = line.indexOf('\t');
117 String header = line.substring(0, index);
118 String headerValue = line.substring(index + 1);
119 if ("x-dmaap-dr-routing".equalsIgnoreCase(header)) {
120 subid = headerValue.replaceAll("[^ ]*/", "");
121 feedid = deliveryTaskHelper.getFeedId(subid.replaceAll(" .*", ""));
123 if (length == 0 && header.toLowerCase().startsWith("content-")) {
126 if ("content-type".equalsIgnoreCase(header)) {
129 if ("x-onap-requestid".equalsIgnoreCase(header)) {
130 MDC.put(MDC_KEY_REQUEST_ID, headerValue);
132 if ("x-invocationid".equalsIgnoreCase(header)) {
133 MDC.put("InvocationId", headerValue);
134 headerValue = UUID.randomUUID().toString();
135 newInvocationId = headerValue;
137 hdrv.add(new String[]{header, headerValue});
139 } catch (Exception e) {
140 eelfLogger.error("Exception", e);
142 hdrs = hdrv.toArray(new String[hdrv.size()][]);
143 url = deliveryTaskHelper.getDestURL(fileid);
147 * Is the object a DeliveryTask with the same publication ID.
149 public boolean equals(Object object) {
150 if (!(object instanceof DeliveryTask)) {
153 return (pubid.equals(((DeliveryTask) object).pubid));
157 * Compare the publication IDs.
159 public int compareTo(DeliveryTask other) {
160 return (pubid.compareTo(other.pubid));
164 * Get the hash code of the publication ID.
166 public int hashCode() {
167 return (pubid.hashCode());
171 * Return the publication ID.
173 public String toString() {
178 * Get the publish ID.
180 String getPublishId() {
190 destInfo = deliveryTaskHelper.getDestinationInfo();
191 boolean monly = destInfo.isMetaDataOnly();
193 if (!"DELETE".equals(method) && !monly) {
194 length = datafile.length();
196 stripSuffixIfIsDecompress();
197 url = deliveryTaskHelper.getDestURL(fileid);
198 URL urlObj = new URL(url);
199 HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection();
200 urlConnection.setConnectTimeout(60000);
201 urlConnection.setReadTimeout(60000);
202 urlConnection.setInstanceFollowRedirects(false);
203 urlConnection.setRequestMethod(method);
204 urlConnection.setRequestProperty("Content-Length", Long.toString(length));
205 urlConnection.setRequestProperty("Authorization", destInfo.getAuth());
206 urlConnection.setRequestProperty("X-DMAAP-DR-PUBLISH-ID", pubid);
207 boolean expect100 = destInfo.isUsing100();
208 int rc = deliverFileToSubscriber(expect100, urlConnection);
209 String rmsg = urlConnection.getResponseMessage();
210 rmsg = getResponseMessage(urlConnection, rmsg);
211 String xpubid = null;
213 if (rc >= 200 && rc <= 299) {
214 is = urlConnection.getInputStream();
215 xpubid = urlConnection.getHeaderField("X-DMAAP-DR-PUBLISH-ID");
217 if (rc >= 300 && rc <= 399) {
218 rmsg = urlConnection.getHeaderField("Location");
220 is = urlConnection.getErrorStream();
222 byte[] buf = new byte[4096];
224 while (is.read(buf) > 0) {
228 deliveryTaskHelper.reportStatus(this, rc, xpubid, rmsg);
229 } catch (Exception e) {
230 eelfLogger.error("Exception " + Arrays.toString(e.getStackTrace()), e);
231 deliveryTaskHelper.reportException(this, e);
236 * To send decompressed gzip to the subscribers.
238 * @param httpURLConnection connection used to make request
240 private void sendDecompressedFile(HttpURLConnection httpURLConnection) throws IOException {
241 byte[] buffer = new byte[8164];
242 httpURLConnection.setRequestProperty(DECOMPRESSION_STATUS, "SUCCESS");
243 OutputStream outputStream = getOutputStream(httpURLConnection);
244 if (outputStream != null) {
246 try (InputStream gzipInputStream = new GZIPInputStream(new FileInputStream(datafile))) {
247 int bufferLength = buffer.length;
248 while ((bytesRead = gzipInputStream.read(buffer, 0, bufferLength)) > 0) {
249 outputStream.write(buffer, 0, bytesRead);
251 outputStream.close();
252 } catch (IOException e) {
253 httpURLConnection.setRequestProperty(DECOMPRESSION_STATUS, "FAILURE");
254 eelfLogger.info("Could not decompress file", e);
255 sendFile(httpURLConnection);
262 * To send any file to the subscriber.
264 * @param httpURLConnection connection used to make request
266 private void sendFile(HttpURLConnection httpURLConnection) throws IOException {
267 OutputStream os = getOutputStream(httpURLConnection);
272 try (InputStream is = new FileInputStream(datafile)) {
273 byte[] buf = new byte[1024 * 1024];
274 while (sofar < length) {
275 int len = buf.length;
276 if (sofar + len > length) {
277 len = (int) (length - sofar);
279 len = is.read(buf, 0, len);
281 throw new IOException("Unexpected problem reading data file " + datafile);
284 os.write(buf, 0, len);
287 } catch (IOException ioe) {
288 deliveryTaskHelper.reportDeliveryExtra(this, sofar);
294 * Get the outputstream that will be used to send data.
296 * @param httpURLConnection connection used to make request
297 * @return AN Outpustream that can be used to send your data.
299 private OutputStream getOutputStream(HttpURLConnection httpURLConnection) throws IOException {
300 OutputStream outputStream = null;
302 outputStream = httpURLConnection.getOutputStream();
303 } catch (ProtocolException pe) {
304 deliveryTaskHelper.reportDeliveryExtra(this, -1L);
305 // Rcvd error instead of 100-continue
306 eelfLogger.error("Exception " + Arrays.toString(pe.getStackTrace()), pe);
311 private void stripSuffixIfIsDecompress() {
312 if (destInfo.isDecompress() && isFiletypeGzip(datafile) && fileid.endsWith(".gz")) {
313 fileid = fileid.replace(".gz", "");
317 private int deliverFileToSubscriber(boolean expect100, HttpURLConnection uc) throws IOException {
318 for (String[] nv : hdrs) {
319 uc.addRequestProperty(nv[0], nv[1]);
323 uc.setRequestProperty("Expect", "100-continue");
325 uc.setDoOutput(true);
326 if (destInfo.isDecompress()) {
327 if (isFiletypeGzip(datafile)) {
328 sendDecompressedFile(uc);
330 uc.setRequestProperty(DECOMPRESSION_STATUS, "UNSUPPORTED_FORMAT");
337 return uc.getResponseCode();
341 private String getResponseMessage(HttpURLConnection uc, String rmsg) {
343 String h0 = uc.getHeaderField(0);
345 int indexOfSpace1 = h0.indexOf(' ');
346 int indexOfSpace2 = h0.indexOf(' ', indexOfSpace1 + 1);
347 if (indexOfSpace1 != -1 && indexOfSpace2 != -1) {
348 rmsg = h0.substring(indexOfSpace2 + 1);
356 * Remove meta and data files.
359 deleteWithRetry(datafile);
360 deleteWithRetry(metafile);
361 eelfLogger.info(EelfMsgs.INVOKE, newInvocationId);
362 eelfLogger.info(EelfMsgs.EXIT);
366 private void deleteWithRetry(File file) {
369 while (tryCount <= maxTries) {
371 Files.deleteIfExists(file.toPath());
373 } catch (IOException e) {
374 eelfLogger.error("IOException : Failed to delete file :" + file.getName() + " on attempt " + tryCount, e);
381 * Get the resume time for a delivery task.
383 long getResumeTime() {
388 * Set the resume time for a delivery task.
390 void setResumeTime(long resumeTime) {
391 this.resumeTime = resumeTime;
395 * Has this delivery task been cleaned.
397 boolean isCleaned() {
398 return (hdrs == null);
402 * Get length of body.
404 public long getLength() {
409 * Get creation date as encoded in the publish ID.
416 * Get the most recent delivery attempt URL.
418 public String getURL() {
423 * Get the content type.
444 * Get the number of delivery attempts.
451 * Get the (space delimited list of) subscription ID for this delivery task.
458 * Get the feed ID for this delivery task.
465 * Get the followRedirects for this delivery task.
467 public boolean getFollowRedirects() {
468 return (followRedirects);