Skip to content

Commit

Permalink
Merge pull request #364 from apache/maintenance/FELIX-6746-websockets…
Browse files Browse the repository at this point in the history
…ervlet-init-NPE

FELIX-6746 Lazy initialization for servlets extending JettyWebSocketServlet
  • Loading branch information
paulrutter authored Jan 22, 2025
2 parents 3854386 + 7612655 commit 0b53823
Show file tree
Hide file tree
Showing 16 changed files with 449 additions and 92 deletions.
1 change: 1 addition & 0 deletions http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,7 @@ properties can be used (some legacy property names still exist but are not docum
| `org.apache.felix.jetty.websocket.enable` | Enables Jetty websocket support. Default is false. |
| `org.apache.felix.http.jetty.threadpool.max` | The maximum number of threads in the Jetty thread pool. Default is unlimited. Works for both platform threads and virtual threads (Jetty 12 only). |
| `org.apache.felix.http.jetty.virtualthreads.enable` | Enables using virtual threads in Jetty 12 (JDK 21 required). Default is false. When enabled, `org.apache.felix.http.jetty.threadpool.max` is used for a bounded virtual thread pool. |
### Multiple Servers
It is possible to configure several Http Services, each running on a different port. The first service can be configured as outlined above using the service PID for `"org.apache.felix.http"`. Additional servers can be configured through OSGi factory configurations using `"org.apache.felix.http"` as the factory PID. The properties for the configuration are outlined as above.
Expand Down
6 changes: 6 additions & 0 deletions http/base/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -157,5 +157,11 @@
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.ee10.websocket</groupId>
<artifactId>jetty-ee10-websocket-jetty-server</artifactId>
<version>12.0.16</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ public void register(@NotNull final ServletContext containerContext, @NotNull fi
*/
public void setAttributeSharedServletContext(String key, Object value) {
this.whiteboardManager.setAttributeSharedServletContext(key, value);
this.httpServiceFactory.setAttributeSharedServletContext(key, value);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
/**
* Servlet handler for servlets registered through the http service.
*/
public final class HttpServiceServletHandler extends ServletHandler
public class HttpServiceServletHandler extends ServletHandler
{
/**
* New handler
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.felix.http.base.internal.handler;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;

import org.apache.felix.http.base.internal.context.ExtServletContext;
import org.apache.felix.http.base.internal.runtime.ServletInfo;

/**
* Servlet handler for servlets extending JettyWebSocketServlet registered through the http service.
*/
public final class HttpServiceWebSocketServletHandler extends HttpServiceServletHandler
{
private final WebSocketHandler webSocketHandler;

public HttpServiceWebSocketServletHandler(final ExtServletContext context,
final ServletInfo servletInfo,
final javax.servlet.Servlet servlet)
{
super(context, servletInfo, servlet);
this.webSocketHandler = new WebSocketHandler(this);
}

@Override
public int init() {
if (webSocketHandler.shouldInit()) {
return super.init();
}
// do nothing, delay init until first service call
return -1;
}

@Override
public void handle(ServletRequest req, ServletResponse res) throws ServletException, IOException {
this.webSocketHandler.lazyInit();
super.handle(req, res);
}

@Override
public boolean destroy() {
if (webSocketHandler.shouldDestroy()) {
return super.destroy();
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,14 @@ public int init()
catch (final Exception e)
{
SystemLogger.LOGGER.error(SystemLogger.formatMessage(this.getServletInfo().getServiceReference(),
"Error during calling init() on servlet ".concat(this.servletInfo.getClassName(this.servlet))),
"Error during calling init() on servlet ".concat(this.servletInfo.getClassName(this.servlet))),
e);
return DTOConstants.FAILURE_REASON_EXCEPTION_ON_INIT;
}
this.useCount++;
return -1;
}


public boolean destroy()
{
if (this.servlet == null)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.felix.http.base.internal.handler;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.felix.http.base.internal.logger.SystemLogger;

/**
* Class that handles initialization for servlets extending JettyWebSocketServlet.
*/
public final class WebSocketHandler {
// The Jetty class used for Jetty WebSocket servlets
private static final String JETTY_WEB_SOCKET_SERVLET_CLASS = "JettyWebSocketServlet";

private final AtomicBoolean lazyFirstInitCall = new AtomicBoolean(true);
private final CountDownLatch initBarrier = new CountDownLatch(1);
private final ServletHandler servletHandler;

public WebSocketHandler(ServletHandler servletHandler) {
this.servletHandler = servletHandler;
}

/*
* Lazy initialization of the servlet.
* Will only be called once for each servlet instance and is thread-safe.
*/
public void lazyInit() {
if (lazyFirstInitCall.compareAndSet(true, false)) {
try {
this.servletHandler.init();
} catch (final Exception e) {
SystemLogger.LOGGER.error(SystemLogger.formatMessage(
this.servletHandler.getServletInfo().getServiceReference(),
"Error calling init() lazy on servlet ".concat(
this.servletHandler.getServletInfo().getClassName(this.servletHandler.getServlet()))), e);
} finally {
initBarrier.countDown();
}
} else {
// already initialized, await the first initialization
try {
initBarrier.await();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

/**
* Returns true if the servlet should be initialized, false otherwise.
* @return true if the servlet should be initialized, false otherwise
*/
public boolean shouldInit() {
return !lazyFirstInitCall.get() && initBarrier.getCount() > 0;
}

/**
* Returns true if the servlet was initialized earlier, false otherwise.
* @return true if the servlet should be destroyed, false otherwise
*/
public boolean shouldDestroy() {
if (!lazyFirstInitCall.get()){
try {
initBarrier.await();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
return true;
}
return false;
}

/**
* Check if the servlet is a JettyWebSocketServlet.
* JettyWebSocket classes are handled differently due to FELIX-6746.
* @param servlet the servlet to check
* @return true if the servlet is a JettyWebSocketServlet, false otherwise
*/
public static boolean isJettyWebSocketServlet(Object servlet) {
final Class<?> superClass = servlet.getClass().getSuperclass();
SystemLogger.LOGGER.debug("Checking if the servlet is a JettyWebSocketServlet: '" + superClass.getSimpleName() + "'");

// Now check if the servlet class extends 'JettyWebSocketServlet'
boolean isJettyWebSocketServlet = superClass.getSimpleName().endsWith(JETTY_WEB_SOCKET_SERVLET_CLASS);
if (!isJettyWebSocketServlet) {
// Recurse through the wrapped servlets, in case of double-wrapping
if (servlet instanceof org.apache.felix.http.jakartawrappers.ServletWrapper) {
final javax.servlet.Servlet wrappedServlet = ((org.apache.felix.http.jakartawrappers.ServletWrapper) servlet).getServlet();
return isJettyWebSocketServlet(wrappedServlet);
} else if (servlet instanceof org.apache.felix.http.javaxwrappers.ServletWrapper) {
final jakarta.servlet.Servlet wrappedServlet = ((org.apache.felix.http.javaxwrappers.ServletWrapper) servlet).getServlet();
return isJettyWebSocketServlet(wrappedServlet);
}
}
return isJettyWebSocketServlet;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
/**
* Servlet handler for servlets registered through the http whiteboard.
*/
public final class WhiteboardServletHandler extends ServletHandler
public class WhiteboardServletHandler extends ServletHandler
{
private final BundleContext bundleContext;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.felix.http.base.internal.handler;

import java.io.FilePermission;
import java.io.IOException;

import jakarta.servlet.Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;

import org.apache.felix.http.base.internal.context.ExtServletContext;
import org.apache.felix.http.base.internal.logger.SystemLogger;
import org.apache.felix.http.base.internal.runtime.ServletInfo;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.servlet.runtime.dto.DTOConstants;

/**
* Servlet handler for servlets extending JettyWebSocketServlet registered through the http whiteboard.
*/
public final class WhiteboardWebSocketServletHandler extends WhiteboardServletHandler
{
private final WebSocketHandler webSocketHandler;

public WhiteboardWebSocketServletHandler(final long contextServiceId,
final ExtServletContext context,
final ServletInfo servletInfo,
final BundleContext contextBundleContext,
final Bundle registeringBundle,
final Bundle httpWhiteboardBundle,
final Object servlet)
{
super(contextServiceId, context, servletInfo, contextBundleContext, registeringBundle, httpWhiteboardBundle);
this.webSocketHandler = new WebSocketHandler(this);
this.setServlet((Servlet) servlet);
}

@Override
public int init() {
if (webSocketHandler.shouldInit()) {
return super.init();
}
// do nothing, delay init until first service call
return -1;
}

@Override
public void handle(ServletRequest req, ServletResponse res) throws ServletException, IOException {
this.webSocketHandler.lazyInit();
super.handle(req, res);
}

@Override
public boolean destroy() {
if (webSocketHandler.shouldDestroy()) {
return super.destroy();
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@
*/
package org.apache.felix.http.base.internal.service;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import org.apache.felix.http.base.internal.logger.SystemLogger;
import org.apache.felix.http.base.internal.registry.HandlerRegistry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
Expand Down Expand Up @@ -76,6 +80,7 @@ public final class HttpServiceFactory
private final HandlerRegistry handlerRegistry;
private volatile SharedHttpServiceImpl sharedHttpService;

private volatile Map<String, Object> attributesForSharedContext = new HashMap<>();

public HttpServiceFactory(final BundleContext bundleContext,
final HandlerRegistry handlerRegistry)
Expand All @@ -101,6 +106,7 @@ public void start(final ServletContext context,
this.context = context;

this.sharedHttpService = new SharedHttpServiceImpl(handlerRegistry);
this.sharedHttpService.setSharedContextAttributes(attributesForSharedContext);

this.active = true;
this.httpServiceReg = bundleContext.registerService(HttpService.class, this, this.httpServiceProps);
Expand All @@ -120,6 +126,7 @@ public void stop()
this.sharedHttpService = null;

this.httpServiceProps.clear();
this.attributesForSharedContext.clear();
}

@Override
Expand Down Expand Up @@ -160,6 +167,11 @@ public long getHttpServiceServiceId()
return (Long) this.httpServiceReg.getReference().getProperty(Constants.SERVICE_ID);
}

public void setAttributeSharedServletContext(String key, Object value) {
SystemLogger.LOGGER.info("HttpServiceFactory: Storing attribute for shared servlet context. Key '{}', value: '{}'", key, value);
this.attributesForSharedContext.put(key, value);
}

private boolean getBoolean(final String property)
{
String prop = this.bundleContext.getProperty(property);
Expand Down
Loading

0 comments on commit 0b53823

Please sign in to comment.