Use ByteStream instead of FileStream
[ccsdk/sli/adaptors.git] / saltstack-adapter / saltstack-adapter-provider / src / main / java / org / onap / ccsdk / sli / adaptors / saltstack / impl / ConnectionBuilder.java
index cc4ce95..6e5feb4 100644 (file)
@@ -1,10 +1,10 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP : APPC
+ * ONAP : CCSDK
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018 Samsung Electronics. All rights reserved.
  * ================================================================================
- * Copyright (C) 2017 Amdocs
+ *
  * =============================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,7 +18,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ *
  * ============LICENSE_END=========================================================
  */
 
@@ -26,18 +26,11 @@ package org.onap.ccsdk.sli.adaptors.saltstack.impl;
 
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.RandomStringUtils;
 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.OutputStream;
-import java.io.StringWriter;
 
 /**
  * Returns a custom SSH client
@@ -47,7 +40,6 @@ import java.io.StringWriter;
  * - return default sshclient (which only trusts known CAs from default cacerts file for process) this is the default
  * option
  **/
-//TODO: This class is to be altered completely based on the SALTSTACK server communication.
 public class ConnectionBuilder {
 
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
@@ -84,8 +76,8 @@ public class ConnectionBuilder {
      * @param cmd Commands to execute
      * @return command execution status
      */
-    public SaltstackResult connectNExecute(String cmd) throws IOException {
-        return connectNExecute(cmd, -1, -1);
+    public SaltstackResult connectNExecute(String cmd, long execTimeout) throws IOException {
+        return connectNExecute(cmd, -1, -1, execTimeout);
     }
 
     /**
@@ -98,12 +90,16 @@ public class ConnectionBuilder {
      * @param retryCount number of count retry to make a SSH connection.
      * @return command execution status
      */
-    public SaltstackResult connectNExecute(String cmd, int retryCount, int retryDelay)
-                            throws IOException{
+    public SaltstackResult connectNExecute(String cmd, int retryCount, int retryDelay, long execTimeout)
+            throws IOException {
 
         SaltstackResult result = new SaltstackResult();
-        OutputStream out = null;
-        OutputStream errs = null;
+        ByteArrayOutputStream out = null;
+        ByteArrayOutputStream errs = null;
+        if (execTimeout >= 0) {
+            sshConnection.setExecTimeout(execTimeout);
+        }
+
         try {
             if (retryCount != -1) {
                 result = sshConnection.connectWithRetry(retryCount, retryDelay);
@@ -113,134 +109,63 @@ public class ConnectionBuilder {
             if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
                 return result;
             }
-            String outFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
-            String errFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
-            out = new FileOutputStream(outFilePath);
-            errs = new FileOutputStream(errFilePath);
-            result = sshConnection.execCommand(cmd, out, errs);
+            out = new ByteArrayOutputStream();
+            errs = new ByteArrayOutputStream();
+            result = sshConnection.execCommand(cmd, out, errs, result);
             sshConnection.disconnect();
             if (result.getSshExitStatus() != 0) {
-                return sortExitStatus(result.getSshExitStatus(), errFilePath, cmd);
+                return sortExitStatus(result.getSshExitStatus(), errs.toString(), cmd);
             }
             if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
                 return result;
             }
             result.setStatusMessage("Success");
-            result.setOutputFileName(outFilePath);
+            result.setOutputMessage(out);
         } catch (Exception io) {
             logger.error("Caught Exception", io);
             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
             result.setStatusMessage(io.getMessage());
         } finally {
-            if( out != null )
+            if (out != null) {
                 out.close();
-            if( errs != null )
+            }
+            if (errs != null) {
                 errs.close();
+            }
         }
         return result;
     }
 
-    public SaltstackResult sortExitStatus(int exitStatus, String errFilePath, String cmd) {
+    public SaltstackResult sortExitStatus(int exitStatus, String errMess, String cmd) {
         SaltstackResult result = new SaltstackResult();
-        String err = "";
-        StringWriter writer = new StringWriter();
-        try {
-            IOUtils.copy(new FileInputStream(new File(errFilePath)), writer, "UTF-8");
-            err = writer.toString();
-        } catch (FileNotFoundException e){
-            logger.info("Error stream file doesn't exist");
-        } catch (IOException e){
-            logger.info("Error stream file doesn't exist");
-        }
         if (exitStatus == 255 || exitStatus == 1) {
             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
                     + "]. Exit Code " + exitStatus + " and Error message : " +
-                    "Malformed configuration. " + err;
+                    "Malformed configuration. " + errMess;
             logger.error(errMessage);
             result.setStatusCode(SaltstackResultCodes.INVALID_COMMAND.getValue());
             result.setStatusMessage(errMessage);
         } else if (exitStatus == 5 || exitStatus == 65) {
             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
                     + "]. Exit Code " + exitStatus + " and Error message : " +
-                    "Host not allowed to connect. " + err;
+                    "Host not allowed to connect. " + errMess;
             logger.error(errMessage);
             result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
             result.setStatusMessage(errMessage);
         } else if (exitStatus == 67 || exitStatus == 73) {
             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
                     + "]. Exit Code " + exitStatus + " and Error message : " +
-                    "Key exchange failed. " + err;
+                    "Key exchange failed. " + errMess;
             logger.error(errMessage);
             result.setStatusCode(SaltstackResultCodes.CERTIFICATE_ERROR.getValue());
             result.setStatusMessage(errMessage);
         } else {
             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
-                    + "]. Exit Code " + exitStatus + " and Error message : " + err;
+                    + "]. Exit Code " + exitStatus + " and Error message : " + errMess;
             logger.error(errMessage);
             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
             result.setStatusMessage(errMessage);
         }
         return result;
     }
-
-    /**
-     * 1. Connect to SSH server.
-     * 2. Exec remote command over SSH. Return command execution status.
-     * Command output is written to out or err stream.
-     *
-     * @param commands   list of commands to execute
-     * @param payloadSLS has the SLS file location that is to be sent to server
-     * @param retryDelay delay between retry to make a SSH connection.
-     * @param retryCount number of count retry to make a SSH connection.
-     * @return command execution status
-     */
-    public SaltstackResult connectNExecuteSLS(String commands, String payloadSLS, int retryDelay, int retryCount) {
-
-        SaltstackResult result = new SaltstackResult();
-        try {
-            //TODO: to implement SSH connected client to Saltstack Server
-        } catch (Exception io) {
-            logger.error("Caught Exception", io);
-            result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
-            result.setStatusMessage(io.getMessage());
-        }
-        return result;
-    }
-
-    /**
-     * Disconnect from SSH server.
-     */
-    public SaltstackResult disConnect() {
-
-        SaltstackResult result = new SaltstackResult();
-        try {
-            //TODO: to implement SSH connected client to Saltstack Server
-        } catch (Exception io) {
-            logger.error("Caught Exception", io);
-            result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
-            result.setStatusMessage(io.getMessage());
-        }
-        return result;
-    }
-
-    /**
-     * Exec remote command over SSH. Return command execution status.
-     * Command output is written to out or err stream.
-     *
-     * @param cmd command to execute
-     * @return command execution status
-     */
-    public SaltstackResult connectNExecuteLog(String cmd) {
-
-        SaltstackResult result = new SaltstackResult();
-
-        try {
-            //TODO: to implement SSH command execute
-        } catch (Exception io) {
-            result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
-            result.setStatusMessage(io.getMessage());
-            logger.error("Caught IOException", io);
-        }
-        return result;
-    }
 }