Ejemplo n.º 1
0
    def reattach_multi_device_templates(self, template_ids):
        """Re-Attach a template to the devices it it attached to.

        Args:
            template_id (str): The template ID to attach to
            config_type (str): Type of template i.e. device or CLI template
            is_edited (bool): True if the template has been edited
            is_master_edited (bool): For CLI device template needs to match is_edited.
                    For device templates using feature templates needs to be set to False.

        Returns:
            action_id (str): Returns the action id of the attachment

        """

        payload = self.get_multi_attach_payload(template_ids)

        if payload['deviceTemplateList'][0]['device']:
            url = f"{self.base_url}template/device/config/attachfeature"

            utils = Utilities(self.session, self.host, self.port)
            response = HttpMethods(self.session,
                                   url).request('POST',
                                                payload=json.dumps(payload))
            action_id = ParseMethods.parse_id(response)
            utils.waitfor_action_completion(action_id)
        else:
            raise RuntimeError(
                f"Could not retrieve input for template {template_ids}")
        return action_id
Ejemplo n.º 2
0
def serial_file(ctx, input_file):
    """
    Import serial file
    """
    vmanage_utilities = Utilities(ctx.auth, ctx.host)

    click.echo(f'Uploading serial file... {input_file}')
    result = vmanage_utilities.upload_file(input_file)
    click.echo(result)
    def reattach_device_template(self,
                                 template_id,
                                 config_type,
                                 is_edited=True,
                                 is_master_edited=True):
        """Re-Attach a template to the devices it it attached to.

        Args:
            template_id (str): The template ID to attach to
            config_type (str): Type of template i.e. device or CLI template

        Returns:
            action_id (str): Returns the action id of the attachment

        """
        device_list = self.get_template_attachments(template_id, key='uuid')
        template_input = self.get_template_input(template_id, device_list)

        # Then we feed that to the attach
        if 'data' in template_input and template_input['data']:
            payload = {
                "deviceTemplateList": [{
                    "templateId": template_id,
                    "device": template_input['data'],
                    "isEdited": is_edited,
                    "isMasterEdited": is_master_edited
                }]
            }
            if config_type == 'file':
                url = f"{self.base_url}template/device/config/attachcli"
            elif config_type == 'template':
                url = f"{self.base_url}template/device/config/attachfeature"
            else:
                raise Exception('Got invalid Config Type')

            utils = Utilities(self.session, self.host, self.port)
            response = HttpMethods(self.session,
                                   url).request('POST',
                                                payload=json.dumps(payload))
            if 'json' in response and 'id' in response['json']:
                action_id = response['json']['id']
                utils.waitfor_action_completion(action_id)
            else:
                raise Exception(
                    f"Did not get action ID after attaching device to template {template_id}."
                )
        else:
            raise Exception(
                f"Could not retrieve input for template {template_id}")
        return action_id
Ejemplo n.º 4
0
    def push_certificates(self):
        """Push certificates to all controllers

        Returns:
            id (str): The action ID of the push command.
        """

        url = f"{self.base_url}vedge/list?action=push"
        response = HttpMethods(self.session, url).request('POST', payload={})
        utilities = Utilities(self.session, self.host)
        action_id = ParseMethods.parse_id(response)
        utilities.waitfor_action_completion(action_id)

        return action_id
Ejemplo n.º 5
0
    def reattach_device_template(self,
                                 template_id,
                                 config_type,
                                 is_edited=True,
                                 is_master_edited=True,
                                 wait=True):
        """Re-Attach a template to the devices it it attached to.

        Args:
            template_id (str): The template ID to attach to
            config_type (str): Type of template i.e. device or CLI template
            is_edited (bool): True if the template has been edited
            is_master_edited (bool): For CLI device template needs to match is_edited.
                    For device templates using feature templates needs to be set to False.

        Returns:
            action_id (str): Returns the action id of the attachment

        """
        device_list = self.get_template_attachments(template_id, key='uuid')
        template_input = self.get_template_input(template_id, device_list)

        # Then we feed that to the attach
        if 'data' in template_input and template_input['data']:
            payload = {
                "deviceTemplateList": [{
                    "templateId": template_id,
                    "device": template_input['data'],
                    "isEdited": is_edited,
                    "isMasterEdited": is_master_edited
                }]
            }
            if config_type == 'file':
                url = f"{self.base_url}template/device/config/attachcli"
            elif config_type == 'template':
                url = f"{self.base_url}template/device/config/attachfeature"
            else:
                raise RuntimeError('Got invalid Config Type')

            utils = Utilities(self.session, self.host, self.port)
            response = HttpMethods(self.session,
                                   url).request('POST',
                                                payload=json.dumps(payload))
            action_id = ParseMethods.parse_id(response)
            if wait:
                utils.waitfor_action_completion(action_id)
        else:
            raise RuntimeError(
                f"Could not retrieve input for template {template_id}")
        return action_id
