The smallmind-spark module is the project’s answer to a single, recurring
question: how do you ship a Java application as something a human or an
operating system can actually run? A Maven build produces jars and a
handful of transitive dependency jars; the gap between that artifact set
and "a service my ops team can start on boot and stop on command" is
wide enough that every project ends up re-inventing the same pair of
tools. smallmind-spark collects those two tools into the tree and gives
each a Maven packaging type:
-
singularity— bundles the project’s classes and every runtime dependency jar into a single self-executing jar. The bundle ships a small boot library and a customClassLoaderthat reads nested jars in place, sojava -jar my-app.jarworks without unpacking anything, without a shaded/uber-jar merge pass, and without classpath management. -
tanukisoft— wraps the project as a proper OS-managed service using Tanuki Software’s Java Service Wrapper (JSW). Produces a ready-to-run tree withbin/,lib/, andconf/, the correct platform-specific wrapper executable, rendered launch scripts (shell / batch / Windows service install-uninstall), and a populatedwrapper.conf. Understands Upstart, systemd, and Windows services.
Both are delivered as Maven extension plugins that install new packaging
types — declare <packaging>singularity</packaging> or
<packaging>tanukisoft</packaging> on a project, and the plugin’s
lifecycle binding handles everything package, install, and deploy
normally would.
The module is organized as two independently usable subprojects, each in turn split into an API/runtime half and a Maven-plugin half:
| Subproject | Runtime artifact | Maven plugin |
|---|---|---|
|
|
|
|
|
|
Java services that wish to distribute themselves in robust self-executing formats must answer some common issues:
-
Shipping. How does the artifact reach a deployed host? A plain jar is useless without its classpath. An uber-jar works, but most shading pipelines have to rewrite bytecode and resources, break signed jars, merge
META-INF/services/files, and strip manifest attributes. Services that need reproducible, untouched dependency jars (signed crypto providers, OSGi fragments, JNI library jars) cannot use a shaded jar. -
Running. Once the jar arrives on the host, how does it start? Platform-native service wrappers exist on every OS — Windows services, launchd, systemd, SysV init, Upstart — but every one expects its own configuration format and lifecycle conventions. A shell script that works on one Linux distro rarely works on another. A Windows service needs an executable wrapper, a registry entry, an install step, an uninstall step, and a command-line surface.
-
Behaving. Once started, how does the service respond to being told to stop? A Java process that blocks a graceful shutdown behind an unfinished transaction is worse than one that crashes; an ops team needs a watchdog that will eventually make the process stop, and a signal path that lets the application flush and close in the meantime.
smallmind-spark solves (1) with singularity and (2) and (3) with
tanukisoft. The two are independent answers to different problems
and target different deployment shapes — a Singularity jar is the
deliverable when the application ships as a single executable jar
invoked with java -jar, while a Tanukisoft distribution is the
deliverable when the application ships as an OS-managed service with
a lib/ directory, a control surface, and a watchdog. Each is a
Maven packaging type, so adopting either is a one-line POM change.
Pick whichever matches the deployment surface.
-
Packages a runnable jar that contains every nested dependency without rewriting them (
spark-singularity-maven-plugin). Boot classes laid down in the jar root, dependency jars stored as-is underMETA-INF/singularity/lib/, project classes at the root, serializedSingularityIndexrecording the provenance of every class and resource. -
Provides a custom
ClassLoaderthat resolves classes from nested jars in place (SingularityClassLoader), backed by a customsingularity:URL protocol that can stream bytes from any entry in any nested library without extracting anything to disk. A nested jar is held in memory once something in it has been used, so later lookups do not reopen the outer archive;useJarCachechooses between fast first use and a smaller footprint. -
Turns the jar into an executable bootstrap via
SingularityEntryPoint:Main-Classof the outer jar, reflectively invokes whatever fully qualified class name was configured asmainClassat build time. -
Runs a modular application on a module path when the project is a named module and
modularis set: the application and the modular dependencies it requires run as named modules, everything else on the class path, and the module graph is checked when the bundle is built. -
Assembles a ready-to-run Tanuki wrapper distribution (
spark-tanukisoft-maven-plugin) withbin/,lib/,conf/, the correct platform-specific wrapper executable and native library (19 supported platform triples), runtime dependencies, the project’s own jar, the Tanuki license, and any additional configuration files. -
Renders launch scripts and
wrapper.conffrom Freemarker templates —<app>.shfor Unix,<app>.bat/Install<app>-NT.bat/Uninstall<app>-NT.batfor Windows, andwrapper.conffor every platform. The Freemarker model includes heap sizing, JVM arguments, environment variables, NT service dependencies, Upstart / systemd toggles, run-as user, and classpath. -
Provides an
AbstractWrapperListenerthat subclasses can extend to hook the wrapper’s start / stop callbacks to their own application lifecycle — with a built-in keep-alive signaller so slow startups do not trip the wrapper’s watchdog. -
Provides
SpringContextWrapperListenerandClassPathXmlSpringContextWrapperListenerso Spring-based applications can be wrapped by declaring the XML locations in the plugin configuration — the most common integration path, requiring no application-specific wrapper-listener class at all. -
Registers new Maven packaging types (
singularityandtanukisoft) that rebindpackage,install, anddeployphases to the module’s own goals via Plexuscomponents.xml.
-
It does not rewrite dependency bytecode or resources. The whole point of Singularity is that the jars in
META-INF/singularity/lib/are the exact jars Maven resolved — signatures intact, service descriptors intact,META-INF/intact. If you need shading, usemaven-shade-plugin; Singularity is the other choice. -
It does not hide Tanuki’s Java Service Wrapper.
wrapper.confis stillwrapper.conf, in exactly the form Tanuki documents. The plugin generates it from a Freemarker template whose inputs are Maven-configurable; everything else is Tanuki’s. -
It does not ship Tanuki’s wrapper license. The Tanuki wrapper binaries themselves are bundled (as
wrapper-<os>-<arch>(.exe)resources in the plugin jar) for convenience, but a production deployment needs a real Tanuki license file and is expected to pointlicenseFileat it. -
It does not replace Spring Boot, Quarkus, Micronaut, or any other "framework that packages its own runtime." The target audience is a plain Java service — typically a Spring application — that wants a jar it can hand to ops and an OS service wrapping story, without adopting a heavier framework.
-
It does not provide hot redeploy, health probes, config reload, or any other long-running-service amenity. The Tanuki wrapper has its own watchdog; anything beyond that is the application’s concern.
| If you are … | Read, in this order |
|---|---|
… shipping a Java service and you just need one file for the deploy team to drop on a host |
|
… running that service as a Windows service or a Linux daemon on a long-lived host |
|
… building a Spring application that should come up on host boot and shut down gracefully on host shutdown |
|
… debugging a |
Class Loading Rules → Class Path Order → Reserved JDK Namespaces. |
… packaging an application that has its own |
|
… tuning how much memory a running Singularity jar holds for its dependencies, or how fast it starts |
|
… debugging "the service started, then the wrapper killed it" in production |
|
… adding a new platform (OS/arch) to the plugin’s supported list |
|
… trying to exclude a specific dependency from a Singularity bundle because it is already present on the host |
| Problem | Use | Notes |
|---|---|---|
Package a single, self-executing jar that contains every runtime dependency without rewriting bytecode |
|
Dependency jars land under |
Run an application that is a named module, with its modular dependencies on a module path |
|
The module graph is checked when the bundle is built. See Modular Mode. |
Reduce the memory a running Singularity jar holds for its dependencies |
|
Smaller footprint, much slower first use of each dependency. See Nested Jars In Memory. |
Wrap a Java service as a Windows service, Linux daemon, or macOS launchd task with a real watchdog |
|
Produces |
Run a Spring application under the wrapper without writing any wrapper-listener class yourself |
Set |
Pass Spring XML resource locations as |
Write a custom wrapper listener (non-Spring or custom context factory) |
Subclass |
Built-in keep-alive signaller pings the watchdog while |
Control the Spring context factory in a non-trivial way (programmatic construction, multiple contexts, non-classpath resources) |
Subclass |
Lifecycle ( |
Exclude a dependency from the Singularity bundle (e.g. the JDK already has it, or a host agent provides it) |
|
Matches on |
Bundle additional compile- or provided-scope jars in the wrapper
distribution (e.g. JDBC drivers installed via |
|
Matches on |
Make the wrapper install as a Windows NT service with specific service dependencies |
|
Rendered into |
Make the wrapper install as a systemd or Upstart unit on Linux |
|
Both default to |
Deploy the aggregate archive to a Maven repository so other modules can consume it |
The |
The aggregate archive is attached with classifier |
smallmind-spark ships four independently resolvable artifacts. Pick
the smallest set that matches your integration surface.
You never depend on this directly. The Singularity Maven plugin has it
as its own compile-scope dependency and extracts its classes into the
outer jar at package time, which is why the boot classes appear under
org/smallmind/spark/singularity/boot/ at the root of every Singularity
jar. If you are consuming a Singularity jar (rather than building one)
you can ignore this artifact entirely.
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>spark-singularity-boot</artifactId>
<version>${project.version}</version>
</dependency>Module name (for requires): org.smallmind.spark.singularity.boot
The jar ships an explicit module descriptor that exports
org.smallmind.spark.singularity.boot and requires nothing beyond java.base. The
generate-singularity goal copies only the entries under
org/smallmind/spark/singularity/boot/ into a Singularity jar, so the descriptor does not
travel with them: a Singularity jar is not itself a named module and is launched with
java -jar. By default the classes its boot loader defines run in that loader’s unnamed
module; a bundle built in modular mode defines a module layer
for the application and its modular dependencies instead. See
Module Path And Classpath for the repository-wide rules.
Declare this as a build plugin with <extensions>true</extensions>. The
extensions attribute is what registers the singularity packaging
type and its lifecycle mapping — without it, <packaging>singularity</packaging>
will not be recognized.
<packaging>singularity</packaging>
<build>
<plugins>
<plugin>
<groupId>org.smallmind</groupId>
<artifactId>spark-singularity-maven-plugin</artifactId>
<version>${project.version}</version>
<extensions>true</extensions>
<configuration>
<mainClass>com.example.service.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>Automatic module name: org.smallmind.spark.singularity.mojo — Maven loads plugins through its own class realms, so this name only identifies the jar; it is not intended for a consumer’s requires.
Depend on this from application code that extends
AbstractWrapperListener or uses the shipped Spring specializations.
Brings in the Tanuki wrapper runtime jar (tanukisoft:wrapper),
Spring’s spring-context, and smallmind-nutsnbolts.
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>spark-tanukisoft-integration</artifactId>
<version>${project.version}</version>
</dependency>Module name (for requires): org.smallmind.spark.tanukisoft.integration
This jar has no module descriptor and stays an automatic module under the name above. On
a module path it depends on the Tanuki wrapper jar, which declares no module name of its
own, so the JVM derives one from the file name: wrapper-3.5.54.jar becomes wrapper, and
a renamed jar becomes a differently named module. Keep the jar’s Maven file name. See
Module Path And Classpath for the repository-wide rules.
If you are using the shipped
ClassPathXmlSpringContextWrapperListener and you do not need to
compile any code against the wrapper API, a project with
<packaging>tanukisoft</packaging> will pull this in through the
example POM’s dependency on spark-tanukisoft-integration.
Declare this as a build plugin with <extensions>true</extensions> so
the tanukisoft packaging type is registered.
<packaging>tanukisoft</packaging>
<build>
<plugins>
<plugin>
<groupId>org.smallmind</groupId>
<artifactId>spark-tanukisoft-maven-plugin</artifactId>
<version>${project.version}</version>
<extensions>true</extensions>
<configuration>
<operatingSystem>${tanukisoft.wrapper.os}</operatingSystem>
<wrapperListener>org.smallmind.spark.tanukisoft.integration.spring.ClassPathXmlSpringContextWrapperListener</wrapperListener>
<appParameters>
<appParameter>classpath:spring/application-context.xml</appParameter>
</appParameters>
</configuration>
</plugin>
</plugins>
</build>Automatic module name: org.smallmind.spark.tanukisoft.mojo — Maven loads plugins through its own class realms, so this name only identifies the jar; it is not intended for a consumer’s requires.
|
Important
|
The Tanuki wrapper binaries are distributed inside the plugin jar under
the |
spark/
pom.xml Aggregator POM (smallmind-spark)
singularity/
pom.xml Intermediate POM (spark-singularity)
boot/
pom.xml spark-singularity-boot
src/main/java/
org/smallmind/spark/singularity/boot/
SingularityEntryPoint.java Main-Class of every Singularity jar
SingularityClassLoader.java Custom ClassLoader over nested jars
SingularityIndex.java Serializable map of bundle contents
SingularityModule.java A module of a modular bundle
SingularityModuleFinder.java ModuleFinder over those modules
NestedJarFile.java A dependency jar held in memory
CachedJarFile.java ... kept as-is (useJarCache=true)
RecompressedJarFile.java ... kept re-compressed (useJarCache=false)
SingularityJarURLConnection.java singularity: URL connection
SingularityJarURLStreamHandler.java singularity: URL handler
SingularityJarURLStreamHandlerFactory.java JVM-wide handler factory
mojo/
pom.xml spark-singularity-maven-plugin
src/main/java/
org/smallmind/spark/singularity/maven/
GenerateSingularityMojo.java @Mojo generate-singularity
InstallSingularityMojo.java @Mojo install-singularity
DeploySingularityMojo.java @Mojo deploy-singularity
Exclusion.java <exclusion> configuration POJO
AscArtifactMetadata.java .asc signature companion
CopyFileVisitor.java File-tree walker for target/classes
src/main/maven/
singularity-pom.xml Example POM
src/main/resources/meta/META-INF/plexus/
components.xml singularity packaging + lifecycle
tanukisoft/
pom.xml Intermediate POM (spark-tanukisoft)
integration/
pom.xml spark-tanukisoft-integration
src/main/java/
org/smallmind/spark/tanukisoft/integration/
AbstractWrapperListener.java Wrapper bridge base class
spring/
SpringContextWrapperListener.java Abstract Spring lifecycle
ClassPathXmlSpringContextWrapperListener.java classpath XML variant
mojo/
pom.xml spark-tanukisoft-maven-plugin
src/main/java/
org/smallmind/spark/tanukisoft/maven/
GenerateWrapperMojo.java @Mojo generate-wrapper
InstallWrapperMojo.java @Mojo install-wrapper
DeployWrapperMojo.java @Mojo deploy-wrapper
OSType.java Platform enum (19 constants)
OSStyle.java WINDOWS / UNIX family enum
Dependency.java <dependency> configuration POJO
EnvironmentArgument.java <envArg> configuration POJO
src/main/installation/
org/smallmind/spark/tanukisoft/maven/
bin/ Wrapper binaries, shell/batch templates
freemarker.App.sh.in Unix launch-script Freemarker template
AppCommand.bat.in Windows service command
InstallApp-NT.bat.in Windows service install
UninstallApp-NT.bat.in Windows service uninstall
wrapper-<os>-<arch>(.exe) Tanuki wrapper binaries (19 of them)
conf/
freemarker.wrapper.conf.in wrapper.conf Freemarker template
wrapper.conf.in Non-Freemarker wrapper.conf template
lib/ Tanuki native libraries, per platform
src/main/maven/
tanukisoft-pom.xml Example POM with OS profiles
src/main/resources/meta/META-INF/plexus/
components.xml tanukisoft lifecycle mappingThe module rests on two orthogonal ideas, one per subproject. Holding them distinct in your head is the shortest path to correct use.
A Singularity bundle is a normal .jar file whose contents are
partitioned three ways:
-
Boot classes at the jar root under
org/smallmind/spark/singularity/boot/. These are copied into the outer jar at package time from thespark-singularity-bootplugin dependency. They are reachable by a fresh JVM’s system class loader. -
Application classes at the jar root, in their natural package directories. Same position as a normal jar’s contents; same resolution story.
-
Library jars under
META-INF/singularity/lib/, each one kept verbatim as a.jarfile. Nothing unpacks them. A normal system class loader cannot reach classes inside these nested jars, so a customClassLoaderis necessary.
Glue holds the three apart:
- Index
-
A serialized
SingularityIndexatMETA-INF/singularity/index/singularity.idxrecords, for every class and resource, which of the three populations it belongs to. For library entries, it also records which library jars insidelib/supply it, in class path order. In a modular bundle it also records which dependencies form the module path. - Custom URL protocol
-
The
singularity:protocol has the formsingularity:<outer-jar-url>@/META-INF/singularity/lib/<lib>!/<entry>.SingularityJarURLStreamHandlerclaims it JVM-wide fromSingularityClassLoader’s static initializer, so any component that resolves an entry’s URL (including `javax.crypto.JarVerifier,ServiceLoader, Spring’sPathMatchingResourcePatternResolver, and URL-based classloaders layered on top) can reach the bytes. - Custom ClassLoader
-
SingularityClassLoaderreads the index at boot and servesfindClass/findResourcefrom it, addressing jar-root entries withjar:URLs and library entries withsingularity:URLs. It refuses a small set of JDK-shadowed namespaces so the platform’s own copies win. In a modular bundle it is also the class loader of every module on the bundle’s module path. - Entry point
-
SingularityEntryPointis the jar’sMain-Class. Onmain, it opens the enclosing jar viaCodeSource, constructs aSingularityClassLoader, installs it as the context class loader, and reflectively invokes the application’s realmain— whose class name is stored in the manifest attributeSingularity-Class. In a modular bundle it first sets up the module path and loads the main class from the application’s module.
Tanukisoft’s Java Service Wrapper is a native executable that launches
a JVM as a child process, watches that child for health, restarts it
on crash, and translates OS-level service / daemon conventions
(Windows services, systemd units, SysV init, launchd, Upstart) into a
consistent API. The application code inside that JVM is a normal Java
program that implements one interface (WrapperListener) so the
wrapper can deliver start and stop callbacks across the JNI
boundary.
smallmind-spark gives that a three-layer shape:
- Bridge
-
AbstractWrapperListenerimplementsWrapperListenerand bolts on the one-time setup each wrapped application needs: a CLI bootstrap that reads the configured listener class name from the first argument and reflectively creates it; a Property-Expander pass over the remaining arguments; a daemon-backed scheduled task that callsWrapperManager.signalStarting(int)as soon asstartbegins and then at half the startup timeout so a slowstartupis not killed by the watchdog. - Spring specialization
-
SpringContextWrapperListenerextendsAbstractWrapperListenerand maps the abstractstartup/shutdownhooks onto the life of a SpringConfigurableApplicationContext. Subclasses need only implement one factory method. This is the layer most applications should use, directly or throughClassPathXmlSpringContextWrapperListener. - Build-time assembly
-
spark-tanukisoft-maven-pluginstages abin/+lib/+conf/tree, copies in the platform-specific wrapper binary plus native library, copies in all dependency jars, renders the Freemarker templates into<app>.sh(or the Windows batch equivalents) andwrapper.conf, and optionally compresses the result into an archive that can be dropped on a host.
Nothing about the runtime layer assumes a Singularity jar; the two
subprojects are independent. They are also not intended to be
stacked: Singularity exists to fold a classpath into one deliverable
when the goal is a single executable jar. A Tanukisoft distribution
is already a multi-file tree where every dependency lives in lib/,
so the problem Singularity solves does not arise. Choose whichever
distribution shape matches the artifact the application is meant to
ship as.
generate-singularity(phase:package)-
Assembles the bundle. Creates
${project.build.directory}/${singularityBuildDir}/with itsMETA-INF/singularity/{lib,index}subtree, extracts the boot classes from the plugin’s ownspark-singularity-bootdependency into the tree, walksproject.getRuntimeArtifacts()and copies each non-excluded dependency jar verbatim intolib/(while recording every one of its entries in theSingularityIndex), walkstarget/classes/and copies every file into the tree (while recording each in the index), serializes the index toMETA-INF/singularity/index/singularity.idx, composes the manifest (see Manifest Attributes), compresses the tree into${project.build.directory}/<artifactId>-<version>[-<classifier>].jar, and attaches the result as a project artifact. In modular mode it also works out which dependencies form the module path and fails the build if the module graph does not resolve. install-singularity(phase:install)-
Locates the output jar in
target/using the same naming rule asgenerate-singularity, looks for a sibling.ascsignature file, attaches it viaAscArtifactMetadataif present, and installs the artifact into the local repository viaArtifactInstaller.install. deploy-singularity(phase:deploy)-
Same as
install-singularity, except it pushes to the project’s configureddistributionManagementrepository throughArtifactDeployer.deploy.
mainClass(required)-
Fully qualified name of the application’s main class — the one the user would have invoked had they had a classpath. Stored in the jar manifest as
Singularity-Class.SingularityEntryPointreads it and reflectively calls itsmain(String[]). singularityBuildDir(default:singularity)-
Name of the subdirectory under
${project.build.directory}into which the bundle tree is staged before compression. Rarely needs changing. exclusions-
List of
<exclusion>entries, each with<groupId>and<artifactId>, that should be dropped from the bundle. Matched exactly on both coordinates. verbose(default:false)-
Enables per-file progress logging.
skip(default:false)-
Skips execution. Combine with a Maven profile to build a "development" jar that intentionally omits the Singularity step.
modular(default:false)-
Runs the application on a module path. The project must be a named module (it has a
module-info.java), andmainClassmust be one of its classes. See Modular Mode. useJarCache(default:true)-
How the running bundle keeps a dependency jar in memory once something in it has been used.
truefavors speed;falseuses less memory but makes the first use of each dependency much slower. See Nested Jars In Memory.
generate-singularity writes these attributes into the bundle’s
manifest, and the bundle reads them when it starts. They are derived
from the plugin configuration; there is no need to set them by hand.
| Attribute | Meaning |
|---|---|
|
Always |
|
The application’s main class, from |
|
The application’s module name. Present only in a modular bundle. |
|
|
SingularityEntryPoint-
Main-Classof every generated jar. Itsmain(String…)opens the enclosing jar through its ownCodeSource, reads the manifest, constructs aSingularityClassLoaderbound to that jar, installs the loader as the context class loader, and reflectively invokes theSingularity-Class’s `mainwith the original argument array. In a modular bundle it first sets up the module path (see Modular Mode). Silently ignores the degenerate case whereSingularity-Classequals itself (so the boot does not recurse). SingularityClassLoader-
The runtime’s center. Reads the serialized
SingularityIndexoff the jar and servesfindClass/findResource/findResourcesfrom it, searching the jar’s own classes first and then the bundled libraries in class path order (see Class Path Order). In a modular bundle it is also the class loader of every module on the bundle’s module path.Its static initializer installs
SingularityJarURLStreamHandlerFactoryJVM-wide, which is a deliberate singleton: the JVM permits exactly oneURLStreamHandlerFactoryto be registered, andSingularityClassLoadermust be the one that registers it. SingularityIndex-
The serialized record of the bundle’s contents, written at build time: which jar supplies each class and resource and, in a modular bundle, which dependencies form the module path.
SingularityModule,SingularityModuleFinder-
Support for modular bundles: one module of the bundle’s module path, and the
ModuleFinderover all of them. NestedJarFile,CachedJarFile,RecompressedJarFile-
A dependency jar held in memory, and the two ways of holding it that
useJarCachechooses between (see Nested Jars In Memory). SingularityJarURLConnection-
URLConnectionfor thesingularity:protocol. Parses the URL formsingularity:<outer>@/[<inner-jar>!/]<entry>and returns anInputStreamover the addressed entry, reusing a dependency jar already held in memory when possible. SingularityJarURLStreamHandler-
Standard
URLStreamHandlerthat returns a freshSingularityJarURLConnectionfor every URL. SingularityJarURLStreamHandlerFactory-
URLStreamHandlerFactoryregistered JVM-wide. Claims thesingularityprotocol; returnsnullfor everything else so the platform’s default handler selection stays in effect.
Exclusion-
Configuration POJO with
groupIdandartifactIdfields and a singlematchesArtifact(Artifact)predicate. Both coordinates must match exactly; version is ignored. AscArtifactMetadata-
Maven
ArtifactMetadataimplementation that carries a detached-GPG.ascfile alongside an artifact through install and deploy. The local filename is<artifactId>-<version>[-<classifier>].jar.asc. Lives in the artifact’s version directory. Used only if an.ascis found next to the generated jar. CopyFileVisitor-
SimpleFileVisitor<Path>used bygenerate-singularityto walktarget/classes/. On each file, copies it to the matching location under the singularity build tree and registers the relative resource path (with/separators) in theSingularityIndexviaaddFileName.
SingularityClassLoader.loadClass(String, boolean) follows a
self-before-parent strategy:
-
Check
findLoadedClass— return an already-defined class directly. -
Otherwise call
findClass— the bundled definition is preferred. -
If
findClassthrowsClassNotFoundException, delegate to the parent (or tofindSystemClassif no parent is configured).
findClass itself:
-
Rejects names in reserved namespaces (see below) so the platform’s own copies resolve through the parent.
-
Looks up
<binary>.classin the index; if absent, throwsClassNotFoundException. -
Determines a
CodeSourceURL based on the entry’s protocol:-
jar:<outer>!/…→CodeSourceis<outer>!/. -
singularity:<outer>@/<inner>!/…→CodeSourceissingularity:<outer>@/<inner>(no trailing!/). This form compensates for a quirk injavax.crypto.JarVerifierthat would otherwise mangle the URL.
-
-
Reads the bytes via
URL.openStream(). -
Lazily defines the enclosing package on first touch, using the outer manifest’s specification/implementation titles and the optional seal base.
-
Calls
defineClass(name, bytes, 0, bytes.length, protectionDomain)where the protection domain hasAllPermission.
In a modular bundle, a class in a package of a module on the bundle’s module path is defined into that module, with the module’s jar as its code source, and the reserved namespaces do not apply to it.
When the same class or resource name appears in more than one place,
a Singularity jar resolves it the way java -cp
target/classes:<dependencies> would: the project’s own classes and
resources first, then the dependency jars in the project’s runtime
class path order.
A class, or a resource fetched with getResource, comes from the first
place that has it. getResources returns every copy, in that order, so
ServiceLoader sees the META-INF/services files of every dependency,
and getResources("META-INF/MANIFEST.MF") returns one manifest per
jar.
|
Note
|
Bundles built by plugins before 7.4.0 kept one source per entry name:
the last library jar to contain an entry, which also took precedence
over the project’s own copy. Consequently |
SingularityClassLoader deliberately refuses to define classes whose
names begin with:
-
jakarta.xml.— exceptjakarta.xml.bind.which is admitted. -
org.xml. -
org.w3c.
Bundled dependencies sometimes ship these packages (older SAX stubs,
stale JAXB API jars, or test fixtures that repackage XML APIs). The
JDK requires its own copies of these classes for platform code to
function; allowing the bundle to provide conflicting versions causes
LinkageError failures when the JDK’s own parser code hits them. The allow
list for jakarta.xml.bind exists because production code that wants
JAXB needs a real implementation, and a Singularity bundle is the
correct place to ship one.
A host JVM that already exposes a library (a container-provided JDBC
driver, say, or a shared agent) should not have it duplicated inside
the Singularity jar — same class, two definitions, different
Class<?> objects, mystery ClassCastException at the seam.
<plugin>
<groupId>org.smallmind</groupId>
<artifactId>spark-singularity-maven-plugin</artifactId>
<version>${project.version}</version>
<extensions>true</extensions>
<configuration>
<mainClass>com.example.service.Main</mainClass>
<exclusions>
<exclusion>
<groupId>com.oracle.database.jdbc</groupId> <!--(1)-->
<artifactId>ojdbc11</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId> <!--(2)-->
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</configuration>
</plugin>-
Oracle JDBC driver provided by the host.
-
SLF4J API already loaded by the host’s logging framework.
Exclusions match exactly on both coordinates. There is no glob / version / scope filtering — add an entry per artifact id.
By default a Singularity jar runs its application on a class path, as
java -cp would, even when the application and its dependencies carry
module descriptors. If the project is a named module (it has a
module-info.java), set modular to run it on a module path instead,
as java --module-path … --module … would:
<plugin>
<groupId>org.smallmind</groupId>
<artifactId>spark-singularity-maven-plugin</artifactId>
<version>${project.version}</version>
<extensions>true</extensions>
<configuration>
<mainClass>com.example.service.main.Main</mainClass> <!--(1)-->
<modular>true</modular>
</configuration>
</plugin>-
Must be a class of the project’s own module. Its package does not need to be exported.
The running jar then behaves as if it had been launched with both a module path and a class path:
-
The project’s module, the modular dependencies it requires, and the modular dependencies that provide services it
usesrun as named modules. -
A dependency without a module descriptor runs as an automatic module when one of those modules
requiresit, and on the class path otherwise. -
Every other dependency stays on the class path, exactly as in a class path bundle.
The usual module-path rules apply. Code outside a module can use only
the packages it exports. A framework that reflects into a module, or
loads a resource from one of its packages by path (as Spring does with
classpath: locations), needs that package opened by the module’s
opens declaration. A named module can use classes on the class path
only if it is an automatic module.
The plugin works out the module path when the bundle is built and logs
one Module path: or Class path: line per dependency. A module that
cannot be found, two dependencies that supply the same module, or a
package split across two modules fails the build rather than the
launch (see
Build-Time Failure Signatures).
That check runs on the JDK that runs Maven, so launch the jar on the
same Java feature release.
The reserved JDK namespaces apply to the
class path only. A dependency on the module path that duplicates a JDK
package (an old XML API jar carrying org.w3c.dom, say) usually fails
the build as a split package; exclude it.
generate-wrapper(phase:package)-
Assembles the wrapper distribution under
${project.build.directory}/${applicationDir}/<app-name>with the standardbin/,lib/,conf/layout. Validates theoperatingSystemandcompressionvalues against theOSTypeandCompressionTypeenums; copies the license file, user configurations, runtime dependencies, any<dependencies>matches, and the project jar (creating one if the project’s packaging is notjar); copies the platform-specific Tanuki executable tobin/and native library tolib/; rendersfreemarker.App.sh.into<app-name>.shon Unix or copiesAppCommand.bat.in/InstallApp-NT.bat.in/UninstallApp-NT.bat.inon Windows; rendersfreemarker.wrapper.conf.intowrapper.conffor all platforms; optionally compresses the tree into${project.build.directory}/<app-name>-<version>[-<classifier>]-app.<ext>. install-wrapper(phase:install)-
Installs the aggregate archive into the local Maven repository with classifier
app(or<classifier>-appif aclassifieris also configured). deploy-wrapper(phase:deploy)-
Deploys the aggregate archive to the project’s configured
distributionManagementrepository with the same classifier.
The full set of parameters, in the order a user typically cares about:
operatingSystem(required)-
An
OSTypeenum value, supplied as its string name (hyphens accepted in place of underscores, case-insensitive — e.g.LINUX_X86_64,linux-x86-64, andLinux_X86_64all work). See [ostype-reference]. wrapperListener(required)-
Fully qualified name of the
WrapperListenersubclass that the wrapper should instantiate. This is the class whosestartupandshutdownhooks get called. Typical values:-
org.smallmind.spark.tanukisoft.integration.spring.ClassPathXmlSpringContextWrapperListener— pass Spring XML locations asappParameters. -
Your own subclass of
AbstractWrapperListenerorSpringContextWrapperListener.
-
applicationName(default:${project.artifactId})-
Short name used for the staging directory, the shell script (
<name>.sh), the Windows batch files (<name>.bat,Install<name>-NT.bat,Uninstall<name>-NT.bat), and the wrapper’s ownwrapper.nameproperty. applicationLongName(default:${project.name})-
Long name, used in the wrapper’s
wrapper.displaynameand in Windows service registration. applicationDescription(default:${project.description})-
Description, used in
wrapper.descriptionand in Windows service registration. Whenproject.descriptionis unset it falls back to a generated placeholder string; override for an informative service description. applicationDir(default:application)-
Name of the subdirectory of
${project.build.directory}into which the distribution is staged. licenseFile-
Filesystem path (not classpath) to a Tanuki wrapper license file. Copied into
conf/. Production builds always need one. configurations-
List of filesystem paths. Each file is copied into
conf/. Use this for any additional configuration files the running application needs (Log4j configuration, Spring property files, Terracotta config, etc.). dependencies-
List of
<dependency>entries (groupId+artifactId) that should be bundled inlib/even when their Maven scope iscompile,provided, orsystem(i.e. not normally part of the runtime artifact set). Use for driver jars shipped atprovidedscope to avoid running tests against them. jvmArgs-
List of raw JVM arguments for the wrapper to pass on the child
javacommand. Each element becomes awrapper.java.additional.N=<arg>entry inwrapper.conf. jvmInitMemoryMB/jvmMaxMemoryMB-
Strings setting the wrapper’s
wrapper.java.initmemoryandwrapper.java.maxmemoryproperties (both in megabytes). Omit to let Tanuki use its own defaults. startupTimeoutSeconds-
Integer rendered as
wrapper.startup.timeoutinwrapper.conf: how long the wrapper waits for the listener to report "started" before stopping the JVM.0waits indefinitely; values from 1 to 9 fail the build, matching the listener’s own check. Omit to leave the wrapper’s default of 30. The listener reads the same property atstartto size its keep-alive signals. startupCeilingSeconds-
Integer rendered as
spark.startup.ceilinginwrapper.conf: how long the listener keeps extending the startup timeout whilestartupis still running. Zero or a negative value removes the ceiling. Omit for the listener’s default of 180. See Startup Timeout And Keep-Alive. perApplicationScope-
Boolean rendered as
spark.per.application.scopeinwrapper.conf: whether the listener creates aPerApplicationScopeand runsstartup,shutdown, and control events inside it. Onlytrueturns the scope on. Omit to leave the scope off, which is the listener’s default. See The Per-Application Scope. appParameters-
Ordered list of arguments passed to the wrapper listener’s
main. The plugin prependswrapperListenerto this list (becauseAbstractWrapperListener.mainexpects the concrete listener class as its first argument). Subsequent entries are the application’s own arguments — typically Spring XML resource locations when usingClassPathXmlSpringContextWrapperListener. envArgs-
List of
<envArg>entries (name/value). Each one becomes aset.<name>=<value>inwrapper.conf, available to the wrapper’s own substitution and to the launched JVM’s environment. serviceDependencies-
Ordered list of Windows NT service names this service depends on. Each becomes
wrapper.ntservice.dependency.N=<name>inwrapper.conf. javaCommand(default:java)-
Name of the
javaexecutable to invoke. A fully qualified path avoids relying onPATH. umask(default:0022)-
Process umask on Unix. Rendered as
wrapper.umaskinwrapper.conf. runAs-
Unix user to run the service as. On Windows, renders permissions entries for that account. Left unset, the service runs as the user that launched the wrapper.
waitAfterStartup(default:0)-
Milliseconds to delay between the child JVM becoming ready and the wrapper reporting "started" to the OS. Useful when a service binds a port or reaches a health threshold slightly after
startupreturns. useUpstart(default:false)-
Generate Upstart-style scripts (Ubuntu). Mutually exclusive with
useSystemDfor any single build. useSystemD(default:false)-
Generate systemd unit files.
compression(default:zip)-
Compression type for the aggregate archive. Must be a value of
org.smallmind.nutsnbolts.zip.CompressionType(ZIP,JAR,TGZ,BZ2, etc.). createArtifact(default:true)-
If
true, compress the entire staged tree into a single archive and attach it. Iffalse, leave the staged tree in place — use this if a later build step assembles the distribution its own way. includeVersion(default:true)-
If
true, the staging directory and archive name include-<version>. Iffalse, the stable<applicationName>is used. compactClasspath(default:true)-
If
true, the wrapper’s classpath is a single*wildcard that matches every file inlib/. Iffalse, each jar is listed individually aswrapper.java.classpath.N.trueis simpler and is the only sensible choice when dependencies change between builds. classifier-
Optional Maven-style classifier for the aggregate archive filename.
verbose(default:false)-
Per-file progress logging.
skip(default:false)-
Skip execution.
AbstractWrapperListener-
The bridge class every wrapper integration flows through. Supplies a static
mainthat Tanuki’s wrapper invokes; thatmainreflects the listener class named inargs[0], pre-expands the remaining arguments throughPropertyExpander(so Ant-style${property}placeholders inwrapper.confresolve at runtime), and hands the listener toWrapperManager.start.On
start(String[]), opens a single-threadScheduledExecutorService(daemon worker namedspark-wrapper-signal) in a try-with-resources block and schedules a keep-alive task that callsWrapperManager.signalStarting(timeout * 1000)— the wrapper reads the wait hint in milliseconds — immediately and then everytimeout / 2seconds (wrapper.startup.timeout, read fromWrapperManager.getProperties()instart; default 30, minimum 10;0tells the wrapper to wait indefinitely, and no keep-alive is scheduled). That keeps the wrapper’s watchdog from killing the JVM during slow context refreshes. Once the fail-safe ceiling passes (spark.startup.ceilinginwrapper.conf, 180 seconds when unset; see Startup Timeout And Keep-Alive) the task prints a notice to stderr, stops signalling and cancels its own future; whenstartupreturns or throws the try-with-resourcesclose()shuts the executor down.Owns a
PerApplicationScopeonly whenspark.per.application.scopeinwrapper.confistrue(perApplicationScopeon the Maven plugin). The property is read through the protectedisPerApplicationScopeEnabled(), which subclasses may override, and the decision is settled on the firstgetPerApplicationScope()call and kept. With the scope on,start,stop, andcontrolEventrun their whole body inside it; with it off they run with the inheritedPerApplicationContextbinding alone andgetPerApplicationScope()returnsnull. See The Per-Application Scope.Converts anything thrown by
startuporshutdown, anErrorincluded, into exit code2(STACK_TRACE_ERROR_CODE), and returns the same code whenwrapper.startup.timeoutorspark.startup.ceilingcannot be parsed or is out of range. ImplementscontrolEventto translate Ctrl-C / Close / Shutdown intoWrapperManager.stop(0)only when the process is not under the native wrapper — when the native wrapper is in charge, it delivers these events itself. SpringContextWrapperListener-
Abstract specialization that owns a
ConfigurableApplicationContextfield and mapsstartup(String[])/shutdown()onto the context:-
startupcreates the context on first call by invokingloadApplicationContext(args); when the listener has a scope and that newly loaded context is not yet active, it adds aBeanFactoryPostProcessorthat registers the scope as the singleton beanorg.smallmind.spark.perApplicationScopeduring the refresh. The post-processor is added only when the context is first loaded, not on everystartupthat finds the context inactive; each suchstartupthen refreshes it, inside the scope when there is one. With the scope off, no scope bean is registered and the context is loaded and refreshed with only thePerApplicationContextbinding. -
shutdowncloses the context if one was created and is still active, inside the listener’s scope when it has one.Subclasses implement exactly one method:
loadApplicationContext(String[] args).
-
ClassPathXmlSpringContextWrapperListener-
The zero-code listener. Its
loadApplicationContext(String[] args)returnsnew ClassPathXmlApplicationContext(args, false)— an unrefreshed context, so thatstartupcan add the post-processor that registers the scope bean during the refresh when the scope is on — and every argument passed through the plugin’sappParametersbecomes a classpath-relative Spring XML location. In most deployments this is the only listener you ever reference.
OSType-
Enum of every supported platform triple. Each constant carries an
OSStyle(Windows vs Unix, which decides launch-script selection) plus the platform-specific wrapper executable filename and native library filename. The 19 constants cover AIX (ppc-32, ppc-64), HP-UX (ia-32, ia-64, parisc-32, parisc-64), Linux (ia-64, ppc-32, ppc-64, x86-32, x86-64), macOS (universal-32, universal-64), Solaris (sparc-32, sparc-64, x86-32, x86-64), and Windows (x86-32, x86-64). The plugin’soperatingSystemparameter accepts the enum name with underscores or hyphens. OSStyle-
WINDOWSorUNIX. Selects the launch-script template and the generic native library name (wrapper.dllorlibwrapper.so) that the wrapper looks for inlib/. Also present as the platform-specific name so the wrapper can locate it either way. Dependency-
Configuration POJO for the
<dependencies>list. Fields:groupId,artifactId. Single methodmatchesArtifact(Artifact). EnvironmentArgument-
Configuration POJO for the
<envArgs>list. Fields:name,value.
All Freemarker templates ship as resources inside
spark-tanukisoft-maven-plugin and use SQUARE_BRACKET tag syntax
([#if …], [#list … as …]) so the templates remain legal inside
POM files and shell scripts.
bin/freemarker.App.sh.in-
Unix launch script. Rendered to
<applicationName>.shwhen the selectedOSTypehasOSStyle.UNIX. bin/AppCommand.bat.in/bin/InstallApp-NT.bat.in/bin/UninstallApp-NT.bat.in-
Windows scripts. Copied — not Freemarker-rendered — to
<applicationName>.bat,Install<applicationName>-NT.bat, andUninstall<applicationName>-NT.batrespectively when the selectedOSTypehasOSStyle.WINDOWS. conf/freemarker.wrapper.conf.in-
The wrapper configuration template. Rendered to
wrapper.confregardless ofOSStyle. Its Freemarker model is populated with every plugin parameter that shapes wrapper behavior — the application name / long name / description, the Java command, each JVM argument, heap sizes, startup timeout and ceiling, the per-application scope flag, umask, run-as user, Upstart / systemd flags, wait-after-startup, appParameters, envArgs, service dependencies, and the classpath element list.
Each subproject registers a new Maven packaging type via the Plexus
components.xml bundled in its plugin. The <extensions>true</extensions>
attribute on the plugin declaration is what activates the mapping.
Registered by spark-singularity-maven-plugin. Binds:
| Phase | Bound goal |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The singularity artifact handler reports extension=jar and
addedToClasspath=false. A downstream project that adds a
singularity-packaged module as a dependency gets the jar file but
not classpath inclusion — which is correct, because a Singularity
jar is an executable artifact, not a library.
Registered by spark-tanukisoft-maven-plugin. Binds:
| Phase | Bound goal |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The double bind on package is deliberate: maven-jar-plugin:jar
produces the normal project jar first, and generate-wrapper picks
it up as one of the files staged into lib/. If the normal jar step
were skipped, generate-wrapper would synthesize one from
target/classes/ on its own, but letting maven-jar-plugin run
keeps ordinary test-jar and classifier logic intact.
A minimal POM for a service that should ship as a single executable jar:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-service</artifactId>
<version>1.0.0</version>
<packaging>singularity</packaging> <!--(1)-->
<dependencies>
<!-- ordinary runtime dependencies -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.smallmind</groupId>
<artifactId>spark-singularity-maven-plugin</artifactId>
<version>${smallmind.version}</version>
<extensions>true</extensions> <!--(2)-->
<configuration>
<mainClass>com.example.service.Main</mainClass> <!--(3)-->
</configuration>
</plugin>
</plugins>
</build>
</project>-
Declaring
singularityas the packaging triggers the plugin’s lifecycle mapping. Requires the plugin extension to be enabled. -
Registers the plugin as a build extension so its packaging type and lifecycle mapping are loaded.
-
Fully qualified name of the application’s main class.
Run mvn package. The output is
target/my-service-1.0.0.jar, containing:
my-service-1.0.0.jar
META-INF/
MANIFEST.MF Main-Class: SingularityEntryPoint
Singularity-Class: com.example.service.Main
Singularity-Jar-Cache: true
singularity/
index/singularity.idx Serialized SingularityIndex
lib/
jackson-databind-2.17.0.jar Dependency jar, untouched
jackson-annotations-2.17.0.jar
jackson-core-2.17.0.jar
org/
smallmind/spark/singularity/boot/ Boot classes at the jar root
SingularityEntryPoint.class
SingularityClassLoader.class
...
com/
example/service/ Project classes at the jar root
Main.class
...Run the output with java -jar target/my-service-1.0.0.jar — the
boot class is the manifest’s Main-Class, installs a
SingularityClassLoader from the bundled index, and reflectively
invokes com.example.service.Main.main(String[]).
A minimal POM for a Spring service that should ship as a Tanuki-wrapped distribution:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-service</artifactId>
<version>1.0.0</version>
<packaging>tanukisoft</packaging> <!--(1)-->
<dependencies>
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>spark-tanukisoft-integration</artifactId> <!--(2)-->
<version>${smallmind.version}</version>
</dependency>
<!-- ordinary runtime dependencies -->
</dependencies>
<profiles>
<profile> <!--(3)-->
<id>linux-x86-64</id>
<activation>
<os><name>linux</name><arch>amd64</arch></os>
</activation>
<properties>
<tanukisoft.wrapper.os>LINUX_X86_64</tanukisoft.wrapper.os>
</properties>
</profile>
<profile>
<id>windows-x86-64</id>
<activation>
<os><family>windows</family><arch>amd64</arch></os>
</activation>
<properties>
<tanukisoft.wrapper.os>WINDOWS_X86_64</tanukisoft.wrapper.os>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.smallmind</groupId>
<artifactId>spark-tanukisoft-maven-plugin</artifactId>
<version>${smallmind.version}</version>
<extensions>true</extensions>
<configuration>
<operatingSystem>${tanukisoft.wrapper.os}</operatingSystem> <!--(4)-->
<wrapperListener>
org.smallmind.spark.tanukisoft.integration.spring.ClassPathXmlSpringContextWrapperListener
</wrapperListener> <!--(5)-->
<licenseFile>${user.home}/.m2/wrapper-license.conf</licenseFile>
<jvmInitMemoryMB>512</jvmInitMemoryMB>
<jvmMaxMemoryMB>2048</jvmMaxMemoryMB>
<startupTimeoutSeconds>60</startupTimeoutSeconds>
<startupCeilingSeconds>600</startupCeilingSeconds>
<perApplicationScope>true</perApplicationScope> <!--(6)-->
<jvmArgs>
<jvmArg>-server</jvmArg>
<jvmArg>-XX:+UseG1GC</jvmArg>
</jvmArgs>
<appParameters> <!--(7)-->
<appParameter>spring/application-context.xml</appParameter>
</appParameters>
<useSystemD>true</useSystemD>
</configuration>
</plugin>
</plugins>
</build>
</project>-
The
tanukisoftpackaging triggers the plugin’s lifecycle mapping. -
The runtime bridge — required so
ClassPathXmlSpringContextWrapperListeneris on the classpath at execution time. -
OS-activated profiles let the same POM build the correct wrapper for whatever host runs
mvn package. See the pattern inspark/tanukisoft/mojo/src/main/maven/tanukisoft-pom.xml. -
Driven by whichever profile matched. Must be a valid
OSTypeconstant (underscores or hyphens). -
The classpath XML variant — no application-specific listener class needed.
-
Turns on the listener’s
PerApplicationScope, rendered asspark.per.application.scope=trueinwrapper.conf. Omit it to run with thePerApplicationContextbinding alone. See The Per-Application Scope. -
Prepended with the
wrapperListenerclass name at render time (that is whatAbstractWrapperListener.mainexpects), so the effectivemainarguments at runtime are:[ClassPathXmlSpringContextWrapperListener, spring/application-context.xml]. The listener’sloadApplicationContextignores the first element (the wrapper’s own framing) and passes the rest toClassPathXmlApplicationContext.
Run mvn package. The output tree is:
target/
application/
my-service-1.0.0/
bin/
wrapper-linux-x86-64 Tanuki wrapper executable
my-service.sh Rendered launch script
lib/
libwrapper-linux-x86-64.so Tanuki native library
libwrapper.so Generic-name copy
my-service-1.0.0.jar Your jar
spring-context-6.1.0.jar Dependencies (compile/runtime)
spark-tanukisoft-integration-7.4.0-SNAPSHOT.jar
...
conf/
wrapper-license.conf Copied from licenseFile
wrapper.conf Rendered from Freemarker
my-service-1.0.0-app.zip Aggregate archive (createArtifact=true)To run: cd my-service-1.0.0 && ./bin/my-service.sh console (or
start, or install to register as a systemd unit).
The recommended integration path for Spring applications is to not
write your own wrapper listener — use the shipped
ClassPathXmlSpringContextWrapperListener and pass Spring XML
locations as appParameters.
If you need programmatic context construction (not XML, or XML plus
Java config, or a parent-child hierarchy), subclass
SpringContextWrapperListener:
package com.example.service.wrapper;
import org.smallmind.spark.tanukisoft.integration.spring.SpringContextWrapperListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AnnotationConfigWrapperListener extends SpringContextWrapperListener {
@Override
public ConfigurableApplicationContext loadApplicationContext (String[] args) { (1)
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
for (String arg : args) { (2)
try {
context.register(Class.forName(arg));
} catch (ClassNotFoundException classNotFoundException) {
throw new RuntimeException(classNotFoundException);
}
}
return context; (3)
}
}-
The one abstract hook. Receives the
appParameterslist (minus the wrapper-framing first element). -
Interpret each argument however makes sense for your app. Here they are
@Configurationclass names. -
Return an unrefreshed context —
SpringContextWrapperListenercallsrefresh()itself and, when the listener has a scope (spark.per.application.scope=true), first adds aBeanFactoryPostProcessorthat registers theorg.smallmind.spark.perApplicationScopesingleton during the refresh. A context that arrives already refreshed is detected viaisActive()and left alone, which means the scope bean is never registered in it; with the scope off no scope bean is registered either way. In both cases any definition with arefto it fails the refresh with aBeanCreationExceptioncaused byNoSuchBeanDefinitionException.
Point the plugin at your class:
<wrapperListener>com.example.service.wrapper.AnnotationConfigWrapperListener</wrapperListener>
<appParameters>
<appParameter>com.example.service.config.AppConfig</appParameter>
<appParameter>com.example.service.config.PersistenceConfig</appParameter>
</appParameters>For non-Spring applications, extend AbstractWrapperListener directly:
package com.example.service.wrapper;
import org.smallmind.spark.tanukisoft.integration.AbstractWrapperListener;
public class PlainWrapperListener extends AbstractWrapperListener {
private MyService service;
@Override
public void startup (String[] args) (1)
throws Exception {
service = new MyService();
service.start();
}
@Override
public void shutdown () (2)
throws Exception {
if (service != null) {
service.stop();
}
}
}-
Called on the wrapper’s start thread. The keep-alive daemon is already running — take as long as you need, up to the fail-safe ceiling (
spark.startup.ceilinginwrapper.conf, 180 seconds when unset) plus onewrapper.startup.timeout. -
Called on the wrapper’s stop thread when the OS or an operator asks for shutdown.
Each packaging type targets a different deployment shape. Pick one per project; the two are not layers.
Use <packaging>singularity</packaging> when the deliverable is a
single executable jar invoked with java -jar. Typical fits include
command-line tools, batch jobs, ad-hoc utilities, and any
self-contained application shipped to developers or operators as one
file. Each dependency jar is preserved verbatim under
META-INF/singularity/lib/ and resolved through
SingularityClassLoader, so signed jars, META-INF/services/
descriptors, and per-jar manifests stay intact — the namespace
collapse and resource-merge problems that arise when a shaded
uber-jar flattens every dependency into one tree do not apply.
Use <packaging>tanukisoft</packaging> when the deliverable is a
long-running service supervised by the host operating system.
Typical fits include daemons, web services, and any application
that must register as a Windows service, systemd unit, Upstart job,
or launchd task. The generated tree has the bin/ + lib/
conf/ layout an ops team expects, with native wrapper binaries,
rendered launch scripts, and a watchdog.
The two are not intended to be combined. Singularity exists for the
single-file case — pay the custom-classloader cost so the
deliverable can be one jar. Once a Tanukisoft tree is on the table
that case is gone: the wrapper already builds a classpath from every
jar in lib/, and nesting a Singularity jar there only hides the
dependencies from the ordinary jar-level tooling an operator expects
to use against them.
SingularityEntryPoint.main:
-
Reads the enclosing jar through
SingularityEntryPoint.class.getProtectionDomain().getCodeSource().getLocation(). -
Opens that URL as a
JarInputStream, advances to the manifest, and reads the manifest in the same pass. -
Constructs
SingularityClassLoader(null, manifest, codeSource, jarInputStream)— which (a) triggers the static registration ofSingularityJarURLStreamHandlerFactoryand (b) advances the stream further until it hitsMETA-INF/singularity/index/singularity.idx, deserializes the index, and closes the stream. -
Sets the new loader as
Thread.currentThread().getContextClassLoader(). The system loader remains the loader defined by the JVM on startup — only the context loader is replaced. -
Reads
Singularity-Classfrom the manifest. -
If the value equals
SingularityEntryPoint.class.getName(), does nothing (the recursive case). Otherwise, loads the class through the context loader and reflectively invokes itsmain(String[]). -
In a modular bundle (
Singularity-Modulepresent), the module path is set up first and the main class is loaded from the module named bySingularity-Module. See Modular Mode.
Side effects:
-
URL.setURLStreamHandlerFactoryis called once, from the static initializer ofSingularityClassLoader. The JVM permits this exactly once per process; if another library has already registered a factory, bundle construction throws anError. -
ClassLoader.registerAsParallelCapable()is called at the same time soloadClasscan run in parallel without a global lock.
loadClass(name, resolve) in SingularityClassLoader is:
if (already loaded)
return cached
try findClass // bundled first
except ClassNotFoundException:
if parent != null:
return parent.loadClass(name)
else:
return findSystemClass(name)The conventional parent-first order is deliberately inverted: a
Singularity bundle may contain classes in packages that also exist on
the system classpath (because the JVM was launched with
-classpath …:the-bundle.jar and some transitively reachable
classpath entry duplicates a bundled name). Checking the bundle first
avoids silently preferring a system copy when the bundle has a newer
definition.
Classes in the reserved JDK namespaces (jakarta.xml., org.xml.,
org.w3c.) bypass this loop and go straight to the parent, so the
JVM’s own XML stack is always used even if a bundled library
accidentally ships those packages.
singularity:<outer-jar-url>@/[<inner-jar-path>!/]<entry-name>Parts:
-
<outer-jar-url>— external form of the outer jar’s URL, typicallyfile:/path/to/my-service-1.0.0.jar. -
@/— separator that replaces the!/of the standardjar:protocol to avoid a three-leveljar:jar:nesting. -
<inner-jar-path>(optional) — path of a nested jar underMETA-INF/singularity/lib/. Absent when the entry lives directly in the outer jar. -
!/— standard separator between jar location and intra-jar entry. -
<entry-name>— the entry’s path inside whichever jar contains it.
The first time a class or resource is needed from a dependency jar, the running Singularity jar reads that dependency out of the outer jar and keeps it in memory, so later classes and resources from it are served without touching the file again. Dependencies that are never used are never read. Held dependencies are softly referenced: under memory pressure the JVM may release them, and the next use reads them again. There is no other eviction and no size limit.
useJarCache decides how a dependency is held:
true(default)-
The dependency jar is kept as it is, and each class or resource is decompressed when it is read. First use of a dependency is fast.
false-
Every entry of the dependency jar is decompressed and compressed again when the jar is first used. The memory held is somewhat smaller, but the first use of each dependency is much slower.
Measured with a 110-jar dependency set, loading 3,000 classes in a freshly started jar:
useJarCache true |
useJarCache false |
|
|---|---|---|
Classes from a few dependencies |
0.6–0.7 s |
3.0–3.3 s |
Classes from all 110 dependencies |
0.9–1.0 s |
9.2–9.3 s |
Memory held with all 110 dependencies in use |
105–114 MB |
84–93 MB |
Once a dependency is in memory, reading from it costs the same either
way. Choose false only when memory matters more than startup time.
With false, signed dependency jars have their signatures checked as
they are read into memory, and a tampered one fails at that point. With
true they are not checked. In neither case do signatures affect which
classes may load: Singularity does not attach signers' certificates to
the classes it defines.
AbstractWrapperListener.start(args):
-
Binds the listener’s own
PerApplicationScope(see The Per-Application Scope) for the whole of the call whenspark.per.application.scopeistrue, so everything below,startup(args)included, runs inside it; with the scope off the call runs with thePerApplicationContextbinding alone. -
Reads the wrapper’s startup timeout in seconds through
getStartupTimeoutSeconds(), which consultsWrapperManager.getProperties().getProperty("wrapper.startup.timeout")and defaults to 30. The wrapper configuration only becomes readable once the JVM has connected to the wrapper, somainleaves this lookup tostart. A non-numeric value, or one from 1 to 9, is reported as exit code2withoutstartupbeing invoked. Listeners that want a different policy overridegetStartupTimeoutSeconds(), which replaces the property lookup. -
Opens a single-thread
ScheduledExecutorServicewhose worker is a daemon namedspark-wrapper-signal, declared in a try-with-resources block so it is shut down the momentstartupreturns or throws. Its thread factory is deliberately not wrapped in the scope: the keep-alive task only talks to the wrapper and never resolves per-application data. -
Unless the timeout is
0(the wrapper waits indefinitely, so no keep-alive is scheduled), schedules the keep-alive task withscheduleWithFixedDelay(…, 0, max(1, startupTimeoutSeconds / 2), SECONDS), then invokesstartup(args)on the current thread.
The scheduled keep-alive task, on each firing:
ceiling = getStartupCeilingSeconds() // spark.startup.ceiling, or 180
if ceiling <= 0 or (nanoTime() - startNanos < ceiling):
WrapperManager.signalStarting(startupTimeoutSeconds * 1000) // wait hint in milliseconds
else:
print notice to stderr
signalFuture.cancel(false) // stop reschedulingA RuntimeException thrown by signalStarting is printed to stderr
and the task keeps firing on schedule; a failed signal does not end
the keep-alive.
The invariant: the wrapper’s startup clock runs from JVM launch, and
each signalStarting call resets it to startupTimeoutSeconds (sent
as a millisecond wait hint, the unit the wrapper expects). The
first firing happens as soon as start is entered, so JVM launch and
wrapper hand-shake time do not count against the application, and
each later firing lands at half the timeout, well inside the window
the previous one granted. The task keeps the
wrapper patient until either startup returns — at which point the
try-with-resources close() shuts the executor down and the periodic
task is cancelled — or the fail-safe ceiling is reached.
Tuning hints:
-
Set
wrapper.startup.timeoutinwrapper.conf(startupTimeoutSecondson the Maven plugin) when your application routinely takes more than 30 seconds to reach "ready". Values from 1 to 9 are rejected;0tells the wrapper to wait indefinitely, and the keep-alive is then not scheduled. -
The fail-safe ceiling is a hard stop — once it passes the task prints a notice to stderr, stops signalling and cancels itself even while
startupis still running, after which the wrapper stops the JVM once the window granted by the last signal expires. The longest startup that survives is therefore roughly the ceiling pluswrapper.startup.timeout(about 195 seconds with defaults). -
Set
spark.startup.ceilinginwrapper.conf(startupCeilingSecondson the Maven plugin; 180 when unset) when your application legitimately needs longer. Zero or a negative value removes the ceiling, so the keep-alive runs untilstartupreturns. An unparsable value is reported as exit code2fromstart. Listeners that want a different policy altogether overridegetStartupCeilingSeconds(), which replaces the property lookup.
An AbstractWrapperListener owns one
org.smallmind.nutsnbolts.scope.PerApplicationScope when
spark.per.application.scope in wrapper.conf is true
(perApplicationScope on the Maven plugin). Only the value true, in
any letter case and ignoring surrounding whitespace, turns the scope on;
an absent property or any other value leaves it off, which is the
default. The property is read through the protected
isPerApplicationScopeEnabled(), which a listener overrides to replace
the lookup with its own policy, and the decision is settled the first
time the protected getPerApplicationScope() runs and kept for the life
of the listener: it returns the scope, or null when the scope is off.
With the scope on, the three wrapper callbacks — start (and so
startup), stop (and so shutdown), and controlEvent — each run
their whole body inside that scope’s run / call, so per-application
data registered during startup is visible to shutdown and to the
WrapperManager.stop call a control event makes. The scope binding ends
when each callback returns; the context map described next stays
attached to the thread. With the scope off, the same callbacks run with
the context binding alone.
The listener extends PerApplicationContext whether or not it has a
scope, so constructing it attaches an InheritableThreadLocal map to
the wrapper’s main thread.
A thread inherits that map from the thread that creates it — the thread
calling new Thread, the thread whose submission makes a pool create a
worker, or the submitting thread of a thread-per-task executor — so
threads the application starts from a thread carrying the map carry it
too. Threads created elsewhere, such as the common ForkJoinPool behind
CompletableFuture.Async, carry nothing. With the scope on, the Spring
refresh inside startup runs with *both bindings, and every library
registration made during it — DAOs, sessions, data sources, the Claxon
registry, the pool, resource proxies — goes through a bridging
*Manager that writes to both maps (see
scope — ScopedValue-bound scopes).
Consequently:
-
A thread handed the scope resolves through the scope map first: a thread from the scope’s
boundThreadFactoryor a task on itsboundExecutor(neither needs a binding on the creating or submitting thread), a thread from the staticwrapThreadFactoryor a task onwrapExecutoror anApplicationCarrier(which capture the binding of a thread already inside the scope), or a thread started by a transport, pool, or web server that resolved the listener’s scope when it was constructed or started during the refresh (see below). -
A thread the application starts without the scope, from a thread that carries the context map, carries only that map, which holds the same registrations, so it resolves exactly as every thread does when the scope is off. Applications that never ask for the scope, including those that never heard of
PerApplicationScope, run with the context binding alone. A thread that inherited nothing fails lookups withMissingPerApplicationContextException(metrics lookups return null and the instrumentation is unplugged). -
Only
WireScopedecoding and directPerApplicationScope/*ScopeManagerreads require the scope itself; those threads must be given it, which needs the scope to be on.
The property is the one switch: the context binding is always
established, and the scope is bound only when it is enabled. The
keep-alive executor described above is the one thread start creates
itself, and it is left without the scope because it never resolves
per-application data.
SpringContextWrapperListener makes the same instance available to the
Spring assembly: when the listener has a scope and the context returned
by loadApplicationContext has not been refreshed, startup adds a
BeanFactoryPostProcessor that registers the scope as the singleton
bean named org.smallmind.spark.perApplicationScope
(SpringContextWrapperListener.PER_APPLICATION_SCOPE_BEAN_NAME) during
the refresh — after the bean definitions are loaded and after any
bean-defined BeanDefinitionRegistryPostProcessor has run — so a bean
definition can ref it, though a registry post-processor cannot. With
the scope off nothing is registered under that name, and a ref to it
fails the refresh with a BeanCreationException caused by
NoSuchBeanDefinitionException. An
assembly that must load either way holds the scope through a bean
declared in the XML itself, with no registration step, as
<bean id="perApplicationScope" class="org.smallmind.nutsnbolts.scope.PerApplicationScope" factory-method="getBound"/>:
with the scope on, startup refreshes inside the listener’s scope, so
getBound() returns it; with the scope off, getBound() returns
null, which Spring keeps as a null bean, so a ref injects null
(see holding the scope
as a bean).
Every library bean that accepts a scope resolves the value it is given
once, through PerApplicationScope.resolve, on the thread that
constructs it (constructor and factory parameters) or starts it (Spring
properties, inside afterPropertiesSet / onApplicationEvent /
startup), and keeps the result for every thread and callback it runs:
GrizzlyInitializingBean / JettyInitializingBean (perApplicationScope
property, resolved in onApplicationEvent, binding request threads), the
phalanx transports and WorkManager (constructor argument),
ComponentPool.setPerApplicationScope (resolved in startup()),
PooledDataSourceFactoryBean and DynamicPooledDataSourceInitializingBean
(perApplicationScope property, resolved by the pool they start in
afterPropertiesSet), PooledDataSourceFactory.createPooledDataSource
and PooledConnectionComponentPoolFactory.constructComponentPool
(parameter, resolved by the pool when it starts), OumuamuaConfiguration
(perApplicationScope, resolved in the OumuamuaServer constructor), and
KafkaBackbone (constructor argument). The parameters are required;
there is no scope-less overload. Resolution follows one rule:
-
A scope handed in is used, and under the wrapper with the scope on it must be the listener’s: a
reftoorg.smallmind.spark.perApplicationScoperesolves to the instance the refresh is bound to. A different instance fails withorg.smallmind.nutsnbolts.scope.ScopeExceptionat construction or start; a pool that fails this way stays stopped. With the scope off nothing is bound, so a scope handed in is used as given, and areftoorg.smallmind.spark.perApplicationScopefails the refresh with aBeanCreationExceptioncaused byNoSuchBeanDefinitionException, because the name is not registered. -
null(<null/>in XML, as the shippedmock-wire.xml/rabbitmq-wire.xmlpass, or an unset property) adopts the scope bound on the resolving thread. Under the wrapper with the scope on the refresh runs inside the listener’s scope, sonulland therefare two ways to hand in the same scope; with the scope off nothing is bound, sonullresolves to no scope. A bean resolved on a thread outside the refresh — a lazy-init bean first reached from an application thread, or one started from a background bootstrap — adopts whatever that thread has bound, which is nothing unless the thread is itself inside the scope. -
With neither a scope handed in nor one bound, which with the scope off is every consumer not handed one, the threads the owner starts run with no scope and carry only the
PerApplicationContextthey inherit — under the wrapper, the context map every thread started from the refresh carries.
A context that arrives already refreshed receives no scope bean, and any
ref to it then fails the refresh; null properties in such a context
still adopt the listener’s scope when it has one, because
loadApplicationContext itself runs inside it.
ClassPathXmlSpringContextWrapperListener builds its
ClassPathXmlApplicationContext unrefreshed and leaves the refresh to
startup; a custom loadApplicationContext must do the same.
With the scope on, startup runs the whole of loadApplicationContext
and the refresh inside the listener’s scope: reached through start,
which is how the wrapper calls it, the calling thread is already inside
the scope, and called directly from a thread that is not, startup
binds the scope itself. shutdown closes the context inside the scope
in the same way, so a shutdown() called directly behaves like one
reached through stop. The scope singleton is registered by a
BeanFactoryPostProcessor that startup adds once per context instance
and that registers the singleton on every refresh of that context. A
shutdown() followed by a second startup() on the same listener in
one JVM therefore works only for a context that supports a second
refresh: ClassPathXmlApplicationContext, which
ClassPathXmlSpringContextWrapperListener builds, does;
GenericApplicationContext and AnnotationConfigApplicationContext do
not, and the second refresh fails with IllegalStateException. With
the scope off, startup and shutdown load, refresh, and close with
only the context binding, and the same second-refresh rule applies.
<bean id="grizzlyServer"
class="org.smallmind.web.grizzly.GrizzlyInitializingBean">
<property name="perApplicationScope"
ref="org.smallmind.spark.perApplicationScope"/> <!--(1)-->
...
</bean>-
Registered during the refresh by the post-processor
SpringContextWrapperListener.startupadds when the scope is on; not declared in the XML. With the scope off the name is not registered and thisreffails the refresh with aBeanCreationExceptioncaused byNoSuchBeanDefinitionException. Leaving the property unset resolves to the same scope under the wrapper with the scope on, and to no scope with it off, as does arefto a bean declared withfactory-method="getBound".
AbstractWrapperListener converts exceptions to exit codes as
follows:
null(fromstart)-
Startup succeeded; the wrapper keeps running.
2(fromstartorstop)-
STACK_TRACE_ERROR_CODE.startuporshutdownthrew (anErrorsuch asNoClassDefFoundErrorcounts), orwrapper.startup.timeout/spark.startup.ceilingcould not be parsed or was out of range; the stack trace was printed. The wrapper interprets a non-nullreturn fromstartas "startup failed" and stops the JVM. exitCode(fromstop, whenshutdownreturned normally)-
The wrapper’s requested exit code is passed through unchanged.
WrapperManager.isControlledByNativeWrapper() reports false when
the application is launched without the wrapper executable (for
example, by running java … AbstractWrapperListener
com.example.Listener directly during development). In that mode:
-
controlEvent(WrapperManager.WRAPPER_CTRL_C_EVENT)→WrapperManager.stop(0) -
controlEvent(WrapperManager.WRAPPER_CTRL_CLOSE_EVENT)→WrapperManager.stop(0) -
controlEvent(WrapperManager.WRAPPER_CTRL_SHUTDOWN_EVENT)→WrapperManager.stop(0)
When the native wrapper is in charge, these events are intercepted by the wrapper itself; the Java layer does nothing.
generate-singularity calls
project.addAttachedArtifact(applicationArtifact) with a freshly
created artifact of packaging type jar. The project’s primary
artifact is therefore the generated Singularity jar — the
singularity packaging handler reports extension=jar, so there is
no type mismatch.
generate-wrapper does not attach the aggregate archive itself —
install-wrapper and deploy-wrapper locate it by filename in
target/ and install / deploy it with classifier app. The
classifier ensures the aggregate does not collide with the primary
.jar artifact from maven-jar-plugin:jar that ran earlier in the
lifecycle.
generate-wrapper copies the platform-specific native library to
lib/ twice:
-
Under its platform-specific name (
libwrapper-linux-x86-64.so,wrapper-windows-x86-64.dll, etc.) so maintenance scripts andfilecommand inspection can identify it. -
Under the generic
OSStylename (libwrapper.soorwrapper.dll) so the wrapper’s own default lookup finds it without platform-aware configuration.
Both copies point at the same bundled resource. The duplication
costs a few hundred KB on disk and simplifies wrapper.conf.
spark-singularity-boot-
smallmind-nutsnboltsonly. spark-singularity-maven-plugin-
smallmind-nutsnbolts,spark-singularity-boot,maven-plugin-api,maven-core,maven-model,maven-artifact,maven-compat, andmaven-plugin-annotations. The Maven artifacts areprovidedorcompile— nothing unusual for a Maven plugin. spark-tanukisoft-integration-
smallmind-nutsnbolts,spring-context, andtanukisoft:wrapper(the Java Service Wrapper’s own Java API jar).spring-contextis a hard dependency becauseSpringContextWrapperListeneris part of the artifact; a pure non-Spring user still needs it on the classpath, but only theAbstractWrapperListenerclass is referenced. spark-tanukisoft-maven-plugin-
freemarker(forwrapper.confrendering), plus the same Maven provided/compile matrix.
- "Unable to locate the boot class dependencies"
-
generate-singularitywalkspluginArtifactslooking fororg.smallmind:spark-singularity-boot. The plugin’s POM has it as a compile-scope dependency, so under normal circumstances it is always present. This error means the plugin was installed with a modified POM, or Maven’s dependency resolution stripped the boot artifact. - "Modular packaging requires the project to be a named module…"
-
modularistrue, but the project has nomodule-info.java. Add one, or turn modular mode off. - "Unable to resolve the module path of module(…)"
-
In modular mode, the module graph does not resolve. The rest of the message is the JDK’s own explanation, usually one of: a module that is required but missing from the dependencies, a package found in two modules (often an old API jar duplicating a JDK or Jakarta module; exclude it), or two modules exporting the same package to one module.
- "Module(…) is supplied by more than one dependency(…)"
-
In modular mode, two dependency jars carry the same module name. Exclude one of them.
- "Missing singularity index"
-
SingularityClassLoader’s constructor advanced through every entry of the outer jar and did not find `META-INF/singularity/index/singularity.idx. Either the jar is not actually a Singularity bundle (wrongMain-Class, wrong layout) or the index-writing step ingenerate-singularitywas interrupted. - "Unknown operating system type(…)"
-
generate-wrappercould not parse theoperatingSystemparameter as anOSTypeconstant. Valid names are listed inOSType.values()— underscores and hyphens are interchangeable, case-insensitive. - "Unknown compression type(…)"
-
Same as above for
compressionvsCompressionType. - "Unknown os style(…)"
-
The plugin derived an unrecognized
OSStylefrom a validatedOSType. This is an internal consistency check; anOSTypeconstant whoseOSStyleis neitherWINDOWSnorUNIXwould trigger it, but no such constant exists, so seeing this error means the enum has been modified. - "Unable to load template(…)"
-
processFreemarkerTemplatecould not resolve a bundled Freemarker resource. The template resource path is built fromGenerateWrapperMojo.class.getPackage().getName()plusbin/orconf/; a plugin jar that has been repackaged without theinstallation/resource root will fail here.
NoClassDefFoundErroron a class that is inside a bundled library-
Almost always one of two things:
-
The class’s package is in the reserved JDK namespaces (
jakarta.xml.,org.xml.,org.w3c.) and the loader refused to define it. Add it to an allow-list if genuinely necessary (requires modifyingSingularityClassLoader.OPERABLE_NAMESPACES), or prefer the JDK’s own implementation. -
The class is loaded by a framework that captured the system class loader before
SingularityEntryPoint.mainreplaced the context class loader. JNI libraries and some JDBC drivers cache loaders early; make sure the offending framework is initialized from within the application’smain, not from a static initializer that runs before it.
-
InaccessibleObjectException: … does not "opens …" to …-
In a modular bundle, a framework (Spring, Jackson, Hibernate, and so on) tried to reflect into a package of a module on the module path that the module does not open. Add an
opensdeclaration for that package to the module’s descriptor; a Singularity jar has no equivalent of--add-opens. ZipExceptionnaming a nested jar ("Encrypted entry…", "Unsupported compression method…", "Invalid central directory…")-
A dependency jar is damaged, or uses a zip feature that Singularity does not read: encryption, or a compression method other than stored or deflated. Standard jar tools do not produce such jars; rebuild or replace the dependency.
StackOverflowError during static initialization of
SingularityClassLoader::
Another library already installed a URLStreamHandlerFactory.
The JVM blocks a second installation, and if the first one
delegates to the platform default for unknown protocols, a
Singularity-built jar running on top of an app that also wants
to own the URL protocol must be reconciled manually — register
the Singularity handler into the pre-existing factory.
BeanCreationExceptioncaused byNoSuchBeanDefinitionExceptionnamingorg.smallmind.spark.perApplicationScopeduring the refresh-
A bean definition holds a
refto the scope singleton thatSpringContextWrapperListenerregisters, but the listener has no scope to register:spark.per.application.scopeis absent fromwrapper.confor is nottrue(perApplicationScopeon the Maven plugin), or the context returned byloadApplicationContextarrived already refreshed. Set the property, or declare the scope withfactory-method="getBound"instead, which injectsnullwhen the scope is off. See The Per-Application Scope. WrapperManagererrors ("WrapperStartException", "not initialized")-
AbstractWrapperListener.mainwas invoked outside a wrapper process, or the wrapper process was started withoutwrapper.confpresent. During development, run./bin/<app>.sh consoleto exercise the full wrapper path; running the jar directly withjava -jar …puts the listener into "unwrapped" mode where Ctrl-C triggersWrapperManager.stop(0)but most wrapper features are inert.
The Tanuki wrapper requires a license for production use. The plugin
has no opinion about where the license comes from — it just copies
whatever path licenseFile names into conf/. Common patterns:
-
Keep the license under
~/.m2/wrapper-license.confon every build host; pass<licenseFile>${user.home}/.m2/wrapper-license.conf</licenseFile>. -
Keep the license in a
secret-resourcessubmodule that the build system unpacks on the CI runner; pass a repo-relative path. -
Leave
licenseFileunset during development builds (the wrapper still runs in evaluation mode) and set it only in the release profile.
AbstractWrapperListener.main can be invoked with the wrapper binary
not in the loop:
java -cp … org.smallmind.spark.tanukisoft.integration.AbstractWrapperListener \
com.example.MyListener arg1 arg2In that mode:
-
Property expansion (
${…}) onargsstill runs. -
The keep-alive task still runs —
WrapperManager.signalStartingjust becomes a no-op whenisControlledByNativeWrapper()isfalse. -
Ctrl-C reaches
controlEventand triggersWrapperManager.stop(0), which unwinds through the listener’sstopcallback and callsshutdown.
Use this mode during development; use the real wrapper binary for anything that looks like production.
- One
URLStreamHandlerFactoryper JVM -
SingularityClassLoader’s static initializer installs the `singularity:handler by callingURL.setURLStreamHandlerFactory. The JVM permits exactly one such installation; any subsequent call — including, recursively, a second Singularity jar loaded into the same JVM — throws anError. This is rarely a problem because a Singularity jar is typically the only launch artifact, but embedding Singularity inside a host that already owns URL protocols needs care. - Reserved-namespace list is fixed
-
The hard-coded
INOPERABLE_NAMESPACES/OPERABLE_NAMESPACESarrays inSingularityClassLoadercannot be configured at build or boot time. A bundled library whose platform-shadowed class must come from the bundle (a newerorg.xml.sax, say) cannot be accommodated without a code change. - Module path only for a modular application
-
A class path bundle (the default) ignores the module descriptors its dependencies carry. Modular mode requires the project itself to be a named module; selected dependencies cannot be put on a module path beneath a class path application. There is no equivalent of
--add-opens,--add-exports, or--add-reads. - Exclusions and bundled-dependencies match exactly
-
Exclusion(singularity) andDependency(tanukisoft) both comparegroupIdandartifactIdas exact strings. There is no glob, no version filter, and no scope filter. For most projects this is sufficient; large multi-module builds that want to exclude whole dependency groups must enumerate each artifact. - Single
URLStreamHandlerchain -
A library that installs its own
URLStreamHandlerfor a non-singularityprotocol afterSingularityClassLoader’s static initializer has run will be dispatched correctly, but any library that registers before the class loader is first touched must be compatible with the JVM default-handler pattern, because Singularity’s factory returns `nullfor non-singularityprotocols and the JVM falls back to its built-in search. - No in-flight reloading
-
SingularityClassLoaderreads the index once in its constructor and never re-reads it. Swapping the bundle file while the JVM is running has no effect until the process is restarted. - Wrapper generation is single-platform per build
-
generate-wrappertakes exactly oneoperatingSystemvalue per execution. Producing a multi-platform distribution requires multiple plugin executions (or multiple Maven modules). The example POM uses<os>activation to pick the right value for whichever host runs the build — which is the normal pattern, but means a single build host cannot produce every platform’s wrapper. - Upstart and systemd are mutually exclusive
-
Both
useUpstartanduseSystemDfeed the same Freemarker template. Setting bothtruein one build is not a supported configuration; pick one per distribution. - Tanuki wrapper binaries are bundled, not downloaded
-
Every supported platform’s wrapper binary lives inside
spark-tanukisoft-maven-pluginas a resource. The plugin jar is therefore large (~25 MB). Adding a new platform means adding a binary and anOSTypeconstant, which requires rebuilding the plugin — there is no runtime extension point. - Build directory reuse is not self-cleaning
-
generate-singularityandgenerate-wrapperboth rely on Maven’scleanto remove stale contents. Incremental builds that do not clean can carry stale library jars or index entries forward, producing a bundle with ghost entries. Prefermvn clean packageovermvn packagefor release builds. AbstractWrapperListener.mainis a static entry point, not a bean-
The listener is reflectively constructed via
Class.forName(…).getConstructor().newInstance(), so every concrete listener class must expose a public no-arg constructor. Dependencies have to be acquired insidestartup(e.g. through the Spring context constructed there), not through constructor injection. - Singularity jars are not hermetic
-
A Singularity jar includes its bundled dependencies, but the JVM still resolves platform classes from the JDK. A bundle compiled against JDK 21 will fail at runtime on JDK 17 the same way a normal jar would. Plan JDK version management at the deployment layer, not at the bundle layer.
-
NUTSNBOLTS.adoc —
smallmind-nutsnboltsprovidesCompressionType(used by both plugins for archive compression),PropertyExpander(used byAbstractWrapperListener.main),PerApplicationContext(base class ofAbstractWrapperListener),PerApplicationScope(owned byAbstractWrapperListenerwhenspark.per.application.scopeistrue; see The Per-Application Scope), andClassPathTemplateLoader(used bygenerate-wrapperfor Freemarker). -
PHALANX.adoc — for services that also need coordinated cluster membership in the wrapped runtime.
-
Tanuki Software Java Service Wrapper documentation — authoritative reference for
wrapper.confproperties and the native wrapper’s behavior.