Prepare files before rollout

  • An optional pre-rollout Job prepares reusable versioned files before consumers start; compare it with per-Pod copying.
100%

Worked design example · evaluate before adopting

Prepare reusable files before starting application PodsOrder / release gateFailure alternativeCopy / read files1 · start2 · stage files3 · checksum + manifest identity3F · fail; unpublished3S · publish complete version4 · verify immutable identity5 · Job Complete6 · release pinned consumers7 · read-only published filesPrerequisite before step 1: CI validates the complete compatible release set and compares the consumer image and versioned paths with the approved manifest. The gate script assumes this prior approval. The controller starts preparation, waits for successful completion and only then releases reviewed consumers. The Job verifies files and identity; it does not prove application integration or schema compatibility. A Job alone does not gate a Deployment.CONTROLLERPrior CI approvalCompatible setAn optional preparation Job publishes missing immutable content before release. A PV does not inherently require a Job. The runnable publisher verifies checksums, the exact file set and manifest identity. It exits successfully only after publication and verification. Compatibility approval is a prior CI prerequisite, not a result of these file checks.EXECUTIONPreparation JobA unique private staging directory holds incomplete copy/extraction work. Consumers never select it. Checksum, file-set or manifest-identity failure stops publication and fails preparation. Partial staging stays unpublished; the example cleans its stage under the writer lock. It does not run application compatibility tests.STORAGEPrivate stagingPublish only the validated complete file set and its manifest using backend-supported atomic visibility semantics. Same-version retries may accept identical already-published content; reject conflicting bytes. Coordinate concurrent writers. Rename/visibility guarantees must be verified for the selected filesystem or object store.STORAGEImmutable versionsThe controller releases consumers only after the preparation Job is Complete and the published manifest matches the pinned expected identity. Consumers read only published immutable paths. Add an admission/init verification gate if needed; do not assume creating a Job automatically orders a separate Deployment.EXECUTIONConsumer Pods1 · start2 · stage files3 · checksum +manifest identity3F · fail; unpublished3S · publish completeversion4 · verify immutableidentity5 · Job Complete6 · release pinnedconsumers7 · read-onlypublished files

Select a component to trace its direct connections. Drag to pan · Ctrl + wheel or pinch to zoom.

  • Before step 1: CI approves the compatible release set and compares consumer image/paths with the approved manifest. The illustrated gate assumes that approval; it does not implement integration or schema tests.
  • 3F / 3S are alternatives: failed checksum, exact-file-set or manifest checks stop preparation; partial staging is never advertised. Success publishes a complete immutable version.
  • Explicit gate: the controller waits for Job Complete before submitting the reviewed consumer. The Job publishes and verifies the pinned identities. A Job alone does not gate a Deployment.
  • Retries: accept an existing version only when identity and checksums match. Changed bytes require a new version. Serialize writers and cleanup; verify backend atomic visibility. A PV does not inherently require a Job.
Prepare reusable files before rollout

Prepare reusable files before rollout

Kubernetes v1 Pods, apps/v1 and batch/v1 · Node.js >=24 teaching protocol · illustrative release identities

Use a preparation Job with an explicit owner

  • This optional pre-rollout step prepares reusable files on versioned storage before new OBRH consumers start. Per-Pod init copying remains a separate alternative; a Job is not required for every Deployment.
  • The Job’s custom image contains Node, the publisher, an exact release manifest and payload directories. The example does not download tools at startup or claim that the placeholder image exists.
  • Publish and verify common first, then release. A verified common/V1 can return already-published; a different V1 identity fails closed.
  • parallelism: 1 limits that Job’s intended concurrency. Kubernetes can still start the same program twice; other Jobs and release attempts also exist. Serialization and idempotency remain required.
Illustrative Job — pinned preparer and checked publicationyaml
# Illustrative preparation Job, NOT an implicit prerequisite of any Deployment.
# Custom image prerequisites: Node >=24; /tools/artifact-publisher.cjs;
# /input/release.json matching artifact-release-r2.json; verified /payload/common
# and /payload/release. The included JSON uses text fixtures, not real binaries.
# Replace digest, size, namespace/PVC, UID/GID and CSI/access topology deliberately.
apiVersion: batch/v1
kind: Job
metadata: {name: prepare-r2, namespace: domain-a}
spec:
  completions: 1
  parallelism: 1
  backoffLimit: 2
  activeDeadlineSeconds: 300
  template:
    spec:
      restartPolicy: Never
      securityContext: {runAsUser: 1000, runAsGroup: 1000, fsGroup: 1000}
      containers:
        - name: publish
          image: registry.example/preparer-r2@sha256:6666666666666666666666666666666666666666666666666666666666666666
          command: [sh, -ec]
          args:
            - |
              node /tools/artifact-publisher.cjs publish /store /payload/common /input/release.json common
              node /tools/artifact-publisher.cjs publish /store /payload/release /input/release.json release
              node /tools/artifact-publisher.cjs verify /store /payload/common /input/release.json common
              node /tools/artifact-publisher.cjs verify /store /payload/release /input/release.json release
          volumeMounts:
            - {name: store, mountPath: /store}
      volumes:
        - name: store
          persistentVolumeClaim: {claimName: domain-a-artifacts}
