2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Copyright (C) 2017 Amdocs
 
   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.
 
  21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 
  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 = 120000;
 
  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         this.timeout = timeout;
 
 168     public SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err) {
 
 169         return execCommand(cmd, out, err, false);
 
 172     public SaltstackResult execCommandWithPty(String cmd, OutputStream out) {
 
 173         return execCommand(cmd, out, out, true);
 
 176     private SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
 
 177         SaltstackResult result = new SaltstackResult();
 
 179             if (logger.isDebugEnabled()) {
 
 180                 logger.debug("SSH: executing command");
 
 182             ChannelExec client = clientSession.createExecChannel(cmd);
 
 183             client.setUsePty(usePty); // use pseudo-tty?
 
 186             OpenFuture openFuture = client.open();
 
 189                 client.waitFor(ClientChannel.CLOSED, timeout);
 
 191                 Integer exitStatusI = client.getExitStatus();
 
 192                 if (exitStatusI == null) {
 
 193                     String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host
 
 194                             + ":" + port + "]. SSH operation timed out.";
 
 195                     result.setStatusCode(SaltstackResultCodes.OPERATION_TIMEOUT.getValue());
 
 196                     result.setStatusMessage(errMessage);
 
 199                 exitStatus = exitStatusI;
 
 203             result.setSshExitStatus(exitStatus);
 
 205         } catch (RuntimeException e) {
 
 206             String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
 
 207                     "Runtime Exception : " + e.getMessage();
 
 208             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
 
 209             result.setStatusMessage(errMessage);
 
 210         } catch (Exception e1) {
 
 211             String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" +
 
 212                     port + "]" + e1.getMessage();
 
 213             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
 
 214             result.setStatusMessage(errMessage);
 
 216         result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
 
 220     private void waitForConnection(int retryDelay) {
 
 221         long time = retryDelay * 1000L;
 
 222         long future = System.currentTimeMillis() + time;
 
 224             while (System.currentTimeMillis() < future && time > 0) {
 
 227                 } catch (InterruptedException e) {
 
 229                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
 
 230                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
 
 231                      * amount of delay time needed and reenter the sleep until we get to the future time.
 
 233                     time = future - System.currentTimeMillis();
 
 240     public String toString() {
 
 241         String address = host;
 
 242         if (username != null) {
 
 243             address = username + '@' + address + ':' + port;