示例#1
0
    def find_objects_by_type():
        """Retrieve a list of properties for the table"""
        # pylint: disable=broad-except
        try:
            keyword = request.form['keyword']
            object_type = request.form['object_type']

            # Get entities based on the selection
            entities = g.user.get_api().get_by_object_types(
                keyword, object_type)

            # Parse response object into table data
            data = raw_entities_to_table_data(entities)

            # If no entities were found reutrn with failure state and message
            result = get_result_template()
            if len(data['data']) == 0:
                result['status'] = 'FAIL'
                result[
                    'message'] = 'No entities of type "{TYPE}" were found.'.format(
                        TYPE=object_type)
            else:
                result['status'] = 'SUCCESS'
            result['data'] = {"table_field": data}
            return jsonify(result_decorator(result))

        except Exception as e:
            result = get_result_template()
            result['status'] = 'FAIL'
            result['message'] = str(e)
            return jsonify(result_decorator(result))
    def find_objects_by_type():
        """Retrieve a list of properties for the table"""
        # pylint: disable=broad-except
        try:

            # Valid units for interval:
            # millennium, century, decade, year, month, week, day, hour, minute, second, millisecond, microsecond

            form_interval = request.form['interval']
            logs = g.user.get_api().get_audit_logs(form_interval,
                                                   transaction_id=None,
                                                   descending=False)

            # Parse response object into table data
            data = raw_entities_to_table_data(logs)

            # If no entities were found return with failure state and message
            result = get_result_template()
            if len(data['data']) == 0:
                result['status'] = 'FAIL'
                result['message'] = 'No records  were found.'
            else:
                result['status'] = 'SUCCESS'
            result['data'] = {"table_field": data}
            return jsonify(result_decorator(result))

        except Exception as e:
            result = get_result_template()
            result['status'] = 'FAIL'
            result['message'] = str(e)
            return jsonify(result_decorator(result))
示例#3
0
def update_objects():
    """checks the status of task and transfer the results to the table"""
    try:
        key = request.form['message']
        status = g.user.get_api().get_deployment_task_status(key)

        entity_status = {}
        dns_records_list = request.form['dns_records_list'].split('.')
        deployment_error = ''
        for record_id in dns_records_list:
            entity_status[record_id] = '<font color = yellow> '+status['status']+' </font>'
            if status['status'] == SelectiveDeploymentStatus.FINISHED:
                entity_status[record_id] = 'Already deployed and not modified'
                if status['response']['errors']:
                    deployment_error = 'ERROR Selective Deployment: ' + \
                                       status['response']['errors'][0]
                    entity_status[record_id] = \
                        '<font color = red>ERROR: See logs for details</font>'
                elif status['response']['views']:
                    try:
                        for records in status['response']['views'][0]['zones'][0]['records']:
                            if str(records['id']) == str(record_id):
                                color = '#cb4814'
                                if records['result'] == SelectiveDeploymentStatus.FAILED:
                                    color = 'red'
                                elif records['result'] == SelectiveDeploymentStatus.SUCCEEDED:
                                    color = '#76ce66'
                                entity_status[record_id] = '<font color = %s>' % color + \
                                                           records['result'] + '</font>'
                                app.logger.info(record_id + ' Status : ' + entity_status[record_id])
                    except IndexError as error:
                        entity_status[record_id] = '<font color = red> ERROR: '\
                                           + str(error) + ', Could not find the results </font>'
        if deployment_error != '':
            app.logger.error(deployment_error)

        data = raw_entities_to_table_data(entity_status, False)
        result = get_result_template()
        data['columnDefs'] = [{'targets': [3], 'render': ''}]
        result['status'] = status['status']
        result['data'] = {"table_field": data,
                          "message": '%s' % key,
                          "configuration": request.form['configuration'],
                          "view": request.form['view'],
                          "zone": request.form['zone'],
                          "dns_records_list": request.form['dns_records_list']}
    # pylint: disable=broad-except
    except Exception as e:
        result = get_result_template()
        result['status'] = 'FAIL'
        result['message'] = util.safe_str(e)
        return jsonify(empty_decorator(result))

    return jsonify(empty_decorator(result))
    def find_objects_by_type():
        # pylint: disable=unused-variable
        """Retrieve a list of properties for the table"""

        try:

            if g.user.get_api().get_version() < '8.3.2':
                result = get_result_template()
                result['status'] = 'FAIL'
                result['message'] = 'BAM must be Version 8.3.2 or greater'
                return jsonify(result_decorator(result))

            configuration = g.user.get_api().get_entity_by_id(
                request.form['configuration'])
            view = configuration.get_view(request.form['view'])
            zone_string = request.form['zone'].split('.')

            zone = view
            for i in range(len(zone_string) - 1, -1, -1):
                zone = zone.get_zone(zone_string[i])

            entities = chain(zone.get_children_of_type('HostRecord'),
                             zone.get_children_of_type('AliasRecord'),
                             zone.get_children_of_type('TXTRecord'),
                             zone.get_children_of_type('HINFORecord'),
                             zone.get_children_of_type('SRVRecord'),
                             zone.get_children_of_type('MXRecord'),
                             zone.get_children_of_type('NAPTRRecord'))

            data = raw_entities_to_table_data(entities, True)

            result = get_result_template()
            data["columnDefs"] = [{
                "width": "10%",
                "targets": [3],
                'render': ''
            }]
            if not data['data']:
                result['message'] = 'No DNS Records Found'
            result['status'] = 'SUCCESS'
            result['data'] = {"table_field": data}
            return jsonify(result_decorator(result))

        except Exception as error:  # pylint: disable=broad-except
            result = get_result_template()
            result['status'] = 'FAIL'
            result['message'] = str(error)

            return jsonify(result_decorator(result))
