From 7ec89df117cfb57dabc87dd4fb0b6f9b100c4172 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 09:45:26 -0800 Subject: [PATCH 1/6] Skip Tomcat's WEB-INF/classes probe on every class load --- .../LabKeyTomcatServletWebServerFactory.java | 1 + .../embedded/LabKeyWebResourceRoot.java | 59 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java diff --git a/server/embedded/src/org/labkey/embedded/LabKeyTomcatServletWebServerFactory.java b/server/embedded/src/org/labkey/embedded/LabKeyTomcatServletWebServerFactory.java index 4f809d240f..33b08c251d 100644 --- a/server/embedded/src/org/labkey/embedded/LabKeyTomcatServletWebServerFactory.java +++ b/server/embedded/src/org/labkey/embedded/LabKeyTomcatServletWebServerFactory.java @@ -229,6 +229,7 @@ protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) loader.setLoaderClass(LabKeySpringBootClassLoader.class.getName()); context.setLoader(loader); context.setParentClassLoader(this.getClass().getClassLoader()); + context.setResources(new LabKeyWebResourceRoot(context)); } catch (ConfigException e) { diff --git a/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java b/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java new file mode 100644 index 0000000000..c79078803b --- /dev/null +++ b/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed 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.labkey.embedded; + +import org.apache.catalina.Context; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.WebResource; +import org.apache.catalina.webresources.EmptyResource; +import org.apache.catalina.webresources.StandardRoot; + +/** + * Module classes load from module jars, not the webapp, yet Tomcat probes WEB-INF/classes for every class and + * canonicalizes each missing path on disk. When the webapp supplies no classes, answer those probes without the disk. + */ +class LabKeyWebResourceRoot extends StandardRoot +{ + private static final String WEB_INF_CLASSES = "/WEB-INF/classes"; + + private volatile boolean _noWebappClasses = false; + + LabKeyWebResourceRoot(Context context) + { + super(context); + } + + @Override + protected void startInternal() throws LifecycleException + { + _noWebappClasses = false; + super.startInternal(); + // WEB-INF/lib jars register as class resources; anything else serving WEB-INF/classes shows up in the lookup + _noWebappClasses = getClassResources().length == 0 && !getResource(WEB_INF_CLASSES, false, true).exists(); + } + + @Override + public WebResource getClassLoaderResource(String path) + { + return _noWebappClasses ? new EmptyResource(this, WEB_INF_CLASSES + path) : super.getClassLoaderResource(path); + } + + @Override + public WebResource[] getClassLoaderResources(String path) + { + return _noWebappClasses ? new WebResource[0] : super.getClassLoaderResources(path); + } +} From abf018f932b4bc266acb8140330ad103c92935fc Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 11:29:37 -0800 Subject: [PATCH 2/6] Re-extract only the changed entries of a modified module archive --- .../org/labkey/bootstrap/ModuleArchive.java | 36 ++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java index 9cfde83ec6..9a2a349e99 100644 --- a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java +++ b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java @@ -34,8 +34,8 @@ import java.util.ArrayList; import java.util.Enumeration; import java.util.LinkedHashSet; -import java.util.List; import java.util.Properties; +import java.util.SequencedSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.jar.JarEntry; @@ -234,11 +234,10 @@ public void extractAll(File targetDirectory) throws IOException long archiveFileLastModified = archiveFile.lastModified(); _log.info("Extracting module " + archiveFile.getName() + "."); - // delete existing directory so that files that are - // no longer in the archive are removed - List undeleted = new ArrayList<>(); - ExplodedModule.deleteDirectory(targetDirectory, false, undeleted); - Set unreplaced = new LinkedHashSet<>(undeleted); + // Rewrite only entries whose content changed; every build rewrites module.xml, so most entries are unchanged + SequencedSet previouslyExtracted = new LinkedHashSet<>(); + listTree(targetDirectory, previouslyExtracted); + Set unreplaced = new LinkedHashSet<>(); long startTime = System.currentTimeMillis(); int fileCount = 0; @@ -248,7 +247,7 @@ public void extractAll(File targetDirectory) throws IOException Enumeration entries = jar.entries(); while(entries.hasMoreElements()) { - extractEntry(jar, entries.nextElement(), targetDirectory, archiveFileLastModified, unreplaced); + previouslyExtracted.remove(extractEntry(jar, entries.nextElement(), targetDirectory, archiveFileLastModified, unreplaced)); fileCount++; } } @@ -258,6 +257,13 @@ public void extractAll(File targetDirectory) throws IOException throw new IOException("Failed to process " + archiveFile, e); } + // Remove what the archive no longer contains; listTree() put children after parents, so delete in reverse + for (File stale : previouslyExtracted.reversed()) + { + if (!stale.delete() && stale.isFile()) + unreplaced.add(stale); + } + if (!unreplaced.isEmpty()) { // A timestamp no archive has, so the next startup retries the extraction @@ -272,6 +278,20 @@ public void extractAll(File targetDirectory) throws IOException } + private static void listTree(File dir, Set files) + { + File[] children = dir.listFiles(); + if (null == children) + return; + for (File child : children) + { + files.add(child); + if (child.isDirectory()) + listTree(child, files); + } + } + + public static void ensureChild(File parent, File child) throws IOException { // Prevent Zip Slip: though we should always only deploy trusted modules, it's wise to always unzip safely @@ -319,7 +339,7 @@ public File extractEntry(JarFile jar, JarEntry entry, File targetDirectory, long return destFile; } - // Only files the pre-extraction delete couldn't remove get here, typically jars the JVM holds open on Windows + // Unchanged entries keep their file, so a jar the JVM holds open on Windows is only replaced when it changed if (hasSameContent(entry, destFile)) { unreplaced.remove(destFile); From dcbd2afabc5289bfef1859beacc77ca79059530a Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 12:15:01 -0800 Subject: [PATCH 3/6] Extract the largest module archives first --- .../org/labkey/bootstrap/ModuleArchive.java | 13 +++ .../org/labkey/bootstrap/ModuleExtractor.java | 81 ++++++++++++------- 2 files changed, 66 insertions(+), 28 deletions(-) diff --git a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java index 9a2a349e99..bc603d95a6 100644 --- a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java +++ b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java @@ -53,9 +53,13 @@ public class ModuleArchive protected static final FileComparator _fileComparator = new FileComparator(); + // Measured on macOS, creating one file costs about as much as writing this many bytes + private static final long BYTES_PER_FILE_CREATED = 175_000; + private final File _file; private final String _moduleName; private final SimpleLogger _log; + private final long _extractionCost; private String stripToNull(String s) { @@ -130,6 +134,7 @@ public ModuleArchive(File file, SimpleLogger log) throws IOException _log = log; String moduleName = null; + long extractionCost = 0; /* try to find moduleName in archive */ try (JarFile jar = new JarFile(getFile())) @@ -139,6 +144,7 @@ public ModuleArchive(File file, SimpleLogger log) throws IOException { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); + extractionCost += Math.max(0, entry.getSize()) + BYTES_PER_FILE_CREATED; if ("config/module.properties".equals(entryName)) { @@ -163,6 +169,13 @@ public ModuleArchive(File file, SimpleLogger log) throws IOException } _moduleName = moduleName; + _extractionCost = extractionCost; + } + + /** Relative cost of a full extraction, for scheduling the biggest archives first */ + public long getExtractionCost() + { + return _extractionCost; } public File getFile() diff --git a/server/bootstrap/src/org/labkey/bootstrap/ModuleExtractor.java b/server/bootstrap/src/org/labkey/bootstrap/ModuleExtractor.java index 013360bc3c..3b2ef2ea63 100644 --- a/server/bootstrap/src/org/labkey/bootstrap/ModuleExtractor.java +++ b/server/bootstrap/src/org/labkey/bootstrap/ModuleExtractor.java @@ -18,7 +18,12 @@ import java.io.*; import java.util.*; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -57,12 +62,6 @@ public Collection extractModules() _log.info("Exploding module archives"); - // Explode each module archive file into its directory, in parallel. Note: Default thread pool uses (CPU - 1) threads. - - // It might be tempting to try replacing .collect().parallelStream() below with .parallel(), but the intermediate - // list is critical in this case. File.listFiles() can't estimate the size of its results, so invoking parallel() - // directly leads to a terrible splitting strategy that has no parallelization benefit. - // https://stackoverflow.com/questions/34341656/why-is-files-list-parallel-stream-performing-so-much-slower-than-using-collect var archives = _moduleDirectories.streamAllModuleDirectories() .flatMap(dir -> { File[] files = dir.listFiles(moduleArchiveFilter); @@ -95,27 +94,28 @@ public Collection extractModules() } } - // extract - archives.parallelStream() - .forEach(moduleArchive->{ - File moduleArchiveFile = moduleArchive.getFile(); - try - { - File dir = moduleArchive.extractAll(); - _moduleArchiveFiles.put(moduleArchiveFile, moduleArchive); - mapModuleDirToArchive.put(dir.getAbsoluteFile(), moduleArchive); - } - catch (ModuleArchive.StaleFilesException e) - { - _log.warn(e.getMessage()); - _errorArchives.put(moduleArchiveFile, moduleArchiveFile.lastModified()); - } - catch (IOException e) - { - _log.error("Unable to extract module archive " + moduleArchiveFile.getPath() + "!", e); - _errorArchives.put(moduleArchiveFile, moduleArchiveFile.lastModified()); - } - }); + // Biggest first from a FIFO queue so a large archive can't start last; a sorted parallel stream would instead hand the biggest ones to one thread as a contiguous chunk + List> extractions = archives.stream() + .sorted(Comparator.comparingLong(ModuleArchive::getExtractionCost).reversed()) + .map(moduleArchive -> (Callable) () -> { + extract(moduleArchive, mapModuleDirToArchive); + return null; + }) + .toList(); + try (ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), Thread.ofPlatform().name("ModuleExtractor-", 0).factory())) + { + for (Future extraction : executor.invokeAll(extractions)) + extraction.get(); + } + catch (InterruptedException e) + { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while extracting modules", e); + } + catch (ExecutionException e) + { + throw e.getCause() instanceof RuntimeException re ? re : new IllegalStateException(e.getCause()); + } _log.info("Deploying resources from exploded modules to web app directory"); _explodedModules = getConcurrentSet(); @@ -125,7 +125,11 @@ public Collection extractModules() // from a .module archive. _moduleDirectories.streamAllModuleDirectories() .flatMap(dir-> {File[] files=dir.listFiles(File::isDirectory); return null==files ? null : Stream.of(files);}) - .toList() // This intermediate list is critical. See comment above. + // It might be tempting to try replacing .toList().parallelStream() with .parallel(), but the intermediate + // list is critical in this case. File.listFiles() can't estimate the size of its results, so invoking parallel() + // directly leads to a terrible splitting strategy that has no parallelization benefit. + // https://stackoverflow.com/questions/34341656/why-is-files-list-parallel-stream-performing-so-much-slower-than-using-collect + .toList() .parallelStream() .forEach(dir->{ if (dir.isHidden() || dir.getName().startsWith(".")) @@ -156,6 +160,27 @@ public Collection extractModules() return _explodedModules; } + private void extract(ModuleArchive moduleArchive, Map mapModuleDirToArchive) + { + File moduleArchiveFile = moduleArchive.getFile(); + try + { + File dir = moduleArchive.extractAll(); + _moduleArchiveFiles.put(moduleArchiveFile, moduleArchive); + mapModuleDirToArchive.put(dir.getAbsoluteFile(), moduleArchive); + } + catch (ModuleArchive.StaleFilesException e) + { + _log.warn(e.getMessage()); + _errorArchives.put(moduleArchiveFile, moduleArchiveFile.lastModified()); + } + catch (IOException e) + { + _log.error("Unable to extract module archive " + moduleArchiveFile.getPath() + "!", e); + _errorArchives.put(moduleArchiveFile, moduleArchiveFile.lastModified()); + } + } + private Set getConcurrentSet() { return Collections.newSetFromMap(new ConcurrentHashMap<>()); From a41d4b261969535e491c1c7cda2e7cd550ef330f Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 14:58:27 -0800 Subject: [PATCH 4/6] Handle case-only renames and file/directory swaps when re-extracting modules --- .../org/labkey/bootstrap/ModuleArchive.java | 64 +++++++++++++++++-- 1 file changed, 60 insertions(+), 4 deletions(-) diff --git a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java index bc603d95a6..aee4663630 100644 --- a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java +++ b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java @@ -34,10 +34,15 @@ import java.util.ArrayList; import java.util.Enumeration; import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Properties; import java.util.SequencedSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import java.util.stream.Collectors; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.CRC32; @@ -251,17 +256,18 @@ public void extractAll(File targetDirectory) throws IOException SequencedSet previouslyExtracted = new LinkedHashSet<>(); listTree(targetDirectory, previouslyExtracted); Set unreplaced = new LinkedHashSet<>(); + List extracted = new ArrayList<>(); long startTime = System.currentTimeMillis(); - int fileCount = 0; //extract all entries try (JarFile jar = new JarFile(archiveFile)) { Enumeration entries = jar.entries(); while(entries.hasMoreElements()) { - previouslyExtracted.remove(extractEntry(jar, entries.nextElement(), targetDirectory, archiveFileLastModified, unreplaced)); - fileCount++; + File file = extractEntry(jar, entries.nextElement(), targetDirectory, archiveFileLastModified, unreplaced); + previouslyExtracted.remove(file); + extracted.add(file); } } catch (IOException e) @@ -270,9 +276,16 @@ public void extractAll(File targetDirectory) throws IOException throw new IOException("Failed to process " + archiveFile, e); } + // File.equals() is case-sensitive, so on a case-insensitive file system a case-only rename lists the just-extracted file as stale + Map extractedByFoldedPath = previouslyExtracted.isEmpty() ? Map.of() : + extracted.stream().collect(Collectors.toMap(ModuleArchive::foldedPath, Function.identity(), (first, _) -> first)); + // Remove what the archive no longer contains; listTree() put children after parents, so delete in reverse for (File stale : previouslyExtracted.reversed()) { + File current = extractedByFoldedPath.get(foldedPath(stale)); + if (current != null && isSameFile(stale, current)) + continue; if (!stale.delete() && stale.isFile()) unreplaced.add(stale); } @@ -287,7 +300,26 @@ public void extractAll(File targetDirectory) throws IOException //set last mod on target directory to match module file targetDirectory.setLastModified(archiveFileLastModified); - _log.info("Done extracting module " + archiveFile.getName() + ". Processed " + fileCount + " file(s) in " + (System.currentTimeMillis() - startTime) + "ms."); + _log.info("Done extracting module " + archiveFile.getName() + ". Processed " + extracted.size() + " file(s) in " + (System.currentTimeMillis() - startTime) + "ms."); + } + + + private static String foldedPath(File file) + { + return file.getPath().toLowerCase(Locale.ROOT); + } + + + private static boolean isSameFile(File a, File b) + { + try + { + return Files.isSameFile(a.toPath(), b.toPath()); + } + catch (IOException e) + { + return false; + } } @@ -326,6 +358,30 @@ public File extractEntry(JarFile jar, JarEntry entry, File targetDirectory, long @SuppressWarnings({"SSBasedInspection", "JvmTaintAnalysis"}) File destFile = new File(targetDirectory, entry.getName()); ensureChild(targetDirectory, destFile); + // Extraction writes over an earlier build's files, which may have a file where this build has a directory or the reverse + for (File ancestor = destFile.getParentFile(); ancestor != null && !ancestor.equals(targetDirectory); ancestor = ancestor.getParentFile()) + { + if (ancestor.isFile()) + { + if (!ancestor.delete()) + { + unreplaced.add(ancestor); + return destFile; + } + break; + } + } + if (entry.isDirectory() ? destFile.isFile() : destFile.isDirectory()) + { + List undeleted = new ArrayList<>(); + ExplodedModule.deleteDirectory(destFile, false, undeleted); + if (!undeleted.isEmpty()) + { + unreplaced.addAll(undeleted); + return destFile; + } + } + File entryParent = destFile.getParentFile(); if (!entryParent.isDirectory()) entryParent.mkdirs(); From 3f4cd88d9d5278042d5fd525519bdcc42695051a Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sun, 22 Nov 2026 13:06:53 -0800 Subject: [PATCH 5/6] One more review --- server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java index aee4663630..70be931ca4 100644 --- a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java +++ b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java @@ -58,8 +58,8 @@ public class ModuleArchive protected static final FileComparator _fileComparator = new FileComparator(); - // Measured on macOS, creating one file costs about as much as writing this many bytes - private static final long BYTES_PER_FILE_CREATED = 175_000; + // Rough cost of creating a file, in bytes written; used to figure out an optimal extraction order + private static final long BYTES_PER_FILE_CREATED = 100_000; private final File _file; private final String _moduleName; From bf56c1affc21dc716e913195ee54a5ad553ec173 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Mon, 23 Nov 2026 17:47:57 -0800 Subject: [PATCH 6/6] Always skip WEB-INF/classes lookups and clarify comments --- .../org/labkey/bootstrap/ModuleArchive.java | 2 +- .../embedded/LabKeyWebResourceRoot.java | 20 ++++--------------- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java index 70be931ca4..c9e5a1a87d 100644 --- a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java +++ b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java @@ -252,7 +252,7 @@ public void extractAll(File targetDirectory) throws IOException long archiveFileLastModified = archiveFile.lastModified(); _log.info("Extracting module " + archiveFile.getName() + "."); - // Rewrite only entries whose content changed; every build rewrites module.xml, so most entries are unchanged + // Rewrite only entries whose content changed; a rebuilt module is re-extracted over the last one, and most files are usually unchanged SequencedSet previouslyExtracted = new LinkedHashSet<>(); listTree(targetDirectory, previouslyExtracted); Set unreplaced = new LinkedHashSet<>(); diff --git a/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java b/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java index c79078803b..359a97402d 100644 --- a/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java +++ b/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java @@ -16,44 +16,32 @@ package org.labkey.embedded; import org.apache.catalina.Context; -import org.apache.catalina.LifecycleException; import org.apache.catalina.WebResource; import org.apache.catalina.webresources.EmptyResource; import org.apache.catalina.webresources.StandardRoot; /** - * Module classes load from module jars, not the webapp, yet Tomcat probes WEB-INF/classes for every class and - * canonicalizes each missing path on disk. When the webapp supplies no classes, answer those probes without the disk. + * Module classes load from module jars, not the webapp, yet Tomcat probes WEB-INF/classes for every class and resource + * lookup, canonicalizing the path on disk each time. We don't use WEB-INF/classes or WEB-INF/lib, so short-circuit. */ class LabKeyWebResourceRoot extends StandardRoot { private static final String WEB_INF_CLASSES = "/WEB-INF/classes"; - private volatile boolean _noWebappClasses = false; - LabKeyWebResourceRoot(Context context) { super(context); } - @Override - protected void startInternal() throws LifecycleException - { - _noWebappClasses = false; - super.startInternal(); - // WEB-INF/lib jars register as class resources; anything else serving WEB-INF/classes shows up in the lookup - _noWebappClasses = getClassResources().length == 0 && !getResource(WEB_INF_CLASSES, false, true).exists(); - } - @Override public WebResource getClassLoaderResource(String path) { - return _noWebappClasses ? new EmptyResource(this, WEB_INF_CLASSES + path) : super.getClassLoaderResource(path); + return new EmptyResource(this, WEB_INF_CLASSES + path); } @Override public WebResource[] getClassLoaderResources(String path) { - return _noWebappClasses ? new WebResource[0] : super.getClassLoaderResources(path); + return new WebResource[0]; } }