update link to upper-constraints.txt
[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 jakarta.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     @SuppressWarnings("deprecation")
112     /**
113      * Create a DRRouteCLI object connecting to the specified server.
114      *
115      * @param server the server to send command to
116      * @throws Exception generic exception
117      */
118     public DRRouteCLI(String server) throws Exception {
119         this.server = server;
120         this.httpclient = new DefaultHttpClient();
121         ProvTlsManager provTlsManager = null;
122
123         Properties provProperties = ProvRunner.getProvProperties();
124         try {
125             provTlsManager = new ProvTlsManager(provProperties, false);
126         } catch (Exception e) {
127             intlogger.error("NODE0314 Failed to load TLS config. Exiting", e);
128             exit(1);
129         }
130
131         String truststoreFile = provTlsManager.getTrustStoreFile();
132         String truststorePw = provTlsManager.getTrustStorePassword();
133
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";
139             }
140             truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH;
141         }
142         File file = new File(truststoreFile);
143         if (file.exists()) {
144             FileInputStream instream = new FileInputStream(file);
145             try {
146                 trustStore.load(instream, truststorePw.toCharArray());
147             } catch (Exception x) {
148                 intlogger.error("Problem reading truststore: " + x.getMessage(), x);
149                 throw x;
150             } finally {
151                 try {
152                     instream.close();
153                 } catch (Exception e) {
154                     intlogger.error("Ignore error closing input stream: " + e.getMessage(), e);
155                 }
156             }
157         }
158
159         SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
160         Scheme sch = new Scheme("https", 443, socketFactory);
161         httpclient.getConnectionManager().getSchemeRegistry().register(sch);
162     }
163
164     private void interactive() throws IOException {
165         LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in));
166         while (true) {
167             System.out.print(PROMPT);
168             String line = in.readLine();
169             if (line == null) {
170                 return;
171             }
172             line = line.trim();
173             if (line.equalsIgnoreCase("exit")) {    // "exit" may only be used in interactive mode
174                 return;
175             }
176             if (line.equalsIgnoreCase("quit")) {   // "quit" may only be used in interactive mode
177                 return;
178             }
179             String[] args = line.split("[ \t]+");
180             if (args.length > 0) {
181                 runCommand(args);
182             }
183         }
184     }
185
186     /**
187      * Run the command specified by the arguments.
188      *
189      * @param args The command line arguments.
190      * @return true if the command was valid and succeeded
191      */
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);
198                 }
199                 if (args[1].startsWith("eg") && args.length == 4) {
200                     return addEgress(args);
201                 }
202                 if (args[1].startsWith("ne") && args.length == 5) {
203                     return addRoute(args);
204                 }
205             }
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);
214                 }
215                 if (args[1].startsWith("in") && args.length == 3) {
216                     return delIngress(args);
217                 }
218                 if (args[1].startsWith("eg") && args.length == 3) {
219                     return delEgress(args);
220                 }
221                 if (args[1].startsWith("ne") && args.length == 4) {
222                     return delRoute(args);
223                 }
224             }
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")) {
231             return list(args);
232         } else if (cmd.startsWith("wid") && args.length > 1) {
233             width = Integer.parseInt(args[1]);
234             return true;
235         } else if (cmd.startsWith("?") || cmd.startsWith("hel") || cmd.startsWith("usa")) {
236             usage();
237         } else if (cmd.startsWith("#")) {
238             // comment -- ignore
239         } else {
240             System.err.println("Command should be one of add, del, list, exit, quit");
241         }
242         return false;
243     }
244
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");
257     }
258
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];
263         }
264         return doPost(url);
265     }
266
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]);
269         return doPost(url);
270     }
271
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]);
274         return doPost(url);
275     }
276
277     private boolean delIngress(String[] args) {
278         String url;
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);
282         } else {
283             url = String.format("https://%s/internal/route/ingress/%s", server, args[2]);
284         }
285         return doDelete(url);
286     }
287
288     private boolean delEgress(String[] args) {
289         String url = String.format("https://%s/internal/route/egress/%s", server, args[2]);
290         return doDelete(url);
291     }
292
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);
296     }
297
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")) {
303             // Display the IRT
304             JSONArray irt = jo.optJSONArray("ingress");
305             int cw1 = 6;
306             int cw2 = 6;
307             int cw3 = 6;
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());
317             }
318
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("")) {
330                     user = "-";
331                 }
332                 if (subnet.equals("")) {
333                     subnet = "-";
334                 }
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)) {
343                         sb.append("\n");
344                         sol = sb.length();
345                         sb.append(ext(" ", nblank));
346                     }
347                     sb.append(nd);
348                     if ((j + 1) < nodes.length()) {
349                         sb.append(", ");
350                     }
351                 }
352                 sb.append("\n");
353             }
354         }
355         if (tbl.startsWith("al") || tbl.startsWith("eg")) {
356             // Display the ERT
357             JSONObject ert = jo.optJSONObject("egress");
358             String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert);
359             if (subs == null) {
360                 subs = new String[0];
361             }
362             Arrays.sort(subs);
363             int cw1 = 5;
364             for (int i = 0; i < subs.length; i++) {
365                 cw1 = Math.max(cw1, subs[i].length());
366             }
367
368             if (sb.length() > 0) {
369                 sb.append("\n");
370             }
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));
377                 }
378
379             }
380         }
381         if (tbl.startsWith("al") || tbl.startsWith("ne")) {
382             // Display the NRT
383             JSONArray nrt = jo.optJSONArray("routing");
384             int cw1 = 4;
385             int cw2 = 4;
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());
392             }
393
394             if (sb.length() > 0) {
395                 sb.append("\n");
396             }
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));
405             }
406         }
407         System.out.print(sb.toString());
408         return true;
409     }
410
411     private String ext(String str, int num) {
412         if (str == null) {
413             str = "-";
414         }
415         while (str.length() < num) {
416             str += " ";
417         }
418         return str;
419     }
420
421     private boolean doDelete(String url) {
422         boolean rv = false;
423         HttpDelete meth = new HttpDelete(url);
424         try {
425             HttpResponse response = httpclient.execute(meth);
426             HttpEntity entity = response.getEntity();
427             StatusLine sl = response.getStatusLine();
428             rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
429             if (rv) {
430                 System.out.println("Routing entry deleted.");
431                 EntityUtils.consume(entity);
432             } else {
433                 printErrorText(entity);
434             }
435         } catch (Exception e) {
436             intlogger.error("PROV0006 doDelete: " + e.getMessage(), e);
437         } finally {
438             meth.releaseConnection();
439         }
440         return rv;
441     }
442
443     private JSONObject doGet(String url) {
444         JSONObject rv = new JSONObject();
445         HttpGet meth = new HttpGet(url);
446         try {
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()));
452             } else {
453                 printErrorText(entity);
454             }
455         } catch (Exception e) {
456             intlogger.error("PROV0005 doGet: " + e.getMessage(), e);
457         } finally {
458             meth.releaseConnection();
459         }
460         return rv;
461     }
462
463     private boolean doPost(String url) {
464         boolean rv = false;
465         HttpPost meth = new HttpPost(url);
466         try {
467             HttpResponse response = httpclient.execute(meth);
468             HttpEntity entity = response.getEntity();
469             StatusLine sl = response.getStatusLine();
470             rv = (sl.getStatusCode() == HttpServletResponse.SC_OK);
471             if (rv) {
472                 System.out.println("Routing entry added.");
473                 EntityUtils.consume(entity);
474             } else {
475                 printErrorText(entity);
476             }
477         } catch (Exception e) {
478             intlogger.error("PROV0009 doPost: " + e.getMessage(), e);
479         } finally {
480             meth.releaseConnection();
481         }
482         return rv;
483     }
484
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];
490         int num;
491         while ((num = is.read(bite)) > 0) {
492             sb.append(new String(bite, 0, num));
493         }
494         is.close();
495         int ix = sb.indexOf("<pre>");
496         if (ix > 0) {
497             sb.delete(0, ix + 5);
498         }
499         ix = sb.indexOf("</pre>");
500         if (ix > 0) {
501             sb.delete(ix, sb.length());
502         }
503         System.err.println(sb.toString());
504     }
505 }