b861653a46f46e414676bca0794bf4eb09abcddf
[dcaegen2/collectors/datafile.git] /
1 /*
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.onap.dcaegen2.collectors.datafile.tasks;
18
19 import java.io.File;
20 import java.net.URI;
21
22 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
23 import org.onap.dcaegen2.collectors.datafile.configuration.Config;
24 import org.onap.dcaegen2.collectors.datafile.configuration.FtpesConfig;
25 import org.onap.dcaegen2.collectors.datafile.ftp.FileCollectClient;
26 import org.onap.dcaegen2.collectors.datafile.ftp.FileCollectResult;
27 import org.onap.dcaegen2.collectors.datafile.ftp.FileServerData;
28 import org.onap.dcaegen2.collectors.datafile.ftp.FtpsClient;
29 import org.onap.dcaegen2.collectors.datafile.ftp.ImmutableFileServerData;
30 import org.onap.dcaegen2.collectors.datafile.ftp.SftpClient;
31 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
32 import org.onap.dcaegen2.collectors.datafile.model.FileData;
33 import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.stereotype.Component;
38
39 import reactor.core.publisher.Flux;
40
41 /**
42  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
43  */
44 @Component
45 public class XnfCollectorTaskImpl implements XnfCollectorTask {
46
47     private static final String FTPES = "ftpes";
48     private static final String FTPS = "ftps";
49     private static final String SFTP = "sftp";
50
51     private static final Logger logger = LoggerFactory.getLogger(XnfCollectorTaskImpl.class);
52     private Config datafileAppConfig;
53
54     private final FtpsClient ftpsClient;
55     private final SftpClient sftpClient;
56     private RetryTimer retryTimer;
57
58     @Autowired
59     protected XnfCollectorTaskImpl(AppConfig datafileAppConfig, FtpsClient ftpsCleint, SftpClient sftpClient) {
60         this.datafileAppConfig = datafileAppConfig;
61         this.ftpsClient = ftpsCleint;
62         this.sftpClient = sftpClient;
63     }
64
65     @Override
66     public Flux<ConsumerDmaapModel> execute(FileData fileData) {
67         logger.trace("Entering execute with {}", fileData);
68         resolveKeyStore();
69
70         String localFile = collectFile(fileData);
71
72         if (localFile != null) {
73             ConsumerDmaapModel consumerDmaapModel = getConsumerDmaapModel(fileData, localFile);
74             logger.trace("Exiting execute with {}", consumerDmaapModel);
75             return Flux.just(consumerDmaapModel);
76         }
77         logger.trace("Exiting execute with empty");
78         return Flux.empty();
79     }
80
81     @Override
82     public FtpesConfig resolveConfiguration() {
83         return datafileAppConfig.getFtpesConfiguration();
84     }
85
86     private void resolveKeyStore() {
87         FtpesConfig ftpesConfig = resolveConfiguration();
88         ftpsClient.setKeyCertPath(ftpesConfig.keyCert());
89         ftpsClient.setKeyCertPassword(ftpesConfig.keyPassword());
90         ftpsClient.setTrustedCAPath(ftpesConfig.trustedCA());
91         ftpsClient.setTrustedCAPassword(ftpesConfig.trustedCAPassword());
92     }
93
94     private String collectFile(FileData fileData) {
95         logger.trace("starting to collectFile");
96         String location = fileData.location();
97         URI uri = URI.create(location);
98         FileServerData fileServerData = getFileServerData(uri);
99         String remoteFile = uri.getPath();
100         String localFile = "target" + File.separator + fileData.name();
101
102         FileCollectClient currentClient = selectClient(fileData, uri);
103
104         if (currentClient != null) {
105             FileCollectResult fileCollectResult = currentClient.collectFile(fileServerData, remoteFile, localFile);
106             if (!fileCollectResult.downloadSuccessful()) {
107                 fileCollectResult = retry(fileCollectResult, currentClient);
108             }
109             if (!fileCollectResult.downloadSuccessful()) {
110                 localFile = null;
111                 logger.error("Download of file aborted after maximum number of retries. Data: {} Error causes {}",
112                         fileServerData, fileCollectResult.getErrorData());
113             }
114         } else {
115             localFile = null;
116         }
117         return localFile;
118     }
119
120     private FileServerData getFileServerData(URI uri) {
121         String[] userInfo = getUserNameAndPasswordIfGiven(uri.getUserInfo());
122         // @formatter:off
123         return ImmutableFileServerData.builder()
124                 .serverAddress(uri.getHost())
125                 .userId(userInfo != null ? userInfo[0] : "")
126                 .password(userInfo != null ? userInfo[1] : "")
127                 .port(uri.getPort())
128                 .build();
129         // @formatter:on
130     }
131
132     private String[] getUserNameAndPasswordIfGiven(String userInfoString) {
133         String[] userInfo = null;
134         if (userInfoString != null && !userInfoString.isEmpty()) {
135             userInfo = userInfoString.split(":");
136         }
137         return userInfo;
138     }
139
140     private FileCollectClient selectClient(FileData fileData, URI uri) {
141         FileCollectClient selectedClient = null;
142         String scheme = uri.getScheme();
143         if (FTPES.equals(scheme) || FTPS.equals(scheme)) {
144             selectedClient = ftpsClient;
145         } else if (SFTP.equals(scheme)) {
146             selectedClient = sftpClient;
147         } else {
148             logger.error("DFC does not support protocol {}. Supported protocols are {}, {}, and {}. Data: {}", scheme,
149                     FTPES, FTPS, SFTP, fileData);
150         }
151         return selectedClient;
152     }
153
154     private FileCollectResult retry(FileCollectResult fileCollectResult, FileCollectClient fileCollectClient) {
155         int retryCount = 1;
156         FileCollectResult newResult = fileCollectResult;
157         while (!newResult.downloadSuccessful() && retryCount++ < 3) {
158             getRetryTimer().waitRetryTime();
159             newResult = fileCollectClient.retryCollectFile();
160         }
161         return newResult;
162     }
163
164     private ConsumerDmaapModel getConsumerDmaapModel(FileData fileData, String localFile) {
165         String productName = fileData.fileMetaData().productName();
166         String vendorName = fileData.fileMetaData().vendorName();
167         String lastEpochMicrosec = fileData.fileMetaData().lastEpochMicrosec();
168         String sourceName = fileData.fileMetaData().sourceName();
169         String startEpochMicrosec = fileData.fileMetaData().startEpochMicrosec();
170         String timeZoneOffset = fileData.fileMetaData().timeZoneOffset();
171         String name = fileData.name();
172         String location = fileData.location();
173         String internalLocation = localFile;
174         String compression = fileData.compression();
175         String fileFormatType = fileData.fileFormatType();
176         String fileFormatVersion = fileData.fileFormatVersion();
177
178         // @formatter:off
179         return ImmutableConsumerDmaapModel.builder()
180                 .productName(productName)
181                 .vendorName(vendorName)
182                 .lastEpochMicrosec(lastEpochMicrosec)
183                 .sourceName(sourceName)
184                 .startEpochMicrosec(startEpochMicrosec)
185                 .timeZoneOffset(timeZoneOffset)
186                 .name(name)
187                 .location(location)
188                 .internalLocation(internalLocation)
189                 .compression(compression)
190                 .fileFormatType(fileFormatType)
191                 .fileFormatVersion(fileFormatVersion)
192                 .build();
193         // @formatter:on
194     }
195
196     private RetryTimer getRetryTimer() {
197         if (retryTimer == null) {
198             retryTimer = new RetryTimer();
199         }
200         return retryTimer;
201     }
202
203     protected void setRetryTimer(RetryTimer retryTimer) {
204         this.retryTimer = retryTimer;
205     }
206 }