# Path: es_stats_zabbix/version.py

# 
# Path: es_stats_zabbix/exceptions.py
# 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.exceptions import FailedExecution, NotFound
from es_stats_zabbix.helpers.utils import do_request, log_to_listener, open_port
import click
@click.version_option(version=__version__)
@click.pass_context
def cli(ctx, host, port, debug, value, flag):
    """
    Connect to the backend at --host and --port.

    Specify whether to gather 'cluster' or 'nodes' LLD information with --value

    --flag is pseudo-arbitrary value used to make it possible to have multiple Zabbix keys
    reference the same data.

    Perform --debug logging upstream to the backend if specified
    """

    uri = '/api/clusterdiscovery/{0}'.format(value)
    fail = 'ZBX_NOTSUPPORTED'
    method = 'post'
    body = {}
    if flag:
        body['flag'] = flag
    if debug:
        log_to_listener(host, port, 'debug',
                        {'host':host, 'port':port, 'uri':uri, 'value':value, 'flag':flag})
    try:
        result = do_request(host, port, uri, method, body=body)
        if debug:
            msgs = {
                'result': str(result),
                'size_in_bytes': len(str(result).encode('utf-8'))
            }

# Path: es_stats_zabbix/version.py

# 
# Path: es_stats_zabbix/exceptions.py
# 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/get_cluster.py
from sys import exit
from es_stats_zabbix import __version__
from es_stats_zabbix.exceptions import FailedExecution, NotFound
from es_stats_zabbix.helpers.utils import do_request, log_to_listener, open_port
import click

@click.version_option(version=__version__)
@click.pass_context
def cli(ctx, host, port, debug, value, flag):
    """
    Connect to the backend at --host and --port.

    Specify whether to gather 'cluster' or 'nodes' LLD information with --value

    --flag is pseudo-arbitrary value used to make it possible to have multiple Zabbix keys
    reference the same data.

    Perform --debug logging upstream to the backend if specified
    """

    uri = '/api/clusterdiscovery/{0}'.format(value)
    fail = 'ZBX_NOTSUPPORTED'
    method = 'post'
    body = {}
    if flag:
        body['flag'] = flag
    if debug:
        log_to_listener(host, port, 'debug',
                        {'host':host, 'port':port, 'uri':uri, 'value':value, 'flag':flag})
    try:
        result = do_request(host, port, uri, method, body=body)
        if debug:
            msgs = {
                'result': str(result),
                'size_in_bytes': len(str(result).encode('utf-8'))
            }

            log_to_listener(host, port, 'debug', msgs)