Example #1
0
def do_detect_list():
    try:
        (code, r) = get_opsbro_local('/agent/detectors')
    except get_request_errors() as exp:
        logger.error(exp)
        return
    
    try:
        d = jsoner.loads(r)
    except ValueError as exp:  # bad json
        logger.error('Bad return from the server %s' % exp)
        return
    print_info_title('Detectors')
    logger.debug(str(d))
    e = []
    d = sorted(d, key=lambda i: i['name'])
    for i in d:
        # aligne name too
        name = '%-20s' % i['name'].split('/')[-1]
        groups = i['add_groups']
        # align pack level
        pack_level = '%-6s' % i['pack_level']
        # Aligne pack name
        pack_name = '%-10s' % i['pack_name']
        
        print_element_breadcumb(pack_name, pack_level, 'detector', name, set_pack_color=True)
        cprint('')
        cprint('   if:         ', color='grey', end='')
        cprint(i['apply_if'], color='green')
        cprint('   add groups: ', color='grey', end='')
        cprint(','.join(groups), color='magenta')
Example #2
0
def do_collectors_run(name):
    collectormgr.load_collectors({})
    for (colname, e) in collectormgr.collectors.items():
        colname = e['name']
        if colname != name:
            continue
        logger.debug('Launching collector', name)
        inst = e['inst']
        logger.debug('COLLECTOR: launching collector %s' % colname)
        inst.main()
        pretty_print(e['results'])
Example #3
0
 def _parse_cgroup_file(self, stat_file):
     try:
         logger.debug("Opening cgroup file: %s" % stat_file)
         with open(stat_file) as fp:
             return dict(map(lambda x: x.split(), fp.read().splitlines()))
     except IOError:
         # It is possible that the container got stopped between the API call and now
         logger.info(
             "Can't open %s. Theses metrics for this container are skipped."
             % stat_file)
         return None
Example #4
0
def do_wait_ok(check_name, timeout=30):
    import itertools
    spinners = itertools.cycle(CHARACTERS.spinners)
    
    name = check_name
    
    state_string = 'UNKNOWN'
    for i in range(timeout):
        
        uri = '/monitoring/state'
        try:
            (code, r) = get_opsbro_local(uri)
        except get_request_errors() as exp:
            logger.error(exp)
            return
        
        try:
            states = jsoner.loads(r)
        except ValueError as exp:  # bad json
            logger.error('Bad return from the server %s' % exp)
            return
        checks = states['checks']
        check = None
        for (cname, c) in checks.items():
            if c['display_name'] == name:
                check = c
        if not check:
            logger.error("Cannot find the check '%s'" % name)
            sys.exit(2)
        state_id = check['state_id']
        
        c = STATE_ID_COLORS.get(state_id, 'cyan')
        state_string = STATE_ID_STRINGS.get(state_id, 'UNKNOWN')
        
        cprint('\r %s ' % next(spinners), color='blue', end='')
        cprint('%s' % name, color='magenta', end='')
        cprint(' is ', end='')
        cprint('%s' % state_string.ljust(10), color=c, end='')
        cprint(' (%d/%d)' % (i, timeout), end='')
        # As we did not \n, we must flush stdout to print it
        sys.stdout.flush()
        if state_id == 0:
            cprint("\nThe check %s is OK" % name)
            sys.exit(0)
        logger.debug("Current state %s" % state_id)
        
        time.sleep(1)
    cprint("\nThe check %s is not OK after %s seconds (currently %s)" % (name, timeout, state_string))
    sys.exit(2)
Example #5
0
def __do_install_files(lst):
    # * dir : dest_directory
    # * lfiles : local files in this archive
    for (dir, lfiles) in lst:
        # Be sute the directory do exist
        if not os.path.exists(dir):
            # ==> mkdir -p
            logger.debug('The directory %s is missing, creating it' % dir)
            os.makedirs(dir)
        for lfile in lfiles:
            lfile_name = os.path.basename(lfile)
            destination = os.path.join(dir, lfile_name)
            logger.debug("Copying local file %s into %s" %
                         (lfile, destination))
            shutil.copy2(lfile, destination)
