Example #1
0
    def post(self, jwt):
        data = []
        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()

                host_name = post_data.get('host_name')

                community_str = ""

                if host_name is None:
                    return jsonify(error=True,
                                   msg="Missing host_name required field.")

                host = Host.get_by_hostname(host_name)
                if host is None:
                    return jsonify(error=True)
                else:
                    community_str = host._SNMPCOMMUNITY
                    if community_str is None or len(community_str) == 0:
                        return jsonify(error=True,
                                       msg="Missing SNMP community.")

                    data.append({
                        "id":
                        "1",
                        "type_name":
                        "snmp_cpuload",
                        "type_alias":
                        "SNMP CPU Load",
                        "type_info":
                        "Monitors the load of a CPU via SNMP"
                    })

                    data.append({
                        "id":
                        "2",
                        "type_name":
                        "snmp_traffic",
                        "type_alias":
                        "SNMP Traffic",
                        "type_info":
                        "Monitors bandwidth and traffic on servers, PCs, switches, etc. using SNMP"
                    })

                    data.append({
                        "id":
                        "3",
                        "type_name":
                        "snmp_memory",
                        "type_alias":
                        "SNMP Memory",
                        "type_info":
                        "Monitors the memory usage via SNMP"
                    })
            except Exception as e:
                return jsonify(error=True, msg=str(e))

        return jsonify(data=data)
Example #2
0
    def get(self, jwt, host_id, page_id, host_name=None):
        data = []

        # If page_id is None do it the slow way.
        if page_id is None:
            # If no host_id is passed in get all hosts.
            if (host_id is None) and (host_name is None):
                # This is slow so lets just return an error
                # hosts = Host.get_all()
                return jsonify(
                    error=True,
                    msg=
                    "Getting all hosts is slow. Please use the pagination endpoint at ./manage_host/page/"
                )
            elif host_id:
                if Host.get_by_id(host_id):
                    hosts = [Host.get_by_id(host_id)]
                else:
                    hosts = []
            elif host_name:
                hosts = [Host.get_by_hostname(host_name)]

            # Loop over results and get json form of host to return.
            if len(hosts) > 0:
                for host in hosts:
                    temp_data = host.serialize()
                    temp_data_services = Service.get_all_by_host_name(
                        host.host_name)
                    temp_data["all_services"] = []
                    for tds in temp_data_services:
                        temp_data["all_services"].append(tds.serialize())
                    data.append(temp_data)
                    pass
                return jsonify(data=data)
            else:
                return jsonify(error=True, msg="Host does not exist.")
        else:
            per_page = 10
            totalhosts = Host.get_count()
            total_pages = floor(totalhosts / per_page)
            hosts = Host.get_by_page((page_id * per_page), per_page)

            if hosts is not None:
                for host in hosts:
                    temp_data = host.serialize()
                    temp_data_services = Service.get_all_by_host_name(
                        host.host_name)
                    temp_data["all_services"] = []
                    for tds in temp_data_services:
                        temp_data["all_services"].append(tds.serialize())
                    data.append(temp_data)

            return jsonify({
                "data": data,
                "totalhosts": totalhosts,
                "this_page": page_id,
                "more": (page_id < total_pages)
            })
