Ejemplo n.º 1
0
    def delete(self, jwt, command_id):
        if command_id is None:
            return jsonify(error=True)

        command = Command.get_by_id(command_id)
        if command is None:
            return jsonify(error=True)
        else:
            try:
                # check if services exist related to this command
                services = Service.get_all_by_command_name(command.command_name)
                if services is not None and len(services) > 0:
                    return jsonify(error=True,msg="Failed to delete because there are services that's using the command!")

                deleteNagiosCommandsConfigFile(command)
                db.session.delete(command)
                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)
Ejemplo n.º 2
0
def create_commands(status=Command.DELIVERED, count=5):
    if status not in [Command.DELIVERED, Command.NEVER_DELIVERED]:
        raise Exception('Command.DELIVERED Command.NEVER_DELIVERED')

    shops = Shop.query.all()
    managers = User.query.filter_by(is_manager=True).all()

    for _ in range(count):
        sended_minute = random.randint(MINUTE_MIN_SENDED, MINUTE_MAX_SENDED)
        recieved_minute = random.randint(MINUTE_MIN_RECIEVED,
                                         MINUTE_MAX_RECIEVED)

        sended = datetime.now() - timedelta(minutes=sended_minute)
        recieved = sended + timedelta(minutes=recieved_minute)

        delivery_address = config['COMPANY_ADDRESS']
        shop = random.choice(shops)
        user = random.choice(managers)

        command = Command(delivery_address=delivery_address,
                          sended=sended,
                          recieved=recieved,
                          status=status,
                          shop=shop,
                          user=user)
        db.session.add(command)
    try:
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
Ejemplo n.º 3
0
def randomize_last_command_orders():
    ''' update order for each commands '''
    command = Command.last().empty_orders()
    employees = Employee.query.all()
    orders = []

    foods = command.shop.foods.filter_by(extra=False).all()
    foods_extra = command.shop.foods.filter_by(extra=True).all()
    extra_count = random.randint(
        0, (math.floor(Employee.query.count() * RATE_EXTRA_ORDER) + 1))

    for employee in employees:
        employee_count = random.randint(RATE_EMPLOYEE_COMMANDED_MIN,
                                        RATE_EMPLOYEE_COMMANDED_MAX)
        orders += [
            Order(food=random.choice(foods),
                  command=command,
                  employee=employee) for _ in range(employee_count)
        ]

    for food_extra in foods_extra:
        extra_count = random.randint(RATE_EXTRA_COMMANDED_MIN,
                                     RATE_EXTRA_COMMANDED_MAX)
        orders += [
            Order(food=food_extra, command=command) for _ in range(extra_count)
        ]

    db.session.add_all(orders)
    db.session.commit()
Ejemplo n.º 4
0
def createCommand():
    i = input('Enter Client ID: ')
    c = Command('aaa','bbb')
    u = Client.query.filter_by(id=int(i)).first()
    u.commands.append(c)
    db.session.add(c)
    db.session.commit()
Ejemplo n.º 5
0
    def put(self, jwt, command_id):
        if command_id is None:
            return jsonify(error=True)

        command = Command.get_by_id(command_id)
        if command 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()

                command_line = post_data.get('command_line')

                if not command_line:
                    return jsonify(error=True,msg="Command line empty.")

                command.command_line = command_line

                writeNagiosCommandsConfigFile(command)
                if restartNagios() == False:
                    db.session.rollback()
                    syncNagiosAllConfigWithDb()
                    return jsonify(error=True, msg="Invalid process")
                    
                db.session.commit()
                return jsonify(data=command.serialize())
            except Exception as e:
                db.session.rollback()
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
            finally:
                db.session.close()
        return jsonify(error=True)
Ejemplo n.º 6
0
    def get(self, jwt, command_id):
        data = []

        #If no command_id is passed in get all commands.
        if command_id is None:
            commands = Command.get_all()
        else:
            commands = [Command.get_by_id(command_id)]

        #Loop over results and get json form of command to return.
        if commands is not None:
            for command in commands:
                data.append(command.serialize())
                pass
            return jsonify(data=data)
        else:
            return jsonify(data=[])
Ejemplo n.º 7
0
 def execute_command(self, cmd):
     """ Executes a command on a client """
     client = Client.query.filter_by(id=self.current_client_id).first()
     c = Command(cmd)
     client.commands.append(c)
     db.session.add(c)
     db.session.commit()
     print('Added task successfully.')
