SaltStack adaptor API creation
[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 java.util.Map;
28 import java.util.Properties;
29 import org.apache.commons.lang.StringUtils;
30 import org.json.JSONException;
31 import org.json.JSONObject;
32 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapter;
33 import org.onap.ccsdk.sli.adaptors.saltstack.SaltstackAdapterPropertiesProvider;
34 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackMessageParser;
35 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
36 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
37 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackServerEmulator;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42
43 /**
44  * This class implements the {@link SaltstackAdapter} interface. This interface defines the behaviors
45  * that our service provides.
46  */
47 public class SaltstackAdapterImpl implements SaltstackAdapter {
48
49     private static final long EXEC_TIMEOUT = 120000;
50     private long timeout = EXEC_TIMEOUT;
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     /**
59      * The constant for the status code for a failed outcome
60      */
61     @SuppressWarnings("nls")
62     public static final String OUTCOME_FAILURE = "failure";
63
64     /**
65      * The constant for the status code for a successful outcome
66      */
67     @SuppressWarnings("nls")
68     public static final String OUTCOME_SUCCESS = "success";
69
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
76     private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.result.code";
77     private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.message";
78     private static final String RESULTS_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.results";
79     private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.Id";
80     private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.saltstack.log";
81
82     private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.saltstack.clientType";
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
88     /**
89      * The logger to be used
90      */
91     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SaltstackAdapterImpl.class);
92
93
94     /**
95      * Connection object
96      **/
97     private ConnectionBuilder sshClient;
98
99     /**
100      * Saltstack API Message Handlers
101      **/
102     private SaltstackMessageParser messageProcessor;
103
104     /**
105      * indicator whether in test mode
106      **/
107     private boolean testMode = false;
108
109     /**
110      * server emulator object to be used if in test mode
111      **/
112     private SaltstackServerEmulator testServer;
113
114     /**
115      * This default constructor is used as a work around because the activator wasn't getting called
116      */
117     public SaltstackAdapterImpl() {
118         initialize(new SaltstackAdapterPropertiesProviderImpl());
119     }
120     public SaltstackAdapterImpl(SaltstackAdapterPropertiesProvider propProvider) {
121         initialize(propProvider);
122     }
123
124     /**
125      * Used for jUnit test and testing interface
126      */
127     public SaltstackAdapterImpl(boolean mode) {
128         testMode = mode;
129         testServer = new SaltstackServerEmulator();
130         messageProcessor = new SaltstackMessageParser();
131     }
132
133     /**
134      * Returns the symbolic name of the adapter
135      *
136      * @return The adapter name
137      * @see org.onap.appc.adapter.rest.SaltstackAdapter#getAdapterName()
138      */
139     @Override
140     public String getAdapterName() {
141         return ADAPTER_NAME;
142     }
143
144     @Override
145     public void setExecTimeout(long timeout) {
146         this.timeout = timeout;
147     }
148     /**
149      * @param rc Method posts info to Context memory in case of an error and throws a
150      *        SvcLogicException causing SLI to register this as a failure
151      */
152     @SuppressWarnings("static-method")
153     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
154
155         svcLogic.setStatus(OUTCOME_FAILURE);
156         svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
157         svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
158
159         throw new SvcLogicException("Saltstack Adapter Error = " + message);
160     }
161
162     /**
163      * initialize the Saltstack adapter based on default and over-ride configuration data
164      */
165     private void initialize(SaltstackAdapterPropertiesProvider propProvider) {
166
167
168         Properties props = propProvider.getProperties();
169
170         // Create the message processor instance
171         messageProcessor = new SaltstackMessageParser();
172
173         // Create the ssh client instance
174         // type of client is extracted from the property file parameter
175         // org.onap.appc.adapter.saltstack.clientType
176         // It can be :
177         // 1. BASIC. SSH Connection using username and password
178         // 2. SSH_CERT (trust only those whose certificates have been stored in the SSH KEY file)
179         // 3. DEFAULT SSH Connection without any authentication
180
181         try {
182             String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
183             logger.info("Saltstack ssh client type set to " + clientType);
184
185             if ("BASIC".equals(clientType)) {
186                 logger.info("Creating ssh client connection");
187                 // set path to keystore file
188                 String trustStoreFile = props.getProperty(SS_SERVER_USERNAME);
189                 String key = props.getProperty(SS_SERVER_PASSWORD);
190                 //TODO: Connect to SSH Saltstack server (using username and password) and return client to execute command
191                 sshClient = null;
192             } else if ("SSH_CERT".equals(clientType)) {
193                 // set path to keystore file
194                 String key = props.getProperty(SS_SERVER_SSH_KEY);
195                 logger.info("Creating ssh client with ssh KEY from " + key);
196                 //TODO: Connect to SSH Saltstack server (using SSH Key) and return client to execute command
197                 sshClient = null;
198             } else {
199                 logger.info("Creating ssh client without any Auth");
200                 //TODO: Connect to SSH Saltstack server without any Auth
201                 sshClient = null;
202             }
203         } catch (Exception e) {
204             logger.error("Error Initializing Saltstack Adapter due to Unknown Exception", e);
205         }
206
207         logger.info("Initialized Saltstack Adapter");
208     }
209
210     // Public Method to post single command request to execute saltState. Posts the following back
211     // to Svc context memory
212     //  org.onap.appc.adapter.saltstack.req.code : 100 if successful
213     //  org.onap.appc.adapter.saltstack.req.messge : any message
214     //  org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
215     @Override
216     public void reqExecCommand(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
217         //TODO: to implement
218     }
219
220     /**
221      * Public Method to post SLS file request to execute saltState. Posts the following back
222      * to Svc context memory
223      *
224      * org.onap.appc.adapter.saltstack.req.code : 100 if successful
225      * org.onap.appc.adapter.saltstack.req.messge : any message
226      * org.onap.appc.adapter.saltstack.req.Id : a unique uuid to reference the request
227      */
228     @Override
229     public void reqExecSLS(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
230         //TODO: to implement
231
232     }
233
234     /**
235      * Public method to get logs from saltState execution for a specific request Posts the following back
236      * to Svc context memory
237      *
238      * It blocks till the Saltstack Server responds or the session times out very similar to
239      * reqExecResult logs are returned in the DG context variable org.onap.appc.adapter.saltstack.log
240      */
241     @Override
242     public void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
243         //TODO: to implement
244
245     }
246 }