Esempio n. 1
0
    def make_nagios_changes(self):
        path = os.path.join(self._tmp_conf['nagios_cfgs'], "host-services")
        pattern = re.compile("(?P<kk>^[\w\-]+)$")
        for fi in os.listdir(path):
            os.remove(os.path.join(path, fi))

        path = os.path.join(self._tmp_conf['nagios_cfgs'], "hostgroup-services")

        for fi in os.listdir(path):
            os.remove(os.path.join(path, fi))

        path = os.path.join(self._tmp_conf['nagios_cfgs'], "hostgroups")

        for fi in os.listdir(path):
            os.remove(os.path.join(path, fi))
        self.load_active_hosts()
        services_by_host_dic = {}
        for host_ip, hostname in self._active_hosts.iteritems():
            nh = nagios_host(host_ip, hostname, "", self._tmp_conf)
            nh.write()
            services_by_host = self.get_services_by_hosts(host_ip)
            for service in services_by_host:
                service_type =service['service_type']
                if not pattern.match(service_type):
                    logger.warning('Invalid service type: %s' % service_type)
                    continue
                protocol = service['protocol']
                hostname = service['hostname']
                port = service['port']
                if not services_by_host_dic.has_key(service_type):
                    services_by_host_dic[service_type] = []
                if hostname not in services_by_host_dic[service_type]:
                    services_by_host_dic[service_type].append(hostname)
                k = nagios_host_service(service_type,protocol,hostname,port,"120", self._tmp_conf)
                k.write()
        for key, value in services_by_host_dic.iteritems():
            if key=='unknown':
                continue
            members = ','.join(value)
            hg = nagios_host_group_service(key,key,members,self._tmp_conf)
            hg.write()
        data = self.get_host_groups()
        for hg in data:
            name = hg['name']
            data =self.get_hostlist_from_hg(name)
            host_list = []
            if len(data)>0:
                for host in data:
                    if self._active_hosts.has_key(host['host_ip']):
                        host_list.append(self._active_hosts[host['host_ip']])
            if len(host_list)> 0:
                hosts_list_str = ','.join(host_list)
                nhg = nagios_host_group(name, name, hosts_list_str, self._tmp_conf)
                nhg.write()
        logger.debug("Changes where applied! Reloading Nagios config.")
        
        self.reload_nagios()
