-def time_expired(n, stack):
- import os
- import time
- print '>>> [%s] time ran out.' % (os.getpid())
- raise Exception('(time ran out)')
-
-def pre_request(worker, req):
- import os
- import psutil
- import resource
- import signal
- # VMS and RLIMIT_AS are the same thing: virtual memory, a.k.a. address space
- rss, vms = psutil.Process(os.getpid()).get_memory_info()
- soft, hard = resource.getrlimit(resource.RLIMIT_AS)
- print ">>>>>> [%s] %s %s %s %s %s" % (os.getpid(), vms, req.method, req.path, req.query, req.fragment)
- print ">>>>>> %s" % (req.body,)
- # Let's say 512MB is ok, 768 is a hard limit (will raise MemoryError),
- # 640 will nicely restart the process.
- resource.setrlimit(resource.RLIMIT_AS, (768 * 1024 * 1024, hard))
- if vms > 640 * 1024 * 1024:
- print ">>> Worker eating too much memory, reset it after the request."
- worker.alive = False # Commit suicide after the request.
-
- r = resource.getrusage(resource.RUSAGE_SELF)
- cpu_time = r.ru_utime + r.ru_stime
- signal.signal(signal.SIGXCPU, time_expired)
- soft, hard = resource.getrlimit(resource.RLIMIT_CPU)
- resource.setrlimit(resource.RLIMIT_CPU, (cpu_time + 15, hard))
-