Skip to content
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

fix(temporal): Handle SIGTERM correctly on worker cleanup #25505

Merged
merged 1 commit into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions bin/temporal-django-worker
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,21 @@

set -e

trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
cleanup() {
echo "Stopping worker..."
if kill -0 "$worker_pid" >/dev/null 2>&1; then
kill "$worker_pid"
else
echo "Worker process is not running."
fi
}
Comment on lines +5 to +12
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case this is cleanup outside this script, do not error.


python3 manage.py start_temporal_worker "$@"
trap cleanup SIGINT SIGTERM EXIT

wait
python3 manage.py start_temporal_worker "$@" &

worker_pid=$!

wait $worker_pid

cleanup
8 changes: 4 additions & 4 deletions posthog/temporal/common/worker.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
import signal
import sys
from datetime import timedelta

from temporalio.runtime import PrometheusConfig, Runtime, TelemetryConfig
Expand Down Expand Up @@ -43,10 +43,10 @@ async def start_worker(

# catch the TERM signal, and stop the worker gracefully
# https://github.com/temporalio/sdk-python#worker-shutdown
async def signal_handler(sig, frame):
async def shutdown_worker():
await worker.shutdown()
sys.exit(0)

signal.signal(signal.SIGTERM, signal_handler)
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.create_task(shutdown_worker()))

await worker.run()
Loading