6740220673a9d4bf4d44491e36410893c5b8b432
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Amdocs
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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.openecomp.appc.adapter.ssh.sshd;
24
25 import org.openecomp.appc.adapter.ssh.Constants;
26 import org.openecomp.appc.adapter.ssh.SshConnection;
27 import org.openecomp.appc.adapter.ssh.SshException;
28 import org.openecomp.appc.encryption.EncryptionTool;
29 import org.openecomp.appc.configuration.Configuration;
30 import org.openecomp.appc.configuration.ConfigurationFactory;
31 import org.apache.sshd.ClientChannel;
32 import org.apache.sshd.ClientSession;
33 import org.apache.sshd.SshClient;
34 import org.apache.sshd.client.channel.ChannelExec;
35 import org.apache.sshd.client.future.AuthFuture;
36 import org.apache.sshd.client.future.OpenFuture;
37 import org.apache.sshd.common.KeyPairProvider;
38 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
39
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42
43 import java.io.OutputStream;
44 import java.security.KeyPair;
45
46 /**
47  * Implementation of SshConnection interface based on Apache MINA SSHD library.
48  */
49 class SshConnectionSshd implements SshConnection {
50
51     private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
52
53     private static final long AUTH_TIMEOUT = 60000;
54     private static final long EXEC_TIMEOUT = 120000;
55
56     private String host;
57     private int port;
58     private String username;
59     private String password;
60     private long timeout = EXEC_TIMEOUT;
61     private String keyFile;
62     private SshClient sshClient;
63     private ClientSession clientSession;
64     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
65
66     public SshConnectionSshd(String host, int port, String username, String password, String keyFile) {
67         this.host = host;
68         this.port = port;
69         this.username = username;
70         this.password = password;
71         this.keyFile = keyFile;
72     }
73
74     public SshConnectionSshd(String host, int port, String username, String password) {
75         this(host, port, username, password, null);
76     }
77
78     public SshConnectionSshd(String host, int port, String keyFile) {
79         this(host, port, null, null, keyFile);
80     }
81
82     @Override
83     public void connect() {
84         sshClient = SshClient.setUpDefaultClient();
85         sshClient.start();
86         try {
87             clientSession =
88                 sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession();
89             if (password != null) {
90                 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
91             }
92             if (keyFile != null) {
93                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[] {
94                     keyFile
95                 });
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 = 0;
119         int retryDelay = 0;
120         int retriesLeft = 0;
121         retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT,
122             Constants.DEFAULT_CONNECTION_RETRY_COUNT);
123         retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY,
124             Constants.DEFAULT_CONNECTION_RETRY_DELAY);
125         retriesLeft = retryCount + 1;
126         do {
127             try {
128                 this.connect();
129                 break;
130             } catch (RuntimeException e) {
131                 if (retriesLeft > 1) {
132                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
133                     waitForConnection(retryDelay);
134                     retriesLeft--;
135                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
136                         + "] out of [" + retryCount + "]");
137                 } else {
138                     throw e;
139                 }
140             } catch (Exception e) {
141                 throw e;
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 = 0;
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 t) {
202             throw new SshException(
203                 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", t);
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 }