eb45ead501d9c7b2806a58b1b39d7dbfb658e0b6
[ccsdk/sli/adaptors.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK
4  * ================================================================================
5  * Copyright (C) 2018 Samsung Electronics. All rights reserved.
6  * ================================================================================
7  *
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  *
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.sshd.ClientChannel;
30 import org.apache.sshd.ClientSession;
31 import org.apache.sshd.SshClient;
32 import org.apache.sshd.client.channel.ChannelExec;
33 import org.apache.sshd.client.future.AuthFuture;
34 import org.apache.sshd.client.future.OpenFuture;
35 import org.apache.sshd.common.KeyPairProvider;
36 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
37 import org.onap.ccsdk.sli.adaptors.saltstack.model.Constants;
38 import org.onap.ccsdk.sli.adaptors.saltstack.model.SshException;
39
40 import java.io.OutputStream;
41 import java.security.KeyPair;
42
43 /**
44  * Implementation of SshConnection interface based on Apache MINA SSHD library.
45  */
46 class SshConnection {
47
48     private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
49
50     private static final long AUTH_TIMEOUT = 60000;
51     private static final long EXEC_TIMEOUT = 120000;
52     private String host;
53     private int port;
54     private String username;
55     private String password;
56     private long timeout = EXEC_TIMEOUT;
57     private String keyFile;
58     private SshClient sshClient;
59     private ClientSession clientSession;
60
61     public SshConnection(String host, int port, String username, String password, String keyFile) {
62         this.host = host;
63         this.port = port;
64         this.username = username;
65         this.password = password;
66         this.keyFile = keyFile;
67     }
68
69     public SshConnection(String host, int port, String username, String password) {
70         this(host, port, username, password, null);
71     }
72
73     public SshConnection(String host, int port, String keyFile) {
74         this(host, port, null, null, keyFile);
75     }
76
77     public void connect() {
78         sshClient = SshClient.setUpDefaultClient();
79         sshClient.start();
80         try {
81             clientSession =
82                     sshClient.connect(username, host, port).await().getSession();
83             if (password != null) {
84                 clientSession.addPasswordIdentity(password);
85             } else if (keyFile != null) {
86                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[]{
87                         keyFile
88                 });
89                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
90                 clientSession.addPublicKeyIdentity(keyPair);
91             }
92             AuthFuture authFuture = clientSession.auth();
93             authFuture.await(AUTH_TIMEOUT);
94             if (!authFuture.isSuccess()) {
95                 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
96                                                + "]. Authentication failed.");
97             }
98         } catch (RuntimeException e) {
99             throw e;
100         } catch (Exception e) {
101             throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
102                                    e);
103         }
104         if (logger.isDebugEnabled()) {
105             logger.debug("SSH: connected to [" + toString() + "]");
106         }
107     }
108
109     public void connectWithRetry() {
110         int retryCount;
111         int retryDelay;
112         int retriesLeft;
113         retryCount = Constants.DEFAULT_CONNECTION_RETRY_COUNT;
114         retryDelay = Constants.DEFAULT_CONNECTION_RETRY_DELAY;
115         retriesLeft = retryCount + 1;
116         do {
117             try {
118                 this.connect();
119                 break;
120             } catch (RuntimeException e) {
121                 if (retriesLeft > 1) {
122                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
123                     waitForConnection(retryDelay);
124                     retriesLeft--;
125                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
126                                          + "] out of [" + retryCount + "]");
127                 } else {
128                     throw e;
129                 }
130             }
131         } while (retriesLeft > 0);
132     }
133
134     public void disconnect() {
135         try {
136             if (logger.isDebugEnabled()) {
137                 logger.debug("SSH: disconnecting from [" + toString() + "]");
138             }
139             clientSession.close(false);
140         } finally {
141             if (sshClient != null) {
142                 sshClient.stop();
143             }
144         }
145     }
146
147     public void setExecTimeout(long timeout) {
148         this.timeout = timeout;
149     }
150
151     public int execCommand(String cmd, OutputStream out, OutputStream err) {
152         return execCommand(cmd, out, err, false);
153     }
154
155     public int execCommandWithPty(String cmd, OutputStream out) {
156         return execCommand(cmd, out, out, true);
157     }
158
159     private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
160         try {
161             if (logger.isDebugEnabled()) {
162                 logger.debug("SSH: executing command");
163             }
164             ChannelExec client = clientSession.createExecChannel(cmd);
165             client.setUsePty(usePty); // use pseudo-tty?
166             client.setOut(out);
167             client.setErr(err);
168             OpenFuture openFuture = client.open();
169             int exitStatus;
170             try {
171                 client.waitFor(ClientChannel.CLOSED, timeout);
172                 openFuture.verify();
173                 Integer exitStatusI = client.getExitStatus();
174                 if (exitStatusI == null) {
175                     throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
176                                                    + ":" + port + "]. Operation timed out.");
177                 }
178                 exitStatus = exitStatusI;
179             } finally {
180                 client.close(false);
181             }
182             return exitStatus;
183         } catch (RuntimeException e) {
184             throw e;
185         } catch (Exception e1) {
186             throw new SshException(
187                     "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
188         }
189     }
190
191     private void waitForConnection(int retryDelay) {
192         long time = retryDelay * 1000L;
193         long future = System.currentTimeMillis() + time;
194         if (time != 0) {
195             while (System.currentTimeMillis() < future && time > 0) {
196                 try {
197                     Thread.sleep(time);
198                 } catch (InterruptedException e) {
199                     /*
200                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
201                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
202                      * amount of delay time needed and reenter the sleep until we get to the future time.
203                      */
204                     time = future - System.currentTimeMillis();
205                 }
206             }
207         }
208     }
209
210     @Override
211     public String toString() {
212         String address = host;
213         if (username != null) {
214             address = username + '@' + address + ':' + port;
215         }
216         return address;
217     }
218 }