1 /*******************************************************************************
2 * ============LICENSE_START==================================================
4 * * ===========================================================================
5 * * Copyright © 2017 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.
18 * * ============LICENSE_END====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
24 package org.onap.dmaap.datarouter.provisioning.utils;
26 import static java.lang.System.exit;
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
31 import java.io.FileInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.io.LineNumberReader;
36 import java.security.KeyStore;
37 import java.util.Arrays;
38 import java.util.Properties;
40 import javax.servlet.http.HttpServletResponse;
42 import org.apache.http.HttpEntity;
43 import org.apache.http.HttpResponse;
44 import org.apache.http.StatusLine;
45 import org.apache.http.client.methods.HttpDelete;
46 import org.apache.http.client.methods.HttpGet;
47 import org.apache.http.client.methods.HttpPost;
48 import org.apache.http.conn.scheme.Scheme;
49 import org.apache.http.conn.ssl.SSLSocketFactory;
50 import org.apache.http.impl.client.AbstractHttpClient;
51 import org.apache.http.impl.client.DefaultHttpClient;
52 import org.apache.http.util.EntityUtils;
53 import org.json.JSONArray;
54 import org.json.JSONObject;
55 import org.json.JSONTokener;
56 import org.onap.dmaap.datarouter.provisioning.ProvRunner;
59 * This class provides a Command Line Interface for the routing tables in the DR Release 2.0 DB.
60 * A full description of this command is <a href="http://wiki.proto.research.att.com/doku.php?id=datarouter-route-cli">here</a>.
63 * @version $Id: DRRouteCLI.java,v 1.2 2013/11/05 15:54:16 eby Exp $
65 public class DRRouteCLI {
67 * Invoke the CLI. The CLI can be run with a single command (given as command line arguments),
68 * or in an interactive mode where the user types a sequence of commands to the program. The CLI is invoked via:
70 * java org.onap.dmaap.datarouter.provisioning.utils.DRRouteCLI [ -s <i>server</i> ] [ <i>command</i> ]
72 * A full description of the arguments to this command are
73 * <a href="http://wiki.proto.research.att.com/doku.php?id=datarouter-route-cli">here</a>.
75 * @param args command line arguments
76 * @throws Exception for any unrecoverable problem
78 public static void main(String[] args) throws Exception {
79 String server = System.getenv(ENV_VAR);
80 if (args.length >= 2 && args[0].equals("-s")) {
82 String[] str = new String[args.length - 2];
84 System.arraycopy(args, 2, str, 0, str.length);
88 if (server == null || server.equals("")) {
89 System.err.println("dr-route: you need to specify a server, either via $PROVSRVR or the '-s' option.");
92 DRRouteCLI cli = new DRRouteCLI(server);
93 if (args.length > 0) {
94 boolean bool = cli.runCommand(args);
95 System.exit(bool ? 0 : 1);
102 private static final String ENV_VAR = "PROVSRVR";
103 private static final String PROMPT = "dr-route> ";
104 private static final String DEFAULT_TRUSTSTORE_PATH = /* $JAVA_HOME + */ "/jre/lib/security/cacerts";
105 private static final EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
107 private final String server;
108 private int width = 120; // screen width (for list)
109 private AbstractHttpClient httpclient;
112 * Create a DRRouteCLI object connecting to the specified server.
114 * @param server the server to send command to
115 * @throws Exception generic exception
117 public DRRouteCLI(String server) throws Exception {
118 this.server = server;
119 this.httpclient = new DefaultHttpClient();
120 AafPropsUtils aafPropsUtils = null;
122 Properties provProperties = ProvRunner.getProvProperties();
124 aafPropsUtils = new AafPropsUtils(new File(provProperties.getProperty(
125 "org.onap.dmaap.datarouter.provserver.aafprops.path",
126 "/opt/app/osaaf/local/org.onap.dmaap-dr.props")));
127 } catch (IOException e) {
128 intlogger.error("NODE0314 Failed to load AAF props. Exiting", e);
132 String truststoreFile = aafPropsUtils.getTruststorePathProperty();
133 String truststorePw = aafPropsUtils.getTruststorePassProperty();
135 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
136 if (truststoreFile == null || truststoreFile.equals("")) {
137 String jhome = System.getenv("JAVA_HOME");
138 if (jhome == null || jhome.equals("")) {
139 jhome = "/opt/java/jdk/jdk180";
141 truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH;
143 File file = new File(truststoreFile);
145 FileInputStream instream = new FileInputStream(file);
147 trustStore.load(instream, truststorePw.toCharArray());
148 } catch (Exception x) {
149 intlogger.error("Problem reading truststore: " + x.getMessage(), x);
154 } catch (Exception e) {
155 intlogger.error("Ignore error closing input stream: " + e.getMessage(), e);
160 SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
161 Scheme sch = new Scheme("https", 443, socketFactory);
162 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
165 private void interactive() throws IOException {
166 LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in));
168 System.out.print(PROMPT);
169 String line = in.readLine();
174 if (line.equalsIgnoreCase("exit")) { // "exit" may only be used in interactive mode
177 if (line.equalsIgnoreCase("quit")) { // "quit" may only be used in interactive mode
180 String[] args = line.split("[ \t]+");
181 if (args.length > 0) {
188 * Run the command specified by the arguments.
190 * @param args The command line arguments.
191 * @return true if the command was valid and succeeded
193 boolean runCommand(String[] args) {
194 String cmd = args[0].trim().toLowerCase();
195 if (cmd.equals("add")) {
196 if (args.length > 2) {
197 if (args[1].startsWith("in") && args.length >= 6) {
198 return addIngress(args);
200 if (args[1].startsWith("eg") && args.length == 4) {
201 return addEgress(args);
203 if (args[1].startsWith("ne") && args.length == 5) {
204 return addRoute(args);
207 System.err.println("Add command should be one of:");
208 System.err.println(" add in[gress] feedid user subnet nodepatt [ seq ]");
209 System.err.println(" add eg[ress] subid node");
210 System.err.println(" add ne[twork] fromnode tonode vianode");
211 } else if (cmd.startsWith("del")) {
212 if (args.length > 2) {
213 if (args[1].startsWith("in") && args.length == 5) {
214 return delIngress(args);
216 if (args[1].startsWith("in") && args.length == 3) {
217 return delIngress(args);
219 if (args[1].startsWith("eg") && args.length == 3) {
220 return delEgress(args);
222 if (args[1].startsWith("ne") && args.length == 4) {
223 return delRoute(args);
226 System.err.println("Delete command should be one of:");
227 System.err.println(" del in[gress] feedid user subnet");
228 System.err.println(" del in[gress] seq");
229 System.err.println(" del eg[ress] subid");
230 System.err.println(" del ne[twork] fromnode tonode");
231 } else if (cmd.startsWith("lis")) {
233 } else if (cmd.startsWith("wid") && args.length > 1) {
234 width = Integer.parseInt(args[1]);
236 } else if (cmd.startsWith("?") || cmd.startsWith("hel") || cmd.startsWith("usa")) {
238 } else if (cmd.startsWith("#")) {
241 System.err.println("Command should be one of add, del, list, exit, quit");
246 private void usage() {
247 System.out.println("Enter one of the following commands:");
248 System.out.println(" add in[gress] feedid user subnet nodepatt [ seq ]");
249 System.out.println(" add eg[ress] subid node");
250 System.out.println(" add ne[twork] fromnode tonode vianode");
251 System.out.println(" del in[gress] feedid user subnet");
252 System.out.println(" del in[gress] seq");
253 System.out.println(" del eg[ress] subid");
254 System.out.println(" del ne[twork] fromnode tonode");
255 System.out.println(" list [ all | ingress | egress | network ]");
256 System.out.println(" exit");
257 System.out.println(" quit");
260 private boolean addIngress(String[] args) {
261 String url = String.format("https://%s/internal/route/ingress/?feed=%s&user=%s&subnet=%s&nodepatt=%s", server, args[2], args[3], args[4], args[5]);
262 if (args.length > 6) {
263 url += "&seq=" + args[6];
268 private boolean addEgress(String[] args) {
269 String url = String.format("https://%s/internal/route/egress/?sub=%s&node=%s", server, args[2], args[3]);
273 private boolean addRoute(String[] args) {
274 String url = String.format("https://%s/internal/route/network/?from=%s&to=%s&via=%s", server, args[2], args[3], args[4]);
278 private boolean delIngress(String[] args) {
280 if (args.length == 5) {
281 String subnet = args[4].replaceAll("/", "!"); // replace the / with a !
282 url = String.format("https://%s/internal/route/ingress/%s/%s/%s", server, args[2], args[3], subnet);
284 url = String.format("https://%s/internal/route/ingress/%s", server, args[2]);
286 return doDelete(url);
289 private boolean delEgress(String[] args) {
290 String url = String.format("https://%s/internal/route/egress/%s", server, args[2]);
291 return doDelete(url);
294 private boolean delRoute(String[] args) {
295 String url = String.format("https://%s/internal/route/network/%s/%s", server, args[2], args[3]);
296 return doDelete(url);
299 private boolean list(String[] args) {
300 String tbl = (args.length == 1) ? "all" : args[1].toLowerCase();
301 JSONObject jo = doGet("https://" + server + "/internal/route/"); // Returns all 3 tables
302 StringBuilder sb = new StringBuilder();
303 if (tbl.startsWith("al") || tbl.startsWith("in")) {
305 JSONArray irt = jo.optJSONArray("ingress");
309 int cw4 = 6; // determine column widths for first 4 cols
310 for (int i = 0; irt != null && i < irt.length(); i++) {
311 JSONObject jsonObject = irt.getJSONObject(i);
312 cw1 = Math.max(cw1, ("" + jsonObject.getInt("seq")).length());
313 cw2 = Math.max(cw2, ("" + jsonObject.getInt("feedid")).length());
314 String str = jsonObject.optString("user");
315 cw3 = Math.max(cw3, (str == null) ? 1 : str.length());
316 str = jsonObject.optString("subnet");
317 cw4 = Math.max(cw4, (str == null) ? 1 : str.length());
320 int nblank = cw1 + cw2 + cw3 + cw4 + 8;
321 sb.append("Ingress Routing Table\n");
322 sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1),
323 ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4)));
324 for (int i = 0; irt != null && i < irt.length(); i++) {
325 JSONObject jsonObject = irt.getJSONObject(i);
326 String seq = "" + jsonObject.getInt("seq");
327 String feedid = "" + jsonObject.getInt("feedid");
328 String user = jsonObject.optString("user");
329 String subnet = jsonObject.optString("subnet");
330 if (user.equals("")) {
333 if (subnet.equals("")) {
336 JSONArray nodes = jsonObject.getJSONArray("node");
337 int sol = sb.length();
338 sb.append(String.format("%s %s %s %s ", ext(seq, cw1),
339 ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4)));
340 for (int j = 0; j < nodes.length(); j++) {
341 String nd = nodes.getString(j);
342 int cursor = sb.length() - sol;
343 if (j > 0 && (cursor + nd.length() > width)) {
346 sb.append(ext(" ", nblank));
349 if ((j + 1) < nodes.length()) {
356 if (tbl.startsWith("al") || tbl.startsWith("eg")) {
358 JSONObject ert = jo.optJSONObject("egress");
359 String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert);
361 subs = new String[0];
365 for (int i = 0; i < subs.length; i++) {
366 cw1 = Math.max(cw1, subs[i].length());
369 if (sb.length() > 0) {
372 sb.append("Egress Routing Table\n");
373 sb.append(String.format("%s Node\n", ext("SubID", cw1)));
374 for (int i = 0; i < subs.length; i++) {
375 if (ert != null && ert.length() != 0 ) {
376 String node = ert.getString(subs[i]);
377 sb.append(String.format("%s %s\n", ext(subs[i], cw1), node));
382 if (tbl.startsWith("al") || tbl.startsWith("ne")) {
384 JSONArray nrt = jo.optJSONArray("routing");
387 for (int i = 0; nrt != null && i < nrt.length(); i++) {
388 JSONObject jsonObject = nrt.getJSONObject(i);
389 String from = jsonObject.getString("from");
390 String to = jsonObject.getString("to");
391 cw1 = Math.max(cw1, from.length());
392 cw2 = Math.max(cw2, to.length());
395 if (sb.length() > 0) {
398 sb.append("Network Routing Table\n");
399 sb.append(String.format("%s %s Via\n", ext("From", cw1), ext("To", cw2)));
400 for (int i = 0; nrt != null && i < nrt.length(); i++) {
401 JSONObject jsonObject = nrt.getJSONObject(i);
402 String from = jsonObject.getString("from");
403 String to = jsonObject.getString("to");
404 String via = jsonObject.getString("via");
405 sb.append(String.format("%s %s %s\n", ext(from, cw1), ext(to, cw2), via));
408 System.out.print(sb.toString());
412 private String ext(String str, int num) {
416 while (str.length() < num) {
422 private boolean doDelete(String url) {
424 HttpDelete meth = new HttpDelete(url);
426 HttpResponse response = httpclient.execute(meth);
427 HttpEntity entity = response.getEntity();
428 StatusLine sl = response.getStatusLine();
429 rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
431 System.out.println("Routing entry deleted.");
432 EntityUtils.consume(entity);
434 printErrorText(entity);
436 } catch (Exception e) {
437 intlogger.error("PROV0006 doDelete: " + e.getMessage(), e);
439 meth.releaseConnection();
444 private JSONObject doGet(String url) {
445 JSONObject rv = new JSONObject();
446 HttpGet meth = new HttpGet(url);
448 HttpResponse response = httpclient.execute(meth);
449 HttpEntity entity = response.getEntity();
450 StatusLine sl = response.getStatusLine();
451 if (sl.getStatusCode() == HttpServletResponse.SC_OK) {
452 rv = new JSONObject(new JSONTokener(entity.getContent()));
454 printErrorText(entity);
456 } catch (Exception e) {
457 intlogger.error("PROV0005 doGet: " + e.getMessage(), e);
459 meth.releaseConnection();
464 private boolean doPost(String url) {
466 HttpPost meth = new HttpPost(url);
468 HttpResponse response = httpclient.execute(meth);
469 HttpEntity entity = response.getEntity();
470 StatusLine sl = response.getStatusLine();
471 rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
473 System.out.println("Routing entry added.");
474 EntityUtils.consume(entity);
476 printErrorText(entity);
478 } catch (Exception e) {
479 intlogger.error("PROV0009 doPost: " + e.getMessage(), e);
481 meth.releaseConnection();
486 private void printErrorText(HttpEntity entity) throws IOException {
487 // Look for and print only the part of the output between <pre>...</pre>
488 InputStream is = entity.getContent();
489 StringBuilder sb = new StringBuilder();
490 byte[] bite = new byte[512];
492 while ((num = is.read(bite)) > 0) {
493 sb.append(new String(bite, 0, num));
496 int ix = sb.indexOf("<pre>");
498 sb.delete(0, ix + 5);
500 ix = sb.indexOf("</pre>");
502 sb.delete(ix, sb.length());
504 System.err.println(sb.toString());