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