def get_address_data(configuration_id, ip6_address):
    """
    Get the BAM data for a given ip6_address in the given configuration.

    :param configuration_id: The ID of the configuration in which the ip6_address resides.
    :param ip6_address: The IP address in string form.
    :return: The IP address data in JSON, using result template format.
    """

    # Regular expression to match IPv6 format
    result = get_result_template()
    if not is_valid_ipv6_address(ip6_address):
        result['message'] = 'IP address is invalid.'
        result['status'] = FAIL
        return result

    # Retrieve the configuration object
    configuration = g.user.get_api().get_entity_by_id(configuration_id)

    # Check if IP address exists within a network. Fail if not.
    try:
        configuration.get_ip_ranged_by_ip(Entity.IP6Network, ip6_address)
        result['message'] = 'IPv6 Address is available'
        result['status'] = SUCCESS
        result['data'] = {'state': None, 'mac_address': None, 'name': None}
        return result
    except PortalException:
        result[
            'message'] = 'IP address is not in a network or network does not exist'
        result['status'] = FAIL
        return result
示例#6
0
def cisco_aci_example_cisco_aci_example_page_form():
    """
        Takes ACI info and returns Tenants in ACI.
    """
    global progress
    progress = dict()

    result = get_result_template()
    aci_user = request.form.get('apic_username')
    aci_pass = request.form.get('apic_password')
    aci_apic = request.form.get('apic_ip')
    aci_apic = aci_apic.strip('/')

    try:
        aci_session = create_aci_session(aci_apic, aci_user, aci_pass)
    except PortalException as e:
        result['status'] = FAIL
        result['message'] += str(e)
        return jsonify(empty_decorator(result))
    else:
        tenants = ACI.Tenant.get(aci_session)

        result['status'] = SUCCESS
        result['message'] += 'Successfully found tenants!'
        result['data'] = {"table_field": raw_table_data()}

        result['data']['table_field']['data'] = populate_table_data(tenants)

        aci_session.close()

    return jsonify(empty_decorator(result))
    def server_table_data():
        """Retrieve server side table data"""
        keyword = request.form["keyword"]
        object_type_id = request.form["object_type"]

        response = get_result_template()
        response["status"] = "SUCCESS"
        response["message"] = "Retrieved server side table data"
        response["data"] = {
            "table_field": {
                "searching": False,
                "paging": False,
                "ordering": False,
                "info": False,
                "lengthChange": False,
                "columns": [{
                    "title": "keyword"
                }, {
                    "title": "object_type"
                }],
                "data": [
                    [keyword, object_type_id],
                ],
            }
        }
        return jsonify(result_decorator(response))