Example #6
0
def grep_file(string, path, regexp=False):
    """**file_exists(path)** -> return True if a string or a regexp match the content of a file, False otherwise.

 * string: (string)  string (or regexp expression) to check
 * path: (string) path of the file to look inside.
 * regexp: (boolean) is the string a regexp or not.

<code>
    Example:
        grep_file('centos', '/etc/redhat-release')
    Returns:
        True
</code>
    """
    s = string
    p = path
    if not os.path.exists(p):
        logger.debug('[evaluater::grep_file] no such fle %s' % p)
        return False
    try:
        f = open(p, 'r')
        lines = f.readlines()
    except Exception as exp:
        logger.error(
            '[evaluater::grep_file] Trying to grep file %s but cannot open/read it: %s'
            % (p, exp))
        return False
    pat = None
    if regexp:
        try:
            pat = re.compile(s, re.I)
        except Exception as exp:
            logger.error(
                '[evaluater::grep_file]Cannot compile regexp expression: %s')
        return False
    if regexp:
        for line in lines:
            if pat.search(line):
                return True
    else:
        s = s.lower()
        for line in lines:
            if s in line.lower():
                return True
    logger.debug('[evaluater::grep_file] GREP FILE FAIL: no such line %s %s' %
                 (p, s))
    return False
Example #7
0
def do_generators_wait_compliant(generator_name, timeout=30):
    import itertools
    spinners = itertools.cycle(CHARACTERS.spinners)

    current_state = 'UNKNOWN'
    for i in range(timeout):
        uri = '/generators/state'
        try:
            (code, r) = get_opsbro_local(uri)
        except get_request_errors() as exp:
            logger.error(exp)
            return

        try:
            generators = jsoner.loads(r)
        except ValueError as exp:  # bad json
            logger.error('Bad return from the server %s' % exp)
            return
        generator = None
        for (cname, c) in generators.items():
            if c['name'] == generator_name:
                generator = c
        if not generator:
            logger.error("Cannot find the generator '%s'" % generator_name)
            sys.exit(2)
        current_state = generator['state']
        cprint('\r %s ' % next(spinners), color='blue', end='')
        cprint('%s' % generator_name, color='magenta', end='')
        cprint(' is ', end='')
        cprint('%15s ' % current_state,
               color=GENERATOR_STATE_COLORS.get(current_state, 'cyan'),
               end='')
        cprint(' (%d/%d)' % (i, timeout), end='')
        # As we did not \n, we must flush stdout to print it
        sys.stdout.flush()
        if current_state == 'COMPLIANT':
            cprint("\nThe generator %s is compliant" % generator_name)
            sys.exit(0)
        logger.debug("Current state %s" % current_state)

        time.sleep(1)
    cprint(
        "\nThe generator %s is not compliant after %s seconds (currently %s)" %
        (generator_name, timeout, current_state))
    sys.exit(2)
Example #8
0
def do_wait_event(event_type, timeout=30):
    # The information is available only if the agent is started
    wait_for_agent_started(visual_wait=True)

    import itertools
    spinners = itertools.cycle(CHARACTERS.spinners)

    for i in range(timeout):
        uri = '/agent/event/%s' % event_type
        logger.debug('ASK FOR EVENT %s' % event_type)
        try:
            evt = get_opsbro_json(
                uri, timeout=1)  # slow timeout to allow fast looping
        # Timemouts: just loop
        except get_not_critical_request_errors() as exp:
            logger.debug(
                'Asking for event: get timeout (%s), skiping this turn' % exp)
            evt = None
        except get_request_errors() as exp:
            logger.error(
                'Cannot ask for event %s because there is a critical error: %s'
                % (event_type, exp))
            sys.exit(2)

        if evt is not None:
            cprint('\n %s ' % CHARACTERS.arrow_left, color='grey', end='')
            cprint('%s ' % CHARACTERS.check, color='green', end='')
            cprint('The event ', end='')
            cprint('%s' % event_type, color='magenta', end='')
            cprint(' is ', end='')
            cprint('detected', color='green')
            sys.exit(0)
        # Not detected? increase loop
        cprint('\r %s ' % next(spinners), color='blue', end='')
        cprint('%s' % event_type, color='magenta', end='')
        cprint(' is ', end='')
        cprint('NOT DETECTED', color='magenta', end='')
        cprint(' (%d/%d)' % (i, timeout), end='')
        # As we did not \n, we must flush stdout to print it
        sys.stdout.flush()
        time.sleep(1)
    cprint("\nThe event %s was not detected after %s seconds" %
           (event_type, timeout))
    sys.exit(2)
