diff --git a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java index 9cfde83ec6..c9e5a1a87d 100644 --- a/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java +++ b/server/bootstrap/src/org/labkey/bootstrap/ModuleArchive.java @@ -35,9 +35,14 @@ 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; @@ -53,9 +58,13 @@ public class ModuleArchive protected static final FileComparator _fileComparator = new FileComparator(); + // 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; private final SimpleLogger _log; + private final long _extractionCost; private String stripToNull(String s) { @@ -130,6 +139,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 +149,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 +174,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() @@ -234,22 +252,22 @@ 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; 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<>(); + 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()) { - 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) @@ -258,6 +276,20 @@ 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); + } + if (!unreplaced.isEmpty()) { // A timestamp no archive has, so the next startup retries the extraction @@ -268,7 +300,40 @@ 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; + } + } + + + 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); + } } @@ -293,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(); @@ -319,7 +408,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); 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<>()); 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..359a97402d --- /dev/null +++ b/server/embedded/src/org/labkey/embedded/LabKeyWebResourceRoot.java @@ -0,0 +1,47 @@ +/* + * 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.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 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"; + + LabKeyWebResourceRoot(Context context) + { + super(context); + } + + @Override + public WebResource getClassLoaderResource(String path) + { + return new EmptyResource(this, WEB_INF_CLASSES + path); + } + + @Override + public WebResource[] getClassLoaderResources(String path) + { + return new WebResource[0]; + } +}