05f04b30294df5c6eee9d2178c48f07a2613e1af
[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.CommonFunctions;
38 import org.onap.dcaegen2.collectors.datafile.model.FilePublishInformation;
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 NAME_JSON_TAG = "name";
62     private static final String INTERNAL_LOCATION_JSON_TAG = "internalLocation";
63     private static final String PUBLISH_TOPIC = "publish";
64     private static final String DEFAULT_FEED_ID = "1";
65
66     private static final Logger logger = LoggerFactory.getLogger(DataRouterPublisher.class);
67     private final AppConfig datafileAppConfig;
68     private DmaapProducerHttpClient dmaapProducerReactiveHttpClient;
69
70     public DataRouterPublisher(AppConfig datafileAppConfig) {
71         this.datafileAppConfig = datafileAppConfig;
72     }
73
74     /**
75      * Publish one file.
76      *
77      * @param publishInfo information about the file to publish
78      * @param numRetries the maximal number of retries if the publishing fails
79      * @param firstBackoff the time to delay the first retry
80      * @return the (same) filePublishInformation
81      */
82     public Mono<FilePublishInformation> publishFile(FilePublishInformation publishInfo, long numRetries,
83             Duration firstBackoff) {
84         MDC.setContextMap(publishInfo.getContext());
85         logger.trace("publishFile called with arg {}", publishInfo);
86         dmaapProducerReactiveHttpClient = resolveClient();
87
88         return Mono.just(publishInfo) //
89                 .cache() //
90                 .flatMap(this::publishFile) //
91                 .flatMap(httpStatus -> handleHttpResponse(httpStatus, publishInfo)) //
92                 .retryBackoff(numRetries, firstBackoff);
93     }
94
95     private Mono<HttpStatus> publishFile(FilePublishInformation publishInfo
96             ) {
97         logger.trace("Entering publishFile with {}", publishInfo);
98         try {
99             HttpPut put = new HttpPut();
100             prepareHead(publishInfo, put);
101             prepareBody(publishInfo, put);
102             dmaapProducerReactiveHttpClient.addUserCredentialsToHead(put);
103
104             HttpResponse response =
105                     dmaapProducerReactiveHttpClient.getDmaapProducerResponseWithRedirect(put, publishInfo.getContext());
106             logger.trace("{}", response);
107             return Mono.just(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
108         } catch (Exception e) {
109             logger.warn("Unable to send file to DataRouter. Data: {}", publishInfo.getInternalLocation(), e);
110             return Mono.error(e);
111         }
112     }
113
114     private void prepareHead(FilePublishInformation publishInfo, HttpPut put) {
115         put.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
116         JsonElement metaData = new JsonParser().parse(CommonFunctions.createJsonBody(publishInfo));
117         metaData.getAsJsonObject().remove(NAME_JSON_TAG).getAsString();
118         metaData.getAsJsonObject().remove(INTERNAL_LOCATION_JSON_TAG);
119         put.addHeader(X_DMAAP_DR_META, metaData.toString());
120         put.setURI(getPublishUri(publishInfo.getName()));
121         MappedDiagnosticContext.appendTraceInfo(put);
122     }
123
124     private void prepareBody(FilePublishInformation publishInfo, HttpPut put) throws IOException {
125         Path fileLocation = publishInfo.getInternalLocation();
126         try (InputStream fileInputStream = createInputStream(fileLocation)) {
127             put.setEntity(new ByteArrayEntity(IOUtils.toByteArray(fileInputStream)));
128         }
129     }
130
131     private URI getPublishUri(String fileName) {
132         return dmaapProducerReactiveHttpClient.getBaseUri() //
133                 .pathSegment(PUBLISH_TOPIC) //
134                 .pathSegment(DEFAULT_FEED_ID) //
135                 .pathSegment(fileName).build();
136     }
137
138     private Mono<FilePublishInformation> handleHttpResponse(HttpStatus response, FilePublishInformation publishInfo) {
139         MDC.setContextMap(publishInfo.getContext());
140         if (HttpUtils.isSuccessfulResponseCode(response.value())) {
141             logger.trace("Publish to DR successful!");
142             return Mono.just(publishInfo);
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 }