Esempio n. 1
0
def create_service():
    service_from_request = get_json_from_request('service')

    validation_result, validation_errors = valid_service_submission(
        service_from_request)
    if not validation_result:
        return jsonify(error="Invalid JSON",
                       error_details=validation_errors), 400

    user = User.query.get(service_from_request['userId'])

    if not user:
        return jsonify(error="failed to create service - invalid user"), 400

    try:
        token = Token(token=uuid4(), type='client')
        db.session.add(token)
        db.session.flush()

        service = Service(name=service_from_request['name'],
                          created_at=datetime.utcnow(),
                          token_id=token.id,
                          active=True,
                          restricted=True,
                          limit=current_app.config['MAX_SERVICE_LIMIT'])
        service.users.append(user)
        db.session.add(service)
        db.session.commit()
        return jsonify(service=service.serialize()), 201
    except IntegrityError as e:
        print(e.orig)
        db.session.rollback()
        abort(400, "failed to create service")
Esempio n. 2
0
def create_service():
    service_from_request = get_json_from_request('service')

    validation_result, validation_errors = valid_service_submission(service_from_request)
    if not validation_result:
        return jsonify(
            error="Invalid JSON",
            error_details=validation_errors
        ), 400

    user = User.query.get(service_from_request['userId'])

    if not user:
        return jsonify(
            error="failed to create service - invalid user"
        ), 400

    try:
        token = Token(token=uuid4(), type='client')
        db.session.add(token)
        db.session.flush()

        service = Service(
            name=service_from_request['name'],
            created_at=datetime.utcnow(),
            token_id=token.id,
            active=True,
            restricted=True,
            limit=current_app.config['MAX_SERVICE_LIMIT']
        )
        service.users.append(user)
        db.session.add(service)
        db.session.commit()
        return jsonify(
            service=service.serialize()
        ), 201
    except IntegrityError as e:
        print(e.orig)
        db.session.rollback()
        abort(400, "failed to create service")
Esempio n. 3
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)