Exemple #1
0
def get_check(name, config_str):
    from checks import AgentCheck

    checksd_path = get_checksd_path(get_os())
    if checksd_path not in sys.path:
        sys.path.append(checksd_path)
    check_module = __import__(name)
    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)

    max_hierarchy_len = 0
    for name, clsmember in classes:
        if AgentCheck in clsmember.__bases__:
            check_class = clsmember
            break
        class_hierarchy = inspect.getmro(clsmember)
        if AgentCheck in class_hierarchy:
            if len(class_hierarchy) > max_hierarchy_len:
               max_hierarchy_len = len(class_hierarchy)
               check_class = clsmember
    if check_class is None:
        raise Exception("Unable to import check %s. Missing a class that inherits AgentCheck" % name)

    agentConfig = {
        'version': '0.1',
        'api_key': 'tota'
    }

    return check_class.from_yaml(yaml_text=config_str, check_name=name,
                                 agentConfig=agentConfig)
Exemple #2
0
def load_check(name, config, agentConfig):
    checksd_path = get_checksd_path(get_os())
    if checksd_path not in sys.path:
        sys.path.append(checksd_path)

    check_module = __import__(name)
    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)
    for name, clsmember in classes:
        if clsmember == AgentCheck:
            continue
        if issubclass(clsmember, AgentCheck):
            check_class = clsmember
            if AgentCheck in clsmember.__bases__:
                continue
            else:
                break
    if check_class is None:
        raise Exception("Unable to import check %s. Missing a class that inherits AgentCheck" % name)

    init_config = config.get("init_config", None)
    instances = config.get("instances")

    # init the check class
    try:
        return check_class(name, init_config=init_config, agentConfig=agentConfig, instances=instances)
    except:
        # Backwards compatitiblity for old checks that don't support the
        # instances argument.
        c = check_class(name, init_config=init_config, agentConfig=agentConfig)
        c.instances = instances
        return c
Exemple #3
0
def load_check(name, config, agentConfig):
    checksd_path = get_checksd_path(get_os())
    if checksd_path not in sys.path:
        sys.path.append(checksd_path)

    check_module = __import__(name)
    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)
    for _, clsmember in classes:
        if clsmember == AgentCheck:
            continue
        if issubclass(clsmember, AgentCheck):
            check_class = clsmember
            if AgentCheck in clsmember.__bases__:
                continue
            else:
                break
    if check_class is None:
        raise Exception("Unable to import check %s. Missing a class that inherits AgentCheck" % name)

    init_config = config.get('init_config', {})
    instances = config.get('instances')
    agentConfig['checksd_hostname'] = get_hostname(agentConfig)

    # init the check class
    try:
        return check_class(name, init_config=init_config, agentConfig=agentConfig, instances=instances)
    except Exception as e:
        raise Exception("Check is using old API, {0}".format(e))
Exemple #4
0
    def to_dict(self):
        status_info = AgentStatus.to_dict(self)

        # Hostnames
        status_info['hostnames'] = {}
        metadata_whitelist = [
            'hostname',
            'fqdn',
            'ipv4',
            'instance-id'
        ]
        if self.metadata:
            for key, host in self.metadata.items():
                for whitelist_item in metadata_whitelist:
                    if whitelist_item in key:
                        status_info['hostnames'][key] = host
                        break

        # Checks.d Status
        status_info['checks'] = {}
        for cs in self.check_statuses:
            status_info['checks'][cs.name] = {'instances': {}}
            for s in cs.instance_statuses:
                status_info['checks'][cs.name]['instances'][s.instance_id] = {
                    'status': s.status,
                    'has_error': s.has_error(),
                    'has_warnings': s.has_warnings(),
                }
                if s.has_error():
                    status_info['checks'][cs.name]['instances'][s.instance_id]['error'] = s.error
                if s.has_warnings():
                    status_info['checks'][cs.name]['instances'][s.instance_id]['warnings'] = s.warnings
            status_info['checks'][cs.name]['metric_count'] = cs.metric_count
            status_info['checks'][cs.name]['event_count'] = cs.event_count

        # Emitter status
        status_info['emitter'] = []
        for es in self.emitter_statuses:
            check_status = {
                'name': es.name,
                'status': es.status,
                'has_error': es.has_error(),
                }
            if es.has_error():
                check_status['error'] = es.error
            status_info['emitter'].append(check_status)

        osname = config.get_os()

        try:
            status_info['confd_path'] = config.get_confd_path(osname)
        except config.PathNotFound:
            status_info['confd_path'] = 'Not found'
        
        try:
            status_info['checksd_path'] = config.get_checksd_path(osname)
        except config.PathNotFound:
            status_info['checksd_path'] = 'Not found'

        return status_info
