306c2ded9ef8932aa1609cfc2a94a789818639d8
[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         return ImmutableFileServerData.builder().serverAddress(uri.getHost())
123                 .userId(userInfo != null ? userInfo[0] : "").password(userInfo != null ? userInfo[1] : "")
124                 .port(uri.getPort()).build();
125     }
126
127     private String[] getUserNameAndPasswordIfGiven(String userInfoString) {
128         String[] userInfo = null;
129         if (userInfoString != null && !userInfoString.isEmpty()) {
130             userInfo = userInfoString.split(":");
131         }
132         return userInfo;
133     }
134
135     private FileCollectClient selectClient(FileData fileData, URI uri) {
136         FileCollectClient selectedClient = null;
137         String scheme = uri.getScheme();
138         if (FTPES.equals(scheme) || FTPS.equals(scheme)) {
139             selectedClient = ftpsClient;
140         } else if (SFTP.equals(scheme)) {
141             selectedClient = sftpClient;
142         } else {
143             logger.error("DFC does not support protocol {}. Supported protocols are {}, {}, and {}. Data: {}", scheme,
144                     FTPES, FTPS, SFTP, fileData);
145         }
146         return selectedClient;
147     }
148
149     private FileCollectResult retry(FileCollectResult fileCollectResult, FileCollectClient fileCollectClient) {
150         int retryCount = 1;
151         FileCollectResult newResult = fileCollectResult;
152         while (!newResult.downloadSuccessful() && retryCount++ < 3) {
153             getRetryTimer().waitRetryTime();
154             newResult = fileCollectClient.retryCollectFile();
155         }
156         return newResult;
157     }
158
159     private ConsumerDmaapModel getConsumerDmaapModel(FileData fileData, String localFile) {
160         String name = fileData.name();
161         String compression = fileData.compression();
162         String fileFormatType = fileData.fileFormatType();
163         String fileFormatVersion = fileData.fileFormatVersion();
164
165         return ImmutableConsumerDmaapModel.builder().name(name).location(localFile).compression(compression)
166                 .fileFormatType(fileFormatType).fileFormatVersion(fileFormatVersion).build();
167     }
168
169     private RetryTimer getRetryTimer() {
170         if (retryTimer == null) {
171             retryTimer = new RetryTimer();
172         }
173         return retryTimer;
174     }
175
176     protected void setRetryTimer(RetryTimer retryTimer) {
177         this.retryTimer = retryTimer;
178     }
179 }