Beispiel #1
0
    def put(self, jwt, contactgroup_id):
        if contactgroup_id is None:
            return jsonify(error=True)

        contactgroup = ContactGroup.get_by_id(contactgroup_id)
        if contactgroup is None:
            return jsonify(error=True)

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

                if contactgroup_name is not None:
                    contactgroup.contactgroup_name = contactgroup_name

                if alias is not None:
                    contactgroup.alias = alias

                writeNagiosContactGroupsConfigFile(contactgroup)
                if restartNagios() == False:
                    db.session.rollback()
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                db.session.commit()
                return jsonify(data=contactgroup.serialize())
            except Exception as e:
                db.session.rollback()
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
            finally:
                db.session.close()
        return jsonify(error=True)
Beispiel #2
0
    def get(self, jwt, contactgroup_id):
        data = []

        #If no contactgroup_id is passed in get all contactgroups.
        if contactgroup_id is None:
            contactgroups = ContactGroup.get_all()
        else:
            contactgroups = [ContactGroup.get_by_id(contactgroup_id)]

        #Loop over results and get json form of contactgroup to return.
        if contactgroups is not None:
            for contactgroup in contactgroups:
                data.append(contactgroup.serialize())
                pass
            return jsonify(data=data)
        else:
            return jsonify(data=[])
Beispiel #3
0
    def post(self, jwt):
        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()

                contactgroup_name = post_data.get('contactgroup_name')
                alias = post_data.get('alias')

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

                #Confirm this contactgroup_name doesn't already exist first.
                if ContactGroup.get_by_contactgroupname(contactgroup_name):
                    return jsonify(error=True,msg="Contactgroup name already exists.")

                newcontactgroup = ContactGroup(
                    contactgroup_name = contactgroup_name,
                    alias = alias,
                    members = None,
                    contactgroup_members = None
                )

                db.session.add(newcontactgroup)
                db.session.flush()
                writeNagiosContactGroupsConfigFile(newcontactgroup)
                if restartNagios() == False:
                    db.session.rollback()
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                db.session.commit()
                return jsonify(data=newcontactgroup.serialize())
            except Exception as e:
                db.session.rollback()
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
            finally:
                db.session.close()
        return jsonify(error=True)
Beispiel #4
0
def deleteNagiosContactsConfigFile(newcontact):
    """
    Delete contact *.cfg file
    """
    try:
        os.remove("/nagiosetc/conf.d/contacts/" + str(newcontact.id) + ".cfg")

        contactgroups = ContactGroup.get_all()
        for group in contactgroups:
            writeNagiosContactGroupsConfigFile(group)
        return True
    except OSError:
        pass
    return False
Beispiel #5
0
def writeNagiosContactsConfigFile(newcontact):
    """
    Add/Edit contact *.cfg file
    """
    output_from_parsed_template = render_template(
        'generate_contacts_config.j2', contact=newcontact)
    filename = "/nagiosetc/conf.d/contacts/" + str(newcontact.id) + ".cfg"
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "w") as f:
        f.write(output_from_parsed_template)

    contactgroups = ContactGroup.get_all()
    for group in contactgroups:
        writeNagiosContactGroupsConfigFile(group)
    return True
Beispiel #6
0
    def post(self, jwt):
        data = []
        order = None

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

        contactgroups = ContactGroup.search(order)

        #Loop over results and get json form of contactgroup to return.
        if contactgroups is not None:
            for contactgroup in contactgroups:
                data.append(contactgroup.serialize())
                pass
            return jsonify(data=data)
        else:
            return jsonify(data=[])
Beispiel #7
0
        names_list[random.randrange(0, len(names_list))].capitalize()
        for i in range(0, size)
    ]
    return " ".join(name_lst)


role_admin = appbuilder.sm.find_role(appbuilder.sm.auth_role_admin)
user1 = appbuilder.sm.add_user('user1', 'user1', 'test', '*****@*****.**',
                               role_admin, 'password')
user2 = appbuilder.sm.add_user('user2', 'user2', 'test', '*****@*****.**',
                               role_admin, 'password')
user3 = appbuilder.sm.add_user('user3', 'user3', 'test', '*****@*****.**',
                               role_admin, 'password')

try:
    db.session.add(ContactGroup(name='Friends'))
    db.session.add(ContactGroup(name='Family'))
    db.session.add(ContactGroup(name='Work'))
    db.session.commit()
