2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7 * Modifications Copyright (C) 2020 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 java.util.EnumSet;
26 import javax.servlet.DispatcherType;
28 import lombok.ToString;
29 import org.eclipse.jetty.security.ConstraintMapping;
30 import org.eclipse.jetty.security.ConstraintSecurityHandler;
31 import org.eclipse.jetty.security.HashLoginService;
32 import org.eclipse.jetty.security.UserStore;
33 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
34 import org.eclipse.jetty.server.CustomRequestLog;
35 import org.eclipse.jetty.server.HttpConfiguration;
36 import org.eclipse.jetty.server.HttpConnectionFactory;
37 import org.eclipse.jetty.server.SecureRequestCustomizer;
38 import org.eclipse.jetty.server.Server;
39 import org.eclipse.jetty.server.ServerConnector;
40 import org.eclipse.jetty.server.Slf4jRequestLogWriter;
41 import org.eclipse.jetty.servlet.FilterHolder;
42 import org.eclipse.jetty.servlet.ServletContextHandler;
43 import org.eclipse.jetty.util.security.Constraint;
44 import org.eclipse.jetty.util.security.Credential;
45 import org.eclipse.jetty.util.ssl.SslContextFactory;
46 import org.onap.aaf.cadi.filter.CadiFilter;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Http Server implementation using Embedded Jetty.
55 public abstract class JettyServletServer implements HttpServletServer, Runnable {
58 * Keystore/Truststore system property names.
60 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
61 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword"; //NOSONAR
62 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
63 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword"; //NOSONAR
68 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
70 private static final String NOT_SUPPORTED = " is not supported on this type of jetty server";
76 protected final String name;
79 * Server host address.
82 protected final String host;
85 * Server port to bind.
88 protected final int port;
91 * Server auth user name.
94 protected String user;
97 * Server auth password name.
100 protected String password;
103 * Server base context path.
105 protected final String contextPath;
108 * Embedded jetty server.
110 protected final Server jettyServer;
115 protected final ServletContextHandler context;
120 protected final ServerConnector connector;
125 protected Thread jettyThread;
131 protected Object startCondition = new Object();
136 * @param name server name
137 * @param host server host
138 * @param port server port
139 * @param contextPath context path
141 * @throws IllegalArgumentException if invalid parameters are passed in
143 protected JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
144 String srvName = name;
146 if (srvName == null || srvName.isEmpty()) {
147 srvName = "http-" + port;
150 if (port <= 0 || port >= 65535) {
151 throw new IllegalArgumentException("Invalid Port provided: " + port);
154 String srvHost = host;
155 if (srvHost == null || srvHost.isEmpty()) {
156 srvHost = "localhost";
159 String ctxtPath = contextPath;
160 if (ctxtPath == null || ctxtPath.isEmpty()) {
169 this.contextPath = ctxtPath;
171 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
172 this.context.setContextPath(ctxtPath);
174 this.jettyServer = new Server();
176 var requestLog = new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
177 this.jettyServer.setRequestLog(requestLog);
180 this.connector = httpsConnector();
182 this.connector = httpConnector();
185 this.connector.setName(srvName);
186 this.connector.setReuseAddress(true);
187 this.connector.setPort(port);
188 this.connector.setHost(srvHost);
190 this.jettyServer.addConnector(this.connector);
191 this.jettyServer.setHandler(context);
194 protected JettyServletServer(String name, String host, int port, String contextPath) {
195 this(name, false, host, port, contextPath);
199 public void addFilterClass(String filterPath, String filterClass) {
200 if (filterClass == null || filterClass.isEmpty()) {
201 throw new IllegalArgumentException("No filter class provided");
204 String tempFilterPath = filterPath;
205 if (filterPath == null || filterPath.isEmpty()) {
206 tempFilterPath = "/*";
209 context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
213 * Returns the https connector.
215 * @return the server connector
217 public ServerConnector httpsConnector() {
218 SslContextFactory sslContextFactory = new SslContextFactory.Server();
220 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
221 if (keyStore != null) {
222 sslContextFactory.setKeyStorePath(keyStore);
224 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
225 if (ksPassword != null) {
226 sslContextFactory.setKeyStorePassword(ksPassword);
230 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
231 if (trustStore != null) {
232 sslContextFactory.setTrustStorePath(trustStore);
234 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
235 if (tsPassword != null) {
236 sslContextFactory.setTrustStorePassword(tsPassword);
240 var https = new HttpConfiguration();
241 https.addCustomizer(new SecureRequestCustomizer());
243 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
246 public ServerConnector httpConnector() {
247 return new ServerConnector(this.jettyServer);
251 public void setAafAuthentication(String filterPath) {
252 this.addFilterClass(filterPath, CadiFilter.class.getName());
256 public boolean isAaf() {
257 for (FilterHolder filter : context.getServletHandler().getFilters()) {
258 if (CadiFilter.class.getName().equals(filter.getClassName())) {
266 public void setBasicAuthentication(String user, String password, String servletPath) {
267 String srvltPath = servletPath;
269 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
270 throw new IllegalArgumentException("Missing user and/or password");
273 if (srvltPath == null || srvltPath.isEmpty()) {
277 final var hashLoginService = new HashLoginService();
278 final var userStore = new UserStore();
279 userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
280 hashLoginService.setUserStore(userStore);
281 hashLoginService.setName(this.connector.getName() + "-login-service");
283 var constraint = new Constraint();
284 constraint.setName(Constraint.__BASIC_AUTH);
285 constraint.setRoles(new String[] {"user"});
286 constraint.setAuthenticate(true);
288 var constraintMapping = new ConstraintMapping();
289 constraintMapping.setConstraint(constraint);
290 constraintMapping.setPathSpec(srvltPath);
292 var securityHandler = new ConstraintSecurityHandler();
293 securityHandler.setAuthenticator(new BasicAuthenticator());
294 securityHandler.setRealmName(this.connector.getName() + "-realm");
295 securityHandler.addConstraintMapping(constraintMapping);
296 securityHandler.setLoginService(hashLoginService);
298 this.context.setSecurityHandler(securityHandler);
301 this.password = password;
305 * jetty server execution.
310 logger.info("{}: STARTING", this);
312 this.jettyServer.start();
314 if (logger.isTraceEnabled()) {
315 logger.trace("{}: STARTED: {}", this, this.jettyServer.dump());
318 synchronized (this.startCondition) {
319 this.startCondition.notifyAll();
322 this.jettyServer.join();
324 } catch (InterruptedException e) {
325 logger.error("{}: error found while bringing up server", this, e);
326 Thread.currentThread().interrupt();
328 } catch (Exception e) {
329 logger.error("{}: error found while bringing up server", this, e);
334 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
335 logger.info("{}: WAITED-START", this);
337 if (maxWaitTime < 0) {
338 throw new IllegalArgumentException("max-wait-time cannot be negative");
341 long pendingWaitTime = maxWaitTime;
347 synchronized (this.startCondition) {
349 while (!this.jettyServer.isRunning()) {
351 long startTs = System.currentTimeMillis();
353 this.startCondition.wait(pendingWaitTime);
355 if (maxWaitTime == 0) {
356 /* spurious notification */
360 long endTs = System.currentTimeMillis();
361 pendingWaitTime = pendingWaitTime - (endTs - startTs);
363 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
365 if (pendingWaitTime <= 0) {
369 } catch (InterruptedException e) {
370 logger.warn("{}: waited-start has been interrupted", this);
375 return this.jettyServer.isRunning();
380 public boolean start() {
381 logger.info("{}: STARTING", this);
383 synchronized (this) {
384 if (jettyThread == null || !this.jettyThread.isAlive()) {
386 this.jettyThread = new Thread(this);
387 this.jettyThread.setName(this.name + "-" + this.port);
388 this.jettyThread.start();
396 public boolean stop() {
397 logger.info("{}: STOPPING", this);
399 synchronized (this) {
400 if (jettyThread == null) {
404 if (!jettyThread.isAlive()) {
405 this.jettyThread = null;
409 this.connector.stop();
410 } catch (Exception e) {
411 logger.error("{}: error while stopping management server", this, e);
415 this.jettyServer.stop();
416 } catch (Exception e) {
417 logger.error("{}: error while stopping management server", this, e);
428 public void shutdown() {
429 logger.info("{}: SHUTTING DOWN", this);
433 Thread jettyThreadCopy;
434 synchronized (this) {
435 if ((jettyThreadCopy = this.jettyThread) == null) {
440 if (jettyThreadCopy.isAlive()) {
442 jettyThreadCopy.join(2000L);
443 } catch (InterruptedException e) {
444 logger.warn("{}: error while shutting down management server", this);
445 Thread.currentThread().interrupt();
447 if (!jettyThreadCopy.isInterrupted()) {
449 jettyThreadCopy.interrupt();
450 } catch (Exception e) {
452 logger.warn("{}: exception while shutting down (OK)", this, e);
457 this.jettyServer.destroy();
461 public boolean isAlive() {
462 if (this.jettyThread != null) {
463 return this.jettyThread.isAlive();
470 public void setSerializationProvider(String provider) {
471 throw new UnsupportedOperationException("setSerializationProvider()" + NOT_SUPPORTED);
475 public void addServletClass(String servletPath, String restClass) {
476 throw new UnsupportedOperationException("addServletClass()" + NOT_SUPPORTED);
480 public void addServletPackage(String servletPath, String restPackage) {
481 throw new UnsupportedOperationException("addServletPackage()" + NOT_SUPPORTED);
485 public void addServletResource(String servletPath, String resourceBase) {
486 throw new UnsupportedOperationException("addServletResource()" + NOT_SUPPORTED);