c35c587989933c692988c7d56ca1e6be89d1c815
[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  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.ssh.sshd;
26
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.ClientChannel;
34 import org.apache.sshd.ClientSession;
35 import org.apache.sshd.SshClient;
36 import org.apache.sshd.client.channel.ChannelExec;
37 import org.apache.sshd.client.future.AuthFuture;
38 import org.apache.sshd.client.future.OpenFuture;
39 import org.apache.sshd.common.KeyPairProvider;
40 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
41
42 import com.att.eelf.configuration.EELFLogger;
43 import com.att.eelf.configuration.EELFManager;
44
45 import java.io.OutputStream;
46 import java.security.KeyPair;
47
48 /**
49  * Implementation of SshConnection interface based on Apache MINA SSHD library.
50  */
51 class SshConnectionSshd implements SshConnection {
52
53     private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
54
55     private static final long AUTH_TIMEOUT = 60000;
56     private static final long EXEC_TIMEOUT = 120000;
57
58     private String host;
59     private int port;
60     private String username;
61     private String password;
62     private long timeout = EXEC_TIMEOUT;
63     private String keyFile;
64     private SshClient sshClient;
65     private ClientSession clientSession;
66     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
67
68     public SshConnectionSshd(String host, int port, String username, String password, String keyFile) {
69         this.host = host;
70         this.port = port;
71         this.username = username;
72         this.password = password;
73         this.keyFile = keyFile;
74     }
75
76     public SshConnectionSshd(String host, int port, String username, String password) {
77         this(host, port, username, password, null);
78     }
79
80     public SshConnectionSshd(String host, int port, String keyFile) {
81         this(host, port, null, null, keyFile);
82     }
83
84     @Override
85     public void connect() {
86         sshClient = SshClient.setUpDefaultClient();
87         sshClient.start();
88         try {
89             clientSession =
90                 sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession();
91             if (password != null) {
92                 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
93             }
94             if (keyFile != null) {
95                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[] {
96                     keyFile
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 = 0;
121         int retryDelay = 0;
122         int retriesLeft = 0;
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             } catch (Exception e) {
143                 throw e;
144             }
145         } while (retriesLeft > 0);
146     }
147
148     @Override
149     public void disconnect() {
150         try {
151             if (logger.isDebugEnabled()) {
152                 logger.debug("SSH: disconnecting from [" + toString() + "]");
153             }
154             clientSession.close(false);
155         } finally {
156             if (sshClient != null) {
157                 sshClient.stop();
158             }
159         }
160     }
161
162     @Override
163     public void setExecTimeout(long timeout) {
164         this.timeout = timeout;
165     }
166
167     @Override
168     public int execCommand(String cmd, OutputStream out, OutputStream err) {
169         return execCommand(cmd, out, err, false);
170     }
171
172     @Override
173     public int execCommandWithPty(String cmd, OutputStream out) {
174         return execCommand(cmd, out, out, true);
175     }
176
177     private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
178         try {
179             if (logger.isDebugEnabled()) {
180                 logger.debug("SSH: executing command");
181             }
182             ChannelExec client = clientSession.createExecChannel(cmd);
183             client.setUsePty(usePty); // use pseudo-tty?
184             client.setOut(out);
185             client.setErr(err);
186             OpenFuture openFuture = client.open();
187             int exitStatus = 0;
188             try {
189                 client.waitFor(ClientChannel.CLOSED, timeout);
190                 openFuture.verify();
191                 Integer exitStatusI = client.getExitStatus();
192                 if (exitStatusI == null) {
193                     throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
194                         + ":" + port + "]. Operation timed out.");
195                 }
196                 exitStatus = exitStatusI;
197             } finally {
198                 client.close(false);
199             }
200             return exitStatus;
201         } catch (RuntimeException e) {
202             throw e;
203         } catch (Exception t) {
204             throw new SshException(
205                 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", t);
206         }
207     }
208
209     private void waitForConnection(int retryDelay) {
210         long time = retryDelay * 1000L;
211         long future = System.currentTimeMillis() + time;
212         if (time != 0) {
213             while (System.currentTimeMillis() < future && time > 0) {
214                 try {
215                     Thread.sleep(time);
216                 } catch (InterruptedException e) {
217                     /*
218                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
219                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
220                      * amount of delay time needed and reenter the sleep until we get to the future time.
221                      */
222                     time = future - System.currentTimeMillis();
223                 }
224             }
225         }
226     }
227
228     @Override
229     public String toString() {
230         String address = host;
231         if (username != null) {
232             address = username + '@' + address;
233         }
234         return address;
235     }
236 }