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