EscapeLife
7/15/2019 - 5:45 AM

parser_nginx_status.py

解析Nginx服务器状态页面并获取服务器当前连接状态

# -*- coding: utf-8 -*-
"""
解析Nginx自带的链接页面信息

Config:
    location /stub_status
    {
        stub_status;
        access_log off;
    }
"""

import sys
import json
import time
import os.path

import requests


class NginxStatus:
    """解析Nginx服务状态"""
    def __init__(self, scheme='http', host='localhost', port='8000', location='stub_status', interval=5):
        self.scheme = scheme
        self.host = host
        self.port = port
        self.location = location
        self.interval = interval
        self.cache_status = None
        self.http_host = ':'.join([self.host, self.port])

    def parser_status(self):
        """解析状态信息字段"""
        stub_status = {}
        headers = {
            'Host': self.http_host
        }

        # get info from stub_status page
        parser_url = self.scheme + '://' + '/'.join([self.http_host, self.location])
        try:
            req = requests.get(parser_url, headers=headers)
            status = req.text.splitlines()
            # parser info and return stub_status dict
            active_connections = status[0].split(':')
            stub_status['active_connections'] = active_connections[1].strip()
            handled_requests = status[2].split()
            stub_status['accepted_connections'] = handled_requests[0].strip()
            stub_status['handled_connections'] = handled_requests[1].strip()
            stub_status['handled_requests'] = handled_requests[2].strip()
            reading = status[3].split()
            stub_status['reading'] = reading[1].strip()
            stub_status['writing'] = reading[3].strip()
            stub_status['waiting'] = reading[5].strip()
            return stub_status
        except requests.ConnectionError as error:
            print(f'An error occurred on the link request => {parser_url}.\n {error}')
            sys.exit(1)

    def get(self):
        """获取缓存数据"""
        if self.cache_status is not None:
            print(self.cache_status)
        assert(f'[Error] there is not found cache status data to use.')

    def timer(self):
        """设置定时器"""
        start_time = int(time.time())
        self.cache_file()
        try:
            while True:
                current_time = int(time.time())
                if (current_time - start_time) >= self.interval:
                    self.cache_status = self.parser_status()
                    start_time = current_time
        except KeyboardInterrupt:
            print('Bye ~')


if __name__ == '__main__':
    nginx_status = NginxStatus(host='127.0.0.1', port='8000')
    nginx_status.timer()