Ejemplo n.º 6
0
def central_policy(ctx, name):
    """
    Activate Central Policy
    """

    vmanage_central_policy = CentralPolicy(ctx.auth, ctx.host, ctx.port)
    vmanage_utilities = Utilities(ctx.auth, ctx.host, ctx.port)
    central_policy_dict = vmanage_central_policy.get_central_policy_dict(
        remove_key=True)
    if name in central_policy_dict:
        click.echo(f'Activating Central Policy {name}')
        action_id = vmanage_central_policy.activate_central_policy(
            name, central_policy_dict[name]['policyId'])
        vmanage_utilities.waitfor_action_completion(action_id)
    else:
        click.secho(f'Cannot find Central Policy {name}', fg="red")
Ejemplo n.º 7
0
    def push_certificates(self):
        """Push certificates to all controllers

        Returns:
            result (str): The action ID of the push command.
        """

        url = f"{self.base_url}vedge/list?action=push"
        response = HttpMethods(self.session, url).request('POST', payload={})
        utilities = Utilities(self.session, self.host)

        if 'json' in response and 'id' in response['json']:
            utilities.waitfor_action_completion(response['json']['id'])
        else:
            raise Exception('Did not get action ID after pushing certificates.')
        return response['json']['id']
Ejemplo n.º 8
0
    def install_device_cert(self, cert):
        """Install signed cert on vManage

        Args:
            cert (str): The certificate to install.

        Returns:
            id (str): The action ID of the install command.
        """

        url = f"{self.base_url}install/signedCert"
        response = HttpMethods(self.session, url).request('POST', payload=cert)
        utilities = Utilities(self.session, self.host)
        action_id = ParseMethods.parse_id(response)
        utilities.waitfor_action_completion(action_id)

        return action_id
def policy_activation():
    try:

        log_level = logging.DEBUG
        logger = get_logger("log/sdwan-te-integration.txt", log_level)

        if logger is not None:
            logger.info("Loading vManage login details from YAML\n")

        data = json.loads(request.data)

        with open("config_details.yaml") as f:
            config = yaml.safe_load(f.read())

        vmanage_host = config["vmanage_host"]
        vmanage_port = config["vmanage_port"]
        username = config["vmanage_username"]
        password = config["vmanage_password"]

        session = Authentication(host=vmanage_host,
                                 port=vmanage_port,
                                 user=username,
                                 password=password).login()

        name = config["central_policy_name"]

        vmanage_central_policy = CentralPolicy(session, vmanage_host,
                                               vmanage_port)
        central_policy_dict = vmanage_central_policy.get_central_policy_dict(
            remove_key=True)
        if name in central_policy_dict:
            print(f'Activating Central Policy {name}')
            action_id = vmanage_central_policy.activate_central_policy(
                name, central_policy_dict[name]['policyId'])
            utils = Utilities(session, vmanage_host, vmanage_port)
            utils.waitfor_action_completion(action_id)
        else:
            return jsonify(f'Cannot find Central Policy {name}'), 200

    except Exception as exc:
        print('Exception line number: {}'.format(sys.exc_info()[-1].tb_lineno),
              type(exc).__name__, exc)
        return jsonify(str(exc)), 500

    return jsonify(f'Activated Policy {name}'), 200
    def install_device_cert(self, cert):
        """Install signed cert on vManage

        Args:
            cert (str): The certificate to install.

        Returns:
            id (str): The action ID of the install command.
        """

        url = f"{self.base_url}install/signedCert"
        response = HttpMethods(self.session, url).request('POST', payload=cert)
        utilities = Utilities(self.session, self.host)
        if 'json' in response and 'id' in response['json']:
            utilities.waitfor_action_completion(response['json']['id'])
        else:
            raise Exception(
                'Did not get action ID after installing certificate.')
        return response['json']['id']
