PHP-FPM 获取Running进程
2017-06-14 本文已影响0人
dengwei29
概述
新上线一个nginx+php-fpm的项目,最近时长收到一些平均响应时间的告警,为了方便查看php-fpm进程都在处理啥请求,以及处理时长,就有了下面这个脚本
获取指标
指标 | 说明 |
---|---|
pid | 进程ID |
requests | 进程已处理的请求数 |
duration | 请求时长(秒) |
method | 请求方法 |
length | POST内容长度 |
uri | 请求URI(最多取60个字符串) |
get_php-fpm_running.py
$ cat get_php-fpm_running.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import requests
from tabulate import tabulate
def get_fpm_running(url, duration=10):
"""
获取PHP-FPM正在运行并响应时间超过默认10s的进程。
duration: 时间单位秒
request duration: 时间单位微秒
"""
l = []
r = requests.get(url)
headers = ['pid', 'requests', 'duration', 'method', 'length', 'uri']
if r.ok is False:
return False
try:
data = r.json().get('processes')
except:
return False
print('Total process: {0}'.format(len(data)))
for info in data:
states = info.get('state')
req_duration = info.get('request duration')/1000/1000.
if states == "Running" and req_duration > duration:
pid = info.get('pid')
request_nums = info.get('requests')
method = info.get('request method')
length = info.get('content length')
uri = info.get('request uri')
if len(uri) > 60:
uri = info.get('request uri')[:60]
process_info = [pid, request_nums, req_duration, method, length, uri]
l.append(process_info)
return tabulate(l, headers, tablefmt='orgtbl', floatfmt='.2f')
if __name__ == "__main__":
url = 'http://127.0.0.1/php-fpm_stats?json&full'
try:
duration = sys.argv[1]
except IndexError:
duration = 10
data = get_fpm_running(url, int(duration))
print(data)
实时显示可以通过watch进行封装
$ watch -n5 ./get_php-fpm_running.py 3
Every 5.0s: ./get_php-fpm_running.py 3 Wed Jun 14 15:31:54 2017
Total process: 512
| pid | requests | duration | method | length | uri |
|--------+------------+------------+----------+----------+------------|
| 132168 | 489 | 6.71 | POST | 625 | /index.php |