8c1a2cf4bbac35a4d9e1854dd660d2a4be886767
[dcaegen2/collectors/datafile.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dcaegen2.collectors.datafile.tasks;
22
23 import static org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables.REQUEST_ID;
24 import static org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables.X_INVOCATION_ID;
25 import static org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables.X_ONAP_REQUEST_ID;
26
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonParser;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.net.URI;
32 import java.nio.file.Path;
33 import java.time.Duration;
34 import java.util.Map;
35 import java.util.UUID;
36 import org.apache.commons.io.IOUtils;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.client.methods.HttpPut;
39 import org.apache.http.entity.ByteArrayEntity;
40 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
41 import org.onap.dcaegen2.collectors.datafile.model.CommonFunctions;
42 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
43 import org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables;
44 import org.onap.dcaegen2.collectors.datafile.service.HttpUtils;
45 import org.onap.dcaegen2.collectors.datafile.service.producer.DmaapProducerReactiveHttpClient;
46 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.slf4j.MDC;
50 import org.springframework.core.io.FileSystemResource;
51 import org.springframework.http.HttpHeaders;
52 import org.springframework.http.HttpStatus;
53 import reactor.core.publisher.Mono;
54
55 /**
56  * Publishes a file to the DataRouter.
57  *
58  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/13/18
59  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
60  */
61 public class DataRouterPublisher {
62     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
63     private static final String CONTENT_TYPE = "application/octet-stream";
64     private static final String NAME_JSON_TAG = "name";
65     private static final String INTERNAL_LOCATION_JSON_TAG = "internalLocation";
66     private static final String PUBLISH_TOPIC = "publish";
67     private static final String DEFAULT_FEED_ID = "1";
68
69     private static final Logger logger = LoggerFactory.getLogger(DataRouterPublisher.class);
70     private final AppConfig datafileAppConfig;
71     private DmaapProducerReactiveHttpClient dmaapProducerReactiveHttpClient;
72
73     public DataRouterPublisher(AppConfig datafileAppConfig) {
74         this.datafileAppConfig = datafileAppConfig;
75     }
76
77
78     /**
79      * Publish one file.
80      *
81      * @param model information about the file to publish
82      * @param numRetries the maximal number of retries if the publishing fails
83      * @param firstBackoff the time to delay the first retry
84      * @param contextMap tracing context variables
85      * @return the (same) ConsumerDmaapModel
86      */
87     public Mono<ConsumerDmaapModel> execute(ConsumerDmaapModel model, long numRetries, Duration firstBackoff,
88             Map<String, String> contextMap) {
89         MdcVariables.setMdcContextMap(contextMap);
90         logger.trace("Publish called with arg {}", model);
91         dmaapProducerReactiveHttpClient = resolveClient();
92
93         return Mono.just(model)
94                 .cache()
95                 .flatMap(m -> publishFile(m, contextMap)) //
96                 .flatMap(httpStatus -> handleHttpResponse(httpStatus, model, contextMap)) //
97                 .retryBackoff(numRetries, firstBackoff);
98     }
99
100     private Mono<HttpStatus> publishFile(ConsumerDmaapModel consumerDmaapModel, Map<String, String> contextMap) {
101         logger.trace("Entering publishFile with {}", consumerDmaapModel);
102         try {
103             HttpPut put = new HttpPut();
104             String requestId = MDC.get(REQUEST_ID);
105             put.addHeader(X_ONAP_REQUEST_ID, requestId);
106             String invocationId = UUID.randomUUID().toString();
107             put.addHeader(X_INVOCATION_ID, invocationId);
108
109             prepareHead(consumerDmaapModel, put);
110             prepareBody(consumerDmaapModel, put);
111             dmaapProducerReactiveHttpClient.addUserCredentialsToHead(put);
112
113             HttpResponse response =
114                     dmaapProducerReactiveHttpClient.getDmaapProducerResponseWithRedirect(put, contextMap);
115             logger.trace(response.toString());
116             return Mono.just(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
117         } catch (Exception e) {
118             logger.warn("Unable to send file to DataRouter. Data: {}", consumerDmaapModel.getInternalLocation(), e);
119             return Mono.error(e);
120         }
121     }
122
123     private void prepareHead(ConsumerDmaapModel model, HttpPut put) {
124         put.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
125         JsonElement metaData = new JsonParser().parse(CommonFunctions.createJsonBody(model));
126         metaData.getAsJsonObject().remove(NAME_JSON_TAG).getAsString();
127         metaData.getAsJsonObject().remove(INTERNAL_LOCATION_JSON_TAG);
128         put.addHeader(X_DMAAP_DR_META, metaData.toString());
129         put.setURI(getPublishUri(model.getName()));
130     }
131
132     private void prepareBody(ConsumerDmaapModel model, HttpPut put) throws IOException {
133         Path fileLocation = model.getInternalLocation();
134         try (InputStream fileInputStream = createInputStream(fileLocation)) {
135             put.setEntity(new ByteArrayEntity(IOUtils.toByteArray(fileInputStream)));
136         }
137     }
138
139     private URI getPublishUri(String fileName) {
140         return dmaapProducerReactiveHttpClient.getBaseUri() //
141                 .pathSegment(PUBLISH_TOPIC) //
142                 .pathSegment(DEFAULT_FEED_ID) //
143                 .pathSegment(fileName).build();
144     }
145
146     private Mono<ConsumerDmaapModel> handleHttpResponse(HttpStatus response, ConsumerDmaapModel model,
147             Map<String, String> contextMap) {
148         MdcVariables.setMdcContextMap(contextMap);
149         if (HttpUtils.isSuccessfulResponseCode(response.value())) {
150             logger.trace("Publish to DR successful!");
151             return Mono.just(model);
152         } else {
153             logger.warn("Publish to DR unsuccessful, response code: {}", response);
154             return Mono.error(new Exception("Publish to DR unsuccessful, response code: " + response));
155         }
156     }
157
158     InputStream createInputStream(Path filePath) throws IOException {
159         FileSystemResource realResource = new FileSystemResource(filePath);
160         return realResource.getInputStream();
161     }
162
163     DmaapPublisherConfiguration resolveConfiguration() {
164         return datafileAppConfig.getDmaapPublisherConfiguration();
165     }
166
167     DmaapProducerReactiveHttpClient resolveClient() {
168         return new DmaapProducerReactiveHttpClient(resolveConfiguration());
169     }
170 }