Fix ssh adapter compilation issues.
[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             }
95             if (keyFile != null) {
96                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(
97                         new File(keyFile).toPath()
98                 );
99                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
100                 clientSession.addPublicKeyIdentity(keyPair);
101             }
102             AuthFuture authFuture = clientSession.auth();
103             authFuture.await(AUTH_TIMEOUT);
104             if (!authFuture.isSuccess()) {
105                 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
106                     + "]. Authentication failed.");
107             }
108         } catch (RuntimeException e) {
109             throw e;
110         } catch (Exception e) {
111             throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
112                 e);
113         }
114         if (logger.isDebugEnabled()) {
115             logger.debug("SSH: connected to [" + toString() + "]");
116         }
117     }
118
119     @Override
120     public void connectWithRetry() {
121         int retryCount ;
122         int retryDelay ;
123         int retriesLeft;
124         retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT,
125             Constants.DEFAULT_CONNECTION_RETRY_COUNT);
126         retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY,
127             Constants.DEFAULT_CONNECTION_RETRY_DELAY);
128         retriesLeft = retryCount + 1;
129         do {
130             try {
131                 this.connect();
132                 break;
133             } catch (RuntimeException e) {
134                 if (retriesLeft > 1) {
135                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
136                     waitForConnection(retryDelay);
137                     retriesLeft--;
138                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
139                         + "] out of [" + retryCount + "]");
140                 } else {
141                     throw e;
142                 }
143           }
144         } while (retriesLeft > 0);
145     }
146
147     @Override
148     public void disconnect() {
149         try {
150             if (logger.isDebugEnabled()) {
151                 logger.debug("SSH: disconnecting from [" + toString() + "]");
152             }
153             clientSession.close(false);
154         } finally {
155             if (sshClient != null) {
156                 sshClient.stop();
157             }
158         }
159     }
160
161     @Override
162     public void setExecTimeout(long timeout) {
163         this.timeout = timeout;
164     }
165
166     @Override
167     public int execCommand(String cmd, OutputStream out, OutputStream err) {
168         return execCommand(cmd, out, err, false);
169     }
170
171     @Override
172     public int execCommandWithPty(String cmd, OutputStream out) {
173         return execCommand(cmd, out, out, true);
174     }
175
176     private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
177         try {
178             if (logger.isDebugEnabled()) {
179                 logger.debug("SSH: executing command");
180             }
181             ChannelExec client = clientSession.createExecChannel(cmd);
182             client.setUsePty(usePty); // use pseudo-tty?
183             client.setOut(out);
184             client.setErr(err);
185             OpenFuture openFuture = client.open();
186             int exitStatus;
187             try {
188                 client.waitFor(Arrays.asList(ClientChannelEvent.CLOSED), timeout);
189                 openFuture.verify();
190                 Integer exitStatusI = client.getExitStatus();
191                 if (exitStatusI == null) {
192                     throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
193                         + ":" + port + "]. Operation timed out.");
194                 }
195                 exitStatus = exitStatusI;
196             } finally {
197                 client.close(false);
198             }
199             return exitStatus;
200         } catch (RuntimeException e) {
201             throw e;
202         } catch (Exception e1) {
203             throw new SshException(
204                 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
205         }
206     }
207
208     private void waitForConnection(int retryDelay) {
209         long time = retryDelay * 1000L;
210         long future = System.currentTimeMillis() + time;
211         if (time != 0) {
212             while (System.currentTimeMillis() < future && time > 0) {
213                 try {
214                     Thread.sleep(time);
215                 } catch (InterruptedException e) {
216                     /*
217                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
218                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
219                      * amount of delay time needed and reenter the sleep until we get to the future time.
220                      */
221                     time = future - System.currentTimeMillis();
222                 }
223             }
224         }
225     }
226
227     @Override
228     public String toString() {
229         String address = host;
230         if (username != null) {
231             address = username + '@' + address;
232         }
233         return address;
234     }
235 }