-
Notifications
You must be signed in to change notification settings - Fork 349
feat: graceful shutdown #205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,83 +1,60 @@ | ||
| import { round } from '@openpanel/common'; | ||
| import { TABLE_NAMES, chQuery, db } from '@openpanel/db'; | ||
| import { eventsQueue } from '@openpanel/queue'; | ||
| import { isShuttingDown } from '@/utils/graceful-shutdown'; | ||
| import { chQuery, db } from '@openpanel/db'; | ||
| import { getRedisCache } from '@openpanel/redis'; | ||
| import type { FastifyReply, FastifyRequest } from 'fastify'; | ||
|
|
||
| async function withTimings<T>(promise: Promise<T>) { | ||
| const time = performance.now(); | ||
| try { | ||
| const data = await promise; | ||
| return { | ||
| time: round(performance.now() - time, 2), | ||
| data, | ||
| } as const; | ||
| } catch (e) { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| // For docker compose healthcheck | ||
| export async function healthcheck( | ||
| request: FastifyRequest, | ||
| reply: FastifyReply, | ||
| ) { | ||
| if (process.env.DISABLE_HEALTHCHECK) { | ||
| return reply.status(200).send({ | ||
| ok: true, | ||
| try { | ||
| const redisRes = await getRedisCache().ping(); | ||
| const dbRes = await db.project.findFirst(); | ||
| const chRes = await chQuery('SELECT 1'); | ||
| const status = redisRes && dbRes && chRes ? 200 : 503; | ||
|
|
||
| reply.status(status).send({ | ||
| ready: status === 200, | ||
| redis: redisRes === 'PONG', | ||
| db: !!dbRes, | ||
| ch: chRes && chRes.length > 0, | ||
| }); | ||
| } catch (error) { | ||
| return reply.status(503).send({ | ||
| ready: false, | ||
| reason: 'dependencies not ready', | ||
| }); | ||
| } | ||
| const redisRes = await withTimings(getRedisCache().ping()); | ||
| const dbRes = await withTimings(db.project.findFirst()); | ||
| const queueRes = await withTimings(eventsQueue.getCompleted()); | ||
| const chRes = await withTimings( | ||
| chQuery( | ||
| `SELECT * FROM ${TABLE_NAMES.events} WHERE created_at > now() - INTERVAL 10 MINUTE LIMIT 1`, | ||
| ), | ||
| ); | ||
| const status = redisRes && dbRes && queueRes && chRes ? 200 : 500; | ||
| } | ||
|
|
||
| reply.status(status).send({ | ||
| redis: redisRes | ||
| ? { | ||
| ok: redisRes.data === 'PONG', | ||
| time: `${redisRes.time}ms`, | ||
| } | ||
| : null, | ||
| db: dbRes | ||
| ? { | ||
| ok: !!dbRes.data, | ||
| time: `${dbRes.time}ms`, | ||
| } | ||
| : null, | ||
| queue: queueRes | ||
| ? { | ||
| ok: !!queueRes.data, | ||
| time: `${queueRes.time}ms`, | ||
| } | ||
| : null, | ||
| ch: chRes | ||
| ? { | ||
| ok: !!chRes.data, | ||
| time: `${chRes.time}ms`, | ||
| } | ||
| : null, | ||
| }); | ||
| // Kubernetes - Liveness probe - returns 200 if process is alive | ||
| export async function liveness(request: FastifyRequest, reply: FastifyReply) { | ||
| return reply.status(200).send({ live: true }); | ||
| } | ||
|
|
||
| export async function healthcheckQueue( | ||
| request: FastifyRequest, | ||
| reply: FastifyReply, | ||
| ) { | ||
| const count = await eventsQueue.getWaitingCount(); | ||
| if (count > 40) { | ||
| reply.status(500).send({ | ||
| ok: false, | ||
| count, | ||
| }); | ||
| } else { | ||
| reply.status(200).send({ | ||
| ok: true, | ||
| count, | ||
| // Kubernetes - Readiness probe - returns 200 only when accepting requests, 503 during shutdown | ||
| export async function readiness(request: FastifyRequest, reply: FastifyReply) { | ||
| if (isShuttingDown()) { | ||
| return reply.status(503).send({ ready: false, reason: 'shutting down' }); | ||
| } | ||
|
|
||
| // Perform lightweight dependency checks for readiness | ||
| const redisRes = await getRedisCache().ping(); | ||
| const dbRes = await db.project.findFirst(); | ||
| const chRes = await chQuery('SELECT 1'); | ||
|
|
||
| const isReady = redisRes && dbRes && chRes; | ||
|
|
||
| if (!isReady) { | ||
| return reply.status(503).send({ | ||
| ready: false, | ||
| reason: 'dependencies not ready', | ||
| redis: redisRes === 'PONG', | ||
| db: !!dbRes, | ||
| ch: chRes && chRes.length > 0, | ||
| }); | ||
| } | ||
|
|
||
| return reply.status(200).send({ ready: true }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import { ch, db } from '@openpanel/db'; | ||
| import { | ||
| cronQueue, | ||
| eventsQueue, | ||
| miscQueue, | ||
| notificationQueue, | ||
| sessionsQueue, | ||
| } from '@openpanel/queue'; | ||
| import { | ||
| getRedisCache, | ||
| getRedisPub, | ||
| getRedisQueue, | ||
| getRedisSub, | ||
| } from '@openpanel/redis'; | ||
| import type { FastifyInstance } from 'fastify'; | ||
| import { logger } from './logger'; | ||
|
|
||
| let shuttingDown = false; | ||
|
|
||
| export function setShuttingDown(value: boolean) { | ||
| shuttingDown = value; | ||
| } | ||
|
|
||
| export function isShuttingDown() { | ||
| return shuttingDown; | ||
| } | ||
|
|
||
| // Graceful shutdown handler | ||
| export async function shutdown( | ||
| fastify: FastifyInstance, | ||
| signal: string, | ||
| exitCode = 0, | ||
| ) { | ||
| if (isShuttingDown()) { | ||
| logger.warn('Shutdown already in progress, ignoring signal', { signal }); | ||
| return; | ||
| } | ||
|
|
||
| logger.info('Starting graceful shutdown', { signal }); | ||
|
|
||
| setShuttingDown(true); | ||
|
|
||
| // Step 2: Wait for load balancer to stop sending traffic (matches preStop sleep) | ||
| const gracePeriod = Number(process.env.SHUTDOWN_GRACE_PERIOD_MS || '5000'); | ||
| await new Promise((resolve) => setTimeout(resolve, gracePeriod)); | ||
|
|
||
| // Step 3: Close Fastify to drain in-flight requests | ||
| try { | ||
| await fastify.close(); | ||
| logger.info('Fastify server closed'); | ||
| } catch (error) { | ||
| logger.error('Error closing Fastify server', error); | ||
| } | ||
|
|
||
| // Step 4: Close database connections | ||
| try { | ||
| await db.$disconnect(); | ||
| logger.info('Database connection closed'); | ||
| } catch (error) { | ||
| logger.error('Error closing database connection', error); | ||
| } | ||
|
|
||
| // Step 5: Close ClickHouse connections | ||
| try { | ||
| await ch.close(); | ||
| logger.info('ClickHouse connections closed'); | ||
| } catch (error) { | ||
| logger.error('Error closing ClickHouse connections', error); | ||
| } | ||
|
|
||
| // Step 6: Close Bull queues (graceful shutdown of queue state) | ||
| try { | ||
| await Promise.all([ | ||
| eventsQueue.close(), | ||
| sessionsQueue.close(), | ||
| cronQueue.close(), | ||
| miscQueue.close(), | ||
| notificationQueue.close(), | ||
| ]); | ||
| logger.info('Queue state closed'); | ||
| } catch (error) { | ||
| logger.error('Error closing queue state', error); | ||
| } | ||
|
|
||
| // Step 7: Close Redis connections | ||
| try { | ||
| const redisConnections = [ | ||
| getRedisCache(), | ||
| getRedisPub(), | ||
| getRedisSub(), | ||
| getRedisQueue(), | ||
| ]; | ||
|
|
||
| await Promise.all( | ||
| redisConnections.map(async (redis) => { | ||
| if (redis.status === 'ready') { | ||
| await redis.quit(); | ||
| } | ||
| }), | ||
| ); | ||
| logger.info('Redis connections closed'); | ||
| } catch (error) { | ||
| logger.error('Error closing Redis connections', error); | ||
| } | ||
|
|
||
| logger.info('Graceful shutdown completed'); | ||
| process.exit(exitCode); | ||
| } |
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.