Ejemplo n.º 8
0
def command_prepare():
    '''Register a new command'''
    delivery_address = app.config['COMPANY_ADDRESS']
    shop_id = input('shop id: ')
    user_id = input('user id:')
    db.session.add(
        Command(delivery_address=delivery_address,
                shop_id=shop_id,
                user_id=user_id))
Ejemplo n.º 9
0
def parseCommand(commandDict):
    name = commandDict['name']
    decodeType = commandDict['decode_type']
    value = commandDict['value']
    rawLen = commandDict['rawLen']
    bitLen = commandDict['bitLen']
    raw = ",".join([str(val) for val in commandDict['raw']])
    pos = commandDict['pos']

    return Command(name, decodeType, value, raw, rawLen, bitLen, pos)
Ejemplo n.º 10
0
    def execute_command(self, cmd):
        """ Executes a command on a client """

        client = Client.query.filter_by(id=self.current_client_id).first()
        c = Command(cmd)
        client.commands.append(c)
        db.session.add(c)
        db.session.commit()
        print(
            '{colors.italics}{colors.fg.lightgrey}Added task successfully.{colors.reset}'
            .format(colors=Colors))
Ejemplo n.º 11
0
    def post(self, jwt):
        if request.is_json and request.get_json(silent=True) is not None:
            try:
                post_data = request.get_json()

                command_name = post_data.get('command_name')
                command_line = post_data.get('command_line')

                # check if input data is empty
                if not command_name:
                    return jsonify(error=True,msg="Command name empty.")
                if not command_line:
                    return jsonify(error=True,msg="Command line empty.")

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

                newcommand = Command(
                    command_name = command_name,
                    command_line = command_line
                )

                db.session.add(newcommand)

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

                db.session.commit()
                return jsonify(data=newcommand.serialize())
            except Exception as e:
                db.session.rollback()
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
            finally:
                db.session.close()
        return jsonify(error=True)
Ejemplo n.º 12
0
def index():
    form = CmdForm()

    if form.validate_on_submit():
        if current_user.admin == 0:
            flash('You are not an admin. Please request to be an admin.')
        if current_user.admin == 1:
            cmdnew = Command(name=form.cmdname.data,
                             context=form.context.data,
                             value=form.cmdvalue.data,
                             author=current_user.username,
                             help=form.help.data)
            db.create_all()
            db.session.add(cmdnew)
            db.session.commit()
            flash('Command successfully added')
            redirect(url_for('command_list'))
    return render_template('index.html', title='Home', form=form)
Ejemplo n.º 13
0
def make_shell_context():
    return dict(
        app=app,
        current_user=current_user,
        auth=auth,
        fx=fx,
        fk=fx.fk,
        db=db,
        User=User,
        Employee=Employee,
        Shop=Shop,
        Food=Food,
        Order=Order,
        Command=Command,
        l=Command.last(),
        datetime=datetime,
        date=date,
        timedelta=timedelta,
    )
Ejemplo n.º 14
0
    def to_engine():
        while True:
            try:
                print '================to engine:================'
                ssl_connect()

                for item in Command.select().where(Command.status.is_null(True)).order_by('timestamp').limit(10):
                    try:
                        if item.raw:
                            binascii.unhexlify(item.raw)
                            g_ssl_sock.sendall(binascii.unhexlify(item.raw))
                    except:
                        continue

                gevent.sleep(10)
            except:
                traceback.print_exc()
                ssl_close()
                gevent.sleep(5)
                print '================================'
Ejemplo n.º 15
0
def commands(server_id):
    """
    Commands on specified server
    :param server_id: ID for the selected server
    :return: renders template for commands based on server ID
    """
    commands = Command.query.filter_by(server_id_fk=server_id).all()
    server = Server.query.filter_by(id=server_id).first()
    form = CommandForm()
    if form.validate_on_submit():
        command = Command(command=form.command.data,
                          expectation=form.expectation.data,
                          server_id_fk=server_id)
        db.session.add(command)
        db.session.commit()
        return redirect(url_for('commands', server_id=server_id))
    return render_template('commands.html',
                           commands=commands,
                           server=server,
                           form=form)
