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 com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import com.sun.jersey.api.client.Client;
31 import com.sun.jersey.api.client.ClientResponse;
32 import com.sun.jersey.api.client.WebResource;
33 import com.sun.jersey.core.util.Base64;
34 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
35 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
38 import java.net.HttpURLConnection;
41 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
43 private static EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
44 DebugLog debugLog = new DebugLog();
45 private String configUrl = null;
46 private String configUser = null;
47 private String configPassword = null;
48 private String auditUrl = null;
49 private String auditUser = null;
50 private String auditPassword = null;
52 public String getConfigUrl() {
56 public String getConfigUser() {
60 public String getConfigPassword() {
61 return configPassword;
64 public String getAuditUrl() {
68 public String getAuditUser() {
72 public String getAuditPassword() {
76 public String getConfigCallbackUrl() {
77 return configCallbackUrl;
80 public String getAuditCallbackUrl() {
81 return auditCallbackUrl;
84 private String configCallbackUrl = null;
85 private String auditCallbackUrl = null;
86 private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ;
88 public ConfigComponentAdaptor(Properties props) {
90 configUrl = props.getProperty("configComponent.url", "");
91 configUser = props.getProperty("configComponent.user", "");
92 configPassword = props.getProperty("configComponent.passwd", "");
93 auditUrl = props.getProperty("auditComponent.url", "");
94 auditUser = props.getProperty("auditComponent.user", "");
95 auditPassword = props.getProperty("auditComponent.passwd", "");
96 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
97 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
105 configCallbackUrl = "";
106 auditCallbackUrl = "";
111 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
112 String fnName = "ConfigComponentAdaptor.configure";
113 HttpResponse r = new HttpResponse();
115 log.debug("ConfigComponentAdaptor.configure - key = " + key);
116 DebugLog.printRTAriDebug(fnName, "key = " + key);
117 log.debug("Parameters:");
118 DebugLog.printRTAriDebug(fnName, "Parameters:");
119 for (Map.Entry<String, String> entry : parameters.entrySet()) {
120 log.debug(" " + entry.getKey() + " = " + entry.getValue());
121 DebugLog.printRTAriDebug(fnName, " " + entry.getKey() + " = " + entry.getValue());
124 String parmval = parameters.get("config-component-configUrl");
125 if ((parmval != null) && (parmval.length() > 0)) {
126 log.debug("Overwriting URL with " + parmval);
130 parmval = parameters.get("config-component-configPassword");
131 if ((parmval != null) && (parmval.length() > 0)) {
132 log.debug("Overwriting configPassword with " + parmval);
133 configPassword = parmval;
136 parmval = parameters.get("config-component-configUser");
137 if ((parmval != null) && (parmval.length() > 0)) {
138 log.debug("Overwriting configUser id with " + parmval);
139 configUser = parmval;
142 String action = parameters.get("action");
144 String chg = ctx.getAttribute(
145 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
146 if (chg != null && "prepare".equalsIgnoreCase(action)) {
147 return prepare(ctx, "CHANGE", "change");
149 if (chg != null && "activate".equalsIgnoreCase(action)) {
150 return activate(ctx, true);
153 String scale = ctx.getAttribute(
154 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
155 if (scale != null && "prepare".equalsIgnoreCase(action)) {
156 return prepare(ctx, "CHANGE", "scale");
158 if (scale != null && "activate".equalsIgnoreCase(action)) {
159 return activate(ctx, true);
162 if ("prepare".equalsIgnoreCase(action)) {
163 return prepare(ctx, "BASE", "create");
165 if ("activate".equalsIgnoreCase(action)) {
166 return activate(ctx, false);
169 if ("backup".equalsIgnoreCase(action)) {
170 return prepare(ctx, "BACKUP", "backup");
172 if ("restorebackup".equalsIgnoreCase(action)) {
173 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
175 if ("deletebackup".equalsIgnoreCase(action)) {
176 return prepare(ctx, "DELETEBACKUP", "deletebackup");
178 if ("audit".equalsIgnoreCase(action)) {
179 return audit(ctx, "FULL");
181 if ("getrunningconfig".equalsIgnoreCase(action)) {
182 return audit(ctx, "RUNNING");
185 if (("put".equals(key)) || ("get".equals(key))) {
186 String loginId = parameters.get("loginId");
187 String host = parameters.get("host");
188 String password = parameters.get("password");
189 password = EncryptionTool.getInstance().decrypt(password);
190 String fullPathFileName = parameters.get("fullPathFileName");
193 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
194 log.debug("SCP: SshJcraftWrapper has been instantiated");
195 DebugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
197 if (key.equals("put")) {
198 data = parameters.get("data");
200 DebugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
201 InputStream is = new ByteArrayInputStream(data.getBytes());
202 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
203 DebugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
204 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
206 DebugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
207 Thread.sleep(1000l * 180);
208 DebugLog.printRTAriDebug(fnName, "Woke up....");
209 } catch (java.lang.InterruptedException ee) {
210 boolean ignore = true;
211 Thread.currentThread().interrupt();
214 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
215 log.debug(fnName + " Command is for put: data is null");
217 } else // Must be a get
219 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
220 DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
221 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
222 DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
223 ctx.setAttribute("fileContents", response);
224 log.debug("SCP: Closing the SFTP connection");
226 return (setResponseStatus(ctx, r));
227 } catch (IOException e) {
228 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
229 log.debug(fnName + " : Caught a IOException e=" + e);
230 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
231 r.message = e.getMessage();
232 return (setResponseStatus(ctx, r));
235 if (key.equals("cli")) {
236 String loginId = parameters.get("loginId");
237 String host = parameters.get("host");
238 String password = parameters.get("password");
239 password = EncryptionTool.getInstance().decrypt(password);
240 String portNumber = parameters.get("portNumber");
241 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
243 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
244 " portNumber=" + portNumber);
245 DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
246 " portNumber=" + portNumber);
247 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
249 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
250 String response = sshJcraftWrapper.send("sdc", ":");
251 DebugLog.printAriDebug(fnName, "Sending 1");
252 response = sshJcraftWrapper.send("1", ":");
253 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
254 response = sshJcraftWrapper.send("1", "#");
255 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
256 response = sshJcraftWrapper.send("paging-options disable", "#");
257 DebugLog.printAriDebug(fnName, "Sending show config");
258 response = sshJcraftWrapper.send("show config", "#");
260 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
261 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
262 ctx.setAttribute("cliOutput", response);
263 sshJcraftWrapper.closeConnection();
265 sshJcraftWrapper = null;
266 return (setResponseStatus(ctx, r));
267 } catch (IOException e) {
268 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
269 log.debug(fnName + " : Caught a IOException e=" + e);
270 sshJcraftWrapper.closeConnection();
271 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
272 r.message = e.getMessage();
273 sshJcraftWrapper = null;
274 DebugLog.printAriDebug(fnName, "Returning error message");
275 return (setResponseStatus(ctx, r));
278 if (key.equals("escapeSql")) {
279 String data = parameters.get("artifactContents");
280 log.debug("ConfigComponentAdaptor.configure - escapeSql");
281 data = escapeMySql(data);
282 ctx.setAttribute("escapedData", data);
283 return (setResponseStatus(ctx, r));
285 if (key.equals("GetCliRunningConfig")) {
286 DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
287 log.debug("key was: GetCliRunningConfig: ");
288 String User_name = parameters.get("User_name");
289 String Host_ip_address = parameters.get("Host_ip_address");
290 String Password = parameters.get("Password");
291 Password = EncryptionTool.getInstance().decrypt(Password);
292 String Port_number = parameters.get("Port_number");
293 String Get_config_template = parameters.get("Get_config_template");
294 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
295 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
296 DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
298 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
299 " Host_ip_address=" + Host_ip_address + " Port_number="
301 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
302 " User_name=" + User_name + " Port_number=" + Port_number);
303 String response = "";
304 String CliResponse = "";
305 boolean showConfigFlag = false;
306 sshJcraftWrapper.connect(Host_ip_address,
311 Integer.parseInt(Port_number));
312 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
313 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
314 String command = null;
316 while (st.hasMoreTokens()) {
317 String line = st.nextToken();
318 DebugLog.printAriDebug(fnName, "line=" + line);
319 if (line.indexOf("Request:") != -1) {
320 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
321 command = getStringBetweenQuotes(line);
322 DebugLog.printAriDebug(fnName, "Sending command=" + command);
323 sshJcraftWrapper.send(command);
324 DebugLog.printAriDebug(fnName, "command has been sent");
325 if (line.indexOf("show config") != -1) {
326 showConfigFlag = true;
327 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
328 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
331 if (line.indexOf("Response: Ends_With") != -1) {
332 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
333 String delemeter = getStringBetweenQuotes(line);
334 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
335 //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806
336 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter,
337 DEFAULT_TIMEOUT_GETRUNNING_CLI, command);
338 response += tmpResponse;
339 if (showConfigFlag) {
340 showConfigFlag = false;
341 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
342 // Strip off the last line which is the command prompt from the VNF device.
343 while (st2.hasMoreTokens()) {
344 String line2 = st2.nextToken();
345 if (line2.indexOf('#') == -1) {
346 CliResponse += line2 + "\n";
352 } catch (NoSuchElementException e) {
353 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
355 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
356 ctx.setAttribute("cliOutput", CliResponse);
357 sshJcraftWrapper.closeConnection();
359 sshJcraftWrapper = null;
360 return (setResponseStatus(ctx, r));
361 } catch (IOException e) {
362 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
363 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
364 sshJcraftWrapper.closeConnection();
365 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
366 r.message = e.getMessage();
367 sshJcraftWrapper = null;
368 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
369 return (setResponseStatus(ctx, r));
372 if (key.equals("xml-download")) {
373 log(fnName, "key was: xml-download");
374 String User_name = parameters.get("User_name");
375 String Host_ip_address = parameters.get("Host_ip_address");
376 String Password = parameters.get("Password");
377 Password = EncryptionTool.getInstance().decrypt(Password);
378 String Port_number = parameters.get("Port_number");
379 String Contents = parameters.get("Contents");
380 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>";
381 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 ]]>]]>";
382 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 ]]>]]>";
385 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
386 + " Port_number=" + Port_number);
387 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
389 sshJcraftWrapper.connect(Host_ip_address,
394 Integer.parseInt(Port_number),
396 String NetconfHelloCmd = netconfHelloCmd;
397 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
398 log(fnName, "Sending the hello command");
399 sshJcraftWrapper.send(NetconfHelloCmd);
400 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
401 log(fnName, "Sending xmlCmd cmd");
402 String xmlCmd = Contents;
403 String messageId = "1";
404 messageId = "\"" + messageId + "\"";
405 String loadConfigurationString =
406 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
408 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
409 + xmlCmd + "</config> </edit-config> </rpc>";
410 loadConfigurationString = loadConfigurationString + "]]>]]>";
411 sshJcraftWrapper.send(loadConfigurationString);
412 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
413 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
414 if (response.indexOf("rpc-error") != -1) {
415 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
416 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
417 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
418 r.message = response;
420 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
421 sshJcraftWrapper.send(commitCmd);
422 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
423 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
424 if (response.indexOf("rpc-error") != -1) {
425 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
426 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
427 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
428 r.message = response;
430 DebugLog.printAriDebug(fnName, ":Looks like a success");
431 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
435 sshJcraftWrapper.send(terminateConnectionCmd);
436 sshJcraftWrapper.closeConnection();
437 sshJcraftWrapper = null;
438 return (setResponseStatus(ctx, r));
439 } catch (Exception e) {
440 log(fnName, "Caught an Exception, e=" + e);
441 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
442 sshJcraftWrapper.closeConnection();
443 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
444 r.message = e.getMessage();
445 sshJcraftWrapper = null;
446 log(fnName, "Returning error message");
447 return (setResponseStatus(ctx, r));
450 if (key.equals("xml-getrunningconfig")) {
451 log(fnName, "key was: : xml-getrunningconfig");
452 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";
453 String Host_ip_address = parameters.get("Host_ip_address");
454 String User_name = parameters.get("User_name");
455 String Password = parameters.get("Password");
456 Password = EncryptionTool.getInstance().decrypt(Password);
457 String Port_number = parameters.get("Port_number");
458 String Protocol = parameters.get("Protocol");
459 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>";
460 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 ]]>]]>";
462 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
463 + " Port_number=" + Port_number);
464 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
466 String NetconfHelloCmd = netconfHelloCmd;
467 sshJcraftWrapper.connect(Host_ip_address,
472 Integer.parseInt(Port_number),
474 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
475 log(fnName, ":Sending the hello command");
476 sshJcraftWrapper.send(NetconfHelloCmd);
477 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
478 log(fnName, "Sending get running config command");
479 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
480 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
481 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
482 response = trimResponse(response);
483 ctx.setAttribute("xmlRunningConfigOutput", response);
484 sshJcraftWrapper.send(terminateConnectionCmd);
485 sshJcraftWrapper.closeConnection();
487 sshJcraftWrapper = null;
488 return (setResponseStatus(ctx, r));
489 } catch (Exception e) {
490 log(fnName, "Caught an Exception, e=" + e);
491 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
492 sshJcraftWrapper.closeConnection();
493 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
494 r.message = e.getMessage();
495 sshJcraftWrapper = null;
496 log(fnName, "Returning error message");
497 return (setResponseStatus(ctx, r));
500 if (key.equals("DownloadCliConfig")) {
501 DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
502 log.debug("key was: DownloadCliConfig: ");
503 String User_name = parameters.get("User_name");
504 String Host_ip_address = parameters.get("Host_ip_address");
505 String Password = parameters.get("Password");
506 Password = EncryptionTool.getInstance().decrypt(Password);
507 String Port_number = parameters.get("Port_number");
508 String Download_config_template = parameters.get("Download_config_template");
509 String Config_contents = parameters.get("Config_contents");
510 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
511 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
512 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
513 DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
514 int timeout = 4 * 60 * 1000;
516 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
517 " Host_ip_address=" + Host_ip_address + " Port_number="
519 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
520 " User_name=" + User_name + " Port_number=" + Port_number);
521 String CliResponse = "";
522 sshJcraftWrapper.connect(Host_ip_address,
527 Integer.parseInt(Port_number));
528 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
529 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
530 String command = null;
531 String executeConfigContentsDelemeter = null;
533 while (st.hasMoreTokens()) {
534 String line = st.nextToken();
535 DebugLog.printAriDebug(fnName, "line=" + line);
536 if (line.indexOf("Request:") != -1) {
537 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
538 command = getStringBetweenQuotes(line);
539 DebugLog.printAriDebug(fnName, "Sending command=" + command);
540 sshJcraftWrapper.send(command);
541 DebugLog.printAriDebug(fnName, "command has been sent");
542 } else if ((line.indexOf("Response: Ends_With") != -1) && (
543 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
544 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
545 String delemeter = getStringBetweenQuotes(line);
546 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
547 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
548 CliResponse += tmpResponse;
549 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
550 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
551 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
552 DebugLog.printAriDebug(fnName,
553 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
554 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
555 while (st2.hasMoreTokens()) {
556 String cmd = st2.nextToken();
557 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
558 sshJcraftWrapper.send(cmd);
559 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
562 CliResponse += tmpResponse;
566 } catch (NoSuchElementException e) {
567 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
569 sshJcraftWrapper.closeConnection();
570 sshJcraftWrapper = null;
571 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
572 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
573 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
574 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
575 ctx.setAttribute("cliOutput", CliResponse);
577 return (setResponseStatus(ctx, r));
578 } catch (IOException e) {
579 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
580 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
581 sshJcraftWrapper.closeConnection();
582 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
583 r.message = e.getMessage();
584 sshJcraftWrapper = null;
585 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
586 return (setResponseStatus(ctx, r));
590 DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
591 log.error("Unsupported action - " + action);
592 return ConfigStatus.FAILURE;
595 private void log(String fileName, String messg) {
596 DebugLog.printRTAriDebug(fileName, messg);
597 log.debug(fileName + ": " + messg);
600 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
601 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
602 String ndTemplate = readFile(templateName);
603 String nd = buildNetworkData2(ctx, ndTemplate, operation);
605 String reqTemplate = readFile("/config-request.xml");
606 Map<String, String> param = new HashMap<String, String>();
607 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
608 param.put("request-type", requestType);
609 param.put("callback-url", configCallbackUrl);
610 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
611 param.put("action", "GenerateOnly");
613 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
614 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
615 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
616 param.put("network-data", nd);
620 req = buildXmlRequest(param, reqTemplate);
621 } catch (Exception e) {
622 log.error("Error building the XML request: ", e);
624 HttpResponse r = new HttpResponse();
625 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
626 r.message = e.getMessage();
627 return setResponseStatus(ctx, r);
630 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
631 return setResponseStatus(ctx, r);
634 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
635 String reqTemplate = readFile("/config-request.xml");
636 Map<String, String> param = new HashMap<String, String>();
637 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
638 param.put("callback-url", configCallbackUrl);
639 param.put("action", change ? "DownloadChange" : "DownloadBase");
640 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
644 req = buildXmlRequest(param, reqTemplate);
645 } catch (Exception e) {
646 log.error("Error building the XML request: ", e);
648 HttpResponse r = new HttpResponse();
649 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
650 r.message = e.getMessage();
651 return setResponseStatus(ctx, r);
654 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
655 return setResponseStatus(ctx, r);
658 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
659 String reqTemplate = readFile("/audit-request.xml");
660 Map<String, String> param = new HashMap<String, String>();
661 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
662 param.put("callback-url", auditCallbackUrl);
663 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
664 param.put("audit-level", auditLevel);
668 req = buildXmlRequest(param, reqTemplate);
669 } catch (Exception e) {
670 log.error("Error building the XML request: ", e);
672 HttpResponse r = new HttpResponse();
673 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
674 r.message = e.getMessage();
675 return setResponseStatus(ctx, r);
678 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
679 return setResponseStatus(ctx, r);
683 public ConfigStatus activate(String key, SvcLogicContext ctx) {
684 return ConfigStatus.SUCCESS;
688 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
689 return ConfigStatus.SUCCESS;
692 private String escapeMySql(String input) {
697 input = input.replace("\\", "\\\\");
698 input = input.replace("\'", "\\'");
703 protected String readFile(String fileName) {
704 InputStream is = getClass().getResourceAsStream(fileName);
705 InputStreamReader isr = new InputStreamReader(is);
706 BufferedReader in = new BufferedReader(isr);
707 StringBuilder ss = new StringBuilder();
709 String s = in.readLine();
711 ss.append(s).append('\n');
714 } catch (IOException e) {
715 System.out.println("Error reading " + fileName + ": " + e.getMessage());
716 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
720 } catch (Exception e) {
721 log.warn("Could not close BufferedReader", e);
725 } catch (Exception e) {
726 log.warn("Could not close InputStreamReader", e);
730 } catch (Exception e) {
731 log.warn("Could not close InputStream", e);
734 return ss.toString();
737 private String buildXmlRequest(Map<String, String> param, String template) {
738 StringBuilder ss = new StringBuilder();
740 while (i < template.length()) {
741 int i1 = template.indexOf("${", i);
743 ss.append(template.substring(i));
747 int i2 = template.indexOf('}', i1 + 2);
749 throw new RuntimeException("Template error: Matching } not found");
752 String var1 = template.substring(i1 + 2, i2);
753 String value1 = param.get(var1);
754 if (value1 == null || value1.trim().length() == 0) {
755 // delete the whole element (line)
756 int i3 = template.lastIndexOf('\n', i1);
760 int i4 = template.indexOf('\n', i1);
762 i4 = template.length();
766 ss.append(template.substring(i, i3));
770 ss.append(template.substring(i, i1)).append(value1);
775 return ss.toString();
778 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
779 log.info("Building XML started");
780 long t1 = System.currentTimeMillis();
782 template = expandRepeats(ctx, template, 1);
784 Map<String, String> mm = new HashMap<>();
785 for (String s : ctx.getAttributeKeySet()) {
786 mm.put(s, ctx.getAttribute(s));
788 mm.put("operation", operation);
790 StringBuilder ss = new StringBuilder();
792 while (i < template.length()) {
793 int i1 = template.indexOf("${", i);
795 ss.append(template.substring(i));
799 int i2 = template.indexOf('}', i1 + 2);
801 throw new RuntimeException("Template error: Matching } not found");
804 String var1 = template.substring(i1 + 2, i2);
805 String value1 = XmlUtil.getXml(mm, var1);
806 if (value1 == null || value1.trim().length() == 0) {
807 // delete the whole element (line)
808 int i3 = template.lastIndexOf('\n', i1);
812 int i4 = template.indexOf('\n', i1);
814 i4 = template.length();
818 ss.append(template.substring(i, i3));
822 ss.append(template.substring(i, i1)).append(value1);
827 long t2 = System.currentTimeMillis();
828 log.info("Building XML completed. Time: " + (t2 - t1));
830 return ss.toString();
833 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
834 StringBuilder newTemplate = new StringBuilder();
836 while (k < template.length()) {
837 int i1 = template.indexOf("${repeat:", k);
839 newTemplate.append(template.substring(k));
843 int i2 = template.indexOf(':', i1 + 9);
845 throw new RuntimeException(
846 "Template error: Context variable name followed by : is required after repeat");
849 // Find the closing }, store in i3
853 while (nn > 0 && i < template.length()) {
854 i3 = template.indexOf('}', i);
856 throw new RuntimeException("Template error: Matching } not found");
858 int i32 = template.indexOf('{', i);
859 if (i32 >= 0 && i32 < i3) {
868 String var1 = template.substring(i1 + 9, i2);
869 String value1 = ctx.getAttribute(var1);
870 log.info(" " + var1 + ": " + value1);
873 n = Integer.parseInt(value1);
874 } catch (Exception e) {
878 newTemplate.append(template.substring(k, i1));
880 String rpt = template.substring(i2 + 1, i3);
882 for (int ii = 0; ii < n; ii++) {
883 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
884 newTemplate.append(ss);
891 return newTemplate.toString();
894 return expandRepeats(ctx, newTemplate.toString(), level + 1);
897 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
899 Client client = getClient();
900 client.setConnectTimeout(5000);
901 WebResource webResource = client.resource(url);
903 log.info("SENDING...............");
904 if (log.isTraceEnabled()) {
905 log.trace(xmlRequest);
908 if(xmlRequest.length() > 255 ) {
909 log.info(xmlRequest.substring(0, 255));
910 log.info("\n...\n" + xmlRequest.length() +
911 " characters in request, turn on TRACE logging to log entire request");
914 log.info(xmlRequest);
917 String authString = user + ":" + password;
918 byte[] authEncBytes = Base64.encode(authString);
919 String authStringEnc = new String(authEncBytes);
920 authString = "Basic " + authStringEnc;
922 ClientResponse response = getClientResponse(webResource, authString, xmlRequest);
924 int code = response.getStatus();
925 String message = null;
927 log.info("RESPONSE...............");
928 log.info("HTTP response code: " + code);
929 log.info("HTTP response message: " + message);
932 HttpResponse r = new HttpResponse();
937 } catch (Exception e) {
938 log.error("Error sending the request: ", e);
940 HttpResponse r = new HttpResponse();
941 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
942 r.message = e.getMessage();
947 private static class HttpResponse {
951 public String message;
954 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
955 ctx.setAttribute("error-code", String.valueOf(r.code));
956 ctx.setAttribute("error-message", r.message);
958 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
961 private String getStringBetweenQuotes(String string) {
962 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
963 DebugLog.printAriDebug(fnName, "string=" + string);
964 String retString = null;
965 int start = string.indexOf('\"');
966 int end = string.lastIndexOf('\"');
967 retString = string.substring(start + 1, end);
968 DebugLog.printAriDebug(fnName, "retString=" + retString);
972 public static String _readFile(String fileName) {
973 StringBuffer strBuff = new StringBuffer();
975 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
976 while ((line = in.readLine()) != null) {
977 strBuff.append(line + "\n");
979 } catch (IOException e) {
980 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
982 return (strBuff.toString());
985 private String trimResponse(String response) {
986 log.debug("runningConfig before trimResponse : " + response);
987 StringTokenizer line = new StringTokenizer(response, "\n");
988 StringBuffer sb = new StringBuffer();
989 String runningConfig = "" ;
990 boolean captureText = false;
991 while (line.hasMoreTokens()) {
992 String token = line.nextToken();
993 if (token.indexOf("<configuration xmlns=") != -1) {
995 }else if(token.indexOf("<data>") != -1) {
996 log.debug("token-line:with in Data: "+token);
1001 if(token.indexOf("</data>") != -1) {
1002 log.debug("token-line:with in </data>"+token);
1003 captureText = false;
1006 sb.append(token + "\n");
1008 if (token.indexOf("</configuration>") != -1) {
1009 captureText = false;
1012 runningConfig = sb.toString();
1014 if (log.isTraceEnabled()) {
1015 log.trace("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1018 if (runningConfig.length() > 255) {
1019 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1020 runningConfig.substring(0, 255));
1021 log.info("\n...\n" + runningConfig.length() +
1022 " characters in config, turn on TRACE logging to log entire config");
1025 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1029 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1030 return runningConfig;
1033 public static void main(String args[]) throws Exception {
1034 Properties props = null;
1035 System.out.println("*************************Hello*****************************");
1036 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1037 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
1038 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
1039 String key = "GetCliRunningConfig";
1040 Map<String, String> parameters = new HashMap();
1041 parameters.put("Host_ip_address", "000.00.000.00");
1042 parameters.put("User_name", "root");
1043 parameters.put("Password", "!bootstrap");
1044 parameters.put("Port_number", "22");
1045 parameters.put("Get_config_template", Get_config_template);
1047 SvcLogicContext ctx = null;
1048 System.out.println("*************************TRACE 1*****************************");
1049 cca.configure(key, parameters, ctx);
1052 protected SshJcraftWrapper getSshJcraftWrapper() {
1053 return new SshJcraftWrapper();
1056 protected Client getClient() {
1057 return Client.create();
1060 protected ClientResponse getClientResponse(WebResource webResource, String authString, String xmlRequest) {
1061 return webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
1062 ClientResponse.class, xmlRequest);