2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * =============================================================================
7 * Modifications Copyright (C) 2018 IBM.
8 * =============================================================================
9 * Modifications Copyright (C) 2018 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 java.io.BufferedReader;
35 import java.io.ByteArrayInputStream;
36 import java.io.FileReader;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.InputStreamReader;
40 import java.net.HttpURLConnection;
41 import java.util.HashMap;
43 import java.util.NoSuchElementException;
44 import java.util.Properties;
45 import java.util.StringTokenizer;
46 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
47 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
49 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
51 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
52 DebugLog debugLog = new DebugLog();
53 private String configUrl = null;
54 private String configUser = null;
55 private String configPassword = null;
56 private String auditUrl = null;
57 private String auditUser = null;
58 private String auditPassword = null;
60 public String getConfigUrl() {
64 public String getConfigUser() {
68 public String getConfigPassword() {
69 return configPassword;
72 public String getAuditUrl() {
76 public String getAuditUser() {
80 public String getAuditPassword() {
84 public String getConfigCallbackUrl() {
85 return configCallbackUrl;
88 public String getAuditCallbackUrl() {
89 return auditCallbackUrl;
92 private String configCallbackUrl = null;
93 private String auditCallbackUrl = null;
94 private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ;
96 public ConfigComponentAdaptor(Properties props) {
98 configUrl = props.getProperty("configComponent.url", "");
99 configUser = props.getProperty("configComponent.user", "");
100 configPassword = props.getProperty("configComponent.passwd", "");
101 auditUrl = props.getProperty("auditComponent.url", "");
102 auditUser = props.getProperty("auditComponent.user", "");
103 auditPassword = props.getProperty("auditComponent.passwd", "");
104 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
105 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
113 configCallbackUrl = "";
114 auditCallbackUrl = "";
119 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
120 String fnName = "ConfigComponentAdaptor.configure";
121 HttpResponse r = new HttpResponse();
123 log.debug("ConfigComponentAdaptor.configure - key = " + key);
124 DebugLog.printRTAriDebug(fnName, "key = " + key);
125 log.debug("Parameters:");
126 DebugLog.printRTAriDebug(fnName, "Parameters:");
127 for (String parmName : parameters.keySet()) {
128 log.debug(" " + parmName + " = " + parameters.get(parmName));
129 DebugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
132 String parmval = parameters.get("config-component-configUrl");
133 if ((parmval != null) && (parmval.length() > 0)) {
134 log.debug("Overwriting URL with " + parmval);
138 parmval = parameters.get("config-component-configPassword");
139 if ((parmval != null) && (parmval.length() > 0)) {
140 log.debug("Overwriting configPassword with " + parmval);
141 configPassword = parmval;
144 parmval = parameters.get("config-component-configUser");
145 if ((parmval != null) && (parmval.length() > 0)) {
146 log.debug("Overwriting configUser id with " + parmval);
147 configUser = parmval;
150 String action = parameters.get("action");
152 String chg = ctx.getAttribute(
153 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
154 if (chg != null && "prepare".equalsIgnoreCase(action)) {
155 return prepare(ctx, "CHANGE", "change");
157 if (chg != null && "activate".equalsIgnoreCase(action)) {
158 return activate(ctx, true);
161 String scale = ctx.getAttribute(
162 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
163 if (scale != null && "prepare".equalsIgnoreCase(action)) {
164 return prepare(ctx, "CHANGE", "scale");
166 if (scale != null && "activate".equalsIgnoreCase(action)) {
167 return activate(ctx, true);
170 if ("prepare".equalsIgnoreCase(action)) {
171 return prepare(ctx, "BASE", "create");
173 if ("activate".equalsIgnoreCase(action)) {
174 return activate(ctx, false);
177 if ("backup".equalsIgnoreCase(action)) {
178 return prepare(ctx, "BACKUP", "backup");
180 if ("restorebackup".equalsIgnoreCase(action)) {
181 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
183 if ("deletebackup".equalsIgnoreCase(action)) {
184 return prepare(ctx, "DELETEBACKUP", "deletebackup");
186 if ("audit".equalsIgnoreCase(action)) {
187 return audit(ctx, "FULL");
189 if ("getrunningconfig".equalsIgnoreCase(action)) {
190 return audit(ctx, "RUNNING");
193 if ((key.equals("put")) || (key.equals("get"))) {
194 String loginId = parameters.get("loginId");
195 String host = parameters.get("host");
196 String password = parameters.get("password");
197 password = EncryptionTool.getInstance().decrypt(password);
198 String fullPathFileName = parameters.get("fullPathFileName");
201 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
202 log.debug("SCP: SshJcraftWrapper has been instantiated");
203 DebugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
205 if (key.equals("put")) {
206 data = parameters.get("data");
208 DebugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
209 InputStream is = new ByteArrayInputStream(data.getBytes());
210 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
211 DebugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
212 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
214 DebugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
215 Thread.sleep(1000 * 180);
216 DebugLog.printRTAriDebug(fnName, "Woke up....");
217 } catch (java.lang.InterruptedException ee) {
218 boolean ignore = true;
221 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
222 log.debug(fnName + " Command is for put: data is null");
224 } else // Must be a get
226 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
227 DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
228 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
229 DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
230 ctx.setAttribute("fileContents", response);
231 log.debug("SCP: Closing the SFTP connection");
233 sshJcraftWrapper = null;
234 return (setResponseStatus(ctx, r));
235 } catch (IOException e) {
236 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
237 log.debug(fnName + " : Caught a IOException e=" + e);
238 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
239 r.message = e.getMessage();
240 sshJcraftWrapper = null;
241 return (setResponseStatus(ctx, r));
244 if (key.equals("cli")) {
245 String loginId = parameters.get("loginId");
246 String host = parameters.get("host");
247 String password = parameters.get("password");
248 password = EncryptionTool.getInstance().decrypt(password);
249 String cliCommand = parameters.get("cli");
250 String portNumber = parameters.get("portNumber");
251 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
253 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
254 " portNumber=" + portNumber);
255 DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
256 " portNumber=" + portNumber);
257 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
259 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
260 String response = sshJcraftWrapper.send("sdc", ":");
261 DebugLog.printAriDebug(fnName, "Sending 1");
262 response = sshJcraftWrapper.send("1", ":");
263 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
264 response = sshJcraftWrapper.send("1", "#");
265 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
266 response = sshJcraftWrapper.send("paging-options disable", "#");
267 DebugLog.printAriDebug(fnName, "Sending show config");
268 response = sshJcraftWrapper.send("show config", "#");
270 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
271 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
272 ctx.setAttribute("cliOutput", response);
273 sshJcraftWrapper.closeConnection();
275 sshJcraftWrapper = null;
276 return (setResponseStatus(ctx, r));
277 } catch (IOException e) {
278 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
279 log.debug(fnName + " : Caught a IOException e=" + e);
280 sshJcraftWrapper.closeConnection();
281 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
282 r.message = e.getMessage();
283 sshJcraftWrapper = null;
284 DebugLog.printAriDebug(fnName, "Returning error message");
285 return (setResponseStatus(ctx, r));
288 if (key.equals("escapeSql")) {
289 String data = parameters.get("artifactContents");
290 log.debug("ConfigComponentAdaptor.configure - escapeSql");
291 data = escapeMySql(data);
292 ctx.setAttribute("escapedData", data);
293 return (setResponseStatus(ctx, r));
295 if (key.equals("GetCliRunningConfig")) {
296 DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
297 log.debug("key was: GetCliRunningConfig: ");
298 String User_name = parameters.get("User_name");
299 String Host_ip_address = parameters.get("Host_ip_address");
300 String Password = parameters.get("Password");
301 Password = EncryptionTool.getInstance().decrypt(Password);
302 String Port_number = parameters.get("Port_number");
303 String Get_config_template = parameters.get("Get_config_template");
304 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
305 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
306 DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
308 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
309 " Host_ip_address=" + Host_ip_address + " Port_number="
311 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
312 " User_name=" + User_name + " Port_number=" + Port_number);
313 StringBuffer sb = new StringBuffer();
314 String response = "";
315 String CliResponse = "";
316 boolean showConfigFlag = false;
317 sshJcraftWrapper.connect(Host_ip_address,
322 Integer.parseInt(Port_number));
323 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
324 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
325 String command = null;
327 while (st.hasMoreTokens()) {
328 String line = st.nextToken();
329 DebugLog.printAriDebug(fnName, "line=" + line);
330 if (line.indexOf("Request:") != -1) {
331 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
332 command = getStringBetweenQuotes(line);
333 DebugLog.printAriDebug(fnName, "Sending command=" + command);
334 sshJcraftWrapper.send(command);
335 DebugLog.printAriDebug(fnName, "command has been sent");
336 if (line.indexOf("show config") != -1) {
337 showConfigFlag = true;
338 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
339 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
342 if (line.indexOf("Response: Ends_With") != -1) {
343 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
344 String delemeter = getStringBetweenQuotes(line);
345 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
346 //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806
347 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter,
348 DEFAULT_TIMEOUT_GETRUNNING_CLI, command);
349 response += tmpResponse;
350 if (showConfigFlag) {
351 showConfigFlag = false;
352 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
353 // Strip off the last line which is the command prompt from the VNF device.
354 while (st2.hasMoreTokens()) {
355 String line2 = st2.nextToken();
356 if (line2.indexOf("#") == -1) {
357 CliResponse += line2 + "\n";
363 } catch (NoSuchElementException e) {
364 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
366 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
367 ctx.setAttribute("cliOutput", CliResponse);
368 sshJcraftWrapper.closeConnection();
370 sshJcraftWrapper = null;
371 return (setResponseStatus(ctx, r));
372 } catch (IOException e) {
373 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
374 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
375 sshJcraftWrapper.closeConnection();
376 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
377 r.message = e.getMessage();
378 sshJcraftWrapper = null;
379 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
380 return (setResponseStatus(ctx, r));
383 if (key.equals("xml-download")) {
384 log(fnName, "key was: xml-download");
385 String User_name = parameters.get("User_name");
386 String Host_ip_address = parameters.get("Host_ip_address");
387 String Password = parameters.get("Password");
388 Password = EncryptionTool.getInstance().decrypt(Password);
389 String Port_number = parameters.get("Port_number");
390 String Contents = parameters.get("Contents");
391 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>";
392 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 ]]>]]>";
393 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 ]]>]]>";
396 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
397 + " Port_number=" + Port_number);
398 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
400 sshJcraftWrapper.connect(Host_ip_address,
405 Integer.parseInt(Port_number),
407 String NetconfHelloCmd = netconfHelloCmd;
408 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
409 log(fnName, "Sending the hello command");
410 sshJcraftWrapper.send(NetconfHelloCmd);
411 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
412 log(fnName, "Sending xmlCmd cmd");
413 String xmlCmd = Contents;
414 String messageId = "1";
415 messageId = "\"" + messageId + "\"";
416 String loadConfigurationString =
417 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
419 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
420 + xmlCmd + "</config> </edit-config> </rpc>";
421 loadConfigurationString = loadConfigurationString + "]]>]]>";
422 sshJcraftWrapper.send(loadConfigurationString);
423 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
424 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
425 if (response.indexOf("rpc-error") != -1) {
426 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
427 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
428 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
429 r.message = response;
431 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
432 sshJcraftWrapper.send(commitCmd);
433 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
434 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
435 if (response.indexOf("rpc-error") != -1) {
436 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
437 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
438 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
439 r.message = response;
441 DebugLog.printAriDebug(fnName, ":Looks like a success");
442 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
446 sshJcraftWrapper.send(terminateConnectionCmd);
447 sshJcraftWrapper.closeConnection();
448 sshJcraftWrapper = null;
449 return (setResponseStatus(ctx, r));
450 } catch (Exception e) {
451 log(fnName, "Caught an Exception, e=" + e);
452 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
453 sshJcraftWrapper.closeConnection();
454 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
455 r.message = e.getMessage();
456 sshJcraftWrapper = null;
457 log(fnName, "Returning error message");
458 return (setResponseStatus(ctx, r));
461 if (key.equals("xml-getrunningconfig")) {
462 log(fnName, "key was: : xml-getrunningconfig");
463 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";
464 String Host_ip_address = parameters.get("Host_ip_address");
465 String User_name = parameters.get("User_name");
466 String Password = parameters.get("Password");
467 Password = EncryptionTool.getInstance().decrypt(Password);
468 String Port_number = parameters.get("Port_number");
469 String Protocol = parameters.get("Protocol");
470 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>";
471 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 ]]>]]>";
473 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
474 + " Port_number=" + Port_number);
475 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
477 String NetconfHelloCmd = netconfHelloCmd;
478 sshJcraftWrapper.connect(Host_ip_address,
483 Integer.parseInt(Port_number),
485 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
486 log(fnName, ":Sending the hello command");
487 sshJcraftWrapper.send(NetconfHelloCmd);
488 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
489 log(fnName, "Sending get running config command");
490 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
491 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
492 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
493 response = trimResponse(response);
494 ctx.setAttribute("xmlRunningConfigOutput", response);
495 sshJcraftWrapper.send(terminateConnectionCmd);
496 sshJcraftWrapper.closeConnection();
498 sshJcraftWrapper = null;
499 return (setResponseStatus(ctx, r));
500 } catch (Exception e) {
501 log(fnName, "Caught an Exception, e=" + e);
502 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
503 sshJcraftWrapper.closeConnection();
504 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
505 r.message = e.getMessage();
506 sshJcraftWrapper = null;
507 log(fnName, "Returning error message");
508 return (setResponseStatus(ctx, r));
511 if (key.equals("DownloadCliConfig")) {
512 DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
513 log.debug("key was: DownloadCliConfig: ");
514 String User_name = parameters.get("User_name");
515 String Host_ip_address = parameters.get("Host_ip_address");
516 String Password = parameters.get("Password");
517 Password = EncryptionTool.getInstance().decrypt(Password);
518 String Port_number = parameters.get("Port_number");
519 String Download_config_template = parameters.get("Download_config_template");
520 String Config_contents = parameters.get("Config_contents");
521 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
522 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
523 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
524 DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
525 int timeout = 4 * 60 * 1000;
527 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
528 " Host_ip_address=" + Host_ip_address + " Port_number="
530 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
531 " User_name=" + User_name + " Port_number=" + Port_number);
532 StringBuffer sb = new StringBuffer();
533 String response = "";
534 String CliResponse = "";
535 sshJcraftWrapper.connect(Host_ip_address,
540 Integer.parseInt(Port_number));
541 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
542 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
543 String command = null;
544 String executeConfigContentsDelemeter = null;
546 while (st.hasMoreTokens()) {
547 String line = st.nextToken();
548 DebugLog.printAriDebug(fnName, "line=" + line);
549 if (line.indexOf("Request:") != -1) {
550 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
551 command = getStringBetweenQuotes(line);
552 DebugLog.printAriDebug(fnName, "Sending command=" + command);
553 sshJcraftWrapper.send(command);
554 DebugLog.printAriDebug(fnName, "command has been sent");
555 } else if ((line.indexOf("Response: Ends_With") != -1) && (
556 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
557 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
558 String delemeter = getStringBetweenQuotes(line);
559 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
560 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
561 response += tmpResponse;
562 CliResponse += tmpResponse;
563 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
564 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
565 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
566 DebugLog.printAriDebug(fnName,
567 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
568 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
569 while (st2.hasMoreTokens()) {
570 String cmd = st2.nextToken();
571 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
572 sshJcraftWrapper.send(cmd);
573 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
576 CliResponse += tmpResponse;
580 } catch (NoSuchElementException e) {
581 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
583 sshJcraftWrapper.closeConnection();
584 sshJcraftWrapper = null;
585 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
586 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
587 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
588 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
589 ctx.setAttribute("cliOutput", CliResponse);
591 return (setResponseStatus(ctx, r));
592 } catch (IOException e) {
593 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
594 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
595 sshJcraftWrapper.closeConnection();
596 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
597 r.message = e.getMessage();
598 sshJcraftWrapper = null;
599 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
600 return (setResponseStatus(ctx, r));
604 DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
605 log.error("Unsupported action - " + action);
606 return ConfigStatus.FAILURE;
609 private void log(String fileName, String messg) {
610 DebugLog.printRTAriDebug(fileName, messg);
611 log.debug(fileName + ": " + messg);
614 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
615 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
616 String ndTemplate = readFile(templateName);
617 String nd = buildNetworkData2(ctx, ndTemplate, operation);
619 String reqTemplate = readFile("/config-request.xml");
620 Map<String, String> param = new HashMap<String, String>();
621 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
622 param.put("request-type", requestType);
623 param.put("callback-url", configCallbackUrl);
624 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
625 param.put("action", "GenerateOnly");
627 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
628 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
629 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
630 param.put("network-data", nd);
634 req = buildXmlRequest(param, reqTemplate);
635 } catch (Exception e) {
636 log.error("Error building the XML request: ", e);
638 HttpResponse r = new HttpResponse();
639 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
640 r.message = e.getMessage();
641 return setResponseStatus(ctx, r);
644 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
645 return setResponseStatus(ctx, r);
648 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
649 String reqTemplate = readFile("/config-request.xml");
650 Map<String, String> param = new HashMap<String, String>();
651 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
652 param.put("callback-url", configCallbackUrl);
653 param.put("action", change ? "DownloadChange" : "DownloadBase");
654 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
658 req = buildXmlRequest(param, reqTemplate);
659 } catch (Exception e) {
660 log.error("Error building the XML request: ", e);
662 HttpResponse r = new HttpResponse();
663 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
664 r.message = e.getMessage();
665 return setResponseStatus(ctx, r);
668 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
669 return setResponseStatus(ctx, r);
672 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
673 String reqTemplate = readFile("/audit-request.xml");
674 Map<String, String> param = new HashMap<String, String>();
675 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
676 param.put("callback-url", auditCallbackUrl);
677 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
678 param.put("audit-level", auditLevel);
682 req = buildXmlRequest(param, reqTemplate);
683 } catch (Exception e) {
684 log.error("Error building the XML request: ", e);
686 HttpResponse r = new HttpResponse();
687 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
688 r.message = e.getMessage();
689 return setResponseStatus(ctx, r);
692 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
693 return setResponseStatus(ctx, r);
697 public ConfigStatus activate(String key, SvcLogicContext ctx) {
698 return ConfigStatus.SUCCESS;
702 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
703 return ConfigStatus.SUCCESS;
706 private String escapeMySql(String input) {
711 input = input.replace("\\", "\\\\");
712 input = input.replace("\'", "\\'");
717 private String readFile(String fileName) {
718 InputStream is = getClass().getResourceAsStream(fileName);
719 InputStreamReader isr = new InputStreamReader(is);
720 BufferedReader in = new BufferedReader(isr);
721 StringBuilder ss = new StringBuilder();
723 String s = in.readLine();
725 ss.append(s).append('\n');
728 } catch (IOException e) {
729 System.out.println("Error reading " + fileName + ": " + e.getMessage());
730 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
734 } catch (Exception e) {
735 log.warn("Could not close BufferedReader", e);
739 } catch (Exception e) {
740 log.warn("Could not close InputStreamReader", e);
744 } catch (Exception e) {
745 log.warn("Could not close InputStream", e);
748 return ss.toString();
751 private String buildXmlRequest(Map<String, String> param, String template) {
752 StringBuilder ss = new StringBuilder();
754 while (i < template.length()) {
755 int i1 = template.indexOf("${", i);
757 ss.append(template.substring(i));
761 int i2 = template.indexOf('}', i1 + 2);
763 throw new RuntimeException("Template error: Matching } not found");
766 String var1 = template.substring(i1 + 2, i2);
767 String value1 = param.get(var1);
768 if (value1 == null || value1.trim().length() == 0) {
769 // delete the whole element (line)
770 int i3 = template.lastIndexOf('\n', i1);
774 int i4 = template.indexOf('\n', i1);
776 i4 = template.length();
780 ss.append(template.substring(i, i3));
784 ss.append(template.substring(i, i1)).append(value1);
789 return ss.toString();
792 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
793 log.info("Building XML started");
794 long t1 = System.currentTimeMillis();
796 template = expandRepeats(ctx, template, 1);
798 Map<String, String> mm = new HashMap<>();
799 for (String s : ctx.getAttributeKeySet()) {
800 mm.put(s, ctx.getAttribute(s));
802 mm.put("operation", operation);
804 StringBuilder ss = new StringBuilder();
806 while (i < template.length()) {
807 int i1 = template.indexOf("${", i);
809 ss.append(template.substring(i));
813 int i2 = template.indexOf('}', i1 + 2);
815 throw new RuntimeException("Template error: Matching } not found");
818 String var1 = template.substring(i1 + 2, i2);
819 String value1 = XmlUtil.getXml(mm, var1);
820 if (value1 == null || value1.trim().length() == 0) {
821 // delete the whole element (line)
822 int i3 = template.lastIndexOf('\n', i1);
826 int i4 = template.indexOf('\n', i1);
828 i4 = template.length();
832 ss.append(template.substring(i, i3));
836 ss.append(template.substring(i, i1)).append(value1);
841 long t2 = System.currentTimeMillis();
842 log.info("Building XML completed. Time: " + (t2 - t1));
844 return ss.toString();
847 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
848 StringBuilder newTemplate = new StringBuilder();
850 while (k < template.length()) {
851 int i1 = template.indexOf("${repeat:", k);
853 newTemplate.append(template.substring(k));
857 int i2 = template.indexOf(':', i1 + 9);
859 throw new RuntimeException(
860 "Template error: Context variable name followed by : is required after repeat");
863 // Find the closing }, store in i3
867 while (nn > 0 && i < template.length()) {
868 i3 = template.indexOf('}', i);
870 throw new RuntimeException("Template error: Matching } not found");
872 int i32 = template.indexOf('{', i);
873 if (i32 >= 0 && i32 < i3) {
882 String var1 = template.substring(i1 + 9, i2);
883 String value1 = ctx.getAttribute(var1);
884 log.info(" " + var1 + ": " + value1);
887 n = Integer.parseInt(value1);
888 } catch (Exception e) {
892 newTemplate.append(template.substring(k, i1));
894 String rpt = template.substring(i2 + 1, i3);
896 for (int ii = 0; ii < n; ii++) {
897 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
898 newTemplate.append(ss);
905 return newTemplate.toString();
908 return expandRepeats(ctx, newTemplate.toString(), level + 1);
911 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
913 Client client = getClient();
914 client.setConnectTimeout(5000);
915 WebResource webResource = client.resource(url);
917 log.info("SENDING...............");
918 log.info(xmlRequest);
920 String authString = user + ":" + password;
921 byte[] authEncBytes = Base64.encode(authString);
922 String authStringEnc = new String(authEncBytes);
923 authString = "Basic " + authStringEnc;
925 ClientResponse response = getClientResponse(webResource, authString, xmlRequest);
927 int code = response.getStatus();
928 String message = null;
930 log.info("RESPONSE...............");
931 log.info("HTTP response code: " + code);
932 log.info("HTTP response message: " + message);
935 HttpResponse r = new HttpResponse();
940 } catch (Exception e) {
941 log.error("Error sending the request: ", e);
943 HttpResponse r = new HttpResponse();
944 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
945 r.message = e.getMessage();
950 private static class HttpResponse {
954 public String message;
957 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
958 ctx.setAttribute("error-code", String.valueOf(r.code));
959 ctx.setAttribute("error-message", r.message);
961 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
964 private String getStringBetweenQuotes(String string) {
965 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
966 DebugLog.printAriDebug(fnName, "string=" + string);
967 String retString = null;
968 int start = string.indexOf("\"");
969 int end = string.lastIndexOf("\"");
970 retString = string.substring(start + 1, end);
971 DebugLog.printAriDebug(fnName, "retString=" + retString);
975 public static String _readFile(String fileName) {
976 StringBuffer strBuff = new StringBuffer();
978 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
979 while ((line = in.readLine()) != null) {
980 strBuff.append(line + "\n");
982 } catch (IOException e) {
983 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
985 return (strBuff.toString());
988 private String trimResponse(String response) {
989 log.debug("runningConfig before trimResponse : " + response);
990 StringTokenizer line = new StringTokenizer(response, "\n");
991 StringBuffer sb = new StringBuffer();
992 String runningConfig = "" ;
993 boolean captureText = false;
994 while (line.hasMoreTokens()) {
995 String token = line.nextToken();
996 if (token.indexOf("<configuration xmlns=") != -1) {
998 }else if(token.indexOf("<data>") != -1) {
999 log.debug("token-line:with in Data: "+token);
1004 if(token.indexOf("</data>") != -1) {
1005 log.debug("token-line:with in </data>"+token);
1006 captureText = false;
1009 sb.append(token + "\n");
1011 if (token.indexOf("</configuration>") != -1) {
1012 captureText = false;
1015 runningConfig = sb.toString();
1017 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1018 return runningConfig;
1021 public static void main(String args[]) throws Exception {
1022 Properties props = null;
1023 System.out.println("*************************Hello*****************************");
1024 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1025 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
1026 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
1027 String key = "GetCliRunningConfig";
1028 Map<String, String> parameters = new HashMap();
1029 parameters.put("Host_ip_address", "000.00.000.00");
1030 parameters.put("User_name", "root");
1031 parameters.put("Password", "!bootstrap");
1032 parameters.put("Port_number", "22");
1033 parameters.put("Get_config_template", Get_config_template);
1035 SvcLogicContext ctx = null;
1036 System.out.println("*************************TRACE 1*****************************");
1037 cca.configure(key, parameters, ctx);
1040 protected SshJcraftWrapper getSshJcraftWrapper() {
1041 return new SshJcraftWrapper();
1044 protected Client getClient() {
1045 return Client.create();
1048 protected ClientResponse getClientResponse(WebResource webResource, String authString, String xmlRequest) {
1049 return webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
1050 ClientResponse.class, xmlRequest);