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;
73 import javax.ws.rs.core.Feature;
75 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
77 private static EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
78 DebugLog debugLog = new DebugLog();
79 private String configUrl = null;
80 private String configUser = null;
81 private String configPassword = null;
82 private String auditUrl = null;
83 private String auditUser = null;
84 private String auditPassword = null;
86 public String getConfigUrl() {
90 public String getConfigUser() {
94 public String getConfigPassword() {
95 return configPassword;
98 public String getAuditUrl() {
102 public String getAuditUser() {
106 public String getAuditPassword() {
107 return auditPassword;
110 public String getConfigCallbackUrl() {
111 return configCallbackUrl;
114 public String getAuditCallbackUrl() {
115 return auditCallbackUrl;
118 private String configCallbackUrl = null;
119 private String auditCallbackUrl = null;
120 private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ;
122 public ConfigComponentAdaptor(Properties props) {
124 configUrl = props.getProperty("configComponent.url", "");
125 configUser = props.getProperty("configComponent.user", "");
126 configPassword = props.getProperty("configComponent.passwd", "");
127 auditUrl = props.getProperty("auditComponent.url", "");
128 auditUser = props.getProperty("auditComponent.user", "");
129 auditPassword = props.getProperty("auditComponent.passwd", "");
130 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
131 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
139 configCallbackUrl = "";
140 auditCallbackUrl = "";
145 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
146 String fnName = "ConfigComponentAdaptor.configure";
147 HttpResponse r = new HttpResponse();
149 log.debug("ConfigComponentAdaptor.configure - key = " + key);
150 DebugLog.printRTAriDebug(fnName, "key = " + key);
151 log.debug("Parameters:");
152 DebugLog.printRTAriDebug(fnName, "Parameters:");
153 for (Map.Entry<String, String> entry : parameters.entrySet()) {
154 log.debug(" " + entry.getKey() + " = " + entry.getValue());
155 DebugLog.printRTAriDebug(fnName, " " + entry.getKey() + " = " + entry.getValue());
158 String parmval = parameters.get("config-component-configUrl");
159 if ((parmval != null) && (parmval.length() > 0)) {
160 log.debug("Overwriting URL with " + parmval);
164 parmval = parameters.get("config-component-configPassword");
165 if ((parmval != null) && (parmval.length() > 0)) {
166 //log.debug("Overwriting configPassword with " + parmval);
167 configPassword = parmval;
170 parmval = parameters.get("config-component-configUser");
171 if ((parmval != null) && (parmval.length() > 0)) {
172 log.debug("Overwriting configUser id with " + parmval);
173 configUser = parmval;
176 String action = parameters.get("action");
178 String chg = ctx.getAttribute(
179 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
180 if (chg != null && "prepare".equalsIgnoreCase(action)) {
181 return prepare(ctx, "CHANGE", "change");
183 if (chg != null && "activate".equalsIgnoreCase(action)) {
184 return activate(ctx, true);
187 String scale = ctx.getAttribute(
188 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
189 if (scale != null && "prepare".equalsIgnoreCase(action)) {
190 return prepare(ctx, "CHANGE", "scale");
192 if (scale != null && "activate".equalsIgnoreCase(action)) {
193 return activate(ctx, true);
196 if ("prepare".equalsIgnoreCase(action)) {
197 return prepare(ctx, "BASE", "create");
199 if ("activate".equalsIgnoreCase(action)) {
200 return activate(ctx, false);
203 if ("backup".equalsIgnoreCase(action)) {
204 return prepare(ctx, "BACKUP", "backup");
206 if ("restorebackup".equalsIgnoreCase(action)) {
207 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
209 if ("deletebackup".equalsIgnoreCase(action)) {
210 return prepare(ctx, "DELETEBACKUP", "deletebackup");
212 if ("audit".equalsIgnoreCase(action)) {
213 return audit(ctx, "FULL");
215 if ("getrunningconfig".equalsIgnoreCase(action)) {
216 return audit(ctx, "RUNNING");
219 if (("put".equals(key)) || ("get".equals(key))) {
220 String loginId = parameters.get("loginId");
221 String host = parameters.get("host");
222 String password = parameters.get("password");
223 password = EncryptionTool.getInstance().decrypt(password);
224 String fullPathFileName = parameters.get("fullPathFileName");
227 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
228 log.debug("SCP: SshJcraftWrapper has been instantiated");
229 DebugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
231 if (key.equals("put")) {
232 data = parameters.get("data");
234 DebugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
235 InputStream is = new ByteArrayInputStream(data.getBytes());
236 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
237 DebugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
238 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
240 DebugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
241 Thread.sleep(1000l * 180);
242 DebugLog.printRTAriDebug(fnName, "Woke up....");
243 } catch (java.lang.InterruptedException ee) {
244 boolean ignore = true;
245 Thread.currentThread().interrupt();
248 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
249 log.debug(fnName + " Command is for put: data is null");
251 } else // Must be a get
253 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
254 DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
255 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
256 DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
257 ctx.setAttribute("fileContents", response);
258 log.debug("SCP: Closing the SFTP connection");
260 return (setResponseStatus(ctx, r));
261 } catch (IOException e) {
262 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
263 log.debug(fnName + " : Caught a IOException e=" + e);
264 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
265 r.message = e.getMessage();
266 return (setResponseStatus(ctx, r));
269 if (key.equals("cli")) {
270 String loginId = parameters.get("loginId");
271 String host = parameters.get("host");
272 String password = parameters.get("password");
273 password = EncryptionTool.getInstance().decrypt(password);
274 String portNumber = parameters.get("portNumber");
275 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
277 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
278 " portNumber=" + portNumber);
279 DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
280 " portNumber=" + portNumber);
281 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
283 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
284 String response = sshJcraftWrapper.send("sdc", ":");
285 DebugLog.printAriDebug(fnName, "Sending 1");
286 response = sshJcraftWrapper.send("1", ":");
287 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
288 response = sshJcraftWrapper.send("1", "#");
289 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
290 response = sshJcraftWrapper.send("paging-options disable", "#");
291 DebugLog.printAriDebug(fnName, "Sending show config");
292 response = sshJcraftWrapper.send("show config", "#");
294 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
295 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
296 ctx.setAttribute("cliOutput", response);
297 sshJcraftWrapper.closeConnection();
299 sshJcraftWrapper = null;
300 return (setResponseStatus(ctx, r));
301 } catch (IOException e) {
302 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
303 log.debug(fnName + " : Caught a IOException e=" + e);
304 sshJcraftWrapper.closeConnection();
305 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
306 r.message = e.getMessage();
307 sshJcraftWrapper = null;
308 DebugLog.printAriDebug(fnName, "Returning error message");
309 return (setResponseStatus(ctx, r));
312 if (key.equals("escapeSql")) {
313 String data = parameters.get("artifactContents");
314 log.debug("ConfigComponentAdaptor.configure - escapeSql");
315 data = escapeMySql(data);
316 ctx.setAttribute("escapedData", data);
317 return (setResponseStatus(ctx, r));
319 if (key.equals("GetCliRunningConfig")) {
320 DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
321 log.debug("key was: GetCliRunningConfig: ");
322 String User_name = parameters.get("User_name");
323 String Host_ip_address = parameters.get("Host_ip_address");
324 String Password = parameters.get("Password");
325 Password = EncryptionTool.getInstance().decrypt(Password);
326 String Port_number = parameters.get("Port_number");
327 String Get_config_template = parameters.get("Get_config_template");
328 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
329 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
330 DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
332 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
333 " Host_ip_address=" + Host_ip_address + " Port_number="
335 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
336 " User_name=" + User_name + " Port_number=" + Port_number);
337 String response = "";
338 String CliResponse = "";
339 boolean showConfigFlag = false;
340 sshJcraftWrapper.connect(Host_ip_address,
345 Integer.parseInt(Port_number));
346 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
347 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
348 String command = null;
350 while (st.hasMoreTokens()) {
351 String line = st.nextToken();
352 DebugLog.printAriDebug(fnName, "line=" + line);
353 if (line.indexOf("Request:") != -1) {
354 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
355 command = getStringBetweenQuotes(line);
356 DebugLog.printAriDebug(fnName, "Sending command=" + command);
357 sshJcraftWrapper.send(command);
358 DebugLog.printAriDebug(fnName, "command has been sent");
359 if (line.indexOf("show config") != -1) {
360 showConfigFlag = true;
361 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
362 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
365 if (line.indexOf("Response: Ends_With") != -1) {
366 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
367 String delemeter = getStringBetweenQuotes(line);
368 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
369 //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806
370 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter,
371 DEFAULT_TIMEOUT_GETRUNNING_CLI, command);
372 response += tmpResponse;
373 if (showConfigFlag) {
374 showConfigFlag = false;
375 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
376 // Strip off the last line which is the command prompt from the VNF device.
377 while (st2.hasMoreTokens()) {
378 String line2 = st2.nextToken();
379 if (line2.indexOf('#') == -1) {
380 CliResponse += line2 + "\n";
386 } catch (NoSuchElementException e) {
387 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
389 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
390 ctx.setAttribute("cliOutput", CliResponse);
391 sshJcraftWrapper.closeConnection();
393 sshJcraftWrapper = null;
394 return (setResponseStatus(ctx, r));
395 } catch (IOException e) {
396 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
397 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
398 sshJcraftWrapper.closeConnection();
399 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
400 r.message = e.getMessage();
401 sshJcraftWrapper = null;
402 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
403 return (setResponseStatus(ctx, r));
406 if (key.equals("xml-download")) {
407 log(fnName, "key was: xml-download");
408 String User_name = parameters.get("User_name");
409 String Host_ip_address = parameters.get("Host_ip_address");
410 String Password = parameters.get("Password");
411 Password = EncryptionTool.getInstance().decrypt(Password);
412 String Port_number = parameters.get("Port_number");
413 String Contents = parameters.get("Contents");
414 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>";
415 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 ]]>]]>";
416 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 ]]>]]>";
419 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
420 + " Port_number=" + Port_number);
421 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
423 sshJcraftWrapper.connect(Host_ip_address,
428 Integer.parseInt(Port_number),
430 String NetconfHelloCmd = netconfHelloCmd;
431 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
432 log(fnName, "Sending the hello command");
433 sshJcraftWrapper.send(NetconfHelloCmd);
434 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
435 log(fnName, "Sending xmlCmd cmd");
436 String xmlCmd = Contents;
437 String messageId = "1";
438 messageId = "\"" + messageId + "\"";
439 String loadConfigurationString =
440 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
442 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
443 + xmlCmd + "</config> </edit-config> </rpc>";
444 loadConfigurationString = loadConfigurationString + "]]>]]>";
445 sshJcraftWrapper.send(loadConfigurationString);
446 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
447 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
448 if (response.indexOf("rpc-error") != -1) {
449 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
450 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
451 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
452 r.message = response;
454 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
455 sshJcraftWrapper.send(commitCmd);
456 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
457 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
458 if (response.indexOf("rpc-error") != -1) {
459 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
460 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
461 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
462 r.message = response;
464 DebugLog.printAriDebug(fnName, ":Looks like a success");
465 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
469 sshJcraftWrapper.send(terminateConnectionCmd);
470 sshJcraftWrapper.closeConnection();
471 sshJcraftWrapper = null;
472 return (setResponseStatus(ctx, r));
473 } catch (Exception e) {
474 log(fnName, "Caught an Exception, e=" + e);
475 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
476 sshJcraftWrapper.closeConnection();
477 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
478 r.message = e.getMessage();
479 sshJcraftWrapper = null;
480 log(fnName, "Returning error message");
481 return (setResponseStatus(ctx, r));
484 if (key.equals("xml-getrunningconfig")) {
485 log(fnName, "key was: : xml-getrunningconfig");
486 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";
487 String Host_ip_address = parameters.get("Host_ip_address");
488 String User_name = parameters.get("User_name");
489 String Password = parameters.get("Password");
490 Password = EncryptionTool.getInstance().decrypt(Password);
491 String Port_number = parameters.get("Port_number");
492 String Protocol = parameters.get("Protocol");
493 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>";
494 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 ]]>]]>";
496 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
497 + " Port_number=" + Port_number);
498 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
500 String NetconfHelloCmd = netconfHelloCmd;
501 sshJcraftWrapper.connect(Host_ip_address,
506 Integer.parseInt(Port_number),
508 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
509 log(fnName, ":Sending the hello command");
510 sshJcraftWrapper.send(NetconfHelloCmd);
511 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
512 log(fnName, "Sending get running config command");
513 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
514 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
515 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
516 response = trimResponse(response);
517 ctx.setAttribute("xmlRunningConfigOutput", response);
518 sshJcraftWrapper.send(terminateConnectionCmd);
519 sshJcraftWrapper.closeConnection();
521 sshJcraftWrapper = null;
522 return (setResponseStatus(ctx, r));
523 } catch (Exception e) {
524 log(fnName, "Caught an Exception, e=" + e);
525 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
526 sshJcraftWrapper.closeConnection();
527 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
528 r.message = e.getMessage();
529 sshJcraftWrapper = null;
530 log(fnName, "Returning error message");
531 return (setResponseStatus(ctx, r));
534 if (key.equals("DownloadCliConfig")) {
535 DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
536 log.debug("key was: DownloadCliConfig: ");
537 String User_name = parameters.get("User_name");
538 String Host_ip_address = parameters.get("Host_ip_address");
539 String Password = parameters.get("Password");
540 Password = EncryptionTool.getInstance().decrypt(Password);
541 String Port_number = parameters.get("Port_number");
542 String Download_config_template = parameters.get("Download_config_template");
543 String Config_contents = parameters.get("Config_contents");
544 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
545 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
546 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
547 DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
548 int timeout = 4 * 60 * 1000;
550 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
551 " Host_ip_address=" + Host_ip_address + " Port_number="
553 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
554 " User_name=" + User_name + " Port_number=" + Port_number);
555 String CliResponse = "";
556 sshJcraftWrapper.connect(Host_ip_address,
561 Integer.parseInt(Port_number));
562 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
563 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
564 String command = null;
565 String executeConfigContentsDelemeter = null;
567 while (st.hasMoreTokens()) {
568 String line = st.nextToken();
569 DebugLog.printAriDebug(fnName, "line=" + line);
570 if (line.indexOf("Request:") != -1) {
571 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
572 command = getStringBetweenQuotes(line);
573 DebugLog.printAriDebug(fnName, "Sending command=" + command);
574 sshJcraftWrapper.send(command);
575 DebugLog.printAriDebug(fnName, "command has been sent");
576 } else if ((line.indexOf("Response: Ends_With") != -1) && (
577 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
578 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
579 String delemeter = getStringBetweenQuotes(line);
580 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
581 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
582 CliResponse += tmpResponse;
583 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
584 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
585 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
586 DebugLog.printAriDebug(fnName,
587 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
588 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
589 while (st2.hasMoreTokens()) {
590 String cmd = st2.nextToken();
591 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
592 sshJcraftWrapper.send(cmd);
593 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
596 CliResponse += tmpResponse;
600 } catch (NoSuchElementException e) {
601 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
603 sshJcraftWrapper.closeConnection();
604 sshJcraftWrapper = null;
605 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
606 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
607 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
608 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
609 ctx.setAttribute("cliOutput", CliResponse);
611 return (setResponseStatus(ctx, r));
612 } catch (IOException e) {
613 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
614 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
615 sshJcraftWrapper.closeConnection();
616 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
617 r.message = e.getMessage();
618 sshJcraftWrapper = null;
619 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
620 return (setResponseStatus(ctx, r));
624 DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
625 log.error("Unsupported action - " + action);
626 return ConfigStatus.FAILURE;
629 private void log(String fileName, String messg) {
630 DebugLog.printRTAriDebug(fileName, messg);
631 log.debug(fileName + ": " + messg);
634 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
635 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
636 String ndTemplate = readFile(templateName);
637 String nd = buildNetworkData2(ctx, ndTemplate, operation);
639 String reqTemplate = readFile("/config-request.xml");
640 Map<String, String> param = new HashMap<String, String>();
641 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
642 param.put("request-type", requestType);
643 param.put("callback-url", configCallbackUrl);
644 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
645 param.put("action", "GenerateOnly");
647 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
648 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
649 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
650 param.put("network-data", nd);
654 req = buildXmlRequest(param, reqTemplate);
655 } catch (Exception e) {
656 log.error("Error building the XML request: ", e);
658 HttpResponse r = new HttpResponse();
659 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
660 r.message = e.getMessage();
661 return setResponseStatus(ctx, r);
664 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
665 return setResponseStatus(ctx, r);
668 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
669 String reqTemplate = readFile("/config-request.xml");
670 Map<String, String> param = new HashMap<String, String>();
671 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
672 param.put("callback-url", configCallbackUrl);
673 param.put("action", change ? "DownloadChange" : "DownloadBase");
674 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
678 req = buildXmlRequest(param, reqTemplate);
679 } catch (Exception e) {
680 log.error("Error building the XML request: ", e);
682 HttpResponse r = new HttpResponse();
683 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
684 r.message = e.getMessage();
685 return setResponseStatus(ctx, r);
688 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
689 return setResponseStatus(ctx, r);
692 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
693 String reqTemplate = readFile("/audit-request.xml");
694 Map<String, String> param = new HashMap<String, String>();
695 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
696 param.put("callback-url", auditCallbackUrl);
697 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
698 param.put("audit-level", auditLevel);
702 req = buildXmlRequest(param, reqTemplate);
703 } catch (Exception e) {
704 log.error("Error building the XML request: ", e);
706 HttpResponse r = new HttpResponse();
707 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
708 r.message = e.getMessage();
709 return setResponseStatus(ctx, r);
712 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
713 return setResponseStatus(ctx, r);
717 public ConfigStatus activate(String key, SvcLogicContext ctx) {
718 return ConfigStatus.SUCCESS;
722 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
723 return ConfigStatus.SUCCESS;
726 private String escapeMySql(String input) {
731 input = input.replace("\\", "\\\\");
732 input = input.replace("\'", "\\'");
737 protected String readFile(String fileName) {
738 InputStream is = getClass().getResourceAsStream(fileName);
739 InputStreamReader isr = new InputStreamReader(is);
740 BufferedReader in = new BufferedReader(isr);
741 StringBuilder ss = new StringBuilder();
743 String s = in.readLine();
745 ss.append(s).append('\n');
748 } catch (IOException e) {
749 System.out.println("Error reading " + fileName + ": " + e.getMessage());
750 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
754 } catch (Exception e) {
755 log.warn("Could not close BufferedReader", e);
759 } catch (Exception e) {
760 log.warn("Could not close InputStreamReader", e);
764 } catch (Exception e) {
765 log.warn("Could not close InputStream", e);
768 return ss.toString();
771 private String buildXmlRequest(Map<String, String> param, String template) {
772 StringBuilder ss = new StringBuilder();
774 while (i < template.length()) {
775 int i1 = template.indexOf("${", i);
777 ss.append(template.substring(i));
781 int i2 = template.indexOf('}', i1 + 2);
783 throw new RuntimeException("Template error: Matching } not found");
786 String var1 = template.substring(i1 + 2, i2);
787 String value1 = param.get(var1);
788 if (value1 == null || value1.trim().length() == 0) {
789 // delete the whole element (line)
790 int i3 = template.lastIndexOf('\n', i1);
794 int i4 = template.indexOf('\n', i1);
796 i4 = template.length();
800 ss.append(template.substring(i, i3));
804 ss.append(template.substring(i, i1)).append(value1);
809 return ss.toString();
812 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
813 log.info("Building XML started");
814 long t1 = System.currentTimeMillis();
816 template = expandRepeats(ctx, template, 1);
818 Map<String, String> mm = new HashMap<>();
819 for (String s : ctx.getAttributeKeySet()) {
820 mm.put(s, ctx.getAttribute(s));
822 mm.put("operation", operation);
824 StringBuilder ss = new StringBuilder();
826 while (i < template.length()) {
827 int i1 = template.indexOf("${", i);
829 ss.append(template.substring(i));
833 int i2 = template.indexOf('}', i1 + 2);
835 throw new RuntimeException("Template error: Matching } not found");
838 String var1 = template.substring(i1 + 2, i2);
839 String value1 = XmlUtil.getXml(mm, var1);
840 if (value1 == null || value1.trim().length() == 0) {
841 // delete the whole element (line)
842 int i3 = template.lastIndexOf('\n', i1);
846 int i4 = template.indexOf('\n', i1);
848 i4 = template.length();
852 ss.append(template.substring(i, i3));
856 ss.append(template.substring(i, i1)).append(value1);
861 long t2 = System.currentTimeMillis();
862 log.info("Building XML completed. Time: " + (t2 - t1));
864 return ss.toString();
867 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
868 StringBuilder newTemplate = new StringBuilder();
870 while (k < template.length()) {
871 int i1 = template.indexOf("${repeat:", k);
873 newTemplate.append(template.substring(k));
877 int i2 = template.indexOf(':', i1 + 9);
879 throw new RuntimeException(
880 "Template error: Context variable name followed by : is required after repeat");
883 // Find the closing }, store in i3
887 while (nn > 0 && i < template.length()) {
888 i3 = template.indexOf('}', i);
890 throw new RuntimeException("Template error: Matching } not found");
892 int i32 = template.indexOf('{', i);
893 if (i32 >= 0 && i32 < i3) {
902 String var1 = template.substring(i1 + 9, i2);
903 String value1 = ctx.getAttribute(var1);
904 log.info(" " + var1 + ": " + value1);
907 n = Integer.parseInt(value1);
908 } catch (Exception e) {
912 newTemplate.append(template.substring(k, i1));
914 String rpt = template.substring(i2 + 1, i3);
916 for (int ii = 0; ii < n; ii++) {
917 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
918 newTemplate.append(ss);
925 return newTemplate.toString();
928 return expandRepeats(ctx, newTemplate.toString(), level + 1);
931 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
933 Client client = getClient();
934 WebTarget webResource = client.target(url);
936 log.info("SENDING...............");
937 if (log.isTraceEnabled()) {
938 log.trace(xmlRequest);
941 if(xmlRequest.length() > 255 ) {
942 log.info(xmlRequest.substring(0, 255));
943 log.info("\n...\n" + xmlRequest.length() +
944 " characters in request, turn on TRACE logging to log entire request");
947 log.info(xmlRequest);
950 String authString = user + ":" + password;
951 String authStringEnc = Base64.encode(authString.getBytes());
952 authString = "Basic " + authStringEnc;
954 Response response = getClientResponse(webResource, authString, xmlRequest);
956 int code = response.getStatus();
957 String message = response.getStatusInfo().getReasonPhrase();
958 log.info("RESPONSE...............");
959 log.info("HTTP response code: " + code);
960 log.info("HTTP response message: " + message);
963 HttpResponse r = new HttpResponse();
968 } catch (Exception e) {
969 log.error("Error sending the request: ", e);
971 HttpResponse r = new HttpResponse();
972 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
973 r.message = e.getMessage();
978 private static class HttpResponse {
982 public String message;
985 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
986 ctx.setAttribute("error-code", String.valueOf(r.code));
987 ctx.setAttribute("error-message", r.message);
989 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
992 private String getStringBetweenQuotes(String string) {
993 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
994 DebugLog.printAriDebug(fnName, "string=" + string);
995 String retString = null;
996 int start = string.indexOf('\"');
997 int end = string.lastIndexOf('\"');
998 retString = string.substring(start + 1, end);
999 DebugLog.printAriDebug(fnName, "retString=" + retString);
1003 public static String _readFile(String fileName) {
1004 StringBuffer strBuff = new StringBuffer();
1006 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
1007 while ((line = in.readLine()) != null) {
1008 strBuff.append(line + "\n");
1010 } catch (IOException e) {
1011 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
1013 return (strBuff.toString());
1017 * A supporting method to extract the data and configuration element from the NETCONF-XML response
1018 * from the node and create well formatted xml.
1020 * @param requestData The unformatted NETCONF-XML
1021 * @return responseBuilder the extracted data
1022 * @throws APPCException Exception during parsing xml data
1024 private String extractFromNetconfXml(String requestData) throws APPCException {
1025 log.debug("extractFromNetconfXml -- Start");
1026 StringBuilder responseBuilder = new StringBuilder();
1027 StringWriter stringBuffer = new StringWriter();
1029 requestData = requestData.replaceAll("]]>]]>", "");
1030 DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
1031 Document document = documentBuilder.parse(new InputSource(new StringReader(requestData)));
1032 document.getDocumentElement().normalize();
1033 XPath xPath = XPathFactory.newInstance().newXPath();
1034 Node dataNode = (Node) xPath.evaluate("//data", document, XPathConstants.NODE);
1035 Transformer xform = TransformerFactory.newInstance().newTransformer();
1036 xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
1037 xform.setOutputProperty(OutputKeys.INDENT, "yes");
1038 xform.transform(new DOMSource(dataNode), new StreamResult(stringBuffer));
1039 responseBuilder.append(stringBuffer.toString());
1040 if (log.isTraceEnabled()) {
1041 log.trace("ConfigComponentAdaptor:extractFromNetconfXml after Extract: "
1042 + responseBuilder.toString());
1044 } catch (SAXException | IOException | ParserConfigurationException | TransformerException
1045 | XPathExpressionException exception) {
1046 throw new APPCException("Error Occured during parsing Netconf-XML", exception);
1049 log.debug("extractFromNetconfXml -- End");
1050 return responseBuilder.toString();
1053 private String trimResponse(String response) throws APPCException {
1054 response = extractFromNetconfXml(response);
1055 log.debug("runningConfig before trimResponse : " + response);
1056 StringTokenizer line = new StringTokenizer(response, "\n");
1057 StringBuffer sb = new StringBuffer();
1058 String runningConfig = "" ;
1059 boolean captureText = false;
1060 while (line.hasMoreTokens()) {
1061 String token = line.nextToken();
1062 if (token.indexOf("<configuration xmlns=") != -1) {
1064 }else if(token.indexOf("<data") != -1) {
1065 log.debug("token-line:with in Data: "+token);
1070 if(token.indexOf("</data>") != -1) {
1071 log.debug("token-line:with in </data>"+token);
1072 captureText = false;
1075 sb.append(token + "\n");
1077 if (token.indexOf("</configuration>") != -1) {
1078 captureText = false;
1081 runningConfig = sb.toString();
1083 if (log.isTraceEnabled()) {
1084 log.trace("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1087 if (runningConfig.length() > 255) {
1088 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1089 runningConfig.substring(0, 255));
1090 log.info("\n...\n" + runningConfig.length() +
1091 " characters in config, turn on TRACE logging to log entire config");
1094 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1098 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1099 return runningConfig;
1102 public static void main(String args[]) throws Exception {
1103 Properties props = null;
1104 System.out.println("*************************Hello*****************************");
1105 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1106 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
1107 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
1108 String key = "GetCliRunningConfig";
1109 Map<String, String> parameters = new HashMap();
1110 parameters.put("Host_ip_address", "000.00.000.00");
1111 parameters.put("User_name", "root");
1112 parameters.put("Password", "!bootstrap");
1113 parameters.put("Port_number", "22");
1114 parameters.put("Get_config_template", Get_config_template);
1116 SvcLogicContext ctx = null;
1117 System.out.println("*************************TRACE 1*****************************");
1118 cca.configure(key, parameters, ctx);
1121 protected SshJcraftWrapper getSshJcraftWrapper() {
1122 return new SshJcraftWrapper();
1125 protected Client getClient() {
1126 ClientConfig clientConfig = new ClientConfig();
1127 clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 5000);
1128 return ClientBuilder.newClient(clientConfig);
1131 protected Response getClientResponse(WebTarget webResource, String authString, String xmlRequest) {
1132 return webResource.request("UTF-8").header("Authorization", authString).header("Content-Type", "application/xml").post(
1133 Entity.xml(xmlRequest),Response.class);