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.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.UUID;
45 import java.util.zip.GZIPInputStream;
46 import org.jetbrains.annotations.Nullable;
47 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
51 * A file to be delivered to a destination.
53 * <p>A Delivery task represents a work item for the data router - a file that needs to be delivered and provides
54 * mechanisms to get information about the file and its delivery data as well as to attempt delivery.
56 public class DeliveryTask implements Runnable, Comparable<DeliveryTask> {
58 private static final String DECOMPRESSION_STATUS = "Decompression_Status";
59 private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(DeliveryTask.class);
60 private DeliveryTaskHelper deliveryTaskHelper;
62 private DestInfo destInfo;
64 private File datafile;
65 private File metafile;
68 private String method;
69 private String fileid;
72 private String feedid;
75 private boolean followRedirects;
76 private String[][] hdrs;
77 private String newInvocationId;
78 private long resumeTime;
82 * Create a delivery task for a given delivery queue and pub ID
84 * @param deliveryTaskHelper The delivery task helper for the queue this task is in.
85 * @param pubid The publish ID for this file. This is used as the base for the file name in the spool directory and
86 * is of the form <milliseconds since 1970>.<fqdn of initial data router node>
88 DeliveryTask(DeliveryTaskHelper deliveryTaskHelper, String pubid) {
89 this.deliveryTaskHelper = deliveryTaskHelper;
91 destInfo = deliveryTaskHelper.getDestinationInfo();
92 subid = destInfo.getSubId();
93 this.followRedirects = destInfo.isFollowRedirects();
94 feedid = destInfo.getLogData();
95 spool = destInfo.getSpool();
96 String dfn = spool + "/" + pubid;
97 String mfn = dfn + ".M";
98 datafile = new File(spool + "/" + pubid);
99 metafile = new File(mfn);
100 boolean monly = destInfo.isMetaDataOnly();
101 date = Long.parseLong(pubid.substring(0, pubid.indexOf('.')));
102 resumeTime = System.currentTimeMillis();
103 ArrayList<String[]> hdrv = new ArrayList<>();
105 try (BufferedReader br = new BufferedReader(new FileReader(metafile))) {
106 String line = br.readLine();
107 int index = line.indexOf('\t');
108 method = line.substring(0, index);
109 NodeUtils.setIpAndFqdnForEelf(method);
110 if (!"DELETE".equals(method) && !monly) {
111 length = datafile.length();
113 fileid = line.substring(index + 1);
114 while ((line = br.readLine()) != null) {
115 index = line.indexOf('\t');
116 String header = line.substring(0, index);
117 String headerValue = line.substring(index + 1);
118 if ("x-dmaap-dr-routing".equalsIgnoreCase(header)) {
119 subid = headerValue.replaceAll("[^ ]*/", "");
120 feedid = deliveryTaskHelper.getFeedId(subid.replaceAll(" .*", ""));
122 if (length == 0 && header.toLowerCase().startsWith("content-")) {
125 if ("content-type".equalsIgnoreCase(header)) {
128 if ("x-onap-requestid".equalsIgnoreCase(header)) {
129 MDC.put(MDC_KEY_REQUEST_ID, headerValue);
131 if ("x-invocationid".equalsIgnoreCase(header)) {
132 MDC.put("InvocationId", headerValue);
133 headerValue = UUID.randomUUID().toString();
134 newInvocationId = headerValue;
136 hdrv.add(new String[]{header, headerValue});
138 } catch (Exception e) {
139 eelfLogger.error("Exception", e);
141 hdrs = hdrv.toArray(new String[hdrv.size()][]);
142 url = deliveryTaskHelper.getDestURL(fileid);
146 * Is the object a DeliveryTask with the same publication ID.
148 public boolean equals(Object object) {
149 if (!(object instanceof DeliveryTask)) {
152 return (pubid.equals(((DeliveryTask) object).pubid));
156 * Compare the publication IDs.
158 public int compareTo(DeliveryTask other) {
159 return (pubid.compareTo(other.pubid));
163 * Get the hash code of the publication ID.
165 public int hashCode() {
166 return (pubid.hashCode());
170 * Return the publication ID.
172 public String toString() {
177 * Get the publish ID.
179 String getPublishId() {
189 destInfo = deliveryTaskHelper.getDestinationInfo();
190 boolean monly = destInfo.isMetaDataOnly();
192 if (!"DELETE".equals(method) && !monly) {
193 length = datafile.length();
195 stripSuffixIfIsDecompress();
196 url = deliveryTaskHelper.getDestURL(fileid);
197 URL urlObj = new URL(url);
198 HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection();
199 urlConnection.setConnectTimeout(60000);
200 urlConnection.setReadTimeout(60000);
201 urlConnection.setInstanceFollowRedirects(false);
202 urlConnection.setRequestMethod(method);
203 urlConnection.setRequestProperty("Content-Length", Long.toString(length));
204 urlConnection.setRequestProperty("Authorization", destInfo.getAuth());
205 urlConnection.setRequestProperty("X-DMAAP-DR-PUBLISH-ID", pubid);
206 boolean expect100 = destInfo.isUsing100();
207 int rc = deliverFileToSubscriber(expect100, urlConnection);
208 String rmsg = urlConnection.getResponseMessage();
209 rmsg = getResponseMessage(urlConnection, rmsg);
210 String xpubid = null;
212 if (rc >= 200 && rc <= 299) {
213 is = urlConnection.getInputStream();
214 xpubid = urlConnection.getHeaderField("X-DMAAP-DR-PUBLISH-ID");
216 if (rc >= 300 && rc <= 399) {
217 rmsg = urlConnection.getHeaderField("Location");
219 is = urlConnection.getErrorStream();
221 byte[] buf = new byte[4096];
223 while (is.read(buf) > 0) {
227 deliveryTaskHelper.reportStatus(this, rc, xpubid, rmsg);
228 } catch (Exception e) {
229 eelfLogger.error("Exception " + Arrays.toString(e.getStackTrace()), e);
230 deliveryTaskHelper.reportException(this, e);
235 * To send decompressed gzip to the subscribers.
237 * @param httpURLConnection connection used to make request
239 private void sendDecompressedFile(HttpURLConnection httpURLConnection) throws IOException {
240 byte[] buffer = new byte[8164];
241 httpURLConnection.setRequestProperty(DECOMPRESSION_STATUS, "SUCCESS");
242 OutputStream outputStream = getOutputStream(httpURLConnection);
243 if (outputStream != null) {
245 try (InputStream gzipInputStream = new GZIPInputStream(new FileInputStream(datafile))) {
246 int bufferLength = buffer.length;
247 while ((bytesRead = gzipInputStream.read(buffer, 0, bufferLength)) > 0) {
248 outputStream.write(buffer, 0, bytesRead);
250 outputStream.close();
251 } catch (IOException e) {
252 httpURLConnection.setRequestProperty(DECOMPRESSION_STATUS, "FAILURE");
253 eelfLogger.info("Could not decompress file", e);
254 sendFile(httpURLConnection);
261 * To send any file to the subscriber.
263 * @param httpURLConnection connection used to make request
265 private void sendFile(HttpURLConnection httpURLConnection) throws IOException {
266 OutputStream os = getOutputStream(httpURLConnection);
271 try (InputStream is = new FileInputStream(datafile)) {
272 byte[] buf = new byte[1024 * 1024];
273 while (sofar < length) {
274 int len = buf.length;
275 if (sofar + len > length) {
276 len = (int) (length - sofar);
278 len = is.read(buf, 0, len);
280 throw new IOException("Unexpected problem reading data file " + datafile);
283 os.write(buf, 0, len);
286 } catch (IOException ioe) {
287 deliveryTaskHelper.reportDeliveryExtra(this, sofar);
293 * Get the outputstream that will be used to send data.
295 * @param httpURLConnection connection used to make request
296 * @return AN Outpustream that can be used to send your data.
298 private OutputStream getOutputStream(HttpURLConnection httpURLConnection) throws IOException {
299 OutputStream outputStream = null;
301 outputStream = httpURLConnection.getOutputStream();
302 } catch (ProtocolException pe) {
303 deliveryTaskHelper.reportDeliveryExtra(this, -1L);
304 // Rcvd error instead of 100-continue
305 eelfLogger.error("Exception " + Arrays.toString(pe.getStackTrace()), pe);
310 private void stripSuffixIfIsDecompress() {
311 if (destInfo.isDecompress() && isFiletypeGzip(datafile) && fileid.endsWith(".gz")) {
312 fileid = fileid.replace(".gz", "");
316 private int deliverFileToSubscriber(boolean expect100, HttpURLConnection uc) throws IOException {
317 for (String[] nv : hdrs) {
318 uc.addRequestProperty(nv[0], nv[1]);
322 uc.setRequestProperty("Expect", "100-continue");
324 uc.setDoOutput(true);
325 if (destInfo.isDecompress()) {
326 if (isFiletypeGzip(datafile)) {
327 sendDecompressedFile(uc);
329 uc.setRequestProperty(DECOMPRESSION_STATUS, "UNSUPPORTED_FORMAT");
336 return uc.getResponseCode();
340 private String getResponseMessage(HttpURLConnection uc, String rmsg) {
342 String h0 = uc.getHeaderField(0);
344 int indexOfSpace1 = h0.indexOf(' ');
345 int indexOfSpace2 = h0.indexOf(' ', indexOfSpace1 + 1);
346 if (indexOfSpace1 != -1 && indexOfSpace2 != -1) {
347 rmsg = h0.substring(indexOfSpace2 + 1);
355 * Remove meta and data files.
360 eelfLogger.info(EelfMsgs.INVOKE, newInvocationId);
361 eelfLogger.info(EelfMsgs.EXIT);
366 * Get the resume time for a delivery task.
368 long getResumeTime() {
373 * Set the resume time for a delivery task.
375 void setResumeTime(long resumeTime) {
376 this.resumeTime = resumeTime;
380 * Has this delivery task been cleaned.
382 boolean isCleaned() {
383 return (hdrs == null);
387 * Get length of body.
389 public long getLength() {
394 * Get creation date as encoded in the publish ID.
401 * Get the most recent delivery attempt URL.
403 public String getURL() {
408 * Get the content type.
429 * Get the number of delivery attempts.
436 * Get the (space delimited list of) subscription ID for this delivery task.
443 * Get the feed ID for this delivery task.
450 * Get the followRedirects for this delivery task.
452 public boolean getFollowRedirects() {
453 return (followRedirects);