Exemple #1
0
def manage_check_ping_command(elt):
    safe_print('Get check_ping perfdata of', elt.get_full_name())
    p = PerfDatas(elt.perf_data)
    if not 'rta' in p:
        print "No rta in p"
        return None

    m = p['rta']
    v = m.value
    crit = m.critical
    if not v or not crit:
        print "No value, I bailout"
        return None

    # Percent of ok should be the log of time versus max/2
    pct = get_logarithmic(v, crit/2)
    # Now get the color
    # OK : #6f2 (102,255,34) green
    # Warning : #f60 (255,102,0) orange
    # Crit : #ff0033 (255,0,51)
    base_color = {0 : (102,255,34), 1 : (255,102,0), 2 : (255,0,51)}
    state_id = get_stateid(elt)
    color = base_color.get(state_id, (179,196,255))
    s_color = 'RGB(%d,%d,%d)' % color    

    lnk = '#'
    metrics = [(s_color, pct), ('white', 100-pct)]
    title = '%sms' % v
    print "HTTP: return", {'lnk' : lnk, 'metrics' : metrics, 'title' : title}
    return {'lnk' : lnk, 'metrics' : metrics, 'title' : title}
Exemple #2
0
def manage_check_ping_command(elt):
    safe_print('Get check_ping perfdata of', elt.get_full_name())
    p = PerfDatas(elt.perf_data)
    if not 'rta' in p:
        print "No rta in p"
        return None

    m = p['rta']
    v = m.value
    crit = m.critical
    if not v or not crit:
        print "No value, I bailout"
        return None

    # Pourcent of ok should be time/10s
    pct = 100 * (v / crit)
    # go to int
    pct = int(pct)
    # But at least 1%
    pct = max(1, pct)
    #And max to 100%
    pct = min(pct, 100)
    lnk = '#'
    metrics = [('#68f', pct), ('white', 100-pct)]
    title = '%sms' % v
    print "HTTP: return", {'lnk' : lnk, 'metrics' : metrics, 'title' : title}
    return {'lnk' : lnk, 'metrics' : metrics, 'title' : title}
Exemple #3
0
    def is_correct(self):
        # we are ok at the begining. Hope we still ok at the end...
        r = True
        # Some class do not have twins, because they do not have names
        # like servicedependencies
        twins = getattr(self, 'twins', None)
        if twins is not None:
            # Ok, look at no twins (it's bad!)
            for id in twins:
                i = self.items[id]
                safe_print("Error: the", i.__class__.my_type, i.get_name(), "is duplicated from", i.imported_from)
                r = False

        # Then look if we have some errors in the conf
        # Juts print warnings, but raise errors
        for err in self.configuration_warnings:
            print err

        for err in self.configuration_errors:
            print err
            r = False

        # Then look for individual ok
        for i in self:
            if not i.is_correct():
                n = getattr(i, 'imported_from', "unknown")
                safe_print("Error: In", i.get_name(), "is incorrect ; from", n)
                r = False        
        
        return r
Exemple #4
0
    def get_dep_graph_struct(self, elt, levels=3):
        t = elt.__class__.my_type
        # We set the values for webui/plugins/depgraph/htdocs/js/eltdeps.js
        # so a node with important data for rendering
        # type = custom, business_impact and img_src.
        d = {
            "id": elt.get_dbg_name(),
            "name": elt.get_dbg_name(),
            "data": {"$type": "custom", "business_impact": elt.business_impact, "img_src": self.get_icon_state(elt)},
            "adjacencies": [],
        }

        # Set the right info panel
        d["data"][
            "infos"
        ] = r"""%s <h2 class="%s"><img style="width: 64px; height:64px" src="%s"/> %s: %s</h2>
                   <p>since %s</p>
                   <div style="float:right;"> <a href="%s">%s</a></div>""" % (
            '<img src="/static/img/icons/star.png" alt="star">' * (elt.business_impact - 2),
            elt.state.lower(),
            self.get_icon_state(elt),
            elt.state,
            elt.get_full_name(),
            self.print_duration(elt.last_state_change, just_duration=True, x_elts=2),
            self.get_link_dest(elt),
            self.get_button("Go to details", img="/static/images/search.png"),
        )

        d["data"]["elt_type"] = elt.__class__.my_type
        d["data"]["is_problem"] = elt.is_problem
        d["data"]["state_id"] = elt.state_id

        safe_print("ELT:%s is %s" % (elt.get_full_name(), elt.state))
        if elt.state in ["OK", "UP", "PENDING"]:
            d["data"]["circle"] = "none"
        elif elt.state in ["DOWN", "CRITICAL"]:
            d["data"]["circle"] = "red"
        elif elt.state in ["WARNING", "UNREACHABLE"]:
            d["data"]["circle"] = "orange"
        else:
            d["data"]["circle"] = "none"

        # Now put in adj our parents
        for p in elt.parent_dependencies:
            pd = {
                "nodeTo": p.get_dbg_name(),
                "data": {"$type": "line", "$direction": [elt.get_dbg_name(), p.get_dbg_name()]},
            }

            # Naive way of looking at impact
            if elt.state_id != 0 and p.state_id != 0:
                pd["data"]["$color"] = "Tomato"
            # If OK, show host->service as a green link
            elif elt.__class__.my_type != p.__class__.my_type:
                pd["data"]["$color"] = "PaleGreen"
            d["adjacencies"].append(pd)

        # The sons case is now useful, it will be done by our sons
        # that will link us
        return d
Exemple #5
0
def get_page():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        app.bottle.redirect("/user/login")

    all_imp_impacts = app.datamgr.get_important_elements()
    all_imp_impacts.sort(hst_srv_sort)
    #all_imp_impacts.sort(hst_srv_sort)

    #all_imp_impacts = app.datamgr.get_services() #important_elements()

    impacts = []
    for imp in all_imp_impacts:
        safe_print("FIND A BAD SERVICE IN IMPACTS", imp.get_dbg_name())
        d = {'name': imp.get_full_name().encode('utf8', 'ignore'),
             "title": "My Image 3", "thumb": "/static/images/state_flapping.png", "zoom": "/static/images/state_flapping.png",
             "html": get_div(imp)}
        impacts.append(d)

    # Got in json format
    #j_impacts = json.dumps(impacts)
    #print "Return impact in json", j_impacts
    all_pbs = app.datamgr.get_all_problems()
    now = time.time()
    # Get only the last 10min errors
    all_pbs = [pb for pb in all_pbs if pb.last_state_change > now - 600]
    # And sort it
    all_pbs.sort(hst_srv_sort)  # sort_by_last_state_change)

    return {'app': app, 'user': user, 'impacts': impacts, 'problems': all_pbs}
Exemple #6
0
def get_page():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
    

    all_imp_impacts = app.datamgr.get_services()#important_elements()
    #all_imp_impacts.sort(hst_srv_sort)

    impacts = []
    for imp in all_imp_impacts:
        safe_print("FIND A BAD SERVICE IN IMPACTS", imp.get_dbg_name())
        d = {'name' : imp.get_full_name().encode('utf8', 'ignore'),
             "title": "My Image 3", "thumb": "/static/images/state_flapping.png", "zoom": "/static/images/state_flapping.png",
             "html" : get_div(imp)}
        impacts.append(d)
    
    # Got in json format
    #j_impacts = json.dumps(impacts)
#    print "Return impact in json", j_impacts

    return {'app' : app, 'user' : user, 'impacts' : impacts}
