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