Exemplo n.º 1
0
    def __init__(self, **kwds):
        # add all keywords to object, every mode searchs inside for its favorite arguments/keywords
        for k in kwds:
            self.__dict__[k] = kwds[k]

        GenericServer.__init__(self, **kwds)

        # Entries for monitor default actions in context menu
        self.MENU_ACTIONS = ["Recheck", "Acknowledge", "Downtime"]

        # cache MD5 username + password to reduce load
        self.MD5_username = Actions.MD5ify(
            self.conf.servers[self.get_name()].username)
        self.MD5_password = Actions.MD5ify(
            self.conf.servers[self.get_name()].password)
Exemplo n.º 2
0
    def GetHost(self, host):
        """
        Centreonified way to get host ip - attribute "a" in down hosts xml is of no use for up
        hosts so we need to get ip anyway from web page
        """
        # do a web interface search limited to only one result - the hostname
        cgi_data = urllib.urlencode({"sid":self.SID,\
                                    "search":host,\
                                    "num":0,\
                                    "limit":1,\
                                    "sort_type":"hostname",\
                                    "order":"ASC",\
                                    "date_time_format_status":"d/m/Y H:i:s",\
                                    "o":"h",\
                                    "p":20102,\
                                    "time":0})

        result = self.FetchURL(self.nagios_cgi_url + "/include/monitoring/status/Hosts/xml/hostXML.php?"\
                              + cgi_data, giveback="raw")
        raw = result.result
        # cut off <xml blabla>
        xmlraw = ElementTree.fromstring(raw.split("\n")[1])
        xmlobj = Actions.ObjectifyXML(xmlraw)
        del raw, xmlraw

        if len(xmlobj) != 0:
            # when connection by DNS is not configured do it by IP
            try:
                if str(self.conf.connect_by_dns_yes) == "True":
                    # try to get DNS name for ip, if not available use ip
                    try:
                        address = socket.gethostbyaddr(xmlobj[0].a.text)[0]
                        del xmlobj
                    except:
                        self.Error(sys.exc_info())
                        address = str(xmlobj[0].a.text)
                        del xmlobj
                else:
                    address = str(xmlobj[0].a.text)
                    del xmlobj
            except:
                result, error = self.Error(sys.exc_info())
                return Result(error=error)

        else:
            result, error = self.Error(sys.exc_info())
            return Result(error=error)

        # print IP in debug mode
        if str(self.conf.debug_mode) == "True":
            self.Debug(server=self.get_name(),
                       host=host,
                       debug="IP of %s:" % (host) + " " + address)
        # give back host or ip
        return Result(result=address)
Exemplo n.º 3
0
    def _get_status(self):
        """
        Get status from Opsview Server
        """
        # following http://docs.opsview.org/doku.php?id=opsview3.4:api to get ALL services in ALL states except OK
        # because we filter them out later
        # the API seems not to let hosts information directly, we hope to get it from service informations
        try:
            opsapiurl = self.nagios_url + "/api/status/service?state=1&state=2&state=3"
            result = self.FetchURL(opsapiurl, giveback="xml")
            xmlobj, error = result.result, result.error
            if error != "": return Result(result=xmlobj, error=error)

            for host in xmlobj.data.findAll("list"):
                # host
                hostdict = dict(host._getAttrMap())
                self.new_hosts[hostdict["name"]] = GenericHost()
                self.new_hosts[hostdict["name"]].name = str(hostdict["name"])
                # states come in lower case from Opsview
                self.new_hosts[hostdict["name"]].status = str(
                    hostdict["state"].upper())
                self.new_hosts[hostdict["name"]].last_check = str(
                    hostdict["last_check"])
                self.new_hosts[
                    hostdict["name"]].duration = Actions.HumanReadableDuration(
                        hostdict["state_duration"])
                self.new_hosts[hostdict["name"]].attempt = str(
                    hostdict["current_check_attempt"]) + "/" + str(
                        hostdict["max_check_attempts"])
                self.new_hosts[hostdict["name"]].status_information = str(
                    hostdict["output"].replace("\n", " "))
                # if host is in downtime add it to known maintained hosts
                if hostdict["downtime"] == "2":
                    self.new_hosts[hostdict["name"]].scheduled_downtime = True
                if hostdict.has_key("acknowledged"):
                    self.new_hosts[hostdict["name"]].acknowledged = True

                #services
                #for service in host.getchildren()[:-1]:
                for service in host.findAll("services"):
                    servicedict = dict(service._getAttrMap())
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]] = OpsviewService()
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]].host = str(hostdict["name"])
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]].name = str(servicedict["name"])
                    # states come in lower case from Opsview
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]].status = str(
                            servicedict["state"].upper())
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]].last_check = str(
                            servicedict["last_check"])
                    self.new_hosts[hostdict["name"]].services[servicedict[
                        "name"]].duration = Actions.HumanReadableDuration(
                            servicedict["state_duration"])
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]].attempt = str(
                            servicedict["current_check_attempt"]) + "/" + str(
                                servicedict["max_check_attempts"])
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]].status_information = str(
                            servicedict["output"].replace("\n", " "))
                    if servicedict["downtime"] == "2":
                        self.new_hosts[hostdict["name"]].services[
                            servicedict["name"]].scheduled_downtime = True
                    if servicedict.has_key("acknowledged"):
                        self.new_hosts[hostdict["name"]].services[
                            servicedict["name"]].acknowledged = True
                    # extra opsview id for service, needed for submitting check results
                    self.new_hosts[hostdict["name"]].services[
                        servicedict["name"]].service_object_id = str(
                            servicedict["service_object_id"])

        except:
            # set checking flag back to False
            self.isChecking = False
            result, error = self.Error(sys.exc_info())
            return Result(result=result, error=error)

        #dummy return in case all is OK
        return Result()
