SshConnectionSshd - Sonar Fix
[appc.git] / appc-adapters / appc-ssh-adapter / appc-ssh-adapter-sshd / src / main / java / org / onap / appc / adapter / ssh / sshd / SshConnectionSshd.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.adapter.ssh.sshd;
25
26 import org.apache.sshd.client.channel.ClientChannelEvent;
27 import org.onap.appc.adapter.ssh.Constants;
28 import org.onap.appc.adapter.ssh.SshConnection;
29 import org.onap.appc.adapter.ssh.SshException;
30 import org.onap.appc.encryption.EncryptionTool;
31 import org.onap.appc.configuration.Configuration;
32 import org.onap.appc.configuration.ConfigurationFactory;
33 import org.apache.sshd.client.session.ClientSession;
34 import org.apache.sshd.client.SshClient;
35 import org.apache.sshd.client.channel.ChannelExec;
36 import org.apache.sshd.client.future.AuthFuture;
37 import org.apache.sshd.client.future.OpenFuture;
38 import org.apache.sshd.common.keyprovider.KeyPairProvider;
39 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
40
41 import com.att.eelf.configuration.EELFLogger;
42 import com.att.eelf.configuration.EELFManager;
43
44 import java.io.File;
45 import java.io.OutputStream;
46 import java.security.KeyPair;
47 import java.util.Arrays;
48
49 /**
50  * Implementation of SshConnection interface based on Apache MINA SSHD library.
51  */
52 class SshConnectionSshd implements SshConnection {
53
54     private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
55
56     private static final long AUTH_TIMEOUT = 60000;
57     private static final long EXEC_TIMEOUT = 120000;
58
59     private String host;
60     private int port;
61     private String username;
62     private String password;
63     private long timeout = EXEC_TIMEOUT;
64     private String keyFile;
65     private SshClient sshClient;
66     private ClientSession clientSession;
67     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
68
69     public SshConnectionSshd(String host, int port, String username, String password, String keyFile) {
70         this.host = host;
71         this.port = port;
72         this.username = username;
73         this.password = password;
74         this.keyFile = keyFile;
75     }
76
77     public SshConnectionSshd(String host, int port, String username, String password) {
78         this(host, port, username, password, null);
79     }
80
81     public SshConnectionSshd(String host, int port, String keyFile) {
82         this(host, port, null, null, keyFile);
83     }
84
85     @Override
86     public void connect() {
87         sshClient = SshClient.setUpDefaultClient();
88         sshClient.start();
89         try {
90             clientSession =
91                 sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).verify().getSession();
92             if (password != null) {
93                 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
94             } else if (keyFile != null) {
95                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(
96                         new File(keyFile).toPath()
97                 );
98                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
99                 clientSession.addPublicKeyIdentity(keyPair);
100             }
101             AuthFuture authFuture = clientSession.auth();
102             authFuture.await(AUTH_TIMEOUT);
103             if (!authFuture.isSuccess()) {
104                 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
105                     + "]. Authentication failed.");
106             }
107         } catch (RuntimeException e) {
108             throw e;
109         } catch (Exception e) {
110             throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
111                 e);
112         }
113         if (logger.isDebugEnabled()) {
114             logger.debug("SSH: connected to [" + toString() + "]");
115         }
116     }
117
118     @Override
119     public void connectWithRetry() {
120         int retryCount ;
121         int retryDelay ;
122         int retriesLeft;
123         retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT,
124             Constants.DEFAULT_CONNECTION_RETRY_COUNT);
125         retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY,
126             Constants.DEFAULT_CONNECTION_RETRY_DELAY);
127         retriesLeft = retryCount + 1;
128         do {
129             try {
130                 this.connect();
131                 break;
132             } catch (RuntimeException e) {
133                 if (retriesLeft > 1) {
134                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
135                     waitForConnection(retryDelay);
136                     retriesLeft--;
137                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
138                         + "] out of [" + retryCount + "]");
139                 } else {
140                     throw e;
141                 }
142           }
143         } while (retriesLeft > 0);
144     }
145
146     @Override
147     public void disconnect() {
148         try {
149             if (logger.isDebugEnabled()) {
150                 logger.debug("SSH: disconnecting from [" + toString() + "]");
151             }
152             clientSession.close(false);
153         } finally {
154             if (sshClient != null) {
155                 sshClient.stop();
156             }
157         }
158     }
159
160     @Override
161     public void setExecTimeout(long timeout) {
162         this.timeout = timeout;
163     }
164
165     @Override
166     public int execCommand(String cmd, OutputStream out, OutputStream err) {
167         return execCommand(cmd, out, err, false);
168     }
169
170     @Override
171     public int execCommandWithPty(String cmd, OutputStream out) {
172         return execCommand(cmd, out, out, true);
173     }
174
175     private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
176         try(ChannelExec client = clientSession.createExecChannel(cmd)) {
177             if (logger.isDebugEnabled()) {
178                 logger.debug("SSH: executing command");
179             }
180             client.setUsePty(usePty); // use pseudo-tty?
181             client.setOut(out);
182             client.setErr(err);
183             OpenFuture openFuture = client.open();
184             int exitStatus;
185             client.waitFor(Arrays.asList(ClientChannelEvent.CLOSED), timeout);
186             openFuture.verify();
187             Integer exitStatusI = client.getExitStatus();
188             if (exitStatusI == null) {
189                 throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]. Operation timed out.");
190             }
191             exitStatus = exitStatusI;
192             return exitStatus;
193         } catch (RuntimeException e) {
194             throw e;
195         } catch (Exception e1) {
196             throw new SshException(
197                 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
198         }
199     }
200
201     private void waitForConnection(int retryDelay) {
202         long time = retryDelay * 1000L;
203         long future = System.currentTimeMillis() + time;
204         if (time != 0) {
205             while (System.currentTimeMillis() < future && time > 0) {
206                 try {
207                     Thread.sleep(time);
208                 } catch (InterruptedException e) {
209                     /*
210                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
211                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
212                      * amount of delay time needed and reenter the sleep until we get to the future time.
213                      */
214                     time = future - System.currentTimeMillis();
215                 }
216             }
217         }
218     }
219
220     @Override
221     public String toString() {
222         String address = host;
223         if (username != null) {
224             address = username + '@' + address;
225         }
226         return address;
227     }
228 }