25d2d8402f68e91e934adcc235a9a9d6e0e8dfc3
[ccsdk/sli.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 java.io.OutputStream;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.security.KeyPair;
31 import org.apache.sshd.client.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.client.session.ClientSession;
36 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
37 import org.apache.sshd.common.keyprovider.KeyPairProvider;
38 import org.onap.ccsdk.sli.adaptors.saltstack.model.Constants;
39 import org.onap.ccsdk.sli.adaptors.saltstack.model.SshException;
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
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).getSession();
83             if (password != null) {
84                 clientSession.addPasswordIdentity(password);
85                         } else if (keyFile != null) {
86                                 Path keyFilePath = Paths.get(keyFile);
87                                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(keyFilePath);
88                                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
89                                 clientSession.addPublicKeyIdentity(keyPair);
90                         }
91             AuthFuture authFuture = clientSession.auth();
92             authFuture.await(AUTH_TIMEOUT);
93             if (!authFuture.isSuccess()) {
94                 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
95                                                + "]. Authentication failed.");
96             }
97         } catch (RuntimeException e) {
98             throw e;
99         } catch (Exception e) {
100             throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
101                                    e);
102         }
103         if (logger.isDebugEnabled()) {
104             logger.debug("SSH: connected to [" + toString() + "]");
105         }
106     }
107
108     public void connectWithRetry() {
109         int retryCount;
110         int retryDelay;
111         int retriesLeft;
112         retryCount = Constants.DEFAULT_CONNECTION_RETRY_COUNT;
113         retryDelay = Constants.DEFAULT_CONNECTION_RETRY_DELAY;
114         retriesLeft = retryCount + 1;
115         do {
116             try {
117                 this.connect();
118                 break;
119             } catch (RuntimeException e) {
120                 if (retriesLeft > 1) {
121                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
122                     waitForConnection(retryDelay);
123                     retriesLeft--;
124                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
125                                          + "] out of [" + retryCount + "]");
126                 } else {
127                     throw e;
128                 }
129             }
130         } while (retriesLeft > 0);
131     }
132
133     public void disconnect() {
134         try {
135             if (logger.isDebugEnabled()) {
136                 logger.debug("SSH: disconnecting from [" + toString() + "]");
137             }
138             clientSession.close(false);
139         } finally {
140             if (sshClient != null) {
141                 sshClient.stop();
142             }
143         }
144     }
145
146     public void setExecTimeout(long timeout) {
147         this.timeout = timeout;
148     }
149
150     public int execCommand(String cmd, OutputStream out, OutputStream err) {
151         return execCommand(cmd, out, err, false);
152     }
153
154     public int execCommandWithPty(String cmd, OutputStream out) {
155         return execCommand(cmd, out, out, true);
156     }
157
158     private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
159         try {
160             if (logger.isDebugEnabled()) {
161                 logger.debug("SSH: executing command");
162             }
163             ChannelExec client = clientSession.createExecChannel(cmd);
164             client.setUsePty(usePty); // use pseudo-tty?
165             client.setOut(out);
166             client.setErr(err);
167             OpenFuture openFuture = client.open();
168             int exitStatus;
169             try {
170                 client.wait(timeout);
171                 openFuture.verify();
172                 Integer exitStatusI = client.getExitStatus();
173                 if (exitStatusI == null) {
174                     throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
175                                                    + ":" + port + "]. Operation timed out.");
176                 }
177                 exitStatus = exitStatusI;
178             } finally {
179                 client.close(false);
180             }
181             return exitStatus;
182         } catch (RuntimeException e) {
183             throw e;
184         } catch (Exception e1) {
185             throw new SshException(
186                     "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
187         }
188     }
189
190     private void waitForConnection(int retryDelay) {
191         long time = retryDelay * 1000L;
192         long future = System.currentTimeMillis() + time;
193         if (time != 0) {
194             while (System.currentTimeMillis() < future && time > 0) {
195                 try {
196                     Thread.sleep(time);
197                 } catch (InterruptedException e) {
198                     /*
199                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
200                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
201                      * amount of delay time needed and reenter the sleep until we get to the future time.
202                      */
203                     time = future - System.currentTimeMillis();
204                 }
205             }
206         }
207     }
208
209     @Override
210     public String toString() {
211         String address = host;
212         if (username != null) {
213             address = username + '@' + address + ':' + port;
214         }
215         return address;
216     }
217 }