Exemple #7
0
def manage_check_ping_command(elt):
    safe_print('Get check_ping perfdata of', elt.get_full_name())
    p = PerfDatas(elt.perf_data)
    if not 'rta' in p:
        print "No rta in p"
        return None

    m = p['rta']
    v = m.value
    crit = m.critical
    if not v or not crit:
        print "No value, I bailout"
        return None

    # Percent of ok should be the log of time versus max/2
    pct = get_logarithmic(v, crit / 2)
    # Now get the color
    # OK: #6f2 (102,255,34) green
    # Warning: #f60 (255,102,0) orange
    # Crit: #ff0033 (255,0,51)
    base_color = {0: (102, 255, 34), 1: (255, 102, 0), 2: (255, 0, 51)}
    state_id = get_stateid(elt)
    color = base_color.get(state_id, (179, 196, 255))
    s_color = 'RGB(%d,%d,%d)' % color

    lnk = '#'
    metrics = [(s_color, pct), ('white', 100-pct)]
    title = '%sms' % v
    print "HTTP: return", {'lnk': lnk, 'metrics': metrics, 'title': title}
    return {'lnk': lnk, 'metrics': metrics, 'title': title}
    def all_done_linking(self, inst_id):
        """In addition to the original all_done_linking our items will get sorted"""
        super(self.__class__, self).all_done_linking(inst_id)

        # now sort the item collections by name
        safe_print("SORTING HOSTS AND SERVICES")
        # First install a new attribute _id_heap, which holds the
        # item ids in sorted order
        setattr(self.services, '_id_heap', [(get_obj_full_name(v), k) for (k, v) in self.services.items.iteritems()])
        self.services._id_heap.sort(key=lambda x: x[0])
        setattr(self.hosts, '_id_heap', [(get_obj_full_name(v), k) for (k, v) in self.hosts.items.iteritems()])
        self.hosts._id_heap.sort(key=lambda x: x[0])
        setattr(self.contacts, '_id_heap', [(get_obj_full_name(v), k) for (k, v) in self.contacts.items.iteritems()])
        self.contacts._id_heap.sort(key=lambda x: x[0])
        setattr(self.servicegroups, '_id_heap', [(get_obj_full_name(v), k) for (k, v) in self.servicegroups.items.iteritems()])
        self.servicegroups._id_heap.sort(key=lambda x: x[0])
        setattr(self.hostgroups, '_id_heap', [(get_obj_full_name(v), k) for (k, v) in self.hostgroups.items.iteritems()])
        self.hostgroups._id_heap.sort(key=lambda x: x[0])
        setattr(self.contactgroups, '_id_heap', [(get_obj_full_name(v), k) for (k, v) in self.contactgroups.items.iteritems()])
        self.contactgroups._id_heap.sort(key=lambda x: x[0])
        # Then install a method for accessing the lists' elements in sorted order
        setattr(self.services, '__itersorted__', types.MethodType(itersorted, self.services))
        setattr(self.hosts, '__itersorted__', types.MethodType(itersorted, self.hosts))
        setattr(self.contacts, '__itersorted__', types.MethodType(itersorted, self.contacts))
        setattr(self.servicegroups, '__itersorted__', types.MethodType(itersorted, self.servicegroups))
        setattr(self.hostgroups, '__itersorted__', types.MethodType(itersorted, self.hostgroups))
        setattr(self.contactgroups, '__itersorted__', types.MethodType(itersorted, self.contactgroups))

        # Everything is new now. We should clean the cache
        self.cache.wipeout()
Exemple #9
0
 def remove_twins(self):
     for id in self.twins:
         i = self.items[id]
         type = i.__class__.my_type
         safe_print('Warning: the', type, i.get_name(), 'is already defined.')
         del self.items[id] # bye bye
     # do not remove twins, we should look in it, but just void it
     self.twins = []
Exemple #10
0
 def get_important_elements(self):
     res = []
     # We want REALLY important things, so business_impact > 2, but not just IT elments that are
     # root problems, so we look only for config defined my_own_business_impact value too
     res.extend([s for s in self.rg.services if (s.business_impact > 2 and not 0 <= s.my_own_business_impact <= 2) ])
     res.extend([h for h in self.rg.hosts if (h.business_impact > 2 and not 0 <= h.my_own_business_impact <= 2)] )
     print "DUMP IMPORTANT"
     for i in res:
         safe_print(i.get_full_name(), i.business_impact, i.my_own_business_impact)
     return res
Exemple #11
0
 def get_important_elements(self):
     res = []
     # We want REALLY important things, so business_impact > 2, but not just IT elements that are
     # root problems, so we look only for config defined my_own_business_impact value too
     res.extend([s for s in self.rg.services if (s.business_impact > 2 and not 0 <= s.my_own_business_impact <= 2)])
     res.extend([h for h in self.rg.hosts if (h.business_impact > 2 and not 0 <= h.my_own_business_impact <= 2)])
     print "DUMP IMPORTANT"
     for i in res:
         safe_print(i.get_full_name(), i.business_impact, i.my_own_business_impact)
     return res
Exemple #12
0
    def get_dep_graph_struct(self, elt, levels=3):
        t = elt.__class__.my_type
        # We set the values for webui/plugins/depgraph/htdocs/js/eltdeps.js
        # so a node with important data for rendering
        # type = custom, business_impact and img_src.
        d = {'id' : elt.get_dbg_name(), 'name' : elt.get_dbg_name(),
             'data' : {'$type' : 'custom',
                       'business_impact' : elt.business_impact,
                       'img_src' : self.get_icon_state(elt),
                       },
             'adjacencies' : []
             }

        # Set the right info panel
        d['data']['infos'] = r'''%s <h2 class="%s"><img style="width : 64px; height:64px" src="%s"/> %s: %s</h2>
		       <p>since %s</p>
		       <div style="float:right;"> <a href="%s">%s</a></div>'''  % (
            '<img src="/static/images/star.png" alt="star">' * (elt.business_impact - 2),
            elt.state.lower(), self.get_icon_state(elt), elt.state, elt.get_full_name(),
            self.print_duration(elt.last_state_change, just_duration=True, x_elts=2),
            self.get_link_dest(elt), self.get_button('Go to details', img='/static/images/search.png'))
                       

        d['data']['elt_type'] = elt.__class__.my_type
        d['data']['is_problem'] = elt.is_problem
        d['data']['state_id'] = elt.state_id

        safe_print("ELT:%s is %s" % (elt.get_full_name(), elt.state))
        if elt.state in ['OK', 'UP', 'PENDING']:
            d['data']['circle'] = 'none'
        elif elt.state in ['DOWN', 'CRITICAL']:
            d['data']['circle'] = 'red'
        elif elt.state in ['WARNING', 'UNREACHABLE']:
            d['data']['circle'] = 'orange'
        else:
            d['data']['circle'] = 'none'
     

        # Now put in adj our parents
        for p in elt.parent_dependencies:
            pd = {'nodeTo' : p.get_dbg_name(),
                  'data' : {"$type":"line", "$direction": [elt.get_dbg_name(), p.get_dbg_name()]}}

            # Naive way of looking at impact
            if elt.state_id != 0 and p.state_id != 0:
                pd['data']["$color"] = 'Tomato'
            # If OK, show host->service as a green link
            elif elt.__class__.my_type != p.__class__.my_type:
                 pd['data']["$color"] = 'PaleGreen'
            d['adjacencies'].append(pd)

        # The sons case is now useful, it will be done by our sons
        # that will link us
        return d
Exemple #13
0
 def run_external_commands(self, commands):
     if self.con is None:
         self.create_connection()
     if not self.alive:
         return None
     safe_print("Send %d commands", len(commands))
     try:
         self.con.run_external_commands(commands)
     except Pyro.errors.URIError , exp:
         self.con = None
         return False
