Skip to content

Latest commit

 

History

History
2470 lines (2091 loc) · 106 KB

SPARK.adoc

File metadata and controls

2470 lines (2091 loc) · 106 KB

SmallMind Spark

Table of Contents

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 custom ClassLoader that reads nested jars in place, so java -jar my-app.jar works 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 with bin/, lib/, and conf/, the correct platform-specific wrapper executable, rendered launch scripts (shell / batch / Windows service install-uninstall), and a populated wrapper.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

spark/singularity

spark-singularity-boot — the boot classes that end up inside every Singularity jar (entry point, ClassLoader, URL handler, index model).

spark-singularity-maven-plugin — the generate-singularity, install-singularity, and deploy-singularity goals plus the singularity packaging type.

spark/tanukisoft

spark-tanukisoft-integration — AbstractWrapperListener and its Spring specializations, the classes a running wrapped application links against to bridge the wrapper’s start / stop callbacks to application code.

spark-tanukisoft-maven-plugin — the generate-wrapper, install-wrapper, and deploy-wrapper goals plus the tanukisoft packaging type. Carries every Tanuki wrapper binary as a bundled resource.

Java services that wish to distribute themselves in robust self-executing formats must answer some common issues:

  1. 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.

  2. 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.

  3. 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 under META-INF/singularity/lib/, project classes at the root, serialized SingularityIndex recording the provenance of every class and resource.

  • Provides a custom ClassLoader that resolves classes from nested jars in place (SingularityClassLoader), backed by a custom singularity: 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; useJarCache chooses between fast first use and a smaller footprint.

  • Turns the jar into an executable bootstrap via SingularityEntryPoint: Main-Class of the outer jar, reflectively invokes whatever fully qualified class name was configured as mainClass at build time.

  • Runs a modular application on a module path when the project is a named module and modular is 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) with bin/, 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.conf from Freemarker templates — <app>.sh for Unix, <app>.bat / Install<app>-NT.bat / Uninstall<app>-NT.bat for Windows, and wrapper.conf for 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 AbstractWrapperListener that 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 SpringContextWrapperListener and ClassPathXmlSpringContextWrapperListener so 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 (singularity and tanukisoft) that rebind package, install, and deploy phases to the module’s own goals via Plexus components.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, use maven-shade-plugin; Singularity is the other choice.

  • It does not hide Tanuki’s Java Service Wrapper. wrapper.conf is still wrapper.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 point licenseFile at 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

At A Glance → Singularity Quick Start.

… running that service as a Windows service or a Linux daemon on a long-lived host

At A Glance → Tanukisoft Quick Start.

… building a Spring application that should come up on host boot and shut down gracefully on host shutdown

Spring Wrapper-Listener Pattern → Tanukisoft Quick Start.

… debugging a ClassNotFoundException coming out of a Singularity jar

Class Loading Rules → Class Path Order → Reserved JDK Namespaces.

… packaging an application that has its own module-info.java

Modular Mode.

… tuning how much memory a running Singularity jar holds for its dependencies, or how fast it starts

Nested Jars In Memory.

… debugging "the service started, then the wrapper killed it" in production

Startup Timeout And Keep-Alive.

… adding a new platform (OS/arch) to the plugin’s supported list

OSType Reference → Operational Notes.

… trying to exclude a specific dependency from a Singularity bundle because it is already present on the host

Excluding Dependencies.

Problem Use Notes

Package a single, self-executing jar that contains every runtime dependency without rewriting bytecode

<packaging>singularity</packaging> with spark-singularity-maven-plugin

Dependency jars land under META-INF/singularity/lib/ verbatim; a custom ClassLoader reads them in place.

Run an application that is a named module, with its modular dependencies on a module path

<modular>true</modular>

The module graph is checked when the bundle is built. See Modular Mode.

Reduce the memory a running Singularity jar holds for its dependencies

<useJarCache>false</useJarCache>

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

<packaging>tanukisoft</packaging> with spark-tanukisoft-maven-plugin

Produces bin/, lib/, conf/ and platform-specific launch scripts from Freemarker templates.

Run a Spring application under the wrapper without writing any wrapper-listener class yourself