Exemplo n.º 4
0
# dictinary for servers
servers = dict()

# queue for debugging
debug_queue = Queue.Queue()

# create servers
for server in conf.servers.values():
    if server.save_password == "False" and server.enabled == "True":
        pwdialog = GUI.PasswordDialog(
            "Password for " + server.username + " on " + server.nagios_url + ": ")
        if pwdialog.password == None:
            sys.exit(1)
        server.password = pwdialog.password
    created_server = Actions.CreateServer(server, conf, debug_queue)
    if created_server is not None:
        servers[server.name] = created_server     
        
# Initiate Output
output = GUI.GUI(conf=conf, servers=servers, Resources=Resources, debug_queue=debug_queue)

# Start debugging loop
debugloop = Actions.DebugLoop(conf=conf, debug_queue=debug_queue, output=output)
debugloop.start()

# start threaded nagios server checking loop
Actions.StartRefreshLoop(servers=servers, conf=conf, output=output)

# if unconfigured nagstamon shows the settings dialog to get settings
if conf.unconfigured == True:
Exemplo n.º 5
0
    def _get_status(self):
        """
        Get status from Opsview Server
        """
        # following XXXX to get ALL services in ALL states except OK
        # because we filter them out later
        # the REST API gets all host and service info in one call
        try:
            result = self.FetchURL(
                self.monitor_url +
                "/rest/status/service?state=1&state=2&state=3",
                giveback="raw")
            data = json.loads(result.result)

            if str(self.conf.debug_mode) == "True":
                self.Debug(server=self.get_name(),
                           debug="Fetched JSON: " + pprint.pformat(data))

            #for host in xmlobj.opsview.findAll("item"):
            for host in data["list"]:
                self.new_hosts[host["name"]] = GenericHost()
                self.new_hosts[host["name"]].name = str(host["name"])
                self.new_hosts[host["name"]].server = self.name
                # states come in lower case from Opsview
                self.new_hosts[host["name"]].status = str(
                    host["state"].upper())
                self.new_hosts[host["name"]].status_type = str(
                    host["state_type"])
                self.new_hosts[
                    host["name"]].last_check = datetime.fromtimestamp(
                        int(host["last_check"])).strftime(
                            "%Y-%m-%d %H:%M:%S %z")
                self.new_hosts[host[
                    "name"]].duration = Actions.HumanReadableDurationFromSeconds(
                        host["state_duration"])
                self.new_hosts[host["name"]].attempt = host[
                    "current_check_attempt"] + "/" + host["max_check_attempts"]
                self.new_hosts[
                    host["name"]].status_information = host["output"].replace(
                        "\n", " ")

                # if host is in downtime add it to known maintained hosts
                if host["downtime"] == "2":
                    self.new_hosts[host["name"]].scheduled_downtime = True
                if host.has_key("acknowledged"):
                    self.new_hosts[host["name"]].acknowledged = True
                if host.has_key("flapping"):
                    self.new_hosts[host["name"]].flapping = True

                #services
                for service in host["services"]:
                    self.new_hosts[host["name"]].services[
                        service["name"]] = OpsviewService()
                    self.new_hosts[host["name"]].services[
                        service["name"]].host = str(host["name"])
                    self.new_hosts[host["name"]].services[
                        service["name"]].name = service["name"]
                    self.new_hosts[host["name"]].services[
                        service["name"]].server = self.name

                    # states come in lower case from Opsview
                    self.new_hosts[host["name"]].services[
                        service["name"]].status = service["state"].upper()
                    self.new_hosts[host["name"]].services[
                        service["name"]].status_type = service["state_type"]
                    self.new_hosts[host["name"]].services[
                        service["name"]].last_check = datetime.fromtimestamp(
                            int(service["last_check"])).strftime(
                                "%Y-%m-%d %H:%M:%S %z")
                    self.new_hosts[host["name"]].services[service[
                        "name"]].duration = Actions.HumanReadableDurationFromSeconds(
                            service["state_duration"])
                    self.new_hosts[host["name"]].services[
                        service["name"]].attempt = service[
                            "current_check_attempt"] + "/" + service[
                                "max_check_attempts"]
                    self.new_hosts[host["name"]].services[
                        service["name"]].status_information = service[
                            "output"].replace("\n", " ")
                    if service["downtime"] == "2":
                        self.new_hosts[host["name"]].services[
                            service["name"]].scheduled_downtime = True
                    if service.has_key("acknowledged"):
                        self.new_hosts[host["name"]].services[
                            service["name"]].acknowledged = True
                    if service.has_key("flapping"):
                        self.new_hosts[host["name"]].services[
                            service["name"]].flapping = True

                    # extra opsview id for service, needed for submitting check results
                    self.new_hosts[host["name"]].services[
                        service["name"]].service_object_id = service[
                            "service_object_id"]

        except:
            # set checking flag back to False
            self.isChecking = False
            result, error = self.Error(sys.exc_info())
            return Result(result=result, error=error)

        #dummy return in case all is OK
        return Result()
