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 jakarta.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;
111 @SuppressWarnings("deprecation")
113 * Create a DRRouteCLI object connecting to the specified server.
115 * @param server the server to send command to
116 * @throws Exception generic exception
118 public DRRouteCLI(String server) throws Exception {
119 this.server = server;
120 this.httpclient = new DefaultHttpClient();
121 ProvTlsManager provTlsManager = null;
123 Properties provProperties = ProvRunner.getProvProperties();
125 provTlsManager = new ProvTlsManager(provProperties, false);
126 } catch (Exception e) {
127 intlogger.error("NODE0314 Failed to load TLS config. Exiting", e);
131 String truststoreFile = provTlsManager.getTrustStoreFile();
132 String truststorePw = provTlsManager.getTrustStorePassword();
134 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
135 if (truststoreFile == null || truststoreFile.equals("")) {
136 String jhome = System.getenv("JAVA_HOME");
137 if (jhome == null || jhome.equals("")) {
138 jhome = "/opt/java/jdk/jdk180";
140 truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH;
142 File file = new File(truststoreFile);
144 FileInputStream instream = new FileInputStream(file);
146 trustStore.load(instream, truststorePw.toCharArray());
147 } catch (Exception x) {
148 intlogger.error("Problem reading truststore: " + x.getMessage(), x);
153 } catch (Exception e) {
154 intlogger.error("Ignore error closing input stream: " + e.getMessage(), e);
159 SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
160 Scheme sch = new Scheme("https", 443, socketFactory);
161 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
164 private void interactive() throws IOException {
165 LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in));
167 System.out.print(PROMPT);
168 String line = in.readLine();
173 if (line.equalsIgnoreCase("exit")) { // "exit" may only be used in interactive mode
176 if (line.equalsIgnoreCase("quit")) { // "quit" may only be used in interactive mode
179 String[] args = line.split("[ \t]+");
180 if (args.length > 0) {
187 * Run the command specified by the arguments.
189 * @param args The command line arguments.
190 * @return true if the command was valid and succeeded
192 boolean runCommand(String[] args) {
193 String cmd = args[0].trim().toLowerCase();
194 if (cmd.equals("add")) {
195 if (args.length > 2) {
196 if (args[1].startsWith("in") && args.length >= 6) {
197 return addIngress(args);
199 if (args[1].startsWith("eg") && args.length == 4) {
200 return addEgress(args);
202 if (args[1].startsWith("ne") && args.length == 5) {
203 return addRoute(args);
206 System.err.println("Add command should be one of:");
207 System.err.println(" add in[gress] feedid user subnet nodepatt [ seq ]");
208 System.err.println(" add eg[ress] subid node");
209 System.err.println(" add ne[twork] fromnode tonode vianode");
210 } else if (cmd.startsWith("del")) {
211 if (args.length > 2) {
212 if (args[1].startsWith("in") && args.length == 5) {
213 return delIngress(args);
215 if (args[1].startsWith("in") && args.length == 3) {
216 return delIngress(args);
218 if (args[1].startsWith("eg") && args.length == 3) {
219 return delEgress(args);
221 if (args[1].startsWith("ne") && args.length == 4) {
222 return delRoute(args);
225 System.err.println("Delete command should be one of:");
226 System.err.println(" del in[gress] feedid user subnet");
227 System.err.println(" del in[gress] seq");
228 System.err.println(" del eg[ress] subid");
229 System.err.println(" del ne[twork] fromnode tonode");
230 } else if (cmd.startsWith("lis")) {
232 } else if (cmd.startsWith("wid") && args.length > 1) {
233 width = Integer.parseInt(args[1]);
235 } else if (cmd.startsWith("?") || cmd.startsWith("hel") || cmd.startsWith("usa")) {
237 } else if (cmd.startsWith("#")) {
240 System.err.println("Command should be one of add, del, list, exit, quit");
245 private void usage() {
246 System.out.println("Enter one of the following commands:");
247 System.out.println(" add in[gress] feedid user subnet nodepatt [ seq ]");
248 System.out.println(" add eg[ress] subid node");
249 System.out.println(" add ne[twork] fromnode tonode vianode");
250 System.out.println(" del in[gress] feedid user subnet");
251 System.out.println(" del in[gress] seq");
252 System.out.println(" del eg[ress] subid");
253 System.out.println(" del ne[twork] fromnode tonode");
254 System.out.println(" list [ all | ingress | egress | network ]");
255 System.out.println(" exit");
256 System.out.println(" quit");
259 private boolean addIngress(String[] args) {
260 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]);
261 if (args.length > 6) {
262 url += "&seq=" + args[6];
267 private boolean addEgress(String[] args) {
268 String url = String.format("https://%s/internal/route/egress/?sub=%s&node=%s", server, args[2], args[3]);
272 private boolean addRoute(String[] args) {
273 String url = String.format("https://%s/internal/route/network/?from=%s&to=%s&via=%s", server, args[2], args[3], args[4]);
277 private boolean delIngress(String[] args) {
279 if (args.length == 5) {
280 String subnet = args[4].replaceAll("/", "!"); // replace the / with a !
281 url = String.format("https://%s/internal/route/ingress/%s/%s/%s", server, args[2], args[3], subnet);
283 url = String.format("https://%s/internal/route/ingress/%s", server, args[2]);
285 return doDelete(url);
288 private boolean delEgress(String[] args) {
289 String url = String.format("https://%s/internal/route/egress/%s", server, args[2]);
290 return doDelete(url);
293 private boolean delRoute(String[] args) {
294 String url = String.format("https://%s/internal/route/network/%s/%s", server, args[2], args[3]);
295 return doDelete(url);
298 private boolean list(String[] args) {
299 String tbl = (args.length == 1) ? "all" : args[1].toLowerCase();
300 JSONObject jo = doGet("https://" + server + "/internal/route/"); // Returns all 3 tables
301 StringBuilder sb = new StringBuilder();
302 if (tbl.startsWith("al") || tbl.startsWith("in")) {
304 JSONArray irt = jo.optJSONArray("ingress");
308 int cw4 = 6; // determine column widths for first 4 cols
309 for (int i = 0; irt != null && i < irt.length(); i++) {
310 JSONObject jsonObject = irt.getJSONObject(i);
311 cw1 = Math.max(cw1, ("" + jsonObject.getInt("seq")).length());
312 cw2 = Math.max(cw2, ("" + jsonObject.getInt("feedid")).length());
313 String str = jsonObject.optString("user");
314 cw3 = Math.max(cw3, (str == null) ? 1 : str.length());
315 str = jsonObject.optString("subnet");
316 cw4 = Math.max(cw4, (str == null) ? 1 : str.length());
319 int nblank = cw1 + cw2 + cw3 + cw4 + 8;
320 sb.append("Ingress Routing Table\n");
321 sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1),
322 ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4)));
323 for (int i = 0; irt != null && i < irt.length(); i++) {
324 JSONObject jsonObject = irt.getJSONObject(i);
325 String seq = "" + jsonObject.getInt("seq");
326 String feedid = "" + jsonObject.getInt("feedid");
327 String user = jsonObject.optString("user");
328 String subnet = jsonObject.optString("subnet");
329 if (user.equals("")) {
332 if (subnet.equals("")) {
335 JSONArray nodes = jsonObject.getJSONArray("node");
336 int sol = sb.length();
337 sb.append(String.format("%s %s %s %s ", ext(seq, cw1),
338 ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4)));
339 for (int j = 0; j < nodes.length(); j++) {
340 String nd = nodes.getString(j);
341 int cursor = sb.length() - sol;
342 if (j > 0 && (cursor + nd.length() > width)) {
345 sb.append(ext(" ", nblank));
348 if ((j + 1) < nodes.length()) {
355 if (tbl.startsWith("al") || tbl.startsWith("eg")) {
357 JSONObject ert = jo.optJSONObject("egress");
358 String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert);
360 subs = new String[0];
364 for (int i = 0; i < subs.length; i++) {
365 cw1 = Math.max(cw1, subs[i].length());
368 if (sb.length() > 0) {
371 sb.append("Egress Routing Table\n");
372 sb.append(String.format("%s Node\n", ext("SubID", cw1)));
373 for (int i = 0; i < subs.length; i++) {
374 if (ert != null && ert.length() != 0 ) {
375 String node = ert.getString(subs[i]);
376 sb.append(String.format("%s %s\n", ext(subs[i], cw1), node));
381 if (tbl.startsWith("al") || tbl.startsWith("ne")) {
383 JSONArray nrt = jo.optJSONArray("routing");
386 for (int i = 0; nrt != null && i < nrt.length(); i++) {
387 JSONObject jsonObject = nrt.getJSONObject(i);
388 String from = jsonObject.getString("from");
389 String to = jsonObject.getString("to");
390 cw1 = Math.max(cw1, from.length());
391 cw2 = Math.max(cw2, to.length());
394 if (sb.length() > 0) {
397 sb.append("Network Routing Table\n");
398 sb.append(String.format("%s %s Via\n", ext("From", cw1), ext("To", cw2)));
399 for (int i = 0; nrt != null && i < nrt.length(); i++) {
400 JSONObject jsonObject = nrt.getJSONObject(i);
401 String from = jsonObject.getString("from");
402 String to = jsonObject.getString("to");
403 String via = jsonObject.getString("via");
404 sb.append(String.format("%s %s %s\n", ext(from, cw1), ext(to, cw2), via));
407 System.out.print(sb.toString());
411 private String ext(String str, int num) {
415 while (str.length() < num) {
421 private boolean doDelete(String url) {
423 HttpDelete meth = new HttpDelete(url);
425 HttpResponse response = httpclient.execute(meth);
426 HttpEntity entity = response.getEntity();
427 StatusLine sl = response.getStatusLine();
428 rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
430 System.out.println("Routing entry deleted.");
431 EntityUtils.consume(entity);
433 printErrorText(entity);
435 } catch (Exception e) {
436 intlogger.error("PROV0006 doDelete: " + e.getMessage(), e);
438 meth.releaseConnection();
443 private JSONObject doGet(String url) {
444 JSONObject rv = new JSONObject();
445 HttpGet meth = new HttpGet(url);
447 HttpResponse response = httpclient.execute(meth);
448 HttpEntity entity = response.getEntity();
449 StatusLine sl = response.getStatusLine();
450 if (sl.getStatusCode() == HttpServletResponse.SC_OK) {
451 rv = new JSONObject(new JSONTokener(entity.getContent()));
453 printErrorText(entity);
455 } catch (Exception e) {
456 intlogger.error("PROV0005 doGet: " + e.getMessage(), e);
458 meth.releaseConnection();
463 private boolean doPost(String url) {
465 HttpPost meth = new HttpPost(url);
467 HttpResponse response = httpclient.execute(meth);
468 HttpEntity entity = response.getEntity();
469 StatusLine sl = response.getStatusLine();
470 rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
472 System.out.println("Routing entry added.");
473 EntityUtils.consume(entity);
475 printErrorText(entity);
477 } catch (Exception e) {
478 intlogger.error("PROV0009 doPost: " + e.getMessage(), e);
480 meth.releaseConnection();
485 private void printErrorText(HttpEntity entity) throws IOException {
486 // Look for and print only the part of the output between <pre>...</pre>
487 InputStream is = entity.getContent();
488 StringBuilder sb = new StringBuilder();
489 byte[] bite = new byte[512];
491 while ((num = is.read(bite)) > 0) {
492 sb.append(new String(bite, 0, num));
495 int ix = sb.indexOf("<pre>");
497 sb.delete(0, ix + 5);
499 ix = sb.indexOf("</pre>");
501 sb.delete(ix, sb.length());
503 System.err.println(sb.toString());