Esempio n. 2
0
    def make_nagios_changes(self):
        """Loads all the host/host_groups/net/net_groups and creates 
        all the nagios configuration.
        """
        logger.info("Making nagios changes..")

        pattern = re.compile("(?P<kk>^[\w\-]+)$")

        path = os.path.join(self._tmp_conf['nagios_cfgs'], "host-services")
        for fi in os.listdir(path):
            os.remove(os.path.join(path, fi))

        path = os.path.join(self._tmp_conf['nagios_cfgs'], "hostgroup-services")
        for fi in os.listdir(path):
            os.remove(os.path.join(path, fi))

        path = os.path.join(self._tmp_conf['nagios_cfgs'], "hostgroups")
        for fi in os.listdir(path):
            os.remove(os.path.join(path, fi))

        path = os.path.join(self._tmp_conf['nagios_cfgs'], "hosts")
        for fi in os.listdir(path):
            os.remove(os.path.join(path, fi))

        # 1 - Load the active hosts.
        self.load_active_hosts()
        services_by_host_dic = {}
        hostnames_dic = {}
        hostnames_dup_dic = {}

        # Looking for duplicate hostnames
        for host_id, host in self.__active_hosts.iteritems():
            hostname = host.getHostname()
            if (hostnames_dic.has_key(hostname)):
                hostnames_dup_dic[hostname] = True
            hostnames_dic[hostname] = True

        for host_id, host in self.__active_hosts.iteritems():
            hostname = host.getHostname()
            #host_ip = tupla[1]

            for ip in host.getIPList():
                realhostname = hostname

                if host.hasMoreThanOneIP() or hostnames_dup_dic.has_key(hostname):
                    realhostname = "%s_%s" % (hostname,ip)

                nh = nagios_host(ip,realhostname, "", self._tmp_conf)
                logger.info("nagios host: %s->%s" % (ip,realhostname))
                nh.write()
                for service in host.getServicesByIP(ip):
                    service_type = service.getServiceServiceType()
                    if not service_type:
                        continue
                    if not pattern.match(service_type):
                        logger.warning('Invalid service type: %s' % service_type)
                        continue
                    protocol = service.getServiceProtocol()
                    port = service.getServicePort()
                    if not services_by_host_dic.has_key(service_type):
                        services_by_host_dic[service_type] = []
                    if realhostname not in services_by_host_dic[service_type]:
                        services_by_host_dic[service_type].append(realhostname)
                    logger.info("nagios hostservice:  %s,%s,%s,%s" % (service_type,protocol,realhostname,port)) 
                    k = nagios_host_service(service_type,protocol,realhostname,port,"120", self._tmp_conf)
                    k.write()
        for key, value in services_by_host_dic.iteritems():
            if key=='unknown':
                continue
            members = ','.join(value)
            hg = nagios_host_group_service(key,key,members,self._tmp_conf)
            logger.info("nagios host group services %s,%s,%s"%(key,key,members))
            hg.write()
        data = self.get_host_groups()
        for hg in data:
            name = hg['name']   
            hostgroup_id = hg['id']
            data =self.get_hostlist_from_hg(hostgroup_id)
            host_list = []
            if len(data)>0:
                for host in data:
                    if self.__active_hosts.has_key(host['host_id']):
                        ac_host = self.__active_hosts[host['host_id']]
                        if ac_host.hasMoreThanOneIP():
                            for ip in ac_host.getIPList():
                                host_list.append(ac_host.getHostname()+"_%s" % ip)
                        else:
                            host_list.append(ac_host.getHostname())
                    else:
                        logger.info("host from hostgroup not in active hostsa :%s" %host['host_id'])
                logger.info("host from hg: %s" % host_list)
            if len(host_list)> 0:
                hosts_list_str = ','.join(host_list)
                logger.info("name:%s -  %s" % (name,hosts_list_str))
                nhg = nagios_host_group(name, name, hosts_list_str, self._tmp_conf)
                logger.info("nagios hostgroup :%s,%s,%s" % (name,name,hosts_list_str))
                nhg.write()
        logger.debug("Changes where applied! Reloading Nagios config.")
        # Change configuration file permissions.
        try:
            for root, dirs, files in os.walk(self._tmp_conf['nagios_cfgs']):
                for config in files:
                    config_file = root + "/" + config
                    os.chmod(config_file, 0644)
        except Exception as e:
            logger.error("An error occurred while changing the configuration files permissions: %s" % str(e))
        self.reload_nagios()