Set wrapperListener to org.smallmind.spark.tanukisoft.integration.spring.ClassPathXmlSpringContextWrapperListener

Pass Spring XML resource locations as appParameters.

Write a custom wrapper listener (non-Spring or custom context factory)

Subclass AbstractWrapperListener and implement startup / shutdown

Built-in keep-alive signaller pings the watchdog while startup runs.

Control the Spring context factory in a non-trivial way (programmatic construction, multiple contexts, non-classpath resources)

Subclass SpringContextWrapperListener and implement loadApplicationContext(String[])

Lifecycle (startup/shutdown) is handled for you; only the factory hook is abstract.

Exclude a dependency from the Singularity bundle (e.g. the JDK already has it, or a host agent provides it)

<exclusions> list in the plugin’s <configuration> section

Matches on groupId + artifactId only.

Bundle additional compile- or provided-scope jars in the wrapper distribution (e.g. JDBC drivers installed via provided)

<dependencies> list in the plugin’s <configuration> section

Matches on groupId + artifactId; copies the matching artifact into lib/.

Make the wrapper install as a Windows NT service with specific service dependencies

<serviceDependencies> list

Rendered into wrapper.ntservice.dependency.N entries in wrapper.conf.

Make the wrapper install as a systemd or Upstart unit on Linux

<useSystemD>true</useSystemD> or <useUpstart>true</useUpstart>

Both default to false; only one should be enabled per build.

Deploy the aggregate archive to a Maven repository so other modules can consume it

The install-wrapper / deploy-wrapper goals run automatically under the tanukisoft lifecycle

The aggregate archive is attached with classifier app.

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 org/smallmind/spark/tanukisoft/maven/bin/ and …​/lib/ resource roots. They are copied verbatim into the generated distribution. If a platform you need is not in OSType, the plugin will reject the build with "Unknown operating system type(…​)". Adding a platform requires placing the correct wrapper binaries under those resource paths and adding the corresponding OSType enum constant.

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 mapping

The 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:

  1. Boot classes at the jar root under org/smallmind/spark/singularity/boot/. These are copied into the outer jar at package time from the spark-singularity-boot plugin dependency. They are reachable by a fresh JVM’s system class loader.

  2. Application classes at the jar root, in their natural package directories. Same position as a normal jar’s contents; same resolution story.

  3. Library jars under META-INF/singularity/lib/, each one kept verbatim as a .jar file. Nothing unpacks them. A normal system class loader cannot reach classes inside these nested jars, so a custom ClassLoader is necessary.

Glue holds the three apart:

Index