except Exception, e:
    log.error('Group creation error: %s', e)
    db.session.rollback()
    exit(1)

try:
    db.session.add(Gender(name='Male'))
    db.session.add(Gender(name='Female'))
    db.session.commit()
except Exception, e:
    log.error('Gender creation error: %s', e)
    db.session.rollback()
Beispiel #8
0
        for i in range(0, size)
    ]
    return " ".join(name_lst)


try:
    db.session.query(Contact).delete()
    db.session.query(Gender).delete()
    db.session.query(ContactGroup).delete()
    db.session.commit()
except:
    db.session.rollback()

try:
    groups = list()
    groups.append(ContactGroup(name="Friends"))
    groups.append(ContactGroup(name="Work"))
    db.session.add(groups[0])
    db.session.add(groups[1])
    db.session.commit()

    sub_groups = list()
    sub_groups.append(
        ContactSubGroup(name="Close Friends", contact_group=groups[0]))
    sub_groups.append(
        ContactSubGroup(name="Long time no see", contact_group=groups[0]))
    sub_groups.append(ContactSubGroup(name="BBIC", contact_group=groups[1]))
    sub_groups.append(ContactSubGroup(name="Miniclip",
                                      contact_group=groups[1]))
    db.session.add(sub_groups[0])
    db.session.add(sub_groups[1])
Beispiel #9
0
from app.models import ContactGroup, Gender, Contact
import random
from datetime import datetime


def get_random_name(names_list, size=1):
    name_lst = [
        names_list[random.randrange(
            0, len(names_list))].decode("utf-8").capitalize()
        for i in range(0, size)
    ]
    return " ".join(name_lst)


ContactGroup.drop_collection()
Gender.drop_collection()
Contact.drop_collection()

g1 = ContactGroup(name="Friends").save()
g2 = ContactGroup(name="Family").save()
g3 = ContactGroup(name="Work").save()
groups = [g1, g2, g3]

gender1 = Gender(name="Male").save()
gender2 = Gender(name="Female").save()
genders = [gender1, gender2]

