Exemple #1
0
def get_uptime(elastichost, plugin_hostname, data_validity, verbose):
    try:
        # Get prerequisites for ElasticSearch API:
        addr, header = generic_api_call(elastichost)
        payload = custom_api_payload(plugin_hostname, data_validity)
        # Request the ElasticSearch API:
        results = requests.get(url=addr,
                               headers=header,
                               json=payload,
                               verify=False)
        results_json = results.json()
        if verbose:
            print(
                "## VERBOSE MODE - API REST HTTP RESPONSE: ##########################################"
            )
            print("request payload: {}".format(payload))
            print("JSON output: {}".format(results_json))
            print(
                "####################################################################################"
            )  # Extract the "Total Hit" from results (= check if an Uptime has been returned):
        total_hit = int(results_json["hits"]["total"]['value'])
        # If request hits: extract results (Uptime in ms) and display Verbose Mode if requested in ARGS ; otherwise return a static code (0):
        if total_hit != 0:
            uptime_ms = results_json["hits"]["hits"][0]["_source"]["system"][
                "uptime"]["duration"]["ms"]
        else:
            uptime_ms = 0
        return uptime_ms / 1000
    except Exception as e:
        print("Error calling \"get_uptime\"... Exception {}".format(e))
        sys.exit(3)
def get_interfaces(elastichost, hostname, data_validity, verbose):
    try:
        # Get prerequisites for ElasticSearch API:
        addr, header = generic_api_call(elastichost)
        payload = custom_api_payload(hostname, data_validity)
        # Request the ElasticSearch API:
        results = requests.get(url=addr,
                               headers=header,
                               json=payload,
                               verify=False)
        results_json = results.json()
        if verbose:
            pp = pprint.PrettyPrinter(indent=4)
            print(
                "### VERBOSE MODE - API REST HTTP RESPONSE: #########################################"
            )
            print("### request payload:")
            pp.pprint(payload)
            print("### JSON output:")
            print(results_json)
            print(
                "####################################################################################"
            )

        if not bool(results_json['timed_out']) and int(
                results_json["hits"]["total"]['value']) > 0:
            niclst = []
            # get a list of returned fs, then keep only latest item of each mountpoint
            allfslist = [i['_source'] for i in results_json['hits']['hits']]
            for nicname in set(
                [i['system']['network']['name'] for i in allfslist]):
                item = max([
                    i for i in allfslist
                    if i['system']['network']['name'] == nicname
                ],
                           key=lambda timestamp: timestamp['@timestamp'])
                niclst.append(item['system']['network'])

            def sort_list(element):
                return len(element['name'])

            return sorted(niclst, key=sort_list)
        else:
            # no fs returned
            return False

    except Exception as e:
        print("Error calling \"get_interfaces\"... Exception {}".format(e))
        sys.exit(3)
def get_process_nb(elastichost, hostname, process_name, data_validity, verbose,
                   payload_get_process):
    try:
        if payload_get_process != "No_Payload":
            # Get prerequisites for ElasticSearch API:
            addr, header = generic_api_call(elastichost)
            # Request the ElasticSearch API:
            results = requests.get(url=addr,
                                   headers=header,
                                   json=payload_get_process,
                                   verify=False)
            results_json = results.json()
            if verbose:
                print(
                    "## GET PROCESS - VERBOSE MODE - API REST HTTP REQUEST - PAYLOAD: ####################################################################################"
                )
                print("REQUESTED PAYLOAD: {}".format(payload_get_process) +
                      '\n')
                print(
                    "## GET PROCESS - VERBOSE MODE - API REST HTTP RESPONSE - JSON OUTPUT: ###############################################################################"
                )
                print("JSON RESPONSE: {}".format(results_json) + '\n')
                print(
                    "## GET PROCESS - VERBOSE MODE - API REST HTTP RESPONSE - HITS: #####################################################################################"
                )
                print("TOTAL HIT: {}".format(str(results_json["hits"]
                                                 ["total"])) + '\n')
                print(
                    "######################################################################################################################################"
                )
            # Extract the "Total Hit" from results (= check if LOAD Value has been returned):
            ##process_nb = int(results_json["hits"]["total"])
            process_nb = 0
            for event in range(len(results_json["hits"]["hits"])):
                process_state = results_json["hits"]["hits"][event]["_source"][
                    "system"]["process"]["state"]
                if (process_state == "running") or (process_state
                                                    == "sleeping"):
                    process_nb = process_nb + 1
        else:
            process_nb = 0
        return process_nb

    except Exception as e:
        print("Error calling \"get_process_nb\"... Exception {}".format(e))
        sys.exit(3)