Exemplo n.º 6
0
    def _get_status(self):
        """
        Get status from Nagios Server
        """
        ret = Result()
        # create Nagios items dictionary with to lists for services and hosts
        # every list will contain a dictionary for every failed service/host
        # this dictionary is only temporarily
        nagitems = {"services": [], "hosts": []}

        # Create URLs for the configured filters
        if self.zapi is None:
            self._login()

        try:
            hosts = []
            try:
                hosts = self.zapi.host.get({
                    "output": [
                        "host", "ip", "status", "available", "error",
                        "errors_from"
                    ],
                    "filter": {}
                })
            except:
                # set checking flag back to False
                self.isChecking = False
                result, error = self.Error(sys.exc_info())
                return Result(result=result, error=error)

            for host in hosts:
                n = {
                    'host':
                    host['host'],
                    'status':
                    self.statemap.get(host['available'], host['available']),
                    'last_check':
                    'n/a',
                    'duration':
                    Actions.HumanReadableDurationFromTimestamp(
                        host['errors_from']),
                    'status_information':
                    host['error'],
                    'attempt':
                    '1/1',
                    'site':
                    '',
                    'address':
                    host['host'],
                }

                # add dictionary full of information about this host item to nagitems
                nagitems["hosts"].append(n)
                # after collection data in nagitems create objects from its informations
                # host objects contain service objects
                if n["host"] not in self.new_hosts:
                    new_host = n["host"]
                    self.new_hosts[new_host] = GenericHost()
                    self.new_hosts[new_host].name = n["host"]
                    self.new_hosts[new_host].status = n["status"]
                    self.new_hosts[new_host].last_check = n["last_check"]
                    self.new_hosts[new_host].duration = n["duration"]
                    self.new_hosts[new_host].attempt = n["attempt"]
                    self.new_hosts[new_host].status_information = n[
                        "status_information"]
                    self.new_hosts[new_host].site = n["site"]
                    self.new_hosts[new_host].address = n["address"]
        except ZabbixError:
            self.isChecking = False
            result, error = self.Error(sys.exc_info())
            return Result(result=result, error=error)

        # services
        services = []
        groupids = []
        zabbix_triggers = []
        try:
            api_version = self.zapi.api_version()
        except ZabbixAPIException:
            # FIXME Is there a cleaner way to handle this? I just borrowed
            # this code from 80 lines ahead. -- AGV
            # set checking flag back to False
            self.isChecking = False
            result, error = self.Error(sys.exc_info())
            print sys.exc_info()
            return Result(result=result, error=error)

        try:
            response = []
            try:
                #service = self.zapi.trigger.get({"select_items":"extend","monitored":1,"only_true":1,"min_severity":3,"output":"extend","filter":{}})

                triggers_list = []
                if self.monitor_cgi_url:
                    group_list = self.monitor_cgi_url.split(',')

                    #hostgroup_ids = [x['groupid'] for x in self.zapi.hostgroup.get(
                    #    {'output': 'extend',
                    #     'with_monitored_items': True,
                    #     'filter': {"name": group_list}}) if int(x['internal']) == 0]

                    # only without filter there is anything shown at all
                    hostgroup_ids = [
                        x['groupid'] for x in self.zapi.hostgroup.get(
                            {
                                'output': 'extend',
                                'with_monitored_items': True
                            }) if int(x['internal']) == 0
                    ]

                    zabbix_triggers = self.zapi.trigger.get({
                        'sortfield':
                        'lastchange',
                        'withUnacknowledgedEvents':
                        True,
                        'groupids':
                        hostgroup_ids,
                        "monitored":
                        True,
                        "filter": {
                            'value': 1
                        }
                    })
                else:
                    zabbix_triggers = self.zapi.trigger.get({
                        'sortfield':
                        'lastchange',
                        'withUnacknowledgedEvents':
                        True,
                        "monitored":
                        True,
                        "filter": {
                            'value': 1
                        }
                    })
                triggers_list = []

                for trigger in zabbix_triggers:
                    triggers_list.append(trigger.get('triggerid'))
                this_trigger = self.zapi.trigger.get({
                    'triggerids': triggers_list,
                    'expandDescription': True,
                    'output': 'extend',
                    'select_items': 'extend',
                    'expandData': True
                })
                if type(this_trigger) is dict:
                    for triggerid in this_trigger.keys():
                        services.append(this_trigger[triggerid])
                elif type(this_trigger) is list:
                    for trigger in this_trigger:
                        services.append(trigger)

            except ZabbixAPIException:
                # FIXME Is there a cleaner way to handle this? I just borrowed
                # this code from 80 lines ahead. -- AGV
                # set checking flag back to False
                self.isChecking = False
                result, error = self.Error(sys.exc_info())
                print sys.exc_info()
                return Result(result=result, error=error)

            except ZabbixError, e:
                #print "------------------------------------"
                #print "%s" % e.result.error
                if e.terminate:
                    return e.result
                else:
                    service = e.result.content
                    ret = e.result

            for service in services:
                if api_version > '1.8':
                    state = '%s' % service['description']
                else:
                    state = '%s=%s' % (service['items'][0]['key_'],
                                       service['items'][0]['lastvalue'])
                n = {
                    'host':
                    service['host'],
                    'service':
                    service['description'],
                    'status':
                    self.statemap.get(service['priority'],
                                      service['priority']),
                    # 1/1 attempt looks at least like there has been any attempt
                    'attempt':
                    '1/1',
                    'duration':
                    Actions.HumanReadableDurationFromTimestamp(
                        service['lastchange']),
                    'status_information':
                    state,
                    'passiveonly':
                    'no',
                    'last_check':
                    'n/a',
                    'notifications':
                    'yes',
                    'flapping':
                    'no',
                    'site':
                    '',
                    'command':
                    'zabbix',
                    'triggerid':
                    service['triggerid'],
                }

                nagitems["services"].append(n)
                # after collection data in nagitems create objects of its informations
                # host objects contain service objects
                if n["host"] not in self.new_hosts:
                    self.new_hosts[n["host"]] = GenericHost()
                    self.new_hosts[n["host"]].name = n["host"]
                    self.new_hosts[n["host"]].status = "UP"
                    self.new_hosts[n["host"]].site = n["site"]
                    self.new_hosts[n["host"]].address = n["host"]
                    # if a service does not exist create its object
                if n["service"] not in self.new_hosts[n["host"]].services:
                    # workaround for non-existing (or not found) host status flag
                    if n["service"] == "Host is down %s" % (n["host"]):
                        self.new_hosts[n["host"]].status = "DOWN"
                        # also take duration from "service" aka trigger
                        self.new_hosts[n["host"]].duration = n["duration"]
                    else:
                        new_service = n["service"]
                        self.new_hosts[n["host"]].services[
                            new_service] = GenericService()
                        self.new_hosts[
                            n["host"]].services[new_service].host = n["host"]

                        # next dirty workaround to get Zabbix events to look Nagios-esque
                        if (" on " or " is ") in n["service"]:
                            for separator in [" on ", " is "]:
                                n["service"] = n["service"].split(separator)[0]
                        self.new_hosts[n["host"]].services[
                            new_service].name = n["service"]

                        self.new_hosts[n["host"]].services[
                            new_service].status = n["status"]
                        self.new_hosts[n["host"]].services[
                            new_service].last_check = n["last_check"]
                        self.new_hosts[n["host"]].services[
                            new_service].duration = n["duration"]
                        self.new_hosts[n["host"]].services[
                            new_service].attempt = n["attempt"]
                        self.new_hosts[n["host"]].services[
                            new_service].status_information = n[
                                "status_information"]
                        #self.new_hosts[n["host"]].services[new_service].passiveonly = n["passiveonly"]
                        self.new_hosts[n["host"]].services[
                            new_service].passiveonly = False
                        #self.new_hosts[n["host"]].services[new_service].flapping = n["flapping"]
                        self.new_hosts[
                            n["host"]].services[new_service].flapping = False
                        self.new_hosts[
                            n["host"]].services[new_service].site = n["site"]
                        self.new_hosts[n["host"]].services[
                            new_service].address = n["host"]
                        self.new_hosts[n["host"]].services[
                            new_service].command = n["command"]
                        self.new_hosts[n["host"]].services[
                            new_service].triggerid = n["triggerid"]