Example #3
0
def syncNagiosAllConfigWithDb():
    # Delete all nagios config files
    deleteNagiosAllConfigFile()

    # Delete all relation tables
    Contact2Group.delete_all()
    ContactService.delete_all()
    ContactgroupService.delete_all()
    HostContact.delete_all()
    HostContactGroup.delete_all()
    HostService.delete_all()
    HostgroupHost.delete_all()
    Service2Group.delete_all()

    # Sync all settings
    # sync timerperiods table
    timeperiods = Timeperiod.get_all()
    if timeperiods is not None:
        for timeperiod in timeperiods:
            timeperioditems = Timeperioditem.get_by_timeperiodid(timeperiod.id)
            writeNagiosTimeperiodsConfigFile(timeperiod, timeperioditems)

    # sync servicetemplate tables
    servicetemplates = ServiceTemplate.get_all()
    if servicetemplates is not None:
        for servicetemplate in servicetemplates:
            writeNagiosServiceTemplatesConfigFile(servicetemplate)

    # sync commands table
    commands = Command.get_all()
    if commands is not None:
        for command in commands:
            writeNagiosCommandsConfigFile(command)

    # sync servicegroups table
    servicegroups = ServiceGroup.get_all()
    if servicegroups is not None:
        for servicegroup in servicegroups:
            writeNagiosServiceGroupsConfigFile(servicegroup)

    # sync contactgroups table
    contactgroups = ContactGroup.get_all()
    if contactgroups is not None:
        for contactgroup in contactgroups:
            writeNagiosContactGroupsConfigFile(contactgroup)

    # sync contacts table
    contacts = Contact.get_all()
    contact_to_group_relations = []
    if contacts is not None:
        for contact in contacts:
            writeNagiosContactsConfigFile(contact)
            contactgroup_str = contact.contactgroups

            if contactgroup_str is not None and len(
                    contactgroup_str) > 0 and contactgroup_str != "NULL":
                contactgroups = contactgroup_str.split(',')

                for contactgroup_name in contactgroups:
                    contactgroup = ContactGroup.get_by_contactgroupname(
                        contactgroup_name)
                    if contactgroup is None:
                        continue

                    # insert contact_contactgroup table
                    newrelation = Contact2Group(
                        contact_id=contact.id, contactgroup_id=contactgroup.id)
                    contact_to_group_relations.append(newrelation)
        Contact2Group.save_all(contact_to_group_relations)

    # sync hostgroups table
    hostgroups = Hostgroup.get_all()
    hots_to_group_relations = []
    if hostgroups is not None:
        for hostgroup in hostgroups:
            writeNagiosHostgroupsConfigFile(hostgroup)
            hostgroup_str = hostgroup.members

            if hostgroup_str is not None and len(
                    hostgroup_str) > 0 and hostgroup_str != "NULL":
                members = hostgroup_str.split(',')

                for member in members:
                    host = Host.get_by_hostname(member)
                    if host is None:
                        continue

                    # insert hostgroup_host table
                    newrelation = HostgroupHost(hostgroup_id=hostgroup.id,
                                                host_id=host.id)
                    hots_to_group_relations.append(newrelation)
        HostgroupHost.save_all(hots_to_group_relations)

    # sync services table
    services = Service.get_all()
    hots_to_service_relations = []
    contact_to_service_relations = []
    contactgroup_to_service_relations = []
    service_to_group_relations = []
    if services is not None:
        for service in services:
            tmp_checkInterval = service.check_interval
            service.check_interval = round(int(service.check_interval) / 60, 1)
            writeNagiosServicesConfigFile(service)
            service.check_interval = tmp_checkInterval

            # Create relation table between hosts and services
            host_str = service.host_name
            if host_str is not None and len(
                    host_str) > 0 and host_str != "NULL":
                hosts = host_str.split(',')

                for hname in hosts:
                    hostname = Host.get_by_hostname(hname)
                    if hostname is None:
                        continue

                    # insert host_service table
                    newhostrelation = HostService(service_id=service.id,
                                                  host_id=hostname.id)
                    hots_to_service_relations.append(newhostrelation)

            # Create relation table between contacts and services
            contact_str = service.contacts
            if contact_str is not None and len(
                    contact_str) > 0 and contact_str != "NULL":
                contacts = contact_str.split(',')

                for contact in contacts:
                    contactname = Contact.get_by_contactname(contact)
                    if contactname is None:
                        continue

                    # insert contact_service table
                    newcontactrelation = ContactService(
                        service_id=service.id, contact_id=contactname.id)
                    contact_to_service_relations.append(newcontactrelation)

            # Create relation table between contactgroups and services
            contactgroup_str = service.contact_groups
            if contactgroup_str is not None and len(
                    contactgroup_str) > 0 and contactgroup_str != "NULL":
                contact_groups = contactgroup_str.split(',')

                for contactgroup in contact_groups:
                    contactgroupname = ContactGroup.get_by_contactgroupname(
                        contactgroup)
                    if contactgroupname is None:
                        continue

                    # insert contactgroup_service table
                    newgrouprelation = ContactgroupService(
                        service_id=service.id,
                        contactgroup_id=contactgroupname.id)
                    contactgroup_to_service_relations.append(newgrouprelation)

            # Create relation table between services and servicegroups
            servicegroup_str = service.servicegroups
            if servicegroup_str is not None and len(
                    servicegroup_str) > 0 and servicegroup_str != "NULL":
                servicegroups = servicegroup_str.split(',')

                for servicegroup_name in servicegroups:
                    servicegroup = ServiceGroup.get_by_servicegroupname(
                        servicegroup_name)
                    if servicegroup is None:
                        continue

                    # insert service_servicegroup table
                    newservicerelation = Service2Group(
                        service_id=service.id, servicegroup_id=servicegroup.id)
                    service_to_group_relations.append(newservicerelation)
        HostService.save_all(hots_to_service_relations)
        ContactService.save_all(contact_to_service_relations)
        ContactgroupService.save_all(contactgroup_to_service_relations)
        Service2Group.save_all(service_to_group_relations)

    # sync hosts table
    hosts = Host.get_all()
    host_to_contact_relations = []
    host_to_contactgroup_relations = []
    if hosts is not None:
        for host in hosts:
            writeNagiosConfigFile(host)

            contact_str = host.contacts
            if contact_str is not None and len(
                    contact_str) > 0 and contact_str != "NULL":
                contacts = contact_str.split(',')

                for contact_name in contacts:
                    contact = Contact.get_by_contactname(contact_name)
                    if contact is None:
                        continue
                    newhostcontact = HostContact(host_id=host.id,
                                                 contact_id=contact.id)
                    host_to_contact_relations.append(newhostcontact)

            contactgroup_str = host.contact_groups
            if contactgroup_str is not None and len(
                    contactgroup_str) > 0 and contactgroup_str != "NULL":
                contactgroups = contactgroup_str.split(',')

                for contactgroup_name in contactgroups:
                    contactgroup = ContactGroup.get_by_contactgroupname(
                        contactgroup_name)
                    if contactgroup is None:
                        continue
                    newhostcontactgroup = HostContactGroup(
                        host_id=host.id, contactgroup_id=contactgroup.id)
                    host_to_contactgroup_relations.append(newhostcontactgroup)
        HostContact.save_all(contactgroup_to_service_relations)
        HostContactGroup.save_all(service_to_group_relations)

    restartNagios()
