cacti icon indicating copy to clipboard operation
cacti copied to clipboard

fix(satp-hermes): destroy knex connection pools on shutdown

Open mn-ram opened this issue 8 months ago • 5 comments

Summary

  • Destroy orphaned knex connection pool in createDBRepository() after migrations complete
  • Destroy localRepository and remoteRepository connection pools in both shutdown() and kill() methods
  • Prevents database connection pool leaks across gateway restarts

Problem

The SATP Hermes gateway leaked database connection pools in two ways:

  1. createDBRepository() created a local knex() instance for running migrations but never called destroy() on it. The pool stayed alive after the function returned.

  2. shutdown() and kill() never called destroy() on this.localRepository or this.remoteRepository, even though KnexLocalLogRepository.destroy() exists.

This caused:

  • SQLITE_BUSY errors under concurrent load (two pools fighting for WAL lock)
  • PostgreSQL max_connections exhaustion after repeated restarts
  • Node.js process hanging on shutdown (open pool keeps event loop alive)

Changes

File: packages/cactus-plugin-satp-hermes/src/main/typescript/plugin-satp-hermes-gateway.ts

Method Change
createDBRepository() Added await database.destroy() after database.migrate.latest()
shutdown() Added await this.localRepository.destroy() and await this.remoteRepository.destroy() before monitor service shutdown
kill() Added same repository destroy calls before return

Test plan

  • [ ] Start SATP gateway with SQLite (default), verify no SQLITE_BUSY errors under concurrent sessions
  • [ ] Verify gateway process exits cleanly on SIGTERM without requiring SIGKILL
  • [ ] Restart gateway multiple times, confirm no connection pool accumulation
  • [ ] Run existing SATP integration tests to verify no regressions

Fixes #4184

mn-ram avatar Apr 04 '26 12:04 mn-ram

Please squash the commits into single commit

sandeepnRES avatar Apr 13 '26 10:04 sandeepnRES

@sandeepnRES I've squashed all commits into a single commit as requested. Please let me know if any further changes are needed.

mn-ram avatar Apr 13 '26 12:04 mn-ram

@mn-ram thank you for the code. Generally looks good. I left a minor comment. Could you please either 1: run the test plan and assert the changes work or 2: add programatic tests that verify the same?

RafaelAPB avatar Apr 21 '26 20:04 RafaelAPB

Pushed an update based on Copilot feedback:

-Moved cleanup logic into a destroyRepositories() helper with try/catch for each destroy(). -Now calling it in both early-return and normal paths, so DB pools don’t leak. -Wrapped migration knex() in try/finally to always release the pool.

Will run tests and share results soon.

mn-ram avatar Apr 22 '26 03:04 mn-ram

Test results: Ran unit tests — all relevant tests passed, including shutdown tests. Logs show the shutdown flow is working correctly.

No issues found.
Integration tests will run in CI.

mn-ram avatar Apr 22 '26 03:04 mn-ram