6c29ae6e64abe653e7c985304b39d89c608f8cb8
[aaa.git] / web / impl-osgi / src / main / java / org / opendaylight / aaa / web / osgi / WhiteboardWebServer.java
1 /*
2  * Copyright (c) 2022 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.aaa.web.osgi;
9
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableMap;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.stream.Collectors;
17 import javax.servlet.Filter;
18 import javax.servlet.Servlet;
19 import javax.servlet.ServletContextListener;
20 import javax.servlet.ServletException;
21 import org.opendaylight.aaa.web.FilterDetails;
22 import org.opendaylight.aaa.web.ResourceDetails;
23 import org.opendaylight.aaa.web.ServletDetails;
24 import org.opendaylight.aaa.web.WebContext;
25 import org.opendaylight.aaa.web.WebServer;
26 import org.opendaylight.yangtools.concepts.AbstractRegistration;
27 import org.opendaylight.yangtools.concepts.Registration;
28 import org.osgi.framework.Bundle;
29 import org.osgi.framework.FrameworkUtil;
30 import org.osgi.framework.ServiceReference;
31 import org.osgi.framework.ServiceRegistration;
32 import org.osgi.service.component.ComponentContext;
33 import org.osgi.service.component.annotations.Activate;
34 import org.osgi.service.component.annotations.Component;
35 import org.osgi.service.component.annotations.Deactivate;
36 import org.osgi.service.component.annotations.Reference;
37 import org.osgi.service.component.annotations.ServiceScope;
38 import org.osgi.service.http.context.ServletContextHelper;
39 import org.osgi.service.http.runtime.HttpServiceRuntime;
40 import org.osgi.service.http.runtime.HttpServiceRuntimeConstants;
41 import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
42 import org.osgi.service.http.whiteboard.annotations.RequireHttpWhiteboard;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * {@link WebServer} implementation based on
48  * <a href="https://docs.osgi.org/specification/osgi.cmpn/7.0.0/service.http.whiteboard.html">OSGi HTTP Whiteboard</a>.
49  */
50 @RequireHttpWhiteboard
51 @Component(scope = ServiceScope.BUNDLE)
52 public final class WhiteboardWebServer implements WebServer {
53     private static final Logger LOG = LoggerFactory.getLogger(WhiteboardWebServer.class);
54
55     private final Bundle bundle;
56     @Reference
57     private volatile ServiceReference<HttpServiceRuntime> serviceRuntime;
58
59     /**
60      * Construct a {@link WhiteboardWebServer} to a {@link ComponentContext}.
61      *
62      * @param componentContext A {@link ComponentContext}
63      */
64     @Activate
65     public WhiteboardWebServer(final ComponentContext componentContext) {
66         bundle = componentContext.getUsingBundle();
67         LOG.debug("Activated WebServer for bundle {}", bundle);
68     }
69
70     @Deactivate
71     void deactivate() {
72         LOG.debug("Deactivated WebServer for bundle {}", bundle);
73     }
74
75     @Override
76     public String getBaseURL() {
77         final var endpoint = serviceRuntime.getProperty(HttpServiceRuntimeConstants.HTTP_SERVICE_ENDPOINT);
78         if (endpoint instanceof String str) {
79             return str;
80         } else if (endpoint instanceof String[] endpoints) {
81             return getBaseURL(Arrays.asList(endpoints));
82         } else if (endpoint instanceof Collection) {
83             // Safe as per OSGi Compendium R7 section 140.15.3.1
84             @SuppressWarnings("unchecked")
85             final var cast = (Collection<String>) endpoint;
86             return getBaseURL(cast);
87         } else {
88             throw new IllegalStateException("Unhandled endpoint " + endpoint);
89         }
90     }
91
92     private static String getBaseURL(final Collection<String> endpoints) {
93         for (var endpoint : endpoints) {
94             if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
95                 return endpoint;
96             }
97         }
98         throw new IllegalStateException("Cannot select base URL from " + endpoints);
99     }
100
101     @Override
102     public Registration registerWebContext(final WebContext webContext) throws ServletException {
103         final var bundleContext = bundle.getBundleContext();
104         final var builder = ImmutableList.<ServiceRegistration<?>>builder();
105
106         // The order in which we set things up here matters...
107
108         // 1. ServletContextHelper, to which all others are bound to
109         final var contextPath = absolutePath(webContext.contextPath());
110         // TODO: can we create a better name?
111         final var contextName = contextPath + ".id";
112
113         final var contextProps = contextProperties(contextName, contextPath, webContext.contextParams());
114         LOG.debug("Registering context {} with properties {}", contextName, contextProps);
115         builder.add(bundleContext.registerService(ServletContextHelper.class,
116             new WhiteboardServletContextHelper(bundle), FrameworkUtil.asDictionary(contextProps)));
117
118         // 2. Listeners - because they could set up things that filters and servlets need
119         final var contextSelect = "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + contextName + ")";
120         for (var listener : webContext.listeners()) {
121             final var props = Map.of(
122                 HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, contextSelect,
123                 HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER, "true");
124             LOG.debug("Registering listener {} with properties {}", listener, props);
125             builder.add(bundleContext.registerService(ServletContextListener.class, listener,
126                 FrameworkUtil.asDictionary(props)));
127         }
128
129         // 3. Filters - because subsequent servlets should already be covered by the filters
130         for (var filter : webContext.filters()) {
131             final var props = filterProperties(contextSelect, filter);
132             LOG.debug("Registering filter {} with properties {}", filter, props);
133             builder.add(bundleContext.registerService(Filter.class, filter.filter(),
134                 FrameworkUtil.asDictionary(props)));
135         }
136
137         // 4. Servlets - 'bout time for 'em by now, don't you think? ;)
138         for (var servlet : webContext.servlets()) {
139             final var props = servletProperties(contextSelect, servlet);
140             LOG.debug("Registering servlet {} with properties {}", servlet, props);
141             builder.add(bundleContext.registerService(Servlet.class, servlet.servlet(),
142                 FrameworkUtil.asDictionary(props)));
143         }
144
145         // 5. Resources
146         for (var resource : webContext.resources()) {
147             final var props = resourceProperties(contextSelect, resource);
148             LOG.debug("Registering resource {} with properties {}", resource, props);
149             builder.add(bundleContext.registerService(Object.class, WhiteboardResource.INSTANCE,
150                 FrameworkUtil.asDictionary(props)));
151         }
152
153         final var services = builder.build();
154         LOG.info("Bundle {} registered context path {} with {} service(s)", bundle, contextPath, services.size());
155         return new AbstractRegistration() {
156             @Override
157             protected void removeRegistration() {
158                 // The order does not have to be reversed: we unregister ServletContextHelper first, hence everybody
159                 // becomes unbound
160                 services.forEach(ServiceRegistration::unregister);
161             }
162         };
163     }
164
165     private static Map<String, Object> contextProperties(final String contextName, final String contextPath,
166             final Map<String, String> params) {
167         final var builder = ImmutableMap.<String, Object>builder()
168             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, contextName)
169             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, contextPath);
170
171         for (var e : params.entrySet()) {
172             builder.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_INIT_PARAM_PREFIX + e.getKey(), e.getValue());
173         }
174
175         return builder.build();
176     }
177
178     private static Map<String, Object> filterProperties(final String contextSelect, final FilterDetails filter) {
179         final var builder = ImmutableMap.<String, Object>builder()
180             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, contextSelect)
181             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_ASYNC_SUPPORTED, filter.getAsyncSupported())
182             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_NAME, filter.name())
183             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, absolutePatterns(filter.urlPatterns()));
184
185         for (var e : filter.initParams().entrySet()) {
186             builder.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_INIT_PARAM_PREFIX + e.getKey(), e.getValue());
187         }
188
189         return builder.build();
190     }
191
192     private static Map<String, Object> resourceProperties(final String contextSelect, final ResourceDetails resource) {
193         final var path = absolutePath(resource.name());
194         return Map.of(
195             HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, contextSelect,
196             HttpWhiteboardConstants.HTTP_WHITEBOARD_RESOURCE_PATTERN, path,
197             HttpWhiteboardConstants.HTTP_WHITEBOARD_RESOURCE_PREFIX, path);
198     }
199
200     private static Map<String, Object> servletProperties(final String contextSelect, final ServletDetails servlet) {
201         final var builder = ImmutableMap.<String, Object>builder()
202             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, contextSelect)
203             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ASYNC_SUPPORTED, servlet.getAsyncSupported())
204             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, servlet.name())
205             .put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, absolutePatterns(servlet.urlPatterns()));
206
207         for (var e : servlet.initParams().entrySet()) {
208             builder.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX + e.getKey(), e.getValue());
209         }
210
211         return builder.build();
212     }
213
214     private static String absolutePath(final String path) {
215         return path.startsWith("/") ? path : "/" + path;
216     }
217
218     private static List<String> absolutePatterns(final List<String> urlPatterns) {
219         return urlPatterns.stream()
220             // Reject duplicates
221             .distinct()
222             // Ease of debugging
223             .sorted()
224             .collect(Collectors.toUnmodifiableList());
225     }
226 }