cfaf1753eca2abfaffea70386f86cd6a82ee3c3b
[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.File;
27 import java.net.MalformedURLException;
28 import java.net.URI;
29 import java.nio.file.Path;
30 import java.time.Duration;
31
32 import org.apache.http.HttpResponse;
33 import org.apache.http.client.methods.HttpPut;
34 import org.apache.http.entity.ContentType;
35 import org.apache.http.entity.FileEntity;
36 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
37 import org.onap.dcaegen2.collectors.datafile.configuration.PublisherConfiguration;
38 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
39 import org.onap.dcaegen2.collectors.datafile.model.Counters;
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 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
65     private static final Logger logger = LoggerFactory.getLogger(DataRouterPublisher.class);
66     private final AppConfig datafileAppConfig;
67     private final Counters counters;
68
69     public DataRouterPublisher(AppConfig datafileAppConfig, Counters counters) {
70         this.datafileAppConfig = datafileAppConfig;
71         this.counters = counters;
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         return Mono.just(publishInfo) //
86             .cache() //
87             .flatMap(this::publishFile) //
88             .flatMap(httpStatus -> handleHttpResponse(httpStatus, publishInfo)) //
89             .retryBackoff(numRetries, firstBackoff);
90     }
91
92     private Mono<HttpStatus> publishFile(FilePublishInformation publishInfo) {
93         MDC.setContextMap(publishInfo.getContext());
94         logger.trace("Entering publishFile with {}", publishInfo);
95         try {
96             DmaapProducerHttpClient dmaapProducerHttpClient = resolveClient(publishInfo.getChangeIdentifier());
97             HttpPut put = new HttpPut();
98             prepareHead(publishInfo, put);
99             prepareBody(publishInfo, put);
100             dmaapProducerHttpClient.addUserCredentialsToHead(put);
101
102             HttpResponse response =
103                 dmaapProducerHttpClient.getDmaapProducerResponseWithRedirect(put, publishInfo.getContext());
104             logger.trace("{}", response);
105             return Mono.just(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
106         } catch (Exception e) {
107             counters.incNoOfFailedPublishAttempts();
108             logger.warn("Publishing file {} to DR unsuccessful.", publishInfo.getName(), e);
109             return Mono.error(e);
110         }
111     }
112
113     private void prepareHead(FilePublishInformation publishInfo, HttpPut put) throws DatafileTaskException {
114
115         put.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
116         JsonElement metaData = new JsonParser().parse(JsonSerializer.createJsonBodyForDataRouter(publishInfo));
117         put.addHeader(X_DMAAP_DR_META, metaData.toString());
118         URI uri = new DefaultUriBuilderFactory(
119             datafileAppConfig.getPublisherConfiguration(publishInfo.getChangeIdentifier()).publishUrl()) //
120                 .builder() //
121                 .pathSegment(publishInfo.getName()) //
122                 .build();
123         put.setURI(uri);
124
125         MappedDiagnosticContext.appendTraceInfo(put);
126     }
127
128     private void prepareBody(FilePublishInformation publishInfo, HttpPut put) {
129         File file = createInputFile(publishInfo.getInternalLocation());
130         FileEntity entity = new FileEntity(file, ContentType.DEFAULT_BINARY);
131         put.setEntity(entity);
132     }
133
134     private Mono<FilePublishInformation> handleHttpResponse(HttpStatus response, FilePublishInformation publishInfo) {
135         MDC.setContextMap(publishInfo.getContext());
136         if (HttpUtils.isSuccessfulResponseCode(response.value())) {
137             counters.incTotalPublishedFiles();
138             logger.trace("Publishing file {} to DR successful!", publishInfo.getName());
139             return Mono.just(publishInfo);
140         } else {
141             counters.incNoOfFailedPublishAttempts();
142             logger.warn("Publishing file {} to DR unsuccessful. Response code: {}", publishInfo.getName(), response);
143             return Mono.error(new Exception(
144                 "Publishing file " + publishInfo.getName() + " to DR unsuccessful. Response code: " + response));
145         }
146     }
147
148     File createInputFile(Path filePath) {
149         FileSystemResource realResource = new FileSystemResource(filePath);
150         return realResource.getFile();
151     }
152
153     PublisherConfiguration resolveConfiguration(String changeIdentifer) throws DatafileTaskException {
154         return datafileAppConfig.getPublisherConfiguration(changeIdentifer);
155     }
156
157     DmaapProducerHttpClient resolveClient(String changeIdentifier) throws DatafileTaskException {
158         try {
159             DmaapPublisherConfiguration cfg = resolveConfiguration(changeIdentifier).toDmaap();
160             return new DmaapProducerHttpClient(cfg);
161         } catch (MalformedURLException e) {
162             throw new DatafileTaskException("Cannot resolve producer client", e);
163         }
164
165     }
166 }