Exemple #14
0
 def unacknowledge_problem(self):
     if self.problem_has_been_acknowledged:
         safe_print("Deleting acknowledged of", self.get_dbg_name())
         self.problem_has_been_acknowledged = False
         # Should not be deleted, a None is Good
         self.acknowledgement = None
         # del self.acknowledgement
         # find comments of non-persistent ack-comments and delete them too
         for c in self.comments:
             if c.entry_type == 4 and not c.persistent:
                 self.del_comment(c.id)
         self.broks.append(self.get_update_status_brok())
Exemple #15
0
    def is_correct(self):
        res = True

        if self.unknown_members != []:
            for m in self.unknown_members:
                safe_print("Error : the", self.__class__.my_type, self.get_name(), "got a unknown member" , m)
            res = False

        if self.configuration_errors != []:
            for err in self.configuration_errors:
                print err
            res = False
            
        return res
Exemple #16
0
 def create_json_dep_graph(self, elt, levels=3):
     t0 = time.time()
     # First we need ALL elements
     all_elts = self.get_all_linked_elts(elt, levels=levels)
     print "We got all our elements"
     dicts = []
     for i in all_elts:
         safe_print("Elt", i.get_dbg_name())
         d = self.get_dep_graph_struct(i)
         dicts.append(d)
     j = json.dumps(dicts)
     safe_print("Create json", j)
     print "create_json_dep_graph::Json creation time", time.time() - t0
     return j
Exemple #17
0
 def create_json_dep_graph(self, elt, levels=3):
     t0 = time.time()
     # First we need ALL elements
     all_elts = self.get_all_linked_elts(elt, levels=levels)
     print "We got all our elements"
     dicts = []
     for i in all_elts:
         safe_print("Elt", i.get_dbg_name())
         d = self.get_dep_graph_struct(i)
         dicts.append(d)
     j = json.dumps(dicts)
     safe_print("Create json", j)
     print "create_json_dep_graph::Json creation time", time.time() - t0
     return j
Exemple #18
0
    def is_correct(self):
        state = True
        properties = self.__class__.properties
        
        # Raised all previously saw errors like unknown contacts and co
        if self.configuration_errors != []:
            state = False
            for err in self.configuration_errors:
                logger.log(err)

        for prop, entry in properties.items():
            if not hasattr(self, prop) and entry.required:
                safe_print(self.get_name(), "missing property :", prop)
                state = False
                
        return state
Exemple #19
0
def manage_unknown_command(elt):
    safe_print('Get an unmanaged command perfdata of', elt.get_full_name())
    p = PerfDatas(elt.perf_data)
    if len(p) == 0:
        return None

    m = None
    # Got some override name we know to be ok for printing
    if 'time' in p:
        m = p['time']
    else:
        for v in p:
            #print "Look for", v
            if v.name is not None and v.value is not None:
                m = v
                break

    prop = m.name
    safe_print("Got a property", prop, "and a value", m)
    v = m.value
    if not v:
        print "No value, I bailout"
        return None

    # Now look if min/max are available or not
    pct = 0
    if m.min and m.max and (m.max - m.min != 0):
        pct = 100 * (v / (m.max - m.min))
    else:  # ok, we will really guess this time...
        # Percent of ok should be time/10s
        pct = 100 * (v / 10)

    # go to int
    pct = int(pct)
    # But at least 1%
    pct = max(1, pct)
    # And max to 100%
    pct = min(pct, 100)
    lnk = '#'

    color = get_linear_color(elt, prop)
    s_color = 'RGB(%d,%d,%d)' % color
    metrics = [(s_color, pct), ('white', 100-pct)]
    uom = '' or m.uom
    title = '%s%s' % (v, uom)
    #print "HTTP: return", {'lnk': lnk, 'metrics': metrics, 'title': title}
    return {'lnk': lnk, 'metrics': metrics, 'title': title}
Exemple #20
0
def manage_unknown_command(elt):
    safe_print('Get an unmanaged command perfdata of', elt.get_full_name())
    p = PerfDatas(elt.perf_data)
    if len(p) == 0:
        return None

    m = None
    # Got some override name we know to be ok for printing
    if 'time' in p:
        m = p['time']
    else:
        for v in p:
            print "Look for", v
            if v.name is not None and v.value is not None:
                m = v
                break

    prop = m.name
    print "Got a property", prop, "and a value", m
    v = m.value
    if not v:
        print "No value, I bailout"
        return None

    # Now look if min/max are available or not
    pct = 0
    if m.min and m.max and (m.max - m.min != 0):
        pct = 100 * (v / (m.max - m.min))
    else:  # ok, we will really guess this time...
        # Percent of ok should be time/10s
        pct = 100 * (v / 10)

    # go to int
    pct = int(pct)
    # But at least 1%
    pct = max(1, pct)
    # And max to 100%
    pct = min(pct, 100)
    lnk = '#'

    color = get_linear_color(elt, prop)
    s_color = 'RGB(%d,%d,%d)' % color
    metrics = [(s_color, pct), ('white', 100-pct)]
    uom = '' or m.uom
    title = '%s%s' % (v, uom)
    print "HTTP: return", {'lnk': lnk, 'metrics': metrics, 'title': title}
    return {'lnk': lnk, 'metrics': metrics, 'title': title}
Exemple #21
0
    def print_business_tree(self, tree, level=0):
        safe_print("Should print tree", tree)
        node = tree["node"]
        name = node.get_full_name()
        fathers = tree["fathers"]
        fathers = sorted(fathers, key=lambda dict: dict["node"].get_full_name())
        s = ""
        # Do not print the node if it's the root one, we already know its state!
        if level != 0:
            s += "%s is %s since %s\n" % (
                self.get_link(node),
                node.state,
                self.print_duration(node.last_state_change, just_duration=True),
            )

        # If we got no parents, no need to print the expand icon
        if len(fathers) > 0:
            # We look if the below tree is goodor not
            tree_is_good = node.state_id == 0

            # If the tree is good, we will use an expand image
            # and hide the tree
            if tree_is_good:
                display = "none"
                img = "expand.png"
            else:  # we will already show the tree, and use a reduce image
                display = "block"
                img = "reduce.png"

            # If we are the root, we already got this
            if level != 0:
                s += (
                    """<a id="togglelink-%s" href="javascript:toggleBusinessElt('%s')"><img id="business-parents-img-%s" src="/static/images/%s" alt="toggle"> </a> \n"""
                    % (name, name, name, img)
                )

            s += """<ul id="business-parents-%s" class="treeview" style="display: %s; ">""" % (name, display)

            for n in fathers:
                sub_node = n["node"]
                sub_s = self.print_business_rules(n, level=level + 1)
                s += '<li class="%s">%s</li>' % (self.get_small_icon_state(sub_node), sub_s)
            s += "</ul>"
        safe_print("Returning s:", s)
        return s
Exemple #22
0
    def get_all_linked_elts(self, elt, levels=3):
        if levels == 0:
            return set()

        my = set()
        for i in elt.child_dependencies:
            my.add(i)
            child_elts = self.get_all_linked_elts(i, levels=levels - 1)
            for c in child_elts:
                my.add(c)
        for i in elt.parent_dependencies:
            my.add(i)
            par_elts = self.get_all_linked_elts(i, levels=levels - 1)
            for c in par_elts:
                my.add(c)

        safe_print("get_all_linked_elts::Give elements", my)
        return my
Exemple #23
0
    def get_all_linked_elts(self, elt, levels=3):
        if levels == 0:
            return set()

        my = set()
        for i in elt.child_dependencies:
            my.add(i)
            child_elts = self.get_all_linked_elts(i, levels=levels - 1)
            for c in child_elts:
                my.add(c)
        for i in elt.parent_dependencies:
            my.add(i)
            par_elts = self.get_all_linked_elts(i, levels=levels - 1)
            for c in par_elts:
                my.add(c)

        safe_print("get_all_linked_elts::Give elements", my)
        return my