示例#8
0
    def server_table_data():
        """Retrieve server side table data"""
        keyword = request.form['keyword']
        object_type_id = request.form['object_type']

        response = get_result_template()
        response['status'] = 'SUCCESS'
        response['message'] = 'Retrieved server side table data'
        response['data'] = {
            'table_field': {
                'searching': False,
                'paging': False,
                'ordering': False,
                'info': False,
                'lengthChange': False,
                'columns': [{
                    'title': 'keyword'
                }, {
                    'title': 'object_type'
                }],
                'data': [
                    [keyword, object_type_id],
                ]
            }
        }
        return jsonify(result_decorator(response))
示例#9
0
def get_ip4_networks_data(hint):
    """
    Get a list of networks that corresponds to the configuration and hint entered by the user
    :param hint: Network hint to search with
    :return: networks that correspond to the network hint
    """
    # Use the default result template
    result = get_result_template()
    result['data']['autocomplete_field'] = []

    # Retrieve the configuration
    try:
        configuration_id = request.form['configuration']
    except PortalException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        return result

    # Retrieve network based on user input
    try:
        networks = g.user.get_api()._api_client.service.getIP4NetworksByHint(configuration_id, 0, 5, 'hint=%s' % hint)
    except BAMException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        result['message'] = 'Unable to retrieve network with error %s: ' % safe_str(e)
        return result

    if has_response(networks):
        for network in networks.item:
            network = g.user.get_api().instantiate_entity(network)
            network_string = network.get_property('CIDR')
            result['data']['autocomplete_field'].append({"value": network_string})

    result['status'] = SUCCESS
    return result
示例#10
0
def get_next_ip4_address_data(ip4_network):
    """
    Retrieve the next available IP4 Addresses given the network CIDR
    :param ip4_network: Network CIDR
    :return: Next available IP4 Address
    """
    # Endpoint presets
    result = get_result_template()

    # Retrieve the configuration
    try:
        configuration = g.user.get_api().get_configuration(
            config.default_configuration)
    except PortalException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        return result

    # Network is in CIDR format, retrieve the network and the next available ipv4 address
    network = ip4_network.split('/')
    try:
        network = configuration.get_ip_range_by_ip('IP4Network', network[0])
    except BAMException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        return result
    ipv4_address = network.get_next_ip4_address_string()

    if ipv4_address:
        result['status'] = SUCCESS
        result['data'] = [ipv4_address]
    else:
        result['status'] = SUCCESS
        result['data'] = ['network is fully allocated']
    return result
示例#11
0
    def server_table_data():
        """Retrieve server side table data"""
        # pylint: disable=broad-except
        print('Server Table Data is Called!!!!')
        try:
            text = get_resource_text()
            data = load_statistics(g.user.get_api(), text)
            result = get_result_template()

            result['status'] = 'SUCCESS'
            result['data'] = {"table_field": data}
            return jsonify(result_decorator(result))

        except Exception as e:
            result = get_result_template()
            result['status'] = 'FAIL'
            result['message'] = str(e)
            return jsonify(result_decorator(result))
    def find_objects_by_type():
        # pylint: disable=unused-variable
        """Retrieve a list of properties for the table"""

        try:
            configuration = g.user.get_api().get_entity_by_id(
                request.form["configuration"])
            view = configuration.get_view(request.form["view"])
            zone_string = request.form["zone"].split(".")

            zone = view
            for i in range(len(zone_string) - 1, -1, -1):
                zone = zone.get_zone(zone_string[i])

            entities = chain(
                zone.get_children_of_type("HostRecord"),
                zone.get_children_of_type("AliasRecord"),
                zone.get_children_of_type("TXTRecord"),
                zone.get_children_of_type("HINFORecord"),
                zone.get_children_of_type("SRVRecord"),
                zone.get_children_of_type("MXRecord"),
                zone.get_children_of_type("NAPTRRecord"),
            )

            data = raw_entities_to_table_data(entities, True)

            result = get_result_template()
            data["columnDefs"] = [{
                "width": "10%",
                "targets": [3],
                "render": ""
            }]
            if not data["data"]:
                result["message"] = "No DNS Records Found"
            result["status"] = "SUCCESS"
            result["data"] = {"table_field": data}
            return jsonify(result_decorator(result))

        except Exception as error:
            result = get_result_template()
            result["status"] = "FAIL"
            result["message"] = str(error)

            return jsonify(result_decorator(result))
    def find_objects_by_type():
        """Retrieve a list of properties for the table"""
        # pylint: disable=broad-except
        try:
            ip4_network = request.form['ip4_network']
            configuration = g.user.get_api().get_configuration(
                config.default_configuration)
            networks = configuration.get_ip4_networks_by_hint(
                ip4_network.split('/', 1)[0])
            net_id = networks[0].get_id()
            network = g.user.get_api().get_entity_by_id(net_id)
            ip4_addresses = g.user.get_api()._api_client.service.getEntities(
                network.get_id(), 'IP4Address', 0, 100)

            new_ip4_address = []
            for ip4_address in ip4_addresses.item:
                ip4_address = g.user.get_api().instantiate_entity(ip4_address)
                new_ip4_address.append(ip4_address)

            print("Found {} IP Addresses with Network {}".format(
                len(new_ip4_address), network.get_property('CIDR')))

            # Calling the new API
            records = configuration.get_host_records_by_ip(new_ip4_address)

            # Parse response object into table data
            data = raw_entities_to_table_data(records)

            # If no entities were found return with failure state and message
            result = get_result_template()
            if len(data['data']) == 0:
                result['status'] = 'FAIL'
                result['message'] = 'No records  were found.'
            else:
                result['status'] = 'SUCCESS'
            result['data'] = {"table_field": data}
            return jsonify(result_decorator(result))

        except Exception as e:
            result = get_result_template()
            result['status'] = 'FAIL'
            result['message'] = str(e)
            return jsonify(result_decorator(result))
