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 = "withRetry";
 
  65     private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
 
  69     private static final String ADAPTER_NAME = "Saltstack Adapter";
 
  70     private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
 
  71     private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
 
  72     private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
 
  73     private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
 
  74     private static final String SS_SERVER_HOSTNAME = "org.onap.appc.adapter.saltstack.host";
 
  75     private static final String SS_SERVER_PORT = "org.onap.appc.adapter.saltstack.port";
 
  76     private static final String SS_SERVER_USERNAME = "org.onap.appc.adapter.saltstack.userName";
 
  77     private static final String SS_SERVER_PASSWD = "org.onap.appc.adapter.saltstack.userPasswd";
 
  78     private static final String SS_SERVER_SSH_KEY = "org.onap.appc.adapter.saltstack.sshKey";
 
  80     private static final String COMMAND_IN_JSON_OUT = " --out=json --static ";
 
  81     private static final String COMMAND_CHANGE_DEFAULT_DIR = " cd /srv/salt/ ;";
 
  84      * The logger to be used
 
  86     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
 
  90     private ConnectionBuilder sshClient;
 
  93      * Saltstack API Message Handlers
 
  95     private SaltstackMessageParser messageProcessor;
 
  98      * indicator whether in test mode
 
 100     private boolean testMode = false;
 
 103      * server emulator object to be used if in test mode
 
 105     private SaltstackServerEmulator testServer;
 
 108      * This default constructor is used as a work around because the activator wasn't getting called
 
 110     public SaltstackAdapterImpl() throws SvcLogicException {
 
 111         initialize(new SaltstackAdapterPropertiesProviderImpl());
 
 114     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException {
 
 115         initialize(propProvider);
 
 119      * Used for jUnit test and testing interface
 
 121     public SaltstackAdapterImpl(boolean mode) {
 
 123         testServer = new SaltstackServerEmulator();
 
 124         messageProcessor = new SaltstackMessageParser();
 
 128      * Returns the symbolic name of the adapter
 
 130      * @return The adapter name
 
 131      * @see SaltstackAdapter#getAdapterName()
 
 134     public String getAdapterName() {
 
 139      * Method posts info to Context memory in case of an error and throws a
 
 140      * SvcLogicException causing SLI to register this as a failure
 
 142     @SuppressWarnings("static-method")
 
 143     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
 
 144         logger.error(APPC_EXCEPTION_CAUGHT, message);
 
 145         svcLogic.setStatus(OUTCOME_FAILURE);
 
 146         svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
 
 147         svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
 
 148         throw new SvcLogicException("Saltstack Adapter Error = " + message);
 
 152      * initialize the Saltstack adapter based on default and over-ride configuration data
 
 154     private void initialize(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException {
 
 157         Properties props = propProvider.getProperties();
 
 159         // Create the message processor instance
 
 160         messageProcessor = new SaltstackMessageParser();
 
 162         // Create the ssh client instance
 
 163         // type of client is extracted from the property file parameter
 
 164         // org.onap.appc.adapter.saltstack.clientType
 
 166         // 1. BASIC. SSH Connection using username and password
 
 167         // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
 
 168         // 3. DEFAULT SSH Connection without any authentication
 
 171             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
 
 172             logger.info("Saltstack ssh client type set to " + clientType);
 
 174             if ("BASIC".equalsIgnoreCase(clientType)) {
 
 175                 logger.info("Creating ssh client connection");
 
 176                 // set path to keystore file
 
 177                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 178                 String sshPort = reqServerPort(props);
 
 179                 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
 
 180                 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
 
 181                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
 
 182             } else if ("SSH_CERT".equalsIgnoreCase(clientType)) {
 
 183                 // set path to keystore file
 
 184                 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
 
 185                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 186                 String sshPort = reqServerPort(props);
 
 187                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
 
 188                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshKey);
 
 190                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
 
 193         } catch (NumberFormatException e) {
 
 194             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
 
 195             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = port in property file has to be an integer.");
 
 196         } catch (Exception e) {
 
 197             logger.error("Error Initializing Saltstack Adapter due to Exception", e);
 
 198             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
 
 200         logger.info("Initialized Saltstack Adapter");
 
 203     private String reqServerPort(Properties props) {
 
 204         // use default port if null
 
 205         if (props.getProperty(SS_SERVER_PORT) == null) {
 
 208         return props.getProperty(SS_SERVER_PORT);
 
 211     private void setSSHClient(Map<String, String> params) throws SvcLogicException {
 
 212         if (sshClient == null) {
 
 213             logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
 
 214                                 "auth details from DG's parameters");
 
 215             String sshHost = messageProcessor.reqHostNameResult(params);
 
 216             String sshPort = messageProcessor.reqPortResult(params);
 
 217             String sshUserName = messageProcessor.reqUserNameResult(params);
 
 218             String sshPassword = messageProcessor.reqPasswordResult(params);
 
 219             logger.info("Creating ssh client with BASIC Auth");
 
 221                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
 
 226     private String parseEnvParam(JSONObject envParams) {
 
 227         StringBuilder envParamBuilder = new StringBuilder();
 
 228         if (envParams != null) {
 
 229             for (Object key : envParams.keySet()) {
 
 230                 if (envParamBuilder.length() > 0) {
 
 231                     envParamBuilder.append(", ");
 
 233                 envParamBuilder.append(key + "=" + envParams.get((String) key));
 
 234                 logger.info("EnvParameters : " + envParamBuilder);
 
 237         return envParamBuilder.toString();
 
 240     private String parseFileParam(JSONObject fileParams) {
 
 241         StringBuilder fileParamBuilder = new StringBuilder();
 
 242         if (fileParams != null) {
 
 243             for (Object key : fileParams.keySet()) {
 
 244                 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
 
 245                 logger.info("FileParameters : " + fileParamBuilder);
 
 248         return fileParamBuilder.toString();
 
 251     private String putToCommands(SvcLogicContext ctx, String slsFileName,
 
 252                                  String applyTo, JSONObject envParams, JSONObject fileParams) throws SvcLogicException {
 
 254         StringBuilder constructedCommand = new StringBuilder();
 
 256             File file = new File(slsFileName);
 
 257             String slsFile = file.getName();
 
 258             if (!slsFile.substring(slsFile.lastIndexOf("."),
 
 259                                    slsFile.length()).equalsIgnoreCase(".sls")) {
 
 260                 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 261                         "is not of type .sls");
 
 263             InputStream in = new FileInputStream(file);
 
 264             byte[] data = new byte[(int) file.length()];
 
 266             String str = new String(data, "UTF-8");
 
 268             String slsWithoutExtn = stripExtension(slsFile);
 
 269             constructedCommand.append(parseFileParam(fileParams)).append("echo -e \"").append(str).append("\" > /srv/salt/").
 
 270                     append(slsFile).append("; ").append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").
 
 271                     append(applyTo).append("' state.apply ").append(slsWithoutExtn).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
 
 273             logger.info("Command to be executed on server : " + constructedCommand.toString());
 
 275         } catch (FileNotFoundException e) {
 
 276             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 277                     "not found in path : " + slsFileName + ". " + e.getMessage());
 
 278         } catch (IOException e) {
 
 279             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 280                     "error in path : " + slsFileName + ". " + e.getMessage());
 
 281         } catch (StringIndexOutOfBoundsException e) {
 
 282             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 283                     "is not of type .sls");
 
 285         return constructedCommand.toString();
 
 288     private String stripExtension(String str) {
 
 292         int pos = str.lastIndexOf(".");
 
 296         return str.substring(0, pos);
 
 299     private String putToCommands(String slsName, String applyTo, JSONObject envParams, JSONObject fileParams) {
 
 301         StringBuilder constructedCommand = new StringBuilder();
 
 303         constructedCommand.append(parseFileParam(fileParams)).append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").append(applyTo)
 
 304                 .append("' state.apply ").append(slsName).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
 
 306         logger.info("Command to be executed on server : " + constructedCommand.toString());
 
 307         return constructedCommand.toString();
 
 310     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
 
 311             throws SvcLogicException {
 
 313         // Check status of test request returned by Agent
 
 314         if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
 
 315             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 316             doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
 
 318             logger.info(String.format("Execution of request : successful."));
 
 319             ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
 
 320             ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, OUTCOME_SUCCESS);
 
 321             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 325     // Public Method to post single command request to execute saltState. Posts the following back
 
 326     // to Svc context memory
 
 327     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 328     //  org.onap.appc.adapter.saltstack.req.messge : any message
 
 329     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 331     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 334         SaltstackResult testResult;
 
 335         setSSHClient(params);
 
 337             reqID = messageProcessor.reqId(params);
 
 338             String commandToExecute = messageProcessor.reqCmd(params);
 
 339             slsExec = messageProcessor.reqIsSLSExec(params);
 
 340             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 341             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 342             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
 
 343             checkResponseStatus(testResult, ctx, reqID, slsExec);
 
 344         } catch (IOException e) {
 
 345             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 346                       "IOException in file stream : " + e.getMessage());
 
 351      * Public Method to post SLS command request to execute saltState on server. Posts the following back
 
 352      * to Svc context memory
 
 354      * org.onap.appc.adapter.saltstack.req.code : 200 if successful
 
 355      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 356      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 359     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 361         SaltstackResult testResult;
 
 362         setSSHClient(params);
 
 364             reqID = messageProcessor.reqId(params);
 
 365             String slsName = messageProcessor.reqSlsName(params);
 
 366             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 367             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 368             JSONObject envParams = messageProcessor.reqEnvParameters(params);
 
 369             JSONObject fileParams = messageProcessor.reqFileParameters(params);
 
 371             String commandToExecute = putToCommands(slsName, applyTo, envParams, fileParams);
 
 372             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 373             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 374             checkResponseStatus(testResult, ctx, reqID, true);
 
 375         } catch (IOException e) {
 
 376             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 377                       "IOException in file stream : " + e.getMessage());
 
 378         } catch (JSONException e) {
 
 379             doFailure(ctx, SaltstackResultCodes.INVALID_COMMAND.getValue(), e.getMessage());
 
 384      * Public Method to post SLS file request to execute saltState. Posts the following back
 
 385      * to Svc context memory
 
 387      * org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 388      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 389      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 392     public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 394         SaltstackResult testResult;
 
 395         setSSHClient(params);
 
 397             reqID = messageProcessor.reqId(params);
 
 398             String slsFile = messageProcessor.reqSlsFile(params);
 
 399             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 400             long execTimeout = messageProcessor.reqExecTimeout(params);
 
 401             JSONObject envParams = messageProcessor.reqEnvParameters(params);
 
 402             JSONObject fileParams = messageProcessor.reqFileParameters(params);
 
 404             String commandToExecute = putToCommands(ctx, slsFile, applyTo, envParams, fileParams);
 
 405             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
 
 406             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 407             checkResponseStatus(testResult, ctx, reqID, true);
 
 408         } catch (IOException e) {
 
 409             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 410                       "IOException in file stream : " + e.getMessage());
 
 414     public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
 
 416             throws SvcLogicException {
 
 418         //convert execTimeout to Milliseconds
 
 419         execTimeout = execTimeout * 1000;
 
 420         SaltstackResult testResult = new SaltstackResult();
 
 422             if (params.get(CONNECTION_RETRY) == null) {
 
 424                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
 
 426                     testResult = testServer.mockReqExec(params);
 
 428             } else if (params.get(CONNECTION_RETRY).equalsIgnoreCase("true")) {
 
 430                     testResult = sshClient.connectNExecute(commandToExecute, true, execTimeout);
 
 432                     testResult = testServer.mockReqExec(params);
 
 436                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
 
 438                     testResult = testServer.mockReqExec(params);
 
 441         } catch (IOException e) {
 
 442             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 443                       "IOException in file stream : " + e.getMessage());