1d6baa65f8a5fd4d78ac536b335f224bdca3f68e
[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.MalformedURLException;
29 import java.net.URI;
30 import java.nio.file.Path;
31 import java.time.Duration;
32
33 import org.apache.commons.io.IOUtils;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.client.methods.HttpPut;
36 import org.apache.http.entity.ByteArrayEntity;
37 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
38 import org.onap.dcaegen2.collectors.datafile.configuration.PublisherConfiguration;
39 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
40 import org.onap.dcaegen2.collectors.datafile.model.FilePublishInformation;
41 import org.onap.dcaegen2.collectors.datafile.model.JsonSerializer;
42 import org.onap.dcaegen2.collectors.datafile.model.logging.MappedDiagnosticContext;
43 import org.onap.dcaegen2.collectors.datafile.service.HttpUtils;
44 import org.onap.dcaegen2.collectors.datafile.service.producer.DmaapProducerHttpClient;
45 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.slf4j.MDC;
49 import org.springframework.core.io.FileSystemResource;
50 import org.springframework.http.HttpHeaders;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.web.util.DefaultUriBuilderFactory;
53
54 import reactor.core.publisher.Mono;
55
56 /**
57  * Publishes a file to the DataRouter.
58  *
59  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/13/18
60  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
61  */
62 public class DataRouterPublisher {
63     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
64     private static final String CONTENT_TYPE = "application/octet-stream";
65
66     private static final Logger logger = LoggerFactory.getLogger(DataRouterPublisher.class);
67     private final AppConfig datafileAppConfig;
68
69     public DataRouterPublisher(AppConfig datafileAppConfig) {
70         this.datafileAppConfig = datafileAppConfig;
71     }
72
73     /**
74      * Publish one file.
75      *
76      * @param publishInfo 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      * @return the (same) filePublishInformation
80      */
81     public Mono<FilePublishInformation> publishFile(FilePublishInformation publishInfo, long numRetries,
82             Duration firstBackoff) {
83         MDC.setContextMap(publishInfo.getContext());
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             DmaapProducerHttpClient dmaapProducerHttpClient = resolveClient(publishInfo.getChangeIdentifier());
96             HttpPut put = new HttpPut();
97             prepareHead(publishInfo, put);
98             prepareBody(publishInfo, put);
99             dmaapProducerHttpClient.addUserCredentialsToHead(put);
100
101             HttpResponse response =
102                     dmaapProducerHttpClient.getDmaapProducerResponseWithRedirect(put, publishInfo.getContext());
103             logger.trace("{}", response);
104             return Mono.just(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
105         } catch (Exception e) {
106             logger.warn("Unable to send file to DataRouter. Data: {}", publishInfo.getInternalLocation(), e);
107             return Mono.error(e);
108         }
109     }
110
111     private void prepareHead(FilePublishInformation publishInfo, HttpPut put) throws DatafileTaskException {
112
113         put.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
114         JsonElement metaData = new JsonParser().parse(JsonSerializer.createJsonBodyForDataRouter(publishInfo));
115         put.addHeader(X_DMAAP_DR_META, metaData.toString());
116         URI uri = new DefaultUriBuilderFactory(
117                 datafileAppConfig.getPublisherConfiguration(publishInfo.getChangeIdentifier()).publishUrl()) //
118                 .builder() //
119                 .pathSegment(publishInfo.getName()) //
120                 .build();
121         put.setURI(uri);
122
123         MappedDiagnosticContext.appendTraceInfo(put);
124     }
125
126     private void prepareBody(FilePublishInformation publishInfo, HttpPut put) throws IOException {
127         Path fileLocation = publishInfo.getInternalLocation();
128         try (InputStream fileInputStream = createInputStream(fileLocation)) {
129             put.setEntity(new ByteArrayEntity(IOUtils.toByteArray(fileInputStream)));
130         }
131     }
132
133     private static Mono<FilePublishInformation> handleHttpResponse(HttpStatus response, FilePublishInformation publishInfo) {
134         MDC.setContextMap(publishInfo.getContext());
135         if (HttpUtils.isSuccessfulResponseCode(response.value())) {
136             logger.trace("Publish to DR successful!");
137             return Mono.just(publishInfo);
138         } else {
139             logger.warn("Publish to DR unsuccessful, response code: {}", response);
140             return Mono.error(new Exception("Publish to DR unsuccessful, response code: " + response));
141         }
142     }
143
144     InputStream createInputStream(Path filePath) throws IOException {
145         FileSystemResource realResource = new FileSystemResource(filePath);
146         return realResource.getInputStream();
147     }
148
149     PublisherConfiguration resolveConfiguration(String changeIdentifer) throws DatafileTaskException {
150         return datafileAppConfig.getPublisherConfiguration(changeIdentifer);
151     }
152
153     DmaapProducerHttpClient resolveClient(String changeIdentifier) throws DatafileTaskException {
154         try {
155             DmaapPublisherConfiguration cfg = resolveConfiguration(changeIdentifier).toDmaap();
156             return new DmaapProducerHttpClient(cfg);
157         } catch (MalformedURLException e) {
158             throw new DatafileTaskException("Cannot resolve producer client", e);
159         }
160
161     }
162 }