Esempio n. 3
0
    def process(self, message):
        logger.debug("Nagios Manager: Processing: %s" % message)

        response = ""
        action = Util.get_var("action=\"([a-z]+)\"", message)

        if action == "add":
            type = Util.get_var("type=\"([a-zA-Z]+)\"", message)

            logger.debug("TYPE: %s" % type)
            if type == "host":
                liststring = Util.get_var("list=\"[^\"]+\"", message)
                logger.debug("STRING: %s" % liststring)
                list = liststring.split("|")
                logger.debug("LIST: %s" % list)
                for host in list:
                    host_data = re.match(r"^\s*(list=\")*(?P<ip>([0-9]{1,3}\.){3}[0-9]{1,3})\;(?P<hostname>[\w_\-\s.]+)\s*\"*$",host)

                    if host_data.group('ip') != [] and host_data.group('hostname') != []:
                        hostname = host_data.group('hostname')
                        ip = host_data.group('ip')

                        logger.debug("Adding hostname \"%s\" with ip \"%s\" to nagios" % (hostname, ip))

                        nh = nagios_host(ip, hostname, "", self.__conf)
                        nh.write()

            if type == "hostgroup":
                name = Util.get_var("name=\"([\w_\-\s.]+)\"", message)
                liststring = Util.get_var("list=\"([^\"]+)\"", message)
                list = liststring.split(",")
                logger.debug("LISTSTRING: %s" % liststring)
                hosts = ""
                for host in list:
                    #host_data=re.match(r"^\s*(list=\")*(?P<ip>([0-9]{1,3}\.){3}[0-9]{1,3})\s*\"*$",host)
                    #To support nagios name
                            
                    host_data = re.match("(?P<ip>[^;]+);(?P<name>[^$]+)$",host)
                    if host_data and host_data.group('ip') != []:
                        ip = host_data.group('ip')
                        hName = host_data.group('name')

                        if hosts == "":
                            hosts = ip
                            hgName= hName
                        else:
                            hosts = ip + "," + hosts
                            hgName = hName + "," + hgName

                        logger.debug("Adding host \"%s\" with ip \"%s\" needed by group_name %s to nagios" % (hName, ip, name))

                        nh = nagios_host(ip, hName, "", self.__conf)
                        nh.write()

                    else:
                        logger.warning("Nagios format error in message: %s" % message)
                        return

                if hosts != "":
                    logger.debug("Adding %s to nagios" % (name))
                    logger.debug("LIST: %s" % (hgName))
                    nhg = nagios_host_group(name, name, hgName, self.__conf)
                    nhg.write()

                else:
                    logger.debug("Invalid hosts list... not adding %s to nagios" % (name))

            action = "reload"

        if action == "del":
            type = Util.get_var("type=\"([a-zA-Z]+)\"", message)

            if type == "host":
                ip = Util.get_var("list=\"\s*(([0-9]{1,3}\.){3}[0-9]{1,3})\s*\"",message)
                ip = ip[0]

                if ip != "":
                    logger.debug("Deleting hostname \"%s\" from nagios" % (ip))
                    nh = nagios_host(ip, ip, "", self.__conf)
                    nh.delete_host()

            if type == "hostgroup":
                name = Util.get_var("name=\"([\w_\-.]+)\"", message)

                logger.debug("Deleting hostgroup_name \"%s\" from nagios" % (name))

                nhg = nagios_host_group(name, name, "", self.__conf)
                nhg.delete_host_group()

            action="reload"

        else: 
            print


        if action=="restart" or action=="reload":
            if self.__nagios == None:
                self.__nagios = DoNagios()

            self.__nagios.make_nagios_changes()
            self.__nagios.reload_nagios()

        # send back our response
        return response
