Mini Shell

Direktori : /opt/imh-python/lib/python3.9/site-packages/ngxutil/
Upload File :
Current File : //opt/imh-python/lib/python3.9/site-packages/ngxutil/vts.py

#!/opt/imh-python/bin/python3.9
# vim: set ts=4 sw=4 expandtab syntax=python:
"""

ngxutil.vts
VTS Parser & Formatter

@author J. Hipps <jacobh@inmotionhosting.com>

"""

import logging
import socket
import json
import re

from ngxutil import default_vts_socket_path

logger = logging.getLogger('ngxutil')


def parse_vts(sockpath=default_vts_socket_path, uri='/vstatus'):
    """
    Parse VTS data from socket @sock
    """
    # Connect to UNIX socket
    try:
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.connect(sockpath)
    except Exception as e:
        logger.error("Failed to connect to socket [%s]: %s", sockpath, str(e))
        return None

    sock.settimeout(0.5)

    # Send HTTP request over UNIX socket
    m_req = "GET {} HTTP/1.0\nHost: localhost\n\n\n".format(uri).encode('utf8', errors='ignore')
    try:
        rawdata = bytes()
        while True:
            sock.sendall(m_req)
            lastdata = sock.recv(524288)
            if not len(lastdata):
                break
            rawdata += lastdata
        sock.close()
    except Exception as e:
        logger.error("Failed to retrieve data from socket: %s", str(e))
        return None

    # Parse response
    try:
        r_head, r_body = re.match('^(.+)\r\n\r\n(.+)$', rawdata.decode('utf8', errors='ignore'), re.S).groups()
    except:
        logger.error("Failed to parse response body")
        return None

    # Parse JSON body
    try:
        logger.debug("Got data from VTS:\n%s", r_body.strip())
        vdata = json.loads(r_body.strip())
    except Exception as e:
        logger.error("Failed to parse JSON response body: %s", str(e))
        return None

    return vdata

Zerion Mini Shell 1.0