2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * =============================================================================
7 * Modifications Copyright (C) 2018-2019 IBM.
8 * =============================================================================
9 * Modifications Copyright (C) 2018-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
15 * http://www.apache.org/licenses/LICENSE-2.0
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.
23 * ============LICENSE_END=========================================================
26 package org.onap.appc.ccadaptor;
28 import java.io.BufferedReader;
29 import java.io.ByteArrayInputStream;
30 import java.io.FileReader;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.io.StringReader;
35 import java.io.StringWriter;
36 import java.net.HttpURLConnection;
37 import java.util.HashMap;
39 import java.util.NoSuchElementException;
40 import java.util.Properties;
41 import java.util.StringTokenizer;
42 import javax.xml.parsers.DocumentBuilder;
43 import javax.xml.parsers.DocumentBuilderFactory;
44 import javax.xml.parsers.ParserConfigurationException;
45 import javax.xml.transform.OutputKeys;
46 import javax.xml.transform.Transformer;
47 import javax.xml.transform.TransformerException;
48 import javax.xml.transform.TransformerFactory;
49 import javax.xml.transform.dom.DOMSource;
50 import javax.xml.transform.stream.StreamResult;
51 import javax.xml.xpath.XPath;
52 import javax.xml.xpath.XPathConstants;
53 import javax.xml.xpath.XPathExpressionException;
54 import javax.xml.xpath.XPathFactory;
55 import org.onap.appc.exceptions.APPCException;
56 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
57 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
58 import org.w3c.dom.Document;
59 import org.w3c.dom.Node;
60 import org.xml.sax.InputSource;
61 import org.xml.sax.SAXException;
62 import com.att.eelf.configuration.EELFLogger;
63 import com.att.eelf.configuration.EELFManager;
64 import org.glassfish.jersey.oauth1.signature.Base64;
65 import org.glassfish.jersey.client.ClientConfig;
66 import org.glassfish.jersey.client.ClientProperties;
68 import javax.ws.rs.client.Client;
69 import javax.ws.rs.client.ClientBuilder;
70 import javax.ws.rs.client.Entity;
71 import javax.ws.rs.client.WebTarget;
72 import javax.ws.rs.core.Response;
74 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
76 private static EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
77 DebugLog debugLog = new DebugLog();
78 private String configUrl = null;
79 private String configUser = null;
80 private String configPassword = null;
81 private String auditUrl = null;
82 private String auditUser = null;
83 private String auditPassword = null;
85 public String getConfigUrl() {
89 public String getConfigUser() {
93 public String getConfigPassword() {
94 return configPassword;
97 public String getAuditUrl() {
101 public String getAuditUser() {
105 public String getAuditPassword() {
106 return auditPassword;
109 public String getConfigCallbackUrl() {
110 return configCallbackUrl;
113 public String getAuditCallbackUrl() {
114 return auditCallbackUrl;
117 private String configCallbackUrl = null;
118 private String auditCallbackUrl = null;
119 private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ;
121 public ConfigComponentAdaptor(Properties props) {
123 configUrl = props.getProperty("configComponent.url", "");
124 configUser = props.getProperty("configComponent.user", "");
125 configPassword = props.getProperty("configComponent.passwd", "");
126 auditUrl = props.getProperty("auditComponent.url", "");
127 auditUser = props.getProperty("auditComponent.user", "");
128 auditPassword = props.getProperty("auditComponent.passwd", "");
129 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
130 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
138 configCallbackUrl = "";
139 auditCallbackUrl = "";
144 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
145 String fnName = "ConfigComponentAdaptor.configure";
146 HttpResponse r = new HttpResponse();
148 log.debug("ConfigComponentAdaptor.configure - key = " + key);
149 DebugLog.printRTAriDebug(fnName, "key = " + key);
150 log.debug("Parameters:");
151 DebugLog.printRTAriDebug(fnName, "Parameters:");
152 for (Map.Entry<String, String> entry : parameters.entrySet()) {
153 log.debug(" " + entry.getKey() + " = " + entry.getValue());
154 DebugLog.printRTAriDebug(fnName, " " + entry.getKey() + " = " + entry.getValue());
157 String parmval = parameters.get("config-component-configUrl");
158 if ((parmval != null) && (parmval.length() > 0)) {
159 log.debug("Overwriting URL with " + parmval);
163 parmval = parameters.get("config-component-configPassword");
164 if ((parmval != null) && (parmval.length() > 0)) {
165 //log.debug("Overwriting configPassword with " + parmval);
166 configPassword = parmval;
169 parmval = parameters.get("config-component-configUser");
170 if ((parmval != null) && (parmval.length() > 0)) {
171 log.debug("Overwriting configUser id with " + parmval);
172 configUser = parmval;
175 String action = parameters.get("action");
177 String chg = ctx.getAttribute(
178 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
179 if (chg != null && "prepare".equalsIgnoreCase(action)) {
180 return prepare(ctx, "CHANGE", "change");
182 if (chg != null && "activate".equalsIgnoreCase(action)) {
183 return activate(ctx, true);
186 String scale = ctx.getAttribute(
187 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
188 if (scale != null && "prepare".equalsIgnoreCase(action)) {
189 return prepare(ctx, "CHANGE", "scale");
191 if (scale != null && "activate".equalsIgnoreCase(action)) {
192 return activate(ctx, true);
195 if ("prepare".equalsIgnoreCase(action)) {
196 return prepare(ctx, "BASE", "create");
198 if ("activate".equalsIgnoreCase(action)) {
199 return activate(ctx, false);
202 if ("backup".equalsIgnoreCase(action)) {
203 return prepare(ctx, "BACKUP", "backup");
205 if ("restorebackup".equalsIgnoreCase(action)) {
206 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
208 if ("deletebackup".equalsIgnoreCase(action)) {
209 return prepare(ctx, "DELETEBACKUP", "deletebackup");
211 if ("audit".equalsIgnoreCase(action)) {
212 return audit(ctx, "FULL");
214 if ("getrunningconfig".equalsIgnoreCase(action)) {
215 return audit(ctx, "RUNNING");
218 if (("put".equals(key)) || ("get".equals(key))) {
219 String loginId = parameters.get("loginId");
220 String host = parameters.get("host");
221 String password = parameters.get("password");
222 password = EncryptionTool.getInstance().decrypt(password);
223 String fullPathFileName = parameters.get("fullPathFileName");
226 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
227 log.debug("SCP: SshJcraftWrapper has been instantiated");
228 DebugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
230 if (key.equals("put")) {
231 data = parameters.get("data");
233 DebugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
234 InputStream is = new ByteArrayInputStream(data.getBytes());
235 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
236 DebugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
237 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
239 DebugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
240 Thread.sleep(1000l * 180);
241 DebugLog.printRTAriDebug(fnName, "Woke up....");
242 } catch (java.lang.InterruptedException ee) {
243 boolean ignore = true;
244 Thread.currentThread().interrupt();
247 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
248 log.debug(fnName + " Command is for put: data is null");
250 } else // Must be a get
252 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
253 DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
254 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
255 DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
256 ctx.setAttribute("fileContents", response);
257 log.debug("SCP: Closing the SFTP connection");
259 return (setResponseStatus(ctx, r));
260 } catch (IOException e) {
261 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
262 log.debug(fnName + " : Caught a IOException e=" + e);
263 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
264 r.message = e.getMessage();
265 return (setResponseStatus(ctx, r));
268 if (key.equals("cli")) {
269 String loginId = parameters.get("loginId");
270 String host = parameters.get("host");
271 String password = parameters.get("password");
272 password = EncryptionTool.getInstance().decrypt(password);
273 String portNumber = parameters.get("portNumber");
274 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
276 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
277 " portNumber=" + portNumber);
278 DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
279 " portNumber=" + portNumber);
280 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
282 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
283 String response = sshJcraftWrapper.send("sdc", ":");
284 DebugLog.printAriDebug(fnName, "Sending 1");
285 response = sshJcraftWrapper.send("1", ":");
286 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
287 response = sshJcraftWrapper.send("1", "#");
288 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
289 response = sshJcraftWrapper.send("paging-options disable", "#");
290 DebugLog.printAriDebug(fnName, "Sending show config");
291 response = sshJcraftWrapper.send("show config", "#");
293 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
294 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
295 ctx.setAttribute("cliOutput", response);
296 sshJcraftWrapper.closeConnection();
298 sshJcraftWrapper = null;
299 return (setResponseStatus(ctx, r));
300 } catch (IOException e) {
301 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
302 log.debug(fnName + " : Caught a IOException e=" + e);
303 sshJcraftWrapper.closeConnection();
304 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
305 r.message = e.getMessage();
306 sshJcraftWrapper = null;
307 DebugLog.printAriDebug(fnName, "Returning error message");
308 return (setResponseStatus(ctx, r));
311 if (key.equals("escapeSql")) {
312 String data = parameters.get("artifactContents");
313 log.debug("ConfigComponentAdaptor.configure - escapeSql");
314 data = escapeMySql(data);
315 ctx.setAttribute("escapedData", data);
316 return (setResponseStatus(ctx, r));
318 if (key.equals("GetCliRunningConfig")) {
319 DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
320 log.debug("key was: GetCliRunningConfig: ");
321 String userName = parameters.get("User_name");
322 String hostIpAddress = parameters.get("Host_ip_address");
323 String password = parameters.get("Password");
324 password = EncryptionTool.getInstance().decrypt(password);
325 String portNumber = parameters.get("Port_number");
326 String getConfigTemplate = parameters.get("Get_config_template");
327 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
328 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
329 DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
331 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + userName +
332 " Host_ip_address=" + hostIpAddress + " Port_number="
334 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + hostIpAddress +
335 " User_name=" + userName + " Port_number=" + portNumber);
336 String response = "";
337 String CliResponse = "";
338 boolean showConfigFlag = false;
339 sshJcraftWrapper.connect(hostIpAddress,
344 Integer.parseInt(portNumber));
345 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
346 StringTokenizer st = new StringTokenizer(getConfigTemplate, "\n");
347 String command = null;
349 while (st.hasMoreTokens()) {
350 String line = st.nextToken();
351 DebugLog.printAriDebug(fnName, "line=" + line);
352 if (line.indexOf("Request:") != -1) {
353 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
354 command = getStringBetweenQuotes(line);
355 DebugLog.printAriDebug(fnName, "Sending command=" + command);
356 sshJcraftWrapper.send(command);
357 DebugLog.printAriDebug(fnName, "command has been sent");
358 if (line.indexOf("show config") != -1) {
359 showConfigFlag = true;
360 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
361 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
364 if (line.indexOf("Response: Ends_With") != -1) {
365 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
366 String delemeter = getStringBetweenQuotes(line);
367 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
368 //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806
369 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter,
370 DEFAULT_TIMEOUT_GETRUNNING_CLI, command);
371 response += tmpResponse;
372 if (showConfigFlag) {
373 showConfigFlag = false;
374 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
375 // Strip off the last line which is the command prompt from the VNF device.
376 while (st2.hasMoreTokens()) {
377 String line2 = st2.nextToken();
378 if (line2.indexOf('#') == -1) {
379 CliResponse += line2 + "\n";
385 } catch (NoSuchElementException e) {
386 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
388 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
389 ctx.setAttribute("cliOutput", CliResponse);
390 sshJcraftWrapper.closeConnection();
392 sshJcraftWrapper = null;
393 return (setResponseStatus(ctx, r));
394 } catch (IOException e) {
395 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
396 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
397 sshJcraftWrapper.closeConnection();
398 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
399 r.message = e.getMessage();
400 sshJcraftWrapper = null;
401 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
402 return (setResponseStatus(ctx, r));
405 if (key.equals("xml-download")) {
406 log(fnName, "key was: xml-download");
407 String userName = parameters.get("User_name");
408 String hostIpAddress = parameters.get("Host_ip_address");
409 String password = parameters.get("Password");
410 password = EncryptionTool.getInstance().decrypt(password);
411 String portNumber = parameters.get("Port_number");
412 String Contents = parameters.get("Contents");
413 String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <capabilities>\n <capability>urn:ietf:params:netconf:base:1.0</capability>\n <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
414 String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
415 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\"> <commit/> </rpc>\n ]]>]]>";
418 "xml-download: User_name=" + userName + " Host_ip_address=" + hostIpAddress
419 + " Port_number=" + portNumber);
420 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
422 sshJcraftWrapper.connect(hostIpAddress,
427 Integer.parseInt(portNumber),
429 String NetconfHelloCmd = netconfHelloCmd;
430 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
431 log(fnName, "Sending the hello command");
432 sshJcraftWrapper.send(NetconfHelloCmd);
433 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
434 log(fnName, "Sending xmlCmd cmd");
435 String xmlCmd = Contents;
436 String messageId = "1";
437 messageId = "\"" + messageId + "\"";
438 String loadConfigurationString =
439 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
441 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
442 + xmlCmd + "</config> </edit-config> </rpc>";
443 loadConfigurationString = loadConfigurationString + "]]>]]>";
444 sshJcraftWrapper.send(loadConfigurationString);
445 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
446 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
447 if (response.indexOf("rpc-error") != -1) {
448 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
449 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
450 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
451 r.message = response;
453 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
454 sshJcraftWrapper.send(commitCmd);
455 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
456 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
457 if (response.indexOf("rpc-error") != -1) {
458 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
459 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
460 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
461 r.message = response;
463 DebugLog.printAriDebug(fnName, ":Looks like a success");
464 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
468 sshJcraftWrapper.send(terminateConnectionCmd);
469 sshJcraftWrapper.closeConnection();
470 sshJcraftWrapper = null;
471 return (setResponseStatus(ctx, r));
472 } catch (Exception e) {
473 log(fnName, "Caught an Exception, e=" + e);
474 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
475 sshJcraftWrapper.closeConnection();
476 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
477 r.message = e.getMessage();
478 sshJcraftWrapper = null;
479 log(fnName, "Returning error message");
480 return (setResponseStatus(ctx, r));
483 if (key.equals("xml-getrunningconfig")) {
484 log(fnName, "key was: : xml-getrunningconfig");
485 String xmlGetRunningConfigCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\"> <get-config> <source> <running /> </source> </get-config> </rpc>\n";
486 String hostIpAddress = parameters.get("Host_ip_address");
487 String userName = parameters.get("User_name");
488 String password = parameters.get("Password");
489 password = EncryptionTool.getInstance().decrypt(password);
490 String portNumber = parameters.get("Port_number");
491 String Protocol = parameters.get("Protocol");
492 String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <capabilities>\n <capability>urn:ietf:params:netconf:base:1.0</capability>\n <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
493 String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
495 "xml-getrunningconfig: User_name=" + userName + " Host_ip_address=" + hostIpAddress
496 + " Port_number=" + portNumber);
497 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
499 String NetconfHelloCmd = netconfHelloCmd;
500 sshJcraftWrapper.connect(hostIpAddress,
505 Integer.parseInt(portNumber),
507 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
508 log(fnName, ":Sending the hello command");
509 sshJcraftWrapper.send(NetconfHelloCmd);
510 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
511 log(fnName, "Sending get running config command");
512 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
513 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
514 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
515 response = trimResponse(response);
516 ctx.setAttribute("xmlRunningConfigOutput", response);
517 sshJcraftWrapper.send(terminateConnectionCmd);
518 sshJcraftWrapper.closeConnection();
520 sshJcraftWrapper = null;
521 return (setResponseStatus(ctx, r));
522 } catch (Exception e) {
523 log(fnName, "Caught an Exception, e=" + e);
524 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
525 sshJcraftWrapper.closeConnection();
526 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
527 r.message = e.getMessage();
528 sshJcraftWrapper = null;
529 log(fnName, "Returning error message");
530 return (setResponseStatus(ctx, r));
533 if (key.equals("DownloadCliConfig")) {
534 DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
535 log.debug("key was: DownloadCliConfig: ");
536 String userName = parameters.get("User_name");
537 String hostIpAddress = parameters.get("Host_ip_address");
538 String password = parameters.get("Password");
539 password = EncryptionTool.getInstance().decrypt(password);
540 String portNumber = parameters.get("Port_number");
541 String downloadConfigTemplate = parameters.get("Download_config_template");
542 String Config_contents = parameters.get("Config_contents");
543 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
544 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
545 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
546 DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
547 int timeout = 4 * 60 * 1000;
549 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + userName +
550 " Host_ip_address=" + hostIpAddress + " Port_number="
552 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + hostIpAddress +
553 " User_name=" + userName + " Port_number=" + portNumber);
554 String CliResponse = "";
555 sshJcraftWrapper.connect(hostIpAddress,
560 Integer.parseInt(portNumber));
561 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
562 StringTokenizer st = new StringTokenizer(downloadConfigTemplate, "\n");
563 String command = null;
564 String executeConfigContentsDelemeter = null;
566 while (st.hasMoreTokens()) {
567 String line = st.nextToken();
568 DebugLog.printAriDebug(fnName, "line=" + line);
569 if (line.indexOf("Request:") != -1) {
570 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
571 command = getStringBetweenQuotes(line);
572 DebugLog.printAriDebug(fnName, "Sending command=" + command);
573 sshJcraftWrapper.send(command);
574 DebugLog.printAriDebug(fnName, "command has been sent");
575 } else if ((line.indexOf("Response: Ends_With") != -1) && (
576 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
577 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
578 String delemeter = getStringBetweenQuotes(line);
579 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
580 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
581 CliResponse += tmpResponse;
582 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
583 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
584 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
585 DebugLog.printAriDebug(fnName,
586 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
587 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
588 while (st2.hasMoreTokens()) {
589 String cmd = st2.nextToken();
590 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
591 sshJcraftWrapper.send(cmd);
592 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
595 CliResponse += tmpResponse;
599 } catch (NoSuchElementException e) {
600 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
602 sshJcraftWrapper.closeConnection();
603 sshJcraftWrapper = null;
604 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
605 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
606 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
607 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
608 ctx.setAttribute("cliOutput", CliResponse);
610 return (setResponseStatus(ctx, r));
611 } catch (IOException e) {
612 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
613 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
614 sshJcraftWrapper.closeConnection();
615 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
616 r.message = e.getMessage();
617 sshJcraftWrapper = null;
618 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
619 return (setResponseStatus(ctx, r));
623 DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
624 log.error("Unsupported action - " + action);
625 return ConfigStatus.FAILURE;
628 private void log(String fileName, String messg) {
629 DebugLog.printRTAriDebug(fileName, messg);
630 log.debug(fileName + ": " + messg);
633 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
634 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
635 String ndTemplate = readFile(templateName);
636 String nd = buildNetworkData2(ctx, ndTemplate, operation);
638 String reqTemplate = readFile("/config-request.xml");
639 Map<String, String> param = new HashMap<String, String>();
640 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
641 param.put("request-type", requestType);
642 param.put("callback-url", configCallbackUrl);
643 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
644 param.put("action", "GenerateOnly");
646 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
647 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
648 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
649 param.put("network-data", nd);
653 req = buildXmlRequest(param, reqTemplate);
654 } catch (Exception e) {
655 log.error("Error building the XML request: ", e);
657 HttpResponse r = new HttpResponse();
658 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
659 r.message = e.getMessage();
660 return setResponseStatus(ctx, r);
663 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
664 return setResponseStatus(ctx, r);
667 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
668 String reqTemplate = readFile("/config-request.xml");
669 Map<String, String> param = new HashMap<String, String>();
670 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
671 param.put("callback-url", configCallbackUrl);
672 param.put("action", change ? "DownloadChange" : "DownloadBase");
673 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
677 req = buildXmlRequest(param, reqTemplate);
678 } catch (Exception e) {
679 log.error("Error building the XML request: ", e);
681 HttpResponse r = new HttpResponse();
682 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
683 r.message = e.getMessage();
684 return setResponseStatus(ctx, r);
687 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
688 return setResponseStatus(ctx, r);
691 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
692 String reqTemplate = readFile("/audit-request.xml");
693 Map<String, String> param = new HashMap<String, String>();
694 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
695 param.put("callback-url", auditCallbackUrl);
696 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
697 param.put("audit-level", auditLevel);
701 req = buildXmlRequest(param, reqTemplate);
702 } catch (Exception e) {
703 log.error("Error building the XML request: ", e);
705 HttpResponse r = new HttpResponse();
706 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
707 r.message = e.getMessage();
708 return setResponseStatus(ctx, r);
711 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
712 return setResponseStatus(ctx, r);
716 public ConfigStatus activate(String key, SvcLogicContext ctx) {
717 return ConfigStatus.SUCCESS;
721 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
722 return ConfigStatus.SUCCESS;
725 private String escapeMySql(String input) {
730 input = input.replace("\\", "\\\\");
731 input = input.replace("\'", "\\'");
736 protected String readFile(String fileName) {
737 InputStream is = getClass().getResourceAsStream(fileName);
738 InputStreamReader isr = new InputStreamReader(is);
739 BufferedReader in = new BufferedReader(isr);
740 StringBuilder ss = new StringBuilder();
742 String s = in.readLine();
744 ss.append(s).append('\n');
747 } catch (IOException e) {
748 System.out.println("Error reading " + fileName + ": " + e.getMessage());
749 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
753 } catch (Exception e) {
754 log.warn("Could not close BufferedReader", e);
758 } catch (Exception e) {
759 log.warn("Could not close InputStreamReader", e);
763 } catch (Exception e) {
764 log.warn("Could not close InputStream", e);
767 return ss.toString();
770 private String buildXmlRequest(Map<String, String> param, String template) {
771 StringBuilder ss = new StringBuilder();
773 while (i < template.length()) {
774 int i1 = template.indexOf("${", i);
776 ss.append(template.substring(i));
780 int i2 = template.indexOf('}', i1 + 2);
782 throw new RuntimeException("Template error: Matching } not found");
785 String var1 = template.substring(i1 + 2, i2);
786 String value1 = param.get(var1);
787 if (value1 == null || value1.trim().length() == 0) {
788 // delete the whole element (line)
789 int i3 = template.lastIndexOf('\n', i1);
793 int i4 = template.indexOf('\n', i1);
795 i4 = template.length();
799 ss.append(template.substring(i, i3));
803 ss.append(template.substring(i, i1)).append(value1);
808 return ss.toString();
811 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
812 log.info("Building XML started");
813 long t1 = System.currentTimeMillis();
815 template = expandRepeats(ctx, template, 1);
817 Map<String, String> mm = new HashMap<>();
818 for (String s : ctx.getAttributeKeySet()) {
819 mm.put(s, ctx.getAttribute(s));
821 mm.put("operation", operation);
823 StringBuilder ss = new StringBuilder();
825 while (i < template.length()) {
826 int i1 = template.indexOf("${", i);
828 ss.append(template.substring(i));
832 int i2 = template.indexOf('}', i1 + 2);
834 throw new RuntimeException("Template error: Matching } not found");
837 String var1 = template.substring(i1 + 2, i2);
838 String value1 = XmlUtil.getXml(mm, var1);
839 if (value1 == null || value1.trim().length() == 0) {
840 // delete the whole element (line)
841 int i3 = template.lastIndexOf('\n', i1);
845 int i4 = template.indexOf('\n', i1);
847 i4 = template.length();
851 ss.append(template.substring(i, i3));
855 ss.append(template.substring(i, i1)).append(value1);
860 long t2 = System.currentTimeMillis();
861 log.info("Building XML completed. Time: " + (t2 - t1));
863 return ss.toString();
866 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
867 StringBuilder newTemplate = new StringBuilder();
869 while (k < template.length()) {
870 int i1 = template.indexOf("${repeat:", k);
872 newTemplate.append(template.substring(k));
876 int i2 = template.indexOf(':', i1 + 9);
878 throw new RuntimeException(
879 "Template error: Context variable name followed by : is required after repeat");
882 // Find the closing }, store in i3
886 while (nn > 0 && i < template.length()) {
887 i3 = template.indexOf('}', i);
889 throw new RuntimeException("Template error: Matching } not found");
891 int i32 = template.indexOf('{', i);
892 if (i32 >= 0 && i32 < i3) {
901 String var1 = template.substring(i1 + 9, i2);
902 String value1 = ctx.getAttribute(var1);
903 log.info(" " + var1 + ": " + value1);
906 n = Integer.parseInt(value1);
907 } catch (Exception e) {
911 newTemplate.append(template.substring(k, i1));
913 String rpt = template.substring(i2 + 1, i3);
915 for (int ii = 0; ii < n; ii++) {
916 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
917 newTemplate.append(ss);
924 return newTemplate.toString();
927 return expandRepeats(ctx, newTemplate.toString(), level + 1);
930 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
932 Client client = getClient();
933 WebTarget webResource = client.target(url);
935 log.info("SENDING...............");
936 if (log.isTraceEnabled()) {
937 log.trace(xmlRequest);
940 if(xmlRequest.length() > 255 ) {
941 log.info(xmlRequest.substring(0, 255));
942 log.info("\n...\n" + xmlRequest.length() +
943 " characters in request, turn on TRACE logging to log entire request");
946 log.info(xmlRequest);
949 String authString = user + ":" + password;
950 String authStringEnc = Base64.encode(authString.getBytes());
951 authString = "Basic " + authStringEnc;
953 Response response = getClientResponse(webResource, authString, xmlRequest);
955 int code = response.getStatus();
956 String message = response.getStatusInfo().getReasonPhrase();
957 log.info("RESPONSE...............");
958 log.info("HTTP response code: " + code);
959 log.info("HTTP response message: " + message);
962 HttpResponse r = new HttpResponse();
967 } catch (Exception e) {
968 log.error("Error sending the request: ", e);
970 HttpResponse r = new HttpResponse();
971 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
972 r.message = e.getMessage();
977 private static class HttpResponse {
981 public String message;
984 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
985 ctx.setAttribute("error-code", String.valueOf(r.code));
986 ctx.setAttribute("error-message", r.message);
988 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
991 private String getStringBetweenQuotes(String string) {
992 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
993 DebugLog.printAriDebug(fnName, "string=" + string);
994 String retString = null;
995 int start = string.indexOf('\"');
996 int end = string.lastIndexOf('\"');
997 retString = string.substring(start + 1, end);
998 DebugLog.printAriDebug(fnName, "retString=" + retString);
1002 public static String _readFile(String fileName) {
1003 StringBuffer strBuff = new StringBuffer();
1005 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
1006 while ((line = in.readLine()) != null) {
1007 strBuff.append(line + "\n");
1009 } catch (IOException e) {
1010 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
1012 return (strBuff.toString());
1016 * A supporting method to extract the data and configuration element from the NETCONF-XML response
1017 * from the node and create well formatted xml.
1019 * @param requestData The unformatted NETCONF-XML
1020 * @return responseBuilder the extracted data
1021 * @throws APPCException Exception during parsing xml data
1023 private String extractFromNetconfXml(String requestData) throws APPCException {
1024 log.debug("extractFromNetconfXml -- Start");
1025 StringBuilder responseBuilder = new StringBuilder();
1026 StringWriter stringBuffer = new StringWriter();
1028 requestData = requestData.replaceAll("]]>]]>", "");
1029 DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
1030 Document document = documentBuilder.parse(new InputSource(new StringReader(requestData)));
1031 document.getDocumentElement().normalize();
1032 XPath xPath = XPathFactory.newInstance().newXPath();
1033 Node dataNode = (Node) xPath.evaluate("//data", document, XPathConstants.NODE);
1034 Transformer xform = TransformerFactory.newInstance().newTransformer();
1035 xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
1036 xform.setOutputProperty(OutputKeys.INDENT, "yes");
1037 xform.transform(new DOMSource(dataNode), new StreamResult(stringBuffer));
1038 responseBuilder.append(stringBuffer.toString());
1039 if (log.isTraceEnabled()) {
1040 log.trace("ConfigComponentAdaptor:extractFromNetconfXml after Extract: "
1041 + responseBuilder.toString());
1043 } catch (SAXException | IOException | ParserConfigurationException | TransformerException
1044 | XPathExpressionException exception) {
1045 throw new APPCException("Error Occured during parsing Netconf-XML", exception);
1048 log.debug("extractFromNetconfXml -- End");
1049 return responseBuilder.toString();
1052 private String trimResponse(String response) throws APPCException {
1053 response = extractFromNetconfXml(response);
1054 log.debug("runningConfig before trimResponse : " + response);
1055 StringTokenizer line = new StringTokenizer(response, "\n");
1056 StringBuffer sb = new StringBuffer();
1057 String runningConfig = "" ;
1058 boolean captureText = false;
1059 while (line.hasMoreTokens()) {
1060 String token = line.nextToken();
1061 if (token.indexOf("<configuration xmlns=") != -1) {
1063 }else if(token.indexOf("<data") != -1) {
1064 log.debug("token-line:with in Data: "+token);
1069 if(token.indexOf("</data>") != -1) {
1070 log.debug("token-line:with in </data>"+token);
1071 captureText = false;
1074 sb.append(token + "\n");
1076 if (token.indexOf("</configuration>") != -1) {
1077 captureText = false;
1080 runningConfig = sb.toString();
1082 if (log.isTraceEnabled()) {
1083 log.trace("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1086 if (runningConfig.length() > 255) {
1087 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1088 runningConfig.substring(0, 255));
1089 log.info("\n...\n" + runningConfig.length() +
1090 " characters in config, turn on TRACE logging to log entire config");
1093 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1097 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1098 return runningConfig;
1101 public static void main(String args[]) throws Exception {
1102 Properties props = null;
1103 System.out.println("*************************Hello*****************************");
1104 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1105 String getConfigTemplate = _readFile("/home/userID/data/Get_config_template");
1106 String downloadConfigTemplate = _readFile("/home/userID/data/Download_config_template_2");
1107 String key = "GetCliRunningConfig";
1108 Map<String, String> parameters = new HashMap();
1109 parameters.put("Host_ip_address", "000.00.000.00");
1110 parameters.put("User_name", "root");
1111 parameters.put("Password", "!bootstrap");
1112 parameters.put("Port_number", "22");
1113 parameters.put("Get_config_template", getConfigTemplate);
1115 SvcLogicContext ctx = null;
1116 System.out.println("*************************TRACE 1*****************************");
1117 cca.configure(key, parameters, ctx);
1120 protected SshJcraftWrapper getSshJcraftWrapper() {
1121 return new SshJcraftWrapper();
1124 protected Client getClient() {
1125 ClientConfig clientConfig = new ClientConfig();
1126 clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 5000);
1127 return ClientBuilder.newClient(clientConfig);
1130 protected Response getClientResponse(WebTarget webResource, String authString, String xmlRequest) {
1131 return webResource.request("UTF-8").header("Authorization", authString).header("Content-Type", "application/xml").post(
1132 Entity.xml(xmlRequest),Response.class);