예제 #1
0
    def _send_to_zabbix(self, metrics):
        if not (self.zabbix_server and self.zabbix_nodename):
            log.error('zabbix server or nodename not defined, skipping'
                      ' sending metrics')
            return
        # Work around bug in zbxsend, they keep the fraction which zabbix
        # then rejects.
        now = int(time.time())
        metrics = [
            zbxsend.Metric(self.zabbix_nodename, key, value, now)
            for key, value in metrics.items()
        ]
        log.debug(metrics)

        # Try each server in the list if there is more than one.
        sent = False
        for server in self.zabbix_server:
            log.debug('Trying to send metrics to: %s', server)
            if zbxsend.send_to_zabbix(metrics, server):
                log.debug('Sent metrics to: %s', server)
                sent = True
                break
            else:
                log.debug('Failed to send metrics to zabbix server: %s',
                          server)
        if not sent:
            log.error('Failed to send metrics to zabbix servers: %s',
                      self.zabbix_server)
예제 #2
0
def send_data_to_zabbix(send_data_from_dict, host_name, zbx_server_ip,
                        zbx_server_port):
    clock = time.time()
    send_data_list = []
    for keys in send_data_from_dict:
        send_data_list.append(
            zbxsend.Metric(host_name, keys, send_data_from_dict[keys], clock))

    zbxsend.send_to_zabbix(send_data_list,
                           zabbix_host=zbx_server_ip,
                           zabbix_port=zbx_server_port)
예제 #3
0
 def _send_to_zabbix(self, metrics):
     if not (self.zabbix_server and self.zabbix_nodename):
         log.warning('No zabbix connection configured, not sending metrics')
         return
     # Work around bug in zbxsend, they keep the fraction which zabbix
     # then rejects.
     now = int(time.time())
     metrics = [zbxsend.Metric(self.zabbix_nodename, key, value, now)
                for key, value in metrics.items()]
     log.debug(metrics)
     zbxsend.send_to_zabbix(metrics, self.zabbix_server)
예제 #4
0
def send_data_to_zabbix(send_data_from_dict, host_name, zbx_server_ip, zbx_server_port):
    """
        Once we have the processed data as Key/Value pair.
        Now we create a Metric JSON which is similar to below.
        Using Zabbix Metric

        {
            "request":"sender data",
            "data":[
                    {
                        "host":"Host name 1",
                        "key":"item_key",
                        "value":"33",
                        "clock":"123123123123"
                    },
                    {
                        "host":"Host name 2",
                        "key":"item_key",
                        "value":"55",
                        "clock":"23423423423"
                    }
                ]
            }

        'Clock' is taken as the current system time when the JSON was picked up.

    :param send_data_from_dict:
    :param host_name:
    :param zbx_server_ip:
    :param zbx_server_port:
    :return:
    """
    clock = time.time()
    send_data_list = []

    # Creating JSON
    for keys in send_data_from_dict:
        send_data_list.append(zbxsend.Metric(host_name, keys, send_data_from_dict[keys], clock))

    logging.info("Sending Data to Zabbix Server, for Host : " + str(host_name))
    logging.info("Zabbix IP : " + str(zabbix_server_ip))
    logging.info("Zabbix Port : " + str(zbx_server_port))

    # Sending JSON to Zabbix Server.
    zbxsend.send_to_zabbix(send_data_list, zabbix_host=zbx_server_ip, zabbix_port=zbx_server_port)
예제 #5
0
def check(testSet, configinstance, logger):
    """
    Perform the checks when called upon by argparse in main()

    :param testSet:
    :param configinstance:
    :param logger:
    :return: tuple (statcode, check)
    """

    testset = configinstance.get_test_set(testSet)

    config = configinstance.load()
    webinstance = commons.WebCaller(logger)

    # Make a request and check a resource
    response = webfacade(testSet, configinstance, webinstance, config)
    if not response:
        return (1, None)  # caught request exception!

    # This is the host defined in your metric.
    # This matches the name of your host in zabbix.
    zabbix_metric_host = config['config']['zabbix']['host']

    zabbix_telemetry = []
    report_bad_health = False

    # For each testElement do our path check and capture results

    for check in testSet['data']['testElements']:
        if not configinstance.datatypes_valid(check):
            return (1, check)

        try:
            datatypes = check['datatype'].split(',')
        except KeyError as err:
            logging.error("Uncaught unknown error")
            return (1, check)
        # We need to make a metric for each explicit data type
        # (string,int,count)
        for datatype in datatypes:
            try:
                api_res_value = commons.omnipath(
                    response.content, testSet['data']['response_type'], check)
            except KeyError as err:
                logging.error("Uncaught unknown error")
                return (1, check)

            # Append to the check things like response, statuscode, and
            # the request url, I'd like to monitor status codes but don't
            # know what that'll take.

            check['datatype'] = datatype
            check['api_response'] = api_res_value
            check['request_statuscode'] = response.status_code
            check['uri'] = testset['data']['uri']

            # Determines the host of the uri

            try:
                check['originhost'] = urlparse(
                    check['uri']).netloc.split(':')[0]
            except:
                logging.error("Could not use urlparse on '{0}'".format(
                    check['uri']))
                return (1, check)

            try:
                check['key']
            except KeyError as err:
                logging.error("Uncaught unknown error")
                return (1, check)

            # There was no value associated for the desired key.
            # This is considered a failing check, as datatype is unsupported
            if api_res_value == None:
                logging.warning("{0} check failed check="
                                "{1}".format(check['originhost'], check))
                report_bad_health = True

            # Print out each k,v
            logging.debug(" Found resource {uri}||{k} value ({v})".format(
                uri=check['uri'], k=check['key'], v=check['api_response']))

            # Applies a key format from the configuration file, allowing
            # custom zabbix keys for your items reporting to zabbix. Any
            # check in testSet can be substituted, the {uri} and
            # Pdatatype} are also made available.
            metrickey = config['config']['zabbix']['item_key_format'].format(
                **check)

            zabbix_telemetry.append(
                zbxsend.Metric(zabbix_metric_host, metrickey,
                               check['api_response']))

    logger.info("Sending telemetry to zabbix server as Metrics objects")
    logger.debug("Telemetry: {0}".format(zabbix_telemetry))
    if not transmitfacade(
            configinstance=config, metrics=zabbix_telemetry, logger=logger):
        logger.critical("Sending telemetry to zabbix failed!")

    if report_bad_health:
        return (1, check)
    else:
        return (0, check)