Example #4
0
    def post(self, jwt):
        OID_INTERFACE_COUNT = ".1.3.6.1.2.1.2.2.1.1"
        OID_IFDESCR = "1.3.6.1.2.1.2.2.1.2."
        OID_IFOPERSTATUS = "1.3.6.1.2.1.2.2.1.8."
        OID_IFSPEED = "1.3.6.1.2.1.2.2.1.5."
        OID_IFTYPE = "1.3.6.1.2.1.2.2.1.3."

        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()

                host_name = post_data.get('host_name')
                oid_type = post_data.get('snmp_type')

                data = []
                community_str = ""
                version_str = ""
                ip_str = ""

                if host_name is None:
                    return jsonify(error=True,
                                   msg="Missing host_name required field.")

                if oid_type is None:
                    return jsonify(error=True,
                                   msg="Missing OID type required field.")

                host = Host.get_by_hostname(host_name)
                if host is None:
                    return jsonify(error=True)
                else:
                    ip_str = host.address
                    # version_str = host._SNMPVERSION
                    version_str = "2c"
                    community_str = host._SNMPCOMMUNITY
                    if version_str is None or len(version_str) == 0:
                        return jsonify(error=True, msg="Missing SNMP version.")
                    if community_str is None or len(community_str) == 0:
                        return jsonify(error=True,
                                       msg="Missing SNMP community.")

                    # Get the bandwidth of interface
                    if oid_type == COMMON_SNTP_TRAFFIC:
                        # Request the interface list using snmpwalk tool
                        subout = subprocess.Popen([
                            'snmpwalk', '-Oqv', '-v', version_str, '-c',
                            community_str, ip_str, OID_INTERFACE_COUNT
                        ],
                                                  stdout=subprocess.PIPE,
                                                  stderr=subprocess.STDOUT,
                                                  universal_newlines=True)
                        stdout, stderr = subout.communicate()
                        inf_cnt_str = str(stdout)

                        time_pattern = re.compile("[Tt]imeout")
                        if time_pattern.search(inf_cnt_str):
                            obj = {
                                "index": "0",
                                "ifname": inf_cnt_str,
                                "status": "",
                                "speed": "",
                                "type": ""
                            }
                            data.append(obj)
                            return jsonify(data=data)

                        # Extract interface list from response
                        inf_cnt_list = inf_cnt_str.split('\n')
                        for i in inf_cnt_list:
                            if len(i) <= 0:
                                continue
                            subout = subprocess.Popen([
                                'snmpget', '-Oqv', '-v', version_str, '-c',
                                community_str, ip_str, OID_IFDESCR + str(i),
                                OID_IFOPERSTATUS + str(i),
                                OID_IFSPEED + str(i), OID_IFTYPE + str(i)
                            ],
                                                      stdout=subprocess.PIPE,
                                                      stderr=subprocess.STDOUT,
                                                      universal_newlines=True)
                            stdout, stderr = subout.communicate()
                            resp_str = str(stdout)
                            respList = resp_str.split('\n')
                            obj_status = ""
                            obj_type = ""

                            if respList[1] == "1":
                                obj_status = "Connected"
                            else:
                                obj_status = "Disconnected"

                            if respList[3] == "6":
                                obj_type = "Ethernet"
                            elif respList[3] == "24":
                                obj_type = "Loopback"
                            else:
                                obj_type = "Ethernet"

                            obj = {
                                "index":
                                str(i),
                                "ifname":
                                respList[0].replace("\"", "") if
                                (len(respList[0]) > 0) else respList[0],
                                "status":
                                obj_status,
                                "speed":
                                str(int(int(respList[2]) / 1000000)) +
                                " MBit/s",
                                "type":
                                obj_type
                            }

                            data.append(obj)

                        return jsonify(data=data)
                    elif oid_type == COMMON_SNTP_CPULOAD:
                        # process snmp cpu
                        return jsonify(data=data)
                    elif oid_type == COMMON_SNTP_MEMORY:
                        # process snmp memory
                        return jsonify(data=data)
                return jsonify(error=False)
            except Exception as e:
                return jsonify(error=True, msg=str(e))
        return jsonify(error=True)
