import socket import subprocess from django.conf import settings from django.core.cache import cache class CheckCacheServer(object): """ Request-phase cache middleware that checks to make sure the Cache server is running. Starting it if it is not Must be first in the middleware stack so it can check before anything else runs """ def __init__(self): self.cache_backend = settings.CACHE_BACKEND self.servers = self.cache_backend[self.cache_backend.index('//')+2 : self.cache_backend.rindex('/')].split(';') def process_request(self, request): """ This is run for every request, it checks to see if it can get a defined item out of the cache, if that fails it tries to set it Failing that it decides the server is probably crashed, but goes though and attempts to connect to the server. Failing a connection It will launch a new server. """ if not self.cache_backend.startswith('memcached'): return None alive = cache.get("test-connection") if not alive and not cache.set("test-connection", 1, 604800): try: memcached = settings.CACHE_SERVER_STRING except AttributeError: memcached = "memcached -l %s -p %d -c 10 -d" for server in self.servers: ip, port = server.split(':') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((ip, int(port))) except socket.error, e: # not running, start it subprocess.Popen(memcached % (ip, int(port)), shell=True) finally: s.close() return None