Saltstack port not mandatory
[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 = reqServerPort(props) ;
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 = reqServerPort(props);
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 = reqServerPort(props);
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 Exception", e);
208             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
209         }
210         logger.info("Initialized Saltstack Adapter");
211     }
212
213     private String reqServerPort(Properties props) {
214         // use default port if null
215         if (props.getProperty(SS_SERVER_PORT) == null)
216             return "22";
217         return props.getProperty(SS_SERVER_PORT);
218     }
219
220     private void setSSHClient(Map<String, String> params) throws SvcLogicException {
221         if (sshClient == null) {
222             logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
223                                 "auth details from DG's parameters");
224             String sshHost = messageProcessor.reqHostNameResult(params);
225             String sshPort = messageProcessor.reqPortResult(params);
226             String sshUserName = messageProcessor.reqUserNameResult(params);
227             String sshPassword = messageProcessor.reqPasswordResult(params);
228             logger.info("Creating ssh client with BASIC Auth");
229             if (!testMode) {
230                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
231             }
232         }
233     }
234
235     private String parseEnvParam(JSONObject envParams) {
236         StringBuilder envParamBuilder = new StringBuilder();
237         if (envParams != null) {
238             for(Object key : envParams.keySet()) {
239                 if(envParamBuilder.length() > 0) {
240                     envParamBuilder.append(", ");
241                 }
242                 envParamBuilder.append(key+"="+envParams.get((String) key));
243                 logger.info("EnvParameters : " + envParamBuilder);
244             }
245         }
246         return envParamBuilder.toString();
247     }
248
249     private String parseFileParam(JSONObject fileParams) {
250         StringBuilder fileParamBuilder = new StringBuilder();
251         if (fileParams != null) {
252             for(Object key : fileParams.keySet()) {
253                 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
254                 logger.info("FileParameters : " + fileParamBuilder);
255             }
256         }
257         return fileParamBuilder.toString();
258     }
259
260     private String putToCommands(SvcLogicContext ctx, String slsFileName,
261                                     String applyTo, JSONObject envParams, JSONObject fileParams) throws SvcLogicException {
262
263         StringBuilder constructedCommand = new StringBuilder();
264         try {
265             File file = new File(slsFileName);
266             String slsFile = file.getName();
267             if (!slsFile.substring(slsFile.lastIndexOf("."),
268                                    slsFile.length()).equalsIgnoreCase(".sls")) {
269                 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
270                         "is not of type .sls");
271             }
272             InputStream in = new FileInputStream(file);
273             byte[] data = new byte[(int) file.length()];
274             in.read(data);
275             String str = new String(data, "UTF-8");
276             in.close();
277             String slsWithoutExtn = stripExtension(slsFile);
278             constructedCommand.append(parseFileParam(fileParams)).append("echo -e \"").append(str).append("\" > /srv/salt/").
279                     append(slsFile).append("; ").append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").
280                     append(applyTo).append("' state.apply ").append(slsWithoutExtn).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
281
282             logger.info("Command to be executed on server : " + constructedCommand.toString());
283
284         } catch (FileNotFoundException e) {
285             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
286                     "not found in path : " + slsFileName+". "+ e.getMessage());
287         } catch (IOException e) {
288             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
289                     "error in path : " + slsFileName +". "+ e.getMessage());
290         } catch (StringIndexOutOfBoundsException e) {
291             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
292                     "is not of type .sls");
293         }
294         return constructedCommand.toString();
295     }
296
297     private String stripExtension (String str) {
298         if (str == null) return null;
299         int pos = str.lastIndexOf(".");
300         if (pos == -1) return str;
301         return str.substring(0, pos);
302     }
303
304     private String putToCommands(String slsName, String applyTo, JSONObject envParams, JSONObject fileParams) {
305
306         StringBuilder constructedCommand = new StringBuilder();
307
308         constructedCommand.append(parseFileParam(fileParams)).append(COMMAND_CHANGE_DEFAULT_DIR).append(" salt '").append(applyTo)
309                 .append("' state.apply ").append(slsName).append(" ").append(parseEnvParam(envParams)).append(COMMAND_IN_JSON_OUT);
310
311         logger.info("Command to be executed on server : " + constructedCommand.toString());
312         return constructedCommand.toString();
313     }
314
315     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
316             throws SvcLogicException {
317
318         // Check status of test request returned by Agent
319         if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
320             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
321             doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
322         } else {
323             logger.info(String.format("Execution of request : successful."));
324             ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
325             ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, OUTCOME_SUCCESS);
326             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
327         }
328     }
329
330     // Public Method to post single command request to execute saltState. Posts the following back
331     // to Svc context memory
332     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
333     //  org.onap.appc.adapter.saltstack.req.messge : any message
334     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
335     @Override
336     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
337         String reqID;
338         boolean slsExec;
339         SaltstackResult testResult;
340         setSSHClient(params);
341         try {
342             reqID = messageProcessor.reqId(params);
343             String commandToExecute = messageProcessor.reqCmd(params);
344             slsExec = messageProcessor.reqIsSLSExec(params);
345             long execTimeout = messageProcessor.reqExecTimeout(params);
346             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
347             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
348             checkResponseStatus(testResult, ctx, reqID, slsExec);
349         } catch (IOException e) {
350             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
351                       "IOException in file stream : "+ e.getMessage());
352         }
353     }
354
355     /**
356      * Public Method to post SLS command request to execute saltState on server. Posts the following back
357      * to Svc context memory
358      * <p>
359      * org.onap.appc.adapter.saltstack.req.code : 200 if successful
360      * org.onap.appc.adapter.saltstack.req.messge : any message
361      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
362      */
363     @Override
364     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
365         String reqID;
366         SaltstackResult testResult;
367         setSSHClient(params);
368         try {
369             reqID = messageProcessor.reqId(params);
370             String slsName = messageProcessor.reqSlsName(params);
371             String applyTo = messageProcessor.reqApplyToDevices(params);
372             long execTimeout = messageProcessor.reqExecTimeout(params);
373             JSONObject envParams = messageProcessor.reqEnvParameters(params);
374             JSONObject fileParams = messageProcessor.reqFileParameters(params);
375
376             String commandToExecute = putToCommands(slsName, applyTo, envParams, fileParams);
377             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
378             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
379             checkResponseStatus(testResult, ctx, reqID, true);
380         } catch (IOException e) {
381             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
382                       "IOException in file stream : "+ e.getMessage());
383         } catch (JSONException e) {
384             doFailure(ctx, SaltstackResultCodes.INVALID_COMMAND.getValue(), e.getMessage());
385         }
386     }
387
388     /**
389      * Public Method to post SLS file request to execute saltState. Posts the following back
390      * to Svc context memory
391      * <p>
392      * org.onap.appc.adapter.saltstack.req.code : 100 if successful
393      * org.onap.appc.adapter.saltstack.req.messge : any message
394      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
395      */
396     @Override
397     public void reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
398         String reqID;
399         SaltstackResult testResult;
400         setSSHClient(params);
401         try {
402             reqID = messageProcessor.reqId(params);
403             String slsFile = messageProcessor.reqSlsFile(params);
404             String applyTo = messageProcessor.reqApplyToDevices(params);
405             long execTimeout = messageProcessor.reqExecTimeout(params);
406             JSONObject envParams = messageProcessor.reqEnvParameters(params);
407             JSONObject fileParams = messageProcessor.reqFileParameters(params);
408
409             String commandToExecute = putToCommands(ctx, slsFile, applyTo, envParams, fileParams);
410             testResult = execCommand(ctx, params, commandToExecute, execTimeout);
411             testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
412             checkResponseStatus(testResult, ctx, reqID, true);
413         } catch (IOException e) {
414             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
415                       "IOException in file stream : "+ e.getMessage());
416         }
417     }
418
419     public SaltstackResult execCommand(SvcLogicContext ctx, Map<String, String> params, String commandToExecute,
420                                        long execTimeout)
421                                     throws SvcLogicException{
422
423         SaltstackResult testResult = new SaltstackResult();
424         try {
425             if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
426                 int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
427                 int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
428                 if (!testMode) {
429                     testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay, execTimeout);
430                 } else {
431                     testResult = testServer.mockReqExec(params);
432                 }
433             } else {
434                 if (!testMode) {
435                     testResult = sshClient.connectNExecute(commandToExecute, execTimeout);
436                 } else {
437                     testResult = testServer.mockReqExec(params);
438                 }
439             }
440         } catch (IOException e) {
441             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(),
442                       "IOException in file stream : "+ e.getMessage());
443         }
444         return testResult;
445     }
446 }