Esempio n. 4
0
    def make_nagios_changes(self):
        """Loads all the host/host_groups/net/net_groups and creates 
        all the nagios configuration.
        """
        logger.info("Making nagios changes..")

        # 1 - Load the active hosts.
        self.load_active_hosts()

        # Check if the return is the same as last time.
        # This will prevent unnecessary reloads and disk writes of configs
        # This *could* still run after the first change, but not subsequent ones without change
        current_hash = hash(str(sorted(self.__active_hosts)))

        if current_hash == self.__prevhash:
            logger.info("No Nagios Changes")
        else:
            # Store new activity diff.
            self.__save_nagios_activity_diff(current_hash)

            services_by_host_dic = {}
            hostnames_dic = {}
            hostnames_dup_dic = {}
            pattern = re.compile("(?P<kk>^\w[\w\-\s]+)$")

            path = os.path.join(self._tmp_conf['nagios_cfgs'], "host-services")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            path = os.path.join(self._tmp_conf['nagios_cfgs'], "hostgroup-services")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            path = os.path.join(self._tmp_conf['nagios_cfgs'], "hostgroups")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            path = os.path.join(self._tmp_conf['nagios_cfgs'], "hosts")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            # Looking for duplicate hostname
            for host_id, host in self.__active_hosts.iteritems():
                hostname = host.getHostname()
                if hostname in hostnames_dic:
                    hostnames_dup_dic[hostname] = True
                hostnames_dic[hostname] = True

            for host_id, host in self.__active_hosts.iteritems():
                hostname = host.getHostname()

                for ip in host.getIPList():
                    realhostname = hostname

                    if host.hasMoreThanOneIP() or hostname in hostnames_dup_dic:
                        realhostname = "%s_%s" % (hostname, ip)

                    nh = nagios_host(ip, realhostname, "", self._tmp_conf)
                    logger.info("nagios host: %s->%s" % (ip, realhostname))
                    nh.write()

                    for service in host.getServicesByIP(ip):
                        service_type = service.getServiceServiceType()
                        if not service_type:
                            continue
                        if not pattern.match(service_type):
                            logger.warning('Invalid service type: %s' % service_type)
                            continue
                        protocol = service.getServiceProtocol()
                        port = service.getServicePort()

                        if service_type not in services_by_host_dic:
                            services_by_host_dic[service_type] = []
                        if realhostname not in services_by_host_dic[service_type]:
                            services_by_host_dic[service_type].append(realhostname)
                        logger.info("nagios hostservice:  %s,%s,%s,%s" % (service_type, protocol, realhostname, port))
                        k = nagios_host_service(service_type, protocol, realhostname, port, "120", self._tmp_conf)
                        k.write()

            for key, value in services_by_host_dic.iteritems():
                if key == 'unknown':
                    continue
                members = ','.join(value)
                hg = nagios_host_group_service(key, key, members, self._tmp_conf)
                logger.info("nagios host group services %s,%s,%s" % (key, key, members))
                hg.write()

            data = self.get_host_groups()
            for hg in data:
                name = hg['name']
                hostgroup_id = hg['id']
                data = self.get_hostlist_from_hg(hostgroup_id)
                host_list = []

                if len(data) > 0:
                    for host in data:
                        host_id = host['host_id']
                        if host_id in self.__active_hosts:
                            ac_host = self.__active_hosts[host_id]
                            if ac_host.hasMoreThanOneIP():
                                for ip in ac_host.getIPList():
                                    host_list.append(ac_host.getHostname()+"_%s" % ip)
                            else:
                                host_list.append(ac_host.getHostname())
                        else:
                            logger.info("host from hostgroup not in active hosts :%s" % host_id)
                    logger.info("host from hg: %s" % host_list)

                if len(host_list) > 0:
                    hosts_list_str = ','.join(host_list)
                    logger.info("name:%s -  %s" % (name, hosts_list_str))
                    nhg = nagios_host_group(name, name, hosts_list_str, self._tmp_conf)
                    logger.info("nagios hostgroup :%s,%s,%s" % (name, name, hosts_list_str))
                    nhg.write()

            logger.debug("Changes were applied! Reloading Nagios config.")
            # Change configuration file permissions.
            try:
                for root, dirs, files in os.walk(self._tmp_conf['nagios_cfgs']):
                    for config in files:
                        config_file = root + "/" + config
                        os.chmod(config_file, 0644)
                    for cdir in dirs:
                        config_dir = root + "/" + cdir
                        os.chmod(config_dir, 0755)
                os.chmod(self._tmp_conf['nagios_cfgs'], 0755)
            except Exception as e:
                logger.error("An error occurred while changing the configuration files permissions: %s" % str(e))

            self.reload_nagios()