Exemple #5
0
def load_check(name, config, agentConfig):
    if not _is_sdk():
        checksd_path = agentConfig.get('additional_checksd', get_checksd_path(get_os()))

        # find (in checksd_path) and load the check module
        fd, filename, desc = imp.find_module(name, [checksd_path])
        check_module = imp.load_module(name, fd, filename, desc)
    else:
        check_module = _load_sdk_module(name) # parent module

    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)
    for _, clsmember in classes:
        if clsmember == AgentCheck:
            continue
        if issubclass(clsmember, AgentCheck):
            check_class = clsmember
            if AgentCheck in clsmember.__bases__:
                continue
            else:
                break
    if check_class is None:
        raise Exception("Unable to import check %s. Missing a class that inherits AgentCheck" % name)

    init_config = config.get('init_config', {})
    instances = config.get('instances')
    agentConfig['checksd_hostname'] = get_hostname(agentConfig)

    # init the check class
    try:
        return check_class(name, init_config, agentConfig, instances=instances)
    except TypeError as e:
        raise Exception("Check is using old API, {0}".format(e))
    except Exception:
        raise
Exemple #6
0
    def to_dict(self):
        status_info = AgentStatus.to_dict(self)

        # Hostnames
        status_info["hostnames"] = {}
        metadata_whitelist = ["hostname", "fqdn", "ipv4", "instance-id"]
        if self.metadata:
            for key, host in self.metadata.items():
                for whitelist_item in metadata_whitelist:
                    if whitelist_item in key:
                        status_info["hostnames"][key] = host
                        break

        # Checks.d Status
        status_info["checks"] = {}
        check_statuses = self.check_statuses + get_jmx_status()
        for cs in check_statuses:
            status_info["checks"][cs.name] = {"instances": {}}
            if cs.init_failed_error:
                status_info["checks"][cs.name]["init_failed"] = True
                status_info["checks"][cs.name]["traceback"] = cs.init_failed_traceback
            else:
                status_info["checks"][cs.name] = {"instances": {}}
                status_info["checks"][cs.name]["init_failed"] = False
                for s in cs.instance_statuses:
                    status_info["checks"][cs.name]["instances"][s.instance_id] = {
                        "status": s.status,
                        "has_error": s.has_error(),
                        "has_warnings": s.has_warnings(),
                    }
                    if s.has_error():
                        status_info["checks"][cs.name]["instances"][s.instance_id]["error"] = s.error
                    if s.has_warnings():
                        status_info["checks"][cs.name]["instances"][s.instance_id]["warnings"] = s.warnings
                status_info["checks"][cs.name]["metric_count"] = cs.metric_count
                status_info["checks"][cs.name]["event_count"] = cs.event_count

        # Emitter status
        status_info["emitter"] = []
        for es in self.emitter_statuses:
            check_status = {"name": es.name, "status": es.status, "has_error": es.has_error()}
            if es.has_error():
                check_status["error"] = es.error
            status_info["emitter"].append(check_status)

        osname = config.get_os()

        try:
            status_info["confd_path"] = config.get_confd_path(osname)
        except config.PathNotFound:
            status_info["confd_path"] = "Not found"

        try:
            status_info["checksd_path"] = config.get_checksd_path(osname)
        except config.PathNotFound:
            status_info["checksd_path"] = "Not found"

        return status_info
Exemple #7
0
    def to_dict(self):
        status_info = AgentStatus.to_dict(self)

        # Hostnames
        status_info['hostnames'] = {}

        # Checks.d Status
        status_info['checks'] = {}
        check_statuses = self.check_statuses + get_jmx_status()
        for cs in check_statuses:
            status_info['checks'][cs.name] = {'instances': {}}
            if cs.init_failed_error:
                status_info['checks'][cs.name]['init_failed'] = True
                status_info['checks'][cs.name]['traceback'] = cs.init_failed_traceback
            else:
                status_info['checks'][cs.name] = {'instances': {}}
                status_info['checks'][cs.name]['init_failed'] = False
                for s in cs.instance_statuses:
                    status_info['checks'][cs.name]['instances'][s.instance_id] = {
                        'status': s.status,
                        'has_error': s.has_error(),
                        'has_warnings': s.has_warnings(),
                    }
                    if s.has_error():
                        status_info['checks'][cs.name]['instances'][
                            s.instance_id]['error'] = s.error
                    if s.has_warnings():
                        status_info['checks'][cs.name]['instances'][
                            s.instance_id]['warnings'] = s.warnings
                status_info['checks'][cs.name]['metric_count'] = cs.metric_count
                status_info['checks'][cs.name]['event_count'] = cs.event_count

        # Emitter status
        status_info['emitter'] = []
        for es in self.emitter_statuses:
            check_status = {'name': es.name,
                            'status': es.status,
                            'has_error': es.has_error()}
            if es.has_error():
                check_status['error'] = es.error
            status_info['emitter'].append(check_status)

        osname = config.get_os()

        try:
            status_info['confd_path'] = config.get_confd_path(osname)
        except config.PathNotFound:
            status_info['confd_path'] = 'Not found'

        try:
            status_info['checksd_path'] = config.get_checksd_path(osname)
        except config.PathNotFound:
            status_info['checksd_path'] = 'Not found'

        return status_info
