001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.microservice.tomcat; 018 019import static org.apache.juneau.commons.reflect.ReflectionUtils.*; 020import static org.apache.juneau.commons.utils.FileUtils.*; 021import static org.apache.juneau.commons.utils.ObjectUtils.*; 022import static org.apache.juneau.commons.utils.Shorts.*; 023import static org.apache.juneau.commons.utils.StringUtils.*; 024import static org.apache.juneau.commons.utils.ThrowableUtils.*; 025import static org.apache.juneau.marshall.collections.JsonMap.*; 026 027import java.io.*; 028import java.net.*; 029import java.nio.file.*; 030import java.nio.file.attribute.*; 031import java.time.*; 032import java.util.*; 033import java.util.concurrent.*; 034import java.util.concurrent.atomic.*; 035import java.util.logging.*; 036 037import org.apache.catalina.*; 038import org.apache.catalina.startup.*; 039import org.apache.coyote.*; 040import org.apache.juneau.commons.inject.*; 041import org.apache.juneau.commons.reflect.*; 042import org.apache.juneau.config.event.*; 043import org.apache.juneau.marshall.cp.*; 044import org.apache.juneau.microservice.*; 045import org.apache.juneau.rest.server.*; 046import org.apache.juneau.rest.server.health.*; 047import org.apache.juneau.rest.server.servlet.*; 048import org.apache.tomcat.util.descriptor.web.*; 049 050import jakarta.servlet.*; 051 052/** 053 * Drives the embedded Tomcat server lifecycle on behalf of the microservice via the {@link MicroserviceListener} fan-out. 054 * 055 * <p> 056 * Contributed by {@link TomcatConfiguration} as a <c>@Bean</c>. The microservice's {@link Microservice#start()} 057 * call invokes {@link #onStart(Microservice)}, which: 058 * <ol> 059 * <li>Picks the first available port from the resolved {@link TomcatSettings#getPorts() ports} (falling back to 060 * <c>Tomcat/port</c> config, then <c>Tomcat-Port</c> manifest, then <c>8000</c>). 061 * <li>Resolves the {@link Tomcat} instance — preferring an externally-supplied <c>@Bean Tomcat</c>, otherwise 062 * building one programmatically via the {@link TomcatServerFactory} against a writable base directory. 063 * <li>Mounts servlets from {@code Tomcat/servlets}, {@code Tomcat/servletMap}, {@code Tomcat/servletAttributes} 064 * config sections, plus auto-mounts every {@code @Bean Servlet} whose runtime class is annotated with 065 * {@link Rest @Rest} (at {@link Rest#path()}, or <c>"/"</c> when no path is set). 066 * <li>Mounts every <c>@Bean</c> {@link ServletFilterRegistration} (and the <c>@Bean</c> <c>AuthFilterChain</c>, at 067 * <c>/*</c>, unless a registration already wraps it) in {@link ServletFilterRegistration#getOrder() order}. 068 * <li>Materializes the connector via {@link Tomcat#getConnector()}, starts the server, and publishes the bound 069 * port via the {@code availablePort} / {@code juneau.serverPort} system properties. 070 * </ol> 071 * 072 * <p> 073 * {@link #onStop(Microservice)} performs the inverse: stops and destroys the server gracefully in a worker thread, 074 * then deletes the auto-created temp base directory (if one was created). 075 * 076 * <p> 077 * External callers reach this component via 078 * {@code Microservice.getInstance().getBeanStore().getBean(TomcatServerComponent.class).orElseThrow()}. 079 * 080 * <h2 class='section'>See Also:</h2><ul> 081 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauMicroserviceTomcat">juneau-microservice-tomcat</a> 082 * </ul> 083 * 084 * @since 10.0.0 085 */ 086@SuppressWarnings({ 087 "java:S115", // Constants use UPPER_SNAKE_CASE convention (e.g., ROOT_CONTEXT_PATH) 088 "java:S3878", // Array wrapper required to dispatch to varargs overload; without it the call recurses infinitely back to this single-String overload. 089 "resource" // The Tomcat server is held by this component and closed in onStop(); its lifecycle spans onStart/onStop, so it cannot be try-with-resources. Eclipse JDT @Owning warning is by design. 090}) 091public class TomcatServerComponent implements MicroserviceListener { 092 093 @SuppressWarnings({ 094 "java:S2245" // Non-security use: port-selection jitter only; not used for tokens, session IDs, or any security-sensitive purpose. 095 }) 096 private static final Random RANDOM = new Random(); 097 private static final String ROOT_CONTEXT_PATH = ""; 098 private static final String ROOT_DOC_BASE = "."; 099 100 /** Default bounded graceful-shutdown drain timeout applied when none is configured. */ 101 static final Duration DEFAULT_STOP_TIMEOUT = Duration.ofSeconds(30); 102 103 private final Messages messages = Messages.of(TomcatServerComponent.class); 104 private final AtomicReference<Tomcat> tomcat = new AtomicReference<>(); 105 private final AtomicReference<Microservice> microservice = new AtomicReference<>(); 106 private final AtomicReference<File> baseDir = new AtomicReference<>(); 107 private final AtomicBoolean ownsBaseDir = new AtomicBoolean(false); 108 private final AtomicReference<Duration> stopTimeout = new AtomicReference<>(DEFAULT_STOP_TIMEOUT); 109 private final AtomicReference<Duration> shutdownSettleDelay = new AtomicReference<>(Duration.ZERO); 110 111 /** 112 * Env-driven sentinel for {@code availablePort}; {@link Optional#empty()} when unset (in which case 113 * {@link #onStart(Microservice)} publishes the bound port back as the {@code availablePort} system property). 114 */ 115 @Value("${availablePort}") 116 Optional<String> availablePortEnv = oe(); 117 118 /** 119 * Env-driven sentinel for {@code juneau.serverPort}; {@link Optional#empty()} when unset (in which case 120 * {@link #onStart(Microservice)} publishes the bound port back as the {@code juneau.serverPort} system property). 121 */ 122 @Value("${juneau.serverPort}") 123 Optional<String> serverPortEnv = oe(); 124 125 private static int[] parseIntArray(String csv) { 126 if (ie(csv)) 127 return new int[0]; 128 var parts = csv.split(","); 129 var out = new int[parts.length]; 130 for (var i = 0; i < parts.length; i++) 131 out[i] = Integer.parseInt(parts[i].trim()); 132 return out; 133 } 134 135 private static int findOpenPort(int[] ports, String bindAddress) { 136 for (var port : ports) { 137 if (port == 0) 138 port = RANDOM.nextInt(32767 - ports[0] + 1) + ports[0]; 139 try (var ss = new ServerSocket(port, 50, InetAddress.getByName(bindAddress))) { 140 return port; 141 } catch (IOException e) { 142 // Port is in use, try next port in array 143 } 144 } 145 return 0; 146 } 147 148 private static String normalizePathSpec(String rawPath) { 149 var p = rawPath == null ? "" : rawPath; 150 if (p.isEmpty() || eq(p, "/")) 151 return "/*"; 152 if (! p.startsWith("/")) 153 p = "/" + p; 154 if (! p.endsWith("/*")) 155 p = trimTrailingSlashes(p) + "/*"; 156 return p; 157 } 158 159 private static String normalizeExactPathSpec(String rawPath) { 160 var p = rawPath == null ? "" : trimTrailingSlashes(rawPath); 161 if (p.isEmpty()) 162 return "/"; 163 if (! p.startsWith("/")) 164 p = "/" + p; 165 return p; 166 } 167 168 /** 169 * Resolves the top-level Tomcat mount path-specs for an auto-discovered {@code @Rest}-annotated servlet. 170 * 171 * <p> 172 * Delegates to {@link RestContext#resolveTopLevelPaths(Class, Object, BeanStore)} so the runtime-override 173 * resolution chain (programmatic > {@code getPaths()} getter > annotation default) is honored at 174 * mount time. The programmatic Builder rung is N/A for Tomcat auto-discovery (the {@code RestContext} does 175 * not exist yet at this point in the lifecycle); users can substitute by overriding {@code getPaths()} on 176 * the resource class, or by leaning on SVL inside {@code @Rest(paths=...)} elements (e.g. 177 * {@code paths={"${C:health.paths}"}}) so each element is resolved through {@code Config} / 178 * {@code ${E:...}} / {@code ${S:...}} before being comma-split. 179 * 180 * @return The normalized exact-match path-specs (for multi-mount), or the singular {@code @Rest(path)}-style 181 * {@code "/.../*"} pathspec when no {@code paths} are resolved. 182 */ 183 private static String[] restPathsFor(Servlet servlet, BeanStore store) { 184 var cls = servlet.getClass(); 185 var r = cls.getAnnotation(Rest.class); 186 if (r == null) 187 return new String[] {"/*"}; 188 var resolved = RestContext.resolveTopLevelPaths(cls, servlet, store); 189 if (resolved.length > 0) 190 return Arrays.stream(resolved).map(TomcatServerComponent::normalizeExactPathSpec).toArray(String[]::new); 191 return new String[] {normalizePathSpec(r.path())}; 192 } 193 194 /** 195 * Constructor. 196 */ 197 @SuppressWarnings({ 198 "java:S1186" // Empty constructor; all state is initialized via onStart(Microservice) when wired through the bean store. 199 }) 200 public TomcatServerComponent() {} 201 202 @Override /* Overridden from MicroserviceListener */ 203 @SuppressWarnings({ 204 "java:S3776" // Cognitive complexity acceptable for server creation logic 205 }) 206 public void onStart(Microservice ms) { 207 try { 208 microservice.set(ms); 209 var store = ms.getBeanStore(); 210 ClassInfo.of(this).inject(this, store); 211 var cf = ms.getConfig(); 212 var mf = ms.getManifest(); 213 var settings = store.getBean(TomcatSettings.class).orElseGet(() -> TomcatSettings.create().build()); 214 215 // Port resolution: settings > Tomcat/port config > Tomcat-Port manifest > 8000 216 var ports = settings.getPorts(); 217 if (ports == null) 218 ports = cf.get("Tomcat/port").as(int[].class) 219 .orElseGet(() -> mf.get("Tomcat-Port").map(TomcatServerComponent::parseIntArray).orElseGet(() -> ints(8000))); 220 // Binds to the loopback interface by default; set the juneau.bindAddress system property to listen elsewhere. 221 var bindAddress = System.getProperty("juneau.bindAddress", "127.0.0.1"); 222 var availablePort = findOpenPort(ports, bindAddress); 223 224 if (availablePortEnv.isEmpty()) 225 // Intentional real-JVM-property publish: the bound port is exposed as a process-global system 226 // property so external config/templates (e.g. the bundled jetty.xml's ${S:availablePort}) can read 227 // it. The ${S:...} SVL var resolves via raw System.getProperty (bypassing the Settings override 228 // chain), so a Settings-based write would be invisible to those consumers. The @Value-injected 229 // availablePortEnv read side is already Settings-abstracted; only this publish must stay raw. 230 System.setProperty("availablePort", String.valueOf(availablePort)); 231 232 // Prefer a @Bean-supplied Tomcat, else build one programmatically via the factory. 233 var injectedTomcat = store.getBean(Tomcat.class).orElse(null); 234 if (nn(injectedTomcat)) { 235 tomcat.set(injectedTomcat); 236 } else { 237 var factory = store.getBean(TomcatServerFactory.class).orElseGet(BasicTomcatServerFactory::new); 238 tomcat.set(createServer(factory, resolveBaseDir(settings))); 239 } 240 tomcat.get().setPort(availablePort); 241 var connector = tomcat.get().getConnector(); 242 if (connector.getProtocolHandler() instanceof AbstractProtocol<?> ap) 243 ap.setAddress(InetAddress.getByName(bindAddress)); 244 245 // Publish back to the store for downstream beans / lookups. 246 store.addBean(Tomcat.class, tomcat.get()); 247 248 // Graceful-shutdown wiring (zero-downtime k8s rollouts), kept identical to the Jetty contract: 249 // - Resolve the bounded drain timeout (TomcatSettings > Tomcat/stopTimeout config > 30s default) so 250 // onStop() can wait for in-flight requests to complete before the server stops. 251 // - Remember the settle delay so onStop() can let the LB observe the /readyz 503 before draining. 252 // - Mark readiness ready so a freshly-(re)started service serves traffic. 253 stopTimeout.set(coalesce(settings.getStopTimeout(), cf.get("Tomcat/stopTimeout").asLong().map(Duration::ofMillis).orElse(DEFAULT_STOP_TIMEOUT))); 254 shutdownSettleDelay.set(coalesce(settings.getShutdownSettleDelay(), cf.get("Tomcat/shutdownSettleDelay").asLong().map(Duration::ofMillis).orElse(Duration.ZERO))); 255 256 // Per-service readiness: reuse an app/test-supplied @Bean ReadinessState if present, else construct 257 // one, and publish it into this microservice's bean store. shared() is intentionally NOT used here: 258 // it is one JVM-wide singleton, so falling back to it would leak this service's readiness into every 259 // other default-configured microservice in the same JVM. The health-probe servlet side of this 260 // dual-store publish happens below, in the @Rest servlet auto-discovery loop. 261 var readinessState = store.getBean(ReadinessState.class).orElseGet(ReadinessState::new); 262 store.addBean(ReadinessState.class, readinessState); 263 readinessState.markReady(); 264 265 // Track each servlet pathSpec with its declaring source so we can fail loudly on collisions. 266 var mountedPaths = new LinkedHashMap<String,String>(); 267 268 for (var s : cf.get("Tomcat/servlets").asStringArray().orElse(new String[0])) 269 mountConfiguredServlet(s, mountedPaths); 270 271 cf.get("Tomcat/servletMap").asMap().orElse(EMPTY_MAP).forEach((k, v) -> mountMappedServlet(k, v, mountedPaths)); 272 273 cf.get("Tomcat/servletAttributes").asMap().orElse(EMPTY_MAP).forEach(this::addServletAttribute); 274 275 // Mount the @Bean ServletFilterRegistration filters, plus the @Bean AuthFilterChain at /* unless a 276 // registration already wraps it, outermost first. Filter matching does not depend on whether the 277 // servlets or the filters were added first, so mounting after the config-sourced servlets is fine. 278 for (var registration : ServletFilterRegistration.collect(store)) 279 addFilter(registration); 280 281 // Auto-discover @Rest servlets contributed via @Configuration/@Bean methods. 282 // Path source precedence: @Rest(path=...) on the resource class, else "/". 283 for (var e : store.getBeansOfType(Servlet.class).entrySet()) { 284 var servlet = e.getValue(); 285 var cls = servlet.getClass(); 286 if (cls.getAnnotation(Rest.class) == null) 287 continue; 288 if (servlet instanceof HealthServlet hs) 289 // Dual-store publish (READY-394): this probe's own RestContext bean store is not linked to 290 // ms.getBeanStore(), so the lifecycle-owned instance must be handed to it explicitly before 291 // it initializes; HealthServlet.initReadinessState() registers it into its own bean store. 292 hs.publishReadinessState(readinessState); 293 if (servlet instanceof ReadinessStateAware rsa) 294 // Lets servlets holding long-lived streams (e.g. MCP subscriptions/listen) end them when shutdown 295 // begins, so the graceful drain does not wait out the full stopTimeout for them. 296 rsa.acceptReadinessState(readinessState); 297 var pathSpecs = restPathsFor(servlet, store); 298 var source = "@Bean " + cls.getName() + (ine(e.getKey()) ? "[" + e.getKey() + "]" : ""); 299 for (var pathSpec : pathSpecs) 300 checkPathCollision(pathSpec, source, mountedPaths); 301 addServlet(servlet, pathSpecs); 302 } 303 304 if (serverPortEnv.isEmpty()) 305 // Intentional real-JVM-property publish: juneau.serverPort is a documented cross-component/external 306 // publication of the bound port, consumed via raw System.getProperty (and ${S:...} SVL). A 307 // Settings-based write would not be visible to those raw readers, so this is kept. The 308 // @Value-injected serverPortEnv read side is already Settings-abstracted. 309 System.setProperty("juneau.serverPort", String.valueOf(availablePort)); 310 311 tomcat.get().start(); 312 ms.out(messages, "ServerStarted", getPort()); 313 } catch (Exception e) { 314 throw toRex(e); 315 } 316 } 317 318 @Override /* Overridden from MicroserviceListener */ 319 public void onStop(Microservice ms) { 320 final Logger logger = ms.getLogger(); 321 // Flip readiness out of service BEFORE the connector stops so /readyz returns 503 and the load balancer / 322 // Kubernetes stops routing new traffic while in-flight requests drain. /livez stays healthy so the pod is 323 // not killed mid-drain. The settle delay (default 0) gives the LB a window to observe the 503. 324 ReadinessState.resolve(ms.getBeanStore()).markOutOfService(); 325 ms.out(messages, "DrainingRequests"); 326 sleepQuietly(shutdownSettleDelay.get()); 327 var t = new Thread("TomcatServerComponentStop") { 328 @Override /* Overridden from Thread */ 329 public void run() { 330 try { 331 var t2 = tomcat.get(); 332 if (t2 == null) 333 return; 334 drainConnector(t2, stopTimeout.get(), logger); 335 ms.out(messages, "StoppingServer"); 336 t2.stop(); 337 t2.destroy(); 338 ms.out(messages, "ServerStopped"); 339 } catch (Exception e) { 340 logger.log(Level.WARNING, localizedMessage(e), e); 341 } finally { 342 cleanupBaseDir(); 343 } 344 } 345 }; 346 t.start(); 347 try { 348 t.join(); 349 } catch (InterruptedException e) { 350 Thread.currentThread().interrupt(); 351 } 352 } 353 354 /** 355 * Pauses the connector (stops accepting new connections) and waits up to {@code timeout} for in-flight requests 356 * to drain before the caller stops the server. Best-effort: never throws out of the shutdown sequence. 357 */ 358 private static void drainConnector(Tomcat t2, Duration timeout, Logger logger) { 359 try { 360 var connector = t2.getConnector(); 361 if (connector == null) 362 return; 363 connector.pause(); 364 var executor = connector.getProtocolHandler() == null ? null : connector.getProtocolHandler().getExecutor(); 365 if (executor instanceof ThreadPoolExecutor executor2) { 366 var deadline = System.nanoTime() + Math.max(0L, timeout.toNanos()); 367 while (executor2.getActiveCount() > 0 && System.nanoTime() < deadline) { 368 if (sleepInterruptibly(50L)) 369 return; 370 } 371 } 372 } catch (Exception e) { 373 logger.log(Level.WARNING, localizedMessage(e), e); 374 } 375 } 376 377 private static void sleepQuietly(Duration d) { 378 if (d == null || d.isZero() || d.isNegative()) 379 return; 380 try { 381 Thread.sleep(d.toMillis()); 382 } catch (@SuppressWarnings("unused") InterruptedException e) { 383 Thread.currentThread().interrupt(); 384 } 385 } 386 387 private static boolean sleepInterruptibly(long millis) { 388 try { 389 Thread.sleep(millis); 390 return false; 391 } catch (@SuppressWarnings("unused") InterruptedException e) { 392 Thread.currentThread().interrupt(); 393 return true; 394 } 395 } 396 397 @Override /* Overridden from MicroserviceListener */ 398 public void onConfigChange(Microservice ms, ConfigEvents events) { 399 // No-op: Intentional empty implementation - this component is purely lifecycle-driven. 400 } 401 402 /** 403 * Adds an arbitrary servlet to this Tomcat server. 404 * 405 * @param servlet The servlet instance. 406 * @param pathSpec The context path of the servlet. 407 * @return This object. 408 */ 409 public TomcatServerComponent addServlet(Servlet servlet, String pathSpec) { 410 return addServlet(servlet, new String[]{normalizePathSpec(pathSpec)}); 411 } 412 413 /** 414 * Adds an arbitrary servlet to this Tomcat server at one or more context paths. 415 * 416 * <p> 417 * The servlet is registered async-capable (Tomcat's default is off), so that 418 * {@link jakarta.servlet.http.HttpServletRequest#startAsync()} and asynchronous REST operations work, matching Jetty. 419 * 420 * @param servlet The servlet instance. 421 * @param pathSpecs The context paths of the servlet. 422 * @return This object. 423 */ 424 @SuppressWarnings({ 425 "deprecation" // Context.addServletMappingDecoded is deprecated in Tomcat 11 in favor of Wrapper.addMapping, which does not populate Context.findServletMappings() during embed startup. 426 }) 427 public TomcatServerComponent addServlet(Servlet servlet, String...pathSpecs) { 428 var context = getContext(); 429 var servletName = cn(servlet) + "#" + UUID.randomUUID(); 430 var wrapper = Tomcat.addServlet(context, servletName, servlet); 431 wrapper.setAsyncSupported(true); 432 for (var pathSpec : pathSpecs) 433 context.addServletMappingDecoded(pathSpec, servletName); 434 return this; 435 } 436 437 /** 438 * Adds a servlet filter to this Tomcat server at the specified URL pattern. 439 * 440 * @param filter The filter instance. 441 * @param urlPattern The URL pattern the filter applies to (e.g. {@code "/*"}, {@code "/api/*"}). 442 * @return This object. 443 */ 444 public TomcatServerComponent addFilter(jakarta.servlet.Filter filter, String urlPattern) { 445 return addFilter(filter, new String[]{urlPattern}); 446 } 447 448 /** 449 * Adds a servlet filter to this Tomcat server at one or more URL patterns. 450 * 451 * @param filter The filter instance. 452 * @param urlPatterns The URL patterns the filter applies to. 453 * @return This object. 454 */ 455 public TomcatServerComponent addFilter(jakarta.servlet.Filter filter, String...urlPatterns) { 456 var context = getContext(); 457 var filterName = cn(filter) + "#" + UUID.randomUUID(); 458 var fd = new FilterDef(); 459 fd.setFilter(filter); 460 fd.setFilterName(filterName); 461 context.addFilterDef(fd); 462 for (var pattern : urlPatterns) { 463 var fm = new FilterMap(); 464 fm.setFilterName(filterName); 465 fm.addURLPattern(pattern); 466 fm.setDispatcher(DispatcherType.REQUEST.name()); 467 context.addFilterMap(fm); 468 } 469 return this; 470 } 471 472 /** 473 * Adds a servlet filter registration to this Tomcat server. 474 * 475 * <p> 476 * Maps the filter on every URL pattern and dispatcher type of the registration with one filter map, and sets exactly 477 * the requested dispatcher types. Mapping order is call order, so call this outermost first. 478 * 479 * <p> 480 * Applications contribute a {@link ServletFilterRegistration} <c>@Bean</c> instead; {@link #onStart(Microservice)} 481 * applies the beans through this method in {@link ServletFilterRegistration#getOrder() order}. Calling it directly 482 * is only possible once the server object exists (during startup) and before the server runs. 483 * 484 * @param registration The registration. Cannot be <jk>null</jk>. 485 * @return This object. 486 * @throws IllegalArgumentException If the registration is <jk>null</jk>. 487 * @throws IllegalStateException If the server has already started. 488 */ 489 public TomcatServerComponent addFilter(ServletFilterRegistration registration) { 490 if (registration == null) 491 throw iaex("registration must not be null."); 492 var context = getContext(); 493 var state = context.getState(); 494 if (state != LifecycleState.NEW && state != LifecycleState.INITIALIZED) 495 throw isex("Filters must be added before the server starts."); 496 var filter = registration.getFilter(); 497 var filterName = registration.getName().orElseGet(() -> cn(filter) + "#" + UUID.randomUUID()); 498 var fd = new FilterDef(); 499 fd.setFilter(filter); 500 fd.setFilterName(filterName); 501 fd.setAsyncSupported(String.valueOf(registration.isAsyncSupported())); 502 context.addFilterDef(fd); 503 var fm = new FilterMap(); 504 fm.setFilterName(filterName); 505 for (var pattern : registration.getUrlPatterns()) 506 fm.addURLPattern(pattern); 507 for (var type : registration.getDispatcherTypes()) 508 fm.setDispatcher(type.name()); 509 context.addFilterMap(fm); 510 return this; 511 } 512 513 /** 514 * Adds a servlet filter to this Tomcat server on the given dispatcher types and URL patterns. 515 * 516 * <p> 517 * Shorthand for {@link #addFilter(ServletFilterRegistration)} with the default order and async support, and the same 518 * validation. The overloads without dispatcher types keep their {@code REQUEST}-only behavior. 519 * 520 * @param filter The filter instance. Cannot be <jk>null</jk>. 521 * @param dispatcherTypes The dispatcher types. Cannot be empty. 522 * @param urlPatterns The URL patterns. At least one is required; see {@link org.apache.juneau.microservice.ServletFilterRegistration.Builder#urlPatterns(String...) ServletFilterRegistration.Builder#urlPatterns(String...)}. 523 * @return This object. 524 * @throws IllegalArgumentException If an argument is invalid. 525 * @throws IllegalStateException If the server has already started. 526 */ 527 public TomcatServerComponent addFilter(jakarta.servlet.Filter filter, Set<DispatcherType> dispatcherTypes, String...urlPatterns) { 528 if (dispatcherTypes == null) 529 throw iaex("dispatcherTypes must not be null."); 530 return addFilter(ServletFilterRegistration.create(filter).urlPatterns(urlPatterns).dispatcherTypes(dispatcherTypes.toArray(DispatcherType[]::new)).build()); 531 } 532 533 /** 534 * Adds an attribute to the root servlet context of the Tomcat server. 535 * 536 * @param name The attribute name. 537 * @param value The attribute value. 538 * @return This object. 539 */ 540 public TomcatServerComponent addServletAttribute(String name, Object value) { 541 getContext().getServletContext().setAttribute(name, value); 542 return this; 543 } 544 545 /** 546 * Returns the context path that this server is using. 547 * 548 * @return The context path. 549 */ 550 public String getContextPath() { 551 return getContext().getPath(); 552 } 553 554 /** 555 * Returns the root {@link Context} of the Tomcat server, creating it if necessary. 556 * 557 * @return The root context. 558 */ 559 public Context getContext() { 560 var context = (Context)getServer().getHost().findChild(ROOT_CONTEXT_PATH); 561 if (context != null) 562 return context; 563 return getServer().addContext(ROOT_CONTEXT_PATH, ROOT_DOC_BASE); 564 } 565 566 /** 567 * Returns the hostname of this microservice. 568 * 569 * @return The hostname. 570 */ 571 public String getHostName() { 572 String hostname = "localhost"; 573 try { 574 hostname = InetAddress.getLocalHost().getHostName(); 575 } catch (UnknownHostException e) { 576 // Cannot determine hostname, use default "localhost" 577 } 578 return hostname; 579 } 580 581 /** 582 * Returns the port that this server is listening on. 583 * 584 * @return The port. 585 */ 586 public int getPort() { 587 return getServer().getConnector().getLocalPort(); 588 } 589 590 /** 591 * Returns whether this server is using <js>"http"</js> or <js>"https"</js>. 592 * 593 * @return The protocol. 594 */ 595 public String getProtocol() { 596 return getServer().getConnector().getSecure() ? "https" : "http"; 597 } 598 599 /** 600 * Returns the underlying Tomcat server. 601 * 602 * @return The underlying Tomcat server. 603 * @throws NullPointerException If the server has not been created yet. 604 */ 605 public Tomcat getServer() { 606 return Objects.requireNonNull(tomcat.get(), "Tomcat not found. Microservice has not been started yet."); 607 } 608 609 /** 610 * Returns the URI where this server is listening. 611 * 612 * @return The URI. 613 */ 614 public URI getURI() { 615 var cp = getContextPath(); 616 try { 617 return new URI(getProtocol(), null, getHostName(), getPort(), ie(cp) ? null : cp, null, null); 618 } catch (URISyntaxException e) { 619 throw toRex(e); 620 } 621 } 622 623 private static Tomcat createServer(TomcatServerFactory factory, File dir) { 624 try { 625 return factory.create(dir); 626 } catch (Exception e) { 627 throw toRex(e); 628 } 629 } 630 631 private File resolveBaseDir(TomcatSettings settings) { 632 var configured = settings.getBaseDir(); 633 if (ine(configured)) { 634 ownsBaseDir.set(false); 635 var f = new File(configured); 636 baseDir.set(f); 637 return f; 638 } 639 try { 640 var f = createTempBaseDir().toFile(); 641 ownsBaseDir.set(true); 642 baseDir.set(f); 643 return f; 644 } catch (IOException e) { 645 throw toRex(e); 646 } 647 } 648 649 @SuppressWarnings({ 650 "java:S5443" // Temp dir created via Files.createTempDirectory with owner-only (rwx------) POSIX perms; non-POSIX fallback relies on OS-default owner-restricted temp dirs. 651 }) 652 private static Path createTempBaseDir() throws IOException { 653 try { 654 // Explicitly restrict to owner-only access (rwx------) on POSIX file systems. 655 Set<PosixFilePermission> ownerOnly = EnumSet.of( 656 PosixFilePermission.OWNER_READ, 657 PosixFilePermission.OWNER_WRITE, 658 PosixFilePermission.OWNER_EXECUTE); 659 return Files.createTempDirectory("juneau-tomcat", 660 PosixFilePermissions.asFileAttribute(ownerOnly)); 661 } catch (UnsupportedOperationException e) { 662 // Non-POSIX filesystem (e.g. Windows) — fall back to default temp-dir creation. 663 return Files.createTempDirectory("juneau-tomcat"); 664 } 665 } 666 667 private void cleanupBaseDir() { 668 if (ownsBaseDir.get()) { 669 var f = baseDir.getAndSet(null); 670 if (nn(f)) 671 deleteFile(f); 672 } 673 } 674 675 private void mountConfiguredServlet(String className, Map<String,String> mountedPaths) { 676 try { 677 var c = info(Class.forName(className)); 678 if (c.isAssignableTo(RestServlet.class)) { 679 var rs = (RestServlet)c.newInstance(); 680 mountWithCollisionCheck(rs, rs.getPath(), "Tomcat/servlets[" + className + "]", mountedPaths); 681 } else { 682 throw rex("Invalid servlet specified in Tomcat/servlets. Must be a subclass of RestServlet: %s", className); 683 } 684 } catch (ClassNotFoundException e) { 685 throw toRex(e); 686 } 687 } 688 689 private void mountMappedServlet(String pathKey, Object className, Map<String,String> mountedPaths) { 690 try { 691 var c = info(Class.forName(className.toString())); 692 if (c.isAssignableTo(Servlet.class)) { 693 var rs = (Servlet)c.newInstance(); 694 mountWithCollisionCheck(rs, pathKey, "Tomcat/servletMap[" + pathKey + "]", mountedPaths); 695 } else { 696 throw rex("Invalid servlet specified in Tomcat/servletMap. Must be a subclass of Servlet: %s", cn(className)); 697 } 698 } catch (ClassNotFoundException e) { 699 throw toRex(e); 700 } 701 } 702 703 private void mountWithCollisionCheck(Servlet servlet, String rawPath, String source, Map<String,String> mountedPaths) { 704 var pathSpec = normalizePathSpec(rawPath); 705 checkPathCollision(pathSpec, source, mountedPaths); 706 addServlet(servlet, pathSpec); 707 } 708 709 private void checkPathCollision(String pathSpec, String source, Map<String,String> mountedPaths) { 710 var prior = mountedPaths.get(pathSpec); 711 if (nn(prior)) 712 throw rex("Servlet mount path collision: '%s' is already mounted by %s; refused by %s.", pathSpec, prior, source); 713 mountedPaths.put(pathSpec, source); 714 } 715}