Merge "Added support for using oauth token for Kafka"
[nonrtric/plt/ranpm.git] / datafilecollector / src / main / java / org / onap / dcaegen2 / collectors / datafile / ftp / SftpClient.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018-2019 Nordix Foundation, 2020 Nokia. 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.ftp;
18
19 import com.jcraft.jsch.Channel;
20 import com.jcraft.jsch.ChannelSftp;
21 import com.jcraft.jsch.JSch;
22 import com.jcraft.jsch.JSchException;
23 import com.jcraft.jsch.Session;
24 import com.jcraft.jsch.SftpException;
25
26 import java.nio.file.Path;
27
28 import org.onap.dcaegen2.collectors.datafile.commons.FileCollectClient;
29 import org.onap.dcaegen2.collectors.datafile.commons.FileServerData;
30 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
31 import org.onap.dcaegen2.collectors.datafile.exceptions.NonRetryableDatafileTaskException;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * Gets file from xNF with SFTP protocol.
37  *
38  * @author <a href="mailto:martin.c.yan@est.tech">Martin Yan</a>
39  */
40 public class SftpClient implements FileCollectClient {
41
42     private static final Logger logger = LoggerFactory.getLogger(SftpClient.class);
43
44     private static final int SFTP_DEFAULT_PORT = 22;
45     private static final String STRICT_HOST_KEY_CHECKING = "StrictHostKeyChecking";
46
47     private final FileServerData fileServerData;
48     protected Session session = null;
49     protected ChannelSftp sftpChannel = null;
50     private final SftpClientSettings settings;
51
52     public SftpClient(FileServerData fileServerData, SftpClientSettings sftpConfig) {
53         this.fileServerData = fileServerData;
54         this.settings = sftpConfig;
55     }
56
57     @Override
58     public void collectFile(String remoteFile, Path localFile) throws DatafileTaskException {
59         logger.trace("collectFile {}", localFile);
60
61         try {
62             sftpChannel.get(remoteFile, localFile.toString());
63             logger.trace("File {} Download successful from xNF", localFile.getFileName());
64         } catch (SftpException e) {
65             boolean retry = e.id != ChannelSftp.SSH_FX_NO_SUCH_FILE && e.id != ChannelSftp.SSH_FX_PERMISSION_DENIED
66                 && e.id != ChannelSftp.SSH_FX_OP_UNSUPPORTED;
67             if (retry) {
68                 throw new DatafileTaskException("Unable to get file from xNF. Data: " + fileServerData, e);
69             } else {
70                 throw new NonRetryableDatafileTaskException(
71                     "Unable to get file from xNF. No retry attempts will be done. Data: " + fileServerData, e);
72             }
73         }
74
75         logger.trace("collectFile OK");
76     }
77
78     @Override
79     public void close() {
80         logger.trace("closing sftp session");
81         if (sftpChannel != null) {
82             sftpChannel.exit();
83             sftpChannel = null;
84         }
85         if (session != null) {
86             session.disconnect();
87             session = null;
88         }
89     }
90
91     @Override
92     public void open() throws DatafileTaskException {
93         try {
94             if (session == null) {
95                 session = setUpSession(fileServerData);
96                 sftpChannel = getChannel(session);
97             }
98         } catch (JSchException e) {
99             boolean retry = !e.getMessage().contains("Auth fail");
100             if (retry) {
101                 throw new DatafileTaskException("Could not open Sftp client. " + e);
102             } else {
103                 throw new NonRetryableDatafileTaskException(
104                     "Could not open Sftp client, no retry attempts will be done. " + e);
105             }
106         }
107     }
108
109     JSch createJsch() {
110         return new JSch();
111     }
112
113     private int getPort(Integer port) {
114         return port != null ? port : SFTP_DEFAULT_PORT;
115     }
116
117     private Session setUpSession(FileServerData fileServerData) throws JSchException {
118         boolean useStrictHostChecking = this.settings.shouldUseStrictHostChecking();
119         JSch jsch = createJschClient(useStrictHostChecking);
120         return createJshSession(jsch, fileServerData, useStrictHostChecking);
121     }
122
123     private JSch createJschClient(boolean useStrictHostChecking) throws JSchException {
124         JSch jsch = createJsch();
125         if (useStrictHostChecking) {
126             jsch.setKnownHosts(this.settings.getKnownHostsFilePath());
127         }
128         return jsch;
129     }
130
131     private Session createJshSession(JSch jsch, FileServerData fileServerData, boolean useStrictHostKeyChecking)
132         throws JSchException {
133         Session newSession =
134             jsch.getSession(fileServerData.userId, fileServerData.serverAddress, getPort(fileServerData.port));
135         newSession.setConfig(STRICT_HOST_KEY_CHECKING, toYesNo(useStrictHostKeyChecking));
136         newSession.setPassword(fileServerData.password);
137         newSession.connect();
138         return newSession;
139     }
140
141     private String toYesNo(boolean useStrictHostKeyChecking) {
142         return useStrictHostKeyChecking ? "yes" : "no";
143     }
144
145     private ChannelSftp getChannel(Session session) throws JSchException {
146         Channel channel = session.openChannel("sftp");
147         channel.connect();
148         return (ChannelSftp) channel;
149     }
150
151 }