From adb2ad2d16e851fbf8dcc71af68949a74463204d Mon Sep 17 00:00:00 2001 From: efiacor Date: Wed, 23 Oct 2019 15:31:43 +0100 Subject: More bug fix and refactoring Signed-off-by: efiacor Change-Id: I4fce4e73faa86573d0c716882bb014b9f83026ee Issue-ID: DMAAP-1284 --- .../dmaap/datarouter/provisioning/ProvRunner.java | 208 +--- .../dmaap/datarouter/provisioning/ProvServer.java | 236 +++++ .../datarouter/provisioning/ProxyServlet.java | 4 - .../datarouter/provisioning/beans/EgressRoute.java | 9 +- .../datarouter/provisioning/beans/Parameters.java | 11 +- .../provisioning/utils/AafPropsUtils.java | 21 +- .../datarouter/provisioning/utils/DRRouteCLI.java | 1011 ++++++++++---------- 7 files changed, 771 insertions(+), 729 deletions(-) create mode 100644 datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvServer.java (limited to 'datarouter-prov/src/main/java') diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvRunner.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvRunner.java index 4078922e..8a0ef448 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvRunner.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvRunner.java @@ -32,37 +32,15 @@ import com.att.eelf.configuration.EELFManager; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.security.Security; -import java.util.EnumSet; import java.util.Properties; import java.util.Timer; -import javax.servlet.DispatcherType; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.Handler; -import org.eclipse.jetty.server.HttpConfiguration; -import org.eclipse.jetty.server.HttpConnectionFactory; -import org.eclipse.jetty.server.NCSARequestLog; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.server.SslConnectionFactory; -import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.server.handler.DefaultHandler; -import org.eclipse.jetty.server.handler.HandlerCollection; -import org.eclipse.jetty.server.handler.RequestLogHandler; -import org.eclipse.jetty.servlet.FilterHolder; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.onap.dmaap.datarouter.provisioning.utils.AafPropsUtils; -import org.onap.dmaap.datarouter.provisioning.utils.DRProvCadiFilter; import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader; import org.onap.dmaap.datarouter.provisioning.utils.Poker; import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils; import org.onap.dmaap.datarouter.provisioning.utils.PurgeLogDirTask; import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask; -import org.onap.dmaap.datarouter.provisioning.utils.ThrottleFilter; /** *

@@ -98,10 +76,7 @@ public class ProvRunner { public static final EELFLogger intlogger = EELFManager.getInstance() .getLogger("org.onap.dmaap.datarouter.provisioning.internal"); - /** - * The one and only {@link Server} instance in this JVM. - */ - private static Server server; + private static Server provServer; private static AafPropsUtils aafPropsUtils; private static Properties provProperties; @@ -109,199 +84,50 @@ public class ProvRunner { * Starts the Data Router Provisioning server. * * @param args not used - * @throws Exception if Jetty has a problem starting */ - public static void main(String[] args) throws Exception { - - intlogger.info("PROV0000 **** Data Router Provisioning Server starting...."); - + public static void main(String[] args) { // Check DB is accessible and contains the expected tables if (!ProvDbUtils.getInstance().initProvDB()) { intlogger.error("Data Router Provisioning database init failure. Exiting."); exit(1); } - - int httpPort = Integer.parseInt( - getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.http.port", "8080")); - final int httpsPort = Integer.parseInt( - getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.https.port", "8443")); - - Security.setProperty("networkaddress.cache.ttl", "4"); - // Server's thread pool - QueuedThreadPool queuedThreadPool = new QueuedThreadPool(); - queuedThreadPool.setMinThreads(10); - queuedThreadPool.setMaxThreads(200); - queuedThreadPool.setDetailedDump(false); - - // The server itself - server = new Server(queuedThreadPool); - server.setStopAtShutdown(true); - server.setStopTimeout(5000); - server.setDumpAfterStart(false); - server.setDumpBeforeStop(false); - - // Request log configuration - NCSARequestLog ncsaRequestLog = new NCSARequestLog(); - ncsaRequestLog.setFilename(getProvProperties() - .getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir") - + "/request.log.yyyy_mm_dd"); - ncsaRequestLog.setFilenameDateFormat("yyyyMMdd"); - ncsaRequestLog.setRetainDays(90); - ncsaRequestLog.setAppend(true); - ncsaRequestLog.setExtended(false); - ncsaRequestLog.setLogCookies(false); - ncsaRequestLog.setLogTimeZone("GMT"); - - RequestLogHandler requestLogHandler = new RequestLogHandler(); - requestLogHandler.setRequestLog(ncsaRequestLog); - server.setRequestLog(ncsaRequestLog); - - // HTTP configuration - HttpConfiguration httpConfiguration = new HttpConfiguration(); - httpConfiguration.setSecureScheme("https"); - httpConfiguration.setSecurePort(httpsPort); - httpConfiguration.setOutputBufferSize(32768); - httpConfiguration.setRequestHeaderSize(8192); - httpConfiguration.setResponseHeaderSize(8192); - httpConfiguration.setSendServerVersion(true); - httpConfiguration.setSendDateHeader(false); - + // Set up AAF properties try { - AafPropsUtils.init(new File(getProvProperties().getProperty( + aafPropsUtils = new AafPropsUtils(new File(getProvProperties().getProperty( "org.onap.dmaap.datarouter.provserver.aafprops.path", "/opt/app/osaaf/local/org.onap.dmaap-dr.props"))); } catch (IOException e) { intlogger.error("NODE0314 Failed to load AAF props. Exiting", e); exit(1); } - aafPropsUtils = AafPropsUtils.getInstance(); - - //HTTP Connector - HandlerCollection handlerCollection; - try (ServerConnector httpServerConnector = - new ServerConnector(server, new HttpConnectionFactory(httpConfiguration))) { - httpServerConnector.setPort(httpPort); - httpServerConnector.setAcceptQueueSize(2); - httpServerConnector.setIdleTimeout(300000); - - // SSL Context - SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStoreType(AafPropsUtils.KEYSTORE_TYPE_PROPERTY); - sslContextFactory.setKeyStorePath(getAafPropsUtils().getKeystorePathProperty()); - sslContextFactory.setKeyStorePassword(getAafPropsUtils().getKeystorePassProperty()); - sslContextFactory.setKeyManagerPassword(getAafPropsUtils().getKeystorePassProperty()); - - String truststorePathProperty = getAafPropsUtils().getTruststorePathProperty(); - if (truststorePathProperty != null && truststorePathProperty.length() > 0) { - intlogger.info("@@ TS -> " + truststorePathProperty); - sslContextFactory.setTrustStoreType(AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY); - sslContextFactory.setTrustStorePath(truststorePathProperty); - sslContextFactory.setTrustStorePassword(getAafPropsUtils().getTruststorePassProperty()); - } else { - sslContextFactory.setTrustStorePath(AafPropsUtils.DEFAULT_TRUSTSTORE); - sslContextFactory.setTrustStorePassword("changeit"); - } - - sslContextFactory.setWantClientAuth(true); - sslContextFactory.setExcludeCipherSuites( - "SSL_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_DSS_WITH_DES_CBC_SHA", - "SSL_RSA_EXPORT_WITH_RC4_40_MD5", - "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" - ); - sslContextFactory.addExcludeProtocols("SSLv3"); - sslContextFactory.setIncludeProtocols(getProvProperties().getProperty( - "org.onap.dmaap.datarouter.provserver.https.include.protocols", - "TLSv1.1|TLSv1.2").trim().split("\\|")); - - intlogger.info("Not supported protocols prov server:-" - + String.join(",", sslContextFactory.getExcludeProtocols())); - intlogger.info("Supported protocols prov server:-" - + String.join(",", sslContextFactory.getIncludeProtocols())); - intlogger.info("Not supported ciphers prov server:-" - + String.join(",", sslContextFactory.getExcludeCipherSuites())); - intlogger.info("Supported ciphers prov server:-" - + String.join(",", sslContextFactory.getIncludeCipherSuites())); - - // HTTPS configuration - HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration); - httpsConfiguration.setRequestHeaderSize(8192); - - // HTTPS connector - try (ServerConnector httpsServerConnector = new ServerConnector(server, - new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), - new HttpConnectionFactory(httpsConfiguration))) { - - httpsServerConnector.setPort(httpsPort); - httpsServerConnector.setIdleTimeout(30000); - httpsServerConnector.setAcceptQueueSize(2); - - // Servlet and Filter configuration - ServletContextHandler servletContextHandler = new ServletContextHandler(0); - servletContextHandler.setContextPath("/"); - servletContextHandler.addServlet(new ServletHolder(new FeedServlet()), "/feed/*"); - servletContextHandler.addServlet(new ServletHolder(new FeedLogServlet()), "/feedlog/*"); - servletContextHandler.addServlet(new ServletHolder(new PublishServlet()), "/publish/*"); - servletContextHandler.addServlet(new ServletHolder(new SubscribeServlet()), "/subscribe/*"); - servletContextHandler.addServlet(new ServletHolder(new StatisticsServlet()), "/statistics/*"); - servletContextHandler.addServlet(new ServletHolder(new SubLogServlet()), "/sublog/*"); - servletContextHandler.addServlet(new ServletHolder(new GroupServlet()), "/group/*"); - servletContextHandler.addServlet(new ServletHolder(new SubscriptionServlet()), "/subs/*"); - servletContextHandler.addServlet(new ServletHolder(new InternalServlet()), "/internal/*"); - servletContextHandler.addServlet(new ServletHolder(new RouteServlet()), "/internal/route/*"); - servletContextHandler.addServlet(new ServletHolder(new DRFeedsServlet()), "/"); - servletContextHandler.addFilter(new FilterHolder(new ThrottleFilter()), - "/publish/*", EnumSet.of(DispatcherType.REQUEST)); - - //CADI Filter activation check - if (Boolean.parseBoolean(getProvProperties().getProperty( - "org.onap.dmaap.datarouter.provserver.cadi.enabled", "false"))) { - servletContextHandler.addFilter(new FilterHolder(new DRProvCadiFilter(true, getAafPropsUtils().getPropAccess())), - "/*", EnumSet.of(DispatcherType.REQUEST)); - intlogger.info("PROV0001 AAF CADI Auth enabled for "); - } - - ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection(); - contextHandlerCollection.addHandler(servletContextHandler); - - // Server's Handler collection - handlerCollection = new HandlerCollection(); - handlerCollection.setHandlers(new Handler[]{contextHandlerCollection, new DefaultHandler()}); - handlerCollection.addHandler(requestLogHandler); - - server.setConnectors(new Connector[]{httpServerConnector, httpsServerConnector}); - } - } - server.setHandler(handlerCollection); - // Daemon to clean up the log directory on a daily basis Timer rolex = new Timer(); rolex.scheduleAtFixedRate(new PurgeLogDirTask(), 0, 86400000L); // run once per day - // Start LogfileLoader - LogfileLoader.getLoader(); - try { - server.start(); - intlogger.info("Prov Server started-" + server.getState()); + // Create and start the Jetty server + provServer = ProvServer.getServerInstance(); + intlogger.info("PROV0000 **** DMaaP Data Router Provisioning Server starting...."); + provServer.start(); + provServer.dumpStdErr(); + provServer.join(); + intlogger.info("PROV0000 **** DMaaP Data Router Provisioning Server started: " + provServer.getState()); } catch (Exception e) { - intlogger.error("Jetty failed to start. Exiting: " + e.getMessage(), e); + intlogger.error( + "PROV0010 **** DMaaP Data Router Provisioning Server failed to start. Exiting: " + e.getMessage(), e); exit(1); } - server.join(); - intlogger.info("PROV0001 **** AT&T Data Router Provisioning Server halted."); + // Start LogfileLoader + LogfileLoader.getLoader(); } /** * Stop the Jetty server. */ - public static void shutdown() { + static void shutdown() { new Thread(() -> { try { - server.stop(); + provServer.stop(); Thread.sleep(5000L); exit(0); } catch (Exception e) { diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvServer.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvServer.java new file mode 100644 index 00000000..c0e6b8d6 --- /dev/null +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProvServer.java @@ -0,0 +1,236 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.datarouter.provisioning; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.security.Security; +import java.util.EnumSet; +import java.util.Properties; +import javax.servlet.DispatcherType; +import javax.servlet.ServletException; +import org.eclipse.jetty.http.HttpVersion; +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.HttpConfiguration; +import org.eclipse.jetty.server.HttpConnectionFactory; +import org.eclipse.jetty.server.NCSARequestLog; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.SslConnectionFactory; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; +import org.eclipse.jetty.server.handler.DefaultHandler; +import org.eclipse.jetty.server.handler.HandlerCollection; +import org.eclipse.jetty.server.handler.RequestLogHandler; +import org.eclipse.jetty.servlet.FilterHolder; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.jetbrains.annotations.NotNull; +import org.onap.dmaap.datarouter.provisioning.utils.AafPropsUtils; +import org.onap.dmaap.datarouter.provisioning.utils.DRProvCadiFilter; +import org.onap.dmaap.datarouter.provisioning.utils.ThrottleFilter; + + +public class ProvServer { + + public static final EELFLogger intlogger = EELFManager.getInstance() + .getLogger("InternalLog"); + + private static Server server; + + private ProvServer() { + } + + static Server getServerInstance() { + if (server == null) { + server = createProvServer(ProvRunner.getProvProperties()); + } + return server; + } + + private static Server createProvServer(Properties provProps) { + final int httpsPort = Integer.parseInt( + provProps.getProperty("org.onap.dmaap.datarouter.provserver.https.port", "8443")); + + Security.setProperty("networkaddress.cache.ttl", "4"); + QueuedThreadPool queuedThreadPool = getQueuedThreadPool(); + + server = new Server(queuedThreadPool); + server.setStopAtShutdown(true); + server.setStopTimeout(5000); + server.setDumpAfterStart(false); + server.setDumpBeforeStop(false); + + NCSARequestLog ncsaRequestLog = getRequestLog(provProps); + RequestLogHandler requestLogHandler = new RequestLogHandler(); + requestLogHandler.setRequestLog(ncsaRequestLog); + + server.setRequestLog(ncsaRequestLog); + + HttpConfiguration httpConfiguration = getHttpConfiguration(httpsPort); + + //HTTP Connector + try (ServerConnector httpServerConnector = new ServerConnector(server, + new HttpConnectionFactory(httpConfiguration))) { + httpServerConnector.setPort(Integer.parseInt(provProps.getProperty( + "org.onap.dmaap.datarouter.provserver.http.port", "8080"))); + httpServerConnector.setAcceptQueueSize(2); + httpServerConnector.setIdleTimeout(30000); + + SslContextFactory sslContextFactory = getSslContextFactory(provProps); + + // HTTPS configuration + HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration); + httpsConfiguration.setRequestHeaderSize(8192); + + // HTTPS connector + try (ServerConnector httpsServerConnector = new ServerConnector(server, + new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), + new HttpConnectionFactory(httpsConfiguration))) { + httpsServerConnector.setPort(httpsPort); + httpsServerConnector.setIdleTimeout(30000); + httpsServerConnector.setAcceptQueueSize(2); + + ServletContextHandler servletContextHandler = getServletContextHandler(provProps); + ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection(); + contextHandlerCollection.addHandler(servletContextHandler); + + // Server's Handler collection + HandlerCollection handlerCollection = new HandlerCollection(); + handlerCollection.setHandlers(new Handler[]{contextHandlerCollection, new DefaultHandler()}); + handlerCollection.addHandler(requestLogHandler); + + server.setConnectors(new Connector[]{httpServerConnector, httpsServerConnector}); + server.setHandler(handlerCollection); + } + } + return server; + } + + @NotNull + private static QueuedThreadPool getQueuedThreadPool() { + // Server's thread pool + QueuedThreadPool queuedThreadPool = new QueuedThreadPool(); + queuedThreadPool.setMinThreads(10); + queuedThreadPool.setMaxThreads(200); + queuedThreadPool.setDetailedDump(false); + return queuedThreadPool; + } + + @NotNull + private static SslContextFactory getSslContextFactory(Properties provProps) { + SslContextFactory sslContextFactory = new SslContextFactory(); + sslContextFactory.setKeyStoreType(AafPropsUtils.KEYSTORE_TYPE_PROPERTY); + sslContextFactory.setKeyStorePath(ProvRunner.getAafPropsUtils().getKeystorePathProperty()); + sslContextFactory.setKeyStorePassword(ProvRunner.getAafPropsUtils().getKeystorePassProperty()); + sslContextFactory.setKeyManagerPassword(ProvRunner.getAafPropsUtils().getKeystorePassProperty()); + + sslContextFactory.setTrustStoreType(AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY); + sslContextFactory.setTrustStorePath(ProvRunner.getAafPropsUtils().getTruststorePathProperty()); + sslContextFactory.setTrustStorePassword(ProvRunner.getAafPropsUtils().getTruststorePassProperty()); + + sslContextFactory.setWantClientAuth(true); + sslContextFactory.setExcludeCipherSuites( + "SSL_RSA_WITH_DES_CBC_SHA", + "SSL_DHE_RSA_WITH_DES_CBC_SHA", + "SSL_DHE_DSS_WITH_DES_CBC_SHA", + "SSL_RSA_EXPORT_WITH_RC4_40_MD5", + "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", + "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", + "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" + ); + sslContextFactory.addExcludeProtocols("SSLv3"); + sslContextFactory.setIncludeProtocols(provProps.getProperty( + "org.onap.dmaap.datarouter.provserver.https.include.protocols", + "TLSv1.1|TLSv1.2").trim().split("\\|")); + + intlogger.info("Unsupported protocols: " + String.join(",", sslContextFactory.getExcludeProtocols())); + intlogger.info("Supported protocols: " + String.join(",", sslContextFactory.getIncludeProtocols())); + intlogger.info("Unsupported ciphers: " + String.join(",", sslContextFactory.getExcludeCipherSuites())); + intlogger.info("Supported ciphers: " + String.join(",", sslContextFactory.getIncludeCipherSuites())); + + return sslContextFactory; + } + + @NotNull + private static NCSARequestLog getRequestLog(Properties provProps) { + NCSARequestLog ncsaRequestLog = new NCSARequestLog(); + ncsaRequestLog.setFilename(provProps.getProperty( + "org.onap.dmaap.datarouter.provserver.accesslog.dir") + "/request.log.yyyy_mm_dd"); + ncsaRequestLog.setFilenameDateFormat("yyyyMMdd"); + ncsaRequestLog.setRetainDays(90); + ncsaRequestLog.setAppend(true); + ncsaRequestLog.setExtended(false); + ncsaRequestLog.setLogCookies(false); + ncsaRequestLog.setLogTimeZone("GMT"); + return ncsaRequestLog; + } + + @NotNull + private static HttpConfiguration getHttpConfiguration(int httpsPort) { + HttpConfiguration httpConfiguration = new HttpConfiguration(); + httpConfiguration.setSecureScheme("https"); + httpConfiguration.setSecurePort(httpsPort); + httpConfiguration.setOutputBufferSize(32768); + httpConfiguration.setRequestHeaderSize(8192); + httpConfiguration.setResponseHeaderSize(8192); + httpConfiguration.setSendServerVersion(true); + httpConfiguration.setSendDateHeader(false); + return httpConfiguration; + } + + @NotNull + private static ServletContextHandler getServletContextHandler(Properties provProps) { + ServletContextHandler servletContextHandler = new ServletContextHandler(0); + servletContextHandler.setContextPath("/"); + servletContextHandler.addServlet(new ServletHolder(new FeedServlet()), "/feed/*"); + servletContextHandler.addServlet(new ServletHolder(new FeedLogServlet()), "/feedlog/*"); + servletContextHandler.addServlet(new ServletHolder(new PublishServlet()), "/publish/*"); + servletContextHandler.addServlet(new ServletHolder(new SubscribeServlet()), "/subscribe/*"); + servletContextHandler.addServlet(new ServletHolder(new StatisticsServlet()), "/statistics/*"); + servletContextHandler.addServlet(new ServletHolder(new SubLogServlet()), "/sublog/*"); + servletContextHandler.addServlet(new ServletHolder(new GroupServlet()), "/group/*"); + servletContextHandler.addServlet(new ServletHolder(new SubscriptionServlet()), "/subs/*"); + servletContextHandler.addServlet(new ServletHolder(new InternalServlet()), "/internal/*"); + servletContextHandler.addServlet(new ServletHolder(new RouteServlet()), "/internal/route/*"); + servletContextHandler.addServlet(new ServletHolder(new DRFeedsServlet()), "/"); + servletContextHandler.addFilter(new FilterHolder(new ThrottleFilter()), + "/publish/*", EnumSet.of(DispatcherType.REQUEST)); + setCadiFilter(servletContextHandler, provProps); + return servletContextHandler; + } + + private static void setCadiFilter(ServletContextHandler servletContextHandler, Properties provProps) { + if (Boolean.parseBoolean(provProps.getProperty( + "org.onap.dmaap.datarouter.provserver.cadi.enabled", "false"))) { + try { + servletContextHandler.addFilter(new FilterHolder(new DRProvCadiFilter( + true, ProvRunner.getAafPropsUtils().getPropAccess())), "/*", EnumSet.of(DispatcherType.REQUEST)); + intlogger.info("PROV0001 AAF CADI filter enabled"); + } catch (ServletException e) { + intlogger.error("PROV0001 Failed to add CADI filter to server"); + } + + } + } +} diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java index d84e4925..089ea755 100755 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/ProxyServlet.java @@ -87,10 +87,6 @@ public class ProxyServlet extends BaseServlet { // Set up truststore store = ProvRunner.getAafPropsUtils().getTruststorePathProperty(); pass = ProvRunner.getAafPropsUtils().getTruststorePassProperty(); - if (store == null || store.length() == 0) { - store = AafPropsUtils.DEFAULT_TRUSTSTORE; - pass = "changeit"; - } KeyStore trustStore = readStore(store, pass, AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY); // We are connecting with the node name, but the certificate will have the CNAME diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java index 8cd19866..bd18280e 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/EgressRoute.java @@ -100,10 +100,11 @@ public class EgressRoute extends NodeClass implements Comparable { try (Connection conn = ProvDbUtils.getInstance().getConnection(); PreparedStatement ps = conn.prepareStatement("select NODEID from EGRESS_ROUTES where SUBID = ?")) { ps.setInt(1, sub); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - int node = rs.getInt("NODEID"); - er = new EgressRoute(sub, node); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + int node = rs.getInt("NODEID"); + er = new EgressRoute(sub, node); + } } } catch (SQLException e) { intlogger.error("PROV0009 EgressRoute.getEgressRoute: " + e.getMessage(), e); diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java index 14a0a9dc..79fc91b1 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/beans/Parameters.java @@ -108,8 +108,8 @@ public class Parameters extends Syncable { public static Collection getParameterCollection() { Collection coll = new ArrayList<>(); try (Connection conn = ProvDbUtils.getInstance().getConnection(); - PreparedStatement ps = conn.prepareStatement("select * from PARAMETERS")) { - ResultSet rs = ps.executeQuery(); + PreparedStatement ps = conn.prepareStatement("select * from PARAMETERS"); + ResultSet rs = ps.executeQuery()) { while (rs.next()) { Parameters param = new Parameters(rs); coll.add(param); @@ -132,9 +132,10 @@ public class Parameters extends Syncable { PreparedStatement stmt = conn.prepareStatement( "select KEYNAME, VALUE from PARAMETERS where KEYNAME = ?")) { stmt.setString(1, key); - ResultSet rs = stmt.executeQuery(); - if (rs.next()) { - val = new Parameters(rs); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + val = new Parameters(rs); + } } } catch (SQLException e) { intlogger.error(SQLEXCEPTION + e.getMessage(), e); diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/AafPropsUtils.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/AafPropsUtils.java index 68981599..6b78d21d 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/AafPropsUtils.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/AafPropsUtils.java @@ -29,10 +29,8 @@ import org.onap.aaf.cadi.PropAccess; public class AafPropsUtils { - private static AafPropsUtils aafPropsUtilsInstance = null; private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(AafPropsUtils.class); - public static final String DEFAULT_TRUSTSTORE = "/opt/app/osaaf/local/org.onap.dmaap-dr.trust.jks"; public static final String KEYSTORE_TYPE_PROPERTY = "PKCS12"; public static final String TRUESTSTORE_TYPE_PROPERTY = "jks"; private static final String KEYSTORE_PATH_PROPERTY = "cadi_keystore"; @@ -42,7 +40,7 @@ public class AafPropsUtils { private PropAccess propAccess; - private AafPropsUtils(File propsFile) throws IOException { + public AafPropsUtils(File propsFile) throws IOException { propAccess = new PropAccess(); try { propAccess.load(new FileInputStream(propsFile)); @@ -52,20 +50,6 @@ public class AafPropsUtils { } } - public static synchronized void init(File propsFile) throws IOException { - if (aafPropsUtilsInstance != null) { - throw new IllegalStateException("Already initialized"); - } - aafPropsUtilsInstance = new AafPropsUtils(propsFile); - } - - public static AafPropsUtils getInstance() { - if (aafPropsUtilsInstance == null) { - throw new IllegalStateException("Call AafPropsUtils.init(File propsFile) first"); - } - return aafPropsUtilsInstance; - } - private String decryptedPass(String password) { String decryptedPass = null; try { @@ -77,9 +61,6 @@ public class AafPropsUtils { } public PropAccess getPropAccess() { - if (propAccess == null) { - throw new IllegalStateException("Call AafPropsUtils.init(File propsFile) first"); - } return propAccess; } diff --git a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java index 187364f9..2d92276e 100644 --- a/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java +++ b/datarouter-prov/src/main/java/org/onap/dmaap/datarouter/provisioning/utils/DRRouteCLI.java @@ -1,505 +1,506 @@ -/******************************************************************************* - * ============LICENSE_START================================================== - * * org.onap.dmaap - * * =========================================================================== - * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * * =========================================================================== - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * ============LICENSE_END==================================================== - * * - * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * * - ******************************************************************************/ - -package org.onap.dmaap.datarouter.provisioning.utils; - -import static java.lang.System.exit; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.security.KeyStore; -import java.util.Arrays; -import java.util.Properties; - -import javax.servlet.http.HttpServletResponse; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.impl.client.AbstractHttpClient; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.util.EntityUtils; -import org.json.JSONArray; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.onap.dmaap.datarouter.provisioning.ProvRunner; - -/** - * This class provides a Command Line Interface for the routing tables in the DR Release 2.0 DB. - * A full description of this command is here. - * - * @author Robert Eby - * @version $Id: DRRouteCLI.java,v 1.2 2013/11/05 15:54:16 eby Exp $ - */ -public class DRRouteCLI { - /** - * Invoke the CLI. The CLI can be run with a single command (given as command line arguments), - * or in an interactive mode where the user types a sequence of commands to the program. The CLI is invoked via: - *

-     * java org.onap.dmaap.datarouter.provisioning.utils.DRRouteCLI [ -s server ] [ command ]
-     * 
- * A full description of the arguments to this command are - * here. - * - * @param args command line arguments - * @throws Exception for any unrecoverable problem - */ - public static void main(String[] args) throws Exception { - String server = System.getenv(ENV_VAR); - if (args.length >= 2 && args[0].equals("-s")) { - server = args[1]; - String[] str = new String[args.length - 2]; - if (str.length > 0) { - System.arraycopy(args, 2, str, 0, str.length); - } - args = str; - } - if (server == null || server.equals("")) { - System.err.println("dr-route: you need to specify a server, either via $PROVSRVR or the '-s' option."); - System.exit(1); - } - DRRouteCLI cli = new DRRouteCLI(server); - if (args.length > 0) { - boolean bool = cli.runCommand(args); - System.exit(bool ? 0 : 1); - } else { - cli.interactive(); - System.exit(0); - } - } - - private static final String ENV_VAR = "PROVSRVR"; - private static final String PROMPT = "dr-route> "; - private static final String DEFAULT_TRUSTSTORE_PATH = /* $JAVA_HOME + */ "/jre/lib/security/cacerts"; - private static final EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog"); - - private final String server; - private int width = 120; // screen width (for list) - private AbstractHttpClient httpclient; - - /** - * Create a DRRouteCLI object connecting to the specified server. - * - * @param server the server to send command to - * @throws Exception generic exception - */ - public DRRouteCLI(String server) throws Exception { - this.server = server; - this.httpclient = new DefaultHttpClient(); - - Properties provProperties = ProvRunner.getProvProperties(); - try { - AafPropsUtils.init(new File(provProperties.getProperty( - "org.onap.dmaap.datarouter.provserver.aafprops.path", - "/opt/app/osaaf/local/org.onap.dmaap-dr.props"))); - } catch (IOException e) { - intlogger.error("NODE0314 Failed to load AAF props. Exiting", e); - exit(1); - } - - String truststoreFile = AafPropsUtils.getInstance().getTruststorePathProperty(); - String truststorePw = AafPropsUtils.getInstance().getTruststorePassProperty(); - - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - if (truststoreFile == null || truststoreFile.equals("")) { - String jhome = System.getenv("JAVA_HOME"); - if (jhome == null || jhome.equals("")) { - jhome = "/opt/java/jdk/jdk180"; - } - truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH; - } - File file = new File(truststoreFile); - if (file.exists()) { - FileInputStream instream = new FileInputStream(file); - try { - trustStore.load(instream, truststorePw.toCharArray()); - } catch (Exception x) { - intlogger.error("Problem reading truststore: " + x.getMessage(), x); - throw x; - } finally { - try { - instream.close(); - } catch (Exception e) { - intlogger.error("Ignore error closing input stream: " + e.getMessage(), e); - } - } - } - - SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); - Scheme sch = new Scheme("https", 443, socketFactory); - httpclient.getConnectionManager().getSchemeRegistry().register(sch); - } - - private void interactive() throws IOException { - LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in)); - while (true) { - System.out.print(PROMPT); - String line = in.readLine(); - if (line == null) { - return; - } - line = line.trim(); - if (line.equalsIgnoreCase("exit")) { // "exit" may only be used in interactive mode - return; - } - if (line.equalsIgnoreCase("quit")) { // "quit" may only be used in interactive mode - return; - } - String[] args = line.split("[ \t]+"); - if (args.length > 0) { - runCommand(args); - } - } - } - - /** - * Run the command specified by the arguments. - * - * @param args The command line arguments. - * @return true if the command was valid and succeeded - */ - boolean runCommand(String[] args) { - String cmd = args[0].trim().toLowerCase(); - if (cmd.equals("add")) { - if (args.length > 2) { - if (args[1].startsWith("in") && args.length >= 6) { - return addIngress(args); - } - if (args[1].startsWith("eg") && args.length == 4) { - return addEgress(args); - } - if (args[1].startsWith("ne") && args.length == 5) { - return addRoute(args); - } - } - System.err.println("Add command should be one of:"); - System.err.println(" add in[gress] feedid user subnet nodepatt [ seq ]"); - System.err.println(" add eg[ress] subid node"); - System.err.println(" add ne[twork] fromnode tonode vianode"); - } else if (cmd.startsWith("del")) { - if (args.length > 2) { - if (args[1].startsWith("in") && args.length == 5) { - return delIngress(args); - } - if (args[1].startsWith("in") && args.length == 3) { - return delIngress(args); - } - if (args[1].startsWith("eg") && args.length == 3) { - return delEgress(args); - } - if (args[1].startsWith("ne") && args.length == 4) { - return delRoute(args); - } - } - System.err.println("Delete command should be one of:"); - System.err.println(" del in[gress] feedid user subnet"); - System.err.println(" del in[gress] seq"); - System.err.println(" del eg[ress] subid"); - System.err.println(" del ne[twork] fromnode tonode"); - } else if (cmd.startsWith("lis")) { - return list(args); - } else if (cmd.startsWith("wid") && args.length > 1) { - width = Integer.parseInt(args[1]); - return true; - } else if (cmd.startsWith("?") || cmd.startsWith("hel") || cmd.startsWith("usa")) { - usage(); - } else if (cmd.startsWith("#")) { - // comment -- ignore - } else { - System.err.println("Command should be one of add, del, list, exit, quit"); - } - return false; - } - - private void usage() { - System.out.println("Enter one of the following commands:"); - System.out.println(" add in[gress] feedid user subnet nodepatt [ seq ]"); - System.out.println(" add eg[ress] subid node"); - System.out.println(" add ne[twork] fromnode tonode vianode"); - System.out.println(" del in[gress] feedid user subnet"); - System.out.println(" del in[gress] seq"); - System.out.println(" del eg[ress] subid"); - System.out.println(" del ne[twork] fromnode tonode"); - System.out.println(" list [ all | ingress | egress | network ]"); - System.out.println(" exit"); - System.out.println(" quit"); - } - - private boolean addIngress(String[] args) { - 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]); - if (args.length > 6) { - url += "&seq=" + args[6]; - } - return doPost(url); - } - - private boolean addEgress(String[] args) { - String url = String.format("https://%s/internal/route/egress/?sub=%s&node=%s", server, args[2], args[3]); - return doPost(url); - } - - private boolean addRoute(String[] args) { - String url = String.format("https://%s/internal/route/network/?from=%s&to=%s&via=%s", server, args[2], args[3], args[4]); - return doPost(url); - } - - private boolean delIngress(String[] args) { - String url; - if (args.length == 5) { - String subnet = args[4].replaceAll("/", "!"); // replace the / with a ! - url = String.format("https://%s/internal/route/ingress/%s/%s/%s", server, args[2], args[3], subnet); - } else { - url = String.format("https://%s/internal/route/ingress/%s", server, args[2]); - } - return doDelete(url); - } - - private boolean delEgress(String[] args) { - String url = String.format("https://%s/internal/route/egress/%s", server, args[2]); - return doDelete(url); - } - - private boolean delRoute(String[] args) { - String url = String.format("https://%s/internal/route/network/%s/%s", server, args[2], args[3]); - return doDelete(url); - } - - private boolean list(String[] args) { - String tbl = (args.length == 1) ? "all" : args[1].toLowerCase(); - JSONObject jo = doGet("https://" + server + "/internal/route/"); // Returns all 3 tables - StringBuilder sb = new StringBuilder(); - if (tbl.startsWith("al") || tbl.startsWith("in")) { - // Display the IRT - JSONArray irt = jo.optJSONArray("ingress"); - int cw1 = 6; - int cw2 = 6; - int cw3 = 6; - int cw4 = 6; // determine column widths for first 4 cols - for (int i = 0; irt != null && i < irt.length(); i++) { - JSONObject jsonObject = irt.getJSONObject(i); - cw1 = Math.max(cw1, ("" + jsonObject.getInt("seq")).length()); - cw2 = Math.max(cw2, ("" + jsonObject.getInt("feedid")).length()); - String str = jsonObject.optString("user"); - cw3 = Math.max(cw3, (str == null) ? 1 : str.length()); - str = jsonObject.optString("subnet"); - cw4 = Math.max(cw4, (str == null) ? 1 : str.length()); - } - - int nblank = cw1 + cw2 + cw3 + cw4 + 8; - sb.append("Ingress Routing Table\n"); - sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1), - ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4))); - for (int i = 0; irt != null && i < irt.length(); i++) { - JSONObject jsonObject = irt.getJSONObject(i); - String seq = "" + jsonObject.getInt("seq"); - String feedid = "" + jsonObject.getInt("feedid"); - String user = jsonObject.optString("user"); - String subnet = jsonObject.optString("subnet"); - if (user.equals("")) { - user = "-"; - } - if (subnet.equals("")) { - subnet = "-"; - } - JSONArray nodes = jsonObject.getJSONArray("node"); - int sol = sb.length(); - sb.append(String.format("%s %s %s %s ", ext(seq, cw1), - ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4))); - for (int j = 0; j < nodes.length(); j++) { - String nd = nodes.getString(j); - int cursor = sb.length() - sol; - if (j > 0 && (cursor + nd.length() > width)) { - sb.append("\n"); - sol = sb.length(); - sb.append(ext(" ", nblank)); - } - sb.append(nd); - if ((j + 1) < nodes.length()) { - sb.append(", "); - } - } - sb.append("\n"); - } - } - if (tbl.startsWith("al") || tbl.startsWith("eg")) { - // Display the ERT - JSONObject ert = jo.optJSONObject("egress"); - String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert); - if (subs == null) { - subs = new String[0]; - } - Arrays.sort(subs); - int cw1 = 5; - for (int i = 0; i < subs.length; i++) { - cw1 = Math.max(cw1, subs[i].length()); - } - - if (sb.length() > 0) { - sb.append("\n"); - } - sb.append("Egress Routing Table\n"); - sb.append(String.format("%s Node\n", ext("SubID", cw1))); - for (int i = 0; i < subs.length; i++) { - if (ert != null && ert.length() != 0 ) { - String node = ert.getString(subs[i]); - sb.append(String.format("%s %s\n", ext(subs[i], cw1), node)); - } - - } - } - if (tbl.startsWith("al") || tbl.startsWith("ne")) { - // Display the NRT - JSONArray nrt = jo.optJSONArray("routing"); - int cw1 = 4; - int cw2 = 4; - for (int i = 0; nrt != null && i < nrt.length(); i++) { - JSONObject jsonObject = nrt.getJSONObject(i); - String from = jsonObject.getString("from"); - String to = jsonObject.getString("to"); - cw1 = Math.max(cw1, from.length()); - cw2 = Math.max(cw2, to.length()); - } - - if (sb.length() > 0) { - sb.append("\n"); - } - sb.append("Network Routing Table\n"); - sb.append(String.format("%s %s Via\n", ext("From", cw1), ext("To", cw2))); - for (int i = 0; nrt != null && i < nrt.length(); i++) { - JSONObject jsonObject = nrt.getJSONObject(i); - String from = jsonObject.getString("from"); - String to = jsonObject.getString("to"); - String via = jsonObject.getString("via"); - sb.append(String.format("%s %s %s\n", ext(from, cw1), ext(to, cw2), via)); - } - } - System.out.print(sb.toString()); - return true; - } - - private String ext(String str, int num) { - if (str == null) { - str = "-"; - } - while (str.length() < num) { - str += " "; - } - return str; - } - - private boolean doDelete(String url) { - boolean rv = false; - HttpDelete meth = new HttpDelete(url); - try { - HttpResponse response = httpclient.execute(meth); - HttpEntity entity = response.getEntity(); - StatusLine sl = response.getStatusLine(); - rv = (sl.getStatusCode() == HttpServletResponse.SC_OK); - if (rv) { - System.out.println("Routing entry deleted."); - EntityUtils.consume(entity); - } else { - printErrorText(entity); - } - } catch (Exception e) { - intlogger.error("PROV0006 doDelete: " + e.getMessage(), e); - } finally { - meth.releaseConnection(); - } - return rv; - } - - private JSONObject doGet(String url) { - JSONObject rv = new JSONObject(); - HttpGet meth = new HttpGet(url); - try { - HttpResponse response = httpclient.execute(meth); - HttpEntity entity = response.getEntity(); - StatusLine sl = response.getStatusLine(); - if (sl.getStatusCode() == HttpServletResponse.SC_OK) { - rv = new JSONObject(new JSONTokener(entity.getContent())); - } else { - printErrorText(entity); - } - } catch (Exception e) { - intlogger.error("PROV0005 doGet: " + e.getMessage(), e); - } finally { - meth.releaseConnection(); - } - return rv; - } - - private boolean doPost(String url) { - boolean rv = false; - HttpPost meth = new HttpPost(url); - try { - HttpResponse response = httpclient.execute(meth); - HttpEntity entity = response.getEntity(); - StatusLine sl = response.getStatusLine(); - rv = (sl.getStatusCode() == HttpServletResponse.SC_OK); - if (rv) { - System.out.println("Routing entry added."); - EntityUtils.consume(entity); - } else { - printErrorText(entity); - } - } catch (Exception e) { - intlogger.error("PROV0009 doPost: " + e.getMessage(), e); - } finally { - meth.releaseConnection(); - } - return rv; - } - - private void printErrorText(HttpEntity entity) throws IOException { - // Look for and print only the part of the output between
...
- InputStream is = entity.getContent(); - StringBuilder sb = new StringBuilder(); - byte[] bite = new byte[512]; - int num; - while ((num = is.read(bite)) > 0) { - sb.append(new String(bite, 0, num)); - } - is.close(); - int ix = sb.indexOf("
");
-        if (ix > 0) {
-            sb.delete(0, ix + 5);
-        }
-        ix = sb.indexOf("
"); - if (ix > 0) { - sb.delete(ix, sb.length()); - } - System.err.println(sb.toString()); - } -} +/******************************************************************************* + * ============LICENSE_START================================================== + * * org.onap.dmaap + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * * ============LICENSE_END==================================================== + * * + * * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * * + ******************************************************************************/ + +package org.onap.dmaap.datarouter.provisioning.utils; + +import static java.lang.System.exit; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.security.KeyStore; +import java.util.Arrays; +import java.util.Properties; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.AbstractHttpClient; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.onap.dmaap.datarouter.provisioning.ProvRunner; + +/** + * This class provides a Command Line Interface for the routing tables in the DR Release 2.0 DB. + * A full description of this command is here. + * + * @author Robert Eby + * @version $Id: DRRouteCLI.java,v 1.2 2013/11/05 15:54:16 eby Exp $ + */ +public class DRRouteCLI { + /** + * Invoke the CLI. The CLI can be run with a single command (given as command line arguments), + * or in an interactive mode where the user types a sequence of commands to the program. The CLI is invoked via: + *
+     * java org.onap.dmaap.datarouter.provisioning.utils.DRRouteCLI [ -s server ] [ command ]
+     * 
+ * A full description of the arguments to this command are + * here. + * + * @param args command line arguments + * @throws Exception for any unrecoverable problem + */ + public static void main(String[] args) throws Exception { + String server = System.getenv(ENV_VAR); + if (args.length >= 2 && args[0].equals("-s")) { + server = args[1]; + String[] str = new String[args.length - 2]; + if (str.length > 0) { + System.arraycopy(args, 2, str, 0, str.length); + } + args = str; + } + if (server == null || server.equals("")) { + System.err.println("dr-route: you need to specify a server, either via $PROVSRVR or the '-s' option."); + System.exit(1); + } + DRRouteCLI cli = new DRRouteCLI(server); + if (args.length > 0) { + boolean bool = cli.runCommand(args); + System.exit(bool ? 0 : 1); + } else { + cli.interactive(); + System.exit(0); + } + } + + private static final String ENV_VAR = "PROVSRVR"; + private static final String PROMPT = "dr-route> "; + private static final String DEFAULT_TRUSTSTORE_PATH = /* $JAVA_HOME + */ "/jre/lib/security/cacerts"; + private static final EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog"); + + private final String server; + private int width = 120; // screen width (for list) + private AbstractHttpClient httpclient; + + /** + * Create a DRRouteCLI object connecting to the specified server. + * + * @param server the server to send command to + * @throws Exception generic exception + */ + public DRRouteCLI(String server) throws Exception { + this.server = server; + this.httpclient = new DefaultHttpClient(); + AafPropsUtils aafPropsUtils = null; + + Properties provProperties = ProvRunner.getProvProperties(); + try { + aafPropsUtils = new AafPropsUtils(new File(provProperties.getProperty( + "org.onap.dmaap.datarouter.provserver.aafprops.path", + "/opt/app/osaaf/local/org.onap.dmaap-dr.props"))); + } catch (IOException e) { + intlogger.error("NODE0314 Failed to load AAF props. Exiting", e); + exit(1); + } + + String truststoreFile = aafPropsUtils.getTruststorePathProperty(); + String truststorePw = aafPropsUtils.getTruststorePassProperty(); + + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + if (truststoreFile == null || truststoreFile.equals("")) { + String jhome = System.getenv("JAVA_HOME"); + if (jhome == null || jhome.equals("")) { + jhome = "/opt/java/jdk/jdk180"; + } + truststoreFile = jhome + DEFAULT_TRUSTSTORE_PATH; + } + File file = new File(truststoreFile); + if (file.exists()) { + FileInputStream instream = new FileInputStream(file); + try { + trustStore.load(instream, truststorePw.toCharArray()); + } catch (Exception x) { + intlogger.error("Problem reading truststore: " + x.getMessage(), x); + throw x; + } finally { + try { + instream.close(); + } catch (Exception e) { + intlogger.error("Ignore error closing input stream: " + e.getMessage(), e); + } + } + } + + SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); + Scheme sch = new Scheme("https", 443, socketFactory); + httpclient.getConnectionManager().getSchemeRegistry().register(sch); + } + + private void interactive() throws IOException { + LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in)); + while (true) { + System.out.print(PROMPT); + String line = in.readLine(); + if (line == null) { + return; + } + line = line.trim(); + if (line.equalsIgnoreCase("exit")) { // "exit" may only be used in interactive mode + return; + } + if (line.equalsIgnoreCase("quit")) { // "quit" may only be used in interactive mode + return; + } + String[] args = line.split("[ \t]+"); + if (args.length > 0) { + runCommand(args); + } + } + } + + /** + * Run the command specified by the arguments. + * + * @param args The command line arguments. + * @return true if the command was valid and succeeded + */ + boolean runCommand(String[] args) { + String cmd = args[0].trim().toLowerCase(); + if (cmd.equals("add")) { + if (args.length > 2) { + if (args[1].startsWith("in") && args.length >= 6) { + return addIngress(args); + } + if (args[1].startsWith("eg") && args.length == 4) { + return addEgress(args); + } + if (args[1].startsWith("ne") && args.length == 5) { + return addRoute(args); + } + } + System.err.println("Add command should be one of:"); + System.err.println(" add in[gress] feedid user subnet nodepatt [ seq ]"); + System.err.println(" add eg[ress] subid node"); + System.err.println(" add ne[twork] fromnode tonode vianode"); + } else if (cmd.startsWith("del")) { + if (args.length > 2) { + if (args[1].startsWith("in") && args.length == 5) { + return delIngress(args); + } + if (args[1].startsWith("in") && args.length == 3) { + return delIngress(args); + } + if (args[1].startsWith("eg") && args.length == 3) { + return delEgress(args); + } + if (args[1].startsWith("ne") && args.length == 4) { + return delRoute(args); + } + } + System.err.println("Delete command should be one of:"); + System.err.println(" del in[gress] feedid user subnet"); + System.err.println(" del in[gress] seq"); + System.err.println(" del eg[ress] subid"); + System.err.println(" del ne[twork] fromnode tonode"); + } else if (cmd.startsWith("lis")) { + return list(args); + } else if (cmd.startsWith("wid") && args.length > 1) { + width = Integer.parseInt(args[1]); + return true; + } else if (cmd.startsWith("?") || cmd.startsWith("hel") || cmd.startsWith("usa")) { + usage(); + } else if (cmd.startsWith("#")) { + // comment -- ignore + } else { + System.err.println("Command should be one of add, del, list, exit, quit"); + } + return false; + } + + private void usage() { + System.out.println("Enter one of the following commands:"); + System.out.println(" add in[gress] feedid user subnet nodepatt [ seq ]"); + System.out.println(" add eg[ress] subid node"); + System.out.println(" add ne[twork] fromnode tonode vianode"); + System.out.println(" del in[gress] feedid user subnet"); + System.out.println(" del in[gress] seq"); + System.out.println(" del eg[ress] subid"); + System.out.println(" del ne[twork] fromnode tonode"); + System.out.println(" list [ all | ingress | egress | network ]"); + System.out.println(" exit"); + System.out.println(" quit"); + } + + private boolean addIngress(String[] args) { + 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]); + if (args.length > 6) { + url += "&seq=" + args[6]; + } + return doPost(url); + } + + private boolean addEgress(String[] args) { + String url = String.format("https://%s/internal/route/egress/?sub=%s&node=%s", server, args[2], args[3]); + return doPost(url); + } + + private boolean addRoute(String[] args) { + String url = String.format("https://%s/internal/route/network/?from=%s&to=%s&via=%s", server, args[2], args[3], args[4]); + return doPost(url); + } + + private boolean delIngress(String[] args) { + String url; + if (args.length == 5) { + String subnet = args[4].replaceAll("/", "!"); // replace the / with a ! + url = String.format("https://%s/internal/route/ingress/%s/%s/%s", server, args[2], args[3], subnet); + } else { + url = String.format("https://%s/internal/route/ingress/%s", server, args[2]); + } + return doDelete(url); + } + + private boolean delEgress(String[] args) { + String url = String.format("https://%s/internal/route/egress/%s", server, args[2]); + return doDelete(url); + } + + private boolean delRoute(String[] args) { + String url = String.format("https://%s/internal/route/network/%s/%s", server, args[2], args[3]); + return doDelete(url); + } + + private boolean list(String[] args) { + String tbl = (args.length == 1) ? "all" : args[1].toLowerCase(); + JSONObject jo = doGet("https://" + server + "/internal/route/"); // Returns all 3 tables + StringBuilder sb = new StringBuilder(); + if (tbl.startsWith("al") || tbl.startsWith("in")) { + // Display the IRT + JSONArray irt = jo.optJSONArray("ingress"); + int cw1 = 6; + int cw2 = 6; + int cw3 = 6; + int cw4 = 6; // determine column widths for first 4 cols + for (int i = 0; irt != null && i < irt.length(); i++) { + JSONObject jsonObject = irt.getJSONObject(i); + cw1 = Math.max(cw1, ("" + jsonObject.getInt("seq")).length()); + cw2 = Math.max(cw2, ("" + jsonObject.getInt("feedid")).length()); + String str = jsonObject.optString("user"); + cw3 = Math.max(cw3, (str == null) ? 1 : str.length()); + str = jsonObject.optString("subnet"); + cw4 = Math.max(cw4, (str == null) ? 1 : str.length()); + } + + int nblank = cw1 + cw2 + cw3 + cw4 + 8; + sb.append("Ingress Routing Table\n"); + sb.append(String.format("%s %s %s %s Nodes\n", ext("Seq", cw1), + ext("FeedID", cw2), ext("User", cw3), ext("Subnet", cw4))); + for (int i = 0; irt != null && i < irt.length(); i++) { + JSONObject jsonObject = irt.getJSONObject(i); + String seq = "" + jsonObject.getInt("seq"); + String feedid = "" + jsonObject.getInt("feedid"); + String user = jsonObject.optString("user"); + String subnet = jsonObject.optString("subnet"); + if (user.equals("")) { + user = "-"; + } + if (subnet.equals("")) { + subnet = "-"; + } + JSONArray nodes = jsonObject.getJSONArray("node"); + int sol = sb.length(); + sb.append(String.format("%s %s %s %s ", ext(seq, cw1), + ext(feedid, cw2), ext(user, cw3), ext(subnet, cw4))); + for (int j = 0; j < nodes.length(); j++) { + String nd = nodes.getString(j); + int cursor = sb.length() - sol; + if (j > 0 && (cursor + nd.length() > width)) { + sb.append("\n"); + sol = sb.length(); + sb.append(ext(" ", nblank)); + } + sb.append(nd); + if ((j + 1) < nodes.length()) { + sb.append(", "); + } + } + sb.append("\n"); + } + } + if (tbl.startsWith("al") || tbl.startsWith("eg")) { + // Display the ERT + JSONObject ert = jo.optJSONObject("egress"); + String[] subs = (ert == null) ? new String[0] : JSONObject.getNames(ert); + if (subs == null) { + subs = new String[0]; + } + Arrays.sort(subs); + int cw1 = 5; + for (int i = 0; i < subs.length; i++) { + cw1 = Math.max(cw1, subs[i].length()); + } + + if (sb.length() > 0) { + sb.append("\n"); + } + sb.append("Egress Routing Table\n"); + sb.append(String.format("%s Node\n", ext("SubID", cw1))); + for (int i = 0; i < subs.length; i++) { + if (ert != null && ert.length() != 0 ) { + String node = ert.getString(subs[i]); + sb.append(String.format("%s %s\n", ext(subs[i], cw1), node)); + } + + } + } + if (tbl.startsWith("al") || tbl.startsWith("ne")) { + // Display the NRT + JSONArray nrt = jo.optJSONArray("routing"); + int cw1 = 4; + int cw2 = 4; + for (int i = 0; nrt != null && i < nrt.length(); i++) { + JSONObject jsonObject = nrt.getJSONObject(i); + String from = jsonObject.getString("from"); + String to = jsonObject.getString("to"); + cw1 = Math.max(cw1, from.length()); + cw2 = Math.max(cw2, to.length()); + } + + if (sb.length() > 0) { + sb.append("\n"); + } + sb.append("Network Routing Table\n"); + sb.append(String.format("%s %s Via\n", ext("From", cw1), ext("To", cw2))); + for (int i = 0; nrt != null && i < nrt.length(); i++) { + JSONObject jsonObject = nrt.getJSONObject(i); + String from = jsonObject.getString("from"); + String to = jsonObject.getString("to"); + String via = jsonObject.getString("via"); + sb.append(String.format("%s %s %s\n", ext(from, cw1), ext(to, cw2), via)); + } + } + System.out.print(sb.toString()); + return true; + } + + private String ext(String str, int num) { + if (str == null) { + str = "-"; + } + while (str.length() < num) { + str += " "; + } + return str; + } + + private boolean doDelete(String url) { + boolean rv = false; + HttpDelete meth = new HttpDelete(url); + try { + HttpResponse response = httpclient.execute(meth); + HttpEntity entity = response.getEntity(); + StatusLine sl = response.getStatusLine(); + rv = (sl.getStatusCode() == HttpServletResponse.SC_OK); + if (rv) { + System.out.println("Routing entry deleted."); + EntityUtils.consume(entity); + } else { + printErrorText(entity); + } + } catch (Exception e) { + intlogger.error("PROV0006 doDelete: " + e.getMessage(), e); + } finally { + meth.releaseConnection(); + } + return rv; + } + + private JSONObject doGet(String url) { + JSONObject rv = new JSONObject(); + HttpGet meth = new HttpGet(url); + try { + HttpResponse response = httpclient.execute(meth); + HttpEntity entity = response.getEntity(); + StatusLine sl = response.getStatusLine(); + if (sl.getStatusCode() == HttpServletResponse.SC_OK) { + rv = new JSONObject(new JSONTokener(entity.getContent())); + } else { + printErrorText(entity); + } + } catch (Exception e) { + intlogger.error("PROV0005 doGet: " + e.getMessage(), e); + } finally { + meth.releaseConnection(); + } + return rv; + } + + private boolean doPost(String url) { + boolean rv = false; + HttpPost meth = new HttpPost(url); + try { + HttpResponse response = httpclient.execute(meth); + HttpEntity entity = response.getEntity(); + StatusLine sl = response.getStatusLine(); + rv = (sl.getStatusCode() == HttpServletResponse.SC_OK); + if (rv) { + System.out.println("Routing entry added."); + EntityUtils.consume(entity); + } else { + printErrorText(entity); + } + } catch (Exception e) { + intlogger.error("PROV0009 doPost: " + e.getMessage(), e); + } finally { + meth.releaseConnection(); + } + return rv; + } + + private void printErrorText(HttpEntity entity) throws IOException { + // Look for and print only the part of the output between
...
+ InputStream is = entity.getContent(); + StringBuilder sb = new StringBuilder(); + byte[] bite = new byte[512]; + int num; + while ((num = is.read(bite)) > 0) { + sb.append(new String(bite, 0, num)); + } + is.close(); + int ix = sb.indexOf("
");
+        if (ix > 0) {
+            sb.delete(0, ix + 5);
+        }
+        ix = sb.indexOf("
"); + if (ix > 0) { + sb.delete(ix, sb.length()); + } + System.err.println(sb.toString()); + } +} -- cgit 1.2.3-korg