Example #9
0
def do_collectors_wait_ok(collector_name, timeout=30):
    import itertools
    spinners = itertools.cycle(CHARACTERS.spinners)

    current_state = 'PENDING'
    for i in range(timeout):
        try:
            collectors = get_opsbro_json('/collectors')
        except get_request_errors() as exp:
            logger.error(exp)
            return
        collector = None
        for (cname, c) in collectors.items():
            if cname == collector_name:
                collector = c
        if not collector:
            logger.error("Cannot find the collector '%s'" % collector_name)
            sys.exit(2)
        current_state = collector['state']
        cprint('\r %s ' % next(spinners), color='blue', end='')
        cprint('%s' % collector_name, color='magenta', end='')
        cprint(' is ', end='')
        cprint('%15s ' % current_state,
               color=COLLECTORS_STATE_COLORS.get(current_state, 'cyan'),
               end='')
        cprint(' (%d/%d)' % (i, timeout), end='')
        # As we did not \n, we must flush stdout to print it
        sys.stdout.flush()
        if current_state == 'OK':
            cprint("\nThe collector %s is OK" % collector_name)
            sys.exit(0)
        logger.debug("Current state %s" % current_state)

        time.sleep(1)
    cprint("\nThe collector %s is not OK after %s seconds (currently %s)" %
           (collector_name, timeout, current_state))
    sys.exit(2)
Example #10
0
 def _get_value_from_expression():
     logger.debug('\n\n\n\n\n\n\n\n\n\nEVAL EXPR %s\n\n' % this_expr)
     expr_64 = base64.b64encode(unicode_to_bytes(this_expr))
     try:
         r = post_opsbro_json('/agent/evaluator/eval', {'expr': expr_64})
     except Exception as exp:
         logger.debug('\n\n\n\n\n\n\n\n\n\nExcep Result %s => %s\n\n' %
                      (this_expr, exp))
         r = None
     logger.debug('\n\n\n\n\n\n\n\nResult %s => %s\n\n' % (this_expr, r))
     return r
