4194159fee60be6a02514b09d353e1db82c85ab6
[ccsdk/sli.git] /
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.ccsdk.sli.adaptors.ssh.sshd;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import java.io.OutputStream;
30 import java.nio.file.Paths;
31 import java.security.KeyPair;
32 import java.util.Collections;
33 import org.apache.sshd.client.SshClient;
34 import org.apache.sshd.client.channel.ChannelExec;
35 import org.apache.sshd.client.channel.ClientChannelEvent;
36 import org.apache.sshd.client.future.AuthFuture;
37 import org.apache.sshd.client.future.OpenFuture;
38 import org.apache.sshd.client.session.ClientSession;
39 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
40 import org.apache.sshd.common.keyprovider.KeyPairProvider;
41 import org.onap.ccsdk.sli.adaptors.ssh.Constants;
42 import org.onap.ccsdk.sli.adaptors.ssh.SshConnection;
43 import org.onap.ccsdk.sli.adaptors.ssh.SshException;
44 import org.onap.ccsdk.sli.core.utils.configuration.Configuration;
45 import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory;
46 import org.onap.ccsdk.sli.core.utils.encryption.EncryptionTool;
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 final String host;
59     private final int port;
60     private final String username;
61     private final String password;
62     private long timeout = EXEC_TIMEOUT;
63     private final 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).verify().getSession();
91             if (password != null) {
92                 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
93             }
94             if (keyFile != null) {
95                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(Paths.get(keyFile));
96                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
97                 clientSession.addPublicKeyIdentity(keyPair);
98             }
99             AuthFuture authFuture = clientSession.auth();
100             authFuture.await(AUTH_TIMEOUT);
101             if (!authFuture.isSuccess()) {
102                 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
103                     + "]. Authentication failed.");
104             }
105         } catch (RuntimeException e) {
106             throw e;
107         } catch (Exception e) {
108             throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
109                 e);
110         }
111         if (logger.isDebugEnabled()) {
112             logger.debug("SSH: connected to [" + toString() + "]");
113         }
114     }
115
116     @Override
117     public void connectWithRetry() {
118         int retryCount ;
119         int retryDelay ;
120         int retriesLeft;
121
122         retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT,
123             Constants.DEFAULT_CONNECTION_RETRY_COUNT);
124         retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY,
125             Constants.DEFAULT_CONNECTION_RETRY_DELAY);
126         retriesLeft = retryCount + 1;
127         do {
128             try {
129                 this.connect();
130                 break;
131             } catch (RuntimeException e) {
132                 if (retriesLeft > 1) {
133                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
134                     waitForConnection(retryDelay);
135                     retriesLeft--;
136                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
137                         + "] out of [" + retryCount + "]");
138                 } else {
139                     throw e;
140                 }
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;
185             try {
186                 client.waitFor(Collections.singleton(ClientChannelEvent.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 e1) {
201             throw new SshException(
202                 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
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 }