Exemple #8
0
def load_class(check_name, class_name):
    """
    Retrieve a class with the given name among the given check module.
    """
    checksd_path = get_checksd_path(get_os())
    check_module = __import__(check_name)
    classes = inspect.getmembers(check_module, inspect.isclass)
    for name, clsmember in classes:
        if name == class_name:
            return clsmember

    raise Exception(u"Unable to import class {0} from the check module.".format(class_name))
Exemple #9
0
def get_check(name, config_str):
    checksd_path = get_checksd_path(getOS())
    if checksd_path not in sys.path:
        sys.path.append(checksd_path)
    check_module = __import__(name)
    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)
    for name, clsmember in classes:
        if AgentCheck in clsmember.__bases__:
            check_class = clsmember
            break
    if check_class is None:
        raise Exception("Unable to import check %s. Missing a class that inherits AgentCheck" % name)

    return check_class.from_yaml(yaml_text=config_str, check_name=name)
Exemple #10
0
def get_check_class(name):
    checksd_path = get_checksd_path(get_os())
    if checksd_path not in sys.path:
        sys.path.append(checksd_path)

    check_module = __import__(name)
    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)
    for _, clsmember in classes:
        if clsmember == AgentCheck:
            continue
        if issubclass(clsmember, AgentCheck):
            check_class = clsmember
            if AgentCheck in clsmember.__bases__:
                continue
            else:
                break

    return check_class
Exemple #11
0
def get_check(name, config_str):
    from checks import AgentCheck

    checksd_path = get_checksd_path(get_os())
    if checksd_path not in sys.path:
        sys.path.append(checksd_path)
    check_module = __import__(name)
    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)
    for name, clsmember in classes:
        if issubclass(clsmember, AgentCheck) and clsmember != AgentCheck:
            check_class = clsmember
            break
    if check_class is None:
        raise Exception("Unable to import check %s. Missing a class that inherits AgentCheck" % name)

    agentConfig = {"version": "0.1", "api_key": "tota"}

    return check_class.from_yaml(yaml_text=config_str, check_name=name, agentConfig=agentConfig)
Exemple #12
0
def load_class(check_name, class_name):
    """
    Retrieve a class with the given name within the given check module.
    """
    check_module_name = check_name
    if not _is_sdk():
        checksd_path = get_checksd_path(get_os())
        if checksd_path not in sys.path:
            sys.path.append(checksd_path)
        check_module = __import__(check_module_name)
    else:
        check_module = _load_sdk_module(check_name)

    classes = inspect.getmembers(check_module, inspect.isclass)
    for name, clsmember in classes:
        if name == class_name:
            return clsmember

    raise Exception(u"Unable to import class {0} from the check module.".format(class_name))
def load_check(name, config, agentConfig):
    checksd_path = get_checksd_path(getOS())
    if checksd_path not in sys.path:
        sys.path.append(checksd_path)

    check_module = __import__(name)
    check_class = None
    classes = inspect.getmembers(check_module, inspect.isclass)
    for name, clsmember in classes:
        if clsmember == AgentCheck:
            continue
        if issubclass(clsmember, AgentCheck):
            check_class = clsmember
            if AgentCheck in clsmember.__bases__:
                continue
            else:
                break
    if check_class is None:
        raise Exception("Unable to import check %s. Missing a class that inherits AgentCheck" % name)

    init_config = config.get('init_config', None)

    # init the check class
    return check_class(name, init_config=init_config, agentConfig=agentConfig)