A serialized SingularityIndex at META-INF/singularity/index/singularity.idx records, for every class and resource, which of the three populations it belongs to. For library entries, it also records which library jars inside lib/ 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 form singularity:<outer-jar-url>@/META-INF/singularity/lib/<lib>!/<entry>. SingularityJarURLStreamHandler claims it JVM-wide from SingularityClassLoader’s static initializer, so any component that resolves an entry’s URL (including `javax.crypto.JarVerifier, ServiceLoader, Spring’s PathMatchingResourcePatternResolver, and URL-based classloaders layered on top) can reach the bytes.

Custom ClassLoader

SingularityClassLoader reads the index at boot and serves findClass / findResource from it, addressing jar-root entries with jar: URLs and library entries with singularity: 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

SingularityEntryPoint is the jar’s Main-Class. On main, it opens the enclosing jar via CodeSource, constructs a SingularityClassLoader, installs it as the context class loader, and reflectively invokes the application’s real main — whose class name is stored in the manifest attribute Singularity-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

AbstractWrapperListener implements WrapperListener and 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 calls WrapperManager.signalStarting(int) as soon as start begins and then at half the startup timeout so a slow startup is not killed by the watchdog.

Spring specialization

SpringContextWrapperListener extends AbstractWrapperListener and maps the abstract startup / shutdown hooks onto the life of a Spring ConfigurableApplicationContext. Subclasses need only implement one factory method. This is the layer most applications should use, directly or through ClassPathXmlSpringContextWrapperListener.

Build-time assembly

spark-tanukisoft-maven-plugin stages a bin/ + 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) and wrapper.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 its META-INF/singularity/{lib,index} subtree, extracts the boot classes from the plugin’s own spark-singularity-boot dependency into the tree, walks project.getRuntimeArtifacts() and copies each non-excluded dependency jar verbatim into lib/ (while recording every one of its entries in the SingularityIndex), walks target/classes/ and copies every file into the tree (while recording each in the index), serializes the index to META-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 as generate-singularity, looks for a sibling .asc signature file, attaches it via AscArtifactMetadata if present, and installs the artifact into the local repository via ArtifactInstaller.install.

deploy-singularity (phase: deploy)

Same as install-singularity, except it pushes to the project’s configured distributionManagement repository through ArtifactDeployer.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. SingularityEntryPoint reads it and reflectively calls its main(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), and mainClass must 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. true favors speed; false uses 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

Main-Class

Always org.smallmind.spark.singularity.boot.SingularityEntryPoint.

Singularity-Class

The application’s main class, from mainClass.

Singularity-Module

The application’s module name. Present only in a modular bundle.

Singularity-Jar-Cache

true or false, from useJarCache. A bundle without this attribute behaves as true.

SingularityEntryPoint

Main-Class of every generated jar. Its main(String…​) opens the enclosing jar through its own CodeSource, reads the manifest, constructs a SingularityClassLoader bound to that jar, installs the loader as the context class loader, and reflectively invokes the Singularity-Class’s `main with the original argument array. In a modular bundle it first sets up the module path (see Modular Mode). Silently ignores the degenerate case where Singularity-Class equals itself (so the boot does not recurse).

SingularityClassLoader

The runtime’s center. Reads the serialized SingularityIndex off the jar and serves findClass / findResource / findResources from 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 SingularityJarURLStreamHandlerFactory JVM-wide, which is a deliberate singleton: the JVM permits exactly one URLStreamHandlerFactory to be registered, and SingularityClassLoader must 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 ModuleFinder over all of them.

NestedJarFile, CachedJarFile, RecompressedJarFile

A dependency jar held in memory, and the two ways of holding it that useJarCache chooses between (see Nested Jars In Memory).

SingularityJarURLConnection

URLConnection for the singularity: protocol. Parses the URL form singularity:<outer>@/[<inner-jar>!/]<entry> and returns an InputStream over the addressed entry, reusing a dependency jar already held in memory when possible.

SingularityJarURLStreamHandler

Standard URLStreamHandler that returns a fresh SingularityJarURLConnection for every URL.

SingularityJarURLStreamHandlerFactory

URLStreamHandlerFactory registered JVM-wide. Claims the singularity protocol; returns null for everything else so the platform’s default handler selection stays in effect.

Exclusion

Configuration POJO with groupId and artifactId fields and a single matchesArtifact(Artifact) predicate. Both coordinates must match exactly; version is ignored.

AscArtifactMetadata

Maven ArtifactMetadata implementation that carries a detached-GPG .asc file 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 .asc is found next to the generated jar.

CopyFileVisitor

SimpleFileVisitor<Path> used by generate-singularity to walk target/classes/. On each file, copies it to the matching location under the singularity build tree and registers the relative resource path (with / separators) in the SingularityIndex via addFileName.

SingularityClassLoader.loadClass(String, boolean) follows a self-before-parent strategy:

  1. Check findLoadedClass — return an already-defined class directly.

  2. Otherwise call findClass — the bundled definition is preferred.

  3. If findClass throws ClassNotFoundException, delegate to the parent (or to findSystemClass if no parent is configured).

findClass itself:

  1. Rejects names in reserved namespaces (see below) so the platform’s own copies resolve through the parent.

  2. Looks up <binary>.class in the index; if absent, throws ClassNotFoundException.

  3. Determines a CodeSource URL based on the entry’s protocol:

    • jar:<outer>!/… → CodeSource is <outer>!/.

    • singularity:<outer>@/<inner>!/… → CodeSource is singularity:<outer>@/<inner> (no trailing !/). This form compensates for a quirk in javax.crypto.JarVerifier that would otherwise mangle the URL.

  4. Reads the bytes via URL.openStream().

  5. Lazily defines the enclosing package on first touch, using the outer manifest’s specification/implementation titles and the optional seal base.

  6. Calls defineClass(name, bytes, 0, bytes.length, protectionDomain) where the protection domain has AllPermission.

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 getResources returned at most one URL per name, and ServiceLoader saw only one jar’s providers for each service. A project that relied on a dependency overriding one of its own resources, or on a later dependency overriding an earlier one, now gets the class path behavior instead.

SingularityClassLoader deliberately refuses to define classes whose names begin with:

  • jakarta.xml. — except jakarta.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>
  1. Oracle JDBC driver provided by the host.

  2. 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>
  1. 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 uses run as named modules.

  • A dependency without a module descriptor runs as an automatic module when one of those modules requires it, 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 standard bin/, lib/, conf/ layout. Validates the operatingSystem and compression values against the OSType and CompressionType enums; copies the license file, user configurations, runtime dependencies, any <dependencies> matches, and the project jar (creating one if the project’s packaging is not jar); copies the platform-specific Tanuki executable to bin/ and native library to lib/; renders freemarker.App.sh.in to <app-name>.sh on Unix or copies AppCommand.bat.in / InstallApp-NT.bat.in / UninstallApp-NT.bat.in on Windows; renders freemarker.wrapper.conf.in to wrapper.conf for 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>-app if a classifier is also configured).