f = open("NAMES.DIC", "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()
Beispiel #10
0
from app.models import ContactGroup, Gender, Contact
import random
from datetime import datetime


def get_random_name(names_list, size=1):
    name_lst = [
        names_list[random.randrange(0, len(names_list))].capitalize()
        for i in range(0, size)
    ]
    return " ".join(name_lst)


ContactGroup.drop_collection()
Gender.drop_collection()
Contact.drop_collection()

g1 = ContactGroup(name='Friends').save()
g2 = ContactGroup(name='Family').save()
g3 = ContactGroup(name='Work').save()
groups = [g1, g2, g3]

gender1 = Gender(name='Male').save()
gender2 = Gender(name='Female').save()
genders = [gender1, gender2]

f = open('NAMES.DIC', "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()
Beispiel #11
0
from app.models import ContactGroup, Gender, Contact
import random
from datetime import datetime


def get_random_name(names_list, size=1):
    name_lst = [names_list[random.randrange(0, len(names_list))].capitalize() for i in range(0, size)]
    return " ".join(name_lst)

ContactGroup.drop_collection()
Gender.drop_collection()
Contact.drop_collection()

g1 = ContactGroup(name='Friends').save()
g2 = ContactGroup(name='Family').save()
g3 = ContactGroup(name='Work').save()
groups = [g1,g2,g3]

gender1 = Gender(name='Male').save()
gender2 = Gender(name='Female').save()
genders = [gender1, gender2]

f = open('NAMES.DIC', "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()

for i in range(1, 1000):
    c = Contact()
    c.name = get_random_name(names_list, random.randrange(2, 6))
    c.address = 'Street ' + names_list[random.randrange(0, len(names_list))]
Beispiel #12
0
    def post(self, jwt):
        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()

                contact_name = post_data.get('contact_name')
                alias = post_data.get('alias')
                email = post_data.get('email')
                text_number = int(post_data.get('_text_number')) if post_data.get('_text_number') else None
                contactgroups = post_data.get('contactgroups')
                contacttemplates = post_data.get('use')
                host_notifications_enabled = 1 if post_data.get('host_notifications_enabled') == True else 0
                host_notification_period = post_data.get('host_notification_period')
                host_notification_options = ','.join(post_data.get('host_notification_options'))
                host_notification_commands = 'notify-host-by-email'
                if len(post_data.get('host_notification_commands')) > 0:
                    host_notification_commands = ','.join(post_data.get('host_notification_commands'))
                service_notifications_enabled = 1 if post_data.get('service_notifications_enabled') == True else 0
                service_notification_period = post_data.get('service_notification_period')
                service_notification_commands = 'notify-service-by-email'
                if len(post_data.get('service_notification_commands')) > 0:
                    service_notification_commands = ','.join(post_data.get('service_notification_commands'))
                # service_notification_options = ','.join(post_data.get('service_notification_options'))
                service_notification_options = 1
                contactgroups_str = ''
                contacttemplates_str = ''

                #Confirm this contact_name doesn't already exist first.
                if Contact.get_by_contactname(contact_name):
                    return jsonify(error=True, msg="Contact name already exists.")

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

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

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

                newcontact = Contact(
                    contact_name=contact_name,
                     alias=alias,
                     contactgroups=contactgroups_str,
                     minimum_importance=1,
                     host_notifications_enabled=host_notifications_enabled,
                     service_notifications_enabled=service_notifications_enabled,
                     host_notification_period=host_notification_period,
                     service_notification_period=service_notification_period,
                     host_notification_options=host_notification_options,
                     service_notification_options=service_notification_options,
                     host_notification_commands=host_notification_commands,
                     service_notification_commands=service_notification_commands,
                     email=email,
                     pager="",
                     addressx="",
                     can_submit_commands=1,
                     retain_status_information=1,
                     retain_nonstatus_information=1,
                     use=contacttemplates_str,
                     text_number=text_number
                )
                db.session.add(newcontact)
                db.session.flush()
                writeNagiosContactsConfigFile(newcontact)

                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 = newcontact.id,
                        contactgroup_id = contactgroup.id
                    )
                    db.session.add(newrelation)
                    db.session.flush()

                    # update members field of contactgroups table
                    contact_names_str = ""
                    connection = db.session.connection()
                    result = connection.execute(
                        "SELECT GROUP_CONCAT(B.contact_name) contact_names FROM contact_contactgroup A" +
                        " LEFT JOIN contacts B ON A.contact_id=B.id" +
                        " WHERE A.contactgroup_id = '%s'" +
                        " GROUP BY A.contactgroup_id"
                        , (contactgroup.id))
                    for row in result:
                        contact_names_str = row['contact_names']
                        contactgroup.members = contact_names_str
                        writeNagiosContactGroupsConfigFile(contactgroup)
                        break

                for contacttemplate_name in contacttemplates:
                    contacttemplate = ContactTemplate.get_by_contacttemplatename(contacttemplate_name)
                    if contacttemplate is None:
                        continue

                    # insert contact_contacttemplate table
                    newrelation = Contact2Template(
                        contact_id = newcontact.id,
                        contacttemplate_id = contacttemplate.id
                    )
                    db.session.add(newrelation)
                    db.session.flush()

                if restartNagios() == False:
                    db.session.rollback()
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                db.session.commit()
                return jsonify(data=newcontact.serialize())
            except Exception as e:
                db.session.rollback()
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
            finally:
                db.session.close()
        return jsonify(error=True)
Beispiel #13
0
    def put(self, jwt, contact_id):
        if contact_id is None:
            return jsonify(error=True)

        contact = Contact.get_by_id(contact_id)
        if contact is None:
            return jsonify(error=True)

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

                contact_name = post_data.get('contact_name')
                alias = post_data.get('alias')
                email = post_data.get('email')
                text_number = int(post_data.get('_text_number')) if post_data.get('_text_number') else None
                contactgroups = post_data.get('contactgroups')
                contacttemplates = post_data.get('use')
                host_notifications_enabled = 1 if post_data.get('host_notifications_enabled') == True else 0
                host_notification_period = post_data.get('host_notification_period')
                host_notification_options = ','.join(post_data.get('host_notification_options'))
                host_notification_commands = 'notify-host-by-email'
                if len(post_data.get('host_notification_commands')) > 0:
                    host_notification_commands = ','.join(post_data.get('host_notification_commands'))
                service_notifications_enabled = 1 if post_data.get('service_notifications_enabled') == True else 0
                service_notification_period = post_data.get('service_notification_period')
                service_notification_commands = 'notify-service-by-email'
                if len(post_data.get('service_notification_commands')) > 0:
                    service_notification_commands = ','.join(post_data.get('service_notification_commands'))
                # service_notification_options = ','.join(post_data.get('service_notification_options'))
                service_notification_options = 1
                contactgroup_names_to_update = []

                if contact.contactgroups:
                    contactgroup_names_to_update = contactgroup_names_to_update + contact.contactgroups.split(',')
                if contactgroups:
                    contactgroup_names_to_update = contactgroup_names_to_update + contactgroups

                if contact_name is not None:
                    contact.contact_name = contact_name

                if alias is not None:
                    contact.alias = alias

                if email is not None:
                    contact.email = email

                if text_number is not None:
                    contact.text_number = text_number

                if contactgroups is not None:
                    contact.contactgroups = ','.join(contactgroups)

                if contacttemplates is not None:
                    contact.use = ','.join(contacttemplates)

                if host_notifications_enabled is not None:
                    contact.host_notifications_enabled = host_notifications_enabled

                if host_notification_options is not None:
                    contact.host_notification_options = host_notification_options

                if host_notification_commands is not None:
                    contact.host_notification_commands = host_notification_commands

                if host_notification_period is not None:
                    contact.host_notification_period = host_notification_period

                if service_notifications_enabled is not None:
                    contact.service_notifications_enabled = service_notifications_enabled

                if service_notification_period is not None:
                    contact.service_notification_period = service_notification_period

                if service_notification_commands is not None:
                    contact.service_notification_commands = service_notification_commands

                if service_notification_options is not None:
                    contact.service_notification_options = service_notification_options

                writeNagiosContactsConfigFile(contact)

                # update contact_contactgroup table
                connection = db.session.connection()
                connection.execute("DELETE FROM contact_contactgroup WHERE contact_id = '%s'", (contact.id))

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

                    newrelation = Contact2Group(
                        contact_id = contact.id,
                        contactgroup_id = contactgroup.id
                    )
                    db.session.add(newrelation)
                    db.session.flush()

                # update contact_contacttemplate table
                connection = db.session.connection()
                connection.execute("DELETE FROM contact_contacttemplate WHERE contact_id = '%s'", (contact.id))

                for contacttemplate_name in contacttemplates:
                    contacttemplate = ContactTemplate.get_by_contacttemplatename(contacttemplate_name)
                    if contacttemplate is None:
                        continue

                    # insert contact_contacttemplate table
                    newrelation = Contact2Template(
                        contact_id = contact.id,
                        contacttemplate_id = contacttemplate.id
                    )
                    db.session.add(newrelation)
                    db.session.flush()

                # update members field of contactgroups table
                for contactgroup_name in contactgroup_names_to_update:
                    contactgroup = ContactGroup.get_by_contactgroupname(contactgroup_name)
                    if contactgroup is None:
                        continue

                    contact_names_str = ""
                    connection = db.session.connection()
                    result = connection.execute(
                        "SELECT GROUP_CONCAT(B.contact_name) contact_names FROM contact_contactgroup A" +
                        " LEFT JOIN contacts B ON A.contact_id=B.id" +
                        " WHERE A.contactgroup_id = '%s'" +
                        " GROUP BY A.contactgroup_id"
                        , (contactgroup.id))
                    if len(result._saved_cursor._result.rows) == 0:
                       contactgroup.members = None
                       writeNagiosContactGroupsConfigFile(contactgroup)
                    else:
                        for row in result:
                            contact_names_str = row['contact_names']
                            contactgroup.members = contact_names_str
                            writeNagiosContactGroupsConfigFile(contactgroup)
                            break

                if restartNagios() == False:
                    db.session.rollback()
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")

                db.session.commit()
                return jsonify(data=contact.serialize())
            except Exception as e:
                db.session.rollback()
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
            finally:
                db.session.close()
        return jsonify(error=True)
Beispiel #14
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()
Beispiel #15
0
        names_list[random.randrange(0, len(names_list))].capitalize()
        for i in range(0, size)
    ]
    return " ".join(name_lst)


try:
    db.session.query(Contact).delete()
    db.session.query(ContactGroup).delete()
    db.session.commit()
except:
    db.session.rollback()

try:
    groups = list()
    groups.append(ContactGroup(name='Friends'))
    groups.append(ContactGroup(name='Family'))
    groups.append(ContactGroup(name='Work'))
    db.session.add(groups[0])
    db.session.add(groups[1])
    db.session.add(groups[2])
    print(groups[0].id)
    db.session.commit()
except Exception as e:
    log.error("Creating Groups: %s", e)
    db.session.rollback()

f = open('NAMES.DIC', "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()
Beispiel #16
0
from app.models import ContactGroup, Gender, Contact
import random
from datetime import datetime


def get_random_name(names_list, size=1):
    name_lst = [
        names_list[random.randrange(
            0, len(names_list))].decode("utf-8").capitalize()
        for i in range(0, size)
    ]
    return " ".join(name_lst)


try:
    db.session.add(ContactGroup(name="Friends"))
    db.session.add(ContactGroup(name="Family"))
    db.session.add(ContactGroup(name="Work"))
    db.session.commit()
except:
    db.session.rollback()

try:
    db.session.add(Gender(name="Male"))
    db.session.add(Gender(name="Female"))
    db.session.commit()
except:
    db.session.rollback()

f = open("NAMES.DIC", "rb")
names_list = [x.strip() for x in f.readlines()]
Beispiel #17
0
    def delete(self, jwt, contactgroup_id):
        if contactgroup_id is None:
            return jsonify(error=True)

        contactgroup = ContactGroup.get_by_id(contactgroup_id)
        if contactgroup is None:
            return jsonify(error=True)
        else:
            try:
                deleteNagiosContactGroupsConfigFile(contactgroup)
                db.session.delete(contactgroup)

                # process contact_contactgroup table
                relations = Contact2Group.query.filter_by(contactgroup_id=contactgroup_id).all()
                relation_contact_ids = []
                if relations is not None:
                    for relation in relations:
                        relation_contact_ids.append(relation.contact_id)

                # delete from contact_contactgroup table
                connection = db.session.connection()
                connection.execute("DELETE FROM contact_contactgroup WHERE contactgroup_id = '%s'", (contactgroup_id))

                # update contact table
                for relation_contact_id in relation_contact_ids:
                    contact = Contact.get_by_id(relation_contact_id)
                    if contact is None:
                        continue

                    connection = db.session.connection()
                    result = connection.execute(
                        "SELECT GROUP_CONCAT(B.contactgroup_name) contactgroup_names FROM contact_contactgroup A" +
                        " LEFT JOIN contactgroups B ON A.contactgroup_id=B.id" +
                        " WHERE A.contact_id = '%s'" +
                        " GROUP BY A.contact_id"
                        , (contact.id))
                    if len(result._saved_cursor._result.rows) == 0:
                        contact.contactgroups = ''
                        writeNagiosContactsConfigFile(contact)
                    else:
                        for row in result:
                            contactgroup_names_str = row['contactgroup_names']
                            contact.contactgroups = contactgroup_names_str
                            writeNagiosContactsConfigFile(contact)
                            break

                # process contactgroup_service table
                csrelations = ContactgroupService.query.filter_by(contactgroup_id=contactgroup_id).all()
                relation_service_ids = []
                if csrelations is not None:
                    for csrelation in csrelations:
                        relation_service_ids.append(csrelation.service_id)

                # delete from contactgroup_service table
                connection = db.session.connection()
                connection.execute("DELETE FROM contactgroup_service WHERE contactgroup_id = '%s'", (contactgroup_id))

                # update service table
                for relation_service_id in relation_service_ids:
                    service = Service.get_by_id(relation_service_id)
                    if service is None:
                        continue

                    connection = db.session.connection()
                    result = connection.execute(
                        "SELECT GROUP_CONCAT(B.contactgroup_name) contactgroup_names FROM contactgroup_service A" +
                        " LEFT JOIN contactgroups B ON A.contactgroup_id=B.id" +
                        " WHERE A.service_id = '%s'" +
                        " GROUP BY A.service_id"
                        , (service.id))
                    if len(result._saved_cursor._result.rows) == 0:
                        service.contact_groups = ''
                        tmp_checkInterval = service.check_interval
                        service.check_interval = round(int(service.check_interval) / 60, 1)
                        writeNagiosServicesConfigFile(service)
                        service.check_interval = tmp_checkInterval
                    else:
                        for row in result:
                            contactgroup_names_str = row['contactgroup_names']
                            service.contact_groups = contactgroup_names_str
                            tmp_checkInterval = service.check_interval
                            service.check_interval = round(int(service.check_interval) / 60, 1)
                            writeNagiosServicesConfigFile(service)
                            service.check_interval = tmp_checkInterval
                            break

                if restartNagios() == False:
                    db.session.rollback()
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")
                    
                db.session.commit()
                return jsonify(error=False)
            except Exception as e:
                db.session.rollback()
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
            finally:
                db.session.close()
        return jsonify(error=True)