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 for the status code for a failed outcome
55 @SuppressWarnings("nls")
56 public static final String OUTCOME_FAILURE = "failure";
58 * The constant for the status code for a successful outcome
60 @SuppressWarnings("nls")
61 public static final String OUTCOME_SUCCESS = "success";
62 public static final String CONNECTION_RETRY_DELAY = "retryDelay";
63 public static final String CONNECTION_RETRY_COUNT = "retryCount";
67 private static final String ADAPTER_NAME = "Saltstack Adapter";
68 private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
69 private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
70 private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
71 private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
72 private static final String SS_SERVER_HOSTNAME = "org.onap.appc.adapter.saltstack.host";
73 private static final String SS_SERVER_PORT = "org.onap.appc.adapter.saltstack.port";
74 private static final String SS_SERVER_USERNAME = "org.onap.appc.adapter.saltstack.userName";
75 private static final String SS_SERVER_PASSWD = "org.onap.appc.adapter.saltstack.userPasswd";
76 private static final String SS_SERVER_SSH_KEY = "org.onap.appc.adapter.saltstack.sshKey";
78 * The logger to be used
80 private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
84 private ConnectionBuilder sshClient;
87 * Saltstack API Message Handlers
89 private SaltstackMessageParser messageProcessor;
92 * indicator whether in test mode
94 private boolean testMode = false;
97 * server emulator object to be used if in test mode
99 private SaltstackServerEmulator testServer;
102 * This default constructor is used as a work around because the activator wasn't getting called
104 public SaltstackAdapterImpl() throws SvcLogicException{
105 initialize(new SaltstackAdapterPropertiesProviderImpl());
108 public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
109 initialize(propProvider);
113 * Used for jUnit test and testing interface
115 public SaltstackAdapterImpl(boolean mode) {
117 testServer = new SaltstackServerEmulator();
118 messageProcessor = new SaltstackMessageParser();
122 * Returns the symbolic name of the adapter
124 * @return The adapter name
125 * @see SaltstackAdapter#getAdapterName()
128 public String getAdapterName() {
133 * Method posts info to Context memory in case of an error and throws a
134 * SvcLogicException causing SLI to register this as a failure
136 @SuppressWarnings("static-method")
137 private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
139 svcLogic.setStatus(OUTCOME_FAILURE);
140 svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
141 svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
142 throw new SvcLogicException("Saltstack Adapter Error = " + message);
146 * initialize the Saltstack adapter based on default and over-ride configuration data
148 private void initialize(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
151 Properties props = propProvider.getProperties();
153 // Create the message processor instance
154 messageProcessor = new SaltstackMessageParser();
156 // Create the ssh client instance
157 // type of client is extracted from the property file parameter
158 // org.onap.appc.adapter.saltstack.clientType
160 // 1. BASIC. SSH Connection using username and password
161 // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
162 // 3. DEFAULT SSH Connection without any authentication
165 String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
166 logger.info("Saltstack ssh client type set to " + clientType);
168 if ("BASIC".equalsIgnoreCase(clientType)) {
169 logger.info("Creating ssh client connection");
170 // set path to keystore file
171 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
172 String sshPort = props.getProperty(SS_SERVER_PORT);
173 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
174 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
175 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
176 } else if ("SSH_CERT".equalsIgnoreCase(clientType)) {
177 // set path to keystore file
178 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
179 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
180 String sshPort = props.getProperty(SS_SERVER_PORT);
181 logger.info("Creating ssh client with ssh KEY from " + sshKey);
182 sshClient = new ConnectionBuilder(sshHost, sshPort, sshKey);
183 } else if ("BOTH".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 sshUserName = props.getProperty(SS_SERVER_USERNAME);
188 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
189 String sshPort = props.getProperty(SS_SERVER_PORT);
190 logger.info("Creating ssh client with ssh KEY from " + sshKey);
191 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword, sshKey);
193 logger.info("No saltstack-adapter.properties defined so reading from DG props");
196 } catch (NumberFormatException e) {
197 logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
198 throw new SvcLogicException("Saltstack Adapter Property file parsing Error = port in property file has to be an integer.");
199 } catch (Exception e) {
200 logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
201 throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
204 logger.info("Initialized Saltstack Adapter");
207 private void setSSHClient(Map<String, String> params) throws SvcLogicException {
208 if (sshClient == null) {
209 logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
210 "auth details from DG's parameters");
211 String sshHost = messageProcessor.reqHostNameResult(params);
212 String sshPort = messageProcessor.reqPortResult(params);
213 String sshUserName = messageProcessor.reqUserNameResult(params);
214 String sshPassword = messageProcessor.reqPasswordResult(params);
215 logger.info("Creating ssh client with BASIC Auth");
217 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
222 private String putToCommands(SvcLogicContext ctx, String slsFileName,
223 String applyTo) throws SvcLogicException {
224 String constructedCommand = "";
226 File file = new File(slsFileName);
227 String slsFile = file.getName();
228 if (!slsFile.substring(slsFile.lastIndexOf("."),
229 slsFile.length()).equalsIgnoreCase(".sls")) {
230 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
231 "is not of type .sls");
233 InputStream in = new FileInputStream(file);
234 byte[] data = new byte[(int) file.length()];
236 String str = new String(data, "UTF-8");
238 String slsWithoutExtn = stripExtension(slsFile);
239 constructedCommand = "echo -e \""+str+"\" > /srv/salt/"+slsFile+"; cd /srv/salt/; salt '"+
240 applyTo+"' state.apply "+slsWithoutExtn+" --out=json --static";
241 } catch (FileNotFoundException e) {
242 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
243 "not found in path : " + slsFileName+". "+ e.getMessage());
244 } catch (IOException e) {
245 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
246 "error in path : " + slsFileName +". "+ e.getMessage());
247 } catch (StringIndexOutOfBoundsException e) {
248 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
249 "is not of type .sls");
251 logger.info("Command to be executed on server : " + constructedCommand);
252 return constructedCommand;
255 private String stripExtension (String str) {
256 if (str == null) return null;
257 int pos = str.lastIndexOf(".");
258 if (pos == -1) return str;
259 return str.substring(0, pos);
262 private String putToCommands(String slsName, String applyTo) {
264 constructedCommand = "cd /srv/salt/; salt '"+applyTo+"' state.apply "+slsName+" --out=json --static";
266 logger.info("Command to be executed on server : " + constructedCommand);
267 return constructedCommand;
270 private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
271 throws SvcLogicException {
273 // Check status of test request returned by Agent
274 if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
275 ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
276 doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
279 logger.info(String.format("Execution of request : successful."));
280 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
281 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, OUTCOME_SUCCESS);
282 ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
286 // Public Method to post single command request to execute saltState. Posts the following back
287 // to Svc context memory
288 // org.onap.appc.adapter.saltstack.req.code : 100 if successful
289 // org.onap.appc.adapter.saltstack.req.messge : any message
290 // org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
292 public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
295 SaltstackResult testResult;
296 setSSHClient(params);
298 reqID = messageProcessor.reqId(params);
299 String commandToExecute = messageProcessor.reqCmd(params);
300 slsExec = messageProcessor.reqIsSLSExec(params);
301 long execTimeout = messageProcessor.reqExecTimeout(params);
302 testResult = execCommand(ctx, params, commandToExecute, execTimeout);
303 testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
304 checkResponseStatus(testResult, ctx, reqID, slsExec);
305 } catch (IOException e) {
306 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
307 "IOException in file stream : "+ e.getMessage());
312 * Public Method to post SLS command request to execute saltState on server. Posts the following back
313 * to Svc context memory
315 * org.onap.appc.adapter.saltstack.req.code : 200 if successful
316 * org.onap.appc.adapter.saltstack.req.messge : any message
317 * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
320 public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
322 SaltstackResult testResult;
323 setSSHClient(params);
325 reqID = messageProcessor.reqId(params);
326 String slsName = messageProcessor.reqSlsName(params);
327 String applyTo = messageProcessor.reqApplyToDevices(params);
328 long execTimeout = messageProcessor.reqExecTimeout(params);
329 String commandToExecute = putToCommands(slsName, applyTo);
330 testResult = execCommand(ctx, params, commandToExecute, execTimeout);
331 testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
332 checkResponseStatus(testResult, ctx, reqID, true);
333 } catch (IOException e) {
334 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
335 "IOException in file stream : "+ e.getMessage());
340 * Public Method to post SLS file request to execute saltState. Posts the following back
341 * to Svc context memory
343 * org.onap.appc.adapter.saltstack.req.code : 100 if successful
344 * org.onap.appc.adapter.saltstack.req.messge : any message
345 * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
348 public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
350 SaltstackResult testResult;
351 setSSHClient(params);
353 reqID = messageProcessor.reqId(params);
354 String slsFile = messageProcessor.reqSlsFile(params);
355 String applyTo = messageProcessor.reqApplyToDevices(params);
356 long execTimeout = messageProcessor.reqExecTimeout(params);
357 String commandToExecute = putToCommands(ctx, slsFile, applyTo);
358 testResult = execCommand(ctx, params, commandToExecute, execTimeout);
359 testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
360 checkResponseStatus(testResult, ctx, reqID, true);
361 } catch (IOException e) {
362 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
363 "IOException in file stream : "+ e.getMessage());
367 public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
369 throws SvcLogicException{
371 SaltstackResult testResult = new SaltstackResult();
373 if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
374 int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
375 int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
377 testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay, execTimeout);
379 testResult = testServer.mockReqExec(params);
383 testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
385 testResult = testServer.mockReqExec(params);
388 } catch (IOException e) {
389 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
390 "IOException in file stream : "+ e.getMessage());