deploy-wrapper (phase: deploy)

Deploys the aggregate archive to the project’s configured distributionManagement repository with the same classifier.

The full set of parameters, in the order a user typically cares about:

operatingSystem (required)

An OSType enum value, supplied as its string name (hyphens accepted in place of underscores, case-insensitive — e.g. LINUX_X86_64, linux-x86-64, and Linux_X86_64 all work). See [ostype-reference].

wrapperListener (required)

Fully qualified name of the WrapperListener subclass that the wrapper should instantiate. This is the class whose startup and shutdown hooks get called. Typical values:

  • org.smallmind.spark.tanukisoft.integration.spring.ClassPathXmlSpringContextWrapperListener — pass Spring XML locations as appParameters.

  • Your own subclass of AbstractWrapperListener or SpringContextWrapperListener.

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 own wrapper.name property.

applicationLongName (default: ${project.name})

Long name, used in the wrapper’s wrapper.displayname and in Windows service registration.

applicationDescription (default: ${project.description})

Description, used in wrapper.description and in Windows service registration. When project.description is 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 in lib/ even when their Maven scope is compile, provided, or system (i.e. not normally part of the runtime artifact set). Use for driver jars shipped at provided scope to avoid running tests against them.

jvmArgs

List of raw JVM arguments for the wrapper to pass on the child java command. Each element becomes a wrapper.java.additional.N=<arg> entry in wrapper.conf.

jvmInitMemoryMB / jvmMaxMemoryMB

Strings setting the wrapper’s wrapper.java.initmemory and wrapper.java.maxmemory properties (both in megabytes). Omit to let Tanuki use its own defaults.

startupTimeoutSeconds

Integer rendered as wrapper.startup.timeout in wrapper.conf: how long the wrapper waits for the listener to report "started" before stopping the JVM. 0 waits 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 at start to size its keep-alive signals.

startupCeilingSeconds

Integer rendered as spark.startup.ceiling in wrapper.conf: how long the listener keeps extending the startup timeout while startup is 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.scope in wrapper.conf: whether the listener creates a PerApplicationScope and runs startup, shutdown, and control events inside it. Only true turns 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 prepends wrapperListener to this list (because AbstractWrapperListener.main expects the concrete listener class as its first argument). Subsequent entries are the application’s own arguments — typically Spring XML resource locations when using ClassPathXmlSpringContextWrapperListener.

envArgs

List of <envArg> entries (name / value). Each one becomes a set.<name>=<value> in wrapper.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> in wrapper.conf.

javaCommand (default: java)

Name of the java executable to invoke. A fully qualified path avoids relying on PATH.

umask (default: 0022)

Process umask on Unix. Rendered as wrapper.umask in wrapper.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 startup returns.

useUpstart (default: false)

Generate Upstart-style scripts (Ubuntu). Mutually exclusive with useSystemD for 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. If false, 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>. If false, the stable <applicationName> is used.

compactClasspath (default: true)