Example #11
0
def do_members(detail=False):
    # The information is available only if the agent is started
    wait_for_agent_started(visual_wait=True)

    try:
        members = get_opsbro_json('/agent/members').values()
    except get_request_errors() as exp:
        logger.error('Cannot join opsbro agent to list members: %s' % exp)
        sys.exit(1)
    members = my_sort(members, cmp_f=__sorted_members)
    pprint = libstore.get_pprint()
    logger.debug('Raw members: %s' % (pprint.pformat(members)))
    # If there is a display_name, use it
    max_name_size = max([
        max(len(m['name']),
            len(m.get('display_name', '')) + 4) for m in members
    ])
    max_addr_size = max(
        [len(m['addr']) + len(str(m['port'])) + 1 for m in members])
    zones = set()
    for m in members:
        mzone = m.get('zone', '')
        if mzone == '':
            mzone = NO_ZONE_DEFAULT
        m['zone'] = mzone  # be sure to fix broken zones
        zones.add(mzone)
    zones = list(zones)
    zones.sort()
    for z in zones:
        z_display = z
        if not z:
            z_display = NO_ZONE_DEFAULT
        z_display = z_display.ljust(15)
        title_s = '%s: %s' % (sprintf('Zone', color='yellow', end=''),
                              sprintf(z_display, color='blue', end=''))
        print_h1(title_s, raw_title=True)
        for m in members:
            zone = m.get('zone', NO_ZONE_DEFAULT)
            if zone != z:
                continue
            name = m['name']
            if m.get('display_name', ''):
                name = '[ ' + m.get('display_name') + ' ]'
            groups = m.get('groups', [])
            groups.sort()
            port = m['port']
            addr = m['addr']
            state = m['state']
            is_proxy = m.get('is_proxy', False)
            if not detail:
                cprint('  - %s > ' % zone, color='blue', end='')
                cprint('%s  ' % name.ljust(max_name_size),
                       color='magenta',
                       end='')
            else:
                cprint(' %s  %s  ' % (m['uuid'], name.ljust(max_name_size)),
                       end='')
            c = NODE_STATE_COLORS.get(state, 'cyan')
            state_prefix = NODE_STATE_PREFIXS.get(
                state, CHARACTERS.double_exclamation)
            cprint(('%s %s' % (state_prefix, state)).ljust(9), color=c,
                   end='')  # 7 for the maximum state string + 2 for prefix
            s = ' %s:%s ' % (addr, port)
            s = s.ljust(max_addr_size + 2)  # +2 for the spaces
            cprint(s, end='')
            if is_proxy:
                cprint('proxy ', end='')
            else:
                cprint('      ', end='')
            if detail:
                cprint('%5d' % m['incarnation'], end='')
            cprint(' %s ' % ','.join(groups))
Example #12
0
def do_compliance_wait_compliant(compliance_name, timeout=30, exit_if_ok=True):
    import itertools
    spinners = itertools.cycle(CHARACTERS.spinners)

    current_state = COMPLIANCE_STATES.UNKNOWN
    for i in range(timeout):  # no xrange in python3
        uri = '/compliance/state'
        try:
            (code, r) = get_opsbro_local(uri)
        except get_request_errors() as exp:
            logger.error(exp)
            return

        try:
            compliances = jsoner.loads(r)
        except ValueError as exp:  # bad json
            logger.error('Bad return from the server %s' % exp)
            return
        compliance = None
        for (cname, c) in compliances.items():
            if c['name'] == compliance_name:
                compliance = c
        if not compliance:
            logger.error("Cannot find the compliance '%s'" % compliance_name)
            sys.exit(2)
        logger.debug('Current compliance data', compliance)
        current_step = ''
        current_state = compliance['state']
        if compliance['is_running']:
            current_state = COMPLIANCE_STATES.RUNNING
            current_step = compliance['current_step']
        # Clean line
        try:
            terminal_height, terminal_width = get_terminal_size()
        except:  # beware, maybe we don't have a tty
            terminal_width = 100
        cprint('\r' + ' ' * terminal_width, end='')
        cprint('\r %s ' % next(spinners), color='blue',
               end='')  # no spinnner.next in python3
        cprint('%s' % compliance_name, color='magenta', end='')
        cprint(' is ', end='')
        cprint('%15s ' % current_state,
               color=COMPLIANCE_STATE_COLORS.get(current_state, 'cyan'),
               end='')
        cprint(' (%d/%d)' % (i, timeout), end='')
        if current_step:
            cprint(' [ in step ', end='')
            cprint(current_step, color='magenta', end='')
            cprint(' ]', end='')
        # As we did not \n, we must flush stdout to print it
        sys.stdout.flush()
        if current_state == COMPLIANCE_STATES.COMPLIANT:
            cprint("\nThe compliance rule %s is compliant" % compliance_name)
            if exit_if_ok:
                sys.exit(0)
            else:
                return
        logger.debug("Current state %s" % current_state)

        time.sleep(1)
    cprint(
        "\nThe compliance rule %s is not compliant after %s seconds (currently %s)"
        % (compliance_name, timeout, current_state))
    sys.exit(2)
