3546a08f33c2ca2636d4b7c8c0e7c523f6a652ad
[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 com.google.gson.JsonElement;
24 import com.google.gson.JsonParser;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.net.URI;
28 import java.nio.file.Path;
29 import java.time.Duration;
30 import java.util.Map;
31 import org.apache.commons.io.IOUtils;
32 import org.apache.http.HttpResponse;
33 import org.apache.http.client.methods.HttpPut;
34 import org.apache.http.entity.ByteArrayEntity;
35 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
36 import org.onap.dcaegen2.collectors.datafile.model.CommonFunctions;
37 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
38 import org.onap.dcaegen2.collectors.datafile.model.logging.MappedDiagnosticContext;
39 import org.onap.dcaegen2.collectors.datafile.service.HttpUtils;
40 import org.onap.dcaegen2.collectors.datafile.service.producer.DmaapProducerHttpClient;
41 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.slf4j.MDC;
45 import org.springframework.core.io.FileSystemResource;
46 import org.springframework.http.HttpHeaders;
47 import org.springframework.http.HttpStatus;
48 import reactor.core.publisher.Mono;
49
50 /**
51  * Publishes a file to the DataRouter.
52  *
53  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/13/18
54  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
55  */
56 public class DataRouterPublisher {
57     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
58     private static final String CONTENT_TYPE = "application/octet-stream";
59     private static final String NAME_JSON_TAG = "name";
60     private static final String INTERNAL_LOCATION_JSON_TAG = "internalLocation";
61     private static final String PUBLISH_TOPIC = "publish";
62     private static final String DEFAULT_FEED_ID = "1";
63
64     private static final Logger logger = LoggerFactory.getLogger(DataRouterPublisher.class);
65     private final AppConfig datafileAppConfig;
66     private DmaapProducerHttpClient dmaapProducerReactiveHttpClient;
67
68     public DataRouterPublisher(AppConfig datafileAppConfig) {
69         this.datafileAppConfig = datafileAppConfig;
70     }
71
72
73     /**
74      * Publish one file.
75      *
76      * @param model information about the file to publish
77      * @param numRetries the maximal number of retries if the publishing fails
78      * @param firstBackoff the time to delay the first retry
79      * @param contextMap tracing context variables
80      * @return the (same) ConsumerDmaapModel
81      */
82     public Mono<ConsumerDmaapModel> execute(ConsumerDmaapModel model, long numRetries, Duration firstBackoff,
83             Map<String, String> contextMap) {
84         MDC.setContextMap(contextMap);
85         logger.trace("Publish called with arg {}", model);
86         dmaapProducerReactiveHttpClient = resolveClient();
87
88         return Mono.just(model)
89                 .cache()
90                 .flatMap(m -> publishFile(m, contextMap)) //
91                 .flatMap(httpStatus -> handleHttpResponse(httpStatus, model, contextMap)) //
92                 .retryBackoff(numRetries, firstBackoff);
93     }
94
95     private Mono<HttpStatus> publishFile(ConsumerDmaapModel consumerDmaapModel, Map<String, String> contextMap) {
96         logger.trace("Entering publishFile with {}", consumerDmaapModel);
97         try {
98             HttpPut put = new HttpPut();
99             prepareHead(consumerDmaapModel, put);
100             prepareBody(consumerDmaapModel, put);
101             dmaapProducerReactiveHttpClient.addUserCredentialsToHead(put);
102
103             HttpResponse response =
104                     dmaapProducerReactiveHttpClient.getDmaapProducerResponseWithRedirect(put, contextMap);
105             logger.trace("{}", response);
106             return Mono.just(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
107         } catch (Exception e) {
108             logger.warn("Unable to send file to DataRouter. Data: {}", consumerDmaapModel.getInternalLocation(), e);
109             return Mono.error(e);
110         }
111     }
112
113     private void prepareHead(ConsumerDmaapModel model, HttpPut put) {
114         put.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
115         JsonElement metaData = new JsonParser().parse(CommonFunctions.createJsonBody(model));
116         metaData.getAsJsonObject().remove(NAME_JSON_TAG).getAsString();
117         metaData.getAsJsonObject().remove(INTERNAL_LOCATION_JSON_TAG);
118         put.addHeader(X_DMAAP_DR_META, metaData.toString());
119         put.setURI(getPublishUri(model.getName()));
120         MappedDiagnosticContext.appendTraceInfo(put);
121     }
122
123     private void prepareBody(ConsumerDmaapModel model, HttpPut put) throws IOException {
124         Path fileLocation = model.getInternalLocation();
125         try (InputStream fileInputStream = createInputStream(fileLocation)) {
126             put.setEntity(new ByteArrayEntity(IOUtils.toByteArray(fileInputStream)));
127         }
128     }
129
130     private URI getPublishUri(String fileName) {
131         return dmaapProducerReactiveHttpClient.getBaseUri() //
132                 .pathSegment(PUBLISH_TOPIC) //
133                 .pathSegment(DEFAULT_FEED_ID) //
134                 .pathSegment(fileName).build();
135     }
136
137     private Mono<ConsumerDmaapModel> handleHttpResponse(HttpStatus response, ConsumerDmaapModel model,
138             Map<String, String> contextMap) {
139         MDC.setContextMap(contextMap);
140         if (HttpUtils.isSuccessfulResponseCode(response.value())) {
141             logger.trace("Publish to DR successful!");
142             return Mono.just(model);
143         } else {
144             logger.warn("Publish to DR unsuccessful, response code: {}", response);
145             return Mono.error(new Exception("Publish to DR unsuccessful, response code: " + response));
146         }
147     }
148
149     InputStream createInputStream(Path filePath) throws IOException {
150         FileSystemResource realResource = new FileSystemResource(filePath);
151         return realResource.getInputStream();
152     }
153
154     DmaapPublisherConfiguration resolveConfiguration() {
155         return datafileAppConfig.getDmaapPublisherConfiguration();
156     }
157
158     DmaapProducerHttpClient resolveClient() {
159         return new DmaapProducerHttpClient(resolveConfiguration());
160     }
161 }