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 = props.getProperty(SS_SERVER_PORT);
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 = props.getProperty(SS_SERVER_PORT);
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 = props.getProperty(SS_SERVER_PORT);
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 Unknown Exception", e);
208 throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
211 logger.info("Initialized Saltstack Adapter");
214 private void setSSHClient(Map<String, String> params) throws SvcLogicException {
215 if (sshClient == null) {
216 logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
217 "auth details from DG's parameters");
218 String sshHost = messageProcessor.reqHostNameResult(params);
219 String sshPort = messageProcessor.reqPortResult(params);
220 String sshUserName = messageProcessor.reqUserNameResult(params);
221 String sshPassword = messageProcessor.reqPasswordResult(params);
222 logger.info("Creating ssh client with BASIC Auth");
224 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
229 private String parseEnvParam(JSONObject envParams) {
230 StringBuilder envParamBuilder = new StringBuilder();
231 if (envParams != null) {
232 for(Object key : envParams.keySet()) {
233 if(envParamBuilder.length() > 0) {
234 envParamBuilder.append(", ");
236 envParamBuilder.append(key+"="+envParams.get((String) key));
237 logger.info("EnvParameters : " + envParamBuilder);
240 return envParamBuilder.toString();
243 private String parseFileParam(JSONObject fileParams) {
244 StringBuilder fileParamBuilder = new StringBuilder();
245 if (fileParams != null) {
246 for(Object key : fileParams.keySet()) {
247 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
248 logger.info("FileParameters : " + fileParamBuilder);
251 return fileParamBuilder.toString();
254 private String putToCommands(SvcLogicContext ctx, String slsFileName,
255 String applyTo, JSONObject envParams, JSONObject fileParams) throws SvcLogicException {
257 StringBuilder constructedCommand = new StringBuilder();
259 File file = new File(slsFileName);
260 String slsFile = file.getName();
261 if (!slsFile.substring(slsFile.lastIndexOf("."),
262 slsFile.length()).equalsIgnoreCase(".sls")) {
263 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
264 "is not of type .sls");
266 InputStream in = new FileInputStream(file);
267 byte[] data = new byte[(int) file.length()];
269 String str = new String(data, "UTF-8");
271 String slsWithoutExtn = stripExtension(slsFile);
272 constructedCommand.append(parseFileParam(fileParams)).append("echo -e \"").append(str).append("\" > /srv/salt/").
273 append(slsFile).append("; ").append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").
274 append(applyTo).append("' state.apply ").append(slsWithoutExtn).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
276 logger.info("Command to be executed on server : " + constructedCommand.toString());
278 } catch (FileNotFoundException e) {
279 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
280 "not found in path : " + slsFileName+". "+ e.getMessage());
281 } catch (IOException e) {
282 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
283 "error in path : " + slsFileName +". "+ e.getMessage());
284 } catch (StringIndexOutOfBoundsException e) {
285 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
286 "is not of type .sls");
288 return constructedCommand.toString();
291 private String stripExtension (String str) {
292 if (str == null) return null;
293 int pos = str.lastIndexOf(".");
294 if (pos == -1) return str;
295 return str.substring(0, pos);
298 private String putToCommands(String slsName, String applyTo, JSONObject envParams, JSONObject fileParams) {
300 StringBuilder constructedCommand = new StringBuilder();
302 constructedCommand.append(parseFileParam(fileParams)).append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").append(applyTo)
303 .append("' state.apply ").append(slsName).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
305 logger.info("Command to be executed on server : " + constructedCommand.toString());
306 return constructedCommand.toString();
309 private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
310 throws SvcLogicException {
312 // Check status of test request returned by Agent
313 if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
314 ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
315 doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
317 logger.info(String.format("Execution of request : successful."));
318 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
319 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, OUTCOME_SUCCESS);
320 ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
324 // Public Method to post single command request to execute saltState. Posts the following back
325 // to Svc context memory
326 // org.onap.appc.adapter.saltstack.req.code : 100 if successful
327 // org.onap.appc.adapter.saltstack.req.messge : any message
328 // org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
330 public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
333 SaltstackResult testResult;
334 setSSHClient(params);
336 reqID = messageProcessor.reqId(params);
337 String commandToExecute = messageProcessor.reqCmd(params);
338 slsExec = messageProcessor.reqIsSLSExec(params);
339 long execTimeout = messageProcessor.reqExecTimeout(params);
340 testResult = execCommand(ctx, params, commandToExecute, execTimeout);
341 testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
342 checkResponseStatus(testResult, ctx, reqID, slsExec);
343 } catch (IOException e) {
344 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
345 "IOException in file stream : "+ e.getMessage());
350 * Public Method to post SLS command request to execute saltState on server. Posts the following back
351 * to Svc context memory
353 * org.onap.appc.adapter.saltstack.req.code : 200 if successful
354 * org.onap.appc.adapter.saltstack.req.messge : any message
355 * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
358 public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
360 SaltstackResult testResult;
361 setSSHClient(params);
363 reqID = messageProcessor.reqId(params);
364 String slsName = messageProcessor.reqSlsName(params);
365 String applyTo = messageProcessor.reqApplyToDevices(params);
366 long execTimeout = messageProcessor.reqExecTimeout(params);
367 JSONObject envParams = messageProcessor.reqEnvParameters(params);
368 JSONObject fileParams = messageProcessor.reqFileParameters(params);
370 String commandToExecute = putToCommands(slsName, applyTo, envParams, fileParams);
371 testResult = execCommand(ctx, params, commandToExecute, execTimeout);
372 testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
373 checkResponseStatus(testResult, ctx, reqID, true);
374 } catch (IOException e) {
375 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
376 "IOException in file stream : "+ e.getMessage());
377 } catch (JSONException e) {
378 doFailure(ctx, SaltstackResultCodes.INVALID_COMMAND.getValue(), e.getMessage());
383 * Public Method to post SLS file request to execute saltState. Posts the following back
384 * to Svc context memory
386 * org.onap.appc.adapter.saltstack.req.code : 100 if successful
387 * org.onap.appc.adapter.saltstack.req.messge : any message
388 * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
391 public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
393 SaltstackResult testResult;
394 setSSHClient(params);
396 reqID = messageProcessor.reqId(params);
397 String slsFile = messageProcessor.reqSlsFile(params);
398 String applyTo = messageProcessor.reqApplyToDevices(params);
399 long execTimeout = messageProcessor.reqExecTimeout(params);
400 JSONObject envParams = messageProcessor.reqEnvParameters(params);
401 JSONObject fileParams = messageProcessor.reqFileParameters(params);
403 String commandToExecute = putToCommands(ctx, slsFile, applyTo, envParams, fileParams);
404 testResult = execCommand(ctx, params, commandToExecute, execTimeout);
405 testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
406 checkResponseStatus(testResult, ctx, reqID, true);
407 } catch (IOException e) {
408 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
409 "IOException in file stream : "+ e.getMessage());
413 public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
415 throws SvcLogicException{
417 SaltstackResult testResult = new SaltstackResult();
419 if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
420 int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
421 int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
423 testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay, execTimeout);
425 testResult = testServer.mockReqExec(params);
429 testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
431 testResult = testServer.mockReqExec(params);
434 } catch (IOException e) {
435 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
436 "IOException in file stream : "+ e.getMessage());