2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * =============================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.appc.ccadaptor;
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import com.sun.jersey.api.client.Client;
27 import com.sun.jersey.api.client.ClientResponse;
28 import com.sun.jersey.api.client.WebResource;
29 import com.sun.jersey.core.util.Base64;
30 import java.io.BufferedReader;
31 import java.io.ByteArrayInputStream;
32 import java.io.FileReader;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.io.UncheckedIOException;
37 import java.net.HttpURLConnection;
38 import java.util.HashMap;
40 import java.util.Map.Entry;
41 import java.util.NoSuchElementException;
42 import java.util.Properties;
43 import java.util.StringTokenizer;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
47 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
49 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
50 DebugLog debugLog = new DebugLog();
51 private String configUrl = null;
52 private String configUser = null;
53 private String configPassword = null;
54 private String auditUrl = null;
55 private String auditUser = null;
56 private String auditPassword = null;
57 private String configCallbackUrl = null;
58 private String auditCallbackUrl = null;
59 private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ;
61 public ConfigComponentAdaptor(Properties props) {
63 configUrl = props.getProperty("configComponent.url", "");
64 configUser = props.getProperty("configComponent.user", "");
65 configPassword = props.getProperty("configComponent.passwd", "");
66 auditUrl = props.getProperty("auditComponent.url", "");
67 auditUser = props.getProperty("auditComponent.user", "");
68 auditPassword = props.getProperty("auditComponent.passwd", "");
69 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
70 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
78 configCallbackUrl = "";
79 auditCallbackUrl = "";
84 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
85 String fnName = "ConfigComponentAdaptor.configure";
86 HttpResponse r = new HttpResponse();
88 log.debug("ConfigComponentAdaptor.configure - key = " + key);
89 debugLog.printRTAriDebug(fnName, "key = " + key);
90 log.debug("Parameters:");
91 debugLog.printRTAriDebug(fnName, "Parameters:");
92 for (String parmName : parameters.keySet()) {
93 log.debug(" " + parmName + " = " + parameters.get(parmName));
94 debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
97 String parmval = parameters.get("config-component-configUrl");
98 if ((parmval != null) && (parmval.length() > 0)) {
99 log.debug("Overwriting URL with " + parmval);
103 parmval = parameters.get("config-component-configPassword");
104 if ((parmval != null) && (parmval.length() > 0)) {
105 log.debug("Overwriting configPassword with " + parmval);
106 configPassword = parmval;
109 parmval = parameters.get("config-component-configUser");
110 if ((parmval != null) && (parmval.length() > 0)) {
111 log.debug("Overwriting configUser id with " + parmval);
112 configUser = parmval;
115 String action = parameters.get("action");
117 String chg = ctx.getAttribute(
118 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
119 if (chg != null && "prepare".equalsIgnoreCase(action)) {
120 return prepare(ctx, "CHANGE", "change");
122 if (chg != null && "activate".equalsIgnoreCase(action)) {
123 return activate(ctx, true);
126 String scale = ctx.getAttribute(
127 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
128 if (scale != null && "prepare".equalsIgnoreCase(action)) {
129 return prepare(ctx, "CHANGE", "scale");
131 if (scale != null && "activate".equalsIgnoreCase(action)) {
132 return activate(ctx, true);
135 if ("prepare".equalsIgnoreCase(action)) {
136 return prepare(ctx, "BASE", "create");
138 if ("activate".equalsIgnoreCase(action)) {
139 return activate(ctx, false);
142 if ("backup".equalsIgnoreCase(action)) {
143 return prepare(ctx, "BACKUP", "backup");
145 if ("restorebackup".equalsIgnoreCase(action)) {
146 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
148 if ("deletebackup".equalsIgnoreCase(action)) {
149 return prepare(ctx, "DELETEBACKUP", "deletebackup");
151 if ("audit".equalsIgnoreCase(action)) {
152 return audit(ctx, "FULL");
154 if ("getrunningconfig".equalsIgnoreCase(action)) {
155 return audit(ctx, "RUNNING");
158 if ((key.equals("put")) || (key.equals("get"))) {
159 String loginId = parameters.get("loginId");
160 String host = parameters.get("host");
161 String password = parameters.get("password");
162 password = EncryptionTool.getInstance().decrypt(password);
163 String fullPathFileName = parameters.get("fullPathFileName");
166 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
167 log.debug("SCP: SshJcraftWrapper has been instantiated");
168 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
170 if (key.equals("put")) {
171 data = parameters.get("data");
173 debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
174 InputStream is = new ByteArrayInputStream(data.getBytes());
175 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
176 debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
177 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
179 debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
180 Thread.sleep(1000 * 180);
181 debugLog.printRTAriDebug(fnName, "Woke up....");
182 } catch (java.lang.InterruptedException ee) {
183 boolean ignore = true;
186 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
187 log.debug(fnName + " Command is for put: data is null");
189 } else // Must be a get
191 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
192 debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
193 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
194 debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
195 ctx.setAttribute("fileContents", response);
196 log.debug("SCP: Closing the SFTP connection");
198 sshJcraftWrapper = null;
199 return (setResponseStatus(ctx, r));
200 } catch (IOException e) {
201 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
202 log.debug(fnName + " : Caught a IOException e=" + e);
203 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
204 r.message = e.getMessage();
205 sshJcraftWrapper = null;
206 return (setResponseStatus(ctx, r));
209 if (key.equals("cli")) {
210 String loginId = parameters.get("loginId");
211 String host = parameters.get("host");
212 String password = parameters.get("password");
213 password = EncryptionTool.getInstance().decrypt(password);
214 String cliCommand = parameters.get("cli");
215 String portNumber = parameters.get("portNumber");
216 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
218 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
219 " portNumber=" + portNumber);
220 debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
221 " portNumber=" + portNumber);
222 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
224 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
225 String response = sshJcraftWrapper.send("sdc", ":");
226 DebugLog.printAriDebug(fnName, "Sending 1");
227 response = sshJcraftWrapper.send("1", ":");
228 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
229 response = sshJcraftWrapper.send("1", "#");
230 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
231 response = sshJcraftWrapper.send("paging-options disable", "#");
232 DebugLog.printAriDebug(fnName, "Sending show config");
233 response = sshJcraftWrapper.send("show config", "#");
235 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
236 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
237 ctx.setAttribute("cliOutput", response);
238 sshJcraftWrapper.closeConnection();
240 sshJcraftWrapper = null;
241 return (setResponseStatus(ctx, r));
242 } catch (IOException e) {
243 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
244 log.debug(fnName + " : Caught a IOException e=" + e);
245 sshJcraftWrapper.closeConnection();
246 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
247 r.message = e.getMessage();
248 sshJcraftWrapper = null;
249 DebugLog.printAriDebug(fnName, "Returning error message");
250 return (setResponseStatus(ctx, r));
253 if (key.equals("escapeSql")) {
254 String data = parameters.get("artifactContents");
255 log.debug("ConfigComponentAdaptor.configure - escapeSql");
256 data = escapeMySql(data);
257 ctx.setAttribute("escapedData", data);
258 return (setResponseStatus(ctx, r));
260 if (key.equals("GetCliRunningConfig")) {
261 debugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
262 log.debug("key was: GetCliRunningConfig: ");
263 String User_name = parameters.get("User_name");
264 String Host_ip_address = parameters.get("Host_ip_address");
265 String Password = parameters.get("Password");
266 Password = EncryptionTool.getInstance().decrypt(Password);
267 String Port_number = parameters.get("Port_number");
268 String Get_config_template = parameters.get("Get_config_template");
269 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
270 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
271 debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
273 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
274 " Host_ip_address=" + Host_ip_address + " Port_number="
276 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
277 " User_name=" + User_name + " Port_number=" + Port_number);
278 StringBuffer sb = new StringBuffer();
279 String response = "";
280 String CliResponse = "";
281 boolean showConfigFlag = false;
282 sshJcraftWrapper.connect(Host_ip_address,
287 Integer.parseInt(Port_number));
288 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
289 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
290 String command = null;
292 while (st.hasMoreTokens()) {
293 String line = st.nextToken();
294 DebugLog.printAriDebug(fnName, "line=" + line);
295 if (line.indexOf("Request:") != -1) {
296 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
297 command = getStringBetweenQuotes(line);
298 DebugLog.printAriDebug(fnName, "Sending command=" + command);
299 sshJcraftWrapper.send(command);
300 DebugLog.printAriDebug(fnName, "command has been sent");
301 if (line.indexOf("show config") != -1) {
302 showConfigFlag = true;
303 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
304 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
307 if (line.indexOf("Response: Ends_With") != -1) {
308 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
309 String delemeter = getStringBetweenQuotes(line);
310 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
311 //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806
312 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter,
313 DEFAULT_TIMEOUT_GETRUNNING_CLI, command);
314 response += tmpResponse;
315 if (showConfigFlag) {
316 showConfigFlag = false;
317 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
318 // Strip off the last line which is the command prompt from the VNF device.
319 while (st2.hasMoreTokens()) {
320 String line2 = st2.nextToken();
321 if (line2.indexOf("#") == -1) {
322 CliResponse += line2 + "\n";
328 } catch (NoSuchElementException e) {
329 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
331 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
332 ctx.setAttribute("cliOutput", CliResponse);
333 sshJcraftWrapper.closeConnection();
335 sshJcraftWrapper = null;
336 return (setResponseStatus(ctx, r));
337 } catch (IOException e) {
338 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
339 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
340 sshJcraftWrapper.closeConnection();
341 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
342 r.message = e.getMessage();
343 sshJcraftWrapper = null;
344 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
345 return (setResponseStatus(ctx, r));
348 if (key.equals("xml-download")) {
349 log(fnName, "key was: xml-download");
350 String User_name = parameters.get("User_name");
351 String Host_ip_address = parameters.get("Host_ip_address");
352 String Password = parameters.get("Password");
353 Password = EncryptionTool.getInstance().decrypt(Password);
354 String Port_number = parameters.get("Port_number");
355 String Contents = parameters.get("Contents");
356 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>";
357 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 ]]>]]>";
358 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 ]]>]]>";
361 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
362 + " Port_number=" + Port_number);
363 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
365 sshJcraftWrapper.connect(Host_ip_address,
370 Integer.parseInt(Port_number),
372 String NetconfHelloCmd = netconfHelloCmd;
373 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
374 log(fnName, "Sending the hello command");
375 sshJcraftWrapper.send(NetconfHelloCmd);
376 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
377 log(fnName, "Sending xmlCmd cmd");
378 String xmlCmd = Contents;
379 String messageId = "1";
380 messageId = "\"" + messageId + "\"";
381 String loadConfigurationString =
382 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
384 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
385 + xmlCmd + "</config> </edit-config> </rpc>";
386 loadConfigurationString = loadConfigurationString + "]]>]]>";
387 sshJcraftWrapper.send(loadConfigurationString);
388 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
389 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
390 if (response.indexOf("rpc-error") != -1) {
391 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
392 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
393 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
394 r.message = response;
396 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
397 sshJcraftWrapper.send(commitCmd);
398 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
399 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
400 if (response.indexOf("rpc-error") != -1) {
401 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
402 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
403 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
404 r.message = response;
406 DebugLog.printAriDebug(fnName, ":Looks like a success");
407 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
411 sshJcraftWrapper.send(terminateConnectionCmd);
412 sshJcraftWrapper.closeConnection();
413 sshJcraftWrapper = null;
414 return (setResponseStatus(ctx, r));
415 } catch (Exception e) {
416 log(fnName, "Caught an Exception, e=" + e);
417 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
418 sshJcraftWrapper.closeConnection();
419 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
420 r.message = e.getMessage();
421 sshJcraftWrapper = null;
422 log(fnName, "Returning error message");
423 return (setResponseStatus(ctx, r));
426 if (key.equals("xml-getrunningconfig")) {
427 log(fnName, "key was: : xml-getrunningconfig");
428 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";
429 String Host_ip_address = parameters.get("Host_ip_address");
430 String User_name = parameters.get("User_name");
431 String Password = parameters.get("Password");
432 Password = EncryptionTool.getInstance().decrypt(Password);
433 String Port_number = parameters.get("Port_number");
434 String Protocol = parameters.get("Protocol");
435 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>";
436 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 ]]>]]>";
438 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
439 + " Port_number=" + Port_number);
440 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
442 String NetconfHelloCmd = netconfHelloCmd;
443 sshJcraftWrapper.connect(Host_ip_address,
448 Integer.parseInt(Port_number),
450 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
451 log(fnName, ":Sending the hello command");
452 sshJcraftWrapper.send(NetconfHelloCmd);
453 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
454 log(fnName, "Sending get running config command");
455 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
456 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
457 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
458 response = trimResponse(response);
459 ctx.setAttribute("xmlRunningConfigOutput", response);
460 sshJcraftWrapper.send(terminateConnectionCmd);
461 sshJcraftWrapper.closeConnection();
463 sshJcraftWrapper = null;
464 return (setResponseStatus(ctx, r));
465 } catch (Exception e) {
466 log(fnName, "Caught an Exception, e=" + e);
467 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
468 sshJcraftWrapper.closeConnection();
469 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
470 r.message = e.getMessage();
471 sshJcraftWrapper = null;
472 log(fnName, "Returning error message");
473 return (setResponseStatus(ctx, r));
476 if (key.equals("DownloadCliConfig")) {
477 debugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
478 log.debug("key was: DownloadCliConfig: ");
479 String User_name = parameters.get("User_name");
480 String Host_ip_address = parameters.get("Host_ip_address");
481 String Password = parameters.get("Password");
482 Password = EncryptionTool.getInstance().decrypt(Password);
483 String Port_number = parameters.get("Port_number");
484 String Download_config_template = parameters.get("Download_config_template");
485 String Config_contents = parameters.get("Config_contents");
486 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
487 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
488 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
489 debugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
490 int timeout = 4 * 60 * 1000;
492 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
493 " Host_ip_address=" + Host_ip_address + " Port_number="
495 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
496 " User_name=" + User_name + " Port_number=" + Port_number);
497 StringBuffer sb = new StringBuffer();
498 String response = "";
499 String CliResponse = "";
500 sshJcraftWrapper.connect(Host_ip_address,
505 Integer.parseInt(Port_number));
506 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
507 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
508 String command = null;
509 String executeConfigContentsDelemeter = null;
511 while (st.hasMoreTokens()) {
512 String line = st.nextToken();
513 DebugLog.printAriDebug(fnName, "line=" + line);
514 if (line.indexOf("Request:") != -1) {
515 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
516 command = getStringBetweenQuotes(line);
517 DebugLog.printAriDebug(fnName, "Sending command=" + command);
518 sshJcraftWrapper.send(command);
519 DebugLog.printAriDebug(fnName, "command has been sent");
520 } else if ((line.indexOf("Response: Ends_With") != -1) && (
521 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
522 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
523 String delemeter = getStringBetweenQuotes(line);
524 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
525 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
526 response += tmpResponse;
527 CliResponse += tmpResponse;
528 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
529 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
530 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
531 DebugLog.printAriDebug(fnName,
532 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
533 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
534 while (st2.hasMoreTokens()) {
535 String cmd = st2.nextToken();
536 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
537 sshJcraftWrapper.send(cmd);
538 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
541 CliResponse += tmpResponse;
545 } catch (NoSuchElementException e) {
546 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
548 sshJcraftWrapper.closeConnection();
549 sshJcraftWrapper = null;
550 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
551 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
552 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
553 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
554 ctx.setAttribute("cliOutput", CliResponse);
556 return (setResponseStatus(ctx, r));
557 } catch (IOException e) {
558 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
559 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
560 sshJcraftWrapper.closeConnection();
561 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
562 r.message = e.getMessage();
563 sshJcraftWrapper = null;
564 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
565 return (setResponseStatus(ctx, r));
569 debugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
570 log.error("Unsupported action - " + action);
571 return ConfigStatus.FAILURE;
574 private void log(String fileName, String messg) {
575 debugLog.printRTAriDebug(fileName, messg);
576 log.debug(fileName + ": " + messg);
579 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
580 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
581 String ndTemplate = readFile(templateName);
582 String nd = buildNetworkData2(ctx, ndTemplate, operation);
584 String reqTemplate = readFile("/config-request.xml");
585 Map<String, String> param = new HashMap<String, String>();
586 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
587 param.put("request-type", requestType);
588 param.put("callback-url", configCallbackUrl);
589 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
590 param.put("action", "GenerateOnly");
592 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
593 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
594 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
595 param.put("network-data", nd);
599 req = buildXmlRequest(param, reqTemplate);
600 } catch (Exception e) {
601 log.error("Error building the XML request: ", e);
603 HttpResponse r = new HttpResponse();
604 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
605 r.message = e.getMessage();
606 return setResponseStatus(ctx, r);
609 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
610 return setResponseStatus(ctx, r);
613 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
614 String reqTemplate = readFile("/config-request.xml");
615 Map<String, String> param = new HashMap<String, String>();
616 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
617 param.put("callback-url", configCallbackUrl);
618 param.put("action", change ? "DownloadChange" : "DownloadBase");
619 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
623 req = buildXmlRequest(param, reqTemplate);
624 } catch (Exception e) {
625 log.error("Error building the XML request: ", e);
627 HttpResponse r = new HttpResponse();
628 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
629 r.message = e.getMessage();
630 return setResponseStatus(ctx, r);
633 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
634 return setResponseStatus(ctx, r);
637 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
638 String reqTemplate = readFile("/audit-request.xml");
639 Map<String, String> param = new HashMap<String, String>();
640 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
641 param.put("callback-url", auditCallbackUrl);
642 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
643 param.put("audit-level", auditLevel);
647 req = buildXmlRequest(param, reqTemplate);
648 } catch (Exception e) {
649 log.error("Error building the XML request: ", e);
651 HttpResponse r = new HttpResponse();
652 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
653 r.message = e.getMessage();
654 return setResponseStatus(ctx, r);
657 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
658 return setResponseStatus(ctx, r);
662 public ConfigStatus activate(String key, SvcLogicContext ctx) {
663 return ConfigStatus.SUCCESS;
667 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
668 return ConfigStatus.SUCCESS;
671 private String escapeMySql(String input) {
676 input = input.replace("\\", "\\\\");
677 input = input.replace("\'", "\\'");
682 private String readFile(String fileName) {
683 InputStream is = getClass().getResourceAsStream(fileName);
684 InputStreamReader isr = new InputStreamReader(is);
685 BufferedReader in = new BufferedReader(isr);
686 StringBuilder ss = new StringBuilder();
688 String s = in.readLine();
690 ss.append(s).append('\n');
693 } catch (IOException e) {
694 System.out.println("Error reading " + fileName + ": " + e.getMessage());
695 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
699 } catch (Exception e) {
700 log.warn("Could not close BufferedReader", e);
704 } catch (Exception e) {
705 log.warn("Could not close InputStreamReader", e);
709 } catch (Exception e) {
710 log.warn("Could not close InputStream", e);
713 return ss.toString();
716 private String buildXmlRequest(Map<String, String> param, String template) {
717 StringBuilder ss = new StringBuilder();
719 while (i < template.length()) {
720 int i1 = template.indexOf("${", i);
722 ss.append(template.substring(i));
726 int i2 = template.indexOf('}', i1 + 2);
728 throw new RuntimeException("Template error: Matching } not found");
731 String var1 = template.substring(i1 + 2, i2);
732 String value1 = param.get(var1);
733 if (value1 == null || value1.trim().length() == 0) {
734 // delete the whole element (line)
735 int i3 = template.lastIndexOf('\n', i1);
739 int i4 = template.indexOf('\n', i1);
741 i4 = template.length();
745 ss.append(template.substring(i, i3));
749 ss.append(template.substring(i, i1)).append(value1);
754 return ss.toString();
757 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
758 log.info("Building XML started");
759 long t1 = System.currentTimeMillis();
761 template = expandRepeats(ctx, template, 1);
763 Map<String, String> mm = new HashMap<>();
764 for (String s : ctx.getAttributeKeySet()) {
765 mm.put(s, ctx.getAttribute(s));
767 mm.put("operation", operation);
769 StringBuilder ss = new StringBuilder();
771 while (i < template.length()) {
772 int i1 = template.indexOf("${", i);
774 ss.append(template.substring(i));
778 int i2 = template.indexOf('}', i1 + 2);
780 throw new RuntimeException("Template error: Matching } not found");
783 String var1 = template.substring(i1 + 2, i2);
784 String value1 = XmlUtil.getXml(mm, var1);
785 if (value1 == null || value1.trim().length() == 0) {
786 // delete the whole element (line)
787 int i3 = template.lastIndexOf('\n', i1);
791 int i4 = template.indexOf('\n', i1);
793 i4 = template.length();
797 ss.append(template.substring(i, i3));
801 ss.append(template.substring(i, i1)).append(value1);
806 long t2 = System.currentTimeMillis();
807 log.info("Building XML completed. Time: " + (t2 - t1));
809 return ss.toString();
812 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
813 StringBuilder newTemplate = new StringBuilder();
815 while (k < template.length()) {
816 int i1 = template.indexOf("${repeat:", k);
818 newTemplate.append(template.substring(k));
822 int i2 = template.indexOf(':', i1 + 9);
824 throw new RuntimeException(
825 "Template error: Context variable name followed by : is required after repeat");
828 // Find the closing }, store in i3
832 while (nn > 0 && i < template.length()) {
833 i3 = template.indexOf('}', i);
835 throw new RuntimeException("Template error: Matching } not found");
837 int i32 = template.indexOf('{', i);
838 if (i32 >= 0 && i32 < i3) {
847 String var1 = template.substring(i1 + 9, i2);
848 String value1 = ctx.getAttribute(var1);
849 log.info(" " + var1 + ": " + value1);
852 n = Integer.parseInt(value1);
853 } catch (Exception e) {
857 newTemplate.append(template.substring(k, i1));
859 String rpt = template.substring(i2 + 1, i3);
861 for (int ii = 0; ii < n; ii++) {
862 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
863 newTemplate.append(ss);
870 return newTemplate.toString();
873 return expandRepeats(ctx, newTemplate.toString(), level + 1);
876 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
878 Client client = Client.create();
879 client.setConnectTimeout(5000);
880 WebResource webResource = client.resource(url);
882 log.info("SENDING...............");
883 log.info(xmlRequest);
885 String authString = user + ":" + password;
886 byte[] authEncBytes = Base64.encode(authString);
887 String authStringEnc = new String(authEncBytes);
888 authString = "Basic " + authStringEnc;
890 ClientResponse response =
891 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
892 ClientResponse.class, xmlRequest);
894 int code = response.getStatus();
895 String message = null;
897 log.info("RESPONSE...............");
898 log.info("HTTP response code: " + code);
899 log.info("HTTP response message: " + message);
902 HttpResponse r = new HttpResponse();
907 } catch (Exception e) {
908 log.error("Error sending the request: ", e);
910 HttpResponse r = new HttpResponse();
911 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
912 r.message = e.getMessage();
917 private static class HttpResponse {
921 public String message;
924 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
925 ctx.setAttribute("error-code", String.valueOf(r.code));
926 ctx.setAttribute("error-message", r.message);
928 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
931 private String getStringBetweenQuotes(String string) {
932 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
933 DebugLog.printAriDebug(fnName, "string=" + string);
934 String retString = null;
935 int start = string.indexOf("\"");
936 int end = string.lastIndexOf("\"");
937 retString = string.substring(start + 1, end);
938 DebugLog.printAriDebug(fnName, "retString=" + retString);
942 public static String _readFile(String fileName) {
943 StringBuffer strBuff = new StringBuffer();
945 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
946 while ((line = in.readLine()) != null) {
947 strBuff.append(line + "\n");
949 } catch (IOException e) {
950 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
952 return (strBuff.toString());
955 private String trimResponse(String response) {
956 log.debug("runningConfig before trimResponse : " + response);
957 StringTokenizer line = new StringTokenizer(response, "\n");
958 StringBuffer sb = new StringBuffer();
959 String runningConfig = "" ;
960 boolean captureText = false;
961 while (line.hasMoreTokens()) {
962 String token = line.nextToken();
963 if (token.indexOf("<configuration xmlns=") != -1) {
965 }else if(token.indexOf("<data>") != -1) {
966 log.debug("token-line:with in Data: "+token);
971 if(token.indexOf("</data>") != -1) {
972 log.debug("token-line:with in </data>"+token);
976 sb.append(token + "\n");
978 if (token.indexOf("</configuration>") != -1) {
982 runningConfig = sb.toString();
984 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
985 return runningConfig;
988 public static void main(String args[]) throws Exception {
989 Properties props = null;
990 System.out.println("*************************Hello*****************************");
991 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
992 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
993 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
994 String key = "GetCliRunningConfig";
995 Map<String, String> parameters = new HashMap();
996 parameters.put("Host_ip_address", "000.00.000.00");
997 parameters.put("User_name", "root");
998 parameters.put("Password", "!bootstrap");
999 parameters.put("Port_number", "22");
1000 parameters.put("Get_config_template", Get_config_template);
1002 SvcLogicContext ctx = null;
1003 System.out.println("*************************TRACE 1*****************************");
1004 cca.configure(key, parameters, ctx);