File: when_ready.conf.py

package info (click to toggle)
gunicorn 20.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,088 kB
  • sloc: python: 9,219; makefile: 161; xml: 73; sh: 40; javascript: 35
file content (37 lines) | stat: -rw-r--r-- 1,020 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import signal
import commands
import threading
import time

max_mem = 100000

class MemoryWatch(threading.Thread):

    def __init__(self, server, max_mem):
        super().__init__()
        self.daemon = True
        self.server = server
        self.max_mem = max_mem
        self.timeout = server.timeout / 2

    def memory_usage(self, pid):
        try:
            out = commands.getoutput("ps -o rss -p %s" % pid)
        except IOError:
            return -1
        used_mem = sum(int(x) for x in out.split('\n')[1:])
        return used_mem

    def run(self):
        while True:
            for (pid, worker) in list(self.server.WORKERS.items()):
                if self.memory_usage(pid) > self.max_mem:
                    self.server.log.info("Pid %s killed (memory usage > %s)",
                        pid, self.max_mem)
                    self.server.kill_worker(pid, signal.SIGTERM)
            time.sleep(self.timeout)


def when_ready(server):
    mw = MemoryWatch(server, max_mem)
    mw.start()