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