示例#14
0
    def query_unused_mac_address():
        """Retrieve a list of properties for the table"""
        # pylint: disable=broad-except
        try:
            configuration = get_configuration(g.user.get_api(), config.default_configuration)
            expire_time = request.form['expire_time']

            data = load_lease_history(configuration.get_id(),  expire_time)

            # If no entities were found reutrn with failure state and message
            result = get_result_template()
            result['status'] = 'SUCCESS'
            result['data'] = {"table_field": data}
            return jsonify(result_decorator(result))

        except Exception as e:
            result = get_result_template()
            result['status'] = 'FAIL'
            result['message'] = str(e)
            return jsonify(result_decorator(result))
示例#15
0
def deploy_objects():
    """Retrieve a list of user selected host records and passes it to the update function"""

    selected_list = []
    dns_records_list = ''
    try:
        for key in request.form:
            try:
                if key.isdigit() and request.form['%s' % key] == 'on':
                    selected_list.append(key)
            except AttributeError:
                if request.form[key] == 'on':
                    selected_list.append(key)

        token = g.user.get_api().selective_deploy(selected_list,
                                                  'scope=related')
        status = g.user.get_api().get_deployment_task_status(token)

        for record_id in selected_list:
            dns_records_list = dns_records_list + '%s.' % record_id

        dns_records_list = dns_records_list[:-1]
        result = get_result_template()
        result['status'] = '%s' % status['status']
        result['data'] = {
            "message": '%s' % token,
            "configuration": request.form['configuration'],
            "view": request.form['view'],
            "zone": request.form['zone'],
            "dns_records_list": dns_records_list
        }
        g.user.logger.info(token)
    # pylint: disable=broad-except
    except Exception as e:
        result = get_result_template()
        result['status'] = 'FAIL'
        result['message'] = util.safe_str(e)
        return jsonify(empty_decorator(result))

    return jsonify(empty_decorator(result))
示例#16
0
def get_address_data(configuration_id, ip4_address):
    """
    Get the BAM data for a given ip4_address in the given configuration.

    :param configuration_id: The ID of the configuration in which the ip4_address resides.
    :param ip4_address: The IP address in octet form.
    :return: The IP address data in JSON, using result template format.
    """
    result = get_result_template()
    if not is_valid_ipv4_address(ip4_address):
        result['message'] = 'IP address is invalid.'
        result['status'] = FAIL
        return result

    # Retrieve the configuration object
    configuration = g.user.get_api().get_configuration(
        config.default_configuration)

    # Since unallocated address does not exist as an object, first verify if
    # this is an address in a network
    try:
        configuration.get_ip_range_by_ip('IP4Network', ip4_address)
    except PortalException:
        result['message'] = 'IP address is not in a network'
        result['status'] = FAIL
        return result

    # Second, return  Retrieve the IP4 address object and if not found, create one with UNALLOCATED state
    try:
        ip4_address = configuration.get_ip4_address(ip4_address)
    except PortalException as e:
        if 'IP4 address not found' in safe_str(e):
            result['status'] = SUCCESS
            result['data'] = {
                'state': 'UNALLOCATED',
                'mac_address': None,
                'name': None
            }
            return result
        raise e

    # Retrieve the IP4 object name and MAC address properties
    state = ip4_address.get_property('state')

    result['status'] = SUCCESS
    result['data'] = {
        'state': state,
        'mac_address': ip4_address.get_property('macAddress'),
        'name': ip4_address.get_name()
    }

    return result
