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