Ejemplo n.º 16
0
def command_wait():
    '''Set the current command status to wait'''
    Command.last().wait()
Ejemplo n.º 17
0
def command_prepare_auto():
    '''Register a command with user_id = 1 and shop_id = 1'''
    delivery_address = app.config['COMPANY_ADDRESS']
    db.session.add(
        Command(delivery_address=delivery_address, shop_id=1, user_id=1))
Ejemplo n.º 18
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()
Ejemplo n.º 19
0
def command_never_delivered():
    '''Set the current command status to not delivered'''
    Command.last().delivered()
Ejemplo n.º 20
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)
Ejemplo n.º 21
0
def create_job():

    start = time.time()

    data = request.get_json(force=True) or {}

    # Validate data
    if not _is_valid(data, constants.JOB_REQ):
        return error_response(400, 'Missing values.')

    analyst = Analyst.query.get(data['analyst_id'])

    if data['targets'] == 'all':
        query = db.session.query(Worker.target_queue).all()
        targets = [hostname[0] for hostname in query]
        data['targets'] = targets
    else:
        targets = data['targets']

    # Save job into db
    job = Job()
    job.from_dict(data)
    analyst.jobs.append(job)

    db.session.add(analyst)

    # Flushing data base to retrieve job id.
    db.session.flush()

    command_list = data['description']

    job_request = job.to_dict()

    queue = RQueue()

    if len(command_list) > 0:
        for target_queue in targets:
            worker = Worker.query.filter_by(target_queue=target_queue).first()
            for i, cmd in enumerate(command_list):
                command = Command()
                command.from_dict(cmd,
                                  job_id=job.job_id,
                                  worker_id=worker.worker_id)
                db.session.add(command)
                db.session.flush()

                job_request['description'][i][
                    'command_id'] = command.command_id

            job_request['targets'] = target_queue

            # Send job request to queue
            db.session.commit()
            if not queue.send_job(job_request):
                return error_response(
                    500, 'Error while sending message to message broker')

    else:
        return error_response(400, 'A job must contain at least one command.')

    queue.close()

    # Once the queue receives the command, return response.
    response = jsonify(job_request)
    response.status_code = 202

    print(time.time() - start)

    return response
Ejemplo n.º 22
0
def addcmd(json):
    c = Command()
    try:
        c.number = Command.query.filter_by(
            date=datetime.datetime.now().date()).order_by(
                Command.number.desc()).first().number + 1
    except AttributeError:
        c.number = 1
    if all(i in json and json[i] for i in ["firstname", "lastname", "client"]):
        db.session.add(
            User(username=json["client"],
                 firstname=json["firstname"],
                 lastname=json["lastname"]))
    if "client" in json:
        try:
            c.client_id = User.query.filter_by(
                username=json["client"]).first().id
        except AttributeError:
            c.client_id = User.query.filter_by(username="******").first().id
    if "pc" in json:
        try:
            c.pc_id = User.query.filter_by(username=json["pc"]).first().id
        except AttributeError:
            c.pc_id = User.query.filter_by(username="******").first().id
    if "price" in json:
        try:
            c.price = json["price"]
        except AttributeError:
            c.price = -1
    else:
        c.price = -1
    if "plate" in json:
        try:
            c.plate_id = Plate.query.get(json["plate"]).id
        except AttributeError:
            pass
    if "ingredient" in json:
        for i in json["ingredient"]:
            try:
                c.content.append(Ingredient.query.get(i))
            except AttributeError:
                pass
    if "sauce" in json:
        for s in json["sauce"]:
            try:
                c.sauce.append(Sauce.query.get(s))
            except AttributeError:
                pass
    if "drink" in json:
        try:
            c.drink_id = Drink.query.get(json["drink"]).id
        except AttributeError:
            pass
    if "dessert" in json:
        try:
            c.dessert_id = Dessert.query.get(json["dessert"]).id
        except AttributeError:
            pass
    db.session.add(c)
    db.session.commit()
    emit("new command", command_json(c), broadcast=True)
