Saltstack now aligned with APPC
[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 : CCSDK
4  * ================================================================================
5  * Copyright (C) 2018 Samsung Electronics. All rights reserved.
6  * ================================================================================
7  *
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  *
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
26
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;
39
40 import java.io.File;
41 import java.io.FileInputStream;
42 import java.io.FileNotFoundException;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.util.Map;
46 import java.util.Properties;
47
48 /**
49  * This class implements the {@link SaltstackAdapter} interface. This interface defines the behaviors
50  * that our service provides.
51  */
52 public class SaltstackAdapterImpl implements SaltstackAdapter {
53
54     /**
55      * The constant for the status code for a failed outcome
56      */
57     @SuppressWarnings("nls")
58     public static final String OUTCOME_FAILURE = "failure";
59     /**
60      * The constant for the status code for a successful outcome
61      */
62     @SuppressWarnings("nls")
63     public static final String OUTCOME_SUCCESS = "success";
64     public static final String CONNECTION_RETRY = "withRetry";
65     private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
66     /**
67      * Adapter Name
68      */
69     private static final String ADAPTER_NAME = "Saltstack Adapter";
70     private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
71     private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
72     private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
73     private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
74     private static final String SS_SERVER_HOSTNAME = "org.onap.appc.adapter.saltstack.host";
75     private static final String SS_SERVER_PORT = "org.onap.appc.adapter.saltstack.port";
76     private static final String SS_SERVER_USERNAME = "org.onap.appc.adapter.saltstack.userName";
77     private static final String SS_SERVER_PASSWD = "org.onap.appc.adapter.saltstack.userPasswd";
78     private static final String SS_SERVER_SSH_KEY = "org.onap.appc.adapter.saltstack.sshKey";
79
80     private static final String COMMAND_IN_JSON_OUT = " --out=json --static ";
81     private static final String COMMAND_CHANGE_DEFAULT_DIR = " cd /srv/salt/ ;";
82
83     /**
84      * The logger to be used
85      */
86     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
87     /**
88      * Connection object
89      **/
90     private ConnectionBuilder sshClient;
91
92     /**
93      * Saltstack API Message Handlers
94      **/
95     private SaltstackMessageParser messageProcessor;
96
97     /**
98      * indicator whether in test mode
99      **/
100     private boolean testMode = false;
101
102     /**
103      * server emulator object to be used if in test mode
104      **/
105     private SaltstackServerEmulator testServer;
106
107     /**
108      * This default constructor is used as a work around because the activator wasn't getting called
109      */
110     public SaltstackAdapterImpl() throws SvcLogicException {
111         initialize(new SaltstackAdapterPropertiesProviderImpl());
112     }
113
114     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException {
115         initialize(propProvider);
116     }
117
118     /**
119      * Used for jUnit test and testing interface
120      */
121     public SaltstackAdapterImpl(boolean mode) {
122         testMode = mode;
123         testServer = new SaltstackServerEmulator();
124         messageProcessor = new SaltstackMessageParser();
125     }
126
127     /**
128      * Returns the symbolic name of the adapter
129      *
130      * @return The adapter name
131      * @see SaltstackAdapter#getAdapterName()
132      */
133     @Override
134     public String getAdapterName() {
135         return ADAPTER_NAME;
136     }
137
138     /**
139      * Method posts info to Context memory in case of an error and throws a
140      * SvcLogicException causing SLI to register this as a failure
141      */
142     @SuppressWarnings("static-method")
143     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
144         logger.error(APPC_EXCEPTION_CAUGHT, message);
145         svcLogic.setStatus(OUTCOME_FAILURE);
146         svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
147         svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
148         throw new SvcLogicException("Saltstack Adapter Error = " + message);
149     }
150
151     /**
152      * initialize the Saltstack adapter based on default and over-ride configuration data
153      */
154     private void initialize(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException {
155
156
157         Properties props = propProvider.getProperties();
158
159         // Create the message processor instance
160         messageProcessor = new SaltstackMessageParser();
161
162         // Create the ssh client instance
163         // type of client is extracted from the property file parameter
164         // org.onap.appc.adapter.saltstack.clientType
165         // It can be :
166         // 1. BASIC. SSH Connection using username and password
167         // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
168         // 3. DEFAULT SSH Connection without any authentication
169
170         try {
171             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
172             logger.info("Saltstack ssh client type set to " + clientType);
173
174             if ("BASIC".equalsIgnoreCase(clientType)) {
175                 logger.info("Creating ssh client connection");
176                 // set path to keystore file
177                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
178                 String sshPort = reqServerPort(props);
179                 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
180                 String sshPassword = props.getProperty(SS_SERVER_PASSWD);
181                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
182             } else if ("SSH_CERT".equalsIgnoreCase(clientType)) {
183                 // set path to keystore file
184                 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
185                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
186                 String sshPort = reqServerPort(props);
187                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
188                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshKey);
189             } else {
190                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
191                 sshClient = null;
192             }
193         } catch (NumberFormatException e) {
194             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
195             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = port in property file has to be an integer.");
196         } catch (Exception e) {
197             logger.error("Error Initializing Saltstack Adapter due to Exception", e);
198             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
199         }
200         logger.info("Initialized Saltstack Adapter");
201     }
202
203     private String reqServerPort(Properties props) {
204         // use default port if null
205         if (props.getProperty(SS_SERVER_PORT) == null) {
206             return "22";
207         }
208         return props.getProperty(SS_SERVER_PORT);
209     }
210
211     private void setSSHClient(Map<String, String> params) throws SvcLogicException {
212         if (sshClient == null) {
213             logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
214                                 "auth details from DG's parameters");
215             String sshHost = messageProcessor.reqHostNameResult(params);
216             String sshPort = messageProcessor.reqPortResult(params);
217             String sshUserName = messageProcessor.reqUserNameResult(params);
218             String sshPassword = messageProcessor.reqPasswordResult(params);
219             logger.info("Creating ssh client with BASIC Auth");
220             if (!testMode) {
221                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
222             }
223         }
224     }
225
226     private String parseEnvParam(JSONObject envParams) {
227         StringBuilder envParamBuilder = new StringBuilder();
228         if (envParams != null) {
229             for (Object key : envParams.keySet()) {
230                 if (envParamBuilder.length() > 0) {
231                     envParamBuilder.append(", ");
232                 }
233                 envParamBuilder.append(key + "=" + envParams.get((String) key));
234                 logger.info("EnvParameters : " + envParamBuilder);
235             }
236         }
237         return envParamBuilder.toString();
238     }
239
240     private String parseFileParam(JSONObject fileParams) {
241         StringBuilder fileParamBuilder = new StringBuilder();
242         if (fileParams != null) {
243             for (Object key : fileParams.keySet()) {
244                 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
245                 logger.info("FileParameters : " + fileParamBuilder);
246             }
247         }
248         return fileParamBuilder.toString();
249     }
250
251     private String putToCommands(SvcLogicContext ctx, String slsFileName,
252                                  String applyTo, JSONObject envParams, JSONObject fileParams) throws SvcLogicException {
253
254         StringBuilder constructedCommand = new StringBuilder();
255         try {
256             File file = new File(slsFileName);
257             String slsFile = file.getName();
258             if (!slsFile.substring(slsFile.lastIndexOf("."),
259                                    slsFile.length()).equalsIgnoreCase(".sls")) {
260                 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
261                         "is not of type .sls");
262             }
263             InputStream in = new FileInputStream(file);
264             byte[] data = new byte[(int) file.length()];
265             in.read(data);
266             String str = new String(data, "UTF-8");
267             in.close();
268             String slsWithoutExtn = stripExtension(slsFile);
269             constructedCommand.append(parseFileParam(fileParams)).append("echo -e \"").append(str).append("\" > /srv/salt/").
270                     append(slsFile).append("; ").append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").
271                     append(applyTo).append("' state.apply ").append(slsWithoutExtn).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
272
273             logger.info("Command to be executed on server : " + constructedCommand.toString());
274
275         } catch (FileNotFoundException e) {
276             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
277                     "not found in path : " + slsFileName + ". " + e.getMessage());
278         } catch (IOException e) {
279             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
280                     "error in path : " + slsFileName + ". " + e.getMessage());
281         } catch (StringIndexOutOfBoundsException e) {
282             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
283                     "is not of type .sls");
284         }
285         return constructedCommand.toString();
286     }
287
288     private String stripExtension(String str) {
289         if (str == null) {
290             return null;
291         }
292         int pos = str.lastIndexOf(".");
293         if (pos == -1) {
294             return str;
295         }
296         return str.substring(0, pos);
297     }
298
299     private String putToCommands(String slsName, String applyTo, JSONObject envParams, JSONObject fileParams) {
300
301         StringBuilder constructedCommand = new StringBuilder();
302
303         constructedCommand.append(parseFileParam(fileParams)).append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").append(applyTo)
304                 .append("' state.apply ").append(slsName).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
305
306         logger.info("Command to be executed on server : " + constructedCommand.toString());
307         return constructedCommand.toString();
308     }
309
310     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
311             throws SvcLogicException {
312
313         // Check status of test request returned by Agent
314         if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
315             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
316             doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
317         } else {
318             logger.info(String.format("Execution of request : successful."));
319             ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
320             ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, OUTCOME_SUCCESS);
321             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
322         }
323     }
324
325     // Public Method to post single command request to execute saltState. Posts the following back
326     // to Svc context memory
327     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
328     //  org.onap.appc.adapter.saltstack.req.messge : any message
329     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
330     @Override
331     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
332         String reqID;
333         boolean slsExec;
334         SaltstackResult testResult;
335         setSSHClient(params);
336         try {
337             reqID = messageProcessor.reqId(params);
338             String commandToExecute = messageProcessor.reqCmd(params);
339             slsExec = messageProcessor.reqIsSLSExec(params);
340             long execTimeout = messageProcessor.reqExecTimeout(params);
341             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
342             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
343             checkResponseStatus(testResult, ctx, reqID, slsExec);
344         } catch (IOException e) {
345             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
346                       "IOException in file stream : " + e.getMessage());
347         }
348     }
349
350     /**
351      * Public Method to post SLS command request to execute saltState on server. Posts the following back
352      * to Svc context memory
353      * <p>
354      * org.onap.appc.adapter.saltstack.req.code : 200 if successful
355      * org.onap.appc.adapter.saltstack.req.messge : any message
356      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
357      */
358     @Override
359     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
360         String reqID;
361         SaltstackResult testResult;
362         setSSHClient(params);
363         try {
364             reqID = messageProcessor.reqId(params);
365             String slsName = messageProcessor.reqSlsName(params);
366             String applyTo = messageProcessor.reqApplyToDevices(params);
367             long execTimeout = messageProcessor.reqExecTimeout(params);
368             JSONObject envParams = messageProcessor.reqEnvParameters(params);
369             JSONObject fileParams = messageProcessor.reqFileParameters(params);
370
371             String commandToExecute = putToCommands(slsName, applyTo, envParams, fileParams);
372             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
373             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
374             checkResponseStatus(testResult, ctx, reqID, true);
375         } catch (IOException e) {
376             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
377                       "IOException in file stream : " + e.getMessage());
378         } catch (JSONException e) {
379             doFailure(ctx, SaltstackResultCodes.INVALID_COMMAND.getValue(), e.getMessage());
380         }
381     }
382
383     /**
384      * Public Method to post SLS file request to execute saltState. Posts the following back
385      * to Svc context memory
386      * <p>
387      * org.onap.appc.adapter.saltstack.req.code : 100 if successful
388      * org.onap.appc.adapter.saltstack.req.messge : any message
389      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
390      */
391     @Override
392     public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
393         String reqID;
394         SaltstackResult testResult;
395         setSSHClient(params);
396         try {
397             reqID = messageProcessor.reqId(params);
398             String slsFile = messageProcessor.reqSlsFile(params);
399             String applyTo = messageProcessor.reqApplyToDevices(params);
400             long execTimeout = messageProcessor.reqExecTimeout(params);
401             JSONObject envParams = messageProcessor.reqEnvParameters(params);
402             JSONObject fileParams = messageProcessor.reqFileParameters(params);
403
404             String commandToExecute = putToCommands(ctx, slsFile, applyTo, envParams, fileParams);
405             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
406             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
407             checkResponseStatus(testResult, ctx, reqID, true);
408         } catch (IOException e) {
409             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
410                       "IOException in file stream : " + e.getMessage());
411         }
412     }
413
414     public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
415                                        long execTimeout)
416             throws SvcLogicException {
417
418         //convert execTimeout to Milliseconds
419         execTimeout = execTimeout * 1000;
420         SaltstackResult testResult = new SaltstackResult();
421         try {
422             if (params.get(CONNECTION_RETRY) == null) {
423                 if (!testMode) {
424                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
425                 } else {
426                     testResult = testServer.mockReqExec(params);
427                 }
428             } else if (params.get(CONNECTION_RETRY).equalsIgnoreCase("true")) {
429                 if (!testMode) {
430                     testResult = sshClient.connectNExecute(commandToExecute, true, execTimeout);
431                 } else {
432                     testResult = testServer.mockReqExec(params);
433                 }
434             } else {
435                 if (!testMode) {
436                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
437                 } else {
438                     testResult = testServer.mockReqExec(params);
439                 }
440             }
441         } catch (IOException e) {
442             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
443                       "IOException in file stream : " + e.getMessage());
444         }
445         return testResult;
446     }
447 }