reqExec API implemented for saltstack
[ccsdk/sli/adaptors.git] / saltstack-adapter / saltstack-adapter-provider / src / main / java / org / onap / ccsdk / sli / adaptors / saltstack / impl / SaltstackAdapterImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
26
27 import java.util.Map;
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;
42
43 /**
44  * This class implements the {@link SaltstackAdapter} interface. This interface defines the behaviors
45  * that our service provides.
46  */
47 public class SaltstackAdapterImpl implements SaltstackAdapter {
48
49     private static final long EXEC_TIMEOUT = 120000;
50     private long timeout = EXEC_TIMEOUT;
51
52     /**
53      * The constant used to define the service name in the mapped diagnostic context
54      */
55     @SuppressWarnings("nls")
56     public static final String MDC_SERVICE = "service";
57
58     /**
59      * The constant for the status code for a failed outcome
60      */
61     @SuppressWarnings("nls")
62     public static final String OUTCOME_FAILURE = "failure";
63
64     /**
65      * The constant for the status code for a successful outcome
66      */
67     @SuppressWarnings("nls")
68     public static final String OUTCOME_SUCCESS = "success";
69
70     /**
71      * Adapter Name
72      */
73     private static final String ADAPTER_NAME = "Saltstack Adapter";
74     private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
75
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";
81
82     public static final String CONNECTION_RETRY_DELAY = "retryDelay";
83     public static final String CONNECTION_RETRY_COUNT = "retryCount";
84
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";
91
92
93     /**
94      * The logger to be used
95      */
96     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
97
98
99     /**
100      * Connection object
101      **/
102     private ConnectionBuilder sshClient;
103
104     /**
105      * Saltstack API Message Handlers
106      **/
107     private SaltstackMessageParser messageProcessor;
108
109     /**
110      * indicator whether in test mode
111      **/
112     private boolean testMode = false;
113
114     /**
115      * server emulator object to be used if in test mode
116      **/
117     private SaltstackServerEmulator testServer;
118
119     /**
120      * This default constructor is used as a work around because the activator wasn't getting called
121      */
122     public SaltstackAdapterImpl() {
123         initialize(new SaltstackAdapterPropertiesProviderImpl());
124     }
125     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) {
126         initialize(propProvider);
127     }
128
129     /**
130      * Used for jUnit test and testing interface
131      */
132     public SaltstackAdapterImpl(boolean mode) {
133         testMode = mode;
134         testServer = new SaltstackServerEmulator();
135         messageProcessor = new SaltstackMessageParser();
136     }
137
138     /**
139      * Returns the symbolic name of the adapter
140      *
141      * @return The adapter name
142      * @see SaltstackAdapter#getAdapterName()
143      */
144     @Override
145     public String getAdapterName() {
146         return ADAPTER_NAME;
147     }
148
149     @Override
150     public void setExecTimeout(long timeout) {
151         this.timeout = timeout;
152     }
153     /**
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
156      */
157     @SuppressWarnings("static-method")
158     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
159
160         svcLogic.setStatus(OUTCOME_FAILURE);
161         svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
162         svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
163
164         throw new SvcLogicException("Saltstack Adapter Error = " + message);
165     }
166
167     /**
168      * initialize the Saltstack adapter based on default and over-ride configuration data
169      */
170     private void initialize(SaltstackAdapterPropertiesProvider propProvider) {
171
172
173         Properties props = propProvider.getProperties();
174
175         // Create the message processor instance
176         messageProcessor = new SaltstackMessageParser();
177
178         // Create the ssh client instance
179         // type of client is extracted from the property file parameter
180         // org.onap.appc.adapter.saltstack.clientType
181         // It can be :
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
185
186         try {
187             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
188             logger.info("Saltstack ssh client type set to " + clientType);
189
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);
214             } else {
215                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
216                 sshClient = null;
217             }
218         } catch (Exception e) {
219             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
220         }
221
222         logger.info("Initialized Saltstack Adapter");
223     }
224
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
230     @Override
231     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
232         String reqID;
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");
242             if(!testMode)
243                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
244         }
245         try {
246             reqID = params.get("Id");
247             String commandToExecute = params.get("cmd");
248             testResult = execCommand(params, commandToExecute);
249             testResult = messageProcessor.parseResponse(ctx, reqID, testResult);
250
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");
255             } else {
256                 doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
257                 return;
258             }
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 = "
263                               + e.getMessage());
264             return;
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 = "
269                               + e.getMessage());
270             return;
271         }
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);
275     }
276
277     /**
278      * Public Method to post SLS file request to execute saltState. Posts the following back
279      * to Svc context memory
280      *
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
284      */
285     @Override
286     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
287         //TODO: to implement
288
289     }
290
291     /**
292      * Public method to get logs from saltState execution for a specific request Posts the following back
293      * to Svc context memory
294      *
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
297      */
298     @Override
299     public void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
300         //TODO: to implement
301
302     }
303
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));
309             if(!testMode)
310                 testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay);
311             else {
312                 testResult = testServer.MockReqExec(params);
313             }
314         } else {
315             if(!testMode)
316                 testResult = sshClient.connectNExecute(commandToExecute);
317             else {
318                 testResult = testServer.MockReqExec(params);
319             }
320         }
321         return testResult;
322     }
323 }