Example #5
0
    def post(self, jwt):
        OID_CPU_LOAD_1 = "laLoad.1"
        OID_CPU_LOAD_5 = "laLoad.2"
        OID_CPU_LOAD_15 = "laLoad.3"

        OID_PHYSICAL_MEM = "hrStorageSize.1"
        OID_VIRTUAL_MEM = "hrStorageSize.3"
        OID_SWAP_MEM = "hrStorageSize.10"

        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()

                host_names = post_data.get('host_name')
                service_description = post_data.get('service_description')
                display_name = post_data.get('display_name')
                check_command_pre = post_data.get('check_command_pre')
                check_command_param = post_data.get('check_command_param')
                snmp_type = post_data.get('snmp_type', '')
                snmp_option = post_data.get('snmp_option')
                snmp_check = post_data.get('snmp_check')
                snmp_ifname = post_data.get('snmp_ifname')
                max_check_attempts = post_data.get('max_check_attempts')
                check_interval = post_data.get('check_interval')
                retry_interval = post_data.get('retry_interval')
                contacts = post_data.get('contacts')
                contact_groups = post_data.get('contact_groups')
                servicegroups = post_data.get('servicegroups')
                servicetemplates = post_data.get('use')
                warning_limit = post_data.get('warning_limit')
                critical_limit = post_data.get('critical_limit')

                host_name_str = ''
                service_group_str = ''
                contacts_str = ''
                contact_groups_str = ''
                servicetemplates_str = ''
                snmp_option_str = ''
                snmp_check_str = ''
                command_list = []

                if host_names is None:
                    return jsonify(error=True,
                                   msg="Missing host_name required field.")
                if service_description is None:
                    return jsonify(
                        error=True,
                        msg="Missing service_description required field.")
                if display_name is None:
                    display_name = service_description
                if check_command_pre is None:
                    return jsonify(error=True,
                                   msg="Missing check_command required field.")
                if max_check_attempts is None or not str(
                        max_check_attempts).isdigit():
                    max_check_attempts = 5
                if check_interval is None or not str(check_interval).isdigit():
                    check_interval = 60
                if retry_interval is None or not str(retry_interval).isdigit():
                    retry_interval = 1
                if warning_limit is None or warning_limit == '':
                    warning_limit = 100
                if critical_limit is None or critical_limit == '':
                    critical_limit = 200

                if host_names is not None and len(host_names) > 0:
                    temp_data_services = Service.get_by_description(
                        service_description)
                    # Check duplicate host for service_description
                    for tds in temp_data_services:
                        for hname in tds.host_name:
                            for name in host_names:
                                if name == hname:
                                    return jsonify(
                                        error=True,
                                        msg="Service host already exists.")
                    host_name_str = ','.join(host_names)

                if servicegroups is not None and len(servicegroups) > 0:
                    service_group_str = ','.join(servicegroups)
                if contacts is not None and len(contacts) > 0:
                    contacts_str = ','.join(contacts)
                if contact_groups is not None and len(contact_groups) > 0:
                    contact_groups_str = ','.join(contact_groups)

                if snmp_check is not None and len(snmp_check) > 0:
                    snmp_check_str = ','.join(snmp_check)

                if servicetemplates is not None and len(servicetemplates) > 0:
                    servicetemplates_str = ','.join(servicetemplates)

                if check_command_param is not None and len(
                        check_command_param) > 0:
                    check_command_str = check_command_pre + str(
                        check_command_param)
                    command_list.append(check_command_str)
                else:
                    check_command_str = check_command_pre
                    command = Command.get_by_commandname(check_command_pre)
                    if command is not None and command.command_line.find(
                            'check_snmp') != -1:
                        # Check existing host's community
                        host = Host.get_by_hostname(host_names)
                        if host is not None and len(host._SNMPCOMMUNITY) == 0:
                            return jsonify(
                                error=True,
                                msg="The community of host not exists.")

                        if snmp_type is not None and check_command_pre:
                            for option in snmp_option:
                                check_command_str = check_command_pre
                                temp = ""
                                if snmp_type == COMMON_SNTP_TRAFFIC:
                                    if snmp_check is not None and len(
                                            snmp_check) > 0:
                                        cnt = 0
                                        for check in snmp_check:
                                            cnt += 1
                                            if check == "ifUcastPkts":
                                                temp += "!ifHCInUcastPkts." + str(
                                                    option
                                                ) + "!ifHCOutUcastPkts." + str(
                                                    option) + "!" + str(
                                                        check_interval
                                                    ) + "!" + str(
                                                        warning_limit
                                                    ) + "!" + str(
                                                        critical_limit)
                                            elif check == "ifMulticastPkts":
                                                temp += "!ifHCInMulticastPkts." + str(
                                                    option
                                                ) + "!ifHCOutMulticastPkts." + str(
                                                    option) + "!" + str(
                                                        check_interval
                                                    ) + "!" + str(
                                                        warning_limit
                                                    ) + "!" + str(
                                                        critical_limit)
                                            elif check == "ifErrors":
                                                temp += "!ifInErrors." + str(
                                                    option
                                                ) + "!ifOutErrors." + str(
                                                    option) + "!" + str(
                                                        check_interval
                                                    ) + "!" + str(
                                                        warning_limit
                                                    ) + "!" + str(
                                                        critical_limit)
                                        if cnt == 3:
                                            temp = "!ifHCInOctets." + str(
                                                option
                                            ) + "!ifHCOutOctets." + str(
                                                option) + temp
                                    else:
                                        temp = "!ifHCInOctets." + str(
                                            option) + "!ifHCOutOctets." + str(
                                                option) + "!" + str(
                                                    check_interval
                                                ) + "!" + str(
                                                    warning_limit) + "!" + str(
                                                        critical_limit)
                                    check_command_str += temp
                                elif snmp_type == COMMON_SNTP_CPULOAD:
                                    temp = "!" + OID_CPU_LOAD_1 + "!" + OID_CPU_LOAD_5 + "!" + OID_CPU_LOAD_15
                                    check_command_str += temp
                                elif snmp_type == COMMON_SNTP_MEMORY:
                                    temp = "!" + OID_PHYSICAL_MEM + "!" + OID_VIRTUAL_MEM + "!" + OID_SWAP_MEM
                                    check_command_str += temp

                                command_list.append(check_command_str)
                    else:
                        command_list.append(check_command_str)

                idx = 0
                for one_command in command_list:
                    if len(snmp_option) > idx:
                        snmp_option_str = snmp_option[idx]
                    if len(command_list) > 1 and snmp_ifname:
                        service_name = service_description + "-" + snmp_ifname[
                            idx]
                        display_name = service_name
                    else:
                        service_name = service_description
                    idx += 1

                    # Create first Ping Service
                    newservice = Service(
                        host_name=host_name_str.strip(),
                        hostgroup_name=None,
                        service_description=service_name.strip(),
                        display_name=display_name.strip(),
                        importance=None,
                        servicegroups=service_group_str.strip(),
                        is_volatile=None,
                        check_command=one_command.strip(),
                        check_command_pre=check_command_pre.strip(),
                        check_command_param=check_command_param,
                        snmp_type=snmp_type.strip(),
                        snmp_option=snmp_option_str,
                        snmp_check=snmp_check_str,
                        max_check_attempts=max_check_attempts,
                        check_interval=str(check_interval),
                        retry_interval=retry_interval,
                        active_checks_enabled=True,
                        passive_checks_enabled=False,
                        check_period="24x7",
                        obsess_over_host=None,
                        check_freshness=None,
                        freshness_threshold=None,
                        event_handler=None,
                        event_handler_enabled=None,
                        low_flap_threshold=None,
                        high_flap_threshold=None,
                        flap_detection_enabled=None,
                        flap_detection_options=None,
                        process_perf_data=True,
                        retain_status_information=True,
                        retain_nonstatus_information=True,
                        contacts=contacts_str,
                        contact_groups=contact_groups_str,
                        notification_interval=60,
                        first_notification_delay=5,
                        notification_period="24x7",
                        notification_options="w,c,r",
                        notifications_enabled=True,
                        use=servicetemplates_str,
                        command=None,
                        retry_check_interval=None,
                        normal_check_interval=None,
                        name=None,
                        warning=warning_limit,
                        critical=str(critical_limit),
                    )

                    newservice.check_interval = round(
                        int(check_interval) / 60, 1)
                    service_id = newservice.save()
                    writeNagiosServicesConfigFile(newservice)
                    newservice.check_interval = str(check_interval)

                    # Create all relations
                    if host_names:
                        Service.create_hosts_relations(service_id, host_names)
                    if contacts:
                        Service.create_contacts_relations(service_id, contacts)
                    if contact_groups:
                        Service.create_contactgroups_relations(
                            service_id, contact_groups)
                    if servicegroups:
                        Service.create_servicegroups_relations(
                            service_id, servicegroups)
                    if servicetemplates:
                        Service.create_servicetemplate_relations(
                            service_id, servicetemplates)

                if not restartNagios():
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                return jsonify(data=newservice.serialize())
            except Exception as e:
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
        return jsonify(error=True)
