MDK Logo

Tear down MDK services

Stop Kernel, Gateway, and Workers cleanly

TL;DR

Run the snippets from inside your MDK checkout, after its root npm install. Runtime: a host script. The Kernel key is written to ~/.mdk/.kernel-key.

  • Pass handleSignals: true to getKernel() for a clean Ctrl+C; without it MDK installs no signal handler
  • Workers are not chained to the Kernel: push runtime.stop() onto kernel._cleanup yourself
  • A signal-driven shutdown force-exits with code 1 after 3 seconds; raise it with shutdownForceMs or an onShutdown handler's forceMs

Overview

As a library, MDK leaves your process's signals alone: getKernel() and startGateway() install SIGINT/SIGTERM handlers only when you pass handleSignals: true, which a standalone process does so that Ctrl+C triggers a clean teardown with no extra code. This guide covers the three ways to tear down:

Prerequisites

Automatic teardown with getKernel()

getKernel({ handleSignals: true }) registers SIGINT/SIGTERM handlers that drain the cleanup chain, stop the Kernel, and exit the process. Without the option no handler is installed. A Gateway started with opts.kernel is chained into the cleanup sequence automatically. Workers are not auto-chained: WorkerRuntimeV2 has no opts.kernel, so push its stop() onto kernel._cleanup yourself if you want Kernel shutdown to cascade to it. Set AVALON_PASSWORD to the miner's password before you run it: export it, or keep it in .env and start the script with node --env-file=.env:

const path = require('path')
const { getKernel, startGateway } = require('@tetherto/mdk-core')
const { WorkerRuntimeV2 } = require('@tetherto/mdk-worker')

const main = async () => {
  const kernel = await getKernel({ handleSignals: true })

  const runtime = new WorkerRuntimeV2(path.dirname(require.resolve('@tetherto/mdk-worker-avalon/package.json')), {
    workerId: 'avalon-rack-1',
    storeDir: './data/avalon',
    allowedKeys: [kernel.getClientPublicKey()],
    devices: [{ deviceId: 'AV-001', config: { address: '192.168.1.30', port: 4028, password: process.env.AVALON_PASSWORD } }]
  })
  await runtime.start()
  await kernel.registerWorker(runtime.getPublicKey())
  kernel._cleanup.push(() => runtime.stop()) // cascade Worker shutdown from Kernel

  await startGateway({ kernel, port: 3000 })

  // Press Ctrl+C to start cleanup: Gateway, then Worker, then Kernel.
}

main().catch((err) => { console.error(err); process.exit(1) })

The signal handler force-exits after three seconds if cleanup is still running. A stalled telemetry request can keep the Worker's stop() pending past that deadline, so the Kernel may exit before its cleanup completes.

See getKernel API reference and the Workers discovery model for the same-process lifecycle rules.

Explicit teardown in tests or scripted runs

Short-lived processes, such as integration tests and one-shot scripts, and applications that embed MDK and own their signals (the default) call shutdown(kernel) directly to drain the full cleanup chain. Pass the kernel object returned by getKernel(); passing a server object stops only the Gateway.

const { getKernel, startGateway, shutdown } = require('@tetherto/mdk-core')

const main = async () => {
  const kernel = await getKernel()
  await startGateway({ kernel })

  // … run assertions or perform work …

  await shutdown(kernel) // stops Gateway (chained), then stops Kernel
}

main().catch((err) => { console.error(err); process.exit(1) })

See shutdown API reference.

Custom signal handling with onShutdown

Use onShutdown when you need to close resources outside an MDK boot object, such as a database connection or a log buffer. Every handler shares one shutdown and runs last-registered first, so a handler you register after getKernel({ handleSignals: true }) finishes before the Kernel stops:

const { getKernel, onShutdown } = require('@tetherto/mdk-core')

const main = async () => {
  await getKernel({ handleSignals: true })

  onShutdown(async () => {
    await db.close()
    await logger.flush()
  }, { forceMs: 5000 })
}

main().catch((err) => { console.error(err); process.exit(1) })

The onShutdown options set which signals the handler listens for and how long the shutdown waits (forceMs) before forcing the exit. The longest forceMs any handler registers applies, so this one gives the whole shutdown 5 seconds instead of the Kernel's 3. A standalone Gateway started with handleSignals: true works the same way.

A cleanup that throws or outlasts forceMs makes the process exit with code 1 and print the reason to stderr. A cleanup still running at forceMs also leaves the Kernel running until the forced exit, because the Kernel's handler runs after yours. Bound each slow call in your cleanup (a timeout on db.close()) well inside forceMs.

To fold a step into the Kernel's own handler instead, push it onto kernel._cleanup, as automatic teardown does for a Worker.

What just happened

  1. Automatic chain: getKernel({ handleSignals: true }) and startGateway({ kernel }) start cleanup on a single signal, with the Gateway first and the Kernel last. Push a Worker's stop() onto kernel._cleanup yourself to fold it into the same chain.
  2. Explicit drain: shutdown(kernel) gives you the same ordered teardown on demand, without a signal.
  3. Custom hooks: an onShutdown(fn) handler registered after boot closes resources outside the MDK object hierarchy before the Kernel stops.

Next steps

On this page