Esempio n. 1
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))
Esempio n. 2
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))
Esempio n. 3
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))
Esempio n. 4
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))
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))
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))
Esempio n. 8
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))
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))