Ejemplo n.º 11
0
    def __init__(self, session, host, port=443):
        """Initialize Reset vManage object with session parameters.

        Args:
            session (obj): Requests Session object
            host (str): hostname or IP address of vManage
            port (int): default HTTPS 443

        """

        self.session = session
        self.host = host
        self.port = port
        self.base_url = f'https://{self.host}:{self.port}/dataservice/'
        self.utilities = Utilities(self.session, self.host)
        self.cen_pol = CentralizedPolicy(self.session, self.host)
        self.inventory = DeviceInventory(self.session, self.host)
        self.dev_temps = DeviceTemplates(self.session, self.host)
        self.fet_temps = FeatureTemplates(self.session, self.host)
        self.loc_pol = LocalizedPolicy(self.session, self.host)
        self.sec_pol = SecurityPolicy(self.session, self.host)
        self.pol_lists = PolicyLists(self.session, self.host)
Ejemplo n.º 12
0
def central_policy(ctx, name, id):
    """
    deactivate Central Policy
    """

    vmanage_central_policy = CentralPolicy(ctx.auth, ctx.host, ctx.port)
    vmanage_utilities = Utilities(ctx.auth, ctx.host, ctx.port)
    central_policy_dict = vmanage_central_policy.get_central_policy_dict(
        remove_key=True)
    if id:
        vmanage_central_policy.deactivate_central_policy(id)
    elif name:
        if name in central_policy_dict:
            click.echo(f'Deactivating Central Policy {name}')
            action_id = vmanage_central_policy.deactivate_central_policy(
                central_policy_dict[name]['policyId'])
            vmanage_utilities.waitfor_action_completion(action_id)
        else:
            click.secho(f'Cannot find Central Policy {name}', fg="red")
    else:
        click.secho('Must specify either policy name of id to deactivate',
                    fg="red")
Ejemplo n.º 13
0
    def __init__(self, session, host, port=443):
        """Initialize Centralized Policy object with session parameters.

        Args:
            session (obj): Requests Session object
            host (str): hostname or IP address of vManage
            port (int): default HTTPS 443

        """

        self.session = session
        self.host = host
        self.port = port
        self.base_url = f'https://{self.host}:{self.port}/dataservice/'
        self.policy_definitions = PolicyDefinitions(self.session, self.host)
        self.utilities = Utilities(self.session, self.host)