Exemple #24
0
    def print_business_tree(self, tree, level=0):
        safe_print("Should print tree", tree)
        node = tree['node']
        name = node.get_full_name()
        fathers = tree['fathers']
        s = ''
        # Do not print the node if it's the root one, we already know its state!
        if level != 0:
            s += "%s is %s since %s\n" % (self.get_link(node), node.state,
                                          self.print_duration(
                                              node.last_state_change,
                                              just_duration=True))

        # If we got no parents, no need to print the expand icon
        if len(fathers) > 0:
            # We look if the below tree is goodor not
            tree_is_good = (node.state_id == 0)

            # If the tree is good, we will use an expand image
            # and hide the tree
            if tree_is_good:
                display = 'none'
                img = 'expand.png'
            else:  # we will already show the tree, and use a reduce image
                display = 'block'
                img = 'reduce.png'

            # If we are the root, we already got this
            if level != 0:
                s += """<a id="togglelink-%s" href="javascript:toggleBusinessElt('%s')"><img id="business-parents-img-%s" src="/static/images/%s" alt="toggle"> </a> \n""" % (
                    name, name, name, img)

            s += """<ul id="business-parents-%s" class="treeview" style="display: %s; ">""" % (
                name, display)

            for n in fathers:
                sub_node = n['node']
                sub_s = self.print_business_rules(n, level=level + 1)
                s += '<li class="%s">%s</li>' % (
                    self.get_small_icon_state(sub_node), sub_s)
            s += "</ul>"
        safe_print("Returing s:", s)
        return s
Exemple #25
0
def get_perfometer_table_values(elt):
    # first try to get the command name called
    cmd = elt.check_command.call.split('!')[0]
    safe_print("Looking for perfometer value for command", cmd)

    tab = {'check_http': manage_check_http_command,
           'check_ping': manage_check_ping_command,
           'check_tcp': manage_check_tcp_command,
           'check_ftp': manage_check_tcp_command,
        }

    f = tab.get(cmd, None)
    if f:
        return f(elt)

    try:
        r = manage_unknown_command(elt)
    except:
        return None
    return r
Exemple #26
0
def get_perfometer_table_values(elt):
    # first try to get the command name called
    cmd = elt.check_command.call.split('!')[0]
    safe_print("Looking for perfometer value for command", cmd)

    tab = {
        'check_http': manage_check_http_command,
        'check_ping': manage_check_ping_command,
        'check_tcp': manage_check_tcp_command,
        'check_ftp': manage_check_tcp_command,
    }

    f = tab.get(cmd, None)
    if f:
        return f(elt)

    try:
        r = manage_unknown_command(elt)
    except:
        return None
    return r
Exemple #27
0
def show_impacts():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
#        return {'app' : app, 'impacts' : {}, 'valid_user' : False, 'user' : user}

    
    all_imp_impacts = app.datamgr.get_important_elements()
    all_imp_impacts.sort(hst_srv_sort)

    impacts = {}

    imp_id = 0
    for imp in all_imp_impacts:
        safe_print("FIND A BAD SERVICE IN IMPACTS", imp.get_dbg_name())
        imp_id += 1
        impacts[imp_id] = imp

    return {'app' : app, 'impacts' : impacts, 'valid_user' : True, 'user' : user}
    def manage_initial_contact_status_brok(self, b):
        """overwrite it, because the original method deletes some values"""
        data = b.data
        cname = data['contact_name']
        safe_print("Contact with data", data)
        c = self.contacts.find_by_name(cname)
        if c:
            self.update_element(c, data)
        else:
            safe_print("Creating Contact:", cname)
            c = Contact({})
            self.update_element(c, data)
            self.contacts[c.id] = c

        # Now manage notification ways too
        # Same than for contacts. We create or
        # update
        nws = c.notificationways
        safe_print("Got notif ways", nws)
        new_notifways = []
        for cnw in nws:
            nwname = cnw.notificationway_name
            nw = self.notificationways.find_by_name(nwname)
            if not nw:
                safe_print("Creating notif way", nwname)
                nw = NotificationWay([])
                self.notificationways[nw.id] = nw
            # Now update it
            for prop in NotificationWay.properties:
                if hasattr(cnw, prop):
                    setattr(nw, prop, getattr(cnw, prop))
            new_notifways.append(nw)

            # Linking the notification way
            # With commands
            self.linkify_commands(nw, 'host_notification_commands')
            self.linkify_commands(nw, 'service_notification_commands')


            # Now link timeperiods
            self.linkify_a_timeperiod(nw, 'host_notification_period')
            self.linkify_a_timeperiod(nw, 'service_notification_period')

        c.notificationways = new_notifways

        # Ok, declare this contact now :)
        # And notif ways too
        self.contacts.create_reversed_list()
        self.notificationways.create_reversed_list()
Exemple #29
0
def manage_check_tcp_command(elt):
    safe_print('Get check_tcp perfdata of', elt.get_full_name())
    p = PerfDatas(elt.perf_data)
    if not 'time' in p:
        print "No time in p"
        return None

    m = p['time']
    v = m.value

    if not v or not m.max:
        print "No value, I bailout"
        return None

    # Percent of ok should be the log of time versus m.max / 2
    pct = get_logarithmic(v, m.max/2)

    # Now get the color
    # OK : #6f2 (102,255,34) green
    # Warning : #f60 (255,102,0) orange
    # Crit : #ff0033 (255,0,51)
    base_color = {0 : (102,255,34), 1 : (255,102,0), 2 : (255,0,51)}
    state_id = get_stateid(elt)
    color = base_color.get(state_id, (179,196,255))
    s_color = 'RGB(%d,%d,%d)' % color    

    #pct = 100 * (v / m.max)
    # go to int
    #pct = int(pct)
    # But at least 1%
    #pct = max(1, pct)
    #And max to 100%
    #pct = min(pct, 100)
    lnk = '#'
    metrics = [(s_color, pct), ('white', 100-pct)]
    title = '%ss' % v
    print "HTTP: return", {'lnk' : lnk, 'metrics' : metrics, 'title' : title}
    return {'lnk' : lnk, 'metrics' : metrics, 'title' : title}
Exemple #30
0
    def manage_initial_contact_status_brok(self, b):
        """overwrite it, because the original method deletes some values"""
        data = b.data
        cname = data['contact_name']
        safe_print("Contact with data", data)
        c = self.contacts.find_by_name(cname)
        if c:
            self.update_element(c, data)
        else:
            safe_print("Creating Contact:", cname)
            c = Contact({})
            self.update_element(c, data)
            self.contacts[c.id] = c

        # Now manage notification ways too
        # Same than for contacts. We create or
        # update
        nws = c.notificationways
        safe_print("Got notif ways", nws)
        new_notifways = []
        for cnw in nws:
            nwname = cnw.notificationway_name
            nw = self.notificationways.find_by_name(nwname)
            if not nw:
                safe_print("Creating notif way", nwname)
                nw = NotificationWay([])
                self.notificationways[nw.id] = nw
            # Now update it
            for prop in NotificationWay.properties:
                if hasattr(cnw, prop):
                    setattr(nw, prop, getattr(cnw, prop))
            new_notifways.append(nw)

            # Linking the notification way
            # With commands
            self.linkify_commands(nw, 'host_notification_commands')
            self.linkify_commands(nw, 'service_notification_commands')

            # Now link timeperiods
            self.linkify_a_timeperiod(nw, 'host_notification_period')
            self.linkify_a_timeperiod(nw, 'service_notification_period')

        c.notificationways = new_notifways

        # Ok, declare this contact now :)
        # And notif ways too
        self.contacts.create_reversed_list()
        self.notificationways.create_reversed_list()
