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.json.JSONException;
 
  30 import org.json.JSONObject;
 
  31 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapter;
 
  32 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapterPropertiesProvider;
 
  33 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackMessageParser;
 
  34 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
 
  35 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
 
  36 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackServerEmulator;
 
  37 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  38 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  41 import java.io.FileInputStream;
 
  42 import java.io.FileNotFoundException;
 
  43 import java.io.IOException;
 
  44 import java.io.InputStream;
 
  46 import java.util.Properties;
 
  49  * This class implements the {@link SaltstackAdapter} interface. This interface defines the behaviors
 
  50  * that our service provides.
 
  52 public class SaltstackAdapterImpl implements SaltstackAdapter {
 
  55      * The constant for the status code for a failed outcome
 
  57     @SuppressWarnings("nls")
 
  58     public static final String OUTCOME_FAILURE = "failure";
 
  60      * The constant for the status code for a successful outcome
 
  62     @SuppressWarnings("nls")
 
  63     public static final String OUTCOME_SUCCESS = "success";
 
  64     public static final String CONNECTION_RETRY_DELAY = "retryDelay";
 
  65     public static final String CONNECTION_RETRY_COUNT = "retryCount";
 
  66     private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
 
  70     private static final String ADAPTER_NAME = "Saltstack Adapter";
 
  71     private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
 
  72     private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
 
  73     private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
 
  74     private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
 
  75     private static final String SS_SERVER_HOSTNAME = "org.onap.appc.adapter.saltstack.host";
 
  76     private static final String SS_SERVER_PORT = "org.onap.appc.adapter.saltstack.port";
 
  77     private static final String SS_SERVER_USERNAME = "org.onap.appc.adapter.saltstack.userName";
 
  78     private static final String SS_SERVER_PASSWD = "org.onap.appc.adapter.saltstack.userPasswd";
 
  79     private static final String SS_SERVER_SSH_KEY = "org.onap.appc.adapter.saltstack.sshKey";
 
  81     private static final String COMMAND_IN_JSON_OUT = " --out=json --static ";
 
  82     private static final String COMMAND_CHANGE_DEFAULT_DIR = " cd /srv/salt/ ;";
 
  85      * The logger to be used
 
  87     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
 
  91     private ConnectionBuilder sshClient;
 
  94      * Saltstack API Message Handlers
 
  96     private SaltstackMessageParser messageProcessor;
 
  99      * indicator whether in test mode
 
 101     private boolean testMode = false;
 
 104      * server emulator object to be used if in test mode
 
 106     private SaltstackServerEmulator testServer;
 
 109      * This default constructor is used as a work around because the activator wasn't getting called
 
 111     public SaltstackAdapterImpl() throws SvcLogicException{
 
 112         initialize(new SaltstackAdapterPropertiesProviderImpl());
 
 115     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
 
 116         initialize(propProvider);
 
 120      * Used for jUnit test and testing interface
 
 122     public SaltstackAdapterImpl(boolean mode) {
 
 124         testServer = new SaltstackServerEmulator();
 
 125         messageProcessor = new SaltstackMessageParser();
 
 129      * Returns the symbolic name of the adapter
 
 131      * @return The adapter name
 
 132      * @see SaltstackAdapter#getAdapterName()
 
 135     public String getAdapterName() {
 
 140      * Method posts info to Context memory in case of an error and throws a
 
 141      * SvcLogicException causing SLI to register this as a failure
 
 143     @SuppressWarnings("static-method")
 
 144     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
 
 145         logger.error(APPC_EXCEPTION_CAUGHT, message);
 
 146         svcLogic.setStatus(OUTCOME_FAILURE);
 
 147         svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
 
 148         svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
 
 149         throw new SvcLogicException("Saltstack Adapter Error = " + message);
 
 153      * initialize the Saltstack adapter based on default and over-ride configuration data
 
 155     private void initialize(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
 
 158         Properties props = propProvider.getProperties();
 
 160         // Create the message processor instance
 
 161         messageProcessor = new SaltstackMessageParser();
 
 163         // Create the ssh client instance
 
 164         // type of client is extracted from the property file parameter
 
 165         // org.onap.appc.adapter.saltstack.clientType
 
 167         // 1. BASIC. SSH Connection using username and password
 
 168         // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
 
 169         // 3. DEFAULT SSH Connection without any authentication
 
 172             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
 
 173             logger.info("Saltstack ssh client type set to " + clientType);
 
 175             if ("BASIC".equalsIgnoreCase(clientType)) {
 
 176                 logger.info("Creating ssh client connection");
 
 177                 // set path to keystore file
 
 178                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 179                 String sshPort = reqServerPort(props) ;
 
 180                 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
 
 181                 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
 
 182                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
 
 183             } else if ("SSH_CERT".equalsIgnoreCase(clientType)) {
 
 184                 // set path to keystore file
 
 185                 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
 
 186                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 187                 String sshPort = reqServerPort(props);
 
 188                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
 
 189                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshKey);
 
 190             } else if ("BOTH".equalsIgnoreCase(clientType)) {
 
 191                 // set path to keystore file
 
 192                 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
 
 193                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 194                 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
 
 195                 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
 
 196                 String sshPort = reqServerPort(props);
 
 197                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
 
 198                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword, sshKey);
 
 200                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
 
 203         } catch (NumberFormatException e) {
 
 204             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
 
 205             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = port in property file has to be an integer.");
 
 206         } catch (Exception e) {
 
 207             logger.error("Error Initializing Saltstack Adapter due to Exception", e);
 
 208             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
 
 210         logger.info("Initialized Saltstack Adapter");
 
 213     private String reqServerPort(Properties props) {
 
 214         // use default port if null
 
 215         if (props.getProperty(SS_SERVER_PORT) == null)
 
 217         return props.getProperty(SS_SERVER_PORT);
 
 220     private void setSSHClient(Map<String, String> params) throws SvcLogicException {
 
 221         if (sshClient == null) {
 
 222             logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
 
 223                                 "auth details from DG's parameters");
 
 224             String sshHost = messageProcessor.reqHostNameResult(params);
 
 225             String sshPort = messageProcessor.reqPortResult(params);
 
 226             String sshUserName = messageProcessor.reqUserNameResult(params);
 
 227             String sshPassword = messageProcessor.reqPasswordResult(params);
 
 228             logger.info("Creating ssh client with BASIC Auth");
 
 230                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
 
 235     private String parseEnvParam(JSONObject envParams) {
 
 236         StringBuilder envParamBuilder = new StringBuilder();
 
 237         if (envParams != null) {
 
 238             for(Object key : envParams.keySet()) {
 
 239                 if(envParamBuilder.length() > 0) {
 
 240                     envParamBuilder.append(", ");
 
 242                 envParamBuilder.append(key+"="+envParams.get((String) key));
 
 243                 logger.info("EnvParameters : " + envParamBuilder);
 
 246         return envParamBuilder.toString();
 
 249     private String parseFileParam(JSONObject fileParams) {
 
 250         StringBuilder fileParamBuilder = new StringBuilder();
 
 251         if (fileParams != null) {
 
 252             for(Object key : fileParams.keySet()) {
 
 253                 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
 
 254                 logger.info("FileParameters : " + fileParamBuilder);
 
 257         return fileParamBuilder.toString();
 
 260     private String putToCommands(SvcLogicContext ctx, String slsFileName,
 
 261                                     String applyTo, JSONObject envParams, JSONObject fileParams) throws SvcLogicException {
 
 263         StringBuilder constructedCommand = new StringBuilder();
 
 265             File file = new File(slsFileName);
 
 266             String slsFile = file.getName();
 
 267             if (!slsFile.substring(slsFile.lastIndexOf("."),
 
 268                                    slsFile.length()).equalsIgnoreCase(".sls")) {
 
 269                 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 270                         "is not of type .sls");
 
 272             InputStream in = new FileInputStream(file);
 
 273             byte[] data = new byte[(int) file.length()];
 
 275             String str = new String(data, "UTF-8");
 
 277             String slsWithoutExtn = stripExtension(slsFile);
 
 278             constructedCommand.append(parseFileParam(fileParams)).append("echo -e \"").append(str).append("\" > /srv/salt/").
 
 279                     append(slsFile).append("; ").append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").
 
 280                     append(applyTo).append("' state.apply ").append(slsWithoutExtn).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
 
 282             logger.info("Command to be executed on server : " + constructedCommand.toString());
 
 284         } catch (FileNotFoundException e) {
 
 285             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 286                     "not found in path : " + slsFileName+". "+ e.getMessage());
 
 287         } catch (IOException e) {
 
 288             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 289                     "error in path : " + slsFileName +". "+ e.getMessage());
 
 290         } catch (StringIndexOutOfBoundsException e) {
 
 291             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 292                     "is not of type .sls");
 
 294         return constructedCommand.toString();
 
 297     private String stripExtension (String str) {
 
 298         if (str == null) return null;
 
 299         int pos = str.lastIndexOf(".");
 
 300         if (pos == -1) return str;
 
 301         return str.substring(0, pos);
 
 304     private String putToCommands(String slsName, String applyTo, JSONObject envParams, JSONObject fileParams) {
 
 306         StringBuilder constructedCommand = new StringBuilder();
 
 308         constructedCommand.append(parseFileParam(fileParams)).append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").append(applyTo)
 
 309                 .append("' state.apply ").append(slsName).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
 
 311         logger.info("Command to be executed on server : " + constructedCommand.toString());
 
 312         return constructedCommand.toString();
 
 315     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
 
 316             throws SvcLogicException {
 
 318         // Check status of test request returned by Agent
 
 319         if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
 
 320             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 321             doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
 
 323             logger.info(String.format("Execution of request : successful."));
 
 324             ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
 
 325             ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, OUTCOME_SUCCESS);
 
 326             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 330     // Public Method to post single command request to execute saltState. Posts the following back
 
 331     // to Svc context memory
 
 332     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 333     //  org.onap.appc.adapter.saltstack.req.messge : any message
 
 334     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 336     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 339         SaltstackResult testResult;
 
 340         setSSHClient(params);
 
 342             reqID = messageProcessor.reqId(params);
 
 343             String commandToExecute = messageProcessor.reqCmd(params);
 
 344             slsExec = messageProcessor.reqIsSLSExec(params);
 
 345             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 346             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 347             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
 
 348             checkResponseStatus(testResult, ctx, reqID, slsExec);
 
 349         } catch (IOException e) {
 
 350             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 351                       "IOException in file stream : "+ e.getMessage());
 
 356      * Public Method to post SLS command request to execute saltState on server. Posts the following back
 
 357      * to Svc context memory
 
 359      * org.onap.appc.adapter.saltstack.req.code : 200 if successful
 
 360      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 361      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 364     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 366         SaltstackResult testResult;
 
 367         setSSHClient(params);
 
 369             reqID = messageProcessor.reqId(params);
 
 370             String slsName = messageProcessor.reqSlsName(params);
 
 371             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 372             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 373             JSONObject envParams = messageProcessor.reqEnvParameters(params);
 
 374             JSONObject fileParams = messageProcessor.reqFileParameters(params);
 
 376             String commandToExecute = putToCommands(slsName, applyTo, envParams, fileParams);
 
 377             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 378             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 379             checkResponseStatus(testResult, ctx, reqID, true);
 
 380         } catch (IOException e) {
 
 381             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 382                       "IOException in file stream : "+ e.getMessage());
 
 383         } catch (JSONException e) {
 
 384             doFailure(ctx, SaltstackResultCodes.INVALID_COMMAND.getValue(), e.getMessage());
 
 389      * Public Method to post SLS file request to execute saltState. Posts the following back
 
 390      * to Svc context memory
 
 392      * org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 393      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 394      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 397     public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 399         SaltstackResult testResult;
 
 400         setSSHClient(params);
 
 402             reqID = messageProcessor.reqId(params);
 
 403             String slsFile = messageProcessor.reqSlsFile(params);
 
 404             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 405             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 406             JSONObject envParams = messageProcessor.reqEnvParameters(params);
 
 407             JSONObject fileParams = messageProcessor.reqFileParameters(params);
 
 409             String commandToExecute = putToCommands(ctx, slsFile, applyTo, envParams, fileParams);
 
 410             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 411             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 412             checkResponseStatus(testResult, ctx, reqID, true);
 
 413         } catch (IOException e) {
 
 414             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 415                       "IOException in file stream : "+ e.getMessage());
 
 419     public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
 
 421                                     throws SvcLogicException{
 
 423         SaltstackResult testResult = new SaltstackResult();
 
 425             if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
 
 426                 int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
 
 427                 int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
 
 429                     testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay, execTimeout);
 
 431                     testResult = testServer.mockReqExec(params);
 
 435                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
 
 437                     testResult = testServer.mockReqExec(params);
 
 440         } catch (IOException e) {
 
 441             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 442                       "IOException in file stream : "+ e.getMessage());