Ejemplo n.º 14
0
    def login(self):
        """Executes login tasks against vManage to retrieve token(s).

        Args:
            None.

        Returns:
            self.session: a Requests session with JSESSIONID and an
            X-XSRF-TOKEN for vManage version >= 19.2.0.

        Raises:
            LoginFailure: If the username/password are incorrect.
            RequestException: If the host is not accessible.

        """

        try:
            api = 'j_security_check'
            url = f'{self.base_url}{api}'
            response = self.session.post(url=url,
                                         data={
                                             'j_username': self.user,
                                             'j_password': self.password
                                         },
                                         timeout=self.timeout)

            if (response.status_code != 200
                    or response.text.startswith('<html>')):
                raise ConnectionError('Login failed, check user credentials.')

            version = Utilities(self.session, self.host,
                                self.port).get_vmanage_version()

            if version >= '19.2.0':
                api = 'client/token'
                url = f'{self.base_url}{api}'
                response = self.session.get(url=url, timeout=self.timeout)
                self.session.headers['X-XSRF-TOKEN'] = response.content

        except requests.exceptions.RequestException as e:
            raise ConnectionError(f'Could not connect to {self.host}: {e}')

        return self.session
    def __init__(self, session, host, port=443):
        """Initialize Policy Lists object with session parameters.

        Args:
            session (obj): Requests Session object
            host (str): hostname or IP address of vManage
            port (int): default HTTPS 443

        """

        self.session = session
        self.host = host
        self.port = port
        self.base_url = f'https://{self.host}:{self.port}/dataservice/'
        self.policy_lists = PolicyLists(self.session, self.host, self.port)

        version = Utilities(self.session, self.host,
                            self.port).get_vmanage_version()
        if version >= '19.3.0':
            self.definition_types = definition_types_19_3_0
        else:
            self.definition_types = definition_types_19_2_0
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = vmanage_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   choices=['absent', 'present', 'activated', 'deactivated'],
                   default='present'),
        name=dict(type='str', alias='policyName'),
        description=dict(type='str', alias='policyDescription'),
        definition=dict(type='str', alias='policyDefinition'),
        type=dict(type='list', alias='policyType'),
        wait=dict(type='bool', default=False),
        update=dict(type='bool', default=False),
        push=dict(type='bool', default=False),
        aggregate=dict(type='list'),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(changed=False, )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    vmanage = Vmanage(module)
    vmanage_central_policy = CentralPolicy(vmanage.auth, vmanage.host)
    policy_data = PolicyData(vmanage.auth, vmanage.host)
    vmanage_utils = Utilities(vmanage.auth, vmanage.host)

    # Always as an aggregate... make a list if just given a single entry
    if vmanage.params['aggregate']:
        policy_list = vmanage.params['aggregate']
    else:
        if vmanage.params['state'] == 'present':
            policy_list = [{
                'policyName': vmanage.params['name'],
                'policyDescription': vmanage.params['description'],
                'policyType': vmanage.params['type'],
                'policyDefinition': vmanage.params['definition'],
            }]
        else:
            policy_list = [{
                'policyName': vmanage.params['name'],
                'state': 'absent'
            }]

    central_policy_updates = []
    if vmanage.params['state'] == 'present':
        central_policy_updates = policy_data.import_central_policy_list(
            policy_list,
            check_mode=module.check_mode,
            update=vmanage.params['update'],
            push=vmanage.params['push'])
        if central_policy_updates:
            vmanage.result['changed'] = True
    elif vmanage.params['state'] == 'absent':
        central_policy_dict = vmanage_central_policy.get_central_policy_dict(
            remove_key=False)
        for policy in policy_list:
            if policy in central_policy_dict:
                if not module.check_mode:
                    vmanage_central_policy.delete_central_policy(
                        central_policy_dict[policy['policyName']]['policyId'])
                vmanage.result['changed'] = True
    elif vmanage.params['state'] == 'activated':
        central_policy_dict = vmanage_central_policy.get_central_policy_dict(
            remove_key=False)
        if vmanage.params['name'] in central_policy_dict:
            if not central_policy_dict[
                    vmanage.params['name']]['isPolicyActivated']:
                vmanage.result['changed'] = True
                if not module.check_mode:
                    action_id = vmanage_central_policy.activate_central_policy(
                        vmanage.params['name'], central_policy_dict[
                            vmanage.params['name']]['policyId'])
                    if action_id:
                        if vmanage.params['wait']:
                            vmanage_utils.waitfor_action_completion(action_id)
                    else:
                        vmanage.fail_json(
                            msg=
                            'Did not get action ID after attaching device to template.'
                        )

        else:
            # TODO: The reference to 'policy' in the following line is wrong. What should it be?
            vmanage.fail_json(msg="Cannot find central policy {0}".format(
                vmanage.params['name']))
    if vmanage.params['state'] in ['absent', 'deactivated']:
        central_policy_dict = vmanage_central_policy.get_central_policy_dict(
            remove_key=False)
        if policy['policyName'] in central_policy_dict:
            if central_policy_dict[policy['policyName']]['isPolicyActivated']:
                vmanage.result['changed'] = True
                if not module.check_mode:
                    action_id = vmanage_central_policy.deactivate_central_policy(
                        vmanage.params['name'])
                    if action_id:
                        if vmanage.params['wait']:
                            vmanage_central_policy.waitfor_action_completion(
                                action_id)
                    else:
                        vmanage.fail_json(
                            msg=
                            'Did not get action ID after attaching device to template.'
                        )
        else:
            vmanage.fail_json(msg="Cannot find central policy {0}".format(
                policy['policyName']))

    vmanage.params['updates'] = central_policy_updates
    vmanage.exit_json(**vmanage.result)