Exemple #31
0
def manage_check_tcp_command(elt):
    safe_print('Get check_tcp perfdata of', elt.get_full_name())
    p = PerfDatas(elt.perf_data)
    if not 'time' in p:
        print "No time in p"
        return None

    m = p['time']
    v = m.value

    if not v or not m.max:
        print "No value, I bailout"
        return None

    # Percent of ok should be the log of time versus m.max / 2
    pct = get_logarithmic(v, m.max / 2)

    # Now get the color
    # OK: #6f2 (102,255,34) green
    # Warning: #f60 (255,102,0) orange
    # Crit: #ff0033 (255,0,51)
    base_color = {0: (102, 255, 34), 1: (255, 102, 0), 2: (255, 0, 51)}
    state_id = get_stateid(elt)
    color = base_color.get(state_id, (179, 196, 255))
    s_color = 'RGB(%d,%d,%d)' % color

    #pct = 100 * (v / m.max)
    # Convert to int
    #pct = int(pct)
    # Minimum 1%, maximum 100%
    #pct = min(max(1, pct), 100)
    lnk = '#'
    metrics = [(s_color, pct), ('white', 100-pct)]
    title = '%ss' % v
    print "HTTP: return", {'lnk': lnk, 'metrics': metrics, 'title': title}
    return {'lnk': lnk, 'metrics': metrics, 'title': title}
Exemple #32
0
    def print_business_rules(self, tree, level=0, source_problems=[]):
        safe_print("Should print tree", tree)
        safe_print("with source_problems", source_problems)
        node = tree["node"]
        name = node.get_full_name()
        fathers = tree["fathers"]
        s = ""

        # Maybe we are the root problem of this, and so we are printing it
        root_str = ""
        if node in source_problems:
            print "I am a root problem"
            root_str = ' <span class="alert-small alert-critical"> Root problem</span>'
        # Do not print the node if it's the root one, we already know its state!
        if level != 0:
            s += "%s is %s since %s %s\n" % (
                self.get_link(node),
                node.state,
                self.print_duration(node.last_state_change, just_duration=True),
                root_str,
            )

        # If we got no parents, no need to print the expand icon
        if len(fathers) > 0:
            # We look if the below tree is goodor not
            tree_is_good = node.state_id == 0

            # If the tree is good, we will use an expand image
            # and hide the tree
            if tree_is_good:
                display = "none"
                img = "expand.png"
            else:  # we will already show the tree, and use a reduce image
                display = "block"
                img = "reduce.png"

            # If we are the root, we already got this
            if level != 0:
                s += (
                    """<a id="togglelink-%s" href="javascript:toggleBusinessElt('%s')"><img id="business-parents-img-%s" src="/static/images/%s" alt="toggle"> </a> \n"""
                    % (name, name, name, img)
                )

            s += """<ul id="business-parents-%s" style="display: %s; ">""" % (name, display)

            for n in fathers:
                sub_node = n["node"]
                sub_s = self.print_business_rules(n, level=level + 1, source_problems=source_problems)
                s += '<li class="%s">%s</li>' % (self.get_small_icon_state(sub_node), sub_s)
            s += "</ul>"
        safe_print("Returing s:", s)
        return s
Exemple #33
0
    def print_business_rules_mobile(self, tree, level=0, source_problems=[]):
        safe_print("Should print tree", tree)
        safe_print('with source_problems', source_problems)
        node = tree['node']
        name = node.get_full_name()
        fathers = tree['fathers']
        s = ''
        # Maybe we are the root problem of this, and so we are printing it
        root_str = ''
        if node in source_problems:
            print "I am a root problem"
            root_str = ' <span class="alert-small alert-critical"> Root problem</span>'
        # Do not print the node if it's the root one, we already know its state!
        if level != 0:
            s += "%s is %s since %s %s\n" % (
                self.get_link_mobile(node), node.state,
                self.print_duration(node.last_state_change,
                                    just_duration=True), root_str)

        # If we got no parents, no need to print the expand icon
        if len(fathers) > 0:
            # We look if the below tree is goodor not
            tree_is_good = (node.state_id == 0)

            # If the tree is good, we will use an expand image
            # and hide the tree
            if tree_is_good:
                display = 'none'
                img = 'expand.png'
            else:  # we will already show the tree, and use a reduce image
                display = 'block'
                img = 'reduce.png'

            s += """<ul id="business-parents-%s" style="display: %s; ">""" % (
                name, display)

            for n in fathers:
                sub_node = n['node']
                sub_s = self.print_business_rules_mobile(
                    n, level=level + 1, source_problems=source_problems)
                s += '<li class="%s">%s</li>' % (
                    self.get_small_icon_state(sub_node), sub_s)
            s += "</ul>"
        safe_print("Returing s:", s)
        return s
Exemple #34
0
    def print_business_rules_mobile(self, tree, level=0, source_problems=[]):
        safe_print("Should print tree", tree)
        safe_print('with source_problems', source_problems)
        node = tree['node']
        name = node.get_full_name()
        fathers = tree['fathers']
        s = ''
        # Maybe we are the root problem of this, and so we are printing it
        root_str = ''
        if node in source_problems:
            print "I am a root problem"
            root_str = ' <span class="alert-small alert-critical"> Root problem</span>'
        # Do not print the node if it's the root one, we already know its state!
        if level != 0:
            s += "%s is %s since %s %s\n" % (self.get_link_mobile(node), node.state, self.print_duration(node.last_state_change, just_duration=True), root_str)

        # If we got no parents, no need to print the expand icon
        if len(fathers) > 0:
            # We look if the below tree is goodor not
            tree_is_good = (node.state_id == 0)

            # If the tree is good, we will use an expand image
            # and hide the tree
            if tree_is_good:
                display = 'none'
                img = 'expand.png'
            else:  # we will already show the tree, and use a reduce image
                display = 'block'
                img = 'reduce.png'

            s += """<ul id="business-parents-%s" style="display: %s; ">""" % (name, display)

            for n in fathers:
                sub_node = n['node']
                sub_s = self.print_business_rules_mobile(n, level=level+1, source_problems=source_problems)
                s += '<li class="%s">%s</li>' % (self.get_small_icon_state(sub_node), sub_s)
            s += "</ul>"
        safe_print("Returning s:", s)
        return s
