44cedc3bb98347a6be929947d252271791a5189c
[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 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 ;
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 {
177             if (logger.isDebugEnabled()) {
178                 logger.debug("SSH: executing command");
179             }
180             ChannelExec client = clientSession.createExecChannel(cmd);
181             client.setUsePty(usePty); // use pseudo-tty?
182             client.setOut(out);
183             client.setErr(err);
184             OpenFuture openFuture = client.open();
185             int exitStatus;
186             try {
187                 client.waitFor(ClientChannel.CLOSED, timeout);
188                 openFuture.verify();
189                 Integer exitStatusI = client.getExitStatus();
190                 if (exitStatusI == null) {
191                     throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
192                         + ":" + port + "]. Operation timed out.");
193                 }
194                 exitStatus = exitStatusI;
195             } finally {
196                 client.close(false);
197             }
198             return exitStatus;
199         } catch (RuntimeException e) {
200             throw e;
201         } catch (Exception e1) {
202             throw new SshException(
203                 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
204         }
205     }
206
207     private void waitForConnection(int retryDelay) {
208         long time = retryDelay * 1000L;
209         long future = System.currentTimeMillis() + time;
210         if (time != 0) {
211             while (System.currentTimeMillis() < future && time > 0) {
212                 try {
213                     Thread.sleep(time);
214                 } catch (InterruptedException e) {
215                     /*
216                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
217                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
218                      * amount of delay time needed and reenter the sleep until we get to the future time.
219                      */
220                     time = future - System.currentTimeMillis();
221                 }
222             }
223         }
224     }
225
226     @Override
227     public String toString() {
228         String address = host;
229         if (username != null) {
230             address = username + '@' + address;
231         }
232         return address;
233     }
234 }