More bug fix and refactoring
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / utils / DRRouteCLI.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
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
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
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====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24 package org.onap.dmaap.datarouter.provisioning.utils;
25
26 import static java.lang.System.exit;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import java.io.File;
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;
39
40 import javax.servlet.http.HttpServletResponse;
41
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;
57
58 /**
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>.
61  *
62  * @author Robert Eby
63  * @version $Id: DRRouteCLI.java,v 1.2 2013/11/05 15:54:16 eby Exp $
64  */
65 public class DRRouteCLI {
66     /**
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:
69      * <pre>
70      * java org.onap.dmaap.datarouter.provisioning.utils.DRRouteCLI [ -s <i>server</i> ] [ <i>command</i> ]
71      * </pre>
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>.
74      *
75      * @param args command line arguments
76      * @throws Exception for any unrecoverable problem
77      */
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")) {
81             server = args[1];
82             String[] str = new String[args.length - 2];
83             if (str.length > 0) {
84                 System.arraycopy(args, 2, str, 0, str.length);
85             }
86             args = str;
87         }
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.");
90             System.exit(1);
91         }
92         DRRouteCLI cli = new DRRouteCLI(server);
93         if (args.length > 0) {
94             boolean bool = cli.runCommand(args);
95             System.exit(bool ? 0 : 1);
96         } else {
97             cli.interactive();
98             System.exit(0);
99         }
100     }
101
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");
106
107     private final String server;
108     private int width = 120;        // screen width (for list)
109     private AbstractHttpClient httpclient;
110
111     /**
112      * Create a DRRouteCLI object connecting to the specified server.
113      *
114      * @param server the server to send command to
115      * @throws Exception generic exception
116      */
117     public DRRouteCLI(String server) throws Exception {
118         this.server = server;
119         this.httpclient = new DefaultHttpClient();
120         AafPropsUtils aafPropsUtils = null;
121
122         Properties provProperties = ProvRunner.getProvProperties();
123         try {
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);
129             exit(1);
130         }
131
132         String truststoreFile = aafPropsUtils.getTruststorePathProperty();
133         String truststorePw = aafPropsUtils.getTruststorePassProperty();
134
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";
140             }
141             truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH;
142         }
143         File file = new File(truststoreFile);
144         if (file.exists()) {
145             FileInputStream instream = new FileInputStream(file);
146             try {
147                 trustStore.load(instream, truststorePw.toCharArray());
148             } catch (Exception x) {
149                 intlogger.error("Problem reading truststore: " + x.getMessage(), x);
150                 throw x;
151             } finally {
152                 try {
153                     instream.close();
154                 } catch (Exception e) {
155                     intlogger.error("Ignore error closing input stream: " + e.getMessage(), e);
156                 }
157             }
158         }
159
160         SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
161         Scheme sch = new Scheme("https", 443, socketFactory);
162         httpclient.getConnectionManager().getSchemeRegistry().register(sch);
163     }
164
165     private void interactive() throws IOException {
166         LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in));
167         while (true) {
168             System.out.print(PROMPT);
169             String line = in.readLine();
170             if (line == null) {
171                 return;
172             }
173             line = line.trim();
174             if (line.equalsIgnoreCase("exit")) {    // "exit" may only be used in interactive mode
175                 return;
176             }
177             if (line.equalsIgnoreCase("quit")) {   // "quit" may only be used in interactive mode
178                 return;
179             }
180             String[] args = line.split("[ \t]+");
181             if (args.length > 0) {
182                 runCommand(args);
183             }
184         }
185     }
186
187     /**
188      * Run the command specified by the arguments.
189      *
190      * @param args The command line arguments.
191      * @return true if the command was valid and succeeded
192      */
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);
199                 }
200                 if (args[1].startsWith("eg") && args.length == 4) {
201                     return addEgress(args);
202                 }
203                 if (args[1].startsWith("ne") && args.length == 5) {
204                     return addRoute(args);
205                 }
206             }
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);
215                 }
216                 if (args[1].startsWith("in") && args.length == 3) {
217                     return delIngress(args);
218                 }
219                 if (args[1].startsWith("eg") && args.length == 3) {
220                     return delEgress(args);
221                 }
222                 if (args[1].startsWith("ne") && args.length == 4) {
223                     return delRoute(args);
224                 }
225             }
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")) {
232             return list(args);
233         } else if (cmd.startsWith("wid") && args.length > 1) {
234             width = Integer.parseInt(args[1]);
235             return true;
236         } else if (cmd.startsWith("?") || cmd.startsWith("hel") || cmd.startsWith("usa")) {
237             usage();
238         } else if (cmd.startsWith("#")) {
239             // comment -- ignore
240         } else {
241             System.err.println("Command should be one of add, del, list, exit, quit");
242         }
243         return false;
244     }
245
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");
258     }
259
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];
264         }
265         return doPost(url);
266     }
267
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]);
270         return doPost(url);
271     }
272
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]);
275         return doPost(url);
276     }
277
278     private boolean delIngress(String[] args) {
279         String url;
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);
283         } else {
284             url = String.format("https://%s/internal/route/ingress/%s", server, args[2]);
285         }
286         return doDelete(url);
287     }
288
289     private boolean delEgress(String[] args) {
290         String url = String.format("https://%s/internal/route/egress/%s", server, args[2]);
291         return doDelete(url);
292     }
293
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);
297     }
298
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")) {
304             // Display the IRT
305             JSONArray irt = jo.optJSONArray("ingress");
306             int cw1 = 6;
307             int cw2 = 6;
308             int cw3 = 6;
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());
318             }
319
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("")) {
331                     user = "-";
332                 }
333                 if (subnet.equals("")) {
334                     subnet = "-";
335                 }
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)) {
344                         sb.append("\n");
345                         sol = sb.length();
346                         sb.append(ext(" ", nblank));
347                     }
348                     sb.append(nd);
349                     if ((j + 1) < nodes.length()) {
350                         sb.append(", ");
351                     }
352                 }
353                 sb.append("\n");
354             }
355         }
356         if (tbl.startsWith("al") || tbl.startsWith("eg")) {
357             // Display the ERT
358             JSONObject ert = jo.optJSONObject("egress");
359             String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert);
360             if (subs == null) {
361                 subs = new String[0];
362             }
363             Arrays.sort(subs);
364             int cw1 = 5;
365             for (int i = 0; i < subs.length; i++) {
366                 cw1 = Math.max(cw1, subs[i].length());
367             }
368
369             if (sb.length() > 0) {
370                 sb.append("\n");
371             }
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));
378                 }
379
380             }
381         }
382         if (tbl.startsWith("al") || tbl.startsWith("ne")) {
383             // Display the NRT
384             JSONArray nrt = jo.optJSONArray("routing");
385             int cw1 = 4;
386             int cw2 = 4;
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());
393             }
394
395             if (sb.length() > 0) {
396                 sb.append("\n");
397             }
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));
406             }
407         }
408         System.out.print(sb.toString());
409         return true;
410     }
411
412     private String ext(String str, int num) {
413         if (str == null) {
414             str = "-";
415         }
416         while (str.length() < num) {
417             str += " ";
418         }
419         return str;
420     }
421
422     private boolean doDelete(String url) {
423         boolean rv = false;
424         HttpDelete meth = new HttpDelete(url);
425         try {
426             HttpResponse response = httpclient.execute(meth);
427             HttpEntity entity = response.getEntity();
428             StatusLine sl = response.getStatusLine();
429             rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
430             if (rv) {
431                 System.out.println("Routing entry deleted.");
432                 EntityUtils.consume(entity);
433             } else {
434                 printErrorText(entity);
435             }
436         } catch (Exception e) {
437             intlogger.error("PROV0006 doDelete: " + e.getMessage(), e);
438         } finally {
439             meth.releaseConnection();
440         }
441         return rv;
442     }
443
444     private JSONObject doGet(String url) {
445         JSONObject rv = new JSONObject();
446         HttpGet meth = new HttpGet(url);
447         try {
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()));
453             } else {
454                 printErrorText(entity);
455             }
456         } catch (Exception e) {
457             intlogger.error("PROV0005 doGet: " + e.getMessage(), e);
458         } finally {
459             meth.releaseConnection();
460         }
461         return rv;
462     }
463
464     private boolean doPost(String url) {
465         boolean rv = false;
466         HttpPost meth = new HttpPost(url);
467         try {
468             HttpResponse response = httpclient.execute(meth);
469             HttpEntity entity = response.getEntity();
470             StatusLine sl = response.getStatusLine();
471             rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
472             if (rv) {
473                 System.out.println("Routing entry added.");
474                 EntityUtils.consume(entity);
475             } else {
476                 printErrorText(entity);
477             }
478         } catch (Exception e) {
479             intlogger.error("PROV0009 doPost: " + e.getMessage(), e);
480         } finally {
481             meth.releaseConnection();
482         }
483         return rv;
484     }
485
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];
491         int num;
492         while ((num = is.read(bite)) > 0) {
493             sb.append(new String(bite, 0, num));
494         }
495         is.close();
496         int ix = sb.indexOf("<pre>");
497         if (ix > 0) {
498             sb.delete(0, ix + 5);
499         }
500         ix = sb.indexOf("</pre>");
501         if (ix > 0) {
502             sb.delete(ix, sb.length());
503         }
504         System.err.println(sb.toString());
505     }
506 }