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 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 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(1000l * 180);
216 DebugLog.printRTAriDebug(fnName, "Woke up....");
217 } catch (java.lang.InterruptedException ee) {
218 boolean ignore = true;
219 Thread.currentThread().interrupt();
222 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
223 log.debug(fnName + " Command is for put: data is null");
225 } else // Must be a get
227 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
228 DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
229 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
230 DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
231 ctx.setAttribute("fileContents", response);
232 log.debug("SCP: Closing the SFTP connection");
234 sshJcraftWrapper = null;
235 return (setResponseStatus(ctx, r));
236 } catch (IOException e) {
237 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
238 log.debug(fnName + " : Caught a IOException e=" + e);
239 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
240 r.message = e.getMessage();
241 sshJcraftWrapper = null;
242 return (setResponseStatus(ctx, r));
245 if (key.equals("cli")) {
246 String loginId = parameters.get("loginId");
247 String host = parameters.get("host");
248 String password = parameters.get("password");
249 password = EncryptionTool.getInstance().decrypt(password);
250 String cliCommand = parameters.get("cli");
251 String portNumber = parameters.get("portNumber");
252 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
254 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
255 " portNumber=" + portNumber);
256 DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
257 " portNumber=" + portNumber);
258 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
260 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
261 String response = sshJcraftWrapper.send("sdc", ":");
262 DebugLog.printAriDebug(fnName, "Sending 1");
263 response = sshJcraftWrapper.send("1", ":");
264 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
265 response = sshJcraftWrapper.send("1", "#");
266 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
267 response = sshJcraftWrapper.send("paging-options disable", "#");
268 DebugLog.printAriDebug(fnName, "Sending show config");
269 response = sshJcraftWrapper.send("show config", "#");
271 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
272 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
273 ctx.setAttribute("cliOutput", response);
274 sshJcraftWrapper.closeConnection();
276 sshJcraftWrapper = null;
277 return (setResponseStatus(ctx, r));
278 } catch (IOException e) {
279 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
280 log.debug(fnName + " : Caught a IOException e=" + e);
281 sshJcraftWrapper.closeConnection();
282 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
283 r.message = e.getMessage();
284 sshJcraftWrapper = null;
285 DebugLog.printAriDebug(fnName, "Returning error message");
286 return (setResponseStatus(ctx, r));
289 if (key.equals("escapeSql")) {
290 String data = parameters.get("artifactContents");
291 log.debug("ConfigComponentAdaptor.configure - escapeSql");
292 data = escapeMySql(data);
293 ctx.setAttribute("escapedData", data);
294 return (setResponseStatus(ctx, r));
296 if (key.equals("GetCliRunningConfig")) {
297 DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
298 log.debug("key was: GetCliRunningConfig: ");
299 String User_name = parameters.get("User_name");
300 String Host_ip_address = parameters.get("Host_ip_address");
301 String Password = parameters.get("Password");
302 Password = EncryptionTool.getInstance().decrypt(Password);
303 String Port_number = parameters.get("Port_number");
304 String Get_config_template = parameters.get("Get_config_template");
305 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
306 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
307 DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
309 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
310 " Host_ip_address=" + Host_ip_address + " Port_number="
312 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
313 " User_name=" + User_name + " Port_number=" + Port_number);
314 StringBuffer sb = new StringBuffer();
315 String response = "";
316 String CliResponse = "";
317 boolean showConfigFlag = false;
318 sshJcraftWrapper.connect(Host_ip_address,
323 Integer.parseInt(Port_number));
324 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
325 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
326 String command = null;
328 while (st.hasMoreTokens()) {
329 String line = st.nextToken();
330 DebugLog.printAriDebug(fnName, "line=" + line);
331 if (line.indexOf("Request:") != -1) {
332 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
333 command = getStringBetweenQuotes(line);
334 DebugLog.printAriDebug(fnName, "Sending command=" + command);
335 sshJcraftWrapper.send(command);
336 DebugLog.printAriDebug(fnName, "command has been sent");
337 if (line.indexOf("show config") != -1) {
338 showConfigFlag = true;
339 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
340 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
343 if (line.indexOf("Response: Ends_With") != -1) {
344 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
345 String delemeter = getStringBetweenQuotes(line);
346 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
347 //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806
348 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter,
349 DEFAULT_TIMEOUT_GETRUNNING_CLI, command);
350 response += tmpResponse;
351 if (showConfigFlag) {
352 showConfigFlag = false;
353 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
354 // Strip off the last line which is the command prompt from the VNF device.
355 while (st2.hasMoreTokens()) {
356 String line2 = st2.nextToken();
357 if (line2.indexOf("#") == -1) {
358 CliResponse += line2 + "\n";
364 } catch (NoSuchElementException e) {
365 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
367 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
368 ctx.setAttribute("cliOutput", CliResponse);
369 sshJcraftWrapper.closeConnection();
371 sshJcraftWrapper = null;
372 return (setResponseStatus(ctx, r));
373 } catch (IOException e) {
374 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
375 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
376 sshJcraftWrapper.closeConnection();
377 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
378 r.message = e.getMessage();
379 sshJcraftWrapper = null;
380 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
381 return (setResponseStatus(ctx, r));
384 if (key.equals("xml-download")) {
385 log(fnName, "key was: xml-download");
386 String User_name = parameters.get("User_name");
387 String Host_ip_address = parameters.get("Host_ip_address");
388 String Password = parameters.get("Password");
389 Password = EncryptionTool.getInstance().decrypt(Password);
390 String Port_number = parameters.get("Port_number");
391 String Contents = parameters.get("Contents");
392 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>";
393 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 ]]>]]>";
394 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 ]]>]]>";
397 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
398 + " Port_number=" + Port_number);
399 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
401 sshJcraftWrapper.connect(Host_ip_address,
406 Integer.parseInt(Port_number),
408 String NetconfHelloCmd = netconfHelloCmd;
409 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
410 log(fnName, "Sending the hello command");
411 sshJcraftWrapper.send(NetconfHelloCmd);
412 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
413 log(fnName, "Sending xmlCmd cmd");
414 String xmlCmd = Contents;
415 String messageId = "1";
416 messageId = "\"" + messageId + "\"";
417 String loadConfigurationString =
418 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
420 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
421 + xmlCmd + "</config> </edit-config> </rpc>";
422 loadConfigurationString = loadConfigurationString + "]]>]]>";
423 sshJcraftWrapper.send(loadConfigurationString);
424 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
425 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
426 if (response.indexOf("rpc-error") != -1) {
427 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
428 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
429 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
430 r.message = response;
432 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
433 sshJcraftWrapper.send(commitCmd);
434 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
435 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
436 if (response.indexOf("rpc-error") != -1) {
437 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
438 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
439 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
440 r.message = response;
442 DebugLog.printAriDebug(fnName, ":Looks like a success");
443 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
447 sshJcraftWrapper.send(terminateConnectionCmd);
448 sshJcraftWrapper.closeConnection();
449 sshJcraftWrapper = null;
450 return (setResponseStatus(ctx, r));
451 } catch (Exception e) {
452 log(fnName, "Caught an Exception, e=" + e);
453 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
454 sshJcraftWrapper.closeConnection();
455 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
456 r.message = e.getMessage();
457 sshJcraftWrapper = null;
458 log(fnName, "Returning error message");
459 return (setResponseStatus(ctx, r));
462 if (key.equals("xml-getrunningconfig")) {
463 log(fnName, "key was: : xml-getrunningconfig");
464 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";
465 String Host_ip_address = parameters.get("Host_ip_address");
466 String User_name = parameters.get("User_name");
467 String Password = parameters.get("Password");
468 Password = EncryptionTool.getInstance().decrypt(Password);
469 String Port_number = parameters.get("Port_number");
470 String Protocol = parameters.get("Protocol");
471 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>";
472 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 ]]>]]>";
474 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
475 + " Port_number=" + Port_number);
476 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
478 String NetconfHelloCmd = netconfHelloCmd;
479 sshJcraftWrapper.connect(Host_ip_address,
484 Integer.parseInt(Port_number),
486 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
487 log(fnName, ":Sending the hello command");
488 sshJcraftWrapper.send(NetconfHelloCmd);
489 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
490 log(fnName, "Sending get running config command");
491 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
492 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
493 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
494 response = trimResponse(response);
495 ctx.setAttribute("xmlRunningConfigOutput", response);
496 sshJcraftWrapper.send(terminateConnectionCmd);
497 sshJcraftWrapper.closeConnection();
499 sshJcraftWrapper = null;
500 return (setResponseStatus(ctx, r));
501 } catch (Exception e) {
502 log(fnName, "Caught an Exception, e=" + e);
503 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
504 sshJcraftWrapper.closeConnection();
505 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
506 r.message = e.getMessage();
507 sshJcraftWrapper = null;
508 log(fnName, "Returning error message");
509 return (setResponseStatus(ctx, r));
512 if (key.equals("DownloadCliConfig")) {
513 DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
514 log.debug("key was: DownloadCliConfig: ");
515 String User_name = parameters.get("User_name");
516 String Host_ip_address = parameters.get("Host_ip_address");
517 String Password = parameters.get("Password");
518 Password = EncryptionTool.getInstance().decrypt(Password);
519 String Port_number = parameters.get("Port_number");
520 String Download_config_template = parameters.get("Download_config_template");
521 String Config_contents = parameters.get("Config_contents");
522 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
523 SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
524 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
525 DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
526 int timeout = 4 * 60 * 1000;
528 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
529 " Host_ip_address=" + Host_ip_address + " Port_number="
531 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
532 " User_name=" + User_name + " Port_number=" + Port_number);
533 StringBuffer sb = new StringBuffer();
534 String response = "";
535 String CliResponse = "";
536 sshJcraftWrapper.connect(Host_ip_address,
541 Integer.parseInt(Port_number));
542 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
543 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
544 String command = null;
545 String executeConfigContentsDelemeter = null;
547 while (st.hasMoreTokens()) {
548 String line = st.nextToken();
549 DebugLog.printAriDebug(fnName, "line=" + line);
550 if (line.indexOf("Request:") != -1) {
551 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
552 command = getStringBetweenQuotes(line);
553 DebugLog.printAriDebug(fnName, "Sending command=" + command);
554 sshJcraftWrapper.send(command);
555 DebugLog.printAriDebug(fnName, "command has been sent");
556 } else if ((line.indexOf("Response: Ends_With") != -1) && (
557 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
558 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
559 String delemeter = getStringBetweenQuotes(line);
560 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
561 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
562 response += tmpResponse;
563 CliResponse += tmpResponse;
564 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
565 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
566 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
567 DebugLog.printAriDebug(fnName,
568 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
569 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
570 while (st2.hasMoreTokens()) {
571 String cmd = st2.nextToken();
572 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
573 sshJcraftWrapper.send(cmd);
574 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
577 CliResponse += tmpResponse;
581 } catch (NoSuchElementException e) {
582 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
584 sshJcraftWrapper.closeConnection();
585 sshJcraftWrapper = null;
586 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
587 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
588 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
589 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
590 ctx.setAttribute("cliOutput", CliResponse);
592 return (setResponseStatus(ctx, r));
593 } catch (IOException e) {
594 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
595 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
596 sshJcraftWrapper.closeConnection();
597 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
598 r.message = e.getMessage();
599 sshJcraftWrapper = null;
600 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
601 return (setResponseStatus(ctx, r));
605 DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
606 log.error("Unsupported action - " + action);
607 return ConfigStatus.FAILURE;
610 private void log(String fileName, String messg) {
611 DebugLog.printRTAriDebug(fileName, messg);
612 log.debug(fileName + ": " + messg);
615 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
616 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
617 String ndTemplate = readFile(templateName);
618 String nd = buildNetworkData2(ctx, ndTemplate, operation);
620 String reqTemplate = readFile("/config-request.xml");
621 Map<String, String> param = new HashMap<String, String>();
622 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
623 param.put("request-type", requestType);
624 param.put("callback-url", configCallbackUrl);
625 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
626 param.put("action", "GenerateOnly");
628 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
629 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
630 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
631 param.put("network-data", nd);
635 req = buildXmlRequest(param, reqTemplate);
636 } catch (Exception e) {
637 log.error("Error building the XML request: ", e);
639 HttpResponse r = new HttpResponse();
640 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
641 r.message = e.getMessage();
642 return setResponseStatus(ctx, r);
645 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
646 return setResponseStatus(ctx, r);
649 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
650 String reqTemplate = readFile("/config-request.xml");
651 Map<String, String> param = new HashMap<String, String>();
652 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
653 param.put("callback-url", configCallbackUrl);
654 param.put("action", change ? "DownloadChange" : "DownloadBase");
655 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
659 req = buildXmlRequest(param, reqTemplate);
660 } catch (Exception e) {
661 log.error("Error building the XML request: ", e);
663 HttpResponse r = new HttpResponse();
664 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
665 r.message = e.getMessage();
666 return setResponseStatus(ctx, r);
669 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
670 return setResponseStatus(ctx, r);
673 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
674 String reqTemplate = readFile("/audit-request.xml");
675 Map<String, String> param = new HashMap<String, String>();
676 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
677 param.put("callback-url", auditCallbackUrl);
678 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
679 param.put("audit-level", auditLevel);
683 req = buildXmlRequest(param, reqTemplate);
684 } catch (Exception e) {
685 log.error("Error building the XML request: ", e);
687 HttpResponse r = new HttpResponse();
688 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
689 r.message = e.getMessage();
690 return setResponseStatus(ctx, r);
693 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
694 return setResponseStatus(ctx, r);
698 public ConfigStatus activate(String key, SvcLogicContext ctx) {
699 return ConfigStatus.SUCCESS;
703 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
704 return ConfigStatus.SUCCESS;
707 private String escapeMySql(String input) {
712 input = input.replace("\\", "\\\\");
713 input = input.replace("\'", "\\'");
718 private String readFile(String fileName) {
719 InputStream is = getClass().getResourceAsStream(fileName);
720 InputStreamReader isr = new InputStreamReader(is);
721 BufferedReader in = new BufferedReader(isr);
722 StringBuilder ss = new StringBuilder();
724 String s = in.readLine();
726 ss.append(s).append('\n');
729 } catch (IOException e) {
730 System.out.println("Error reading " + fileName + ": " + e.getMessage());
731 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
735 } catch (Exception e) {
736 log.warn("Could not close BufferedReader", e);
740 } catch (Exception e) {
741 log.warn("Could not close InputStreamReader", e);
745 } catch (Exception e) {
746 log.warn("Could not close InputStream", e);
749 return ss.toString();
752 private String buildXmlRequest(Map<String, String> param, String template) {
753 StringBuilder ss = new StringBuilder();
755 while (i < template.length()) {
756 int i1 = template.indexOf("${", i);
758 ss.append(template.substring(i));
762 int i2 = template.indexOf('}', i1 + 2);
764 throw new RuntimeException("Template error: Matching } not found");
767 String var1 = template.substring(i1 + 2, i2);
768 String value1 = param.get(var1);
769 if (value1 == null || value1.trim().length() == 0) {
770 // delete the whole element (line)
771 int i3 = template.lastIndexOf('\n', i1);
775 int i4 = template.indexOf('\n', i1);
777 i4 = template.length();
781 ss.append(template.substring(i, i3));
785 ss.append(template.substring(i, i1)).append(value1);
790 return ss.toString();
793 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
794 log.info("Building XML started");
795 long t1 = System.currentTimeMillis();
797 template = expandRepeats(ctx, template, 1);
799 Map<String, String> mm = new HashMap<>();
800 for (String s : ctx.getAttributeKeySet()) {
801 mm.put(s, ctx.getAttribute(s));
803 mm.put("operation", operation);
805 StringBuilder ss = new StringBuilder();
807 while (i < template.length()) {
808 int i1 = template.indexOf("${", i);
810 ss.append(template.substring(i));
814 int i2 = template.indexOf('}', i1 + 2);
816 throw new RuntimeException("Template error: Matching } not found");
819 String var1 = template.substring(i1 + 2, i2);
820 String value1 = XmlUtil.getXml(mm, var1);
821 if (value1 == null || value1.trim().length() == 0) {
822 // delete the whole element (line)
823 int i3 = template.lastIndexOf('\n', i1);
827 int i4 = template.indexOf('\n', i1);
829 i4 = template.length();
833 ss.append(template.substring(i, i3));
837 ss.append(template.substring(i, i1)).append(value1);
842 long t2 = System.currentTimeMillis();
843 log.info("Building XML completed. Time: " + (t2 - t1));
845 return ss.toString();
848 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
849 StringBuilder newTemplate = new StringBuilder();
851 while (k < template.length()) {
852 int i1 = template.indexOf("${repeat:", k);
854 newTemplate.append(template.substring(k));
858 int i2 = template.indexOf(':', i1 + 9);
860 throw new RuntimeException(
861 "Template error: Context variable name followed by : is required after repeat");
864 // Find the closing }, store in i3
868 while (nn > 0 && i < template.length()) {
869 i3 = template.indexOf('}', i);
871 throw new RuntimeException("Template error: Matching } not found");
873 int i32 = template.indexOf('{', i);
874 if (i32 >= 0 && i32 < i3) {
883 String var1 = template.substring(i1 + 9, i2);
884 String value1 = ctx.getAttribute(var1);
885 log.info(" " + var1 + ": " + value1);
888 n = Integer.parseInt(value1);
889 } catch (Exception e) {
893 newTemplate.append(template.substring(k, i1));
895 String rpt = template.substring(i2 + 1, i3);
897 for (int ii = 0; ii < n; ii++) {
898 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
899 newTemplate.append(ss);
906 return newTemplate.toString();
909 return expandRepeats(ctx, newTemplate.toString(), level + 1);
912 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
914 Client client = getClient();
915 client.setConnectTimeout(5000);
916 WebResource webResource = client.resource(url);
918 log.info("SENDING...............");
919 if (log.isTraceEnabled()) {
920 log.trace(xmlRequest);
923 if(xmlRequest.length() > 255 ) {
924 log.info(xmlRequest.substring(0, 255));
925 log.info("\n...\n" + xmlRequest.length() +
926 " characters in request, turn on TRACE logging to log entire request");
929 log.info(xmlRequest);
932 String authString = user + ":" + password;
933 byte[] authEncBytes = Base64.encode(authString);
934 String authStringEnc = new String(authEncBytes);
935 authString = "Basic " + authStringEnc;
937 ClientResponse response = getClientResponse(webResource, authString, xmlRequest);
939 int code = response.getStatus();
940 String message = null;
942 log.info("RESPONSE...............");
943 log.info("HTTP response code: " + code);
944 log.info("HTTP response message: " + message);
947 HttpResponse r = new HttpResponse();
952 } catch (Exception e) {
953 log.error("Error sending the request: ", e);
955 HttpResponse r = new HttpResponse();
956 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
957 r.message = e.getMessage();
962 private static class HttpResponse {
966 public String message;
969 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
970 ctx.setAttribute("error-code", String.valueOf(r.code));
971 ctx.setAttribute("error-message", r.message);
973 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
976 private String getStringBetweenQuotes(String string) {
977 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
978 DebugLog.printAriDebug(fnName, "string=" + string);
979 String retString = null;
980 int start = string.indexOf("\"");
981 int end = string.lastIndexOf("\"");
982 retString = string.substring(start + 1, end);
983 DebugLog.printAriDebug(fnName, "retString=" + retString);
987 public static String _readFile(String fileName) {
988 StringBuffer strBuff = new StringBuffer();
990 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
991 while ((line = in.readLine()) != null) {
992 strBuff.append(line + "\n");
994 } catch (IOException e) {
995 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
997 return (strBuff.toString());
1000 private String trimResponse(String response) {
1001 log.debug("runningConfig before trimResponse : " + response);
1002 StringTokenizer line = new StringTokenizer(response, "\n");
1003 StringBuffer sb = new StringBuffer();
1004 String runningConfig = "" ;
1005 boolean captureText = false;
1006 while (line.hasMoreTokens()) {
1007 String token = line.nextToken();
1008 if (token.indexOf("<configuration xmlns=") != -1) {
1010 }else if(token.indexOf("<data>") != -1) {
1011 log.debug("token-line:with in Data: "+token);
1016 if(token.indexOf("</data>") != -1) {
1017 log.debug("token-line:with in </data>"+token);
1018 captureText = false;
1021 sb.append(token + "\n");
1023 if (token.indexOf("</configuration>") != -1) {
1024 captureText = false;
1027 runningConfig = sb.toString();
1029 if (log.isTraceEnabled()) {
1030 log.trace("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1033 if (runningConfig.length() > 255) {
1034 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1035 runningConfig.substring(0, 255));
1036 log.info("\n...\n" + runningConfig.length() +
1037 " characters in config, turn on TRACE logging to log entire config");
1040 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " +
1044 log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig);
1045 return runningConfig;
1048 public static void main(String args[]) throws Exception {
1049 Properties props = null;
1050 System.out.println("*************************Hello*****************************");
1051 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1052 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
1053 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
1054 String key = "GetCliRunningConfig";
1055 Map<String, String> parameters = new HashMap();
1056 parameters.put("Host_ip_address", "000.00.000.00");
1057 parameters.put("User_name", "root");
1058 parameters.put("Password", "!bootstrap");
1059 parameters.put("Port_number", "22");
1060 parameters.put("Get_config_template", Get_config_template);
1062 SvcLogicContext ctx = null;
1063 System.out.println("*************************TRACE 1*****************************");
1064 cca.configure(key, parameters, ctx);
1067 protected SshJcraftWrapper getSshJcraftWrapper() {
1068 return new SshJcraftWrapper();
1071 protected Client getClient() {
1072 return Client.create();
1075 protected ClientResponse getClientResponse(WebResource webResource, String authString, String xmlRequest) {
1076 return webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
1077 ClientResponse.class, xmlRequest);