Fix datarouter-prov server issue
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / Main.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
25 package org.onap.dmaap.datarouter.provisioning;
26
27 import java.security.*;
28 import java.util.*;
29
30 import org.apache.log4j.Logger;
31 import org.eclipse.jetty.http.HttpVersion;
32 import org.eclipse.jetty.server.Connector;
33 import org.eclipse.jetty.server.Handler;
34 import org.eclipse.jetty.server.HttpConfiguration;
35 import org.eclipse.jetty.server.HttpConnectionFactory;
36 import org.eclipse.jetty.server.NCSARequestLog;
37 import org.eclipse.jetty.server.Server;
38 import org.eclipse.jetty.server.ServerConnector;
39 import org.eclipse.jetty.server.handler.ContextHandlerCollection;
40 import org.eclipse.jetty.server.handler.DefaultHandler;
41 import org.eclipse.jetty.server.handler.HandlerCollection;
42 import org.eclipse.jetty.server.handler.RequestLogHandler;
43 import org.eclipse.jetty.server.SslConnectionFactory;
44 import org.eclipse.jetty.util.ssl.SslContextFactory;
45 import org.eclipse.jetty.servlet.FilterHolder;
46 import org.eclipse.jetty.servlet.ServletContextHandler;
47 import org.eclipse.jetty.servlet.ServletHolder;
48 import org.eclipse.jetty.util.thread.QueuedThreadPool;
49 import org.onap.dmaap.datarouter.provisioning.utils.DB;
50 import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
51 import org.onap.dmaap.datarouter.provisioning.utils.PurgeLogDirTask;
52 import org.onap.dmaap.datarouter.provisioning.utils.ThrottleFilter;
53
54 import javax.servlet.DispatcherType;
55
56 /**
57  * <p>
58  * A main class which may be used to start the provisioning server with an "embedded" Jetty server.
59  * Configuration is done via the properties file <i>provserver.properties</i>, which should be in the CLASSPATH.
60  * The provisioning server may also be packaged with a web.xml and started as a traditional webapp.
61  * </p>
62  * <p>
63  * Most of the work of the provisioning server is carried out within the eight servlets (configured below)
64  * that are used to handle each of the eight types of requests the server may receive.
65  * In addition, there are background threads started to perform other tasks:
66  * </p>
67  * <ul>
68  * <li>One background Thread runs the {@link LogfileLoader} in order to process incoming logfiles.
69  * This Thread is created as a side effect of the first successful POST to the /internal/logs/ servlet.</li>
70  * <li>One background Thread runs the {@link SynchronizerTask} which is used to periodically
71  * synchronize the database between active and standby servers.</li>
72  * <li>One background Thread runs the {@link Poker} which is used to notify the nodes whenever
73  * provisioning data changes.</li>
74  * <li>One task is run once a day to run {@link PurgeLogDirTask} which purges older logs from the
75  * /opt/app/datartr/logs directory.</li>
76  * </ul>
77  * <p>
78  * The provisioning server is stopped by issuing a GET to the URL http://127.0.0.1/internal/halt
79  * using <i>curl</i> or some other such tool.
80  * </p>
81  *
82  * @author Robert Eby
83  * @version $Id: Main.java,v 1.12 2014/03/12 19:45:41 eby Exp $
84  */
85 public class Main {
86     /**
87      * The truststore to use if none is specified
88      */
89     public static final String DEFAULT_TRUSTSTORE = "/opt/java/jdk/jdk180/jre/lib/security/cacerts";
90     public static final String KEYSTORE_TYPE_PROPERTY = "org.onap.dmaap.datarouter.provserver.keystore.type";
91     public static final String KEYSTORE_PATH_PROPERTY = "org.onap.dmaap.datarouter.provserver.keystore.path";
92     public static final String KEYSTORE_PASSWORD_PROPERTY = "org.onap.dmaap.datarouter.provserver.keystore.password";
93     public static final String TRUSTSTORE_PATH_PROPERTY = "org.onap.dmaap.datarouter.provserver.truststore.path";
94     public static final String TRUSTSTORE_PASSWORD_PROPERTY = "org.onap.dmaap.datarouter.provserver.truststore.password";
95
96     /**
97      * The one and only {@link Server} instance in this JVM
98      */
99     private static Server server;
100
101     /**
102      * Starts the Data Router Provisioning server.
103      *
104      * @param args not used
105      * @throws Exception if Jetty has a problem starting
106      */
107     public static void main(String[] args) throws Exception {
108         Security.setProperty("networkaddress.cache.ttl", "4");
109         Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
110
111         // Check DB is accessible and contains the expected tables
112         if (!checkDatabase(logger))
113             System.exit(1);
114
115         logger.info("PROV0000 **** AT&T Data Router Provisioning Server starting....");
116
117         // Get properties
118         Properties p = (new DB()).getProperties();
119         int httpPort = Integer.parseInt(p.getProperty("org.onap.dmaap.datarouter.provserver.http.port", "8080"));
120         int httpsPort = Integer.parseInt(p.getProperty("org.onap.dmaap.datarouter.provserver.https.port", "8443"));
121
122         // HTTP configuration
123         HttpConfiguration httpConfiguration = new HttpConfiguration();
124         httpConfiguration.setSecureScheme("https");
125         httpConfiguration.setSecurePort(httpsPort);
126         httpConfiguration.setOutputBufferSize(32768);
127         httpConfiguration.setRequestHeaderSize(2048);
128         httpConfiguration.setIdleTimeout(300000);
129         httpConfiguration.setSendServerVersion(true);
130         httpConfiguration.setSendDateHeader(false);
131
132         // Server's thread pool
133         QueuedThreadPool queuedThreadPool = new QueuedThreadPool();
134         queuedThreadPool.setMinThreads(10);
135         queuedThreadPool.setMaxThreads(200);
136         queuedThreadPool.setDetailedDump(false);
137
138         // The server itself
139         server = new Server(queuedThreadPool);
140
141         // HTTP connector
142         ServerConnector httpServerConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
143         httpServerConnector.setPort(httpPort);
144         httpServerConnector.setAcceptQueueSize(2);
145
146         // HTTPS configuration
147         HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
148         httpsConfiguration.setRequestHeaderSize(8192);
149
150         // HTTPS connector
151         SslContextFactory sslContextFactory = new SslContextFactory();
152         sslContextFactory.setKeyStorePath(p.getProperty(KEYSTORE_PATH_PROPERTY));
153         sslContextFactory.setKeyStorePassword(p.getProperty(KEYSTORE_PASSWORD_PROPERTY));
154         sslContextFactory.setKeyManagerPassword(p.getProperty("org.onap.dmaap.datarouter.provserver.keymanager.password"));
155         // SSL stuff
156         /* Skip SSLv3 Fixes */
157         sslContextFactory.addExcludeProtocols("SSLv3");
158         logger.info("Excluded protocols prov-" + sslContextFactory.getExcludeProtocols());
159         /* End of SSLv3 Fixes */
160
161         ServerConnector httpsServerConnector = new ServerConnector(server,
162                 new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
163                 new HttpConnectionFactory(httpsConfiguration));
164         httpsServerConnector.setPort(httpsPort);
165         httpsServerConnector.setIdleTimeout(30000);
166         httpsServerConnector.setAcceptQueueSize(2);
167
168         sslContextFactory.setKeyStoreType(p.getProperty(KEYSTORE_TYPE_PROPERTY, "jks"));
169         sslContextFactory.setKeyStorePath(p.getProperty(KEYSTORE_PATH_PROPERTY));
170         sslContextFactory.setKeyStorePassword(p.getProperty(KEYSTORE_PASSWORD_PROPERTY));
171         sslContextFactory.setKeyManagerPassword(p.getProperty("org.onap.dmaap.datarouter.provserver.keymanager.password"));
172
173         String ts = p.getProperty(TRUSTSTORE_PATH_PROPERTY);
174         if (ts != null && ts.length() > 0) {
175             System.out.println("@@ TS -> " + ts);
176             sslContextFactory.setTrustStorePath(ts);
177             sslContextFactory.setTrustStorePassword(p.getProperty(TRUSTSTORE_PASSWORD_PROPERTY));
178         } else {
179             sslContextFactory.setTrustStorePath(DEFAULT_TRUSTSTORE);
180             sslContextFactory.setTrustStorePassword("changeit");
181         }
182         sslContextFactory.setTrustStorePath("/opt/app/datartr/self_signed/cacerts.jks");
183         sslContextFactory.setTrustStorePassword("changeit");
184         sslContextFactory.setWantClientAuth(true);
185
186         // Servlet and Filter configuration
187         ServletContextHandler ctxt = new ServletContextHandler(0);
188         ctxt.setContextPath("/");
189         ctxt.addServlet(new ServletHolder(new FeedServlet()), "/feed/*");
190         ctxt.addServlet(new ServletHolder(new FeedLogServlet()), "/feedlog/*");
191         ctxt.addServlet(new ServletHolder(new PublishServlet()), "/publish/*");
192         ctxt.addServlet(new ServletHolder(new SubscribeServlet()), "/subscribe/*");
193         ctxt.addServlet(new ServletHolder(new StatisticsServlet()), "/statistics/*");
194         ctxt.addServlet(new ServletHolder(new SubLogServlet()), "/sublog/*");
195         ctxt.addServlet(new ServletHolder(new GroupServlet()), "/group/*"); //Provision groups - Rally US708115 -1610
196         ctxt.addServlet(new ServletHolder(new SubscriptionServlet()), "/subs/*");
197         ctxt.addServlet(new ServletHolder(new InternalServlet()), "/internal/*");
198         ctxt.addServlet(new ServletHolder(new RouteServlet()), "/internal/route/*");
199         ctxt.addServlet(new ServletHolder(new DRFeedsServlet()), "/");
200         ctxt.addFilter(new FilterHolder(new ThrottleFilter()), "/publish/*", EnumSet.of(DispatcherType.REQUEST));
201
202         ContextHandlerCollection contexts = new ContextHandlerCollection();
203         contexts.addHandler(ctxt);
204
205         // Request log configuration
206         NCSARequestLog nrl = new NCSARequestLog();
207         nrl.setFilename(p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir") + "/request.log.yyyy_mm_dd");
208         nrl.setFilenameDateFormat("yyyyMMdd");
209         nrl.setRetainDays(90);
210         nrl.setAppend(true);
211         nrl.setExtended(false);
212         nrl.setLogCookies(false);
213         nrl.setLogTimeZone("GMT");
214
215         RequestLogHandler reqlog = new RequestLogHandler();
216         reqlog.setRequestLog(nrl);
217
218         // Server's Handler collection
219         HandlerCollection hc = new HandlerCollection();
220         hc.setHandlers(new Handler[]{contexts, new DefaultHandler()});
221         hc.addHandler(reqlog);
222
223         // Daemon to clean up the log directory on a daily basis
224         Timer rolex = new Timer();
225         rolex.scheduleAtFixedRate(new PurgeLogDirTask(), 0, 86400000L);    // run once per day
226
227         // Start LogfileLoader
228         LogfileLoader.getLoader();
229
230         ServerConnector serverConnector = new ServerConnector(server,
231                 new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
232                 new HttpConnectionFactory(httpsConfiguration));
233         serverConnector.setPort(httpsPort);
234         serverConnector.setIdleTimeout(500000);
235
236         server.setConnectors(new Connector[]{httpServerConnector, httpsServerConnector});
237         server.setHandler(hc);
238         server.setStopAtShutdown(true);
239         server.setStopTimeout(5000);
240
241         server.setDumpAfterStart(false);
242         server.setDumpBeforeStop(false);
243
244         server.start();
245         server.join();
246         logger.info("PROV0001 **** AT&T Data Router Provisioning Server halted.");
247     }
248
249     private static boolean checkDatabase(Logger logger) {
250         DB db = new DB();
251         return db.runRetroFits();
252     }
253
254     /**
255      * Stop the Jetty server.
256      */
257     static void shutdown() {
258         new Thread(() -> {
259             try {
260                 server.stop();
261                 Thread.sleep(5000L);
262                 System.exit(0);
263             } catch (Exception e) {
264                 // ignore
265             }
266         });
267     }
268 }