Example #6
0
    def post(self, jwt):
        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()
                host_name = post_data.get('host_name')
                alias = post_data.get('alias')
                address = post_data.get('address')
                contact_groups = post_data.get('contact_groups')
                contacts = post_data.get('contacts')
                sms = post_data.get('sms')
                street_address = post_data.get('street_address', '')
                notes = post_data.get('notes')
                notes_url = post_data.get('notes_url')

                hosttemplates = post_data.get('use')
                host_templates_str = ""
                if hosttemplates is not None:
                    host_templates_str = ','.join(hosttemplates)
                notification_period = post_data.get('notification_period',
                                                    "24x7")
                notification_options = "d,u,r"
                if post_data.get('notification_options') is not None:
                    notification_options = ','.join(
                        post_data.get('notification_options'))
                notifications_enabled = 1 if post_data.get(
                    'notifications_enabled') == True else 0
                check_interval = post_data.get('check_interval', 5)
                retry_interval = post_data.get('retry_interval', 1)
                max_check_attempts = post_data.get('max_check_attempts', 5)
                notification_interval = post_data.get('notification_interval',
                                                      120)
                check_command = post_data.get('check_command',
                                              "check-host-alive")
                _SNMPVERSION = post_data.get('_SNMPVERSION', "2c")
                _SNMPCOMMUNITY = post_data.get('_SNMPCOMMUNITY', '')

                # Confirm this hostname doesn't already exist first.
                if Host.get_by_hostname(host_name):
                    return jsonify(error=True, msg="Hostname already exists.")

                if host_name is None:
                    return jsonify(error=True,
                                   msg="Missing host_name required field.")
                if alias is None:
                    return jsonify(error=True,
                                   msg="Missing alias required field.")
                if address is None:
                    return jsonify(error=True,
                                   msg="Missing address required field.")

                contacts_str = ''
                if contacts is not None and len(contacts) > 0:
                    contacts_str = ','.join(contacts)

                newhost = Host(host_name=host_name.strip(),
                               alias=alias.strip(),
                               display_name=None,
                               address=address.strip(),
                               importance=None,
                               check_command=check_command.strip(),
                               max_check_attempts=max_check_attempts,
                               check_interval=check_interval,
                               retry_interval=retry_interval,
                               active_checks_enabled=True,
                               passive_checks_enabled=True,
                               check_period="24x7",
                               obsess_over_host=False,
                               check_freshness=True,
                               freshness_threshold=None,
                               event_handler=None,
                               event_handler_enabled=None,
                               low_flap_threshold=None,
                               high_flap_threshold=None,
                               flap_detection_enabled=None,
                               flap_detection_options=None,
                               process_perf_data=True,
                               retain_status_information=True,
                               retain_nonstatus_information=True,
                               contacts=contacts_str,
                               contact_groups="",
                               notification_interval=notification_interval,
                               first_notification_delay=None,
                               notification_period=notification_period.strip(),
                               notification_options=notification_options,
                               notifications_enabled=notifications_enabled,
                               use=host_templates_str,
                               hostgroups="null",
                               street_address=street_address.strip(),
                               sms=sms.strip(),
                               notes=notes.strip(),
                               notes_url=notes_url.strip(),
                               icon_image='',
                               icon_image_alt='',
                               _SNMPVERSION=_SNMPVERSION,
                               _SNMPCOMMUNITY=_SNMPCOMMUNITY)
                host_id = newhost.save()

                newservice = Service(
                    host_name=host_name.strip(),
                    hostgroup_name=None,
                    service_description="PING",
                    display_name="PING",
                    importance=None,
                    servicegroups="",
                    is_volatile=None,
                    check_command="PING",
                    check_command_pre=None,
                    check_command_param=None,
                    snmp_type=None,
                    snmp_option=None,
                    snmp_check=None,
                    max_check_attempts=5,
                    check_interval=str(1),
                    retry_interval=1,
                    active_checks_enabled=True,
                    passive_checks_enabled=False,
                    check_period="24x7",
                    obsess_over_host=None,
                    check_freshness=None,
                    freshness_threshold=None,
                    event_handler=None,
                    event_handler_enabled=None,
                    low_flap_threshold=None,
                    high_flap_threshold=None,
                    flap_detection_enabled=None,
                    flap_detection_options=None,
                    process_perf_data=True,
                    retain_status_information=True,
                    retain_nonstatus_information=True,
                    contacts=contacts_str,
                    contact_groups="",
                    notification_interval=60,
                    first_notification_delay=5,
                    notification_period="24x7",
                    notification_options="w,c,r",
                    notifications_enabled=True,
                    use="",
                    command=None,
                    retry_check_interval=None,
                    normal_check_interval=None,
                    name=None,
                    warning=None,
                    critical=None,
                )
                service_id = newservice.save()

                # create relations
                if contacts:
                    Host.create_contacts_relations(host_id, contacts)
                    Service.create_contacts_relations(service_id, contacts)
                if contact_groups:
                    Host.create_contactgroups_relations(
                        host_id, contact_groups)
                    Service.create_contactgroups_relations(
                        service_id, contact_groups)
                if hosttemplates:
                    Host.create_hosttemplate_relations(host_id, hosttemplates)

                Service.create_hosts_relations(service_id, [host_name.strip()])

                writeNagiosConfigFile(newhost)
                writeNagiosServicesConfigFile(newservice)

                if not restartNagios():
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                return jsonify(data=newhost.serialize())
            except Exception as e:
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
        return jsonify(error=True)
Example #7
0
    def delete(self, jwt, host_name, host_id, page_id):
        # if host_name is None:
        #     return jsonify(error=True)

        if host_id is not None:
            host = Host.get_by_id(host_id)
        elif host_name is not None:
            host = Host.get_by_hostname(host_name)
        else:
            return jsonify(error=True)

        if host is None:
            return jsonify(error=True)
        else:
            try:
                host_id = host.id
                relations = HostService.query.filter_by(host_id=host_id).all()
                relation_service_ids = []
                if relations is not None:
                    for relation in relations:
                        relation_service_ids.append(relation.service_id)

                relationgroups = HostgroupHost.query.filter_by(
                    host_id=host_id).all()
                relation_hostgroup_ids = []
                if relationgroups is not None:
                    for relationgroup in relationgroups:
                        relation_hostgroup_ids.append(
                            relationgroup.hostgroup_id)

                # delete all relations

                Host.delete_all_host_service_relations(host_id)
                Host.delete_all_contact_relations(host_id)
                Host.delete_all_contactgroup_relations(host_id)
                Host.delete_all_host_template_relations(host_id)
                Host.delete_all_hostgroup_host_relations(host_id)

                host = Host.get_by_id(host_id)
                deleteNagiosConfigFile(host)
                host.delete()

                for relation in relation_service_ids:
                    service = Service.get_by_id(relation)
                    if not service:
                        continue
                    hosts = HostService.get_all_by_sevice(service.id)
                    if hosts:
                        host_ids = [h.id for h in hosts]
                        host_names_str = ','.join(host_ids)
                        service.host_name = host_names_str
                        tmp_check_interval = service.check_interval
                        service.check_interval = round(
                            int(service.check_interval) / 60, 1)
                        writeNagiosServicesConfigFile(service)
                        service.check_interval = tmp_check_interval
                        service.update()
                    else:
                        deleteNagiosServicesConfigFile(service)
                        service.delete()

                for relation in relation_hostgroup_ids:
                    host_group = Hostgroup.get_by_id(relation)
                    if not host_group:
                        continue
                    host_group_hosts = HostgroupHost.get_all_by_hostgroup(
                        host_group.id)
                    if host_group_hosts:
                        host_ids = [h.id for h in host_group_hosts]
                        host_names_str = ','.join(host_ids)
                        host_group.members = host_names_str
                        writeNagiosHostgroupsConfigFile(host_group)
                        host_group.update()
                    else:
                        deleteNagiosHostgroupsConfigFile(host_group)
                        host_group.delete()

                if not restartNagios():
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                return jsonify(error=False)
            except Exception as e:
                syncNagiosAllConfigWithDb()
                print(e.__dict__)
                return jsonify(error=True, msg=str(e))
Example #8
0
    def put(self, jwt, host_id, host_name, page_id):

        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()
                host = None
                hostname_org = None
                index = post_data.get('index')
                if index is not None:
                    host = Host.get_by_id(index)

                if host is None:
                    return jsonify(error=True)

                hostname_org = host.host_name
                host_name = post_data.get('host_name')
                alias = post_data.get('alias')
                address = post_data.get('address')
                contact_groups = post_data.get('contact_groups')
                contacts = post_data.get('contacts')
                sms = post_data.get('sms')
                street_address = post_data.get('street_address', '')
                notes = post_data.get('notes')
                notes_url = post_data.get('notes_url')

                hosttemplates = post_data.get('use')

                notification_period = "24x7"
                if post_data.get('notification_period') is not None and len(
                        post_data.get('notification_period')) > 0:
                    notification_period = post_data.get('notification_period')
                notification_options = "d,u,r"
                if post_data.get('notification_options') is not None and len(
                        post_data.get('notification_options')) > 0:
                    notification_options = ','.join(
                        post_data.get('notification_options'))
                notifications_enabled = 1
                if post_data.get('notifications_enabled') is not None and len(
                        str(post_data.get('notifications_enabled'))) > 0:
                    notifications_enabled = 1 if post_data.get(
                        'notifications_enabled') == True else 0
                check_interval = 5
                if post_data.get('check_interval') is not None and len(
                        str(post_data.get('check_interval'))) > 0:
                    check_interval = post_data.get('check_interval')
                retry_interval = 1
                if post_data.get('retry_interval') is not None and len(
                        str(post_data.get('retry_interval'))) > 0:
                    retry_interval = post_data.get('retry_interval')
                max_check_attempts = 5
                if post_data.get('max_check_attempts') is not None and len(
                        str(post_data.get('max_check_attempts'))) > 0:
                    max_check_attempts = post_data.get('max_check_attempts')
                notification_interval = 120
                if post_data.get('notification_interval') is not None and len(
                        str(post_data.get('notification_interval'))) > 0:
                    notification_interval = post_data.get(
                        'notification_interval')
                check_command = "check-host-alive"
                if post_data.get('check_command') is not None and len(
                        post_data.get('check_command')) > 0:
                    check_command = post_data.get('check_command')
                _SNMPVERSION = "2c"
                if post_data.get('_SNMPVERSION') is not None and len(
                        post_data.get('_SNMPVERSION')) > 0:
                    _SNMPVERSION = post_data.get('_SNMPVERSION')
                _SNMPCOMMUNITY = ""
                if post_data.get('_SNMPCOMMUNITY') is not None and len(
                        post_data.get('_SNMPCOMMUNITY')) > 0:
                    _SNMPCOMMUNITY = post_data.get('_SNMPCOMMUNITY')

                # Confirm this hostname doesn't already exist first.
                if hostname_org != host_name and Host.get_by_hostname(
                        host_name):
                    return jsonify(error=True, msg="Hostname already exists.")

                if host_name is None:
                    return jsonify(error=True,
                                   msg="Missing host_name required field.")
                if alias is None:
                    return jsonify(error=True,
                                   msg="Missing alias required field.")
                if address is None:
                    return jsonify(error=True,
                                   msg="Missing address required field.")

                host.host_name = host_name.strip()
                host.alias = alias.strip()
                host.address = address.strip()

                if contact_groups is not None:
                    host.contact_groups = ','.join(contact_groups)

                if contacts is not None:
                    host.contacts = ','.join(contacts)

                if sms is not None:
                    host.sms = sms.strip()

                if street_address is not None:
                    host.street_address = street_address.strip()

                if notes is not None:
                    host.notes = notes.strip()

                if notes_url is not None:
                    host.notes_url = notes_url.strip()

                host_templates_str = host.use
                if hosttemplates is not None:
                    host_templates_str = ','.join(hosttemplates)

                host.use = host_templates_str
                host.notification_period = notification_period.strip()
                host.notification_options = notification_options
                host.notifications_enabled = notifications_enabled
                host.check_interval = check_interval
                host.retry_interval = retry_interval
                host.max_check_attempts = max_check_attempts
                host.notification_interval = notification_interval
                host.check_command = check_command.strip()
                host._SNMPVERSION = _SNMPVERSION
                host._SNMPCOMMUNITY = _SNMPCOMMUNITY

                writeNagiosConfigFile(host)
                host_id = host.update()
                # update host_contact table
                Host.delete_all_contact_relations(host_id)
                Host.delete_all_contactgroup_relations(host_id)
                Host.delete_all_host_template_relations(host_id)

                Host.create_contacts_relations(host_id, contacts)
                Host.create_contactgroups_relations(host_id, contact_groups)
                Host.create_hosttemplate_relations(host_id, hosttemplates)

                # re-name of host in services table
                if hostname_org != host_name:
                    services = Service.get_by_hostname_keyword(hostname_org)
                    for service in services:
                        hostnames = service.host_name
                        hostnames = hostnames.replace(hostname_org,
                                                      host.host_name)
                        service.host_name = hostnames
                        tmp_checkInterval = service.check_interval
                        service.check_interval = round(
                            int(service.check_interval) / 60, 1)
                        writeNagiosServicesConfigFile(service)
                        service.check_interval = tmp_checkInterval
                        service.update()

                    # re-name of host in hostgroups table
                    hostgroups = Hostgroup.get_by_hostname_keyword(
                        hostname_org)
                    for hostgroup in hostgroups:
                        hostnames = hostgroup.members
                        hostnames = hostnames.replace(hostname_org,
                                                      host.host_name)
                        hostgroup.members = hostnames
                        hostgroup.update()
                        writeNagiosHostgroupsConfigFile(hostgroup)

                if not restartNagios():
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                if host_id:
                    host = Host.get_by_id(host_id)
                    return jsonify(data=host.serialize())
            except Exception as e:
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
        return jsonify(error=True)