Exemple #14
0
    def body_lines(self):
        # Metadata whitelist
        metadata_whitelist = [
            'hostname',
            'fqdn',
            'ipv4',
            'instance-id'
        ]
        # Paths to checks.d/conf.d
        lines = [
            'Paths',
            '=====',
            ''
        ]

        osname = config.get_os()

        try:
            confd_path = config.get_confd_path(osname)
        except config.PathNotFound:
            confd_path = 'Not found'
        
        try:
            checksd_path = config.get_checksd_path(osname)
        except config.PathNotFound:
            checksd_path = 'Not found'

        lines.append('  conf.d: ' + confd_path)
        lines.append('  checks.d: ' + checksd_path)
        lines.append('')

        # Hostnames
        lines += [
            'Hostnames',
            '=========',
            ''
        ]

        if not self.metadata:
            lines.append("  No host information available yet.")
        else:
            for key, host in self.metadata.items():
                for whitelist_item in metadata_whitelist:
                    if whitelist_item in key:
                        lines.append("  " + key + ": " + host)
                        break

        lines.append('')

        # Checks.d Status
        lines += [
            'Checks',
            '======',
            ''
        ]
        check_statuses = self.check_statuses + get_jmx_status()
        if not check_statuses:
            lines.append("  No checks have run yet.")
        else:
            for cs in check_statuses:
                check_lines = [
                    '  ' + cs.name,
                    '  ' + '-' * len(cs.name)
                ]
                if cs.init_failed_error:
                    check_lines.append("    - initialize check class [%s]: %s" %
                                       (style(STATUS_ERROR, 'red'),
                                       repr(cs.init_failed_error)))
                    if self.verbose and cs.init_failed_traceback:
                        check_lines.extend('      ' + line for line in
                                           cs.init_failed_traceback.split('\n'))
                else:
                    for s in cs.instance_statuses:
                        c = 'green'
                        if s.has_warnings():
                            c = 'yellow'
                        if s.has_error():
                            c = 'red'
                        line =  "    - instance #%s [%s]" % (
                                 s.instance_id, style(s.status, c))
                        if s.has_error():
                            line += u": %s" % s.error

                        check_lines.append(line)

                        if s.has_warnings():
                            for warning in s.warnings:
                                warn = warning.split('\n')
                                if not len(warn): continue
                                check_lines.append(u"        %s: %s" %
                                    (style("Warning", 'yellow'), warn[0]))
                                check_lines.extend(u"        %s" % l for l in
                                            warn[1:])
                        if self.verbose and s.traceback is not None:
                            check_lines.extend('      ' + line for line in
                                           s.traceback.split('\n'))

                    check_lines += [
                        "    - Collected %s metrics & %s events" % (cs.metric_count, cs.event_count),
                    ]

                    if cs.library_versions is not None:
                        check_lines += [
                            "    - Dependencies:"]
                        for library, version in cs.library_versions.iteritems():
                            check_lines += [
                            "        - %s: %s" % (library, version)]

                    check_lines += [""]

                lines += check_lines

        # Emitter status
        lines += [
            "",
            "Emitters",
            "========",
            ""
        ]
        if not self.emitter_statuses:
            lines.append("  No emitters have run yet.")
        else:
            for es in self.emitter_statuses:
                c = 'green'
                if es.has_error():
                    c = 'red'
                line = "  - %s [%s]" % (es.name, style(es.status,c))
                if es.status != STATUS_OK:
                    line += ": %s" % es.error
                lines.append(line)

        return lines
Exemple #15
0
    def body_lines(self):
        lines = [
            'Clocks',
            '======',
            ''
        ]
        try:
            ntp_offset, ntp_styles = get_ntp_info()
            lines.append('  ' + style('NTP offset', *ntp_styles) + ': ' +
                         style('%s s' % round(ntp_offset, 4), *ntp_styles))
        except Exception as e:
            lines.append('  NTP offset: Unkwown (%s)' % str(e))
        lines.append('  System UTC time: ' + datetime.datetime.utcnow().__str__())
        lines.append('')

        # Paths to checks_d/conf.d
        lines += [
            'Paths',
            '=====',
            ''
        ]

        osname = config.get_os()

        try:
            confd_path = config.get_confd_path(osname)
        except config.PathNotFound:
            confd_path = 'Not found'

        try:
            checksd_path = config.get_checksd_path(osname)
        except config.PathNotFound:
            checksd_path = 'Not found'

        lines.append('  conf.d: ' + confd_path)
        lines.append('  checks_d: ' + checksd_path)
        lines.append('')

        # Hostnames
        lines += [
            'Hostnames',
            '=========',
            ''
        ]

        # Checks.d Status
        lines += [
            'Checks',
            '======',
            ''
        ]
        check_statuses = self.check_statuses + get_jmx_status()
        if not check_statuses:
            lines.append("  No checks have run yet.")
        else:
            for cs in check_statuses:
                check_lines = [
                    '  ' + cs.name,
                    '  ' + '-' * len(cs.name)
                ]
                if cs.init_failed_error:
                    check_lines.append("    - initialize check class [%s]: %s" %
                                       (style(STATUS_ERROR, 'red'),
                                        repr(cs.init_failed_error)))
                    if self.verbose and cs.init_failed_traceback:
                        check_lines.extend('      ' + line for line in
                                           cs.init_failed_traceback.split('\n'))
                else:
                    for s in cs.instance_statuses:
                        c = 'green'
                        if s.has_warnings():
                            c = 'yellow'
                        if s.has_error():
                            c = 'red'
                        line = "    - instance #%s [%s]" % (s.instance_id, style(s.status, c))
                        if s.has_error():
                            line += u": %s" % s.error
                        if s.metric_count is not None:
                            line += " collected %s metrics" % s.metric_count

                        check_lines.append(line)

                        if s.has_warnings():
                            for warning in s.warnings:
                                warn = warning.split('\n')
                                if not len(warn):
                                    continue
                                check_lines.append(u"        %s: %s" %
                                                   (style("Warning", 'yellow'), warn[0]))
                                check_lines.extend(u"        %s" % l for l in warn[1:])
                        if self.verbose and s.traceback is not None:
                            check_lines.extend('      ' + line for line in s.traceback.split('\n'))

                    check_lines += [
                        "    - Collected %s metrics & %s events" % (
                            cs.metric_count, cs.event_count),
                    ]

                    if cs.library_versions is not None:
                        check_lines += [
                            "    - Dependencies:"]
                        for library, version in cs.library_versions.iteritems():
                            check_lines += ["        - %s: %s" % (library, version)]

                    check_lines += [""]

                lines += check_lines

        # Emitter status
        lines += [
            "",
            "Emitters",
            "========",
            ""
        ]
        if not self.emitter_statuses:
            lines.append("  No emitters have run yet.")
        else:
            for es in self.emitter_statuses:
                c = 'green'
                if es.has_error():
                    c = 'red'
                line = "  - %s [%s]" % (es.name, style(es.status, c))
                if es.status != STATUS_OK:
                    line += ": %s" % es.error
                lines.append(line)

        return lines
Exemple #16
0
    def to_dict(self):
        status_info = AgentStatus.to_dict(self)

        # Hostnames
        status_info['hostnames'] = {}
        metadata_whitelist = [
            'hostname',
            'fqdn',
            'ipv4',
            'instance-id'
        ]
        if self.host_metadata:
            for key, host in self.host_metadata.iteritems():
                for whitelist_item in metadata_whitelist:
                    if whitelist_item in key:
                        status_info['hostnames'][key] = host
                        break

        # Checks.d Status
        status_info['checks'] = {}
        check_statuses = self.check_statuses + get_jmx_status()
        for cs in check_statuses:
            status_info['checks'][cs.name] = {'instances': {}}
            status_info['checks'][cs.name]['check_version'] = cs.check_version
            if cs.init_failed_error:
                status_info['checks'][cs.name]['init_failed'] = True
                status_info['checks'][cs.name]['traceback'] = \
                    cs.init_failed_traceback or cs.init_failed_error
            else:
                status_info['checks'][cs.name]['init_failed'] = False
                for s in cs.instance_statuses:
                    status_info['checks'][cs.name]['instances'][s.instance_id] = {
                        'status': s.status,
                        'has_error': s.has_error(),
                        'has_warnings': s.has_warnings(),
                    }
                    if s.has_error():
                        status_info['checks'][cs.name]['instances'][s.instance_id]['error'] = s.error
                    if s.has_warnings():
                        status_info['checks'][cs.name]['instances'][s.instance_id]['warnings'] = s.warnings
                status_info['checks'][cs.name]['metric_count'] = cs.metric_count
                status_info['checks'][cs.name]['event_count'] = cs.event_count
                status_info['checks'][cs.name]['service_check_count'] = cs.service_check_count

        # Emitter status
        status_info['emitter'] = []
        for es in self.emitter_statuses:
            check_status = {
                'name': es.name,
                'status': es.status,
                'has_error': es.has_error(),
            }
            if es.has_error():
                check_status['error'] = es.error
            status_info['emitter'].append(check_status)

        osname = config.get_os()

        try:
            status_info['confd_path'] = config.get_confd_path(osname)
        except config.PathNotFound:
            status_info['confd_path'] = 'Not found'

        try:
            status_info['checksd_path'] = config.get_checksd_path(osname)
        except config.PathNotFound:
            status_info['checksd_path'] = 'Not found'

        # Clocks
        try:
            ntp_offset, ntp_style = get_ntp_info()
            warn_ntp = len(ntp_style) > 0
            status_info["ntp_offset"] = round(ntp_offset, 4)
        except Exception as e:
            ntp_offset = "Unknown (%s)" % str(e)
            warn_ntp = True
            status_info["ntp_offset"] = ntp_offset
        status_info["ntp_warning"] = warn_ntp
        status_info["utc_time"] = datetime.datetime.utcnow().__str__()

        return status_info
Exemple #17
0
    def body_lines(self):
        # Metadata whitelist
        metadata_whitelist = [
            'hostname',
            'fqdn',
            'ipv4',
            'instance-id'
        ]

        lines = [
            'Clocks',
            '======',
            ''
        ]
        try:
            ntp_offset, ntp_styles = get_ntp_info()
            lines.append('  ' + style('NTP offset', *ntp_styles) + ': ' + style('%s s' % round(ntp_offset, 4), *ntp_styles))
        except Exception as e:
            lines.append('  NTP offset: Unknown (%s)' % str(e))
        lines.append('  System UTC time: ' + datetime.datetime.utcnow().__str__())
        lines.append('')

        # Paths to checks.d/conf.d
        lines += [
            'Paths',
            '=====',
            ''
        ]

        osname = config.get_os()

        try:
            confd_path = config.get_confd_path(osname)
        except config.PathNotFound:
            confd_path = 'Not found'

        try:
            checksd_path = config.get_checksd_path(osname)
        except config.PathNotFound:
            checksd_path = 'Not found'

        lines.append('  conf.d: ' + confd_path)
        lines.append('  checks.d: ' + checksd_path)
        lines.append('')

        # Hostnames
        lines += [
            'Hostnames',
            '=========',
            ''
        ]

        if not self.host_metadata:
            lines.append("  No host information available yet.")
        else:
            for key, host in self.host_metadata.iteritems():
                for whitelist_item in metadata_whitelist:
                    if whitelist_item in key:
                        lines.append("  " + key + ": " + host)
                        break

        lines.append('')

        # Checks.d Status
        lines += [
            'Checks',
            '======',
            ''
        ]
        check_statuses = self.check_statuses + get_jmx_status()
        if not check_statuses:
            lines.append("  No checks have run yet.")
        else:
            for cs in check_statuses:
                check_lines = [
                    '  ' + cs.name + ' ({})'.format(cs.check_version),
                    '  ' + '-' * (len(cs.name) + 3 + len(cs.check_version))
                ]
                if cs.init_failed_error:
                    check_lines.append("    - initialize check class [%s]: %s" %
                                       (style(STATUS_ERROR, 'red'),
                                        repr(cs.init_failed_error)))
                    if self.verbose and cs.init_failed_traceback:
                        check_lines.extend('      ' + line for line in
                                           cs.init_failed_traceback.split('\n'))
                else:
                    for s in cs.instance_statuses:
                        c = 'green'
                        if s.has_warnings():
                            c = 'yellow'
                        if s.has_error():
                            c = 'red'
                        line = "    - instance #%s [%s]" % (
                            s.instance_id, style(s.status, c))
                        if s.has_error():
                            line += u": %s" % s.error
                        if s.metric_count is not None:
                            line += " collected %s metrics" % s.metric_count
                        if s.instance_check_stats is not None:
                            line += " Last run duration: %s" % s.instance_check_stats.get('run_time')

                        check_lines.append(line)

                        if s.has_warnings():
                            for warning in s.warnings:
                                warn = warning.split('\n')
                                if not len(warn):
                                    continue
                                check_lines.append(u"        %s: %s" %
                                                   (style("Warning", 'yellow'), warn[0]))
                                check_lines.extend(u"        %s" % l for l in
                                                   warn[1:])
                        if self.verbose and s.traceback is not None:
                            check_lines.extend('      ' + line for line in
                                               s.traceback.split('\n'))

                    check_lines += [
                        "    - Collected %s metric%s, %s event%s & %s service check%s" % (
                            cs.metric_count, plural(cs.metric_count),
                            cs.event_count, plural(cs.event_count),
                            cs.service_check_count, plural(cs.service_check_count)),
                    ]

                    if cs.check_stats is not None:
                        check_lines += [
                            "    - Stats: %s" % pretty_statistics(cs.check_stats)
                        ]

                    if cs.library_versions is not None:
                        check_lines += [
                            "    - Dependencies:"]
                        for library, version in cs.library_versions.iteritems():
                            check_lines += [
                                "        - %s: %s" % (library, version)]

                    check_lines += [""]

                lines += check_lines

        # Metadata status
        metadata_enabled = _is_affirmative(get_config().get('display_service_metadata', False))

        if metadata_enabled:
            lines += [
                "",
                "Service metadata",
                "================",
                ""
            ]
            if not check_statuses:
                lines.append("  No checks have run yet.")
            else:
                meta_lines = []
                for cs in check_statuses:
                    # Check title
                    check_line = [
                        '  ' + cs.name,
                        '  ' + '-' * len(cs.name)
                    ]
                    instance_lines = []
                    for i, meta in enumerate(cs.service_metadata):
                        if not meta:
                            continue
                        instance_lines += ["    - instance #%s:" % i]
                        for k, v in meta.iteritems():
                            instance_lines += ["        - %s: %s" % (k, v)]
                    if instance_lines:
                        check_line += instance_lines
                        meta_lines += check_line
                if meta_lines:
                    lines += meta_lines
                else:
                    lines.append("  No metadata were collected.")

        # Emitter status
        lines += [
            "",
            "Emitters",
            "========",
            ""
        ]
        if not self.emitter_statuses:
            lines.append("  No emitters have run yet.")
        else:
            for es in self.emitter_statuses:
                c = 'green'
                if es.has_error():
                    c = 'red'
                line = "  - %s [%s]" % (es.name, style(es.status, c))
                if es.status != STATUS_OK:
                    line += ": %s" % es.error
                lines.append(line)

        return lines
