Sonar fixes in "appc-netconf-adapter-bundle"
[appc.git] / appc-dg / appc-dg-shared / appc-dg-netconf / src / main / java / org / onap / appc / dg / netconf / impl / NetconfClientPluginImpl.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.appc.dg.netconf.impl;
26
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import org.apache.commons.lang.ObjectUtils;
29 import org.apache.commons.lang3.StringUtils;
30 import org.onap.appc.adapter.netconf.*;
31 import org.onap.appc.adapter.netconf.util.Constants;
32 import org.onap.appc.dg.netconf.NetconfClientPlugin;
33 import org.onap.appc.exceptions.APPCException;
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
37 import org.osgi.framework.BundleContext;
38 import org.osgi.framework.FrameworkUtil;
39 import org.osgi.framework.ServiceReference;
40
41 import java.io.IOException;
42 import java.text.DateFormat;
43 import java.text.SimpleDateFormat;
44 import java.util.Date;
45 import java.util.Map;
46
47
48
49 public class NetconfClientPluginImpl implements NetconfClientPlugin {
50
51     private static final String NETCONF_CLIENT_FACTORY_NAME = "org.onap.appc.adapter.netconf.NetconfClientFactory";
52     private static ObjectMapper mapper = new ObjectMapper();
53     private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
54
55     private NetconfDataAccessService dao;
56     private NetconfClientFactory clientFactory;
57
58     public NetconfClientPluginImpl() {
59         BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
60         ServiceReference srefNetconfClientFactory = bctx.getServiceReference(NetconfClientFactory.class);
61         clientFactory = (NetconfClientFactory) bctx.getService(srefNetconfClientFactory);
62     }
63
64     public void setDao(NetconfDataAccessService dao) {
65         this.dao = dao;
66         this.dao.setSchema(Constants.NETCONF_SCHEMA);
67     }
68
69     public void configure(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
70
71         try {
72             // by default, it uses the jsch Netconf Adapter implementation by calling getNetconfClient(NetconfClientType.SSH).
73             NetconfClient client = clientFactory.getNetconfClient(NetconfClientType.SSH);
74             try {
75                 NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class);
76                 String netconfMessage = params.get("file-content");
77                 client.connect(connectionDetails);
78                 client.configure(netconfMessage);
79             } catch (IOException e) {
80                 logger.error("Error " + e.getMessage());
81                 throw new APPCException(e);
82             } finally {
83                 client.disconnect();
84             }
85         } catch (Exception e) {
86             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage());
87             logger.error("Error " + e.getMessage());
88             throw e;
89         }
90     }
91
92     @Override
93     public void operationStateValidation(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
94         if (logger.isTraceEnabled()) {
95             logger.trace("Entering to operationStateValidation with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx));
96         }
97         try{
98             String paramName = Constants.VNF_TYPE_FIELD_NAME;
99             String vfType = params.get(paramName);
100             validateMandatoryParam(paramName, vfType);
101             VnfType vnfType = VnfType.getVnfType(vfType);
102
103             paramName = Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME;
104             String vnfHostIpAddress = params.get(paramName);
105             validateMandatoryParam(paramName, vnfHostIpAddress);
106
107             //get connectionDetails
108             String connectionDetailsStr = params.get(Constants.CONNECTION_DETAILS_FIELD_NAME);
109             NetconfConnectionDetails connectionDetails = null;
110             if(StringUtils.isEmpty(connectionDetailsStr)){
111                 connectionDetails = retrieveConnectionDetails(vnfType);
112                 connectionDetails.setHost(vnfHostIpAddress);
113                 ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails));
114             }else{
115                 connectionDetails = mapper.readValue(connectionDetailsStr, NetconfConnectionDetails.class);
116             }
117             if(connectionDetails == null){
118                 throw new IllegalStateException("missing connectionDetails for VnfType:"+vnfType.name());
119             }
120
121             //get operationsStateNetconfMessage
122             OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(vnfType);
123             String configurationFileName = operationalStateValidator.getConfigurationFileName();
124             String operationsStateNetconfMessage = null;
125             if(!StringUtils.isEmpty(configurationFileName)){
126                 operationsStateNetconfMessage = retrieveConfigurationFileContent(configurationFileName);
127             }
128
129             //connect checK Opertaions state and dissconnect
130             NetconfClient client = clientFactory.getNetconfClient(NetconfClientType.SSH);
131             try {
132                 client.connect(connectionDetails);
133                 String response = null;
134                 if(!StringUtils.isEmpty(operationsStateNetconfMessage)) {
135                     response = client.exchangeMessage(operationsStateNetconfMessage);
136                 }
137                 operationalStateValidator.validateResponse(response);
138             } finally {
139                 client.disconnect();
140             }
141         } catch (APPCException e) {
142             logger.error(e.getMessage());
143             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString());
144             throw e;
145         }
146         catch (Exception e) {
147             logger.error(e.toString());
148             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString());
149             throw new APPCException(e);
150         }
151     }
152
153     @Override
154     public void modifyConfiguration(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
155         this.configure(params, ctx);
156     }
157
158     @Override
159     public void backupConfiguration(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
160
161         NetconfClient client = null;
162         try {
163             if (logger.isDebugEnabled()) {
164                 logger.debug("Entered backup to DEVICE_INTERFACE_LOG");
165             }
166
167             client = clientFactory.getNetconfClient(NetconfClientType.SSH);
168             //get connection details
169             NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class);
170             //connect the client and get configuration
171             client.connect(connectionDetails);
172             String configuration = client.getConfiguration();
173
174             //store configuration in database
175             dao.logDeviceInteraction(null,null,getCurrentDateTime(),configuration);
176
177         } catch (Exception e) {
178             logger.error("Error " + e.getMessage());
179             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage());
180             throw new APPCException(e);
181         } finally {
182             //disconnect the client
183             if(client != null) {
184                 client.disconnect();
185             }
186         }
187     }
188
189     @Override
190     public void getConfig(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
191         NetconfClient client = null;
192         String confId=params.get("conf-id");
193         if(confId.equalsIgnoreCase("current")){
194             try {
195                 if (logger.isDebugEnabled()) {
196                     logger.debug("Entered getConfig to DEVICE_INTERFACE_LOG");
197                 }
198                 //get netconf client to get configuration
199                 BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
200                 ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME);
201                 NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref);
202                 client = clientFactory.getNetconfClient(NetconfClientType.SSH);
203                 //get connection details
204                 NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class);
205                 //connect the client and get configuration
206                 client.connect(connectionDetails);
207                 String configuration = client.getConfiguration();
208                 if(configuration !=null){
209                     String fullConfig = ctx.getAttribute("fullConfig");
210                     fullConfig = fullConfig==null?"":fullConfig;
211                     ctx.setAttribute("fullConfig",fullConfig + configuration);
212
213                     ctx.setAttribute("getConfig_Result","Success");
214                     String entityName=ctx.getAttribute("entity");//VM name
215                     if(entityName!=null){
216                         ctx.setAttribute(entityName+".Configuration",configuration);
217                     }
218                 }else{
219                     ctx.setAttribute("getConfig_Result","failure");
220                 }
221             } catch (Exception e) {
222                 ctx.setAttribute("getConfig_Result","failure");
223                 logger.error("Error " + e.getMessage());
224                 ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage());
225                 throw new APPCException(e);
226             } finally {
227                 //disconnect the client
228                 if(client != null) {
229                     client.disconnect();
230                 }
231             }
232         }else{
233             logger.info("Current Conf id value is not supported");
234         }
235
236     }
237
238
239     @Override
240     public void getRunningConfig(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
241         NetconfClient client = null;
242         try {
243             logger.info("Entered getRunningConfig to DEVICE_INTERFACE_LOG");
244             //get netconf client to get configuration
245             BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
246             ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME);
247             NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref);
248             client = clientFactory.getNetconfClient(NetconfClientType.SSH);
249             //get connection details
250             NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails();
251             connectionDetails.setHost(params.get("host-ip-address"));
252             connectionDetails.setUsername(params.get("user-name"));
253             connectionDetails.setPassword(params.get("password"));
254             connectionDetails.setPort(!("".equalsIgnoreCase(params.get("port-number")))?Integer.parseInt(params.get("port-number")):NetconfConnectionDetails.DEFAULT_PORT);
255             //connect the client and get configuration
256             client.connect(connectionDetails);
257             String configuration = client.getConfiguration();
258             if(configuration !=null){
259                 //  logger.info("*************************************Configuration Output*************************************");
260                 ctx.setAttribute("running-config", configuration);
261
262                 ctx.setAttribute("getRunningConfig_Result","Success");
263             }else{
264                 ctx.setAttribute("getRunningConfig_Result","failure");
265             }
266         } catch (Exception e) {
267             ctx.setAttribute("getRunningConfig_Result","failure");
268             logger.error("Error " + e.getMessage());
269             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage());
270             throw new APPCException(e);
271         } finally {
272             //disconnect the client
273             if(client != null) {
274                 client.disconnect();
275             }
276         }
277     }
278
279     private String getCurrentDateTime() {
280
281         DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
282         Date date = new Date();
283         return dateFormat.format(date);
284     }
285
286     private int getPort(String s) {
287         int port = 830;
288         if((s != null) && !s.isEmpty()) {
289             port = Integer.parseInt(s);
290         }
291         return port;
292     }
293
294     void validateMandatoryParam(String paramName, String paramValue) {
295         if(StringUtils.isEmpty(paramValue)){
296             throw new IllegalArgumentException("input "+paramName+" param is empty");
297         }
298     }
299
300     public NetconfConnectionDetails retrieveConnectionDetails( VnfType vnfType) throws APPCException{
301
302         NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails();
303         if (!dao.retrieveNetconfConnectionDetails(vnfType.getFamilyType().name(), connectionDetails)) {
304             logger.error("Missing configuration for " + vnfType.getFamilyType().name());
305             throw new APPCException("Missing configuration for " + vnfType.getFamilyType().name() + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME);
306         }
307         return connectionDetails;
308     }
309
310     public String retrieveConfigurationFileContent(String configFileName){
311         return dao.retrieveConfigFileName(configFileName);
312     }
313
314 }