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