Exemple #35
0
    def all_done_linking(self, inst_id):
        """In addition to the original all_done_linking our items will get sorted"""

        # We will relink all objects if need. If we are in a scheduler, this function will just bailout
        # because it's not need :)
        super(LiveStatusRegenerator, self).all_done_linking(inst_id)

        # now sort the item collections by name
        safe_print("SORTING HOSTS AND SERVICES")
        # First install a new attribute _id_heap, which holds the
        # item ids in sorted order
        setattr(self.services, '_id_heap', self.services.items.keys())
        self.services._id_heap.sort(
            key=lambda x: get_obj_full_name(self.services.items[x])
        )
        setattr(self.hosts, '_id_heap', self.hosts.items.keys())
        self.hosts._id_heap.sort(
            key=lambda x: get_obj_full_name(self.hosts.items[x])
        )
        setattr(self.contacts, '_id_heap', self.contacts.items.keys())
        self.contacts._id_heap.sort(
            key=lambda x: get_obj_full_name(self.contacts.items[x])
        )
        setattr(self.servicegroups, '_id_heap', self.servicegroups.items.keys())
        self.servicegroups._id_heap.sort(
            key=lambda x: get_obj_full_name(self.servicegroups.items[x])
        )
        setattr(self.hostgroups, '_id_heap', self.hostgroups.items.keys())
        self.hostgroups._id_heap.sort(
            key=lambda x: get_obj_full_name(self.hostgroups.items[x])
        )
        setattr(self.contactgroups, '_id_heap', self.contactgroups.items.keys())
        self.contactgroups._id_heap.sort(
            key=lambda x: get_obj_full_name(self.contactgroups.items[x])
        )
        setattr(self.commands, '_id_heap', self.commands.items.keys())
        self.commands._id_heap.sort(
            key=lambda x: get_obj_full_name(self.commands.items[x])
        )
        setattr(self.timeperiods, '_id_heap', self.timeperiods.items.keys())
        self.timeperiods._id_heap.sort(
            key=lambda x: get_obj_full_name(self.timeperiods.items[x])
        )
        # Then install a method for accessing the lists' elements in sorted order
        setattr(self.services, '__itersorted__',
                types.MethodType(itersorted, self.services))
        setattr(self.hosts, '__itersorted__',
                types.MethodType(itersorted, self.hosts))
        setattr(self.contacts, '__itersorted__',
                types.MethodType(itersorted, self.contacts))
        setattr(self.servicegroups, '__itersorted__',
                types.MethodType(itersorted, self.servicegroups))
        setattr(self.hostgroups, '__itersorted__',
                types.MethodType(itersorted, self.hostgroups))
        setattr(self.contactgroups, '__itersorted__',
                types.MethodType(itersorted, self.contactgroups))
        setattr(self.commands, '__itersorted__',
                types.MethodType(itersorted, self.commands))
        setattr(self.timeperiods, '__itersorted__',
                types.MethodType(itersorted, self.timeperiods))

        # Speedup authUser requests by populating _id_contact_heap with contact-names as key and
        # an array with the associated host and service ids
        setattr(self.hosts, '_id_contact_heap', dict())
        setattr(self.services, '_id_contact_heap', dict())
        setattr(self.hostgroups, '_id_contact_heap', dict())
        setattr(self.servicegroups, '_id_contact_heap', dict())

        [
            self.hosts._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k)
            for (k, v) in self.hosts.items.iteritems()
            for c in v.contacts
        ]
        for c in self.hosts._id_contact_heap.keys():
            self.hosts._id_contact_heap[c].sort(
                key=lambda x: get_obj_full_name(self.hosts.items[x])
            )

        # strict: one must be an explicitly contact of a service in order to see it.
        if self.service_authorization_strict:
            [
                self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k)
                for (k, v) in self.services.items.iteritems()
                for c in v.contacts
            ]
        else:
            # 1. every host contact automatically becomes a service contact
            [
                self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k)
                for (k, v) in self.services.items.iteritems()
                for c in v.host.contacts
            ]
            # 2. explicit service contacts
            [
                self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k)
                for (k, v) in self.services.items.iteritems()
                for c in v.contacts
            ]
        # services without contacts inherit the host's contacts (no matter of strict or loose)
        [
            self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k)
            for (k, v) in self.services.items.iteritems() if not v.contacts
            for c in v.host.contacts
        ]
        for c in self.services._id_contact_heap.keys():
            # remove duplicates
            self.services._id_contact_heap[c] = list(set(self.services._id_contact_heap[c]))
            self.services._id_contact_heap[c].sort(
                key=lambda x: get_obj_full_name(self.services.items[x])
            )

        if self.group_authorization_strict:
            for c in self.hosts._id_contact_heap.keys():
                # only host contacts can be hostgroup-contacts at all
                # now, which hosts does the contact know?
                contact_host_ids = set([h for h in self.hosts._id_contact_heap[c]])
                for (k, v) in self.hostgroups.items.iteritems():
                    # now look if c is contact of all v.members
                    # we already know the hosts for which c is a contact
                    # self.hosts._id_contact_heap[c] is [(hostname, id), (hostname, id)
                    hostgroup_host_ids = set([h.id for h in v.members])
                    # if all of the hostgroup_host_ids are in contact_host_ids
                    # then the hostgroup belongs to the contact
                    if hostgroup_host_ids <= contact_host_ids:
                        self.hostgroups._id_contact_heap.setdefault(c, []).append(v.id)
            for c in self.services._id_contact_heap.keys():
                # only service contacts can be servicegroup-contacts at all
                # now, which service does the contact know?
                contact_service_ids = set([h for h in self.services._id_contact_heap[c]])
                for (k, v) in self.servicegroups.items.iteritems():
                    # now look if c is contact of all v.members
                    # we already know the services for which c is a contact
                    # self.services._id_contact_heap[c] is [(svcdesc, id), (svcdesc, id)
                    servicegroup_service_ids = set([h.id for h in v.members])
                    # if all of the servicegroup_service_ids are in contact_service_ids
                    # then the servicegroup belongs to the contact
                    # print "%-10s %-15s %s <= %s" % (c, v.get_name(), servicegroup_service_ids, contact_service_ids)
                    if servicegroup_service_ids <= contact_service_ids:
                        self.servicegroups._id_contact_heap.setdefault(c, []).append(v.id)
        else:
            # loose: a contact of a member becomes contact of the whole group
            [
                self.hostgroups._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k)
                for (k, v) in self.hostgroups.items.iteritems()
                for h in v.members
                for c in h.contacts
            ]
            [
                self.servicegroups._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k)
                for (k, v) in self.servicegroups.items.iteritems()
                for s in v.members
                for c in s.contacts
            ] # todo: look at mk-livestatus. what about service's host contacts?
        for c in self.hostgroups._id_contact_heap.keys():
            # remove duplicates
            self.hostgroups._id_contact_heap[c] = list(set(self.hostgroups._id_contact_heap[c]))
            self.hostgroups._id_contact_heap[c].sort(
                key=lambda x: get_obj_full_name(self.hostgroups.items[x])
            )
        for c in self.servicegroups._id_contact_heap.keys():
            # remove duplicates
            self.servicegroups._id_contact_heap[c] = list(set(self.servicegroups._id_contact_heap[c]))
            self.servicegroups._id_contact_heap[c].sort(
                key=lambda x: get_obj_full_name(self.servicegroups.items[x])
            )

        # Add another helper structure which allows direct lookup by name
        # For hosts: _id_by_host_name_heap = {'name1':id1, 'name2': id2,...}
        # For services: _id_by_host_name_heap = {'name1':[id1, id2,...], 'name2': [id6, id7,...],...} = hostname maps to list of service_ids
        # For services: _id_by_service_name_heap = {'name1':id1, 'name2': id6,...} = full_service_description maps to service_id
        setattr(self.hosts, '_id_by_host_name_heap', dict([(get_obj_full_name(v), k) for (k, v) in self.hosts.items.iteritems()]))
        setattr(self.services, '_id_by_service_name_heap', dict([(get_obj_full_name(v), k) for (k, v) in self.services.items.iteritems()]))
        setattr(self.services, '_id_by_host_name_heap', dict())
        [
            self.services._id_by_host_name_heap.setdefault(get_obj_full_name(v.host), []).append(k)
            for (k, v) in self.services.items.iteritems()
        ]
        logger.debug("[Livestatus Regenerator] Id by Hostname heap: %s" % str(self.services._id_by_host_name_heap))
        for hn in self.services._id_by_host_name_heap.keys():
            self.services._id_by_host_name_heap[hn].sort(
                key=lambda x: get_obj_full_name(self.services[x])
            )

        # Add another helper structure which allows direct lookup by name
        # For hostgroups: _id_by_hostgroup_name_heap = {'name1':id1, 'name2': id2,...}
        # For servicegroups: _id_by_servicegroup_name_heap = {'name1':id1, 'name2': id2,...}
        setattr(self.hostgroups, '_id_by_hostgroup_name_heap',
                dict([
                    (get_obj_full_name(v), k) for (k, v) in self.hostgroups.items.iteritems()
                ]))
        setattr(self.servicegroups, '_id_by_servicegroup_name_heap',
                dict([
                    (get_obj_full_name(v), k) for (k, v) in self.servicegroups.items.iteritems()
                ]))

        # For hosts: key is a hostgroup_name, value is an array with all host_ids of the hosts in this group
        setattr(self.hosts, '_id_by_hostgroup_name_heap', dict())
        [
            self.hosts._id_by_hostgroup_name_heap.setdefault(get_obj_full_name(hg), []).append(k)
            for (k, v) in self.hosts.items.iteritems()
            for hg in v.hostgroups
        ]
        for hg in self.hosts._id_by_hostgroup_name_heap.keys():
            self.hosts._id_by_hostgroup_name_heap[hg].sort(
                key=lambda x: get_obj_full_name(self.hosts.items[x])
            )
        # For services: key is a servicegroup_name, value is an array with all service_ids of the services in this group
        setattr(self.services, '_id_by_servicegroup_name_heap', dict())
        [
            self.services._id_by_servicegroup_name_heap.setdefault(get_obj_full_name(sg), []).append(k)
            for (k, v) in self.services.items.iteritems()
            for sg in v.servicegroups
        ]
        for sg in self.services._id_by_servicegroup_name_heap.keys():
            self.services._id_by_servicegroup_name_heap[sg].sort(
                key=lambda x: get_obj_full_name(self.services[x])
            )
        # For services: key is a hostgroup_name, value is an array with all service_ids of the hosts in this group
        setattr(self.services, '_id_by_hostgroup_name_heap', dict())
        [
            self.services._id_by_hostgroup_name_heap.setdefault(get_obj_full_name(hg), []).append(k)
            for (k, v) in self.services.items.iteritems()
            for hg in v.host.hostgroups
        ]
        for hg in self.services._id_by_hostgroup_name_heap.keys():
            self.services._id_by_hostgroup_name_heap[hg].sort(
                key=lambda x: get_obj_full_name(self.services[x])
            )

        # print self.services._id_by_host_name_heap
        for hn in self.services._id_by_host_name_heap.keys():
            self.services._id_by_host_name_heap[hn].sort(
                key=lambda x: get_obj_full_name(self.services[x])
            )

        # Everything is new now. We should clean the cache
        self.cache.wipeout()
        if self.transparent_update:
            self.clear_previous_state()
        self.initialized = True
    def all_done_linking(self, inst_id):
        """In addition to the original all_done_linking our items will get sorted"""

        # We will relink all objects if need. If we are in a scheduler, this function will just bailout
        # because it's not need :)
        super(self.__class__, self).all_done_linking(inst_id)

        # now sort the item collections by name
        safe_print("SORTING HOSTS AND SERVICES")
        # First install a new attribute _id_heap, which holds the
        # item ids in sorted order
        setattr(self.services, '_id_heap', self.services.items.keys())
        self.services._id_heap.sort(key=lambda x: get_obj_full_name(self.services.items[x]))
        setattr(self.hosts, '_id_heap', self.hosts.items.keys())
        self.hosts._id_heap.sort(key=lambda x: get_obj_full_name(self.hosts.items[x]))
        setattr(self.contacts, '_id_heap', self.contacts.items.keys())
        self.contacts._id_heap.sort(key=lambda x: get_obj_full_name(self.contacts.items[x]))
        setattr(self.servicegroups, '_id_heap', self.servicegroups.items.keys())
        self.servicegroups._id_heap.sort(key=lambda x: get_obj_full_name(self.servicegroups.items[x]))
        setattr(self.hostgroups, '_id_heap', self.hostgroups.items.keys())
        self.hostgroups._id_heap.sort(key=lambda x: get_obj_full_name(self.hostgroups.items[x]))
        setattr(self.contactgroups, '_id_heap', self.contactgroups.items.keys())
        self.contactgroups._id_heap.sort(key=lambda x: get_obj_full_name(self.contactgroups.items[x]))
        setattr(self.commands, '_id_heap', self.commands.items.keys())
        self.commands._id_heap.sort(key=lambda x: get_obj_full_name(self.commands.items[x]))
        setattr(self.timeperiods, '_id_heap', self.timeperiods.items.keys())
        self.timeperiods._id_heap.sort(key=lambda x: get_obj_full_name(self.timeperiods.items[x]))
        # Then install a method for accessing the lists' elements in sorted order
        setattr(self.services, '__itersorted__', types.MethodType(itersorted, self.services))
        setattr(self.hosts, '__itersorted__', types.MethodType(itersorted, self.hosts))
        setattr(self.contacts, '__itersorted__', types.MethodType(itersorted, self.contacts))
        setattr(self.servicegroups, '__itersorted__', types.MethodType(itersorted, self.servicegroups))
        setattr(self.hostgroups, '__itersorted__', types.MethodType(itersorted, self.hostgroups))
        setattr(self.contactgroups, '__itersorted__', types.MethodType(itersorted, self.contactgroups))
        setattr(self.commands, '__itersorted__', types.MethodType(itersorted, self.commands))
        setattr(self.timeperiods, '__itersorted__', types.MethodType(itersorted, self.timeperiods))

        # Speedup authUser requests by populating _id_contact_heap with contact-names as key and
        # an array with the associated host and service ids
        setattr(self.hosts, '_id_contact_heap', dict())
        setattr(self.services, '_id_contact_heap', dict())
        setattr(self.hostgroups, '_id_contact_heap', dict())
        setattr(self.servicegroups, '_id_contact_heap', dict())

        [self.hosts._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k) for (k, v) in self.hosts.items.iteritems() for c in v.contacts]
        for c in self.hosts._id_contact_heap.keys():
            self.hosts._id_contact_heap[c].sort(key=lambda x: get_obj_full_name(self.hosts.items[x]))

        # strict: one must be an explicity contact of a service in order to see it.
        if self.service_authorization_strict:
            [self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k) for (k, v) in self.services.items.iteritems() for c in v.contacts]
        else:
            # 1. every host contact automatically becomes a service contact
            [self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k) for (k, v) in self.services.items.iteritems() for c in v.host.contacts]
            # 2. explicit service contacts
            [self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k) for (k, v) in self.services.items.iteritems() for c in v.contacts]
        # services without contacts inherit the host's contacts (no matter of strict or loose)
        [self.services._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k) for (k, v) in self.services.items.iteritems() if not v.contacts for c in v.host.contacts]
        for c in self.services._id_contact_heap.keys():
            # remove duplicates
            self.services._id_contact_heap[c] = list(set(self.services._id_contact_heap[c]))
            self.services._id_contact_heap[c].sort(key=lambda x: get_obj_full_name(self.services.items[x]))


        if self.group_authorization_strict:
            for c in self.hosts._id_contact_heap.keys():
                # only host contacts can be hostgroup-contacts at all
                # now, which hosts does the contact know?
                contact_host_ids = set([h for h in self.hosts._id_contact_heap[c]])
                for (k, v) in self.hostgroups.items.iteritems():
                    # now look if c is contact of all v.members
                    # we already know the hosts for which c is a contact
                    # self.hosts._id_contact_heap[c] is [(hostname, id), (hostname, id)
                    hostgroup_host_ids = set([h.id for h in v.members])
                    # if all of the hostgroup_host_ids are in contact_host_ids
                    # then the hostgroup belongs to the contact
                    if hostgroup_host_ids <= contact_host_ids:
                        self.hostgroups._id_contact_heap.setdefault(c, []).append(v.id)
            for c in self.services._id_contact_heap.keys():
                # only service contacts can be servicegroup-contacts at all
                # now, which service does the contact know?
                contact_service_ids = set([h for h in self.services._id_contact_heap[c]])
                for (k, v) in self.servicegroups.items.iteritems():
                    # now look if c is contact of all v.members
                    # we already know the services for which c is a contact
                    # self.services._id_contact_heap[c] is [(svcdesc, id), (svcdesc, id)
                    servicegroup_service_ids = set([h.id for h in v.members])
                    # if all of the servicegroup_service_ids are in contact_service_ids
                    # then the servicegroup belongs to the contact
                    # print "%-10s %-15s %s <= %s" % (c, v.get_name(), servicegroup_service_ids, contact_service_ids)
                    if servicegroup_service_ids <= contact_service_ids:
                        self.servicegroups._id_contact_heap.setdefault(c, []).append(v.id)
        else:
            # loose: a contact of a member becomes contact of the whole group
            [self.hostgroups._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k) for (k, v) in self.hostgroups.items.iteritems() for h in v.members for c in h.contacts]
            [self.servicegroups._id_contact_heap.setdefault(get_obj_full_name(c), []).append(k) for (k, v) in self.servicegroups.items.iteritems() for s in v.members for c in s.contacts] # todo: look at mk-livestatus. what about service's host contacts?
        for c in self.hostgroups._id_contact_heap.keys():
            # remove duplicates
            self.hostgroups._id_contact_heap[c] = list(set(self.hostgroups._id_contact_heap[c]))
            self.hostgroups._id_contact_heap[c].sort(key=lambda x: get_obj_full_name(self.hostgroups.items[x]))
        for c in self.servicegroups._id_contact_heap.keys():
            # remove duplicates
            self.servicegroups._id_contact_heap[c] = list(set(self.servicegroups._id_contact_heap[c]))
            self.servicegroups._id_contact_heap[c].sort(key=lambda x: get_obj_full_name(self.servicegroups.items[x]))

        # Add another helper structure which allows direct lookup by name
        # For hosts: _id_by_host_name_heap = {'name1':id1, 'name2': id2,...}
        # For services: _id_by_host_name_heap = {'name1':[id1, id2,...], 'name2': [id6, id7,...],...} = hostname maps to list of service_ids
        # For services: _id_by_service_name_heap = {'name1':id1, 'name2': id6,...} = full_service_description maps to service_id
        setattr(self.hosts, '_id_by_host_name_heap', dict([(get_obj_full_name(v), k) for (k, v) in self.hosts.items.iteritems()]))
        setattr(self.services, '_id_by_service_name_heap', dict([(get_obj_full_name(v), k) for (k, v) in self.services.items.iteritems()]))
        setattr(self.services, '_id_by_host_name_heap', dict())
        [self.services._id_by_host_name_heap.setdefault(get_obj_full_name(v.host), []).append(k) for (k, v) in self.services.items.iteritems()]
        # print self.services._id_by_host_name_heap
        for hn in self.services._id_by_host_name_heap.keys():
            self.services._id_by_host_name_heap[hn].sort(key=lambda x: get_obj_full_name(self.services[x]))

        # Add another helper structure which allows direct lookup by name
        # For hostgroups: _id_by_hostgroup_name_heap = {'name1':id1, 'name2': id2,...}
        # For servicegroups: _id_by_servicegroup_name_heap = {'name1':id1, 'name2': id2,...}
        setattr(self.hostgroups, '_id_by_hostgroup_name_heap', dict([(get_obj_full_name(v), k) for (k, v) in self.hostgroups.items.iteritems()]))
        setattr(self.servicegroups, '_id_by_servicegroup_name_heap', dict([(get_obj_full_name(v), k) for (k, v) in self.servicegroups.items.iteritems()]))

        # For hosts: key is a hostgroup_name, value is an array with all host_ids of the hosts in this group
        setattr(self.hosts, '_id_by_hostgroup_name_heap', dict())
        [self.hosts._id_by_hostgroup_name_heap.setdefault(get_obj_full_name(hg), []).append(k) for (k, v) in self.hosts.items.iteritems() for hg in v.hostgroups]
        # For services: key is a servicegroup_name, value is an array with all service_ids of the services in this group
        setattr(self.services, '_id_by_servicegroup_name_heap', dict())
        [self.services._id_by_servicegroup_name_heap.setdefault(get_obj_full_name(sg), []).append(k) for (k, v) in self.services.items.iteritems() for sg in v.servicegroups]
        # For services: key is a hostgroup_name, value is an array with all service_ids of the hosts in this group
        setattr(self.services, '_id_by_hostgroup_name_heap', dict())
        [self.services._id_by_hostgroup_name_heap.setdefault(get_obj_full_name(hg), []).append(k) for (k, v) in self.services.items.iteritems() for hg in v.host.hostgroups]



        # print self.services._id_by_host_name_heap
        for hn in self.services._id_by_host_name_heap.keys():
            self.services._id_by_host_name_heap[hn].sort(key=lambda x: get_obj_full_name(self.services[x]))


        # Everything is new now. We should clean the cache
        self.cache.wipeout()