Example #13
0
def do_info(show_logs):
    try:
        d = get_opsbro_json('/agent/info')
    except get_request_errors() as exp:
        logger.error('Cannot join opsbro agent for info: %s' % exp)
        sys.exit(1)
    logs = d.get('logs')
    version = d.get('version')
    cpu_consumption = d.get('cpu_consumption')
    memory_consumption = d.get('memory_consumption')
    name = d.get('name')
    display_name = d.get('display_name', '')
    # A failback to display name is the name (hostname)
    if not display_name:
        display_name = name
    else:  # show it's a display name
        display_name = '[ ' + display_name + ' ]'
    port = d.get('port')
    local_addr = d.get('local_addr')
    public_addr = d.get('public_addr')
    zone = d.get('zone')
    zone_color = 'green'
    if not zone:
        zone = NO_ZONE_DEFAULT
        zone_color = 'red'

    is_managed_system = d.get('is_managed_system')
    system_distro = d.get('system_distro')
    system_distroversion = d.get('system_distroversion')

    is_zone_protected = d.get('is_zone_protected')
    is_zone_protected_display = ('%s zone have a gossip key' %
                                 CHARACTERS.check,
                                 'green') if is_zone_protected else (
                                     '%s zone do not have a gossip key' %
                                     CHARACTERS.double_exclamation, 'yellow')

    nb_threads = d.get('threads')['nb_threads']
    hosting_drivers_state = d.get('hosting_drivers_state', [])
    httpservers = d.get('httpservers', {'internal': None, 'external': None})
    socket_path = d.get('socket')
    _uuid = d.get('uuid')
    # Modules groking
    modules = d.get('modules', {})
    topics = d.get('topics', {})
    # Get groups as sorted
    groups = d.get('groups')
    groups.sort()
    groups = ','.join(groups)
    collectors = d.get('collectors')
    monitoring = d.get('monitoring')
    compliance = d.get('compliance')
    generators = d.get('generators')
    kv_store = d.get('kv')

    ################### Generic
    __print_topic_header(TOPIC_GENERIC)
    # print_info_title('OpsBro Daemon')

    __print_key_val('Name', name, topic=TOPIC_GENERIC)
    display_name_color = 'green' if (name != display_name) else 'grey'
    __print_key_val('Display name',
                    display_name,
                    color=display_name_color,
                    topic=TOPIC_GENERIC)

    __print_key_val('System',
                    '%s (version %s) ' % (system_distro, system_distroversion),
                    color='green',
                    topic=TOPIC_GENERIC,
                    end_line='')
    if is_managed_system:
        cprint(' %s managed' % CHARACTERS.check, color='grey')
    else:
        cprint(' %s this system is not managed' %
               CHARACTERS.double_exclamation,
               color='yellow')
        __print_more(
            ' Not managed means that configuration automation & system compliance will not be available'
        )

    # We will print modules by modules types
    # cprint(' - Modules: '.ljust(DEFAULT_INFO_COL_SIZE), end='', color='blue')
    modules_by_states = {}
    for module_state in MODULE_STATES:
        modules_by_states[module_state] = []
    for (module_name, module) in modules.items():
        modules_by_states[module['state']].append(module)

    strs = []
    for module_state in MODULE_STATES:
        nb = len(modules_by_states[module_state])
        state_color = MODULE_STATE_COLORS.get(module_state, 'grey')
        color = 'grey' if nb == 0 else state_color
        _s = sprintf('%d %s ' % (nb, module_state), color=color, end='')
        strs.append(_s)
    module_string = sprintf(' / ', color='grey', end='').join(strs)

    __print_key_val('Modules', module_string, topic=TOPIC_GENERIC)

    __print_topic_picto(TOPIC_GENERIC)
    __print_more('opsbro agent modules state')

    ################### Service Discovery
    cprint('')
    __print_topic_header(TOPIC_SERVICE_DISCOVERY)

    __print_key_val('UUID', _uuid, topic=TOPIC_SERVICE_DISCOVERY)
    __print_key_val('Local addr', local_addr, topic=TOPIC_SERVICE_DISCOVERY)
    __print_key_val('Public addr', public_addr, topic=TOPIC_SERVICE_DISCOVERY)

    __print_key_val('UDP port', port, topic=TOPIC_SERVICE_DISCOVERY)

    # Normal agent information
    ext_server = httpservers.get('external')
    int_server = httpservers.get('internal')
    ext_threads = '%d/%d' % (ext_server['nb_threads'] -
                             ext_server['idle_threads'],
                             ext_server['nb_threads'])
    if int_server:
        int_threads = '%d/%d' % (int_server['nb_threads'] -
                                 int_server['idle_threads'],
                                 int_server['nb_threads'])
    else:  # windows case
        int_threads = '(not available on windows)'

    __print_key_val('HTTP threads',
                    'LAN:%s                        Private socket:%s' %
                    (ext_threads, int_threads),
                    topic=TOPIC_SERVICE_DISCOVERY)
    __print_topic_picto(TOPIC_SERVICE_DISCOVERY)
    __print_note(
        '          Listen on the TCP port %s     Listen on the unix socket %s'
        % (port, socket_path))

    __print_key_val('Zone',
                    zone,
                    color=zone_color,
                    topic=TOPIC_SERVICE_DISCOVERY,
                    end_line=False)
    cprint(' (%s)' % is_zone_protected_display[0],
           color=is_zone_protected_display[1])
    __print_topic_picto(TOPIC_SERVICE_DISCOVERY)
    __print_more('opsbro gossip members')

    ################################## Automatic Detection
    cprint('')
    __print_topic_header(TOPIC_AUTOMATIC_DECTECTION)
    __print_key_val('Groups', groups, topic=TOPIC_AUTOMATIC_DECTECTION)

    __print_topic_picto(TOPIC_AUTOMATIC_DECTECTION)
    __print_more('opsbro detectors state')

    # Show hosting drivers, and why we did chose this one
    main_driver_founded = False
    strs = []
    for driver_entry in hosting_drivers_state:
        driver_name = driver_entry['name']
        driver_is_active = driver_entry['is_active']
        _name = driver_name
        if not main_driver_founded and driver_is_active:
            strs.append(
                sprintf('[', color='magenta') + sprintf(_name, color='green') +
                sprintf(']', color='magenta'))
            main_driver_founded = True
        elif driver_is_active:
            strs.append(sprintf(_name, color='green'))
        else:
            strs.append(sprintf(_name, color='grey'))

    _hosting_drivers_state_string = sprintf(' %s ' % CHARACTERS.arrow_left,
                                            color='grey').join(strs)
    __print_key_val('Hosting drivers',
                    _hosting_drivers_state_string,
                    topic=TOPIC_AUTOMATIC_DECTECTION)
    __print_topic_picto(TOPIC_AUTOMATIC_DECTECTION)
    __print_note(
        'first founded valid driver is used as main hosting driver (give uuid, public/private ip, %s)'
        % CHARACTERS.three_dots)

    ################################## Monitoring
    cprint('')
    __print_topic_header(TOPIC_MONITORING)

    monitoring_strings = []
    for check_state in CHECK_STATES:
        count = monitoring[check_state]
        color = STATE_COLORS.get(check_state) if count != 0 else 'grey'
        s = ('%d %s' % (count, check_state.upper())).ljust(15)
        s = sprintf(s, color=color, end='')
        monitoring_strings.append(s)
    monitoring_string = sprintf(' / ', color='grey',
                                end='').join(monitoring_strings)
    __print_key_val('Check states', monitoring_string, topic=TOPIC_MONITORING)
    __print_topic_picto(TOPIC_MONITORING)
    __print_more('opsbro monitoring state')

    ################################## Metrology
    # Now collectors part
    cprint('')
    __print_topic_header(TOPIC_METROLOGY)
    cnames = list(collectors.keys())
    cnames.sort()
    collectors_states = {}
    for collector_state in COLLECTORS_STATES:
        collectors_states[collector_state] = []
    for cname in cnames:
        v = collectors[cname]
        collector_state = v['state']
        collectors_states[collector_state].append(cname)

    strs = []
    for collector_state in COLLECTORS_STATES:
        nb = len(collectors_states[collector_state])
        state_color = COLLECTORS_STATE_COLORS.get(collector_state, 'grey')
        color = 'grey' if nb == 0 else state_color
        _s = ('%d %s' % (nb, collector_state)).ljust(15)
        _s = sprintf(_s, color=color, end='')
        strs.append(_s)
    collector_string = sprintf(' / ', color='grey', end='').join(strs)
    __print_key_val('Collectors', collector_string, topic=TOPIC_METROLOGY)
    __print_topic_picto(TOPIC_METROLOGY)
    __print_more('opsbro collectors state')

    ################################## configuration automation
    cprint('')
    __print_topic_header(TOPIC_CONFIGURATION_AUTOMATION)

    strs = []
    for state in GENERATOR_STATES:
        nb = generators[state]
        state_color = GENERATOR_STATE_COLORS.get(state, 'grey')
        color = 'grey' if nb == 0 else state_color
        _s = ('%d %s' % (nb, state)).ljust(15)
        _s = sprintf(_s, color=color, end='')
        strs.append(_s)
    generator_string = sprintf(' / ', color='grey', end='').join(strs)
    __print_key_val('Generators',
                    generator_string,
                    topic=TOPIC_CONFIGURATION_AUTOMATION)
    __print_topic_picto(TOPIC_CONFIGURATION_AUTOMATION)
    __print_more('opsbro generators state')

    ################################## system compliance
    cprint('')
    __print_topic_header(TOPIC_SYSTEM_COMPLIANCE)

    strs = []
    for state in ALL_COMPLIANCE_STATES:
        nb = compliance[state]
        state_color = COMPLIANCE_STATE_COLORS.get(state, 'grey')
        color = 'grey' if nb == 0 else state_color
        _s = ('%d %s' % (nb, state)).ljust(15)
        _s = sprintf(_s, color=color, end='')
        strs.append(_s)
    collector_string = sprintf(' / ', color='grey', end='').join(strs)
    __print_key_val('Compliance rules',
                    collector_string,
                    topic=TOPIC_SYSTEM_COMPLIANCE)
    __print_topic_picto(TOPIC_SYSTEM_COMPLIANCE)
    __print_more('opsbro compliance state')

    ############### Logs:  Show errors logs if any
    cprint('')
    print_info_title('Technical info')

    cprint(' - Job threads: '.ljust(DEFAULT_INFO_COL_SIZE),
           end='',
           color='blue')
    cprint(nb_threads, color='green')

    if memory_consumption != 0:
        mo_memory_consumption = int(memory_consumption / 1024.0 / 1024.0)
        s = '%dMB' % mo_memory_consumption
        __print_key_val('Memory usage', s)

    if cpu_consumption != 0:
        s = '%.1f%%' % cpu_consumption
        __print_key_val('CPU Usage', s)
        __print_more('opsbro agent internal show-threads')

    kv_store_backend = kv_store.get('backend', None)
    if kv_store_backend:
        cprint(' - KV Backend: '.ljust(DEFAULT_INFO_COL_SIZE),
               end='',
               color='blue')
        cprint(kv_store_backend['name'], color='green')
        cprint('    - size: '.ljust(DEFAULT_INFO_COL_SIZE),
               end='',
               color='blue')
        cprint('%.2fMB' % (kv_store['stats']['size'] / 1024.0 / 1024.0),
               color='green')

        if kv_store_backend['name'] != 'leveldb':
            __print_note(
                'You do not have the fastest lib/backend. Please launch the command: opsbro compliance launch "Install tuning libs"'
            )

        kv_store_error = kv_store['stats']['error']
        if kv_store_error != '':
            cprint('    - error: '.ljust(DEFAULT_INFO_COL_SIZE),
                   color='blue',
                   end='')
            cprint(kv_store_error, color='red')

    cprint(' - Version: '.ljust(DEFAULT_INFO_COL_SIZE), end='', color='blue')
    cprint(version, color='green')

    errors = logs.get('ERROR')
    warnings = logs.get('WARNING')

    cprint(' - Logs: '.ljust(DEFAULT_INFO_COL_SIZE), end='', color='blue')
    # Put warning and errors in red/yellow if need only
    error_color = 'red' if len(errors) > 0 else 'grey'
    warning_color = 'yellow' if len(warnings) > 0 else 'grey'
    cprint('%d errors    ' % len(errors), color=error_color, end='')
    cprint('%d warnings   ' % len(warnings), color=warning_color)

    # If there are errors or warnings, help the user to know it can print them
    if not show_logs and (len(errors) > 0 or len(warnings) > 0):
        __print_note(
            'you can show error & warning logs with the --show-logs options')

    if show_logs:
        if len(errors) > 0:
            print_info_title('Error logs')
            for s in errors:
                cprint(s, color='red')

        if len(warnings) > 0:
            print_info_title('Warning logs')
            for s in warnings:
                cprint(s, color='yellow')

    logger.debug('Raw information: %s' % d)