Exemple #18
0
    def to_dict(self):
        status_info = AgentStatus.to_dict(self)

        # Hostnames
        status_info["hostnames"] = {}
        metadata_whitelist = ["hostname", "fqdn", "ipv4", "instance-id"]
        if self.metadata:
            for key, host in self.metadata.items():
                for whitelist_item in metadata_whitelist:
                    if whitelist_item in key:
                        status_info["hostnames"][key] = host
                        break

        # Checks.d Status
        status_info["checks"] = {}
        check_statuses = self.check_statuses + get_jmx_status()
        for cs in check_statuses:
            status_info["checks"][cs.name] = {"instances": {}}
            if cs.init_failed_error:
                status_info["checks"][cs.name]["init_failed"] = True
                status_info["checks"][cs.name]["traceback"] = cs.init_failed_traceback
            else:
                status_info["checks"][cs.name] = {"instances": {}}
                status_info["checks"][cs.name]["init_failed"] = False
                for s in cs.instance_statuses:
                    status_info["checks"][cs.name]["instances"][s.instance_id] = {
                        "status": s.status,
                        "has_error": s.has_error(),
                        "has_warnings": s.has_warnings(),
                    }
                    if s.has_error():
                        status_info["checks"][cs.name]["instances"][s.instance_id]["error"] = s.error
                    if s.has_warnings():
                        status_info["checks"][cs.name]["instances"][s.instance_id]["warnings"] = s.warnings
                status_info["checks"][cs.name]["metric_count"] = cs.metric_count
                status_info["checks"][cs.name]["event_count"] = cs.event_count
                status_info["checks"][cs.name]["service_check_count"] = cs.service_check_count

        # Emitter status
        status_info["emitter"] = []
        for es in self.emitter_statuses:
            check_status = {"name": es.name, "status": es.status, "has_error": es.has_error()}
            if es.has_error():
                check_status["error"] = es.error
            status_info["emitter"].append(check_status)

        osname = config.get_os()

        try:
            status_info["confd_path"] = config.get_confd_path(osname)
        except config.PathNotFound:
            status_info["confd_path"] = "Not found"

        try:
            status_info["checksd_path"] = config.get_checksd_path(osname)
        except config.PathNotFound:
            status_info["checksd_path"] = "Not found"

        # Clocks
        try:
            ntp_offset, ntp_style = get_ntp_info()
            warn_ntp = len(ntp_style) > 0
            status_info["ntp_offset"] = round(ntp_offset, 4)
        except Exception as e:
            ntp_offset = "Unknown (%s)" % str(e)
            warn_ntp = True
            status_info["ntp_offset"] = ntp_offset
        status_info["ntp_warning"] = warn_ntp
        status_info["utc_time"] = datetime.datetime.utcnow().__str__()

        return status_info