If true, the wrapper’s classpath is a single * wildcard that matches every file in lib/. If false, each jar is listed individually as wrapper.java.classpath.N. true is 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 main that Tanuki’s wrapper invokes; that main reflects the listener class named in args[0], pre-expands the remaining arguments through PropertyExpander (so Ant-style ${property} placeholders in wrapper.conf resolve at runtime), and hands the listener to WrapperManager.start.

On start(String[]), opens a single-thread ScheduledExecutorService (daemon worker named spark-wrapper-signal) in a try-with-resources block and schedules a keep-alive task that calls WrapperManager.signalStarting(timeout * 1000) — the wrapper reads the wait hint in milliseconds — immediately and then every timeout / 2 seconds (wrapper.startup.timeout, read from WrapperManager.getProperties() in start; default 30, minimum 10; 0 tells 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.ceiling in wrapper.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; when startup returns or throws the try-with-resources close() shuts the executor down.

Owns a PerApplicationScope only when spark.per.application.scope in wrapper.conf is true (perApplicationScope on the Maven plugin). The property is read through the protected isPerApplicationScopeEnabled(), which subclasses may override, and the decision is settled on the first getPerApplicationScope() call and kept. With the scope on, start, stop, and controlEvent run their whole body inside it; with it off they run with the inherited PerApplicationContext binding alone and getPerApplicationScope() returns null. See The Per-Application Scope.

Converts anything thrown by startup or shutdown, an Error included, into exit code 2 (STACK_TRACE_ERROR_CODE), and returns the same code when wrapper.startup.timeout or spark.startup.ceiling cannot be parsed or is out of range. Implements controlEvent to translate Ctrl-C / Close / Shutdown into WrapperManager.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 ConfigurableApplicationContext field and maps startup(String[]) / shutdown() onto the context:

  • startup creates the context on first call by invoking loadApplicationContext(args); when the listener has a scope and that newly loaded context is not yet active, it adds a BeanFactoryPostProcessor that registers the scope as the singleton bean org.smallmind.spark.perApplicationScope during the refresh. The post-processor is added only when the context is first loaded, not on every startup that finds the context inactive; each such startup then 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 the PerApplicationContext binding.

  • shutdown closes 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) returns new ClassPathXmlApplicationContext(args, false) — an unrefreshed context, so that startup can add the post-processor that registers the scope bean during the refresh when the scope is on — and every argument passed through the plugin’s appParameters becomes 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’s operatingSystem parameter accepts the enum name with underscores or hyphens.

OSStyle