def deploy_objects():
    """Retrieve a list of user selected host records and passes it to the update function"""

    selected_list = []
    dns_records_list = ""
    try:
        for key in request.form:
            try:
                if key.isdigit() and request.form["%s" % key] == "on":
                    selected_list.append(key)
            except AttributeError:
                if request.form[key] == "on":
                    selected_list.append(key)

        token = g.user.get_api().selective_deploy(selected_list, "scope=related")
        status = g.user.get_api().get_deployment_task_status(token)

        for record_id in selected_list:
            dns_records_list = dns_records_list + "%s." % record_id

        dns_records_list = dns_records_list[:-1]
        result = get_result_template()
        result["status"] = "%s" % status["status"]
        result["data"] = {
            "message": "%s" % token,
            "configuration": request.form["configuration"],
            "view": request.form["view"],
            "zone": request.form["zone"],
            "dns_records_list": dns_records_list,
        }
        g.user.logger.info(token)
    except Exception as e:
        result = get_result_template()
        result["status"] = "FAIL"
        result["message"] = str(e)
        return jsonify(empty_decorator(result))

    return jsonify(empty_decorator(result))
示例#18
0
def cisco_aci_cisco_aci_page_import_fabric():
    """
        Takes ACI info and imports ACI Fabric.
    """
    global progress
    progress = dict()
    result = get_result_template()

    if get_api().get_version() < '9.1.0':
        message = 'Error! Current BAM version {version} is less than 9.1.0: Fabric Import failed!'
        result['status'] = FAIL
        result['message'] += message.format(version=get_api().get_version())
        return jsonify(empty_decorator(result))

    bam_config_id = request.form.get('configuration', None)
    aci_user = request.form.get('apic_username')
    aci_pass = request.form.get('apic_password')
    aci_apic = request.form.get('apic_ip')
    aci_apic = aci_apic.strip('/')

    try:
        aci_session = create_aci_session(aci_apic, aci_user, aci_pass)
    except PortalException as e:
        result['status'] = FAIL
        result['message'] += str(e)
        return jsonify(empty_decorator(result))

    try:
        check_and_create_fabric_udfs()
    except RESTFault as e:
        message = 'Failed to create UDFs, please check logs for more details.'
        result['status'] = FAIL
        result['message'] += message
        app.logger.error(str(e))
        return jsonify(empty_decorator(result))

    if bam_config_id is not None and request.form.get(
            'import_devices_checkbox', False):
        bam_configuration = get_api().get_entity_by_id(bam_config_id)
        add_networks_for_fabric(bam_configuration, aci_session)
        create_aci_fabric(aci_session, bam_configuration)

    result['status'] = SUCCESS
    result['message'] += 'Successfully imported ACI Fabric'

    aci_session.close()

    return jsonify(empty_decorator(result))
示例#19
0
def get_deploy_status():
    """
    Retrieves and updates deployment task status
    :return:
    """
    result = get_result_template()
    deploy_token = request.form['deploy_token']
    try:
        task_status = g.user.get_api().get_deployment_task_status(deploy_token)
        result['status'] = task_status['status']

        if task_status['status'] == SelectiveDeploymentStatus.FINISHED:
            deploy_errors = task_status['response']['errors']

            # Deployment failed
            if deploy_errors:
                result['data'] = "FAILED"
                result['message'] = deploy_errors
                raise Exception('Deployment Error: ' + str(deploy_errors))

            # Deployment succeeded
            elif task_status['response']['views']:
                task_result = task_status['response']['views'][0]['zones'][0][
                    'records'][0]['result']
                result['data'] = task_result

            # Deployment finished with no changes
            else:
                result['data'] = 'FINISHED'

            g.user.logger.info('Deployment Task Status: ' + str(task_status))

        # Deployment queued/started
        else:
            result['data'] = task_status['status']
    # pylint: disable=broad-except
    except Exception as e:
        g.user.logger.warning(e)

    return jsonify(empty_decorator(result))
