def denyMACAddress(configuration, macaddr):
    try:
        configuration._api_client.service.denyMACAddress(
            configuration.get_id(), macaddr)
    except WebFault as e:
        print('Exception at denyMACAddress(%s)' % util.safe_str(e))
        raise BAMException(safe_str(e))
Ejemplo n.º 2
0
def delete_host_record_delete_host_record_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    # pylint: disable=broad-except
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes
            configuration = g.user.get_api().get_entity_by_id(form.configuration.data)

            view = configuration.get_view(request.form['view'])

            # Retrieve host record
            host_record = view.get_host_record(request.form['host_record'] + '.' + request.form['parent_zone'])

            # Retrieve host record attributes for flash message
            host_record_name = host_record.get_property('absoluteName')
            host_record_id = util.safe_str(host_record.get_id())

            # Delete host record
            host_record.delete()

            # Put form processing code here
            g.user.logger.info('Success - Host  (A) Record ' + host_record_name + ' Deleted with Object ID: ' +
                               host_record_id)
            flash('Success - Host  (A) Record ' + host_record_name + ' Deleted with Object ID: ' +
                  host_record_id, 'succeed')

            # Perform Selective Deployment (RELATED Scope) on host record if checkbox is checked
            if form.deploy_now.data:
                entity_id_list = [host_record.get_id()]
                deploy_token = g.user.get_api().selective_deploy(entity_id_list)
                return render_template('delete_host_record_page.html',
                                       form=form,
                                       status_token=deploy_token,
                                       text=util.get_text(module_path(), config.language),
                                       options=g.user.get_options())
            return redirect(url_for('delete_host_recorddelete_host_record_delete_host_record_page'))
        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e), msg_type=g.user.logger.EXCEPTION)
            return render_template('delete_host_record_page.html',
                                   form=form,
                                   text=util.get_text(module_path(), config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('delete_host_record_page.html',
                               form=form,
                               text=util.get_text(module_path(), config.language),
                               options=g.user.get_options())
def update_text_record_update_text_record_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    # pylint: disable=broad-except
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes
            text_record = g.user.get_api().get_entity_by_id(
                request.form['txt_list'])

            # Set text record attributes
            text_record.set_name(form.name.data)
            text_record.set_property('txt', form.text.data)
            text_record.update()

            # Put form processing code here
            g.user.logger.info('Success - Text Record Modified - Object ID: ' +
                               util.safe_str(text_record.get_id()))
            flash(
                'Success - Text Record Modified - Object ID: ' +
                util.safe_str(text_record.get_id()), 'succeed')
            return redirect(
                url_for(
                    'update_text_record_exampleupdate_text_record_update_text_record_page'
                ))

        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            form.txt_filter.data = ''
            form.name.data = ''
            form.text.data = ''
            return render_template('update_text_record_example_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())

    else:
        g.user.logger.info('Form data was not valid.')
        form.txt_filter.data = ''
        form.name.data = ''
        form.text.data = ''
        return render_template('update_text_record_example_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
def update_alias_record_update_alias_record_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    # pylint: disable=broad-except
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations()
    if form.validate_on_submit():
        try:
            # Retrieve form attributes and declare variables
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)
            view = configuration.get_view(request.form['view'])

            # Retrieve alias record
            alias_record = view.get_alias_record(request.form['alias_record'] +
                                                 '.' + request.form['zone'])

            # Update the alias record's name and linkedRecordName
            alias_record.set_name(form.alias_name.data)
            alias_record.set_property(
                'linkedRecordName', request.form['linked_record'] + '.' +
                request.form['linked_record_zone'])
            alias_record.update()

            # Put form processing code here
            g.user.logger.info(
                'Success - Alias Record Modified - Object ID: ' +
                util.safe_str(alias_record.get_id()))
            flash(
                'Success - Alias Record Modified - Object ID: ' +
                util.safe_str(alias_record.get_id()), 'succeed')
            return redirect(
                url_for(
                    'update_alias_recordupdate_alias_record_update_alias_record_page'
                ))
        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('update_alias_record_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('update_alias_record_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
Ejemplo n.º 5
0
def delete_alias_record_delete_alias_record_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    # pylint: disable=broad-except
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes and declare variables
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)
            view = configuration.get_view(request.form['view'])

            # Retrieve alias record
            alias_record = view.get_alias_record(request.form['alias_record'] +
                                                 '.' + request.form['zone'])

            # Retrieve alias_record attributes for flash message
            alias_name = alias_record.get_name()
            alias_id = util.safe_str(alias_record.get_id())

            # Delete alias record
            alias_record.delete()

            # Put form processing code here
            g.user.logger.info('Success - Alias Record ' + alias_name +
                               ' Deleted with Object ID: ' + alias_id)
            flash(
                'Success - Alias Record ' + alias_name +
                ' Deleted with Object ID: ' + alias_id, 'succeed')
            return redirect(
                url_for(
                    'delete_alias_recorddelete_alias_record_delete_alias_record_page'
                ))
        except Exception as e:
            flash(util.safe_str(e))
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('delete_alias_record_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('delete_alias_record_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
def delete_ip4_address_delete_ip4_address_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    # pylint: disable=broad-except
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)

            # Retrieve IP4 Object
            ip4_object = configuration.get_ip4_address(
                util.safe_str(request.form.get('ip4_address', '')))

            # Retrieve alias_record attributes for flash message
            ip4_address = util.safe_str(ip4_object.get_property('address'))
            ip4_id = util.safe_str(ip4_object.get_id())

            # Delete IP4 Object
            ip4_object.delete()

            # Put form processing code here
            g.user.logger.info('Success - IP4 Object ' + ip4_address +
                               ' Deleted with Object ID: ' + ip4_id)
            flash(
                'Success - IP4 Object ' + ip4_address +
                ' Deleted with Object ID: ' + ip4_id, 'succeed')
            return redirect(
                url_for(
                    'delete_ip4_addressdelete_ip4_address_delete_ip4_address_page'
                ))
        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('delete_ip4_address_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('delete_ip4_address_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
def add_host_record_example_add_host_record_example_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    # pylint: disable=broad-except
    form = GenericFormTemplate()
    form.configuration.choices = util.get_configurations(default_val=True)

    if form.validate_on_submit():
        ip4_address_list = []
        try:
            # Retrieve form attributes
            configuration = g.user.get_api().get_entity_by_id(form.configuration.data)
            view = configuration.get_view(request.form['view'])
            absolute_name = form.hostname.data + '.' + request.form['zone']
            ip4_address = request.form['ip4_address']
            ip4_address_list.append(ip4_address)

            # Add host Record
            host_record = view.add_host_record(absolute_name, ip4_address_list)

            # Put form processing code here
            g.user.logger.info('Success - Host (A) Record ' + host_record.get_property('absoluteName') +
                               ' added with Object ID: ' + util.safe_str(host_record.get_id()))
            flash('Success - Host (A) Record ' + host_record.get_property('absoluteName') + ' added with Object ID: ' +
                  util.safe_str(host_record.get_id()), 'succeed')

            # Perform Selective Deployment (RELATED Scope) on host record if checkbox is checked
            if form.deploy_now.data:
                entity_id_list = [host_record.get_id()]
                deploy_token = g.user.get_api().selective_deploy(entity_id_list)
                return render_template('add_host_record_example_page.html',
                                       form=form,
                                       status_token=deploy_token,
                                       text=util.get_text(module_path(), config.language),
                                       options=g.user.get_options())
            return redirect(url_for('add_host_record_exampleadd_host_record_example_add_host_record_example_page'))
        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e), msg_type=g.user.logger.EXCEPTION)
            return render_template('add_host_record_example_page.html',
                                   form=form,
                                   text=util.get_text(module_path(), config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('add_host_record_example_page.html',
                               form=form,
                               text=util.get_text(module_path(), config.language),
                               options=g.user.get_options())
def delete_host_record_example_delete_host_record_example_page_form():
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)

            view = configuration.get_view(request.form['view'])

            # Retrieve host record
            host_record = view.get_host_record(request.form['host_record'] +
                                               '.' +
                                               request.form['parent_zone'])

            # Retrieve host record attributes for flash message
            host_record_name = host_record.get_property('absoluteName')
            host_record_id = util.safe_str(host_record.get_id())

            # Delete host record
            host_record.delete()

            # Put form processing code here
            g.user.logger.info('Success - Host  (A) Record ' +
                               host_record_name + ' Deleted with Object ID: ' +
                               host_record_id)
            flash(
                'Success - Host  (A) Record ' + host_record_name +
                ' Deleted with Object ID: ' + host_record_id, 'succeed')
            return redirect(
                url_for(
                    'delete_host_record_exampledelete_host_record_example_delete_host_record_example_page'
                ))
        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('delete_host_record_example_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('delete_host_record_example_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
def add_text_record_add_text_record_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    # pylint: disable=broad-except
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve configuration, view, and absolute name
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)
            view = configuration.get_view(request.form['view'])
            absolute_name = form.name.data + '.' + request.form.get('zone', '')

            # Attempt to add the text record
            text_record = view.add_text_record(absolute_name, form.text.data)

            g.user.logger.info('Success-Text Record ' +
                               text_record.get_property('absoluteName') +
                               ' Added with Object ID: ' +
                               util.safe_str(text_record.get_id()))
            flash(
                'Success - Text Record ' +
                text_record.get_property('absoluteName') +
                ' Added with Object ID: ' +
                util.safe_str(text_record.get_id()), 'succeed')
            return redirect(
                url_for(
                    'add_text_record_exampleadd_text_record_add_text_record_page'
                ))

        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('add_text_record_example_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('add_text_record_example_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
def update_ip4_address_update_ip4_address_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)

            # Retrieve the IP4 address object
            ip4_address = configuration.get_ip4_address(
                request.form.get('ip4_address', ''))

            # Update the form name and mac address properties
            ip4_address.set_name(form.description.data)
            ip4_address.set_property('macAddress', form.mac_address.data)
            ip4_address.update()

            # Put form processing code here
            g.user.logger.info('Success - IP4 Address Modified - Object ID: ' +
                               util.safe_str(ip4_address.get_id()))
            flash(
                'Success - IP4 Address Modified - Object ID: ' +
                util.safe_str(ip4_address.get_id()), 'succeed')
            return redirect(
                url_for(
                    'update_ip4_addressupdate_ip4_address_update_ip4_address_page'
                ))
        except APIException as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('update_ip4_address_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('update_ip4_address_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
def add_dhcp_ip4_address_add_dhcp_ip4_address_page_form():
    """
    Processes the final form after the user has input all the required data.

    :return:
    """
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)
            view = configuration.get_view(request.form.get('view', ''))
            hostinfo = "%s.%s,%s,true,false" % (form.hostname.data,
                                                request.form.get(
                                                    'zone', ''), view.get_id())
            properties = 'name=' + form.description.data

            # Assign DHCP reserved IP4 object
            ip4_object = configuration.assign_ip4_address(
                util.safe_str(request.form.get('ip4_address', '')),
                util.safe_str(form.mac_address.data), hostinfo,
                IPAssignmentActionValues.MAKE_DHCP_RESERVED, properties)

            # Put form processing code here
            g.user.logger.info(
                'Success-DHCP Reserved IP4 Address ' +
                util.safe_str(request.form.get('ip4_address', '')) +
                ' Assigned with Object ID: ' +
                util.safe_str(ip4_object.get_id()))
            flash(
                'Success - DHCP Reserved IP4 Address ' +
                util.safe_str(request.form.get('ip4_address', '')) +
                ' Assigned with Object ID: ' +
                util.safe_str(ip4_object.get_id()), 'succeed')
            return redirect(
                url_for(
                    'add_dhcp_ip4_addressadd_dhcp_ip4_address_add_dhcp_ip4_address_page'
                ))
        except APIException as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('add_dhcp_ip4_address_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('add_dhcp_ip4_address_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
Ejemplo n.º 12
0
def delete_record_endpoint():
    json_data = request.get_json()
    response_data = {'message': ''}

    response_code, response_message = check_common(json_data)
    if 'deploy' not in json_data:
        should_deploy = True
    else:
        should_deploy = False

    if response_code == 200:
        record_type = json_data['record_type'].strip()
        try:
            response_code, response_message, should_deploy, ids = \
                delete_record(record_type, json_data, response_code, should_deploy)

            if should_deploy:
                response_code, deploy_message = deploy(ids)
                response_data['deploy_info'] = deploy_message

        except (APIException, BAMException, PortalException) as e:
            response_code = 500
            response_message = 'Unable to delete the record %s, exception: %s' % \
                               (json_data['record_name'].strip(), util.safe_str(e))

    g.user.logger.info(
        'delete_record returned with the following message: %s' %
        response_message)
    response_data['message'] = response_message
    return jsonify(response_data), response_code
Ejemplo n.º 13
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
def get_acls(**kwargs):
    """
    Retrieve all ACLs from default configuration
    :return: All ACLs in default configuration
    """
    # Use the default result template to store results
    result = []

    # Retrieve the configuration object
    try:
        configuration = g.user.get_api().get_configuration(
            config.default_configuration)
    except PortalException as e:
        g.user.logger.error('%s' % e, msg_type=g.user.logger.EXCEPTION)
        flash(
            'Configuration %s could not be retrieved from the Gateway configuration'
            % config.default_configuration)
        return result

    # Retrieve list of ACLs from configuration
    acls = configuration.get_children_of_type('ACL')

    # Loop through ACLs appending to result dictionary
    for acl in acls:
        result.append((acl.get_id(), safe_str(acl.get_name())))

    return result
Ejemplo n.º 15
0
def delete_reservation_endpoint():
    json_data = request.get_json()
    response_data = {'message': ''}
    response_code = 200
    response_message = ''

    if 'ip' not in json_data or json_data['ip'] == '':
        response_code = 400
        response_message = 'ip not provided'

    if response_code == 200:
        try:
            configuration = g.user.get_api().get_configuration(
                DEFAULT_CONFIG_NAME)
            if ':' in json_data['ip'].strip():
                address = configuration.get_ip6_address(
                    json_data['ip'].strip())
            else:
                address = configuration.get_ip4_address(
                    json_data['ip'].strip())

            address.delete()
            response_message = 'Successfully deleted the reservation for IP address: %s' % json_data[
                'ip'].strip()

        except (APIException, BAMException, PortalException) as e:
            response_code = 500
            response_message = 'Unable to delete the reservation %s, exception: %s' % \
                               (json_data['record_name'].strip(), util.safe_str(e))

    g.user.logger.info(
        'delete_reservation returned with the following message: %s' %
        response_message)
    response_data['message'] = response_message
    return jsonify(response_data), response_code
Ejemplo n.º 16
0
def delete_scope_endpoint():
    json_data = request.get_json()
    response_data = {'message': ''}
    response_code = 200
    response_message = ''

    if 'id' not in json_data or json_data['id'] == '':
        response_code = 400
        response_message = 'id not provided'

    if response_code == 200:
        try:
            scope = g.user.get_api().get_entity_by_id(json_data['id'].strip())

            scope.delete()

            response_message = 'Successfully deleted the scope with ID: %s' % json_data[
                'id'].strip()

        except (APIException, BAMException, PortalException) as e:
            response_code = 500
            response_message = 'Unable to delete the scope %s, exception: %s' % \
                               (json_data['record_name'].strip(), util.safe_str(e))

    g.user.logger.info('delete_scope returned with the following message: %s' %
                       response_message)
    response_data['message'] = response_message
    return jsonify(response_data), response_code
def add_server(server_ip,
               server_name,
               config_id,
               profile='DNS_DHCP_SERVER_60',
               properties='password=bluecat|connected=true|upgrade=False'):
    """
    Add server
    :param server_ip: server ip
    :param server_name: server name
    :param config_id: configuration id
    :param profile: ADONIS_1200, ADONIS_XMB3
    :param properties: contain password, servicesIPv4Address...
    :return: server_id
    """
    try:
        properties = parse_properties(properties)
        server_id = g.user.get_api()._api_client.service.addServer(
            config_id, server_name, server_ip, server_name.replace("_", ""),
            profile, properties)
        start = time.time()
        max_timeout = 30
        while time.time() - start < max_timeout:
            try:
                g.user.logger.debug(
                    f"Check time out add server {server_name} server_ip {server_ip}"
                )
                return g.user.get_api().get_entity_by_id(server_id).get_id()
            except PortalException as exception:
                if 'No such entity exists.:%d' % server_id in exception.get_message(
                ):
                    pass
                else:
                    raise exception
    except WebFault as exception:
        raise BAMException(safe_str(exception))
Ejemplo n.º 18
0
def update_password(user, password):
    options = []
    try:
        user._api_client.updateUserPassword(user.get_id(), password, options)
    except WebFault as e:
        print('Exception at update_password(%s)' % util.safe_str(e))
        raise BAMException(safe_str(e))
Ejemplo n.º 19
0
def generate_service_requests_report():
    try:
        string_output = io.StringIO()

        csv_writer = csv.writer(string_output)

        csv_writer.writerow([
            'TicketNum', 'HostRecord', 'HostID', 'IPAddress', 'IPState',
            'IPID', 'RequestCreate', 'RequestedBy', 'LastUpdate', 'CloseDate',
            'CloseNotes'
        ])
        ticket_url = service_requests_config.servicenow_url + '?assigned_to=admin'
        response = requests.get(
            ticket_url,
            auth=(service_requests_config.servicenow_username,
                  get_password_from_file(
                      service_requests_config.servicenow_secret_file)),
            headers=headers,
            verify=False)
        data = []
        # Check for HTTP codes other than 200
        if response.status_code == 200:
            tickets = response.json()
            for ticket in tickets['result']:
                if 'BlueCat' in ticket['short_description']:
                    description = ticket['description'].split(',')
                    ip_address = g.user.get_api().get_configuration(
                        config.default_configuration).get_ip4_address(
                            description[3].partition('ip_address=')[2])
                    hosts = ip_address.get_linked_entities('HostRecord')
                    host_id = ''
                    for host in hosts:
                        host_id = host.get_id()
                    info = [
                        ticket['number'],
                        description[2].partition('host_record=')[2], host_id,
                        ip_address.get_address(),
                        ip_address.get_state(),
                        ip_address.get_id(), ticket['sys_created_on'],
                        ticket['sys_created_by'], ticket['sys_updated_on'],
                        ticket['closed_at'], ticket['close_notes']
                    ]

                    csv_writer.writerow(info)

            output_response = make_response(string_output.getvalue())
            output_response.headers[
                'Content-Disposition'] = 'attachment; filename=service_requests.csv'
            output_response.headers['Content-type'] = 'text/csv'
        else:
            raise Exception(
                'Received a non 200 response from the service provider: %s, content: %s'
                % (response.status_code, response.content))
    except Exception as e:
        return_message = 'Encountered an error while generating the CSV file: %s' % util.safe_str(
            e)
        output_response = make_response(return_message, 500)

    return output_response
Ejemplo n.º 20
0
def get_deployment_options(entity, option_types, server_id):
    options = []
    try:
        options = entity._api_client.getDeploymentOptions(entity.get_id(), option_types, server_id)
    except GeneralError as e:
        print('Exception at get_deployment_options(%s)' % util.safe_str(e))
        raise BAMException(safe_str(e))
    return options
Ejemplo n.º 21
0
def deploy(ids):
    try:
        # API call to run the selective deployment
        deploy_return = g.user.get_api().selective_deploy_synchronous(
            ids, properties='scope=related', timeout=30)
        return 200, deploy_return
    except (APIException, BAMException, PortalException) as e:
        return 500, 'Unable to deploy the records, exception: %s' % util.safe_str(
            e)
Ejemplo n.º 22
0
 def _free_by_node(self, configuration, node):
     try:
         iprange = configuration.get_ip_range_by_ip('DHCP4Range', node['ipaddr'])
     except PortalException as e:
         try:
             ipaddress = configuration.get_ip4_address(node['ipaddr'])
             ipaddress.delete()
         except PortalException as e:
             if self._debug:
                 print('DEBUG: Exceptin <%s>' % safe_str(e))
Ejemplo n.º 23
0
def create_server_vro_create_server_vro_page_form():
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():

        configuration = g.user.get_api().get_entity_by_id(
            form.configuration.data)
        view = configuration.get_view(form.view.data)
        network = form.ip4_network.data.split('/')
        network = configuration.get_ip_range_by_ip('IP4Network', network[0])

        props = {'excludeDHCPRange': 'True'}
        hostinfo = util.safe_str(form.hostname.data) + '.' + util.safe_str(
            form.zone.data) + ',' + util.safe_str(
                view.get_id()) + ',' + 'True' + ',' + 'False'

        assigned_ip = network.assign_next_available_ip4_address(
            form.mac_address.data,
            hostinfo,
            'MAKE_DHCP_RESERVED',
            properties=props)

        absoluteName = form.hostname.data + '.' + form.zone.data

        g.user.logger.info(
            'Success - Host (A) Record ' + absoluteName + ' IP Address: ' +
            util.safe_str(assigned_ip.get_property('address')) + ' State: ' +
            util.safe_str(assigned_ip.get_property('state')) +
            ' Mac Address: ' +
            util.safe_str(assigned_ip.get_property('macAddress')))
        flash(
            'Success - Host (A) Record ' + absoluteName + ' IP Address: ' +
            util.safe_str(assigned_ip.get_property('address')) + ' State: ' +
            util.safe_str(assigned_ip.get_property('state')) +
            ' Mac Address: ' +
            util.safe_str(assigned_ip.get_property('macAddress')), 'succeed')
        return redirect(
            url_for(
                'create_server_vrocreate_server_vro_create_server_vro_page'))
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template(
            'create_server_vro_page.html',
            form=form,
            text=util.get_text(module_path(), config.language),
            options=g.user.get_options(),
        )
def vro_provision_server_vro_provision_server_page():
    data = json.loads(request.data)

    configuration = g.user.get_api().get_configuration(
        vro_config.default_configuration)
    view = configuration.get_view(vro_config.default_view)

    vro_tag = g.user.get_api().get_tag_group_by_name('vRO Configuration')
    network_tag = vro_tag.get_child_by_name('vRO Networks', 'Tag')
    networks = network_tag.get_linked_entities('IP4Network')

    # Building the host properties string used to create the host
    props = {'excludeDHCPRange': 'True'}

    for network in networks:
        try:
            hostinfo = util.safe_str(
                data['hostname']
            ) + '.' + vro_config.default_zone + ',' + util.safe_str(
                view.get_id(
                )) + ',' + vro_config.default_reverse_flag + ',' + 'False'

            assigned_ip = network.assign_next_available_ip4_address(
                data['mac'], hostinfo, 'MAKE_DHCP_RESERVED', properties=props)
            break
        except Exception as e:
            if 'used by another ip' in util.safe_str(e).lower():
                raise e
            else:
                g.user.logger.warning(
                    'All IPs are used in Network, Getting the next Network in vRO Networks Tag!'
                )
                continue
        else:
            if 'network' not in globals():
                raise Exception('All networks are full')

    result = assigned_ip.to_json()
    result['hostname'] = data['hostname'] + '.' + vro_config.default_zone
    # Log out
    g.user.logout()

    return jsonify(result)
Ejemplo n.º 25
0
def reserve_next_available_endpoint():
    json_data = request.get_json()
    response_data = {'message': ''}
    response_code = 200

    if 'network' not in json_data or json_data['network'] == '':
        response_code = 400
        response_message = 'network not provided'
    if 'host_name' not in json_data or json_data['host_name'] == '':
        response_code = 400
        response_message = 'host_name not provided'
    if 'zone' not in json_data or json_data['zone'] == '':
        response_code = 400
        response_message = 'zone not provided'
    if 'mac_address' not in json_data or json_data['mac_address'] == '':
        response_code = 400
        response_message = 'mac_address not provided'

    if response_code == 200:
        try:
            networks = g.user.get_api().get_by_object_types(
                json_data['network'].strip(), 'IP4Network')
            found_network = None
            for network in networks:
                if network.get_property(
                        'CIDR') == json_data['network'].strip():
                    found_network = network
                    host_string = '%s.%s,%s,true,false' % (
                        json_data['host_name'].strip(),
                        json_data['zone'].strip(), DEFAULT_VIEW_ID)
                    new_address = found_network.assign_next_available_ip4_address(
                        json_data['mac_address'].strip(), host_string,
                        'MAKE_DHCP_RESERVED')
                    break

            if found_network:
                response_message = 'Successfully created the host %s.%s to the network with IP address %s' % (
                    json_data['host_name'].strip(), json_data['zone'].strip(),
                    new_address.get_address())
                response_data['ip'] = new_address.get_address()
                response_data['ip_id'] = new_address.get_id()
            else:
                response_message = 'No matching network found: %s' % json_data[
                    'network'].strip()

        except (APIException, BAMException, PortalException) as e:
            response_code = 500
            response_message = 'Unable to add the option to the network network %s, exception: %s' %\
                               (json_data['network'].strip(), util.safe_str(e))

    g.user.logger.info(
        'reserve_next_available returned with the following message: %s' %
        response_message)
    response_data['message'] = response_message
    return jsonify(response_data), response_code
def create_deployment_roles(server_name,
                            server_id,
                            config_id,
                            view_name,
                            role_type,
                            properties=''):
    """
    Create deployment roles
    :param server_name: server name
    :param server_id: server id
    :param config_id: configuration id
    :param view_name: view name
    :param role_type: SLAVE_STEALTH, RECURSION
    :param properties: user-defined fields
    :return: role_id
    """
    try:
        g.user.logger.debug(
            f"Get view of creating deployment roles {server_name} config_id {config_id} view_name {view_name}"
        )
        configuration = g.user.get_api().get_entity_by_id(config_id)
        view = configuration.get_view(view_name)
    except PortalException as exception:
        g.user.logger.warning('%s' % exception,
                              msg_type=g.user.logger.EXCEPTION)
        return False

    try:
        if not server_id:
            server_obj = g.user.get_api()._api_client.service.getEntityByName(
                config_id, server_name, entity.Entity.Server)
            server_id = server_obj['id']

        properties = parse_properties(properties)
        g.user.logger.debug(
            f"Get server interface of creating deployment roles {server_name} server_id {server_id}"
        )
        server_nsf = g.user.get_api()._api_client.service.getEntityByName(
            server_id, server_name, entity.Entity.NetworkServerInterface)

        role_id = g.user.get_api()._api_client.service.addDNSDeploymentRole(
            view.get_id(), server_nsf['id'], role_type, properties)
        if role_id:
            g.user.logger.debug("Role ID: {}".format(role_id))
            return role_id
        else:
            g.user.logger.error(
                'Role creation for %s and server %s was unsuccessful!' %
                (view_name, server_name))
            g.user.logger.error(traceback.format_exc())
            return False
    except WebFault as exception:
        g.user.logger.error(safe_str(exception))
        g.user.logger.error(traceback.format_exc())
        return False
Ejemplo n.º 27
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))
Ejemplo n.º 28
0
def get_addresses(configuration_id, network):
    result = []
    try:
        # Retrieve the configuration object
        configuration = g.user.get_api().get_entity_by_id(configuration_id)

        # Network is sent with an arbitrary character to replace the / that will interfere with flask
        network = network.replace('A', '/')

        # Check if a valid network is entered, else raise exception
        ipaddress.ip_network(network)

        # Create a list to extract the CIDR
        network_list = network.split('/')

        # Retrieve IP network from network_list
        ip4_network = configuration.get_ip4_networks_by_hint(
            util.safe_str(network_list[0]))

        # Retrieve IP4Address children of network to create list of taken addresses
        children_addresses = ip4_network[0].get_children_of_type('IP4Address')

        # Append all children addresses to results array
        for address in children_addresses:
            result.append(util.safe_str(address.get_property('address')))
            if len(result) >= 10:
                break

        # Sort IP List
        result = sorted(result,
                        key=lambda ip: struct.unpack("!L", inet_aton(ip))[0])

        return jsonify(result)
    except Exception as e:
        if ('does not appear to be an IPv4 or IPv6 network'
                in util.safe_str(e)) or ('has host bits set'
                                         in util.safe_str(e)):
            g.user.logger.warning('%s' % e, msg_type=g.user.logger.EXCEPTION)
            return jsonify([])
        else:
            raise e
Ejemplo n.º 29
0
def add_static_ip4_address_example_add_static_ip4_address_example_page_form():
    form = GenericFormTemplate()
    # Remove this line if your workflow does not need to select a configuration
    form.configuration.choices = util.get_configurations(default_val=True)
    if form.validate_on_submit():
        try:
            # Retrieve form attributes
            configuration = g.user.get_api().get_entity_by_id(
                form.configuration.data)
            selected_view = request.form.get('view', '')
            selected_hostname = request.form.get('hostname', '')
            hostinfo = ''
            if selected_view != '' and selected_hostname != '':
                view = configuration.get_view(selected_view)
                hostinfo = util.safe_str(
                    selected_hostname) + '.' + util.safe_str(
                        request.form.get('zone', '')) + ',' + util.safe_str(
                            view.get_id()) + ',' + 'true' + ',' + 'false'
            properties = 'name=' + form.description.data

            # Assign ip4 object
            ip4_object = configuration.assign_ip4_address(
                request.form.get('ip4_address', ''), form.mac_address.data,
                hostinfo, 'MAKE_STATIC', properties)

            # Put form processing code here
            g.user.logger.info('Success - Static IP4 Address ' +
                               ip4_object.get_property('address') +
                               ' Added with Object ID: ' +
                               util.safe_str(ip4_object.get_id()))
            flash(
                'Success - Static IP4 Address ' +
                ip4_object.get_property('address') +
                ' Added with Object ID: ' + util.safe_str(ip4_object.get_id()),
                'succeed')
            return redirect(
                url_for(
                    'add_static_ip4_address_exampleadd_static_ip4_address_example_add_static_ip4_address_example_page'
                ))
        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e),
                                  msg_type=g.user.logger.EXCEPTION)
            return render_template('add_static_ip4_address_example_page.html',
                                   form=form,
                                   text=util.get_text(module_path(),
                                                      config.language),
                                   options=g.user.get_options())
    else:
        g.user.logger.info('Form data was not valid.')
        return render_template('add_static_ip4_address_example_page.html',
                               form=form,
                               text=util.get_text(module_path(),
                                                  config.language),
                               options=g.user.get_options())
Ejemplo n.º 30
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