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;
28 import java.util.Properties;
29 import org.apache.commons.lang.StringUtils;
30 import org.json.JSONException;
31 import org.json.JSONObject;
32 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapter;
33 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapterPropertiesProvider;
34 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackMessageParser;
35 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
36 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
37 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackServerEmulator;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
44 * This class implements the {@link SaltstackAdapter} interface. This interface defines the behaviors
45 * that our service provides.
47 public class SaltstackAdapterImpl implements SaltstackAdapter {
49 private static final long EXEC_TIMEOUT = 120000;
50 private long timeout = EXEC_TIMEOUT;
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";
59 * The constant for the status code for a failed outcome
61 @SuppressWarnings("nls")
62 public static final String OUTCOME_FAILURE = "failure";
65 * The constant for the status code for a successful outcome
67 @SuppressWarnings("nls")
68 public static final String OUTCOME_SUCCESS = "success";
73 private static final String ADAPTER_NAME = "Saltstack Adapter";
74 private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
76 private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
77 private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
78 private static final String RESULTS_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.results";
79 private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
80 private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.log";
82 public static final String CONNECTION_RETRY_DELAY = "retryDelay";
83 public static final String CONNECTION_RETRY_COUNT = "retryCount";
85 private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
86 private static final String SS_SERVER_HOSTNAME = "org.onap.appc.adapter.saltstack.host";
87 private static final String SS_SERVER_PORT = "org.onap.appc.adapter.saltstack.port";
88 private static final String SS_SERVER_USERNAME = "org.onap.appc.adapter.saltstack.userName";
89 private static final String SS_SERVER_PASSWORD = "org.onap.appc.adapter.saltstack.userPasswd";
90 private static final String SS_SERVER_SSH_KEY = "org.onap.appc.adapter.saltstack.sshKey";
94 * The logger to be used
96 private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
102 private ConnectionBuilder sshClient;
105 * Saltstack API Message Handlers
107 private SaltstackMessageParser messageProcessor;
110 * indicator whether in test mode
112 private boolean testMode = false;
115 * server emulator object to be used if in test mode
117 private SaltstackServerEmulator testServer;
120 * This default constructor is used as a work around because the activator wasn't getting called
122 public SaltstackAdapterImpl() {
123 initialize(new SaltstackAdapterPropertiesProviderImpl());
125 public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) {
126 initialize(propProvider);
130 * Used for jUnit test and testing interface
132 public SaltstackAdapterImpl(boolean mode) {
134 testServer = new SaltstackServerEmulator();
135 messageProcessor = new SaltstackMessageParser();
139 * Returns the symbolic name of the adapter
141 * @return The adapter name
142 * @see SaltstackAdapter#getAdapterName()
145 public String getAdapterName() {
150 public void setExecTimeout(long timeout) {
151 this.timeout = timeout;
154 * Method posts info to Context memory in case of an error and throws a
155 * SvcLogicException causing SLI to register this as a failure
157 @SuppressWarnings("static-method")
158 private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
160 svcLogic.setStatus(OUTCOME_FAILURE);
161 svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
162 svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
164 throw new SvcLogicException("Saltstack Adapter Error = " + message);
168 * initialize the Saltstack adapter based on default and over-ride configuration data
170 private void initialize(SaltstackAdapterPropertiesProvider propProvider) {
173 Properties props = propProvider.getProperties();
175 // Create the message processor instance
176 messageProcessor = new SaltstackMessageParser();
178 // Create the ssh client instance
179 // type of client is extracted from the property file parameter
180 // org.onap.appc.adapter.saltstack.clientType
182 // 1. BASIC. SSH Connection using username and password
183 // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
184 // 3. DEFAULT SSH Connection without any authentication
187 String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
188 logger.info("Saltstack ssh client type set to " + clientType);
190 if ("BASIC".equalsIgnoreCase(clientType)) {
191 logger.info("Creating ssh client connection");
192 // set path to keystore file
193 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
194 String sshPort = props.getProperty(SS_SERVER_PORT);
195 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
196 String sshPassword = props.getProperty(SS_SERVER_PASSWORD);
197 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
198 } else if ("SSH_CERT".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 sshPort = props.getProperty(SS_SERVER_PORT);
203 logger.info("Creating ssh client with ssh KEY from " + sshKey);
204 sshClient = new ConnectionBuilder(sshHost, sshPort, sshKey);
205 } else if ("BOTH".equalsIgnoreCase(clientType)) {
206 // set path to keystore file
207 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
208 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
209 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
210 String sshPassword = props.getProperty(SS_SERVER_PASSWORD);
211 String sshPort = props.getProperty(SS_SERVER_PORT);
212 logger.info("Creating ssh client with ssh KEY from " + sshKey);
213 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword, sshKey);
215 logger.info("No saltstack-adapter.properties defined so reading from DG props");
218 } catch (Exception e) {
219 logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
222 logger.info("Initialized Saltstack Adapter");
225 // Public Method to post single command request to execute saltState. Posts the following back
226 // to Svc context memory
227 // org.onap.appc.adapter.saltstack.req.code : 100 if successful
228 // org.onap.appc.adapter.saltstack.req.messge : any message
229 // org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
231 public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
233 SaltstackResult testResult;
234 if (sshClient == null){
235 logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
236 "auth details from DG's parameters");
237 String sshHost = messageProcessor.reqHostNameResult(params);
238 String sshPort = messageProcessor.reqPortResult(params);
239 String sshUserName = messageProcessor.reqUserNameResult(params);
240 String sshPassword = messageProcessor.reqPasswordResult(params);
241 logger.info("Creating ssh client with BASIC Auth");
243 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
246 reqID = params.get("Id");
247 String commandToExecute = params.get("cmd");
248 testResult = execCommand(params, commandToExecute);
249 testResult = messageProcessor.parseResponse(ctx, reqID, testResult);
251 // Check status of test request returned by Agent
252 if (testResult.getStatusCode() == SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
253 logger.info(String.format("Execution of request-ID : %s successful.", reqID));
254 testResult.setResults("Success");
256 doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
259 } catch (SvcLogicException e) {
260 logger.error(APPC_EXCEPTION_CAUGHT, e);
261 doFailure(ctx, SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue(),
262 "Request for execution of command failed. Reason = "
265 } catch (Exception e) {
266 logger.error("Exception caught", e);
267 doFailure(ctx, SaltstackResultCodes.INVALID_COMMAND.getValue(),
268 "Request for execution of command failed. Reason = "
272 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
273 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, testResult.getResults());
274 ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
278 * Public Method to post SLS file request to execute saltState. Posts the following back
279 * to Svc context memory
281 * org.onap.appc.adapter.saltstack.req.code : 100 if successful
282 * org.onap.appc.adapter.saltstack.req.messge : any message
283 * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
286 public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
292 * Public method to get logs from saltState execution for a specific request Posts the following back
293 * to Svc context memory
295 * It blocks till the Saltstack Server responds or the session times out very similar to
296 * reqExecResult logs are returned in the DG context variable org.onap.appc.adapter.saltstack.log
299 public void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
304 public SaltstackResult execCommand(Map<String, String> params, String commandToExecute){
305 SaltstackResult testResult;
306 if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
307 int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
308 int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
310 testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay);
312 testResult = testServer.MockReqExec(params);
316 testResult = sshClient.connectNExecute(commandToExecute);
318 testResult = testServer.MockReqExec(params);