# Even parallelism:1 does not replace writer serialization/idempotency across
# retries, multiple Jobs or concurrent releases. Crash can leave a lock/stage.

Inspect the small publication protocol

  • Acquire one root-level lock by exclusive directory creation. All publishers and cleanup must honor it; the example serializes concurrent releases rather than building a scheduler.
  • Create a unique staging directory under the same storage root. Copy only declared regular files and validate every SHA-256 before publishing.
  • Write the manifest receipt, then rename the complete stage to its absent immutable version path. Existing identical version: verify and reuse. Different manifest, hash or file set: reject.
  • The protocol assumes atomic exclusive mkdir, same-filesystem directory rename and coherent visibility on the chosen backend. These are backend acceptance criteria, not a promise made by mounting a PVC.
  • Trust the input manifest, source tree and parent directories. This teaching utility does not defend against hostile concurrent writers, symlink races or power loss; it does not fsync directories or files.
  • The tiny text fixtures validate file bytes only. Executable modes, ownership and complete runtime-tree metadata are outside this utility; adopting this pattern for JDK/Tomcat trees requires those packaging contracts too.
Runnable local Node teaching publisher — explicit backend assumptionsjavascript
'use strict';

// Teaching protocol, Node >=24, no dependencies. TRUSTED inputs/parent directory only.
// Backend prerequisites: atomic exclusive mkdir and same-filesystem directory
// rename with coherent visibility to all clients. Validate these on the actual CSI
// backend; Node APIs alone do not establish distributed-filesystem guarantees.
// Every writer AND cleanup process must honor the one root-level lock.
// No automatic stale-lock removal, no fsync/power-loss durability guarantee,
// no hostile-writer/symlink-race protection. Published trees must be write-protected
// by storage identity/permissions. Consumers mount read-only.
const fs = require('node:fs/promises');
const path = require('node:path');
const {createHash} = require('node:crypto');
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const safe = value => typeof value === 'string' && /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(value) && !value.split('/').some(x => x === '.' || x === '..');

function normalize(input) {
  if (!input || !/^(common|releases)\/[A-Za-z0-9_-]+$/.test(input.version) || !Array.isArray(input.files) || !input.files.length) throw Error('Invalid bundle manifest');
  const files = input.files.map(({path: name, sha256}) => {
    if (!safe(name) || name === '.publication.json' || !/^[a-f0-9]{64}$/.test(sha256)) throw Error('Invalid path or checksum');
    return {path: name, sha256};
  }).sort((a,b) => a.path.localeCompare(b.path, 'en'));
  if (new Set(files.map(x => x.path)).size !== files.length) throw Error('Duplicate path');
  return {version: input.version, files};
}
async function regularBytes(filename) {
  if (!(await fs.lstat(filename)).isFile()) throw Error('Expected regular file: ' + filename);
  return fs.readFile(filename);
}
async function namesBelow(dir, prefix = '') {
  const result = [];
  for (const entry of await fs.readdir(dir, {withFileTypes:true})) {
    const relative = prefix + entry.name;
    if (entry.isDirectory()) result.push(...await namesBelow(path.join(dir, entry.name), relative + '/'));
    else if (entry.isFile()) result.push(relative);
    else throw Error('Non-regular published entry: ' + relative);
  }
  return result.sort();
}
async function verifyBundle(root, input) {
  const manifest = normalize(input), final = path.join(root, manifest.version);
  const recorded = JSON.parse(await regularBytes(path.join(final, '.publication.json')));
  if (JSON.stringify(recorded) !== JSON.stringify(manifest)) throw Error('Existing version has different manifest');
  const expected = [...manifest.files.map(x=>x.path), '.publication.json'].sort();
  if (JSON.stringify(await namesBelow(final)) !== JSON.stringify(expected)) throw Error('Published file set differs');
  for (const file of manifest.files) {
    if (hash(await regularBytes(path.join(final, file.path))) !== file.sha256) throw Error('Published checksum mismatch: ' + file.path);
  }
  return {version: manifest.version, state:'verified'};
}
async function publishBundle(root, source, input) {
  const manifest = normalize(input);
  root = path.resolve(root); source = path.resolve(source);
  await fs.mkdir(root, {recursive:true});
  const lock = path.join(root, '.publisher-lock');
  try { await fs.mkdir(lock); } catch (error) {
    if (error.code === 'EEXIST') throw Error('Publisher lock held; do not remove without fencing its owner');
    throw error;
  }
  let stage;
  try {
    const final = path.join(root, manifest.version);
    let exists = false;
    try { await fs.lstat(final); exists = true; } catch (error) { if (error.code !== 'ENOENT') throw error; }
    if (exists) {
      await verifyBundle(root, manifest); // Same identity+bytes: retry succeeds without rewriting.
      return {version:manifest.version, state:'already-published'};
    }
    // Stage lives under root, so promotion does not cross filesystems.
    stage = await fs.mkdtemp(path.join(root, '.stage-'));
    for (const file of manifest.files) {
      const bytes = await regularBytes(path.join(source, file.path));
      if (hash(bytes) !== file.sha256) throw Error('Source checksum mismatch: ' + file.path);
      const target = path.join(stage, file.path);
      await fs.mkdir(path.dirname(target), {recursive:true});
      await fs.writeFile(target, bytes, {flag:'wx'});
      if (hash(await regularBytes(target)) !== file.sha256) throw Error('Staged checksum mismatch: ' + file.path);
    }
    await fs.writeFile(path.join(stage, '.publication.json'), JSON.stringify(manifest) + '\n', {flag:'wx'});
    await fs.mkdir(path.dirname(final), {recursive:true});
    await fs.rename(stage, final); // Cooperating writers serialized; final was absent.
    stage = undefined;
    await verifyBundle(root, manifest);
    return {version:manifest.version, state:'published'};
  } finally {
    try {
      if (stage) {
        if (path.dirname(stage) !== root || !path.basename(stage).startsWith('.stage-')) throw Error('Unsafe staging cleanup target');
        await fs.rm(stage, {recursive:true, force:true});
      }
    }
    finally { await fs.rmdir(lock); }
  }
}
module.exports = {hash, normalize, publishBundle, verifyBundle};
if (require.main === module) {
  (async()=>{
    const [action, root, source, filename, member] = process.argv.slice(2);
    if (!['publish','verify'].includes(action) || !root || !source || !filename) throw Error('Usage: node artifact-publisher.cjs publish|verify ROOT SOURCE MANIFEST [common|release]');
    const document = JSON.parse(await fs.readFile(filename, 'utf8'));
    const manifest = member ? document[member] : document;
    if (!manifest) throw Error('Manifest member missing');
    console.log(JSON.stringify(await (action === 'publish' ? publishBundle(root,source,manifest) : verifyBundle(root,manifest))));
  })().catch(error=>{console.error(error.message); process.exitCode=1;});
}