def get_deploy_status():
    """
    Retrieves and updates deployment task status
    :return:
    """
    result = get_result_template()
    deploy_token = request.form["deploy_token"]
    try:
        task_status = g.user.get_api().get_deployment_task_status(deploy_token)
        result["status"] = task_status["status"]

        if task_status["status"] == SelectiveDeploymentStatus.FINISHED:
            deploy_errors = task_status["response"]["errors"]

            # Deployment failed
            if deploy_errors:
                result["data"] = "FAILED"
                result["message"] = deploy_errors
                raise Exception("Deployment Error: " + str(deploy_errors))

            # Deployment succeeded
            if task_status["response"]["views"]:
                task_result = task_status["response"]["views"][0]["zones"][0]["records"][0][
                    "result"
                ]
                result["data"] = task_result

            # Deployment finished with no changes
            else:
                result["data"] = "FINISHED"

            g.user.logger.info("Deployment Task Status: " + str(task_status))

        # Deployment queued/started
        else:
            result["data"] = task_status["status"]
    except Exception as e:
        g.user.logger.warning(e)

    return jsonify(empty_decorator(result))
示例#21
0
def get_zones_data(hint):
    """
    Get a list of zone FQDNs that corresponds to the given hint.

    :return: FQDN of any zones that match the given hint as data in JSON, using result template format.
    """
    # Declare variables
    result = get_result_template()
    result['data']['autocomplete_field'] = []

    # Retrieve the configuration and view object
    try:
        configuration = g.user.get_api().get_configuration(
            config.default_configuration)
        view = configuration.get_view(config.default_view)
    except PortalException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        return result

    # If null user input then set hint to empty to pre-populate the dropdown, otherwise search with user input
    if safe_str(hint) == 'null':
        properties = 'hint=|'
    else:
        properties = 'hint=' + hint

    # Retrieve zones
    zones = g.user.get_api()._api_client.service.getZonesByHint(
        view.get_id(), 0, 5, properties)

    # If valid zones are retrieved then extract the absolute name and append to result
    if has_response(zones):
        for zone in zones.item:
            result['data']['autocomplete_field'].append(
                properties_to_map(zone['properties'])['absoluteName'])

    result['status'] = SUCCESS
    return result
示例#22
0
def get_ip6_networks_data(hint):
    """
    Get a list of networks that corresponds to the configuration and hint entered by the user
    :param hint: Network hint to search with
    :return: networks that correspond to the network hint
    """
    # Use the default result template
    result = get_result_template()
    result['data']['autocomplete_field'] = []

    # Retrieve the configuration
    try:
        configuration_id = request.form['configuration']
        configuration = g.user.get_api().get_entity_by_id(configuration_id)
    except PortalException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        return result

    # Retrieve network based on user input
    try:
        networks = configuration.get_ip6_objects_by_hint(hint, '', count=10)
    except BAMException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        result['message'] = 'Unable to retrieve network with error %s: ' % safe_str(e)
        return result

    print(len(networks))

    if len(networks) > 0:
        for network in networks:
            network_string = network.get_property('prefix')
            result['data']['autocomplete_field'].append({"value": network_string})

    result['status'] = SUCCESS
    return result
def get_mac_pools_data(configuration):
    """
    Get a list of MACPools that coressponds to a parent configuration=

    :return: MACPools using result template format.
    """
    # Declare variables
    result = get_result_template()
    result['data']['autocomplete_field'] = []

    # Retrieve the configuration
    try:
        configuration = g.user.get_api().get_entity_by_id(configuration)
    except PortalException as e:
        result['status'] = FAIL
        g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
        return result

    # Iterate through child MACPool objects of the configuration and append to result
    for mac_pool in configuration.get_children_of_type('MACPool'):
        result['data']['autocomplete_field'].append(mac_pool.get_name())

    result['status'] = SUCCESS
    return result