Exemple #4
0
def get_cpu(elastic_host, plugin_hostname, data_validity, verbose):
    try:
        # Get prerequisites for ElasticSearch API:
        addr, header = generic_api_call(elastic_host)
        payload = custom_api_payload(plugin_hostname, data_validity)
        # Request the ElasticSearch API:
        results = requests.get(url=addr,
                               headers=header,
                               json=payload,
                               verify=False)
        results_json = results.json()
        # Extract the "Total Hit" from results (= check if CPU Value has been returned):
        total_hit = int(results_json["hits"]["total"]['value'])
        # If request hits: extract results (CPU Values in %) and display Verbose Mode if requested in ARGS ; otherwise return a static code (0):
        if verbose:
            print(
                "## VERBOSE MODE - API REST HTTP RESPONSE: ##########################################"
            )
            print("request payload: {}".format(payload))
            print("JSON output: {}".format(results_json))
            print(
                "####################################################################################"
            )

        cpu_total, cpu_user, cpu_system = 0, 0, 0
        if total_hit != 0:
            cpu_nb = int(results_json["hits"]["hits"][0]["_source"]["system"]
                         ["cpu"]["cores"])
            cpu_total = float(
                float(results_json["hits"]["hits"][0]["_source"]["system"]
                      ["cpu"]["total"]["pct"]) * 100) / cpu_nb
            cpu_user = float(
                float(results_json["hits"]["hits"][0]["_source"]["system"]
                      ["cpu"]["user"]["pct"]) * 100) / cpu_nb
            cpu_system = float(
                float(results_json["hits"]["hits"][0]["_source"]["system"]
                      ["cpu"]["system"]["pct"]) * 100) / cpu_nb
        elif (total_hit == 0) and (verbose == "0"):
            cpu_total, cpu_user, cpu_system = 0, 0, 0
        return total_hit, cpu_total, cpu_user, cpu_system
    except Exception as e:
        print("Error calling \"get_cpu\"... Exception {}".format(e))
        sys.exit(3)
def get_service(elastichost, hostname, data_validity, verbose, custom_payload):
    try:
        # Get prerequisites for ElasticSearch API:
        addr, header = generic_api_call(elastichost)
        # Request the ElasticSearch API:
        results = requests.get(url=addr,
                               headers=header,
                               json=custom_payload,
                               verify=False)
        results_json = results.json()
        if verbose:
            print(
                "## VERBOSE MODE - API REST HTTP REQUEST - PAYLOAD: ####################################################################################"
            )
            print("REQUESTED PAYLOAD: {}".format(custom_payload) + '\n')
            print(
                "## VERBOSE MODE - API REST HTTP RESPONSE - JSON OUTPUT: ###############################################################################"
            )
            print("JSON RESPONSE: {}".format(results_json) + '\n')
            print(
                "## VERBOSE MODE - API REST HTTP RESPONSE - HITS: #####################################################################################"
            )
            print("TOTAL HIT: {}".format(str(results_json["hits"]["total"])) +
                  '\n')
            print(
                "######################################################################################################################################"
            )
        # Extract the "Total Hit" from results (= check if LOAD Value has been returned):
        total_hit = int(results_json["hits"]["total"]['value'])
        # If request hits: extract results and display Verbose Mode if requested in ARGS ; otherwise return a static code (0):
        display_name, service_status = "TBD", "TBD"
        if total_hit != 0:
            display_name = results_json["hits"]["hits"][0]["_source"][
                "windows"]["service"]["display_name"]
            service_status = results_json["hits"]["hits"][0]["_source"][
                "windows"]["service"]["state"]
        return total_hit, display_name, service_status
    except Exception as e:
        print("Error calling \"get_service\"... Exception {}".format(e))
        sys.exit(3)
