Skip to content

Instantly share code, notes, and snippets.

@gyoza
Created April 26, 2018 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gyoza/6eb2829bf0f55cd4f4bcbc6b9c17942a to your computer and use it in GitHub Desktop.
Save gyoza/6eb2829bf0f55cd4f4bcbc6b9c17942a to your computer and use it in GitHub Desktop.
kill hung nginx workers
#!/usr/bin/env python2.7
#
# kills openresty nginx and possibly regular nginx '"hung"' worker processes
#
# version 0.1
#
import psutil
import os
import time
import signal
import sys
grumpy = "nginx: worker process"
VERBOSE = bool("-v" in sys.argv)
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'name', 'username', 'cmdline'])
except psutil.NoSuchProcess:
pass
else:
if pinfo.get("cmdline"):
cmdline = pinfo.get("cmdline")
if grumpy in cmdline:
foundpid = pinfo.get("pid")
test_list = []
for i in range(10):
p = psutil.Process(pid=foundpid)
p_cpu = p.cpu_percent(interval=0.1)
test_list.append(p_cpu)
result = float(sum(test_list)) / len(test_list)
if result > 85.0:
if VERBOSE: print("High CPU nginx Worker Process Found :( PID: {} CPU %: {}").format(foundpid, result)
os.kill(foundpid, signal.SIGKILL)
if VERBOSE: print("Sleeping 30 seconds...")
time.sleep(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment