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