Exemple #19
0
    def body_lines(self):
        # Metadata whitelist
        metadata_whitelist = ['hostname', 'fqdn', 'ipv4', 'instance-id']

        lines = ['Clocks', '======', '']
        try:
            ntp_offset, ntp_styles = get_ntp_info()
            lines.append('  ' + style('NTP offset', *ntp_styles) + ': ' +
                         style('%s s' % round(ntp_offset, 4), *ntp_styles))
        except Exception as e:
            lines.append('  NTP offset: Unknown (%s)' % str(e))
        lines.append('  System UTC time: ' +
                     datetime.datetime.utcnow().__str__())
        lines.append('')

        # Paths to checks.d/conf.d
        lines += ['Paths', '=====', '']

        osname = config.get_os()

        try:
            confd_path = config.get_confd_path(osname)
        except config.PathNotFound:
            confd_path = 'Not found'

        try:
            checksd_path = config.get_checksd_path(osname)
        except config.PathNotFound:
            checksd_path = 'Not found'

        lines.append('  conf.d: ' + confd_path)
        lines.append('  checks.d: ' + checksd_path)
        lines.append('')

        # Hostnames
        lines += ['Hostnames', '=========', '']

        if not self.host_metadata:
            lines.append("  No host information available yet.")
        else:
            for key, host in self.host_metadata.iteritems():
                for whitelist_item in metadata_whitelist:
                    if whitelist_item in key:
                        lines.append("  " + key + ": " + host)
                        break

        lines.append('')

        # Checks.d Status
        lines += ['Checks', '======', '']
        check_statuses = self.check_statuses + get_jmx_status()
        if not check_statuses:
            lines.append("  No checks have run yet.")
        else:
            for cs in check_statuses:
                check_lines = ['  ' + cs.name, '  ' + '-' * len(cs.name)]
                if cs.init_failed_error:
                    check_lines.append(
                        "    - initialize check class [%s]: %s" % (style(
                            STATUS_ERROR, 'red'), repr(cs.init_failed_error)))
                    if self.verbose and cs.init_failed_traceback:
                        check_lines.extend(
                            '      ' + line
                            for line in cs.init_failed_traceback.split('\n'))
                else:
                    for s in cs.instance_statuses:
                        c = 'green'
                        if s.has_warnings():
                            c = 'yellow'
                        if s.has_error():
                            c = 'red'
                        line = "    - instance #%s [%s]" % (s.instance_id,
                                                            style(s.status, c))
                        if s.has_error():
                            line += u": %s" % s.error
                        if s.metric_count is not None:
                            line += " collected %s metrics" % s.metric_count
                        if s.instance_check_stats is not None:
                            line += " Last run duration: %s" % s.instance_check_stats.get(
                                'run_time')

                        check_lines.append(line)

                        if s.has_warnings():
                            for warning in s.warnings:
                                warn = warning.split('\n')
                                if not len(warn):
                                    continue
                                check_lines.append(
                                    u"        %s: %s" %
                                    (style("Warning", 'yellow'), warn[0]))
                                check_lines.extend(u"        %s" % l
                                                   for l in warn[1:])
                        if self.verbose and s.traceback is not None:
                            check_lines.extend(
                                '      ' + line
                                for line in s.traceback.split('\n'))

                    check_lines += [
                        "    - Collected %s metric%s, %s event%s & %s service check%s"
                        % (cs.metric_count, plural(
                            cs.metric_count), cs.event_count,
                           plural(cs.event_count), cs.service_check_count,
                           plural(cs.service_check_count)),
                    ]

                    if cs.check_stats is not None:
                        check_lines += [
                            "    - Stats: %s" %
                            pretty_statistics(cs.check_stats)
                        ]

                    if cs.library_versions is not None:
                        check_lines += ["    - Dependencies:"]
                        for library, version in cs.library_versions.iteritems(
                        ):
                            check_lines += [
                                "        - %s: %s" % (library, version)
                            ]

                    check_lines += [""]

                lines += check_lines

        # Metadata status
        metadata_enabled = _is_affirmative(get_config().get(
            'display_service_metadata', False))

        if metadata_enabled:
            lines += ["", "Service metadata", "================", ""]
            if not check_statuses:
                lines.append("  No checks have run yet.")
            else:
                meta_lines = []
                for cs in check_statuses:
                    # Check title
                    check_line = ['  ' + cs.name, '  ' + '-' * len(cs.name)]
                    instance_lines = []
                    for i, meta in enumerate(cs.service_metadata):
                        if not meta:
                            continue
                        instance_lines += ["    - instance #%s:" % i]
                        for k, v in meta.iteritems():
                            instance_lines += ["        - %s: %s" % (k, v)]
                    if instance_lines:
                        check_line += instance_lines
                        meta_lines += check_line
                if meta_lines:
                    lines += meta_lines
                else:
                    lines.append("  No metadata were collected.")

        # Emitter status
        lines += ["", "Emitters", "========", ""]
        if not self.emitter_statuses:
            lines.append("  No emitters have run yet.")
        else:
            for es in self.emitter_statuses:
                c = 'green'
                if es.has_error():
                    c = 'red'
                line = "  - %s [%s]" % (es.name, style(es.status, c))
                if es.status != STATUS_OK:
                    line += ": %s" % es.error
                lines.append(line)

        return lines