|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import signal |
| 4 | +import threading |
| 5 | +import time |
| 6 | +import requests |
| 7 | +import sys |
| 8 | +from django.core.management.base import BaseCommand |
| 9 | +from django.db import connections |
| 10 | +from django.conf import settings |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class SpotTerminationHandler: |
| 16 | + def __init__(self): |
| 17 | + self.terminating = threading.Event() |
| 18 | + self.spot_termination_url = "http://169.254.170.2/v2/spot/termination-notice" |
| 19 | + self.check_interval = 10 # Polling interval in seconds |
| 20 | + self.grace_period = 30 # Grace period in seconds |
| 21 | + |
| 22 | + def check_termination_notice(self): |
| 23 | + """Check if spot instance is scheduled for termination""" |
| 24 | + try: |
| 25 | + response = requests.get(self.spot_termination_url, timeout=2) |
| 26 | + return response.status_code == 200 |
| 27 | + except requests.RequestException as e: |
| 28 | + logger.warning(f"Error checking termination notice: {e}") |
| 29 | + return False |
| 30 | + |
| 31 | + def graceful_shutdown(self, signum, frame): |
| 32 | + """Handle graceful shutdown of the Django application""" |
| 33 | + if self.terminating.is_set(): |
| 34 | + return |
| 35 | + |
| 36 | + self.terminating.set() |
| 37 | + logger.info("Received termination notice, starting graceful shutdown...") |
| 38 | + |
| 39 | + try: |
| 40 | + # Close database connections |
| 41 | + for conn in connections.all(): |
| 42 | + conn.close_if_unusable_or_obsolete() |
| 43 | + |
| 44 | + # Stop accepting new requests (if using Gunicorn) |
| 45 | + if hasattr(settings, "GUNICORN_PID_FILE") and os.path.exists( |
| 46 | + settings.GUNICORN_PID_FILE |
| 47 | + ): |
| 48 | + with open(settings.GUNICORN_PID_FILE) as f: |
| 49 | + gunicorn_pid = int(f.read()) |
| 50 | + os.kill(gunicorn_pid, signal.SIGTERM) |
| 51 | + |
| 52 | + # Wait for ongoing requests to complete |
| 53 | + logger.info( |
| 54 | + f"Waiting {self.grace_period} seconds for ongoing requests to complete..." |
| 55 | + ) |
| 56 | + time.sleep(self.grace_period) |
| 57 | + |
| 58 | + logger.info("Graceful shutdown completed") |
| 59 | + except Exception as e: |
| 60 | + logger.error(f"Error during shutdown: {e}") |
| 61 | + finally: |
| 62 | + sys.exit(0) |
| 63 | + |
| 64 | + def start_monitoring(self): |
| 65 | + logger.info("Starting Fargate Spot termination monitoring...") |
| 66 | + |
| 67 | + # Register signal handlers |
| 68 | + signal.signal(signal.SIGTERM, self.graceful_shutdown) |
| 69 | + signal.signal(signal.SIGINT, self.graceful_shutdown) |
| 70 | + |
| 71 | + while not self.terminating.is_set(): |
| 72 | + if self.check_termination_notice(): |
| 73 | + self.graceful_shutdown(None, None) |
| 74 | + time.sleep(self.check_interval) |
| 75 | + |
| 76 | + |
| 77 | +class Command(BaseCommand): |
| 78 | + help = "Starts the Fargate Spot termination handler" |
| 79 | + |
| 80 | + def handle(self, *args, **options): |
| 81 | + handler = SpotTerminationHandler() |
| 82 | + monitoring_thread = threading.Thread(target=handler.start_monitoring) |
| 83 | + monitoring_thread.daemon = True |
| 84 | + monitoring_thread.start() |
| 85 | + |
| 86 | + # Keep the main thread alive |
| 87 | + while not handler.terminating.is_set(): |
| 88 | + time.sleep(1) |
0 commit comments