WINDOWS or UNIX. Selects the launch-script template and the generic native library name (wrapper.dll or libwrapper.so) that the wrapper looks for in lib/. 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 method matchesArtifact(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>.sh when the selected OSType has OSStyle.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, and Uninstall<applicationName>-NT.bat respectively when the selected OSType has OSStyle.WINDOWS.

conf/freemarker.wrapper.conf.in

The wrapper configuration template. Rendered to wrapper.conf regardless of OSStyle. 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

process-resources

maven-resources-plugin:resources

compile

maven-compiler-plugin:compile

process-test-resources

maven-resources-plugin:testResources

test-compile

maven-compiler-plugin:testCompile

test

maven-surefire-plugin:test

package

spark-singularity-maven-plugin:generate-singularity

install

spark-singularity-maven-plugin:install-singularity

deploy

spark-singularity-maven-plugin:deploy-singularity

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

process-resources

maven-resources-plugin:resources

compile

maven-compiler-plugin:compile

process-test-resources

maven-resources-plugin:testResources

test-compile

maven-compiler-plugin:testCompile

test

maven-surefire-plugin:test

package

maven-jar-plugin:jar, then spark-tanukisoft-maven-plugin:generate-wrapper

install

spark-tanukisoft-maven-plugin:install-wrapper

deploy

spark-tanukisoft-maven-plugin:deploy-wrapper

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>
  1. Declaring singularity as the packaging triggers the plugin’s lifecycle mapping. Requires the plugin extension to be enabled.

  2. Registers the plugin as a build extension so its packaging type and lifecycle mapping are loaded.

  3. 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>
  1. The tanukisoft packaging triggers the plugin’s lifecycle mapping.

  2. The runtime bridge — required so ClassPathXmlSpringContextWrapperListener is on the classpath at execution time.

  3. OS-activated profiles let the same POM build the correct wrapper for whatever host runs mvn package. See the pattern in spark/tanukisoft/mojo/src/main/maven/tanukisoft-pom.xml.

  4. Driven by whichever profile matched. Must be a valid OSType constant (underscores or hyphens).

  5. The classpath XML variant — no application-specific listener class needed.

  6. Turns on the listener’s PerApplicationScope, rendered as spark.per.application.scope=true in wrapper.conf. Omit it to run with the PerApplicationContext binding alone. See The Per-Application Scope.

  7. Prepended with the wrapperListener class name at render time (that is what AbstractWrapperListener.main expects), so the effective main arguments at runtime are: [ClassPathXmlSpringContextWrapperListener, spring/application-context.xml]. The listener’s loadApplicationContext ignores the first element (the wrapper’s own framing) and passes the rest to ClassPathXmlApplicationContext.

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)
  }
}
  1. The one abstract hook. Receives the appParameters list (minus the wrapper-framing first element).

  2. Interpret each argument however makes sense for your app. Here they are @Configuration class names.

  3. Return an unrefreshed context — SpringContextWrapperListener calls refresh() itself and, when the listener has a scope (spark.per.application.scope=true), first adds a BeanFactoryPostProcessor that registers the org.smallmind.spark.perApplicationScope singleton during the refresh. A context that arrives already refreshed is detected via isActive() 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 a ref to it fails the refresh with a BeanCreationException caused by NoSuchBeanDefinitionException.

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();
    }
  }
}
  1. 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.ceiling in wrapper.conf, 180 seconds when unset) plus one wrapper.startup.timeout.

  2. 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:

  1. Reads the enclosing jar through SingularityEntryPoint.class.getProtectionDomain().getCodeSource().getLocation().

  2. Opens that URL as a JarInputStream, advances to the manifest, and reads the manifest in the same pass.

  3. Constructs SingularityClassLoader(null, manifest, codeSource, jarInputStream) — which (a) triggers the static registration of SingularityJarURLStreamHandlerFactory and (b) advances the stream further until it hits META-INF/singularity/index/singularity.idx, deserializes the index, and closes the stream.

  4. 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.

  5. Reads Singularity-Class from the manifest.

  6. If the value equals SingularityEntryPoint.class.getName(), does nothing (the recursive case). Otherwise, loads the class through the context loader and reflectively invokes its main(String[]).

  7. In a modular bundle (Singularity-Module present), the module path is set up first and the main class is loaded from the module named by Singularity-Module. See Modular Mode.

