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) {
 
 218         return props.getProperty(SS_SERVER_PORT);
 
 221     private void setSSHClient(Map<String, String> params) throws SvcLogicException {
 
 222         if (sshClient == null) {
 
 223             logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
 
 224                                 "auth details from DG's parameters");
 
 225             String sshHost = messageProcessor.reqHostNameResult(params);
 
 226             String sshPort = messageProcessor.reqPortResult(params);
 
 227             String sshUserName = messageProcessor.reqUserNameResult(params);
 
 228             String sshPassword = messageProcessor.reqPasswordResult(params);
 
 229             logger.info("Creating ssh client with BASIC Auth");
 
 231                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
 
 236     private String parseEnvParam(JSONObject envParams) {
 
 237         StringBuilder envParamBuilder = new StringBuilder();
 
 238         if (envParams != null) {
 
 239             for (Object key : envParams.keySet()) {
 
 240                 if (envParamBuilder.length() > 0) {
 
 241                     envParamBuilder.append(", ");
 
 243                 envParamBuilder.append(key + "=" + envParams.get((String) key));
 
 244                 logger.info("EnvParameters : " + envParamBuilder);
 
 247         return envParamBuilder.toString();
 
 250     private String parseFileParam(JSONObject fileParams) {
 
 251         StringBuilder fileParamBuilder = new StringBuilder();
 
 252         if (fileParams != null) {
 
 253             for (Object key : fileParams.keySet()) {
 
 254                 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
 
 255                 logger.info("FileParameters : " + fileParamBuilder);
 
 258         return fileParamBuilder.toString();
 
 261     private String putToCommands(SvcLogicContext ctx, String slsFileName,
 
 262                                  String applyTo, JSONObject envParams, JSONObject fileParams) throws SvcLogicException {
 
 264         StringBuilder constructedCommand = new StringBuilder();
 
 266             File file = new File(slsFileName);
 
 267             String slsFile = file.getName();
 
 268             if (!slsFile.substring(slsFile.lastIndexOf("."),
 
 269                                    slsFile.length()).equalsIgnoreCase(".sls")) {
 
 270                 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 271                         "is not of type .sls");
 
 273             InputStream in = new FileInputStream(file);
 
 274             byte[] data = new byte[(int) file.length()];
 
 276             String str = new String(data, "UTF-8");
 
 278             String slsWithoutExtn = stripExtension(slsFile);
 
 279             constructedCommand.append(parseFileParam(fileParams)).append("echo -e \"").append(str).append("\" > /srv/salt/").
 
 280                     append(slsFile).append("; ").append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").
 
 281                     append(applyTo).append("' state.apply ").append(slsWithoutExtn).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
 
 283             logger.info("Command to be executed on server : " + constructedCommand.toString());
 
 285         } catch (FileNotFoundException e) {
 
 286             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 287                     "not found in path : " + slsFileName + ". " + e.getMessage());
 
 288         } catch (IOException e) {
 
 289             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 290                     "error in path : " + slsFileName + ". " + e.getMessage());
 
 291         } catch (StringIndexOutOfBoundsException e) {
 
 292             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 293                     "is not of type .sls");
 
 295         return constructedCommand.toString();
 
 298     private String stripExtension(String str) {
 
 302         int pos = str.lastIndexOf(".");
 
 306         return str.substring(0, pos);
 
 309     private String putToCommands(String slsName, String applyTo, JSONObject envParams, JSONObject fileParams) {
 
 311         StringBuilder constructedCommand = new StringBuilder();
 
 313         constructedCommand.append(parseFileParam(fileParams)).append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").append(applyTo)
 
 314                 .append("' state.apply ").append(slsName).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
 
 316         logger.info("Command to be executed on server : " + constructedCommand.toString());
 
 317         return constructedCommand.toString();
 
 320     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
 
 321             throws SvcLogicException {
 
 323         // Check status of test request returned by Agent
 
 324         if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
 
 325             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 326             doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
 
 328             logger.info(String.format("Execution of request : successful."));
 
 329             ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
 
 330             ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, OUTCOME_SUCCESS);
 
 331             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 335     // Public Method to post single command request to execute saltState. Posts the following back
 
 336     // to Svc context memory
 
 337     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 338     //  org.onap.appc.adapter.saltstack.req.messge : any message
 
 339     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 341     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 344         SaltstackResult testResult;
 
 345         setSSHClient(params);
 
 347             reqID = messageProcessor.reqId(params);
 
 348             String commandToExecute = messageProcessor.reqCmd(params);
 
 349             slsExec = messageProcessor.reqIsSLSExec(params);
 
 350             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 351             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 352             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
 
 353             checkResponseStatus(testResult, ctx, reqID, slsExec);
 
 354         } catch (IOException e) {
 
 355             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 356                       "IOException in file stream : " + e.getMessage());
 
 361      * Public Method to post SLS command request to execute saltState on server. Posts the following back
 
 362      * to Svc context memory
 
 364      * org.onap.appc.adapter.saltstack.req.code : 200 if successful
 
 365      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 366      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 369     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 371         SaltstackResult testResult;
 
 372         setSSHClient(params);
 
 374             reqID = messageProcessor.reqId(params);
 
 375             String slsName = messageProcessor.reqSlsName(params);
 
 376             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 377             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 378             JSONObject envParams = messageProcessor.reqEnvParameters(params);
 
 379             JSONObject fileParams = messageProcessor.reqFileParameters(params);
 
 381             String commandToExecute = putToCommands(slsName, applyTo, envParams, fileParams);
 
 382             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 383             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 384             checkResponseStatus(testResult, ctx, reqID, true);
 
 385         } catch (IOException e) {
 
 386             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 387                       "IOException in file stream : " + e.getMessage());
 
 388         } catch (JSONException e) {
 
 389             doFailure(ctx, SaltstackResultCodes.INVALID_COMMAND.getValue(), e.getMessage());
 
 394      * Public Method to post SLS file request to execute saltState. Posts the following back
 
 395      * to Svc context memory
 
 397      * org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 398      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 399      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 402     public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 404         SaltstackResult testResult;
 
 405         setSSHClient(params);
 
 407             reqID = messageProcessor.reqId(params);
 
 408             String slsFile = messageProcessor.reqSlsFile(params);
 
 409             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 410             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 411             JSONObject envParams = messageProcessor.reqEnvParameters(params);
 
 412             JSONObject fileParams = messageProcessor.reqFileParameters(params);
 
 414             String commandToExecute = putToCommands(ctx, slsFile, applyTo, envParams, fileParams);
 
 415             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 416             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 417             checkResponseStatus(testResult, ctx, reqID, true);
 
 418         } catch (IOException e) {
 
 419             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 420                       "IOException in file stream : " + e.getMessage());
 
 424     public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
 
 426             throws SvcLogicException {
 
 428         SaltstackResult testResult = new SaltstackResult();
 
 430             if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
 
 431                 int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
 
 432                 int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
 
 434                     testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay, execTimeout);
 
 436                     testResult = testServer.mockReqExec(params);
 
 440                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
 
 442                     testResult = testServer.mockReqExec(params);
 
 445         } catch (IOException e) {
 
 446             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 447                       "IOException in file stream : " + e.getMessage());