2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2018 Samsung Electronics. All rights reserved.
 
   6  * ================================================================================
 
   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
 
  13  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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.
 
  22  * ============LICENSE_END=========================================================
 
  25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
 
  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.encryption.EncryptionTool;
 
  38 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
 
  39 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
 
  41 import java.io.OutputStream;
 
  42 import java.security.KeyPair;
 
  45  * Implementation of SshConnection interface based on Apache MINA SSHD library.
 
  49     public static final int DEFAULT_CONNECTION_RETRY_DELAY = 60;
 
  50     public static final int DEFAULT_CONNECTION_RETRY_COUNT = 5;
 
  51     private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
 
  52     private static final long AUTH_TIMEOUT = 60000;
 
  53     private static final long EXEC_TIMEOUT = 120;
 
  56     private String username;
 
  57     private String password;
 
  58     private long timeout = EXEC_TIMEOUT;
 
  59     private String keyFile;
 
  60     private SshClient sshClient;
 
  61     private ClientSession clientSession;
 
  63     public SshConnection(String host, int port, String username, String password, String keyFile) {
 
  66         this.username = username;
 
  67         this.password = password;
 
  68         this.keyFile = keyFile;
 
  71     public SshConnection(String host, int port, String username, String password) {
 
  72         this(host, port, username, password, null);
 
  75     public SshConnection(String host, int port, String keyFile) {
 
  76         this(host, port, null, null, keyFile);
 
  79     public SaltstackResult connect() {
 
  80         SaltstackResult result = new SaltstackResult();
 
  81         sshClient = SshClient.setUpDefaultClient();
 
  85                     sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession();
 
  86             if (password != null) {
 
  87                 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
 
  89             if (keyFile != null) {
 
  90                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[]{
 
  93                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
 
  94                 clientSession.addPublicKeyIdentity(keyPair);
 
  96             AuthFuture authFuture = clientSession.auth();
 
  97             authFuture.await(AUTH_TIMEOUT);
 
  98             if (!authFuture.isSuccess()) {
 
  99                 String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port
 
 100                         + "]. Authentication failed.";
 
 101                 result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
 
 102                 result.setStatusMessage(errMessage);
 
 104         } catch (RuntimeException e) {
 
 105             String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
 
 106                     "Runtime Exception : " + e.getMessage();
 
 107             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
 
 108             result.setStatusMessage(errMessage);
 
 109         } catch (Exception e) {
 
 110             String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
 
 111                     "Host Unknown : " + e.getMessage();
 
 112             result.setStatusCode(SaltstackResultCodes.HOST_UNKNOWN.getValue());
 
 113             result.setStatusMessage(errMessage);
 
 115         if (logger.isDebugEnabled()) {
 
 116             logger.debug("SSH: connected to [" + toString() + "]");
 
 118         result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
 
 122     public SaltstackResult connectWithRetry(int retryCount, int retryDelay) {
 
 124         SaltstackResult result = new SaltstackResult();
 
 125         if (retryCount == 0) {
 
 126             retryCount = DEFAULT_CONNECTION_RETRY_COUNT;
 
 128         if (retryDelay == 0) {
 
 129             retryDelay = DEFAULT_CONNECTION_RETRY_DELAY;
 
 131         retriesLeft = retryCount + 1;
 
 134                 result = this.connect();
 
 136             } catch (RuntimeException e) {
 
 137                 if (retriesLeft > 1) {
 
 138                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
 
 139                     waitForConnection(retryDelay);
 
 141                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
 
 142                                          + "] out of [" + retryCount + "]");
 
 147         } while (retriesLeft > 0);
 
 151     public void disconnect() {
 
 153             if (logger.isDebugEnabled()) {
 
 154                 logger.debug("SSH: disconnecting from [" + toString() + "]");
 
 156             clientSession.close(false);
 
 158             if (sshClient != null) {
 
 164     public void setExecTimeout(long timeout) {
 
 165         //convert seconds to milliseconds
 
 166         this.timeout = timeout*1000;
 
 169     public SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err, SaltstackResult result ) {
 
 170         return execCommand(cmd, out, err, false, result);
 
 173     public SaltstackResult execCommandWithPty(String cmd, OutputStream out, SaltstackResult result ) {
 
 174         return execCommand(cmd, out, out, true, result);
 
 177     private SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err,
 
 178                                         boolean usePty, SaltstackResult result ) {
 
 181             if (logger.isDebugEnabled()) {
 
 182                 logger.debug("SSH: executing command");
 
 184             ChannelExec client = clientSession.createExecChannel(cmd);
 
 185             client.setUsePty(usePty); // use pseudo-tty?
 
 188             OpenFuture openFuture = client.open();
 
 191                 client.waitFor(ClientChannel.CLOSED, timeout);
 
 193                 Integer exitStatusI = client.getExitStatus();
 
 194                 if (exitStatusI == null) {
 
 195                     String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host
 
 196                             + ":" + port + "]. SSH operation timed out.";
 
 197                     result.setStatusCode(SaltstackResultCodes.OPERATION_TIMEOUT.getValue());
 
 198                     result.setStatusMessage(errMessage);
 
 201                 exitStatus = exitStatusI;
 
 205             result.setSshExitStatus(exitStatus);
 
 207         } catch (RuntimeException e) {
 
 208             String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
 
 209                     "Runtime Exception : " + e.getMessage();
 
 210             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
 
 211             result.setStatusMessage(errMessage);
 
 212         } catch (Exception e1) {
 
 213             String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" +
 
 214                     port + "]" + e1.getMessage();
 
 215             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
 
 216             result.setStatusMessage(errMessage);
 
 218         result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
 
 222     private void waitForConnection(int retryDelay) {
 
 223         long time = retryDelay * 1000L;
 
 224         long future = System.currentTimeMillis() + time;
 
 226             while (System.currentTimeMillis() < future && time > 0) {
 
 229                 } catch (InterruptedException e) {
 
 231                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
 
 232                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
 
 233                      * amount of delay time needed and reenter the sleep until we get to the future time.
 
 235                     time = future - System.currentTimeMillis();
 
 242     public String toString() {
 
 243         String address = host;
 
 244         if (username != null) {
 
 245             address = username + '@' + address + ':' + port;