Exemple #6
0
def get_disk(cfg: disk_cfg):
    '''
    Request a custom ElasticSearch API REST Call
    here: Get space for all Disks with: Percentage Used, Quantity Used (GigaBytes), and Quantity Free (GigaBytes)
    '''
    def _list_append(item):
        return {
            'device_name': item['system']['filesystem']['device_name'],
            'mount_point': item['system']['filesystem']['mount_point'],
            'total': int(item['system']['filesystem']['total']),
            'free': int(item['system']['filesystem']['free']),
            'used': int(item['system']['filesystem']['used']['bytes'])
        }

    def _sort_fslist(element):
        return len(element['mount_point'])

    try:
        # Get prerequisites for ElasticSearch API:
        # resp_entries_range = 0
        addr, header = generic_api_call(cfg.es_api_url)
        payload = custom_api_payload(cfg.hostname, cfg.data_ttl)
        # Request the ElasticSearch API:
        results = requests.get(url=addr, headers=header, json=payload, verify=False)
        results_json = results.json()
        if cfg.verbose_level >= 3:
            pp = pprint.PrettyPrinter(indent=4)
            print("### VERBOSE MODE - API REST HTTP RESPONSE: #########################################")
            print("### request payload:")
            pp.pprint(payload)
            print("### JSON output:")
            pp.pprint(results_json)
            print("####################################################################################")

        if int(results_json["hits"]["total"]['value']) > 0:
            pattern = None
            if cfg.filter_pattern:
                if not cfg.filter_not_re:
                    pattern = re.compile(cfg.filter_pattern)
                else:
                    pattern = cfg.filter_pattern

            fslist = []
            # get a list of returned fs, then keep only latest item of each mountpoint
            allfslist = [i['_source'] for i in results_json['hits']['hits']]
            for fs in set([i['system']['filesystem']['mount_point'] for i in allfslist]):
                item = max(
                    [i for i in allfslist if i['system']['filesystem']['mount_point'] == fs],
                    key=lambda timestamp: timestamp['@timestamp']
                )
                if int(item['system']['filesystem']['total']) == 0:
                    # les FS d'une capacité de 0 octets sont des FS virtuels et sont ignorés
                    continue
                elif cfg.filter_exclude:
                    # exclude filtering mode
                    if pattern and not cfg.filter_not_re:
                        if not pattern.match(item['system']['filesystem']['mount_point']):
                            fslist.append(_list_append(item))
                    elif pattern and cfg.filter_not_re:
                        if pattern != item['system']['filesystem']['mount_point']:
                            fslist.append(_list_append(item))
                    else:
                        fslist.append(_list_append(item))
                else:
                    # include filtering mode
                    if pattern and not cfg.filter_not_re:
                        if pattern.match(item['system']['filesystem']['mount_point']):
                            fslist.append(_list_append(item))
                    elif pattern and cfg.filter_not_re:
                        if pattern == item['system']['filesystem']['mount_point']:
                            fslist.append(_list_append(item))
                    else:
                        fslist.append(_list_append(item))

            return sorted(fslist, key=_sort_fslist)
        else:
            # no fs returned
            return False

    except Exception as e:
        print("Error calling \"get_disk\"... Exception {}".format(e))
        sys.exit(3)