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.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapter;
 
  30 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapterPropertiesProvider;
 
  31 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackMessageParser;
 
  32 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
 
  33 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
 
  34 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackServerEmulator;
 
  35 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  36 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  39 import java.io.FileInputStream;
 
  40 import java.io.FileNotFoundException;
 
  41 import java.io.IOException;
 
  42 import java.io.InputStream;
 
  44 import java.util.Properties;
 
  47  * This class implements the {@link SaltstackAdapter} interface. This interface defines the behaviors
 
  48  * that our service provides.
 
  50 public class SaltstackAdapterImpl implements SaltstackAdapter {
 
  53      * The constant used to define the service name in the mapped diagnostic context
 
  55     @SuppressWarnings("nls")
 
  56     public static final String MDC_SERVICE = "service";
 
  58      * The constant for the status code for a failed outcome
 
  60     @SuppressWarnings("nls")
 
  61     public static final String OUTCOME_FAILURE = "failure";
 
  63      * The constant for the status code for a successful outcome
 
  65     @SuppressWarnings("nls")
 
  66     public static final String OUTCOME_SUCCESS = "success";
 
  67     public static final String CONNECTION_RETRY_DELAY = "retryDelay";
 
  68     public static final String CONNECTION_RETRY_COUNT = "retryCount";
 
  69     private static final long EXEC_TIMEOUT = 120000;
 
  73     private static final String ADAPTER_NAME = "Saltstack Adapter";
 
  74     private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
 
  75     private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
 
  76     private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
 
  77     private static final String RESULTS_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.results";
 
  78     private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
 
  79     private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.log";
 
  80     private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
 
  81     private static final String SS_SERVER_HOSTNAME = "org.onap.appc.adapter.saltstack.host";
 
  82     private static final String SS_SERVER_PORT = "org.onap.appc.adapter.saltstack.port";
 
  83     private static final String SS_SERVER_USERNAME = "org.onap.appc.adapter.saltstack.userName";
 
  84     private static final String SS_SERVER_PASSWD = "org.onap.appc.adapter.saltstack.userPasswd";
 
  85     private static final String SS_SERVER_SSH_KEY = "org.onap.appc.adapter.saltstack.sshKey";
 
  87      * The logger to be used
 
  89     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
 
  90     private long timeout = EXEC_TIMEOUT;
 
  94     private ConnectionBuilder sshClient;
 
  97      * Saltstack API Message Handlers
 
  99     private SaltstackMessageParser messageProcessor;
 
 102      * indicator whether in test mode
 
 104     private boolean testMode = false;
 
 107      * server emulator object to be used if in test mode
 
 109     private SaltstackServerEmulator testServer;
 
 112      * This default constructor is used as a work around because the activator wasn't getting called
 
 114     public SaltstackAdapterImpl() throws SvcLogicException{
 
 115         initialize(new SaltstackAdapterPropertiesProviderImpl());
 
 118     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
 
 119         initialize(propProvider);
 
 123      * Used for jUnit test and testing interface
 
 125     public SaltstackAdapterImpl(boolean mode) {
 
 127         testServer = new SaltstackServerEmulator();
 
 128         messageProcessor = new SaltstackMessageParser();
 
 132      * Returns the symbolic name of the adapter
 
 134      * @return The adapter name
 
 135      * @see SaltstackAdapter#getAdapterName()
 
 138     public String getAdapterName() {
 
 143     public void setExecTimeout(long timeout) {
 
 144         this.timeout = timeout;
 
 148      * Method posts info to Context memory in case of an error and throws a
 
 149      * SvcLogicException causing SLI to register this as a failure
 
 151     @SuppressWarnings("static-method")
 
 152     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
 
 154         svcLogic.setStatus(OUTCOME_FAILURE);
 
 155         svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
 
 156         svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
 
 157         throw new SvcLogicException("Saltstack Adapter Error = " + message);
 
 161      * initialize the Saltstack adapter based on default and over-ride configuration data
 
 163     private void initialize(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
 
 166         Properties props = propProvider.getProperties();
 
 168         // Create the message processor instance
 
 169         messageProcessor = new SaltstackMessageParser();
 
 171         // Create the ssh client instance
 
 172         // type of client is extracted from the property file parameter
 
 173         // org.onap.appc.adapter.saltstack.clientType
 
 175         // 1. BASIC. SSH Connection using username and password
 
 176         // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
 
 177         // 3. DEFAULT SSH Connection without any authentication
 
 180             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
 
 181             logger.info("Saltstack ssh client type set to " + clientType);
 
 183             if ("BASIC".equalsIgnoreCase(clientType)) {
 
 184                 logger.info("Creating ssh client connection");
 
 185                 // set path to keystore file
 
 186                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 187                 String sshPort = props.getProperty(SS_SERVER_PORT);
 
 188                 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
 
 189                 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
 
 190                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
 
 191             } else if ("SSH_CERT".equalsIgnoreCase(clientType)) {
 
 192                 // set path to keystore file
 
 193                 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
 
 194                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 195                 String sshPort = props.getProperty(SS_SERVER_PORT);
 
 196                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
 
 197                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshKey);
 
 198             } else if ("BOTH".equalsIgnoreCase(clientType)) {
 
 199                 // set path to keystore file
 
 200                 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
 
 201                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
 
 202                 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
 
 203                 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
 
 204                 String sshPort = props.getProperty(SS_SERVER_PORT);
 
 205                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
 
 206                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword, sshKey);
 
 208                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
 
 211         } catch (NumberFormatException e) {
 
 212             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
 
 213             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = port in property file has to be an integer.");
 
 214         } catch (Exception e) {
 
 215             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
 
 216             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
 
 219         logger.info("Initialized Saltstack Adapter");
 
 222     private void setSSHClient(Map<String, String> params) throws SvcLogicException {
 
 223         if (sshClient == null) {
 
 224             logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
 
 225                                 "auth details from DG's parameters");
 
 226             String sshHost = messageProcessor.reqHostNameResult(params);
 
 227             String sshPort = messageProcessor.reqPortResult(params);
 
 228             String sshUserName = messageProcessor.reqUserNameResult(params);
 
 229             String sshPassword = messageProcessor.reqPasswordResult(params);
 
 230             logger.info("Creating ssh client with BASIC Auth");
 
 232                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
 
 237     private String putToCommands(SvcLogicContext ctx, String slsFileName,
 
 238                                     String applyTo) throws SvcLogicException {
 
 239         String constructedCommand = "";
 
 241             File file = new File(slsFileName);
 
 242             String slsFile = file.getName();
 
 243             if (!slsFile.substring(slsFile.lastIndexOf("."),
 
 244                                    slsFile.length()).equalsIgnoreCase(".sls")) {
 
 245                 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 246                         "is not of type .sls");
 
 248             InputStream in = new FileInputStream(file);
 
 249             byte[] data = new byte[(int) file.length()];
 
 251             String str = new String(data, "UTF-8");
 
 253             String slsWithoutExtn = stripExtension(slsFile);
 
 254             constructedCommand = "echo -e \""+str+"\" > /srv/salt/"+slsFile+"; cd /srv/salt/; salt '"+
 
 255                     applyTo+"' state.apply "+slsWithoutExtn+" --out=json --static";
 
 256         } catch (FileNotFoundException e) {
 
 257             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 258                     "not found in path : " + slsFileName+". "+ e.getMessage());
 
 259         } catch (IOException e) {
 
 260             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
 
 261                     "error in path : " + slsFileName +". "+ e.getMessage());
 
 262         } catch (StringIndexOutOfBoundsException e) {
 
 263             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
 
 264                     "is not of type .sls");
 
 266         logger.info("Command to be executed on server : " + constructedCommand);
 
 267         return constructedCommand;
 
 270     private String stripExtension (String str) {
 
 271         if (str == null) return null;
 
 272         int pos = str.lastIndexOf(".");
 
 273         if (pos == -1) return str;
 
 274         return str.substring(0, pos);
 
 277     private String putToCommands(String slsName, String applyTo) {
 
 279             constructedCommand = "cd /srv/salt/; salt '"+applyTo+"' state.apply "+slsName+" --out=json --static";
 
 281         logger.info("Command to be executed on server : " + constructedCommand);
 
 282         return constructedCommand;
 
 285     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
 
 286             throws SvcLogicException {
 
 288         // Check status of test request returned by Agent
 
 289         if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
 
 290             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 291             doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
 
 294             logger.info(String.format("Execution of request : successful."));
 
 296                 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
 
 297                 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, "success");
 
 299                 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(SaltstackResultCodes.CHECK_CTX_FOR_CMD_SUCCESS.getValue()));
 
 300                 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, "check context for execution status");
 
 302             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
 
 306     // Public Method to post single command request to execute saltState. Posts the following back
 
 307     // to Svc context memory
 
 308     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 309     //  org.onap.appc.adapter.saltstack.req.messge : any message
 
 310     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 312     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 315         SaltstackResult testResult;
 
 316         setSSHClient(params);
 
 318             reqID = messageProcessor.reqId(params);
 
 319             String commandToExecute = messageProcessor.reqCmd(params);
 
 320             slsExec = messageProcessor.reqIsSLSExec(params);
 
 321             testResult = execCommand(ctx, params, commandToExecute);
 
 322             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
 
 323             checkResponseStatus(testResult, ctx, reqID, slsExec);
 
 324         } catch (IOException e) {
 
 325             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 326                       "IOException in file stream : "+ e.getMessage());
 
 331      * Public Method to post SLS command request to execute saltState on server. Posts the following back
 
 332      * to Svc context memory
 
 334      * org.onap.appc.adapter.saltstack.req.code : 200 if successful
 
 335      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 336      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 339     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 341         SaltstackResult testResult;
 
 342         setSSHClient(params);
 
 344             reqID = messageProcessor.reqId(params);
 
 345             String slsName = messageProcessor.reqSlsName(params);
 
 346             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 347             String commandToExecute = putToCommands(slsName, applyTo);
 
 348             testResult = execCommand(ctx, params, commandToExecute);
 
 349             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 350             checkResponseStatus(testResult, ctx, reqID, true);
 
 351         } catch (IOException e) {
 
 352             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 353                       "IOException in file stream : "+ e.getMessage());
 
 358      * Public Method to post SLS file request to execute saltState. Posts the following back
 
 359      * to Svc context memory
 
 361      * org.onap.appc.adapter.saltstack.req.code : 100 if successful
 
 362      * org.onap.appc.adapter.saltstack.req.messge : any message
 
 363      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
 
 366     public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 368         SaltstackResult testResult;
 
 369         setSSHClient(params);
 
 371             reqID = messageProcessor.reqId(params);
 
 372             String slsFile = messageProcessor.reqSlsFile(params);
 
 373             String applyTo = messageProcessor.reqApplyToDevices(params);
 
 374             String commandToExecute = putToCommands(ctx, slsFile, applyTo);
 
 375             testResult = execCommand(ctx, params, commandToExecute);
 
 376             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
 
 377             checkResponseStatus(testResult, ctx, reqID, true);
 
 378         } catch (IOException e) {
 
 379             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 380                       "IOException in file stream : "+ e.getMessage());
 
 385      * Public method to get logs from saltState execution for a specific request Posts the following back
 
 386      * to Svc context memory
 
 388      * It blocks till the Saltstack Server responds or the session times out very similar to
 
 389      * reqExecResult logs are returned in the DG context variable org.onap.appc.adapter.saltstack.log
 
 392     public void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
 397     public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute)
 
 398                                     throws SvcLogicException{
 
 400         SaltstackResult testResult = new SaltstackResult();
 
 402             if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
 
 403                 int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
 
 404                 int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
 
 406                     testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay);
 
 408                     testResult = testServer.mockReqExec(params);
 
 412                     testResult = sshClient.connectNExecute(commandToExecute);
 
 414                     testResult = testServer.mockReqExec(params);
 
 417         } catch (IOException e) {
 
 418             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
 
 419                       "IOException in file stream : "+ e.getMessage());