84e5d4f19c51b1291e371b96fb5778826d32acb4
[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 com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapter;
30 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapterPropertiesProvider;
31 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackMessageParser;
32 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
33 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
34 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackServerEmulator;
35 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
36 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
37
38 import java.io.File;
39 import java.io.FileInputStream;
40 import java.io.FileNotFoundException;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.util.Map;
44 import java.util.Properties;
45
46 /**
47  * This class implements the {@link SaltstackAdapter} interface. This interface defines the behaviors
48  * that our service provides.
49  */
50 public class SaltstackAdapterImpl implements SaltstackAdapter {
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      * The constant for the status code for a failed outcome
59      */
60     @SuppressWarnings("nls")
61     public static final String OUTCOME_FAILURE = "failure";
62     /**
63      * The constant for the status code for a successful outcome
64      */
65     @SuppressWarnings("nls")
66     public static final String OUTCOME_SUCCESS = "success";
67     public static final String CONNECTION_RETRY_DELAY = "retryDelay";
68     public static final String CONNECTION_RETRY_COUNT = "retryCount";
69     private static final long EXEC_TIMEOUT = 120000;
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     private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
76     private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
77     private static final String RESULTS_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.results";
78     private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
79     private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.log";
80     private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
81     private static final String SS_SERVER_HOSTNAME = "org.onap.appc.adapter.saltstack.host";
82     private static final String SS_SERVER_PORT = "org.onap.appc.adapter.saltstack.port";
83     private static final String SS_SERVER_USERNAME = "org.onap.appc.adapter.saltstack.userName";
84     private static final String SS_SERVER_PASSWORD = "org.onap.appc.adapter.saltstack.userPasswd";
85     private static final String SS_SERVER_SSH_KEY = "org.onap.appc.adapter.saltstack.sshKey";
86     /**
87      * The logger to be used
88      */
89     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
90     private long timeout = EXEC_TIMEOUT;
91     /**
92      * Connection object
93      **/
94     private ConnectionBuilder sshClient;
95
96     /**
97      * Saltstack API Message Handlers
98      **/
99     private SaltstackMessageParser messageProcessor;
100
101     /**
102      * indicator whether in test mode
103      **/
104     private boolean testMode = false;
105
106     /**
107      * server emulator object to be used if in test mode
108      **/
109     private SaltstackServerEmulator testServer;
110
111     /**
112      * This default constructor is used as a work around because the activator wasn't getting called
113      */
114     public SaltstackAdapterImpl() throws SvcLogicException{
115         initialize(new SaltstackAdapterPropertiesProviderImpl());
116     }
117
118     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
119         initialize(propProvider);
120     }
121
122     /**
123      * Used for jUnit test and testing interface
124      */
125     public SaltstackAdapterImpl(boolean mode) {
126         testMode = mode;
127         testServer = new SaltstackServerEmulator();
128         messageProcessor = new SaltstackMessageParser();
129     }
130
131     /**
132      * Returns the symbolic name of the adapter
133      *
134      * @return The adapter name
135      * @see SaltstackAdapter#getAdapterName()
136      */
137     @Override
138     public String getAdapterName() {
139         return ADAPTER_NAME;
140     }
141
142     @Override
143     public void setExecTimeout(long timeout) {
144         this.timeout = timeout;
145     }
146
147     /**
148      * Method posts info to Context memory in case of an error and throws a
149      * SvcLogicException causing SLI to register this as a failure
150      */
151     @SuppressWarnings("static-method")
152     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
153
154         svcLogic.setStatus(OUTCOME_FAILURE);
155         svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
156         svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
157         throw new SvcLogicException("Saltstack Adapter Error = " + message);
158     }
159
160     /**
161      * initialize the Saltstack adapter based on default and over-ride configuration data
162      */
163     private void initialize(SaltstackAdapterPropertiesProvider propProvider) throws SvcLogicException{
164
165
166         Properties props = propProvider.getProperties();
167
168         // Create the message processor instance
169         messageProcessor = new SaltstackMessageParser();
170
171         // Create the ssh client instance
172         // type of client is extracted from the property file parameter
173         // org.onap.appc.adapter.saltstack.clientType
174         // It can be :
175         // 1. BASIC. SSH Connection using username and password
176         // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
177         // 3. DEFAULT SSH Connection without any authentication
178
179         try {
180             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
181             logger.info("Saltstack ssh client type set to " + clientType);
182
183             if ("BASIC".equalsIgnoreCase(clientType)) {
184                 logger.info("Creating ssh client connection");
185                 // set path to keystore file
186                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
187                 String sshPort = props.getProperty(SS_SERVER_PORT);
188                 String sshUserName = props.getProperty(SS_SERVER_USERNAME);
189                 String sshPassword = props.getProperty(SS_SERVER_PASSWORD);
190                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
191             } else if ("SSH_CERT".equalsIgnoreCase(clientType)) {
192                 // set path to keystore file
193                 String sshKey = props.getProperty(SS_SERVER_SSH_KEY);
194                 String sshHost = props.getProperty(SS_SERVER_HOSTNAME);
195                 String sshPort = props.getProperty(SS_SERVER_PORT);
196                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
197                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshKey);
198             } else if ("BOTH".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 sshUserName = props.getProperty(SS_SERVER_USERNAME);
203                 String sshPassword = props.getProperty(SS_SERVER_PASSWORD);
204                 String sshPort = props.getProperty(SS_SERVER_PORT);
205                 logger.info("Creating ssh client with ssh KEY from " + sshKey);
206                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword, sshKey);
207             } else if ("NONE".equalsIgnoreCase(clientType)) {
208                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
209                 sshClient = null;
210             } else {
211                 logger.info("No saltstack-adapter.properties defined so reading from DG props");
212                 sshClient = null;
213             }
214         } catch (NumberFormatException e) {
215             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
216             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = port in property file has to be an integer.");
217         } catch (Exception e) {
218             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
219             throw new SvcLogicException("Saltstack Adapter Property file parsing Error = " + e.getMessage());
220         }
221
222         logger.info("Initialized Saltstack Adapter");
223     }
224
225     private void setSSHClient(Map<String, String> params) throws SvcLogicException {
226         if (sshClient == null) {
227             logger.info("saltstack-adapter.properties not defined so reading saltstack host and " +
228                                 "auth details from DG's parameters");
229             String sshHost = messageProcessor.reqHostNameResult(params);
230             String sshPort = messageProcessor.reqPortResult(params);
231             String sshUserName = messageProcessor.reqUserNameResult(params);
232             String sshPassword = messageProcessor.reqPasswordResult(params);
233             logger.info("Creating ssh client with BASIC Auth");
234             if (!testMode) {
235                 sshClient = new ConnectionBuilder(sshHost, sshPort, sshUserName, sshPassword);
236             }
237         }
238     }
239
240     private String putToCommands(SvcLogicContext ctx, String slsFileName,
241                                     String applyTo) throws SvcLogicException {
242         String constructedCommand = "";
243         try {
244             File file = new File(slsFileName);
245             String slsFile = file.getName();
246             if (!slsFile.substring(slsFile.lastIndexOf("."),
247                                    slsFile.length()).equalsIgnoreCase(".sls")) {
248                 doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
249                         "is not of type .sls");
250             }
251             InputStream in = new FileInputStream(file);
252             byte[] data = new byte[(int) file.length()];
253             in.read(data);
254             String str = new String(data, "UTF-8");
255             in.close();
256             String slsWithoutExtn = stripExtension(slsFile);
257             constructedCommand = "echo -e \""+str+"\" > /srv/salt/"+slsFile+"; cd /srv/salt/; salt '"+
258                     applyTo+"' state.apply "+slsWithoutExtn+" --out=json --static";
259         } catch (FileNotFoundException e) {
260             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
261                     "not found in path : " + slsFileName+". "+ e.getMessage());
262         } catch (IOException e) {
263             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input SLS file " +
264                     "error in path : " + slsFileName +". "+ e.getMessage());
265         } catch (StringIndexOutOfBoundsException e) {
266             doFailure(ctx, SaltstackResultCodes.IO_EXCEPTION.getValue(), "Input file " +
267                     "is not of type .sls");
268         }
269         logger.info("Command to be executed on server : " + constructedCommand);
270         return constructedCommand;
271     }
272
273     private String stripExtension (String str) {
274         if (str == null) return null;
275         int pos = str.lastIndexOf(".");
276         if (pos == -1) return str;
277         return str.substring(0, pos);
278     }
279
280     private String putToCommands(String slsName, String applyTo) {
281         String
282             constructedCommand = "cd /srv/salt/; salt '"+applyTo+"' state.apply "+slsName+" --out=json --static";
283
284         logger.info("Command to be executed on server : " + constructedCommand);
285         return constructedCommand;
286     }
287
288     private void checkResponseStatus(SaltstackResult testResult, SvcLogicContext ctx, String reqID, boolean slsExec)
289             throws SvcLogicException {
290
291         // Check status of test request returned by Agent
292         if (testResult.getStatusCode() != SaltstackResultCodes.FINAL_SUCCESS.getValue()) {
293             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
294             doFailure(ctx, testResult.getStatusCode(), "Request for execution of command failed. Reason = " + testResult.getStatusMessage());
295             return;
296         } else {
297             logger.info(String.format("Execution of request : successful."));
298             if (slsExec) {
299                 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(testResult.getStatusCode()));
300                 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, "success");
301             } else {
302                 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(SaltstackResultCodes.CHECK_CTX_FOR_CMD_SUCCESS.getValue()));
303                 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, "check context for execution status");
304             }
305             ctx.setAttribute(ID_ATTRIBUTE_NAME, reqID);
306         }
307     }
308
309     // Public Method to post single command request to execute saltState. Posts the following back
310     // to Svc context memory
311     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
312     //  org.onap.appc.adapter.saltstack.req.messge : any message
313     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
314     @Override
315     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
316         String reqID;
317         boolean slsExec;
318         SaltstackResult testResult;
319         setSSHClient(params);
320         reqID = messageProcessor.reqId(params);
321         String commandToExecute = messageProcessor.reqCmd(params);
322         slsExec = messageProcessor.reqIsSLSExec(params);
323         testResult = execCommand(params, commandToExecute);
324         testResult = messageProcessor.parseResponse(ctx, reqID, testResult, slsExec);
325         checkResponseStatus(testResult, ctx, reqID, slsExec);
326     }
327
328     /**
329      * Public Method to post SLS command request to execute saltState on server. Posts the following back
330      * to Svc context memory
331      * <p>
332      * org.onap.appc.adapter.saltstack.req.code : 200 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      */
336     @Override
337     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
338         String reqID;
339         SaltstackResult testResult;
340         setSSHClient(params);
341         reqID = messageProcessor.reqId(params);
342         String slsName = messageProcessor.reqSlsName(params);
343         String applyTo = messageProcessor.reqApplyToDevices(params);
344         String commandToExecute = putToCommands(slsName, applyTo);
345         testResult = execCommand(params, commandToExecute);
346         testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
347         checkResponseStatus(testResult, ctx, reqID, true);
348     }
349
350     /**
351      * Public Method to post SLS file request to execute saltState. Posts the following back
352      * to Svc context memory
353      * <p>
354      * org.onap.appc.adapter.saltstack.req.code : 100 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 reqExecSLSFile(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
360         String reqID;
361         SaltstackResult testResult;
362         setSSHClient(params);
363         reqID = messageProcessor.reqId(params);
364         String slsFile = messageProcessor.reqSlsFile(params);
365         String applyTo = messageProcessor.reqApplyToDevices(params);
366         String commandToExecute = putToCommands(ctx, slsFile, applyTo);
367         testResult = execCommand(params, commandToExecute);
368         testResult = messageProcessor.parseResponse(ctx, reqID, testResult, true);
369         checkResponseStatus(testResult, ctx, reqID, true);
370     }
371
372     /**
373      * Public method to get logs from saltState execution for a specific request Posts the following back
374      * to Svc context memory
375      * <p>
376      * It blocks till the Saltstack Server responds or the session times out very similar to
377      * reqExecResult logs are returned in the DG context variable org.onap.appc.adapter.saltstack.log
378      */
379     @Override
380     public void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
381         //TODO: to implement
382
383     }
384
385     public SaltstackResult execCommand(Map<String, String> params, String commandToExecute) {
386         SaltstackResult testResult;
387         if (params.get(CONNECTION_RETRY_DELAY) != null && params.get(CONNECTION_RETRY_COUNT) != null) {
388             int retryDelay = Integer.parseInt(params.get(CONNECTION_RETRY_DELAY));
389             int retryCount = Integer.parseInt(params.get(CONNECTION_RETRY_COUNT));
390             if (!testMode) {
391                 testResult = sshClient.connectNExecute(commandToExecute, retryCount, retryDelay);
392             } else {
393                 testResult = testServer.MockReqExec(params);
394             }
395         } else {
396             if (!testMode) {
397                 testResult = sshClient.connectNExecute(commandToExecute);
398             } else {
399                 testResult = testServer.MockReqExec(params);
400             }
401         }
402         return testResult;
403     }
404 }