2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019-2020,2023 Nordix Foundation.
7 * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.common.endpoints.http.server.internal;
25 import io.prometheus.client.hotspot.DefaultExports;
26 import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet;
27 import jakarta.servlet.Servlet;
28 import java.util.EnumSet;
29 import java.util.HashMap;
32 import lombok.NonNull;
33 import lombok.ToString;
34 import org.eclipse.jetty.security.ConstraintMapping;
35 import org.eclipse.jetty.security.ConstraintSecurityHandler;
36 import org.eclipse.jetty.security.HashLoginService;
37 import org.eclipse.jetty.security.UserStore;
38 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
39 import org.eclipse.jetty.server.CustomRequestLog;
40 import org.eclipse.jetty.server.HttpConfiguration;
41 import org.eclipse.jetty.server.HttpConnectionFactory;
42 import org.eclipse.jetty.server.SecureRequestCustomizer;
43 import org.eclipse.jetty.server.Server;
44 import org.eclipse.jetty.server.ServerConnector;
45 import org.eclipse.jetty.server.Slf4jRequestLogWriter;
46 import org.eclipse.jetty.servlet.FilterHolder;
47 import org.eclipse.jetty.servlet.ServletContextHandler;
48 import org.eclipse.jetty.servlet.ServletHolder;
49 import org.eclipse.jetty.util.security.Constraint;
50 import org.eclipse.jetty.util.security.Credential;
51 import org.eclipse.jetty.util.ssl.SslContextFactory;
52 import org.onap.aaf.cadi.filter.CadiFilter;
53 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Http Server implementation using Embedded Jetty.
61 public abstract class JettyServletServer implements HttpServletServer, Runnable {
64 * Keystore/Truststore system property names.
66 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
67 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword"; // NOSONAR
68 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
69 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword"; // NOSONAR
74 private static final Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
76 private static final String NOT_SUPPORTED = " is not supported on this type of jetty server";
82 protected final String name;
85 * Server host address.
88 protected final String host;
91 * Server port to bind.
94 protected final int port;
97 * Should SNI host checking be done.
100 protected boolean sniHostCheck;
103 * Server auth username.
106 protected String user;
109 * Server auth password name.
112 protected String password;
115 * Server base context path.
117 protected final String contextPath;
120 * Embedded jetty server.
122 protected final Server jettyServer;
127 protected final ServletContextHandler context;
132 protected final ServerConnector connector;
137 protected Thread jettyThread;
140 * Container for default servlets.
142 protected final Map<String, ServletHolder> servlets = new HashMap<>();
148 protected final Object startCondition = new Object();
153 * @param name server name
154 * @param host server host
155 * @param port server port
156 * @param sniHostCheck SNI Host checking flag
157 * @param contextPath context path
159 * @throws IllegalArgumentException if invalid parameters are passed in
161 protected JettyServletServer(String name, boolean https, String host, int port, boolean sniHostCheck,
162 String contextPath) {
163 String srvName = name;
165 if (srvName == null || srvName.isEmpty()) {
166 srvName = "http-" + port;
169 if (port <= 0 || port >= 65535) {
170 throw new IllegalArgumentException("Invalid Port provided: " + port);
173 String srvHost = host;
174 if (srvHost == null || srvHost.isEmpty()) {
175 srvHost = "localhost";
178 String ctxtPath = contextPath;
179 if (ctxtPath == null || ctxtPath.isEmpty()) {
187 this.sniHostCheck = sniHostCheck;
189 this.contextPath = ctxtPath;
191 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
192 this.context.setContextPath(ctxtPath);
194 this.jettyServer = new Server();
196 var requestLog = new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
197 this.jettyServer.setRequestLog(requestLog);
200 this.connector = httpsConnector();
202 this.connector = httpConnector();
205 this.connector.setName(srvName);
206 this.connector.setReuseAddress(true);
207 this.connector.setPort(port);
208 this.connector.setHost(srvHost);
210 this.jettyServer.addConnector(this.connector);
211 this.jettyServer.setHandler(context);
214 protected JettyServletServer(String name, String host, int port, boolean sniHostCheck, String contextPath) {
215 this(name, false, host, port, sniHostCheck, contextPath);
219 public void addFilterClass(String filterPath, String filterClass) {
220 if (filterClass == null || filterClass.isEmpty()) {
221 throw new IllegalArgumentException("No filter class provided");
224 String tempFilterPath = filterPath;
225 if (filterPath == null || filterPath.isEmpty()) {
226 tempFilterPath = "/*";
229 context.addFilter(filterClass, tempFilterPath,
230 EnumSet.of(jakarta.servlet.DispatcherType.INCLUDE, jakarta.servlet.DispatcherType.REQUEST));
233 protected ServletHolder getServlet(@NonNull Class<? extends Servlet> servlet, @NonNull String servletPath) {
234 synchronized (servlets) {
235 return servlets.computeIfAbsent(servletPath, key -> context.addServlet(servlet, servletPath));
239 protected ServletHolder getServlet(String servletClass, String servletPath) {
240 synchronized (servlets) {
241 return servlets.computeIfAbsent(servletPath, key -> context.addServlet(servletClass, servletPath));
246 * Returns the https connector.
248 * @return the server connector
250 public ServerConnector httpsConnector() {
251 SslContextFactory.Server sslContextFactoryServer = new SslContextFactory.Server();
253 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
254 if (keyStore != null) {
255 sslContextFactoryServer.setKeyStorePath(keyStore);
257 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
258 if (ksPassword != null) {
259 sslContextFactoryServer.setKeyStorePassword(ksPassword);
263 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
264 if (trustStore != null) {
265 sslContextFactoryServer.setTrustStorePath(trustStore);
267 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
268 if (tsPassword != null) {
269 sslContextFactoryServer.setTrustStorePassword(tsPassword);
274 var httpsConfiguration = new HttpConfiguration();
275 SecureRequestCustomizer src = new SecureRequestCustomizer();
276 src.setSniHostCheck(sniHostCheck);
277 httpsConfiguration.addCustomizer(src);
279 return new ServerConnector(jettyServer, sslContextFactoryServer, new HttpConnectionFactory(httpsConfiguration));
282 public ServerConnector httpConnector() {
283 return new ServerConnector(this.jettyServer);
287 public void setAafAuthentication(String filterPath) {
288 this.addFilterClass(filterPath, CadiFilter.class.getName());
292 public boolean isAaf() {
293 for (FilterHolder filter : context.getServletHandler().getFilters()) {
294 if (CadiFilter.class.getName().equals(filter.getClassName())) {
302 public void setBasicAuthentication(String user, String password, String servletPath) {
303 String srvltPath = servletPath;
305 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
306 throw new IllegalArgumentException("Missing user and/or password");
309 if (srvltPath == null || srvltPath.isEmpty()) {
313 final var hashLoginService = new HashLoginService();
314 final var userStore = new UserStore();
315 userStore.addUser(user, Credential.getCredential(password), new String[] {
318 hashLoginService.setUserStore(userStore);
319 hashLoginService.setName(this.connector.getName() + "-login-service");
321 var constraint = new Constraint();
322 constraint.setName(Constraint.__BASIC_AUTH);
323 constraint.setRoles(new String[] {
326 constraint.setAuthenticate(true);
328 var constraintMapping = new ConstraintMapping();
329 constraintMapping.setConstraint(constraint);
330 constraintMapping.setPathSpec(srvltPath);
332 var securityHandler = new ConstraintSecurityHandler();
333 securityHandler.setAuthenticator(new BasicAuthenticator());
334 securityHandler.setRealmName(this.connector.getName() + "-realm");
335 securityHandler.addConstraintMapping(constraintMapping);
336 securityHandler.setLoginService(hashLoginService);
338 this.context.setSecurityHandler(securityHandler);
341 this.password = password;
345 * jetty server execution.
350 logger.info("{}: STARTING", this);
352 this.jettyServer.start();
354 if (logger.isTraceEnabled()) {
355 logger.trace("{}: STARTED: {}", this, this.jettyServer.dump());
358 synchronized (this.startCondition) {
359 this.startCondition.notifyAll();
362 this.jettyServer.join();
364 } catch (InterruptedException e) {
365 logger.error("{}: error found while bringing up server", this, e);
366 Thread.currentThread().interrupt();
368 } catch (Exception e) {
369 logger.error("{}: error found while bringing up server", this, e);
374 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
375 logger.info("{}: WAITED-START", this);
377 if (maxWaitTime < 0) {
378 throw new IllegalArgumentException("max-wait-time cannot be negative");
381 long pendingWaitTime = maxWaitTime;
387 synchronized (this.startCondition) {
389 while (!this.jettyServer.isRunning()) {
391 long startTs = System.currentTimeMillis();
393 this.startCondition.wait(pendingWaitTime);
395 if (maxWaitTime == 0) {
396 /* spurious notification */
400 long endTs = System.currentTimeMillis();
401 pendingWaitTime = pendingWaitTime - (endTs - startTs);
403 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
405 if (pendingWaitTime <= 0) {
409 } catch (InterruptedException e) {
410 logger.warn("{}: waited-start has been interrupted", this);
415 return this.jettyServer.isRunning();
420 public boolean start() {
421 logger.info("{}: STARTING", this);
423 synchronized (this) {
424 if (jettyThread == null || !this.jettyThread.isAlive()) {
426 this.jettyThread = new Thread(this);
427 this.jettyThread.setName(this.name + "-" + this.port);
428 this.jettyThread.start();
436 public boolean stop() {
437 logger.info("{}: STOPPING", this);
439 synchronized (this) {
440 if (jettyThread == null) {
444 if (!jettyThread.isAlive()) {
445 this.jettyThread = null;
449 this.connector.stop();
450 } catch (Exception e) {
451 logger.error("{}: error while stopping management server", this, e);
455 this.jettyServer.stop();
456 } catch (Exception e) {
457 logger.error("{}: error while stopping management server", this, e);
468 public void shutdown() {
469 logger.info("{}: SHUTTING DOWN", this);
473 Thread jettyThreadCopy;
474 synchronized (this) {
475 if ((jettyThreadCopy = this.jettyThread) == null) {
480 if (jettyThreadCopy.isAlive()) {
482 jettyThreadCopy.join(2000L);
483 } catch (InterruptedException e) {
484 logger.warn("{}: error while shutting down management server", this);
485 Thread.currentThread().interrupt();
487 if (!jettyThreadCopy.isInterrupted()) {
489 jettyThreadCopy.interrupt();
490 } catch (Exception e) {
492 logger.warn("{}: exception while shutting down (OK)", this, e);
497 this.jettyServer.destroy();
501 public boolean isAlive() {
502 if (this.jettyThread != null) {
503 return this.jettyThread.isAlive();
510 public void setSerializationProvider(String provider) {
511 throw new UnsupportedOperationException("setSerializationProvider()" + NOT_SUPPORTED);
515 public void addServletClass(String servletPath, String servletClass) {
516 throw new UnsupportedOperationException("addServletClass()" + NOT_SUPPORTED);
520 public void addStdServletClass(@NonNull String servletPath, @NonNull String plainServletClass) {
521 this.getServlet(plainServletClass, servletPath);
525 public void setPrometheus(String metricsPath) {
526 this.getServlet(MetricsServlet.class, metricsPath);
527 DefaultExports.initialize();
531 public boolean isPrometheus() {
532 for (ServletHolder servlet : context.getServletHandler().getServlets()) {
533 if (MetricsServlet.class.getName().equals(servlet.getClassName())) {
541 public void addServletPackage(String servletPath, String restPackage) {
542 throw new UnsupportedOperationException("addServletPackage()" + NOT_SUPPORTED);
546 public void addServletResource(String servletPath, String resourceBase) {
547 throw new UnsupportedOperationException("addServletResource()" + NOT_SUPPORTED);