Esempio n. 5
0
    def make_nagios_changes(self):
        """Loads all the host/host_groups/net/net_groups and creates 
        all the nagios configuration.
        """
        logger.info("Making nagios changes..")

        # 1 - Load the active hosts.
        self.load_active_hosts()

        # Check if the return is the same as last time.
        # This will prevent unnecessary reloads and disk writes of configs
        # This *could* still run after the first change, but not subsequent ones without change
        current_hash = hash(str(sorted(self.__active_hosts)))

        if current_hash == self.__prevhash:
            logger.info("No Nagios Changes")
        else:
            # Store new activity diff.
            self.__save_nagios_activity_diff(current_hash)

            services_by_host_dic = {}
            hostnames_dic = {}
            hostnames_dup_dic = {}
            pattern = re.compile("(?P<kk>^\w[\w\-\s]+)$")

            path = os.path.join(self._tmp_conf['nagios_cfgs'], "host-services")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            path = os.path.join(self._tmp_conf['nagios_cfgs'],
                                "hostgroup-services")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            path = os.path.join(self._tmp_conf['nagios_cfgs'], "hostgroups")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            path = os.path.join(self._tmp_conf['nagios_cfgs'], "hosts")
            for fi in os.listdir(path):
                os.remove(os.path.join(path, fi))

            # Looking for duplicate hostname
            for host_id, host in self.__active_hosts.iteritems():
                hostname = host.getHostname()
                if hostname in hostnames_dic:
                    hostnames_dup_dic[hostname] = True
                hostnames_dic[hostname] = True

            for host_id, host in self.__active_hosts.iteritems():
                hostname = host.getHostname()

                for ip in host.getIPList():
                    realhostname = hostname

                    if host.hasMoreThanOneIP(
                    ) or hostname in hostnames_dup_dic:
                        realhostname = "%s_%s" % (hostname, ip)

                    nh = nagios_host(ip, realhostname, "", self._tmp_conf)
                    logger.info("nagios host: %s->%s" % (ip, realhostname))
                    nh.write()

                    for service in host.getServicesByIP(ip):
                        service_type = service.getServiceServiceType()
                        if not service_type:
                            continue
                        if not pattern.match(service_type):
                            logger.warning('Invalid service type: %s' %
                                           service_type)
                            continue
                        protocol = service.getServiceProtocol()
                        port = service.getServicePort()

                        if service_type not in services_by_host_dic:
                            services_by_host_dic[service_type] = []
                        if realhostname not in services_by_host_dic[
                                service_type]:
                            services_by_host_dic[service_type].append(
                                realhostname)
                        logger.info(
                            "nagios hostservice:  %s,%s,%s,%s" %
                            (service_type, protocol, realhostname, port))
                        k = nagios_host_service(service_type, protocol,
                                                realhostname, port, "120",
                                                self._tmp_conf)
                        k.write()

            for key, value in services_by_host_dic.iteritems():
                if key == 'unknown':
                    continue
                members = ','.join(value)
                hg = nagios_host_group_service(key, key, members,
                                               self._tmp_conf)
                logger.info("nagios host group services %s,%s,%s" %
                            (key, key, members))
                hg.write()

            data = self.get_host_groups()
            for hg in data:
                name = hg['name']
                hostgroup_id = hg['id']
                data = self.get_hostlist_from_hg(hostgroup_id)
                host_list = []

                if len(data) > 0:
                    for host in data:
                        host_id = host['host_id']
                        if host_id in self.__active_hosts:
                            ac_host = self.__active_hosts[host_id]
                            if ac_host.hasMoreThanOneIP():
                                for ip in ac_host.getIPList():
                                    host_list.append(ac_host.getHostname() +
                                                     "_%s" % ip)
                            else:
                                host_list.append(ac_host.getHostname())
                        else:
                            logger.info(
                                "host from hostgroup not in active hosts :%s" %
                                host_id)
                    logger.info("host from hg: %s" % host_list)

                if len(host_list) > 0:
                    hosts_list_str = ','.join(host_list)
                    logger.info("name:%s -  %s" % (name, hosts_list_str))
                    nhg = nagios_host_group(name, name, hosts_list_str,
                                            self._tmp_conf)
                    logger.info("nagios hostgroup :%s,%s,%s" %
                                (name, name, hosts_list_str))
                    nhg.write()

            logger.debug("Changes were applied! Reloading Nagios config.")
            # Change configuration file permissions.
            try:
                for root, dirs, files in os.walk(
                        self._tmp_conf['nagios_cfgs']):
                    for config in files:
                        config_file = root + "/" + config
                        os.chmod(config_file, 0644)
                    for cdir in dirs:
                        config_dir = root + "/" + cdir
                        os.chmod(config_dir, 0755)
                os.chmod(self._tmp_conf['nagios_cfgs'], 0755)
            except Exception as e:
                logger.error(
                    "An error occurred while changing the configuration files permissions: %s"
                    % str(e))

            self.reload_nagios()