875300ddb35eb681bd2b5fb8ab769239a28df520
[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                     //  logger.info("*************************************Configuration Output*************************************");
207                     //  logger.info(configuration);
208                     String fullConfig = ctx.getAttribute("fullConfig");
209                     fullConfig = fullConfig==null?"":fullConfig;
210                     ctx.setAttribute("fullConfig",fullConfig + configuration);
211
212                     ctx.setAttribute("getConfig_Result","Success");
213                     String entityName=ctx.getAttribute("entity");//VM name
214                     if(entityName!=null){
215                         ctx.setAttribute(entityName+".Configuration",configuration);
216                     }
217                 }else{
218                     ctx.setAttribute("getConfig_Result","failure");
219                 }
220                 //store configuration in database
221             /*NetconfJDBC dsImpl = new NetconfJDBCImpl();
222             dsImpl.logDeviceInteraction(null,null,getCurrentDateTime(),configuration);*/
223
224             } catch (Exception e) {
225                 ctx.setAttribute("getConfig_Result","failure");
226                 logger.error("Error " + e.getMessage());
227                 ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage());
228                 throw new APPCException(e);
229             } finally {
230                 //disconnect the client
231                 if(client != null) {
232                     client.disconnect();
233                 }
234             }
235         }else{
236             logger.info("Current Conf id value is not supported");
237         }
238
239     }
240
241
242     @Override
243     public void getRunningConfig(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
244         NetconfClient client = null;
245         try {
246             logger.info("Entered getRunningConfig to DEVICE_INTERFACE_LOG");
247             //get netconf client to get configuration
248             BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
249             ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME);
250             NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref);
251             client = clientFactory.GetNetconfClient(NetconfClientType.SSH);
252             //get connection details
253             NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails();
254             connectionDetails.setHost(params.get("host-ip-address"));
255             connectionDetails.setUsername(params.get("user-name"));
256             connectionDetails.setPassword(params.get("password"));
257             connectionDetails.setPort(!("".equalsIgnoreCase(params.get("port-number")))?Integer.parseInt(params.get("port-number")):NetconfConnectionDetails.DEFAULT_PORT);
258             //connect the client and get configuration
259             client.connect(connectionDetails);
260             String configuration = client.getConfiguration();
261             if(configuration !=null){
262                 //  logger.info("*************************************Configuration Output*************************************");
263                 ctx.setAttribute("running-config", configuration);
264
265                 ctx.setAttribute("getRunningConfig_Result","Success");
266             }else{
267                 ctx.setAttribute("getRunningConfig_Result","failure");
268             }
269         } catch (Exception e) {
270             ctx.setAttribute("getRunningConfig_Result","failure");
271             logger.error("Error " + e.getMessage());
272             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage());
273             throw new APPCException(e);
274         } finally {
275             //disconnect the client
276             if(client != null) {
277                 client.disconnect();
278             }
279         }
280     }
281
282     private String getCurrentDateTime() {
283
284         DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
285         Date date = new Date();
286         return dateFormat.format(date);
287     }
288
289     private int getPort(String s) {
290         int port = 830;
291         if((s != null) && !s.isEmpty()) {
292             port = Integer.parseInt(s);
293         }
294         return port;
295     }
296
297     void validateMandatoryParam(String paramName, String paramValue) {
298         if(StringUtils.isEmpty(paramValue)){
299             throw new IllegalArgumentException("input "+paramName+" param is empty");
300         }
301     }
302
303     public NetconfConnectionDetails retrieveConnectionDetails( VnfType vnfType) throws APPCException{
304
305         NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails();
306         if (!dao.retrieveNetconfConnectionDetails(vnfType.getFamilyType().name(), connectionDetails)) {
307             logger.error("Missing configuration for " + vnfType.getFamilyType().name());
308             throw new APPCException("Missing configuration for " + vnfType.getFamilyType().name() + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME);
309         }
310         return connectionDetails;
311     }
312
313     public String retrieveConfigurationFileContent(String configFileName){
314         return dao.retrieveConfigFileName(configFileName);
315     }
316
317 }