Ejemplo n.º 17
0
class ResetVmanage(object):
    """Reset all configuratios on a vManage instance.

    Executes the necessary REST calls in specific order to remove
    configurations applied to a vManage instance.

    """
    def __init__(self, session, host, port=443):
        """Initialize Reset vManage object with session parameters.

        Args:
            session (obj): Requests Session object
            host (str): hostname or IP address of vManage
            port (int): default HTTPS 443

        """

        self.session = session
        self.host = host
        self.port = port
        self.base_url = f'https://{self.host}:{self.port}/dataservice/'
        self.utilities = Utilities(self.session, self.host)
        self.cen_pol = CentralizedPolicy(self.session, self.host)
        self.inventory = DeviceInventory(self.session, self.host)
        self.dev_temps = DeviceTemplates(self.session, self.host)
        self.fet_temps = FeatureTemplates(self.session, self.host)
        self.loc_pol = LocalizedPolicy(self.session, self.host)
        self.sec_pol = SecurityPolicy(self.session, self.host)
        self.pol_lists = PolicyLists(self.session, self.host)

    def active_count_delay(self):

        activeCount = 1
        while activeCount != 0:
            time.sleep(1.0)
            data = self.utilities.get_active_count()
            activeCount = data["activeTaskCount"]

    def execute(self):

        # Step 1 - Deactivate Centralized Policy
        data = self.cen_pol.get_centralized_policy()
        for policy in data:
            if policy['isPolicyActivated']:
                policyId = policy['policyId']
                self.cen_pol.deactivate_centralized_policy(policyId)
        self.active_count_delay()

        # Step 2 - Detach vedges from template
        data = self.inventory.get_device_list('vedges')
        for device in data:
            if (('deviceIP' in device)
                    and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.inventory.post_device_cli_mode(deviceId, deviceIP,
                                                    deviceType)
        self.active_count_delay()

        # Step 3 - Detach controllers from template
        data = self.inventory.get_device_list('controllers')
        for device in data:
            if (('deviceIP' in device)
                    and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.inventory.post_device_cli_mode(deviceId, deviceIP,
                                                    deviceType)
                # Requires pause between controllers
                self.active_count_delay()
        self.active_count_delay()

        # Step 4 - Delete All Device Templates
        data = self.dev_temps.get_device_templates()
        for device in data:
            templateId = device['templateId']
            self.dev_temps.delete_device_template(templateId)
        self.active_count_delay()

        # Step 5 - Delete All Feature Templates
        data = self.fet_temps.get_feature_templates()
        for device in data:
            #pylint: disable=no-else-continue
            if device['factoryDefault']:
                continue
            else:
                templateId = device['templateId']
                self.fet_temps.delete_feature_template(templateId)
        self.active_count_delay()

        # Step 6 - Delete All Centralized Policies
        data = self.cen_pol.get_centralized_policy()
        for policy in data:
            policyId = policy['policyId']
            self.cen_pol.delete_centralized_policy(policyId)
        self.active_count_delay()

        # Step 7 - Delete All Topology, Traffic, Cflowd Policies
        definitionList = [
            'control', 'mesh', 'hubandspoke', 'vpnmembershipgroup', 'approute',
            'data', 'cflowd'
        ]
        for definition in definitionList:
            data = self.cen_pol.get_policy_definition(definition)
            if data:
                for policy in data:
                    definitionId = policy['definitionId']
                    self.cen_pol.delete_policy_definition(
                        definition, definitionId)
        self.active_count_delay()

        # Step 8 - Delete All Localized Policies
        data = self.loc_pol.get_localized_policy()
        for policy in data:
            policyId = policy['policyId']
            self.loc_pol.delete_localized_policy(policyId)
        self.active_count_delay()

        # Step 9 - Delete All Localized Specific Definitions
        definitionList = [
            'qosmap', 'rewriterule', 'acl', 'aclv6', 'vedgeroute'
        ]
        for definition in definitionList:
            data = self.loc_pol.get_localized_definition(definition)
            if data:
                for policy in data:
                    definitionId = policy['definitionId']
                    self.loc_pol.delete_localized_definition(
                        definition, definitionId)
        self.active_count_delay()

        # Step 10 - Delete All Security Policies
        version = self.utilities.get_vmanage_version()
        if version >= '18.2.0':
            data = self.sec_pol.get_security_policy()
            for policy in data:
                policyId = policy['policyId']
                self.sec_pol.delete_security_policy(policyId)
            self.active_count_delay()

        # Step 11 - Delete All UTD Specific Security Policies
        version = self.utilities.get_vmanage_version()
        definitionList = []
        # TODO: implement a proper semver comparison, this will fail if version is 18.30.0
        if version >= '18.4.0':
            definitionList = [
                'zonebasedfw', 'urlfiltering', 'dnssecurity',
                'intrusionprevention', 'advancedMalwareProtection'
            ]
        #pylint: disable=chained-comparison
        if version < '18.4.0' and version >= '18.2.0':
            definitionList = ['zonebasedfw']

        if definitionList:
            for definition in definitionList:
                data = self.sec_pol.get_security_definition(definition)
                if data:
                    for policy in data:
                        definitionId = policy['definitionId']
                        self.sec_pol.delete_security_definition(
                            definition, definitionId)
        self.active_count_delay()

        # Step 12 - Delete All Lists

        data = self.pol_lists.get_policy_list_all()
        for policy_list in data:
            owner = policy_list['owner']

            if owner != 'system':
                listType = policy_list['type'].lower()
                listId = policy_list['listId']
                self.pol_lists.delete_policy_list(listType, listId)

        return ('Reset Complete')
    def attach_to_template(self, template_id, config_type, uuid):
        """Attach and device to a template

        Args:
            template_id (str): The template ID to attach to
            config_type (str): Type of template i.e. device or CLI template
            uuid (dict): The UUIDs of the device to attach and mapping for corresponding variables, system-ip, host-name

        Returns:
            action_id (str): Returns the action id of the attachment

        """
        # Construct the variable payload

        device_template_var_list = list()
        template_variables = self.get_template_input(template_id)

        for device_uuid in uuid:

            device_template_variables = {
                "csv-status": "complete",
                "csv-deviceId": device_uuid,
                "csv-deviceIP": uuid[device_uuid]['system_ip'],
                "csv-host-name": uuid[device_uuid]['host_name'],
                '//system/host-name': uuid[device_uuid]['host_name'],
                '//system/system-ip': uuid[device_uuid]['system_ip'],
                '//system/site-id': uuid[device_uuid]['site_id'],
            }

            # Make sure they passed in the required variables and map
            # variable name -> property mapping

            for entry in template_variables['columns']:
                if entry['variable']:
                    if entry['variable'] in uuid[device_uuid]['variables']:
                        device_template_variables[entry['property']] = uuid[
                            device_uuid]['variables'][entry['variable']]
                    else:
                        raise Exception(
                            f"{entry['variable']} is missing for template {uuid[device_uuid]['host_name']}"
                        )

            device_template_var_list.append(device_template_variables)

        payload = {
            "deviceTemplateList": [{
                "templateId": template_id,
                "device": device_template_var_list,
                "isEdited": False,
                "isMasterEdited": False
            }]
        }

        if config_type == 'file':
            url = f"{self.base_url}template/device/config/attachcli"
        elif config_type == 'template':
            url = f"{self.base_url}template/device/config/attachfeature"
        else:
            raise Exception('Got invalid Config Type')

        utils = Utilities(self.session, self.host, self.port)
        response = HttpMethods(self.session,
                               url).request('POST',
                                            payload=json.dumps(payload))
        if 'json' in response and 'id' in response['json']:
            action_id = response['json']['id']
            utils.waitfor_action_completion(action_id)
        else:
            raise Exception(
                'Did not get action ID after attaching device to template.')

        return action_id
Ejemplo n.º 19
0
class CleanVmanage(object):
    """Reset all configuratios on a vManage instance.

    Executes the necessary REST calls in specific order to remove
    configurations applied to a vManage instance.

    """
    def __init__(self, session, host, port=443):
        """Initialize Reset vManage object with session parameters.

        Args:
            session (obj): Requests Session object
            host (str): hostname or IP address of vManage
            port (int): default HTTPS 443

        """

        self.session = session
        self.host = host
        self.port = port
        self.base_url = f'https://{self.host}:{self.port}/dataservice/'
        self.utilities = Utilities(self.session, self.host)
        self.central_policy = CentralPolicy(self.session, self.host)
        self.local_policy = LocalPolicy(self.session, self.host)
        self.device = Device(self.session, self.host)
        self.device_templates = DeviceTemplates(self.session, self.host)
        self.feature_templates = FeatureTemplates(self.session, self.host)
        self.sec_pol = SecurityPolicy(self.session, self.host)
        self.policy_definitions = PolicyDefinitions(self.session, self.host)
        self.policy_lists = PolicyLists(self.session, self.host)

    def active_count_delay(self):
        """Delay while there are active tasks.

        """
        activeCount = 1
        while activeCount != 0:
            time.sleep(1.0)
            data = self.utilities.get_active_count()
            activeCount = data["activeTaskCount"]

    def clean_vedge_attachments(self):
        """Clean all vedge attachments

        """
        data = self.device.get_device_list('vedges')
        for device in data:
            if (('deviceIP' in device) and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.device.post_device_cli_mode(deviceId, deviceIP, deviceType)
        self.active_count_delay()

    def clean_controller_attachments(self):
        """Clean all controller attachments

        """
        data = self.device.get_device_list('controllers')
        for device in data:
            if (('deviceIP' in device) and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.device.post_device_cli_mode(deviceId, deviceIP, deviceType)
                # Requires pause between controllers
                self.active_count_delay()
        self.active_count_delay()

    def clean_device_templates(self):
        """Clean all device templates

        """
        data = self.device_templates.get_device_templates()
        for device in data:
            templateId = device['templateId']
            self.device_templates.delete_device_template(templateId)
        self.active_count_delay()

    def clean_feature_templates(self):
        """Clean all feature templates

        """
        data = self.feature_templates.get_feature_templates()
        for device in data:
            #pylint: disable=no-else-continue
            if device['factoryDefault']:
                continue
            else:
                templateId = device['templateId']
                self.feature_templates.delete_feature_template(templateId)
        self.active_count_delay()

    def clean_central_policy(self):
        """Clean all central policy

        """
        data = self.central_policy.get_central_policy()
        for policy in data:
            policy_id = policy['policyId']
            if policy['isPolicyActivated']:
                action_id = self.central_policy.deactivate_central_policy(policy_id)
                if action_id:
                    self.utilities.waitfor_action_completion(action_id)
            self.central_policy.delete_central_policy(policy_id)
        self.active_count_delay()

    def clean_local_policy(self):
        """Clean all local policy

        """
        data = self.local_policy.get_local_policy()
        for policy in data:
            policyId = policy['policyId']
            self.local_policy.delete_local_policy(policyId)
        self.active_count_delay()

    def clean_policy_definitions(self):
        """Clean all policy definitions

        """
        policy_definition_list = self.policy_definitions.get_policy_definition_list()
        for policy_definition in policy_definition_list:
            self.policy_definitions.delete_policy_definition(policy_definition['type'],
                                                             policy_definition['definitionId'])
        self.active_count_delay()

    def clean_policy_lists(self):
        """Clean all policy lists

        """
        policy_list_list = self.policy_lists.get_policy_list_list()
        for policy_list in policy_list_list:
            if not policy_list['readOnly'] and policy_list['owner'] != 'system':
                self.policy_lists.delete_policy_list(policy_list['type'], policy_list['listId'])
        self.active_count_delay()

    def clean_security_policy(self):
        """Clean all security policy

        """
        version = self.utilities.get_vmanage_version()
        if version >= '18.2.0':
            data = self.sec_pol.get_security_policy()
            for policy in data:
                policyId = policy['policyId']
                self.sec_pol.delete_security_policy(policyId)
            self.active_count_delay()

        # # Step 11 - Delete All UTD Specific Security Policies
        # version = self.utilities.get_vmanage_version()
        # definitionList = []
        # # TODO: implement a proper semver comparison, this will fail if version is 18.30.0
        # if version >= '18.4.0':
        #     definitionList = [
        #         'zonebasedfw', 'urlfiltering', 'dnssecurity', 'intrusionprevention', 'advancedMalwareProtection'
        #     ]
        # #pylint: disable=chained-comparison
        # if version < '18.4.0' and version >= '18.2.0':
        #     definitionList = ['zonebasedfw']

        # if definitionList:
        #     for definition in definitionList:
        #         data = self.sec_pol.get_security_definition(definition)
        #         if data:
        #             for policy in data:
        #                 definitionId = policy['definitionId']
        #                 self.sec_pol.delete_security_definition(definition, definitionId)
        # self.active_count_delay()

        # # Step 12 - Delete All Lists

        # data = self.pol_lists.get_policy_list_all()
        # for policy_list in data:
        #     owner = policy_list['owner']

        #     if owner != 'system':
        #         listType = policy_list['type'].lower()
        #         listId = policy_list['listId']
        #         self.pol_lists.delete_policy_list(listType, listId)

    def clean_all(self):
        """Clean everything in vManage

        """
        # Step 1 - Deactivate Central Policy
        self.clean_central_policy()

        # Step 2 - Detach vedges from template
        self.clean_vedge_attachments()

        # Step 3 - Detach controllers from template
        self.clean_controller_attachments()

        # Step 4 - Delete All Device Templates
        self.clean_device_templates()

        # Step 5 - Delete All Feature Templates
        self.clean_feature_templates()

        # Step 6 - Delete All Centralized Policies
        self.clean_central_policy()

        # Step 7 - Delete All Policy Definitions
        self.clean_policy_definitions()

        # Step 8 - Delete All Policy Lists
        self.clean_policy_lists()

        # Step 9 - Delete All Local Policies
        self.clean_local_policy()

        # Step 10 - Delete All Security Policies
        self.clean_security_policy()

        return ('Reset Complete')
Ejemplo n.º 20
0
 def load_serial_file(self):
     self.__logger.info(f'[orange1]Load license file')
     vmanage_utilities = Utilities(self.vm_auth, self.vm_mgmt_ip)
     result = vmanage_utilities.upload_file(self.serial_file)
     self.__logger.info(result)
Ejemplo n.º 21
0
    def import_attachment_list(self,
                               attachment_list,
                               check_mode=False,
                               update=False):
        """Import a list of device attachments to vManage.


        Args:
            attachment_list (list): List of attachments
            check_mode (bool): Only check to see if changes would be made
            update (bool): Update the template if it exists

        Returns:
            result (list): Returns the diffs of the updates.

        """
        attachment_updates = {}
        attachment_failures = {}
        action_id_list = []
        device_template_dict = self.device_templates.get_device_template_dict()
        vmanage_device = Device(self.session, self.host, self.port)
        for attachment in attachment_list:
            if attachment['template'] in device_template_dict:
                if attachment['device_type'] == 'vedge':
                    # The UUID is fixes from the serial file/upload
                    device_uuid = attachment['uuid']
                else:
                    # If this is not a vedge, we need to get the UUID from the vmanage since
                    # it is generated by that vmanage
                    device_status = vmanage_device.get_device_status(
                        attachment['host_name'], key='host-name')
                    if device_status:
                        device_uuid = device_status['uuid']
                    else:
                        raise Exception(
                            f"Cannot find UUID for {attachment['host_name']}")

                template_id = device_template_dict[
                    attachment['template']]['templateId']
                attached_uuid_list = self.device_templates.get_attachments(
                    template_id, key='uuid')
                if device_uuid in attached_uuid_list:
                    # The device is already attached to the template.  We need to see if any of
                    # the input changed, so we make an API call to get the input on last attach
                    existing_template_input = self.device_templates.get_template_input(
                        device_template_dict[attachment['template']]
                        ['templateId'], [device_uuid])
                    current_variables = existing_template_input['data'][0]
                    changed = False
                    for property_name in attachment['variables']:
                        # Check to see if any of the passed in varibles have changed from what is
                        # already on the attachment.  We are are not checking to see if the
                        # correct variables are here.  That will be done on attachment.
                        if ((property_name in current_variables) and
                            (str(attachment['variables'][property_name]) !=
                             str(current_variables[property_name]))):
                            changed = True
                    if changed:
                        if not check_mode and update:
                            action_id = self.device_templates.attach_to_template(
                                template_id, device_uuid,
                                attachment['system_ip'],
                                attachment['host_name'], attachment['site_id'],
                                attachment['variables'])
                            action_id_list.append(action_id)
                else:
                    if not check_mode:
                        action_id = self.device_templates.attach_to_template(
                            template_id, device_uuid, attachment['system_ip'],
                            attachment['host_name'], attachment['site_id'],
                            attachment['variables'])
                        action_id_list.append(action_id)
            else:
                raise Exception(f"No template named {attachment['template']}")

        utilities = Utilities(self.session, self.host)
        # Batch the waits so that the peocessing of the attachments is in parallel
        for action_id in action_id_list:
            result = utilities.waitfor_action_completion(action_id)
            data = result['action_response']['data'][0]
            if result['action_status'] == 'failure':
                attachment_failures.update(
                    {data['uuid']: data['currentActivity']})
            else:
                attachment_updates.update(
                    {data['uuid']: data['currentActivity']})

        result = {
            'updates': attachment_updates,
            'failures': attachment_failures
        }
        return result