Gate consumer submission on verified completion

  • The shell example creates the reviewed release Job, waits for its successful completion, and only then submits the reviewed R2 consumer Pod.
  • A normal Deployment does not automatically wait for an unrelated Job. Helm/CI/GitOps must implement the dependency and stop on publication failure; Job YAML alone does not create it.
  • Use unique release/attempt Job identities. A stale Completed Job cannot certify a new image/manifest. The Job’s pinned image and the consumer manifest must agree on the exact release set.
  • Publication completion proves these publisher checks ran successfully. Compatibility, readiness, promotion and drain need their own acceptance evidence.
Illustrative release workflow — wait before consumer submissionbash
#!/bin/sh
# Illustrative CI gate. This file is NOT executed by Atlas tests.
# Requires kubectl context authorization, immutable reviewed Job/consumer manifests,
# unique Job name per release/attempt, compatible storage mounts and CI timeout policy.
# The Job's pinned image must contain the exact release manifest and publisher.
set -eu

# Before this point, CI validates the complete compatible release set and compares
# the consumer image + versioned paths to the approved R2 manifest. That validation
# is a prerequisite; these kubectl commands do not test application compatibility.
kubectl create -f artifact-preparation-job.yaml
kubectl -n domain-a wait --for=condition=complete job/prepare-r2 --timeout=320s

# Job completion means this image's publish+verify commands succeeded. A timeout,
# Failed Job or context/auth failure stops this script; no consumer is submitted.
kubectl create -f artifact-consumer-pod.yaml

# The consumer Pod is illustrative. A release controller would submit the reviewed
# Deployment then verify rollout/health. Do not repeatedly create an identically
# named Job and mistake a stale Complete result for verification of a new release.
# Retain R1 until promotion, drain and the approved rollback window finish.

Work the interruption cases before release

  • A stage is never a consumer path. Ordinary caught failures remove only that attempt’s stage and lock; process/node loss can leave both behind.
Failure Visible result Recovery / release decision
Wrong source hash No final version Stop; rebuild/resolve source identity.
Existing same version and bytes Verified idempotent success Reuse; do not rewrite.
Existing version has different bytes Reject Publish a new version after investigation.
Another release holds lock Reject this attempt Retry through the release workflow; do not break active owner.
Writer dies before rename Orphan stage + possible lock; no final Fence owner, inspect, clean abandoned state, retry. Age alone is not fencing.
Writer dies after rename Complete final may exist; lock may remain Fence owner, verify final, recover lock, retry idempotently.
Common published; release fails Unreferenced valid common may remain Consumer gate stays closed; later retry can reuse common.

Know what the local POC establishes

  • Run node --test tests/artifact-examples.test.cjs from the repository root. Tests create only temporary local directories and execute both the API and CLI.
  • Covered outcomes: complete publication, unchanged retry, wrong source checksum, conflicting identity, damaged publication, held lock, retained R1/R2 and exact common/V1 reuse.
  • These tests do not validate a CSI backend, multi-node cache consistency, crash durability, application compatibility or a live Kubernetes gate. Establish those separately before adopting the protocol.