def update_objects():
    """checks the status of task and transfer the results to the table"""
    try:
        key = request.form["message"]
        status = g.user.get_api().get_deployment_task_status(key)

        entity_status = {}
        dns_records_list = request.form["dns_records_list"].split(".")
        deployment_error = ""
        for record_id in dns_records_list:
            entity_status[record_id] = "<font color = yellow> " + status["status"] + " </font>"
            if status["status"] == SelectiveDeploymentStatus.FINISHED:
                entity_status[record_id] = "Already deployed and not modified"
                if status["response"]["errors"]:
                    deployment_error = (
                        "ERROR Selective Deployment: " + status["response"]["errors"][0]
                    )
                    entity_status[
                        record_id
                    ] = "<font color = red>ERROR: See logs for details</font>"
                elif status["response"]["views"]:
                    try:
                        for records in status["response"]["views"][0]["zones"][0]["records"]:
                            if str(records["id"]) == str(record_id):
                                color = "#cb4814"
                                if records["result"] == SelectiveDeploymentStatus.FAILED:
                                    color = "red"
                                elif records["result"] == SelectiveDeploymentStatus.SUCCEEDED:
                                    color = "#76ce66"
                                entity_status[record_id] = (
                                    "<font color = %s>" % color + records["result"] + "</font>"
                                )
                                app.logger.info(record_id + " Status : " + entity_status[record_id])
                    except IndexError as error:
                        entity_status[record_id] = (
                            "<font color = red> ERROR: "
                            + str(error)
                            + ", Could not find the results </font>"
                        )
        if deployment_error != "":
            app.logger.error(deployment_error)

        data = raw_entities_to_table_data(entity_status, False)
        result = get_result_template()
        data["columnDefs"] = [{"targets": [3], "render": ""}]
        result["status"] = status["status"]
        result["data"] = {
            "table_field": data,
            "message": "%s" % key,
            "configuration": request.form["configuration"],
            "view": request.form["view"],
            "zone": request.form["zone"],
            "dns_records_list": request.form["dns_records_list"],
        }
    except Exception as e:
        result = get_result_template()
        result["status"] = "FAIL"
        result["message"] = str(e)
        return jsonify(empty_decorator(result))

    return jsonify(empty_decorator(result))
示例#25
0
def cisco_aci_example_cisco_aci_example_page_import_tenants():
    """
        Processes the selected Tenants.

        :return:
    """
    global progress
    global messages
    result = get_result_template()

    if get_api().get_version() < '9.1.0':
        message = 'Error! Current BAM version {version} is less than 9.1.0: Infrastructure Import failed!'
        error_message = message.format(version=get_api().get_version())
        result['status'] = FAIL
        result['message'] += error_message
        app.logger.error(error_message)
        return jsonify(empty_decorator(result))

    data = request.form
    result = get_result_template()
    tenant_options = {}
    aci_user = request.form.get('apic_username')
    aci_pass = request.form.get('apic_password')
    aci_apic = request.form.get('apic_ip')
    aci_apic = aci_apic.strip('/')

    try:
        aci_session = create_aci_session(aci_apic, aci_user, aci_pass)
    except PortalException as e:
        result['status'] = FAIL
        result['message'] += str(e)
        return jsonify(empty_decorator(result))

    try:
        check_and_create_tenant_udfs()
    except RESTFault as e:
        message = 'Failed to create UDFs, please check logs for more details.'
        result['status'] = FAIL
        result['message'] += message
        app.logger.error(str(e))
        return jsonify(empty_decorator(result))

    for tenant in data:
        if tenant.endswith('_import'):
            tenant_name = tenant[:-7]
            tenant_import_device = False
            if tenant_name + '_import_endpoint_devices' in data:
                tenant_import_device = True
            tenant_overwrite = False
            if tenant_name + '_overwrite' in data:
                tenant_overwrite = True
            tenant_options[tenant_name] = {'import_endpoint_devices': tenant_import_device,
                                           'overwrite': tenant_overwrite}

    tenants = ACI.Tenant.get(aci_session)
    tenant_info = [(tenant, tenant_options[tenant.name]) for tenant in tenants if tenant.name in tenant_options.keys()]

    if start_progress(tenant_info, aci_session):
        return jsonify('SUCCESS')
    else:
        result['status'] = FAIL
        result['message'] += 'Please select at least one tenant'
        app.logger.error(result['message'])
        return jsonify(empty_decorator(result))