saltstack to take env and file param
[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_DELAY = "retryDelay";
65     public static final String CONNECTION_RETRY_COUNT = "retryCount";
66     private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
67     /**
68      * Adapter Name
69      */
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";
80
81     private static final String COMMAND_IN_JSON_OUT = " --out=json --static ";
82     private static final String COMMAND_CHANGE_DEFAULT_DIR = " cd /srv/salt/ ;";
83
84     /**
85      * The logger to be used
86      */
87     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
88     /**
89      * Connection object
90      **/
91     private ConnectionBuilder sshClient;
92
93     /**
94      * Saltstack API Message Handlers
95      **/
96     private SaltstackMessageParser messageProcessor;
97
98     /**
99      * indicator whether in test mode
100      **/
101     private boolean testMode = false;
102
103     /**
104      * server emulator object to be used if in test mode
105      **/
106     private SaltstackServerEmulator testServer;
107
108     /**
109      * This default constructor is used as a work around because the activator wasn't getting called
110      */
111     public SaltstackAdapterImpl() throws SvcLogicException{
112         initialize(new SaltstackAdapterPropertiesProviderImpl());
113     }
114
115     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
116         initialize(propProvider);
117     }
118
119     /**
120      * Used for jUnit test and testing interface
121      */
122     public SaltstackAdapterImpl(boolean mode) {
123         testMode = mode;
124         testServer = new SaltstackServerEmulator();
125         messageProcessor = new SaltstackMessageParser();
126     }
127
128     /**
129      * Returns the symbolic name of the adapter
130      *
131      * @return The adapter name
132      * @see SaltstackAdapter#getAdapterName()
133      */
134     @Override
135     public String getAdapterName() {
136         return ADAPTER_NAME;
137     }
138
139     /**
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
142      */
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);
150     }
151
152     /**
153      * initialize the Saltstack adapter based on default and over-ride configuration data
154      */
155     private void initialize(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
156
157
158         Properties props = propProvider.getProperties();
159
160         // Create the message processor instance
161         messageProcessor = new SaltstackMessageParser();
162
163         // Create the ssh client instance
164         // type of client is extracted from the property file parameter
165         // org.onap.appc.adapter.saltstack.clientType
166         // It can be :
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
170
171         try {
172             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
173             logger.info("Saltstack ssh client type set to " + clientType);
174
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);
199             } else {
200                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
201                 sshClient = null;
202             }
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());
209         }
210
211         logger.info("Initialized Saltstack Adapter");
212     }
213
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");
223             if (!testMode) {
224                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
225             }
226         }
227     }
228
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(", ");
235                 }
236                 envParamBuilder.append(key+"="+envParams.get((String) key));
237                 logger.info("EnvParameters : " + envParamBuilder);
238             }
239         }
240         return envParamBuilder.toString();
241     }
242
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);
249             }
250         }
251         return fileParamBuilder.toString();
252     }
253
254     private String putToCommands(SvcLogicContext ctx, String slsFileName,
255                                     String applyTo, JSONObject envParams, JSONObject fileParams) throws SvcLogicException {
256
257         StringBuilder constructedCommand = new StringBuilder();
258         try {
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");
265             }
266             InputStream in = new FileInputStream(file);
267             byte[] data = new byte[(int) file.length()];
268             in.read(data);
269             String str = new String(data, "UTF-8");
270             in.close();
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);
275
276             logger.info("Command to be executed on server : " + constructedCommand.toString());
277
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");
287         }
288         return constructedCommand.toString();
289     }
290
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);
296     }
297
298     private String putToCommands(String slsName, String applyTo, JSONObject envParams, JSONObject fileParams) {
299
300         StringBuilder constructedCommand = new StringBuilder();
301
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);
304
305         logger.info("Command to be executed on server : " + constructedCommand.toString());
306         return constructedCommand.toString();
307     }
308
309     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
310             throws SvcLogicException {
311
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());
316         } else {
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);
321         }
322     }
323
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
329     @Override
330     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
331         String reqID;
332         boolean slsExec;
333         SaltstackResult testResult;
334         setSSHClient(params);
335         try {
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());
346         }
347     }
348
349     /**
350      * Public Method to post SLS command request to execute saltState on server. Posts the following back
351      * to Svc context memory
352      * <p>
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
356      */
357     @Override
358     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
359         String reqID;
360         SaltstackResult testResult;
361         setSSHClient(params);
362         try {
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);
369
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());
379         }
380     }
381
382     /**
383      * Public Method to post SLS file request to execute saltState. Posts the following back
384      * to Svc context memory
385      * <p>
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
389      */
390     @Override
391     public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
392         String reqID;
393         SaltstackResult testResult;
394         setSSHClient(params);
395         try {
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);
402
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());
410         }
411     }
412
413     public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
414                                        long execTimeout)
415                                     throws SvcLogicException{
416
417         SaltstackResult testResult = new SaltstackResult();
418         try {
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));
422                 if (!testMode) {
423                     testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay, execTimeout);
424                 } else {
425                     testResult = testServer.mockReqExec(params);
426                 }
427             } else {
428                 if (!testMode) {
429                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
430                 } else {
431                     testResult = testServer.mockReqExec(params);
432                 }
433             }
434         } catch (IOException e) {
435             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
436                       "IOException in file stream : "+ e.getMessage());
437         }
438         return testResult;
439     }
440 }