def post(self, path: str, body: Dict[str, Any]) -> bytes:
        start_time = time.time()
        url = self.connection.url + path
        try:
            data_from_system = requests.post(url, auth=HTTPBasicAuth(self.connection.user, self.connection.passwd),
                                             verify=self.connection.verify,
                                             headers=self.connection.headers,
                                             data=json.dumps(body), timeout=self.connection.timeout)

            data_from_system.raise_for_status()

            if data_from_system.status_code != 200 and data_from_system.status_code != 201:
                log.warn("Not a valid response - {}:{}".format(str(data_from_system.content),
                                                               data_from_system.status_code))
            else:
                log.info("call api {}".format(url), {'status': data_from_system.status_code, 'method': 'POST',
                                                     'response_time': data_from_system.elapsed.total_seconds()})
            return data_from_system.content

        except requests.exceptions.HTTPError as err:
            log.warn("{}".format(str(err)))
            raise err
        except requests.exceptions.RequestException as err:
            log.warn("{}".format(str(err)))
            raise err
        finally:
            request_time = int((time.time() - start_time) * 1000) / 1000
            log.info_response_time("Response time {}".format(self.connection.url), request_time)
    def get(self, path):
        """
        Make a get call to Monitor
        :param path:
        :return:
        """
        start_time = time.time()
        try:
            url = self.connection.url + path
            data_from_system = requests.get(url,
                                            auth=HTTPBasicAuth(self.connection.user, self.connection.passwd),
                                            headers=self.connection.headers,
                                            verify=self.connection.verify, timeout=self.connection.timeout)

            data_from_system.raise_for_status()

            if data_from_system.status_code != 200 and data_from_system.status_code != 201:
                log.warn("Not a valid response - {}:{}".format(str(data_from_system.content),
                                                               data_from_system.status_code))
            else:
                log.info("call api {}".format(url), {'status': data_from_system.status_code, 'method': 'GET',
                                                     'response_time': data_from_system.elapsed.total_seconds()})
            return data_from_system.content

        except requests.exceptions.HTTPError as err:
            log.warn("{}".format(str(err)))
            raise err
        except requests.exceptions.RequestException as err:
            log.warn("{}".format(str(err)))
            raise err
        finally:
            request_time = int((time.time() - start_time) * 1000) / 1000
            log.info_response_time("Response time {}".format(self.connection.url), request_time)
Example #3
0
def main():
    parser = argparse.ArgumentParser(description='monitor-promdiscovery')

    parser.add_argument('-f',
                        '--configfile',
                        dest="configfile",
                        help="Configuration file")

    parser.add_argument('-F',
                        '--force',
                        action="store_true",
                        dest="force",
                        help="Force write of service discovery file")

    parser.add_argument(
        '-s',
        '--system',
        dest="system",
        help=
        "System to discover. Will override configuration. Supported are op5monitor and icinga2"
    )

    args = parser.parse_args()

    if args.configfile:
        config_file = args.configfile
    else:
        config_file = 'config.yml'

    config = read_config(config_file)

    # Override system property in config
    if args.system:
        config['system'] = args.system

    log.configure_logger(config)
    log.info("Start synchronizing")

    monitor: HostByHostgroup
    if 'system' in config and select_system(config['system']):
        monitor = select_system(config['system'])(config)
    else:
        log.error("Not a valid system {}".format(config['system']))
        exit(1)

    promdis = Prom.PromDis(config, monitor.get_hosts_by_hostgroup())

    if not promdis.match() or args.force:
        promdis.update_targets()
Example #4
0
 def match(self) -> bool:
     """
     Match if the current target hosts are the same as the one you got from Monitor
     :return:
     """
     if self.set_of_targets == self.set_of_monitor_hosts and \
             self.existing_labels == self.labels:
         log.info(
             "Monitor and service discovery file match - {} target entries".
             format(len(self.set_of_monitor_hosts)))
         return True
     log.info(
         "Monitor and service discovery file not match - {} target entries in Monitor and {} entries in service discovery"
         .format(len(self.set_of_monitor_hosts), len(self.set_of_targets)))
     return False
Example #5
0
 def update_targets(self):
     """
     Write a new sd_file
     :return:
     """
     try:
         with open(self.file_name, 'w') as filetowrite:
             targets = {
                 'labels': self.labels,
                 'targets': sorted(self.monitor_hosts)
             }
             targets_list = [targets]
             yaml.dump(targets_list, filetowrite, default_flow_style=False)
             log.info("Service discovery file created {}".format(
                 self.file_name))
     except Exception as err:
         log.error("{}".format(str(err)))
         raise err