Ejemplo n.º 23
0
    def put(self, jwt, service_id):
        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 service_id is None:
            return jsonify(error=True)

        service = Service.get_by_id(service_id)
        if service 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()

                host_name = 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')
                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')

                servicegroup_names_to_update = []

                if service.servicegroups:
                    servicegroup_names_to_update = servicegroup_names_to_update + service.servicegroups.split(
                        ',')
                if servicegroups:
                    servicegroup_names_to_update = servicegroup_names_to_update + servicegroups

                if host_name:
                    service.host_name = ','.join(host_name)

                if service_description is not None:
                    service.service_description = service_description.strip()

                if check_command_pre is not None:
                    service.check_command_pre = check_command_pre.strip()
                    if service.check_command_param is not None:
                        if snmp_type != COMMON_SNTP_TRAFFIC:
                            service.check_command = check_command_pre + service.check_command_param.strip(
                            )
                    else:
                        service.check_command = check_command_pre.strip()

                if check_command_param is not None and len(
                        check_command_param) > 0:
                    service.check_command_param = check_command_param.strip()
                    service.check_command = service.check_command_pre + check_command_param.strip(
                    )

                command = Command.get_by_commandname(check_command_pre)
                if command is not None and command.command_line.find(
                        'check_snmp') != -1:
                    if snmp_type is not None and len(snmp_type) > 0:
                        temp = ""
                        service.snmp_type = snmp_type.strip()
                        if snmp_type == COMMON_SNTP_TRAFFIC:
                            for option in snmp_option:
                                if snmp_check is not None and len(
                                        snmp_check) > 0:
                                    for check in snmp_check:
                                        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)
                                else:
                                    temp += "!ifHCInOctets." + str(
                                        option) + "!ifHCOutOctets." + str(
                                            option) + "!" + str(
                                                check_interval) + "!" + str(
                                                    warning_limit) + "!" + str(
                                                        critical_limit)
                                break
                            service.check_command = check_command_pre + temp
                        elif snmp_type == COMMON_SNTP_CPULOAD:
                            temp = "!" + OID_CPU_LOAD_1 + "!" + OID_CPU_LOAD_5 + "!" + OID_CPU_LOAD_15
                            service.check_command = check_command_pre + temp
                        elif snmp_type == COMMON_SNTP_MEMORY:
                            temp = "!" + OID_PHYSICAL_MEM + "!" + OID_VIRTUAL_MEM + "!" + OID_SWAP_MEM
                            service.check_command = check_command_pre + temp

                if snmp_option is not None and len(snmp_option) > 0:
                    snmp_option_str = ','.join("{0}".format(n)
                                               for n in snmp_option)
                    service.snmp_option = snmp_option_str

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

                if max_check_attempts is not None and str(
                        max_check_attempts).isdigit():
                    service.max_check_attempts = max_check_attempts

                if check_interval is not None and str(
                        check_interval).isdigit():
                    service.check_interval = str(
                        round(int(check_interval) / 60, 1))

                if retry_interval is not None and str(
                        retry_interval).isdigit():
                    service.retry_interval = retry_interval

                if warning_limit is not None and str(warning_limit).isdigit():
                    service.warning = warning_limit

                if critical_limit is not None and str(
                        critical_limit).isdigit():
                    service.critical = str(critical_limit)

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

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

                if servicegroups is not None:
                    service.servicegroups = ','.join(servicegroups)

                if servicetemplates is not None:
                    service.use = ','.join(servicetemplates)

                writeNagiosServicesConfigFile(service)

                if check_interval is not None and str(
                        check_interval).isdigit():
                    service.check_interval = str(check_interval)

                updated = service.update()

                if host_name:
                    Service.delete_all_hosts_relations(service_id)
                    Service.create_hosts_relations(service_id, host_name)
                if contacts:
                    Service.delete_all_contacts_relations(service_id)
                    Service.create_contacts_relations(service_id, contacts)
                if contact_groups:
                    Service.delete_all_contactgroups_relations(service_id)
                    Service.create_contactgroups_relations(
                        service_id, contact_groups)
                if servicegroups:
                    Service.delete_all_servicegroups_relations(service_id)
                    Service.create_servicegroups_relations(
                        service_id, servicegroups)
                if servicetemplates:
                    Service.delete_all_servicetemplate_relations(service_id)
                    Service.create_servicetemplate_relations(
                        service_id, servicetemplates)

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

                if updated:
                    service = Service.get_by_id(service_id)
                    return jsonify(data=service.serialize())
            except Exception as e:
                syncNagiosAllConfigWithDb()
                return jsonify(error=True, msg=str(e))
        return jsonify(error=True)