# Path: es_stats_zabbix/version.py

# 
# Path: es_stats_zabbix/defaults/settings.py
# def apis():
#     """
#     Return constant APIS
#     """
#     return APIS
# 
# Path: es_stats_zabbix/exceptions.py
# class EmptyResult(ESZException):
#     """
#     Exception raised when there is no result at all.
#     """
# 
# class FailedExecution(ESZException):
#     """
#     Exception raised when a function fails to execute for some reason.
#     """
# 
# class NotFound(ESZException):
#     """
#     Exception raised when expected information is not found.
#     """
# 
# Path: es_stats_zabbix/helpers/utils.py
# def do_request(host, port, uri, method, body=None):
#     """Wrapper for handling REST requests"""
#     # Since we're manually separating with a /, prune if it exists.
#     uri = uri[1:] if uri[0] == '/' else uri
#     url = 'http://{0}:{1}/{2}'.format(host, port, uri)
#     try:
#         if method == 'get':
#             req = requests.get(url)
#         elif body is not None:
#             LOGGER.debug('POST: url={0}, body={1}'.format(url, body))
#             req = requests.post(url, json=body)
#         else:
#             raise ValueError('No value provided for "body"')
#         if req.status_code != 200:
#             # Something was invalid
#             msgs = {
#                 'message': 'Response received: {0}'.format(req.status_code),
#                 'method': method.upper(),
#                 'url': url,
#                 'body': body,
#             }
#             log_to_listener(host, port, 'error', msgs)
#             raise NotFound('A non-200 HTTP response code was received.')
#         else:
#             # We're good!
#             return req.text
#     except:
#         # Something else is amiss with our api/endpoint/node
#         log_to_listener(host, port, 'error', 'Failed to collect value. Try using --debug')
#         raise FailedExecution('The request was unable to successfully complete.')
# 
# def log_to_listener(host, port, level, msgs):
#     """Log to the REST API"""
#     url = 'http://{0}:{1}/api/logger/{2}'.format(host, port, level)
#     if not isinstance(msgs, dict):
#         requests.post(url, json={'message': '{0}'.format(msgs)})
#     else:
#         requests.post(url, json=msgs)
# 
# def open_port(host, port):
#     """Test whether a port is open at host.  Return boolean"""
#     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#     try:
#         sock.connect((host, port))
#         sock.shutdown(2)
#         return True
#     except:
#         return False


from sys import exit
from es_stats_zabbix import __version__
from es_stats_zabbix.defaults.settings import apis
from es_stats_zabbix.exceptions import EmptyResult, FailedExecution, NotFound
from es_stats_zabbix.helpers.utils import do_request, log_to_listener, open_port
import click
    Connect to the backend at --host and --port using "node" as the target Zabbix host name.
    Collect stats, and ship them to Zabbix via the trapper protocol.

    "node" indicates both the node name and the Zabbix host trapper target
    "nodetype" is the type of node, as defined in the YAML config file. It is one of
        "cluster",
        "coordinating",
        "master",
        "data",
        "ingest",
        "ml",
    "cluster" is special, as it collects cluster-level stats from the clusterstats API endpoint
    "interval" is also defined in the YAML config file.  If not specified, it will be '60s'
    Return the number of stats which failed to be read by Zabbix. A zero indicates all succeeded.

    Perform --debug logging upstream to the backend if specified
    """
    # Do a simple socket check first
    if not open_port(host, port):
        exit(1)

    # Now try to get the value
    if debug:
        mdict = {
            'user_parms': 'node: {0}, nodetype: {1}, interval: {2}'.format(node, nodetype, interval)
        }
        log_to_listener(host, port, 'debug', mdict)

    uri = '/api/trapperstats/{0}'.format(node)
    if debug:

# Path: es_stats_zabbix/version.py

# 
# Path: es_stats_zabbix/defaults/settings.py
# def apis():
#     """
#     Return constant APIS
#     """
#     return APIS
# 
# Path: es_stats_zabbix/exceptions.py
# class EmptyResult(ESZException):
#     """
#     Exception raised when there is no result at all.
#     """
# 
# class FailedExecution(ESZException):
#     """
#     Exception raised when a function fails to execute for some reason.
#     """
# 
# class NotFound(ESZException):
#     """
#     Exception raised when expected information is not found.
#     """
# 
# Path: es_stats_zabbix/helpers/utils.py
# def do_request(host, port, uri, method, body=None):
#     """Wrapper for handling REST requests"""
#     # Since we're manually separating with a /, prune if it exists.
#     uri = uri[1:] if uri[0] == '/' else uri
#     url = 'http://{0}:{1}/{2}'.format(host, port, uri)
#     try:
#         if method == 'get':
#             req = requests.get(url)
#         elif body is not None:
#             LOGGER.debug('POST: url={0}, body={1}'.format(url, body))
#             req = requests.post(url, json=body)
#         else:
#             raise ValueError('No value provided for "body"')
#         if req.status_code != 200:
#             # Something was invalid
#             msgs = {
#                 'message': 'Response received: {0}'.format(req.status_code),
#                 'method': method.upper(),
#                 'url': url,
#                 'body': body,
#             }
#             log_to_listener(host, port, 'error', msgs)
#             raise NotFound('A non-200 HTTP response code was received.')
#         else:
#             # We're good!
#             return req.text
#     except:
#         # Something else is amiss with our api/endpoint/node
#         log_to_listener(host, port, 'error', 'Failed to collect value. Try using --debug')
#         raise FailedExecution('The request was unable to successfully complete.')
# 
# def log_to_listener(host, port, level, msgs):
#     """Log to the REST API"""
#     url = 'http://{0}:{1}/api/logger/{2}'.format(host, port, level)
#     if not isinstance(msgs, dict):
#         requests.post(url, json={'message': '{0}'.format(msgs)})
#     else:
#         requests.post(url, json=msgs)
# 
# def open_port(host, port):
#     """Test whether a port is open at host.  Return boolean"""
#     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#     try:
#         sock.connect((host, port))
#         sock.shutdown(2)
#         return True
#     except:
#         return False


# Path: es_stats_zabbix/cli/trapper_stats.py
from sys import exit
from es_stats_zabbix import __version__
from es_stats_zabbix.defaults.settings import apis
from es_stats_zabbix.exceptions import EmptyResult, FailedExecution, NotFound
from es_stats_zabbix.helpers.utils import do_request, log_to_listener, open_port
import click

    Connect to the backend at --host and --port using "node" as the target Zabbix host name.
    Collect stats, and ship them to Zabbix via the trapper protocol.

    "node" indicates both the node name and the Zabbix host trapper target
    "nodetype" is the type of node, as defined in the YAML config file. It is one of
        "cluster",
        "coordinating",
        "master",
        "data",
        "ingest",
        "ml",
    "cluster" is special, as it collects cluster-level stats from the clusterstats API endpoint
    "interval" is also defined in the YAML config file.  If not specified, it will be '60s'
    Return the number of stats which failed to be read by Zabbix. A zero indicates all succeeded.

    Perform --debug logging upstream to the backend if specified
    """
    # Do a simple socket check first
    if not open_port(host, port):
        exit(1)

    # Now try to get the value
    if debug:
        mdict = {
            'user_parms': 'node: {0}, nodetype: {1}, interval: {2}'.format(node, nodetype, interval)
        }
        log_to_listener(host, port, 'debug', mdict)

    uri = '/api/trapperstats/{0}'.format(node)
    if debug:

        log_to_listener(host, port, 'debug', {'host':host, 'port':port, 'uri':uri})