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