Exemple #37
0
    def get_dep_graph_struct(self, elt, levels=3):
        t = elt.__class__.my_type
        # We set the values for webui/plugins/depgraph/htdocs/js/eltdeps.js
        # so a node with important data for rendering
        # type = custom, business_impact and img_src.
        d = {
            'id': elt.get_dbg_name(),
            'name': elt.get_dbg_name(),
            'data': {
                '$type': 'custom',
                'business_impact': elt.business_impact,
                'img_src': self.get_icon_state(elt),
            },
            'adjacencies': []
        }

        # Set the right info panel
        d['data'][
            'infos'] = r'''%s <h2 class="%s"><img style="width: 64px; height:64px" src="%s"/> %s: %s</h2>
                   <p>since %s</p>
                   <div style="float:right;"> <a href="%s">%s</a></div>''' % (
                '<img src="/static/img/icons/star.png" alt="star">' *
                (elt.business_impact - 2), elt.state.lower(),
                self.get_icon_state(elt), elt.state, elt.get_full_name(),
                self.print_duration(elt.last_state_change,
                                    just_duration=True,
                                    x_elts=2), self.get_link_dest(elt),
                self.get_button('Go to details',
                                img='/static/images/search.png'))

        d['data']['elt_type'] = elt.__class__.my_type
        d['data']['is_problem'] = elt.is_problem
        d['data']['state_id'] = elt.state_id

        safe_print("ELT:%s is %s" % (elt.get_full_name(), elt.state))
        if elt.state in ['OK', 'UP', 'PENDING']:
            d['data']['circle'] = 'none'
        elif elt.state in ['DOWN', 'CRITICAL']:
            d['data']['circle'] = 'red'
        elif elt.state in ['WARNING', 'UNREACHABLE']:
            d['data']['circle'] = 'orange'
        else:
            d['data']['circle'] = 'none'

        # Now put in adj our parents
        for p in elt.parent_dependencies:
            pd = {
                'nodeTo': p.get_dbg_name(),
                'data': {
                    "$type": "line",
                    "$direction": [elt.get_dbg_name(),
                                   p.get_dbg_name()]
                }
            }

            # Naive way of looking at impact
            if elt.state_id != 0 and p.state_id != 0:
                pd['data']["$color"] = 'Tomato'
            # If OK, show host->service as a green link
            elif elt.__class__.my_type != p.__class__.my_type:
                pd['data']["$color"] = 'PaleGreen'
            d['adjacencies'].append(pd)

        # The sons case is now useful, it will be done by our sons
        # that will link us
        return d