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