Example #14
0
from opsbro.characters import CHARACTERS

systepacketmgr = get_systepacketmgr()

##################################       Only root as it's a global system tool.
if os.name != 'nt' and os.getuid() != 0:
    cprint('Setup must be launched as root.', color='red')
    sys.exit(2)

# By default logger should not print anything
logger.setLevel('ERROR')
# By maybe we are in verbose more?
if '-v' in sys.argv or os.environ.get('DEBUG_INSTALL', '0') == '1':
    logger.setLevel('DEBUG')

logger.debug('SCRIPT: install/update script was call with arguments: %s' %
             orig_sys_argv)

what = 'Installing' if not is_update else 'Updating'
title = sprintf('%s' % what, color='magenta', end='') + sprintf(
    ' OpsBro to version ', end='') + sprintf(
        '%s' % VERSION, color='magenta', end='')

if allow_black_magic:
    print_h1(title, raw_title=False)

##################################       Start to print to the user
if allow_black_magic:
    # If we have a real tty, we can print the delicious banner with lot of BRO
    if is_tty():
        cprint(BANNER)
    else:  # ok you are poor, just got some ascii art then
Example #15
0
                if sys.platform.startswith('linux'):
                    CLOCK_MONOTONIC = 1
                elif sys.platform.startswith('freebsd'):
                    CLOCK_MONOTONIC = 4
                elif sys.platform.startswith('sunos5'):
                    CLOCK_MONOTONIC = 4
                elif 'bsd' in sys.platform:
                    CLOCK_MONOTONIC = 3
                elif sys.platform.startswith('aix'):
                    CLOCK_MONOTONIC = ctypes.c_longlong(10)

                def monotonic():
                    """Monotonic clock, cannot go backward."""
                    ts = timespec()
                    if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(ts)):
                        errno = ctypes.get_errno()
                        raise OSError(errno, os.strerror(errno))
                    return ts.tv_sec + ts.tv_nsec / 1.0e9

            # Perform a sanity-check.
            if monotonic() - monotonic() > 0:
                raise ValueError('monotonic() is not monotonic!')

        except Exception as exp:
            from opsbro.log import logger

            logger.debug(
                'DEV-WARNING: No suitable implementation of a monotonic clock for this system (%s:%s), using standard time'
                % (type(exp), exp))
            monotonic = time.time