Side effects:

  • URL.setURLStreamHandlerFactory is called once, from the static initializer of SingularityClassLoader. The JVM permits this exactly once per process; if another library has already registered a factory, bundle construction throws an Error.

  • ClassLoader.registerAsParallelCapable() is called at the same time so loadClass can 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, typically file:/path/to/my-service-1.0.0.jar.

  • @/ — separator that replaces the !/ of the standard jar: protocol to avoid a three-level jar:jar: nesting.

  • <inner-jar-path> (optional) — path of a nested jar under META-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):

  1. Binds the listener’s own PerApplicationScope (see The Per-Application Scope) for the whole of the call when spark.per.application.scope is true, so everything below, startup(args) included, runs inside it; with the scope off the call runs with the PerApplicationContext binding alone.

  2. Reads the wrapper’s startup timeout in seconds through getStartupTimeoutSeconds(), which consults WrapperManager.getProperties().getProperty("wrapper.startup.timeout") and defaults to 30. The wrapper configuration only becomes readable once the JVM has connected to the wrapper, so main leaves this lookup to start. A non-numeric value, or one from 1 to 9, is reported as exit code 2 without startup being invoked. Listeners that want a different policy override getStartupTimeoutSeconds(), which replaces the property lookup.

  3. Opens a single-thread ScheduledExecutorService whose worker is a daemon named spark-wrapper-signal, declared in a try-with-resources block so it is shut down the moment startup returns 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.

  4. Unless the timeout is 0 (the wrapper waits indefinitely, so no keep-alive is scheduled), schedules the keep-alive task with scheduleWithFixedDelay(…​, 0, max(1, startupTimeoutSeconds / 2), SECONDS), then invokes startup(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 rescheduling

A 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.timeout in wrapper.conf (startupTimeoutSeconds on the Maven plugin) when your application routinely takes more than 30 seconds to reach "ready". Values from 1 to 9 are rejected; 0 tells 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 startup is 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 plus wrapper.startup.timeout (about 195 seconds with defaults).

  • Set spark.startup.ceiling in wrapper.conf (startupCeilingSeconds on 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 until startup returns. An unparsable value is reported as exit code 2 from start. Listeners that want a different policy altogether override getStartupCeilingSeconds(), 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 boundThreadFactory or a task on its boundExecutor (neither needs a binding on the creating or submitting thread), a thread from the static wrapThreadFactory or a task on wrapExecutor or an ApplicationCarrier (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 with MissingPerApplicationContextException (metrics lookups return null and the instrumentation is unplugged).

  • Only WireScope decoding and direct PerApplicationScope / *ScopeManager reads 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 ref to org.smallmind.spark.perApplicationScope resolves to the instance the refresh is bound to. A different instance fails with org.smallmind.nutsnbolts.scope.ScopeException at 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 a ref to org.smallmind.spark.perApplicationScope fails the refresh with a BeanCreationException caused by NoSuchBeanDefinitionException, because the name is not registered.

  • null (<null/> in XML, as the shipped mock-wire.xml / rabbitmq-wire.xml pass, 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, so null and the ref are two ways to hand in the same scope; with the scope off nothing is bound, so null resolves 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 PerApplicationContext they 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>
  1. Registered during the refresh by the post-processor SpringContextWrapperListener.startup adds when the scope is on; not declared in the XML. With the scope off the name is not registered and this ref fails the refresh with a BeanCreationException caused by NoSuchBeanDefinitionException. 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 a ref to a bean declared with factory-method="getBound".

AbstractWrapperListener converts exceptions to exit codes as follows:

null (from start)

Startup succeeded; the wrapper keeps running.

2 (from start or stop)

STACK_TRACE_ERROR_CODE. startup or shutdown threw (an Error such as NoClassDefFoundError counts), or wrapper.startup.timeout / spark.startup.ceiling could not be parsed or was out of range; the stack trace was printed. The wrapper interprets a non-null return from start as "startup failed" and stops the JVM.

exitCode (from stop, when shutdown returned 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:

  1. Under its platform-specific name (libwrapper-linux-x86-64.so, wrapper-windows-x86-64.dll, etc.) so maintenance scripts and file command inspection can identify it.

  2. Under the generic OSStyle name (libwrapper.so or wrapper.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-nutsnbolts only.

spark-singularity-maven-plugin

smallmind-nutsnbolts, spark-singularity-boot, maven-plugin-api, maven-core, maven-model, maven-artifact, maven-compat, and maven-plugin-annotations. The Maven artifacts are provided or compile — nothing unusual for a Maven plugin.

spark-tanukisoft-integration

smallmind-nutsnbolts, spring-context, and tanukisoft:wrapper (the Java Service Wrapper’s own Java API jar). spring-context is a hard dependency because SpringContextWrapperListener is part of the artifact; a pure non-Spring user still needs it on the classpath, but only the AbstractWrapperListener class is referenced.

spark-tanukisoft-maven-plugin

freemarker (for wrapper.conf rendering), plus the same Maven provided/compile matrix.

"Unable to locate the boot class dependencies"

generate-singularity walks pluginArtifacts looking for org.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…"

modular is true, but the project has no module-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 (wrong Main-Class, wrong layout) or the index-writing step in generate-singularity was interrupted.

"Unknown operating system type(…)"

generate-wrapper could not parse the operatingSystem parameter as an OSType constant. Valid names are listed in OSType.values() — underscores and hyphens are interchangeable, case-insensitive.

"Unknown compression type(…)"

Same as above for compression vs CompressionType.

"Unknown os style(…)"

The plugin derived an unrecognized OSStyle from a validated OSType. This is an internal consistency check; an OSType constant whose OSStyle is neither WINDOWS nor UNIX would trigger it, but no such constant exists, so seeing this error means the enum has been modified.

"Unable to load template(…)"

processFreemarkerTemplate could not resolve a bundled Freemarker resource. The template resource path is built from GenerateWrapperMojo.class.getPackage().getName() plus bin/ or conf/; a plugin jar that has been repackaged without the installation/ resource root will fail here.

NoClassDefFoundError on 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 modifying SingularityClassLoader.OPERABLE_NAMESPACES), or prefer the JDK’s own implementation.

  • The class is loaded by a framework that captured the system class loader before SingularityEntryPoint.main replaced the context class loader. JNI libraries and some JDBC drivers cache loaders early; make sure the offending framework is initialized from within the application’s main, 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 opens declaration for that package to the module’s descriptor; a Singularity jar has no equivalent of --add-opens.

ZipException naming 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.

BeanCreationException caused by NoSuchBeanDefinitionException naming org.smallmind.spark.perApplicationScope during the refresh

A bean definition holds a ref to the scope singleton that SpringContextWrapperListener registers, but the listener has no scope to register: spark.per.application.scope is absent from wrapper.conf or is not true (perApplicationScope on the Maven plugin), or the context returned by loadApplicationContext arrived already refreshed. Set the property, or declare the scope with factory-method="getBound" instead, which injects null when the scope is off. See The Per-Application Scope.

WrapperManager errors ("WrapperStartException", "not initialized")

AbstractWrapperListener.main was invoked outside a wrapper process, or the wrapper process was started without wrapper.conf present. During development, run ./bin/<app>.sh console to exercise the full wrapper path; running the jar directly with java -jar … puts the listener into "unwrapped" mode where Ctrl-C triggers WrapperManager.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.conf on every build host; pass <licenseFile>${user.home}/.m2/wrapper-license.conf</licenseFile>.

  • Keep the license in a secret-resources submodule that the build system unpacks on the CI runner; pass a repo-relative path.

  • Leave licenseFile unset 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 arg2

In that mode:

  • Property expansion (${…}) on args still runs.

  • The keep-alive task still runs — WrapperManager.signalStarting just becomes a no-op when isControlledByNativeWrapper() is false.

  • Ctrl-C reaches controlEvent and triggers WrapperManager.stop(0), which unwinds through the listener’s stop callback and calls shutdown.

Use this mode during development; use the real wrapper binary for anything that looks like production.

One URLStreamHandlerFactory per JVM

SingularityClassLoader’s static initializer installs the `singularity: handler by calling URL.setURLStreamHandlerFactory. The JVM permits exactly one such installation; any subsequent call — including, recursively, a second Singularity jar loaded into the same JVM — throws an Error. 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_NAMESPACES arrays in SingularityClassLoader cannot be configured at build or boot time. A bundled library whose platform-shadowed class must come from the bundle (a newer org.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) and Dependency (tanukisoft) both compare groupId and artifactId as 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 URLStreamHandler chain

A library that installs its own URLStreamHandler for a non-singularity protocol after SingularityClassLoader’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 `null for non-singularity protocols and the JVM falls back to its built-in search.

No in-flight reloading

SingularityClassLoader reads 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-wrapper takes exactly one operatingSystem value 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 useUpstart and useSystemD feed the same Freemarker template. Setting both true in 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-plugin as a resource. The plugin jar is therefore large (~25 MB). Adding a new platform means adding a binary and an OSType constant, which requires rebuilding the plugin — there is no runtime extension point.

Build directory reuse is not self-cleaning

generate-singularity and generate-wrapper both rely on Maven’s clean to remove stale contents. Incremental builds that do not clean can carry stale library jars or index entries forward, producing a bundle with ghost entries. Prefer mvn clean package over mvn package for release builds.

AbstractWrapperListener.main is 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 inside startup (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-nutsnbolts provides CompressionType (used by both plugins for archive compression), PropertyExpander (used by AbstractWrapperListener.main), PerApplicationContext (base class of AbstractWrapperListener), PerApplicationScope (owned by AbstractWrapperListener when spark.per.application.scope is true; see The Per-Application Scope), and ClassPathTemplateLoader (used by generate-wrapper for 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.conf properties and the native wrapper’s behavior.