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 com.sun.jersey.api.client.Client;
65 import com.sun.jersey.api.client.ClientResponse;
66 import com.sun.jersey.api.client.WebResource;
67 import com.sun.jersey.core.util.Base64;
69 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
71 private static EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
72 DebugLog debugLog = new DebugLog();
73 private String configUrl = null;
74 private String configUser = null;
75 private String configPassword = null;
76 private String auditUrl = null;
77 private String auditUser = null;
78 private String auditPassword = null;
80 public String getConfigUrl() {
84 public String getConfigUser() {
88 public String getConfigPassword() {
89 return configPassword;
92 public String getAuditUrl() {
96 public String getAuditUser() {
100 public String getAuditPassword() {
101 return auditPassword;
104 public String getConfigCallbackUrl() {
105 return configCallbackUrl;
108 public String getAuditCallbackUrl() {
109 return auditCallbackUrl;
112 private String configCallbackUrl = null;
113 private String auditCallbackUrl = null;
114 private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ;
116 public ConfigComponentAdaptor(Properties props) {
118 configUrl = props.getProperty("configComponent.url", "");
119 configUser = props.getProperty("configComponent.user", "");
120 configPassword = props.getProperty("configComponent.passwd", "");
121 auditUrl = props.getProperty("auditComponent.url", "");
122 auditUser = props.getProperty("auditComponent.user", "");
123 auditPassword = props.getProperty("auditComponent.passwd", "");
124 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
125 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
133 configCallbackUrl = "";
134 auditCallbackUrl = "";
139 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
140 String fnName = "ConfigComponentAdaptor.configure";
141 HttpResponse r = new HttpResponse();
143 log.debug("ConfigComponentAdaptor.configure - key = " + key);
144 DebugLog.printRTAriDebug(fnName, "key = " + key);
145 log.debug("Parameters:");
146 DebugLog.printRTAriDebug(fnName, "Parameters:");
147 for (Map.Entry<String, String> entry : parameters.entrySet()) {
148 log.debug(" " + entry.getKey() + " = " + entry.getValue());
149 DebugLog.printRTAriDebug(fnName, " " + entry.getKey() + " = " + entry.getValue());
152 String parmval = parameters.get("config-component-configUrl");
153 if ((parmval != null) && (parmval.length() > 0)) {
154 log.debug("Overwriting URL with " + parmval);
158 parmval = parameters.get("config-component-configPassword");
159 if ((parmval != null) && (parmval.length() > 0)) {
160 log.debug("Overwriting configPassword with " + parmval);
161 configPassword = parmval;
164 parmval = parameters.get("config-component-configUser");
165 if ((parmval != null) && (parmval.length() > 0)) {
166 log.debug("Overwriting configUser id with " + parmval);
167 configUser = parmval;
170 String action = parameters.get("action");
172 String chg = ctx.getAttribute(
173 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
174 if (chg != null && "prepare".equalsIgnoreCase(action)) {
175 return prepare(ctx, "CHANGE", "change");
177 if (chg != null && "activate".equalsIgnoreCase(action)) {
178 return activate(ctx, true);
181 String scale = ctx.getAttribute(
182 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
183 if (scale != null && "prepare".equalsIgnoreCase(action)) {
184 return prepare(ctx, "CHANGE", "scale");
186 if (scale != null && "activate".equalsIgnoreCase(action)) {
187 return activate(ctx, true);
190 if ("prepare".equalsIgnoreCase(action)) {
191 return prepare(ctx, "BASE", "create");
193 if ("activate".equalsIgnoreCase(action)) {
194 return activate(ctx, false);
197 if ("backup".equalsIgnoreCase(action)) {
198 return prepare(ctx, "BACKUP", "backup");
200 if ("restorebackup".equalsIgnoreCase(action)) {
201 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
203 if ("deletebackup".equalsIgnoreCase(action)) {
204 return prepare(ctx, "DELETEBACKUP", "deletebackup");
206 if ("audit".equalsIgnoreCase(action)) {
207 return audit(ctx, "FULL");
209 if ("getrunningconfig".equalsIgnoreCase(action)) {
210 return audit(ctx, "RUNNING");
213 if (("put".equals(key)) || ("get".equals(key))) {
214 String loginId = parameters.get("loginId");
215 String host = parameters.get("host");
216 String password = parameters.get("password");
217 password = EncryptionTool.getInstance().decrypt(password);
218 String fullPathFileName = parameters.get("fullPathFileName");
221 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
222 log.debug("SCP: SshJcraftWrapper has been instantiated");
223 DebugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
225 if (key.equals("put")) {
226 data = parameters.get("data");
228 DebugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
229 InputStream is = new ByteArrayInputStream(data.getBytes());
230 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
231 DebugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
232 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
234 DebugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
235 Thread.sleep(1000l * 180);
236 DebugLog.printRTAriDebug(fnName, "Woke up....");
237 } catch (java.lang.InterruptedException ee) {
238 boolean ignore = true;
239 Thread.currentThread().interrupt();
242 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
243 log.debug(fnName + " Command is for put: data is null");
245 } else // Must be a get
247 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
248 DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
249 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
250 DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
251 ctx.setAttribute("fileContents", response);
252 log.debug("SCP: Closing the SFTP connection");
254 return (setResponseStatus(ctx, r));
255 } catch (IOException e) {
256 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
257 log.debug(fnName + " : Caught a IOException e=" + e);
258 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
259 r.message = e.getMessage();
260 return (setResponseStatus(ctx, r));
263 if (key.equals("cli")) {
264 String loginId = parameters.get("loginId");
265 String host = parameters.get("host");
266 String password = parameters.get("password");
267 password = EncryptionTool.getInstance().decrypt(password);
268 String portNumber = parameters.get("portNumber");
269 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
271 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
272 " portNumber=" + portNumber);
273 DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
274 " portNumber=" + portNumber);
275 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
277 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
278 String response = sshJcraftWrapper.send("sdc", ":");
279 DebugLog.printAriDebug(fnName, "Sending 1");
280 response = sshJcraftWrapper.send("1", ":");
281 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
282 response = sshJcraftWrapper.send("1", "#");
283 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
284 response = sshJcraftWrapper.send("paging-options disable", "#");
285 DebugLog.printAriDebug(fnName, "Sending show config");
286 response = sshJcraftWrapper.send("show config", "#");
288 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
289 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
290 ctx.setAttribute("cliOutput", response);
291 sshJcraftWrapper.closeConnection();
293 sshJcraftWrapper = null;
294 return (setResponseStatus(ctx, r));
295 } catch (IOException e) {
296 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
297 log.debug(fnName + " : Caught a IOException e=" + e);
298 sshJcraftWrapper.closeConnection();
299 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
300 r.message = e.getMessage();
301 sshJcraftWrapper = null;
302 DebugLog.printAriDebug(fnName, "Returning error message");
303 return (setResponseStatus(ctx, r));
306 if (key.equals("escapeSql")) {
307 String data = parameters.get("artifactContents");
308 log.debug("ConfigComponentAdaptor.configure - escapeSql");
309 data = escapeMySql(data);
310 ctx.setAttribute("escapedData", data);
311 return (setResponseStatus(ctx, r));
313 if (key.equals("GetCliRunningConfig")) {
314 DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
315 log.debug("key was: GetCliRunningConfig: ");
316 String User_name = parameters.get("User_name");
317 String Host_ip_address = parameters.get("Host_ip_address");
318 String Password = parameters.get("Password");
319 Password = EncryptionTool.getInstance().decrypt(Password);
320 String Port_number = parameters.get("Port_number");
321 String Get_config_template = parameters.get("Get_config_template");
322 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
323 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
324 DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
326 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
327 " Host_ip_address=" + Host_ip_address + " Port_number="
329 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
330 " User_name=" + User_name + " Port_number=" + Port_number);
331 String response = "";
332 String CliResponse = "";
333 boolean showConfigFlag = false;
334 sshJcraftWrapper.connect(Host_ip_address,
339 Integer.parseInt(Port_number));
340 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
341 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
342 String command = null;
344 while (st.hasMoreTokens()) {
345 String line = st.nextToken();
346 DebugLog.printAriDebug(fnName, "line=" + line);
347 if (line.indexOf("Request:") != -1) {
348 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
349 command = getStringBetweenQuotes(line);
350 DebugLog.printAriDebug(fnName, "Sending command=" + command);
351 sshJcraftWrapper.send(command);
352 DebugLog.printAriDebug(fnName, "command has been sent");
353 if (line.indexOf("show config") != -1) {
354 showConfigFlag = true;
355 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
356 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
359 if (line.indexOf("Response: Ends_With") != -1) {
360 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
361 String delemeter = getStringBetweenQuotes(line);
362 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
363 //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806
364 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter,
365 DEFAULT_TIMEOUT_GETRUNNING_CLI, command);
366 response += tmpResponse;
367 if (showConfigFlag) {
368 showConfigFlag = false;
369 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
370 // Strip off the last line which is the command prompt from the VNF device.
371 while (st2.hasMoreTokens()) {
372 String line2 = st2.nextToken();
373 if (line2.indexOf('#') == -1) {
374 CliResponse += line2 + "\n";
380 } catch (NoSuchElementException e) {
381 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
383 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
384 ctx.setAttribute("cliOutput", CliResponse);
385 sshJcraftWrapper.closeConnection();
387 sshJcraftWrapper = null;
388 return (setResponseStatus(ctx, r));
389 } catch (IOException e) {
390 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
391 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
392 sshJcraftWrapper.closeConnection();
393 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
394 r.message = e.getMessage();
395 sshJcraftWrapper = null;
396 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
397 return (setResponseStatus(ctx, r));
400 if (key.equals("xml-download")) {
401 log(fnName, "key was: xml-download");
402 String User_name = parameters.get("User_name");
403 String Host_ip_address = parameters.get("Host_ip_address");
404 String Password = parameters.get("Password");
405 Password = EncryptionTool.getInstance().decrypt(Password);
406 String Port_number = parameters.get("Port_number");
407 String Contents = parameters.get("Contents");
408 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>";
409 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 ]]>]]>";
410 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 ]]>]]>";
413 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
414 + " Port_number=" + Port_number);
415 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
417 sshJcraftWrapper.connect(Host_ip_address,
422 Integer.parseInt(Port_number),
424 String NetconfHelloCmd = netconfHelloCmd;
425 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
426 log(fnName, "Sending the hello command");
427 sshJcraftWrapper.send(NetconfHelloCmd);
428 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
429 log(fnName, "Sending xmlCmd cmd");
430 String xmlCmd = Contents;
431 String messageId = "1";
432 messageId = "\"" + messageId + "\"";
433 String loadConfigurationString =
434 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
436 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
437 + xmlCmd + "</config> </edit-config> </rpc>";
438 loadConfigurationString = loadConfigurationString + "]]>]]>";
439 sshJcraftWrapper.send(loadConfigurationString);
440 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
441 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
442 if (response.indexOf("rpc-error") != -1) {
443 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
444 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
445 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
446 r.message = response;
448 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
449 sshJcraftWrapper.send(commitCmd);
450 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
451 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
452 if (response.indexOf("rpc-error") != -1) {
453 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
454 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
455 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
456 r.message = response;
458 DebugLog.printAriDebug(fnName, ":Looks like a success");
459 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
463 sshJcraftWrapper.send(terminateConnectionCmd);
464 sshJcraftWrapper.closeConnection();
465 sshJcraftWrapper = null;
466 return (setResponseStatus(ctx, r));
467 } catch (Exception e) {
468 log(fnName, "Caught an Exception, e=" + e);
469 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
470 sshJcraftWrapper.closeConnection();
471 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
472 r.message = e.getMessage();
473 sshJcraftWrapper = null;
474 log(fnName, "Returning error message");
475 return (setResponseStatus(ctx, r));
478 if (key.equals("xml-getrunningconfig")) {
479 log(fnName, "key was: : xml-getrunningconfig");
480 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";
481 String Host_ip_address = parameters.get("Host_ip_address");
482 String User_name = parameters.get("User_name");
483 String Password = parameters.get("Password");
484 Password = EncryptionTool.getInstance().decrypt(Password);
485 String Port_number = parameters.get("Port_number");
486 String Protocol = parameters.get("Protocol");
487 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>";
488 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 ]]>]]>";
490 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
491 + " Port_number=" + Port_number);
492 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
494 String NetconfHelloCmd = netconfHelloCmd;
495 sshJcraftWrapper.connect(Host_ip_address,
500 Integer.parseInt(Port_number),
502 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
503 log(fnName, ":Sending the hello command");
504 sshJcraftWrapper.send(NetconfHelloCmd);
505 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
506 log(fnName, "Sending get running config command");
507 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
508 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
509 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
510 response = trimResponse(response);
511 ctx.setAttribute("xmlRunningConfigOutput", response);
512 sshJcraftWrapper.send(terminateConnectionCmd);
513 sshJcraftWrapper.closeConnection();
515 sshJcraftWrapper = null;
516 return (setResponseStatus(ctx, r));
517 } catch (Exception e) {
518 log(fnName, "Caught an Exception, e=" + e);
519 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
520 sshJcraftWrapper.closeConnection();
521 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
522 r.message = e.getMessage();
523 sshJcraftWrapper = null;
524 log(fnName, "Returning error message");
525 return (setResponseStatus(ctx, r));
528 if (key.equals("DownloadCliConfig")) {
529 DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
530 log.debug("key was: DownloadCliConfig: ");
531 String User_name = parameters.get("User_name");
532 String Host_ip_address = parameters.get("Host_ip_address");
533 String Password = parameters.get("Password");
534 Password = EncryptionTool.getInstance().decrypt(Password);
535 String Port_number = parameters.get("Port_number");
536 String Download_config_template = parameters.get("Download_config_template");
537 String Config_contents = parameters.get("Config_contents");
538 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
539 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
540 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
541 DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
542 int timeout = 4 * 60 * 1000;
544 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
545 " Host_ip_address=" + Host_ip_address + " Port_number="
547 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
548 " User_name=" + User_name + " Port_number=" + Port_number);
549 String CliResponse = "";
550 sshJcraftWrapper.connect(Host_ip_address,
555 Integer.parseInt(Port_number));
556 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
557 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
558 String command = null;
559 String executeConfigContentsDelemeter = null;
561 while (st.hasMoreTokens()) {
562 String line = st.nextToken();
563 DebugLog.printAriDebug(fnName, "line=" + line);
564 if (line.indexOf("Request:") != -1) {
565 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
566 command = getStringBetweenQuotes(line);
567 DebugLog.printAriDebug(fnName, "Sending command=" + command);
568 sshJcraftWrapper.send(command);
569 DebugLog.printAriDebug(fnName, "command has been sent");
570 } else if ((line.indexOf("Response: Ends_With") != -1) && (
571 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
572 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
573 String delemeter = getStringBetweenQuotes(line);
574 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
575 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
576 CliResponse += tmpResponse;
577 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
578 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
579 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
580 DebugLog.printAriDebug(fnName,
581 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
582 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
583 while (st2.hasMoreTokens()) {
584 String cmd = st2.nextToken();
585 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
586 sshJcraftWrapper.send(cmd);
587 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
590 CliResponse += tmpResponse;
594 } catch (NoSuchElementException e) {
595 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
597 sshJcraftWrapper.closeConnection();
598 sshJcraftWrapper = null;
599 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
600 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
601 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
602 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
603 ctx.setAttribute("cliOutput", CliResponse);
605 return (setResponseStatus(ctx, r));
606 } catch (IOException e) {
607 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
608 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
609 sshJcraftWrapper.closeConnection();
610 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
611 r.message = e.getMessage();
612 sshJcraftWrapper = null;
613 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
614 return (setResponseStatus(ctx, r));
618 DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
619 log.error("Unsupported action - " + action);
620 return ConfigStatus.FAILURE;
623 private void log(String fileName, String messg) {
624 DebugLog.printRTAriDebug(fileName, messg);
625 log.debug(fileName + ": " + messg);
628 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
629 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
630 String ndTemplate = readFile(templateName);
631 String nd = buildNetworkData2(ctx, ndTemplate, operation);
633 String reqTemplate = readFile("/config-request.xml");
634 Map<String, String> param = new HashMap<String, String>();
635 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
636 param.put("request-type", requestType);
637 param.put("callback-url", configCallbackUrl);
638 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
639 param.put("action", "GenerateOnly");
641 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
642 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
643 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
644 param.put("network-data", nd);
648 req = buildXmlRequest(param, reqTemplate);
649 } catch (Exception e) {
650 log.error("Error building the XML request: ", e);
652 HttpResponse r = new HttpResponse();
653 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
654 r.message = e.getMessage();
655 return setResponseStatus(ctx, r);
658 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
659 return setResponseStatus(ctx, r);
662 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
663 String reqTemplate = readFile("/config-request.xml");
664 Map<String, String> param = new HashMap<String, String>();
665 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
666 param.put("callback-url", configCallbackUrl);
667 param.put("action", change ? "DownloadChange" : "DownloadBase");
668 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
672 req = buildXmlRequest(param, reqTemplate);
673 } catch (Exception e) {
674 log.error("Error building the XML request: ", e);
676 HttpResponse r = new HttpResponse();
677 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
678 r.message = e.getMessage();
679 return setResponseStatus(ctx, r);
682 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
683 return setResponseStatus(ctx, r);
686 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
687 String reqTemplate = readFile("/audit-request.xml");
688 Map<String, String> param = new HashMap<String, String>();
689 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
690 param.put("callback-url", auditCallbackUrl);
691 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
692 param.put("audit-level", auditLevel);
696 req = buildXmlRequest(param, reqTemplate);
697 } catch (Exception e) {
698 log.error("Error building the XML request: ", e);
700 HttpResponse r = new HttpResponse();
701 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
702 r.message = e.getMessage();
703 return setResponseStatus(ctx, r);
706 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
707 return setResponseStatus(ctx, r);
711 public ConfigStatus activate(String key, SvcLogicContext ctx) {
712 return ConfigStatus.SUCCESS;
716 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
717 return ConfigStatus.SUCCESS;
720 private String escapeMySql(String input) {
725 input = input.replace("\\", "\\\\");
726 input = input.replace("\'", "\\'");
731 protected String readFile(String fileName) {
732 InputStream is = getClass().getResourceAsStream(fileName);
733 InputStreamReader isr = new InputStreamReader(is);
734 BufferedReader in = new BufferedReader(isr);
735 StringBuilder ss = new StringBuilder();
737 String s = in.readLine();
739 ss.append(s).append('\n');
742 } catch (IOException e) {
743 System.out.println("Error reading " + fileName + ": " + e.getMessage());
744 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
748 } catch (Exception e) {
749 log.warn("Could not close BufferedReader", e);
753 } catch (Exception e) {
754 log.warn("Could not close InputStreamReader", e);
758 } catch (Exception e) {
759 log.warn("Could not close InputStream", e);
762 return ss.toString();
765 private String buildXmlRequest(Map<String, String> param, String template) {
766 StringBuilder ss = new StringBuilder();
768 while (i < template.length()) {
769 int i1 = template.indexOf("${", i);
771 ss.append(template.substring(i));
775 int i2 = template.indexOf('}', i1 + 2);
777 throw new RuntimeException("Template error: Matching } not found");
780 String var1 = template.substring(i1 + 2, i2);
781 String value1 = param.get(var1);
782 if (value1 == null || value1.trim().length() == 0) {
783 // delete the whole element (line)
784 int i3 = template.lastIndexOf('\n', i1);
788 int i4 = template.indexOf('\n', i1);
790 i4 = template.length();
794 ss.append(template.substring(i, i3));
798 ss.append(template.substring(i, i1)).append(value1);
803 return ss.toString();
806 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
807 log.info("Building XML started");
808 long t1 = System.currentTimeMillis();
810 template = expandRepeats(ctx, template, 1);
812 Map<String, String> mm = new HashMap<>();
813 for (String s : ctx.getAttributeKeySet()) {
814 mm.put(s, ctx.getAttribute(s));
816 mm.put("operation", operation);
818 StringBuilder ss = new StringBuilder();
820 while (i < template.length()) {
821 int i1 = template.indexOf("${", i);
823 ss.append(template.substring(i));
827 int i2 = template.indexOf('}', i1 + 2);
829 throw new RuntimeException("Template error: Matching } not found");
832 String var1 = template.substring(i1 + 2, i2);
833 String value1 = XmlUtil.getXml(mm, var1);
834 if (value1 == null || value1.trim().length() == 0) {
835 // delete the whole element (line)
836 int i3 = template.lastIndexOf('\n', i1);
840 int i4 = template.indexOf('\n', i1);
842 i4 = template.length();
846 ss.append(template.substring(i, i3));
850 ss.append(template.substring(i, i1)).append(value1);
855 long t2 = System.currentTimeMillis();
856 log.info("Building XML completed. Time: " + (t2 - t1));
858 return ss.toString();
861 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
862 StringBuilder newTemplate = new StringBuilder();
864 while (k < template.length()) {
865 int i1 = template.indexOf("${repeat:", k);
867 newTemplate.append(template.substring(k));
871 int i2 = template.indexOf(':', i1 + 9);
873 throw new RuntimeException(
874 "Template error: Context variable name followed by : is required after repeat");
877 // Find the closing }, store in i3
881 while (nn > 0 && i < template.length()) {
882 i3 = template.indexOf('}', i);
884 throw new RuntimeException("Template error: Matching } not found");
886 int i32 = template.indexOf('{', i);
887 if (i32 >= 0 && i32 < i3) {
896 String var1 = template.substring(i1 + 9, i2);
897 String value1 = ctx.getAttribute(var1);
898 log.info(" " + var1 + ": " + value1);
901 n = Integer.parseInt(value1);
902 } catch (Exception e) {
906 newTemplate.append(template.substring(k, i1));
908 String rpt = template.substring(i2 + 1, i3);
910 for (int ii = 0; ii < n; ii++) {
911 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
912 newTemplate.append(ss);
919 return newTemplate.toString();
922 return expandRepeats(ctx, newTemplate.toString(), level + 1);
925 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
927 Client client = getClient();
928 client.setConnectTimeout(5000);
929 WebResource webResource = client.resource(url);
931 log.info("SENDING...............");
932 if (log.isTraceEnabled()) {
933 log.trace(xmlRequest);
936 if(xmlRequest.length() > 255 ) {
937 log.info(xmlRequest.substring(0, 255));
938 log.info("\n...\n" + xmlRequest.length() +
939 " characters in request, turn on TRACE logging to log entire request");
942 log.info(xmlRequest);
945 String authString = user + ":" + password;
946 byte[] authEncBytes = Base64.encode(authString);
947 String authStringEnc = new String(authEncBytes);
948 authString = "Basic " + authStringEnc;
950 ClientResponse response = getClientResponse(webResource, authString, xmlRequest);
952 int code = response.getStatus();
953 String message = null;
955 log.info("RESPONSE...............");
956 log.info("HTTP response code: " + code);
957 log.info("HTTP response message: " + message);
960 HttpResponse r = new HttpResponse();
965 } catch (Exception e) {
966 log.error("Error sending the request: ", e);
968 HttpResponse r = new HttpResponse();
969 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
970 r.message = e.getMessage();
975 private static class HttpResponse {
979 public String message;
982 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
983 ctx.setAttribute("error-code", String.valueOf(r.code));
984 ctx.setAttribute("error-message", r.message);
986 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
989 private String getStringBetweenQuotes(String string) {
990 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
991 DebugLog.printAriDebug(fnName, "string=" + string);
992 String retString = null;
993 int start = string.indexOf('\"');
994 int end = string.lastIndexOf('\"');
995 retString = string.substring(start + 1, end);
996 DebugLog.printAriDebug(fnName, "retString=" + retString);
1000 public static String _readFile(String fileName) {
1001 StringBuffer strBuff = new StringBuffer();
1003 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
1004 while ((line = in.readLine()) != null) {
1005 strBuff.append(line + "\n");
1007 } catch (IOException e) {
1008 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
1010 return (strBuff.toString());
1014 * A supporting method to extract the data and configuration element from the NETCONF-XML response
1015 * from the node and create well formatted xml.
1017 * @param requestData The unformatted NETCONF-XML
1018 * @return responseBuilder the extracted data
1019 * @throws APPCException Exception during parsing xml data
1021 private String extractFromNetconfXml(String requestData) throws APPCException {
1022 log.debug("extractFromNetconfXml -- Start");
1023 StringBuilder responseBuilder = new StringBuilder();
1024 StringWriter stringBuffer = new StringWriter();
1026 requestData = requestData.replaceAll("]]>]]>", "");
1027 DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
1028 Document document = documentBuilder.parse(new InputSource(new StringReader(requestData)));
1029 document.getDocumentElement().normalize();
1030 XPath xPath = XPathFactory.newInstance().newXPath();
1031 Node dataNode = (Node) xPath.evaluate("//data", document, XPathConstants.NODE);
1032 Transformer xform = TransformerFactory.newInstance().newTransformer();
1033 xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
1034 xform.setOutputProperty(OutputKeys.INDENT, "yes");
1035 xform.transform(new DOMSource(dataNode), new StreamResult(stringBuffer));
1036 responseBuilder.append(stringBuffer.toString());
1037 if (log.isTraceEnabled()) {
1038 log.trace("ConfigComponentAdaptor:extractFromNetconfXml after Extract: "
1039 + responseBuilder.toString());
1041 } catch (SAXException | IOException | ParserConfigurationException | TransformerException
1042 | XPathExpressionException exception) {
1043 throw new APPCException("Error Occured during parsing Netconf-XML", exception);
1046 log.debug("extractFromNetconfXml -- End");
1047 return responseBuilder.toString();
1050 private String trimResponse(String response) throws APPCException {
1051 response = extractFromNetconfXml(response);
1052 log.debug("runningConfig before trimResponse : " + response);
1053 StringTokenizer line = new StringTokenizer(response, "\n");
1054 StringBuffer sb = new StringBuffer();
1055 String runningConfig = "" ;
1056 boolean captureText = false;
1057 while (line.hasMoreTokens()) {
1058 String token = line.nextToken();
1059 if (token.indexOf("<configuration xmlns=") != -1) {
1061 }else if(token.indexOf("<data") != -1) {
1062 log.debug("token-line:with in Data: "+token);
1067 if(token.indexOf("</data>") != -1) {
1068 log.debug("token-line:with in </data>"+token);
1069 captureText = false;
1072 sb.append(token + "\n");
1074 if (token.indexOf("</configuration>") != -1) {
1075 captureText = false;
1078 runningConfig = sb.toString();
1080 if (log.isTraceEnabled()) {
1081 log.trace("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1084 if (runningConfig.length() > 255) {
1085 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1086 runningConfig.substring(0, 255));
1087 log.info("\n...\n" + runningConfig.length() +
1088 " characters in config, turn on TRACE logging to log entire config");
1091 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1095 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1096 return runningConfig;
1099 public static void main(String args[]) throws Exception {
1100 Properties props = null;
1101 System.out.println("*************************Hello*****************************");
1102 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1103 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
1104 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
1105 String key = "GetCliRunningConfig";
1106 Map<String, String> parameters = new HashMap();
1107 parameters.put("Host_ip_address", "000.00.000.00");
1108 parameters.put("User_name", "root");
1109 parameters.put("Password", "!bootstrap");
1110 parameters.put("Port_number", "22");
1111 parameters.put("Get_config_template", Get_config_template);
1113 SvcLogicContext ctx = null;
1114 System.out.println("*************************TRACE 1*****************************");
1115 cca.configure(key, parameters, ctx);
1118 protected SshJcraftWrapper getSshJcraftWrapper() {
1119 return new SshJcraftWrapper();
1122 protected Client getClient() {
1123 return Client.create();
1126 protected ClientResponse getClientResponse(WebResource webResource, String authString, String xmlRequest) {
1127 return webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
1128 ClientResponse.class, xmlRequest);