Ejemplo n.º 1
0
 def setUp(self):
     super(TestPnfServiceAppliance, self).setUp()
     logger.debug("setUp called")
     # Create Global system config object
     self.gsc_obj = self.api.global_system_config_read(
         GlobalSystemConfig().fq_name)
     self.default_gsc_name = 'default-global-system-config'
     # Create Service Appliance Set object
     self.sas_obj = ServiceApplianceSet('sas-' + self.id(), self.gsc_obj)
     self.sas_obj.set_service_appliance_set_virtualization_type(
         'physical-device')
     self.api.service_appliance_set_create(self.sas_obj)
     # Create PNF Physical Router object
     self.pnf_obj = PhysicalRouter('pnf-' + self.id(), self.gsc_obj)
     self.pnf_obj.set_physical_router_role('pnf')
     self.api.physical_router_create(self.pnf_obj)
     # Create spine Physical Router object
     self.spine_obj = PhysicalRouter('spine-' + self.id(), self.gsc_obj)
     self.api.physical_router_create(self.spine_obj)
     # create left, right PNF PI
     self.left_pnf_pi_obj = PhysicalInterface(
         'ge-0/0/1-' + self.id(), parent_obj=self.pnf_obj)
     self.right_pnf_pi_obj = PhysicalInterface(
         'ge-0/0/2-' + self.id(), parent_obj=self.pnf_obj)
     self.api.physical_interface_create(self.left_pnf_pi_obj)
     self.api.physical_interface_create(self.right_pnf_pi_obj)
     # create left, right spine PI
     self.left_spine_pi_obj = PhysicalInterface(
         'xe-0/0/1-' + self.id(), parent_obj=self.spine_obj)
     self.right_spine_pi_obj = PhysicalInterface(
         'xe-0/0/2-' + self.id(), parent_obj=self.spine_obj)
     self.api.physical_interface_create(self.left_spine_pi_obj)
     self.api.physical_interface_create(self.right_spine_pi_obj)
    def _pr_object_create_update(self, oid_mapped, fq_name, update):
        pr_uuid = None
        msg = None
        try:
            os_version = oid_mapped.get('os-version', None)
            serial_num = oid_mapped.get('serial-number', None)
            physicalrouter = PhysicalRouter(
                parent_type='global-system-config',
                fq_name=fq_name,
                physical_router_management_ip=oid_mapped.get('host'),
                physical_router_vendor_name=oid_mapped.get('vendor'),
                physical_router_product_name=oid_mapped.get('product'),
                physical_router_device_family=oid_mapped.get('family'),
                physical_router_vnc_managed=True,
                physical_router_user_credentials={
                    'username': oid_mapped.get('username'),
                    'password': oid_mapped.get('password')
                })
            if update:
                pr_unicode_obj = self.vncapi.physical_router_update(
                    physicalrouter)
                if pr_unicode_obj:
                    pr_obj_dict = ast.literal_eval(pr_unicode_obj)
                    pr_uuid = pr_obj_dict['physical-router']['uuid']
                    msg = "Discovered %s:\n   Host name: %s\n   Vendor: %s\n" \
                          "   Model: %s" % (
                        oid_mapped.get('host'),
                        fq_name[1],
                        oid_mapped.get('vendor'),
                        oid_mapped.get('product')
                    )
                    self.logger.info("Discovered {} : {}".format(
                        oid_mapped.get('host'), pr_uuid))
            else:
                # underlay_managed flag should only be set at physical-router
                # creation time
                physicalrouter.set_physical_router_underlay_managed(
                    self.job_ctx.get('job_input').get('manage_underlay', True))
                pr_uuid = self.vncapi.physical_router_create(physicalrouter)
                msg = "Discovered device details: {} : {} : {}".format(
                    oid_mapped.get('host'), fq_name[1],
                    oid_mapped.get('product'))
                self.logger.info("Device created with uuid- {} : {}".format(
                    oid_mapped.get('host'), pr_uuid))
            self.module.send_prouter_object_log(fq_name, "DISCOVERED",
                                                os_version, serial_num)
        except (RefsExistError, Exception) as ex:
            if isinstance(ex, RefsExistError):
                return REF_EXISTS_ERROR, None
            self.logger.error("VNC create failed with error: {}".format(
                str(ex)))
            return False, None

        self.module.send_job_object_log(
            msg,
            JOB_IN_PROGRESS,
            None,
            job_success_percent=self.per_greenlet_percentage)
        self.discovery_percentage_write()
        return True, pr_uuid
    def test_logical_interface_create_qfx_l3(self):
        # create test device object
        phy_router_obj = PhysicalRouter(
            parent_type='global-system-config',
            fq_name=[
                "default-global-system-config",
                "test_device_qfx_%s" % self.id()
            ],
            physical_router_management_ip="1.1.1.1",
            physical_router_vendor_name="juniper",
            physical_router_product_name="qfx5k",
            physical_router_user_credentials={
                "username": "******",
                "password": "******"
            },
            physical_router_device_family='junos-qfx')
        self._vnc_lib.physical_router_create(phy_router_obj)

        phy_int_obj = PhysicalInterface(name="phy_intf_qfx_%s" % self.id(),
                                        parent_obj=phy_router_obj)
        self._vnc_lib.physical_interface_create(phy_int_obj)

        log_int_obj = LogicalInterface(name="log_intf_qfx_%s" % self.id(),
                                       parent_obj=phy_int_obj,
                                       logical_interface_vlan_tag=2,
                                       logical_interface_type='l3')

        self.assertIsNotNone(
            self._vnc_lib.logical_interface_create(log_int_obj))
    def test_logical_interface_create_qfx_l2(self):
        # create test device object
        phy_router_obj = PhysicalRouter(
            parent_type='global-system-config',
            fq_name=[
                "default-global-system-config",
                "test_device_qfx_%s" % self.id()
            ],
            physical_router_management_ip="1.1.1.1",
            physical_router_vendor_name="juniper",
            physical_router_product_name="qfx5k",
            physical_router_user_credentials={
                "username": "******",
                "password": "******"
            },
            physical_router_device_family='junos-qfx')
        self._vnc_lib.physical_router_create(phy_router_obj)

        phy_int_obj = PhysicalInterface(name="phy_intf_qfx_%s" % self.id(),
                                        parent_obj=phy_router_obj)
        self._vnc_lib.physical_interface_create(phy_int_obj)

        log_int_obj = LogicalInterface(name="log_intf_qfx_%s" % self.id(),
                                       parent_obj=phy_int_obj,
                                       logical_interface_vlan_tag=2,
                                       logical_interface_type='l2')

        regex_msg = (r"Vlan ids \[1, 2, 4094\] are not allowed on "
                     "QFX logical interface type: l2")
        self.assertRaisesRegexp(BadRequest, regex_msg,
                                self._vnc_lib.logical_interface_create,
                                log_int_obj)
 def create_qfx_and_pi(self, pr_and_pi):
     logger.warn("Creating PR")
     for pr_data in pr_and_pi:
         pr = PhysicalRouter(pr_data)
         pr_uuid = self.api.physical_router_create(pr)
         pr_obj = self.api.physical_router_read(id=pr_uuid)
         logger.warn("Created PR: " + pr_data)
         for pi_data in pr_and_pi[pr_data]:
             logger.warn("    Created PI: " + pr_data + " => " + pi_data)
             pi_obj = PhysicalInterface(name=pi_data, parent_obj=pr_obj)
             self.api.physical_interface_create(pi_obj)
Ejemplo n.º 6
0
    def create_image_and_device(self, img_name, img_uri, img_version,
                                img_family, img_vendor, device_family,
                                device_vendor, prouter_ip, prouter_password,
                                device_name):
        """create image and physical device"""
        img_fqname = None
        device_fqname = None
        try:
            self._logger.info('Creating image: %s', img_name)
            img_fqname = ['default-global-system-config', img_name]
            image = DeviceImage(name=img_name,
                                fq_name=img_fqname,
                                parent_type='global-system-config',
                                device_image_file_uri=img_uri,
                                device_image_os_version=img_version,
                                device_image_device_family=img_family,
                                device_image_vendor_name=img_vendor)
            img_uuid = self._api.device_image_create(image)
            image = self._api.device_image_read(id=img_uuid)

        except RefsExistError:
            self._logger.warn("Image '%s' already exists", img_name)
            image = self._api.device_image_read(fq_name=img_fqname)

        self._logger.debug(
            "Image created:\n%s",
            pprint.pformat(self._api.obj_to_dict(image), indent=4))

        try:
            self._logger.info('Creating device: %s', device_name)
            device_fqname = ['default-global-system-config', device_name]
            device = PhysicalRouter(
                name=device_name,
                fq_name=device_fqname,
                physical_router_device_family=device_family,
                physical_router_management_ip=prouter_ip,
                physical_router_vendor_name=device_vendor,
                physical_router_user_credentials={
                    'username': '******',
                    'password': prouter_password
                })
            device_uuid = self._api.physical_router_create(device)
            device = self._api.physical_router_read(id=device_uuid)

        except RefsExistError:
            self._logger.warn("Device '%s' already exists", device_name)
            device = self._api.physical_router_read(fq_name=device_fqname)

        self._logger.debug(
            "Device created:\n%s",
            pprint.pformat(self._api.obj_to_dict(device), indent=4))

        return image, device
Ejemplo n.º 7
0
def _pr_object_create_update(vncapi, device_info, fq_name, module, update,
                             per_greenlet_percentage):
    pr_uuid = None
    logger = module.logger
    try:
        os_version = device_info.get('os-version', None)
        serial_num = device_info.get('serial-number', None)
        physicalrouter = PhysicalRouter(
            parent_type='global-system-config',
            fq_name=fq_name,
            physical_router_management_ip=device_info.get('host'),
            physical_router_vendor_name=device_info.get('vendor'),
            physical_router_product_name=device_info.get('product'),
            physical_router_device_family=device_info.get('family'),
            physical_router_vnc_managed=True,
            physical_router_user_credentials={
                'username': device_info.get('username'),
                'password': device_info.get('password')
            })
        if update:
            pr_unicode_obj = vncapi.physical_router_update(physicalrouter)
            if pr_unicode_obj:
                pr_obj_dict = ast.literal_eval(pr_unicode_obj)
                pr_uuid = pr_obj_dict['physical-router']['uuid']
                msg = "Updated device info for: {} : {} : {}".format(
                    device_info.get('host'), fq_name[1],
                    device_info.get('product'))
                logger.info("Updated device info for: {} : {}".format(
                    device_info.get('host'), pr_uuid))
        else:
            pr_uuid = vncapi.physical_router_create(physicalrouter)
            msg = "Discovered device details: {} : {} : {}".format(
                device_info.get('host'), fq_name[1],
                device_info.get('product'))
            logger.info("Device created with uuid- {} : {}".format(
                device_info.get('host'), pr_uuid))
            module.send_prouter_object_log(fq_name, "DISCOVERED", os_version,
                                           serial_num)
    except (RefsExistError, Exception) as ex:
        if isinstance(ex, RefsExistError):
            return REF_EXISTS_ERROR, None
        logger.error("VNC create failed with error: {}".format(str(ex)))
        return False, None
    module.send_job_object_log(msg,
                               JOB_IN_PROGRESS,
                               None,
                               job_success_percent=per_greenlet_percentage)
    return True, pr_uuid
    def test_physical_interface_ae_id_alloc_and_free(self):
        AE_ID_TEST_CASES = [3, 127]

        mock_zk = self._api_server._db_conn._zk_db

        pr_name = self.id() + '_physical_router'
        pr = PhysicalRouter(pr_name)
        pr_uuid = self._vnc_lib.physical_router_create(pr)
        pr_obj = self._vnc_lib.physical_router_read(id=pr_uuid)

        for ae_id in AE_ID_TEST_CASES:
            pi_name = 'ae' + str(ae_id)
            pi = PhysicalInterface(name=pi_name, parent_obj=pr_obj)
            pi_uuid = self._vnc_lib.physical_interface_create(pi)
            self.assertEqual(pi_name,
                             mock_zk.ae_id_is_occupied(pr_name, ae_id))
            self._vnc_lib.physical_interface_delete(id=pi_uuid)
            self.assertFalse(mock_zk.ae_id_is_occupied(pr_name, ae_id))

        self._vnc_lib.physical_router_delete(id=pr_uuid)
    def test_physical_interface_ae_id_is_busy(self):
        AE_ID = 3
        NAME_OF_OBJECT_OCCUPING_AE_ID = 'VPG_1'

        mock_zk = self._api_server._db_conn._zk_db

        pr_name = self.id() + '_physical_router'
        pr = PhysicalRouter(pr_name)
        pr_uuid = self._vnc_lib.physical_router_create(pr)
        pr_obj = self._vnc_lib.physical_router_read(id=pr_uuid)

        pi_name = 'ae' + str(AE_ID)
        mock_zk.alloc_ae_id(pr_name, NAME_OF_OBJECT_OCCUPING_AE_ID, AE_ID)
        self.assertEqual(NAME_OF_OBJECT_OCCUPING_AE_ID,
                         mock_zk.ae_id_is_occupied(pr_name, AE_ID))

        pi = PhysicalInterface(name=pi_name, parent_obj=pr_obj)
        self.assertRaises(PermissionDenied,
                          self._vnc_lib.physical_interface_create, pi)
        self.assertEqual(NAME_OF_OBJECT_OCCUPING_AE_ID,
                         mock_zk.ae_id_is_occupied(pr_name, AE_ID))

        self._vnc_lib.physical_router_delete(id=pr_uuid)
        mock_zk.free_ae_id(pr_name, AE_ID, NAME_OF_OBJECT_OCCUPING_AE_ID)
Ejemplo n.º 10
0
def _pr_object_create(
        vncapi,
        oid_mapped,
        fq_name,
        logger,
        object_log,
        fabric_uuid):
    try:
        physicalrouter = PhysicalRouter(
            parent_type='global-system-config',
            fq_name=fq_name,
            physical_router_management_ip=oid_mapped.get('host'),
            physical_router_vendor_name=oid_mapped.get('vendor'),
            physical_router_product_name=oid_mapped.get('product'),
            physical_router_device_family=oid_mapped.get('family'),
            physical_router_vnc_managed=True,
            physical_router_user_credentials={
                'username': oid_mapped.get('username'),
                'password': oid_mapped.get('password')
            }
        )
        pr_uuid = vncapi.physical_router_create(physicalrouter)
    except(RefsExistError, Exception) as ex:
        if isinstance(ex, RefsExistError):
            return REF_EXISTS_ERROR
        logger.error("VNC create failed with error: {}".format(str(ex)))
        return False

    msg = "Discovered device details: {} : {} : {}".format(
        oid_mapped.get('host'), fq_name[1], oid_mapped.get('product'))
    logger.info("Device created with uuid- {} : {}".format(oid_mapped.get(
        'host'), pr_uuid))
    vncapi.ref_update(
        "fabric", fabric_uuid, "physical_router", pr_uuid, None, "ADD")
    _send_sandesh_log(object_log, msg, logger, False)
    return True
Ejemplo n.º 11
0
    def _pr_object_create_update(self, oid_mapped, fq_name, update):
        pr_uuid = None
        msg = None
        dhcp_fq_name = None

        try:
            os_version = oid_mapped.get('os-version', None)
            serial_num = oid_mapped.get('serial-number', None)
            physicalrouter = PhysicalRouter(
                parent_type='global-system-config',
                fq_name=fq_name,
                physical_router_management_ip=oid_mapped.get('host'),
                physical_router_vendor_name=oid_mapped.get('vendor'),
                physical_router_product_name=oid_mapped.get('product'),
                physical_router_device_family=oid_mapped.get('family'),
                physical_router_vnc_managed=True,
                physical_router_snmp_credentials={
                    'version': 2,
                    'v2_community': 'public',
                    'local_port': 161
                },
                physical_router_hostname=fq_name[-1],
                display_name=fq_name[-1],
                physical_router_serial_number=serial_num,
                physical_router_managed_state='active',
                physical_router_user_credentials={
                    'username': oid_mapped.get('username'),
                    'password': oid_mapped.get('password')
                },
                physical_router_encryption_type='none',
                physical_router_supplemental_config=oid_mapped.get(
                    'supplemental_config')  # noqa: E501
            )
            if update:
                pr_unicode_obj = self.vncapi.physical_router_update(
                    physicalrouter)
                if pr_unicode_obj:
                    pr_obj_dict = ast.literal_eval(pr_unicode_obj)
                    pr_uuid = pr_obj_dict['physical-router']['uuid']
                    msg = "Discovered %s:\n   Host name: %s\n   Vendor: %s\n" \
                          "   Model: %s" % (
                              oid_mapped.get('host'),
                              fq_name[1],
                              oid_mapped.get('vendor'),
                              oid_mapped.get('product')
                          )
                    self.logger.info("Discovered {} : {}".format(
                        oid_mapped.get('host'), pr_uuid))
            else:
                # underlay_managed flag should only be set at physical-router
                # creation time
                physicalrouter.set_physical_router_underlay_managed(
                    self.job_ctx.get('job_input').get('manage_underlay', True))
                pr_uuid = self.vncapi.physical_router_create(physicalrouter)
                msg = "Discovered device details: {} : {} : {}".format(
                    oid_mapped.get('host'), fq_name[1],
                    oid_mapped.get('product'))
                self.logger.info("Device created with uuid- {} : {}".format(
                    oid_mapped.get('host'), pr_uuid))
            self.module.send_prouter_object_log(fq_name, "DISCOVERED",
                                                os_version, serial_num)
        except (RefsExistError, Exception) as ex:
            if isinstance(ex, RefsExistError):
                return REF_EXISTS_ERROR, None
            self.logger.error("VNC create failed with error: {}".format(
                str(ex)))
            return False, None

        try:
            # delete the corresponding dhcp state PR object if it exists
            dhcp_fq_name = [
                'default-global-system-config',
                oid_mapped.get('serial-number')
            ]
            pr_obj = self.vncapi.physical_router_read(
                fq_name=dhcp_fq_name, fields=['physical_router_managed_state'])

            if pr_obj.get_physical_router_managed_state() == 'dhcp':
                self.vncapi.physical_router_delete(fq_name=dhcp_fq_name)
                self.logger.info(
                    "Router {} in dhcp state deleted".format(dhcp_fq_name))
        except (NoIdError, Exception) as ex:
            self.logger.info(
                "Router {} in dhcp state doesn't exist. Failed with "
                "error {}".format(dhcp_fq_name, str(ex)))
            pass

        self.module.send_job_object_log(
            msg,
            JOB_IN_PROGRESS,
            None,
            job_success_percent=self.per_greenlet_percentage)
        self.discovery_percentage_write()
        return True, pr_uuid
Ejemplo n.º 12
0
def main():
    logging.basicConfig(filename=DEFAULT_LOG_PATH,
                        level=logging.INFO,
                        format=LOGGING_FORMAT,
                        datefmt=DATE_FORMAT)
    logger = logging.getLogger("dnsmasq")
    logger.setLevel(logging.INFO)
    vnc_api = _initialize_vnc()
    if sys.argv[1] == 'read':
        # read from DB mac:ip
        filters = {}
        lease = 0
        filters['physical_router_managed_state'] = "dhcp"
        for pr in vnc_api.physical_routers_list(
                filters=filters).get('physical-routers'):
            device_obj = vnc_api.physical_router_read(
                id=pr.get('uuid'),
                fields=[
                    'physical_router_management_mac',
                    'physical_router_management_ip',
                    'physical_router_dhcp_parameters'
                ])
            if device_obj.get_physical_router_dhcp_parameters():
                lease = device_obj.get_physical_router_dhcp_parameters().\
                        lease_expiry_time

            print("DNSMASQ_LEASE=%s %s %s * *" %
                  (lease, device_obj.get_physical_router_management_mac(),
                   device_obj.get_physical_router_management_ip()))
            logger.info(
                "DNSMASQ_LEASE=%s %s %s * *" %
                (lease, device_obj.get_physical_router_management_mac(),
                 device_obj.get_physical_router_management_ip()))
    elif sys.argv[1] == 'write':
        # write to the DB dummy PR with mac:ip
        fq_name = ['default-global-system-config', sys.argv[4]]
        physicalrouter = PhysicalRouter(
            parent_type='global-system-config',
            fq_name=fq_name,
            physical_router_management_mac=sys.argv[2],
            physical_router_management_ip=sys.argv[3],
            physical_router_managed_state='dhcp',
            physical_router_hostname=sys.argv[4],
            physical_router_dhcp_parameters={'lease_expiry_time': sys.argv[5]},
            physical_router_device_family=sys.argv[6])
        try:
            pr_uuid = vnc_api.physical_router_create(physicalrouter)
        except Exception:
            logger.info("Router '%s' already exists, hence updating it" %
                        fq_name[-1])
            pr_uuid = vnc_api.physical_router_update(physicalrouter)

        logger.info("DNSMASQ_LEASE_OBTAINED=%s %s %s" %
                    (sys.argv[4], sys.argv[2], sys.argv[3]))
        logger.info("Router created id: %s" % pr_uuid)
    elif sys.argv[1] == 'delete':
        object_type = "physical_router"
        device_family = ""
        fq_name = ['default-global-system-config', sys.argv[2]]
        try:
            pr_uuid = vnc_api.fq_name_to_id(object_type, fq_name)
            device_obj = vnc_api.physical_router_read(
                id=pr_uuid, fields=['physical_router_device_family'])
            device_family = device_obj.get_physical_router_device_family()
            logger.info("Device Family %s", device_family)
            if "qfx5220" not in device_family:
                vnc_api.physical_router_delete(fq_name=fq_name)
        except Exception:
            logger.info("Router '%s' doesnot exist" % fq_name[-1])
Ejemplo n.º 13
0
    def _pr_object_create_update(
            self,
            oid_mapped,
            fq_name,
            update):
        pr_uuid = None
        msg = None
        try:
            os_version = oid_mapped.get('os-version', None)
            serial_num = oid_mapped.get('serial-number', None)
            physicalrouter = PhysicalRouter(
                parent_type='global-system-config',
                fq_name=fq_name,
                physical_router_management_ip=oid_mapped.get('host'),
                physical_router_vendor_name=oid_mapped.get('vendor'),
                physical_router_product_name=oid_mapped.get('product'),
                physical_router_device_family=oid_mapped.get('family'),
                physical_router_vnc_managed=True,
                physical_router_hostname=fq_name[-1],
                display_name=fq_name[-1],
                physical_router_serial_number=serial_num,
                physical_router_managed_state='active',
                physical_router_user_credentials={
                    'username': oid_mapped.get('username'),
                    'password': oid_mapped.get('password')
                }
            )
            if update:
                pr_unicode_obj = self.vncapi.physical_router_update(
                    physicalrouter)
                if pr_unicode_obj:
                    pr_obj_dict = ast.literal_eval(pr_unicode_obj)
                    pr_uuid = pr_obj_dict['physical-router']['uuid']
                    msg = "Discovered %s:\n   Host name: %s\n   Vendor: %s\n" \
                          "   Model: %s" % (
                        oid_mapped.get('host'),
                        fq_name[1],
                        oid_mapped.get('vendor'),
                        oid_mapped.get('product')
                    )
                    self.logger.info("Discovered {} : {}".format(
                        oid_mapped.get('host'), pr_uuid
                    ))
            else:
                # underlay_managed flag should only be set at physical-router
                # creation time
                physicalrouter.set_physical_router_underlay_managed(
                    self.job_ctx.get('job_input').get('manage_underlay', True)
                )
                pr_uuid = self.vncapi.physical_router_create(physicalrouter)
                msg = "Discovered device details: {} : {} : {}".format(
                    oid_mapped.get('host'), fq_name[1], oid_mapped.get(
                        'product'))
                self.logger.info("Device created with uuid- {} : {}".format(
                    oid_mapped.get(
                        'host'), pr_uuid))
            self.module.send_prouter_object_log(fq_name, "DISCOVERED",
                                                os_version, serial_num)
        except(RefsExistError, Exception) as ex:
            if isinstance(ex, RefsExistError):
                return REF_EXISTS_ERROR, None
            self.logger.error("VNC create failed with error: {}".format(str(
                ex)))
            return False, None

        self.module.send_job_object_log(
            msg,
            JOB_IN_PROGRESS,
            None,
            job_success_percent=self.per_greenlet_percentage)
        self.discovery_percentage_write()
        return True, pr_uuid
    def test_physical_interface_esi(self):
        pr_name = self.id() + '_physical_router'
        pr = PhysicalRouter(pr_name)
        pr_uuid = self._vnc_lib.physical_router_create(pr)
        pr_obj = self._vnc_lib.physical_router_read(id=pr_uuid)

        esi_id = '00:11:22:33:44:55:66:77:88:99'

        pi1_name = self.id() + '_physical_interface1'
        pi1 = PhysicalInterface(name=pi1_name,
                                parent_obj=pr_obj,
                                ethernet_segment_identifier=esi_id)
        pi1_uuid = self._vnc_lib.physical_interface_create(pi1)
        pi1_obj = self._vnc_lib.physical_interface_read(id=pi1_uuid)

        li1_name = pi1_name + '_li1'
        li1 = LogicalInterface(name=li1_name,
                               parent_obj=pi1_obj,
                               logical_interface_vlan_tag=2)

        vn_name = self.id() + '_test_vn'
        vn = VirtualNetwork(vn_name)
        vn_uuid = self._vnc_lib.virtual_network_create(vn)
        vn_obj = self._vnc_lib.virtual_network_read(id=vn_uuid)

        vmi_name = self.id() + '_common_vmi'
        vmi_obj = self._create_vmi(vmi_name, vn_obj)

        li1.add_virtual_machine_interface(vmi_obj)
        li1_uuid = self._vnc_lib.logical_interface_create(li1)
        self._vnc_lib.logical_interface_read(id=li1_uuid)

        pi2_name = self.id() + '_physical_interface2'
        pi2 = PhysicalInterface(name=pi2_name,
                                parent_obj=pr_obj,
                                ethernet_segment_identifier=esi_id)
        pi2_uuid = self._vnc_lib.physical_interface_create(pi2)
        pi2_obj = self._vnc_lib.physical_interface_read(id=pi2_uuid)

        li2_name = pi2_name + '_li2'
        li2 = LogicalInterface(name=li2_name,
                               parent_obj=pi2_obj,
                               logical_interface_vlan_tag=2)

        second_vmi_name = self.id() + '_2nd_vmi'
        second_vmi_obj = self._create_vmi(second_vmi_name, vn_obj,
                                          'AA:AA:AA:AA:AA:AA')
        li2.add_virtual_machine_interface(second_vmi_obj)

        self.assertRaises(PermissionDenied,
                          self._vnc_lib.logical_interface_create, li2)

        li2 = LogicalInterface(name=li2_name,
                               parent_obj=pi2_obj,
                               logical_interface_vlan_tag=2)
        li2_uuid = self._vnc_lib.logical_interface_create(li2)
        li2_obj = self._vnc_lib.logical_interface_read(id=li2_uuid)
        li2_obj.add_virtual_machine_interface(second_vmi_obj)

        self.assertRaises(PermissionDenied,
                          self._vnc_lib.logical_interface_update, li2_obj)

        pi3_name = self.id() + '_physical_interface3'
        pi3 = PhysicalInterface(
            name=pi3_name,
            parent_obj=pr_obj,
            ethernet_segment_identifier='00:00:00:00:00:00:00:00:00:AA')
        pi3_uuid = self._vnc_lib.physical_interface_create(pi3)
        pi3_obj = self._vnc_lib.physical_interface_read(id=pi3_uuid)

        li3_name = pi3_name + '_li3'
        li3 = LogicalInterface(name=li3_name,
                               parent_obj=pi3_obj,
                               logical_interface_vlan_tag=2)

        li3.add_virtual_machine_interface(vmi_obj)
        self._vnc_lib.logical_interface_create(li3)
        pi3_obj.set_ethernet_segment_identifier(esi_id)
        self._vnc_lib.physical_interface_update(pi3_obj)
Ejemplo n.º 15
0
    def setUp(self):
        def _carve_out_subnets(subnets, cidr):
            carved_subnets = []
            for subnet in subnets:
                slash_x_subnets = IPNetwork(subnet.get('cidr')).subnet(cidr)
                for slash_x_sn in slash_x_subnets:
                    carved_subnets.append({'cidr': str(slash_x_sn)})
            return carved_subnets
        # end _carve_out_subnets

        def _get_network_ipam(ipam_name, subnets, subnetting):
            def _new_subnet(cidr):
                split_cidr = cidr.split('/')
                return SubnetType(
                    ip_prefix=split_cidr[0],
                    ip_prefix_len=split_cidr[1])
            # end _new_subnet
            ipam = NetworkIpam(
                name=ipam_name,
                ipam_subnets=IpamSubnets([
                    IpamSubnetType(
                        subnet=_new_subnet(sn.get('cidr')),
                        default_gateway=sn.get('gateway'),
                        subnet_uuid=str(uuid.uuid1())
                    ) for sn in subnets if int(
                        sn.get('cidr').split('/')[-1]) < 31
                ]),
                ipam_subnet_method='flat-subnet',
                ipam_subnetting=subnetting
            )
            return ipam
        # end _add_network_ipam
        super(TestPnfPortTuple, self).setUp()
        logger.debug("setUp called")
        # Create Global objects
        default_gsc_name = 'default-global-system-config'
        gsc_obj = self.api.global_system_config_read(
            GlobalSystemConfig().fq_name)
        proj_obj = self.api.project_read(Project().fq_name)
        # Create PNF and spine Physical Router
        pnf_obj = PhysicalRouter('pnf-' + self.id(), gsc_obj)
        pnf_obj.set_physical_router_role('pnf')
        self.pnf_uuid = self.api.physical_router_create(pnf_obj)
        # Create spine Physical Router
        spine_obj = PhysicalRouter('spine-' + self.id(), gsc_obj)
        self.spine_uuid = self.api.physical_router_create(spine_obj)
        # Create left/right LR
        left_lr_name = 'left_lr-' + self.id()
        left_lr_obj = LogicalRouter(name=left_lr_name, parent_obj=proj_obj)
        left_lr_obj.add_physical_router(spine_obj)
        self.left_lr_uuid = self.api.logical_router_create(left_lr_obj)
        right_lr_name = 'right_lr-' + self.id()
        right_lr_obj = LogicalRouter(name=right_lr_name, parent_obj=proj_obj)
        right_lr_obj.add_physical_router(spine_obj)
        self.right_lr_uuid = self.api.logical_router_create(right_lr_obj)
        # create left, right PNF PI
        left_pnf_pi_obj = PhysicalInterface(
            'ge-0/0/1-' + self.id(), parent_obj=pnf_obj)
        right_pnf_pi_obj = PhysicalInterface(
            'ge-0/0/2-' + self.id(), parent_obj=pnf_obj)
        lo_pnf_pi_obj = PhysicalInterface('lo0', parent_obj=pnf_obj)
        self.left_pnf_pi_uuid = self.api.physical_interface_create(
            left_pnf_pi_obj)
        self.right_pnf_pi_uuid = self.api.physical_interface_create(
            right_pnf_pi_obj)
        self.lo_pnf_pi_uuid = self.api.physical_interface_create(lo_pnf_pi_obj)
        # create left, right spine PI
        left_spine_pi_obj = PhysicalInterface(
            'xe-0/0/1-' + self.id(), parent_obj=spine_obj)
        right_spine_pi_obj = PhysicalInterface(
            'xe-0/0/2-' + self.id(), parent_obj=spine_obj)
        self.left_spine_pi_uuid = self.api.physical_interface_create(
            left_spine_pi_obj)
        self.right_spine_pi_uuid = self.api.physical_interface_create(
            right_spine_pi_obj)
        # Create Service Appliance Set
        sas_obj = ServiceApplianceSet('sas-' + self.id(), gsc_obj)
        sas_obj.set_service_appliance_set_virtualization_type(
            'physical-device')
        self.sas_uuid = self.api.service_appliance_set_create(sas_obj)
        # Create Service template
        st_obj = ServiceTemplate(name='st-' + self.id())
        st_obj.set_service_appliance_set(sas_obj)
        svc_properties = ServiceTemplateType()
        svc_properties.set_service_virtualization_type('physical-device')
        if_type = ServiceTemplateInterfaceType()
        if_type.set_service_interface_type('left')
        svc_properties.add_interface_type(if_type)
        if_type = ServiceTemplateInterfaceType()
        if_type.set_service_interface_type('right')
        svc_properties.add_interface_type(if_type)
        st_obj.set_service_template_properties(svc_properties)
        self.st_uuid = self.api.service_template_create(st_obj)
        # Create Service Instance object
        si_fqn = ['default-domain', 'default-project', 'si-' + self.id()]
        si_obj = ServiceInstance(fq_name=si_fqn)
        si_obj.fq_name = si_fqn
        si_obj.add_service_template(st_obj)
        kvp_array = []
        kvp = KeyValuePair("left-svc-vlan", "100")
        kvp_array.append(kvp)
        kvp = KeyValuePair("right-svc-vlan", "101")
        kvp_array.append(kvp)
        kvp = KeyValuePair("left-svc-asns", "66000,66001")
        kvp_array.append(kvp)
        kvp = KeyValuePair("right-svc-asns", "66000,66002")
        kvp_array.append(kvp)
        kvps = KeyValuePairs()
        kvps.set_key_value_pair(kvp_array)
        si_obj.set_annotations(kvps)
        props = ServiceInstanceType()
        props.set_service_virtualization_type('physical-device')
        props.set_ha_mode("active-standby")
        si_obj.set_service_instance_properties(props)
        self.si_uuid = self.api.service_instance_create(si_obj)
        # Create service appliance
        sa_obj = ServiceAppliance('sa-' + self.id(), parent_obj=sas_obj)
        kvp_array = []
        kvp = KeyValuePair(
            "left-attachment-point",
            default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/1-' +
            self.id())
        kvp_array.append(kvp)
        kvp = KeyValuePair(
            "right-attachment-point",
            default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/2-' +
            self.id())
        kvp_array.append(kvp)
        kvps = KeyValuePairs()
        kvps.set_key_value_pair(kvp_array)
        sa_obj.set_service_appliance_properties(kvps)
        sa_obj.set_service_appliance_virtualization_type('physical-device')
        attr = ServiceApplianceInterfaceType(interface_type='left')
        sa_obj.add_physical_interface(left_pnf_pi_obj, attr)
        attr = ServiceApplianceInterfaceType(interface_type='right')
        sa_obj.add_physical_interface(right_pnf_pi_obj, attr)
        self.sa_uuid = self.api.service_appliance_create(sa_obj)
        # Create fabric and add it to spine and PNF
        fab_obj = Fabric('fab-' + self.id())
        self.fab_uuid = self.api.fabric_create(fab_obj)
        pnf_obj.add_fabric(fab_obj)
        self.api.physical_router_update(pnf_obj)
        spine_obj.add_fabric(fab_obj)
        self.api.physical_router_update(spine_obj)
        fab_obj = self.api.fabric_read(id=self.fab_uuid)
        # Create PNF service chain IPAM/network
        pnf_cidr = [{'cidr': "10.1.1.0/28"}]
        peer_subnets = _carve_out_subnets(pnf_cidr, 29)
        pnf_vn_obj = VirtualNetwork(
            name='fab-' + self.id() + '-pnf-servicechain-network',
            virtual_network_properties=VirtualNetworkType(
                forwarding_mode='l3'),
            address_allocation_mode='flat-subnet-only')
        self.pnf_vn_uuid = self.api.virtual_network_create(pnf_vn_obj)
        pnf_ipam_obj = _get_network_ipam(
            'fab-' +
            self.id() +
            '-pnf-servicechain-network-ipam',
            peer_subnets,
            True)
        self.pnf_ipam_uuid = self.api.network_ipam_create(pnf_ipam_obj)
        pnf_vn_obj.add_network_ipam(pnf_ipam_obj, VnSubnetsType([]))
        self.api.virtual_network_update(pnf_vn_obj)
        fab_obj = self.api.fabric_read(id=self.fab_uuid)
        fab_obj.add_virtual_network(
            pnf_vn_obj, FabricNetworkTag(
                network_type='pnf-servicechain'))
        self.api.fabric_update(fab_obj)
        # Create loopback IPAM/network
        lo_cidr = [{'cidr': "100.100.100.0/28"}]
        peer_subnets = _carve_out_subnets(lo_cidr, 28)
        lo_vn_obj = VirtualNetwork(
            name='fab-' + self.id() + '-loopback-network',
            virtual_network_properties=VirtualNetworkType(
                forwarding_mode='l3'),
            address_allocation_mode='flat-subnet-only')
        self.lo_vn_uuid = self.api.virtual_network_create(lo_vn_obj)
        lo_ipam_obj = _get_network_ipam(
            'fab-' +
            self.id() +
            '-loopback-network-ipam',
            peer_subnets,
            False)
        self.lo_ipam_uuid = self.api.network_ipam_create(lo_ipam_obj)
        lo_vn_obj.add_network_ipam(lo_ipam_obj, VnSubnetsType([]))
        self.api.virtual_network_update(lo_vn_obj)
        fab_obj = self.api.fabric_read(id=self.fab_uuid)
        fab_obj.add_virtual_network(
            lo_vn_obj, FabricNetworkTag(
                network_type='loopback'))
        self.api.fabric_update(fab_obj)
Ejemplo n.º 16
0
class TestPnfServiceAppliance(TestServiceApplianceBase):
    def setUp(self):
        super(TestPnfServiceAppliance, self).setUp()
        logger.debug("setUp called")
        # Create Global system config object
        self.gsc_obj = self.api.global_system_config_read(
            GlobalSystemConfig().fq_name)
        self.default_gsc_name = 'default-global-system-config'
        # Create Service Appliance Set object
        self.sas_obj = ServiceApplianceSet('sas-' + self.id(), self.gsc_obj)
        self.sas_obj.set_service_appliance_set_virtualization_type(
            'physical-device')
        self.api.service_appliance_set_create(self.sas_obj)
        # Create PNF Physical Router object
        self.pnf_obj = PhysicalRouter('pnf-' + self.id(), self.gsc_obj)
        self.pnf_obj.set_physical_router_role('pnf')
        self.api.physical_router_create(self.pnf_obj)
        # Create spine Physical Router object
        self.spine_obj = PhysicalRouter('spine-' + self.id(), self.gsc_obj)
        self.api.physical_router_create(self.spine_obj)
        # create left, right PNF PI
        self.left_pnf_pi_obj = PhysicalInterface(
            'ge-0/0/1-' + self.id(), parent_obj=self.pnf_obj)
        self.right_pnf_pi_obj = PhysicalInterface(
            'ge-0/0/2-' + self.id(), parent_obj=self.pnf_obj)
        self.api.physical_interface_create(self.left_pnf_pi_obj)
        self.api.physical_interface_create(self.right_pnf_pi_obj)
        # create left, right spine PI
        self.left_spine_pi_obj = PhysicalInterface(
            'xe-0/0/1-' + self.id(), parent_obj=self.spine_obj)
        self.right_spine_pi_obj = PhysicalInterface(
            'xe-0/0/2-' + self.id(), parent_obj=self.spine_obj)
        self.api.physical_interface_create(self.left_spine_pi_obj)
        self.api.physical_interface_create(self.right_spine_pi_obj)

    def tearDown(self):
        super(TestPnfServiceAppliance, self).tearDown()
        logger.debug("TearDown called")
        # delete PNF PI
        self.api.physical_interface_delete(id=self.left_pnf_pi_obj.uuid)
        self.api.physical_interface_delete(id=self.right_pnf_pi_obj.uuid)
        # delete spine PI
        self.api.physical_interface_delete(id=self.left_spine_pi_obj.uuid)
        self.api.physical_interface_delete(id=self.right_spine_pi_obj.uuid)
        # delete PNF PR and spine PR
        self.api.physical_router_delete(id=self.spine_obj.uuid)
        self.api.physical_router_delete(id=self.pnf_obj.uuid)
        # delete sas
        self.api.service_appliance_set_delete(id=self.sas_obj.uuid)

    def test_valid_sa(self):
        sa_obj = ServiceAppliance('sa-' + self.id(), parent_obj=self.sas_obj)
        kvp_array = []
        kvp = KeyValuePair(
            "left-attachment-point",
            self.default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/1-' +
            self.id())
        kvp_array.append(kvp)
        kvp = KeyValuePair(
            "right-attachment-point",
            self.default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/2-' +
            self.id())
        kvp_array.append(kvp)
        kvps = KeyValuePairs()
        kvps.set_key_value_pair(kvp_array)
        sa_obj.set_service_appliance_properties(kvps)
        sa_obj.set_service_appliance_virtualization_type('physical-device')

        # Add PNF PI refs
        attr = ServiceApplianceInterfaceType(interface_type='left')
        sa_obj.add_physical_interface(self.left_pnf_pi_obj, attr)
        attr = ServiceApplianceInterfaceType(interface_type='right')
        sa_obj.add_physical_interface(self.right_pnf_pi_obj, attr)

        # Create SA
        self.api.service_appliance_create(sa_obj)
        self.left_pnf_pi_obj = self.api.physical_interface_read(
            id=self.left_pnf_pi_obj.uuid)
        self.right_pnf_pi_obj = self.api.physical_interface_read(
            id=self.right_pnf_pi_obj.uuid)

        # Check if spine PI <-> PNF PI link has been created
        self.assertEqual(
            self.left_pnf_pi_obj.physical_interface_refs[0].get('uuid'),
            self.left_spine_pi_obj.uuid)
        self.assertEqual(
            self.right_pnf_pi_obj.physical_interface_refs[0].get('uuid'),
            self.right_spine_pi_obj.uuid)

        # Delete service appliance
        self.api.service_appliance_delete(id=sa_obj.uuid)

        # Check if spine PI <-> PNF PI link got removed
        self.left_pnf_pi_obj = self.api.physical_interface_read(
            id=self.left_pnf_pi_obj.uuid)
        self.right_pnf_pi_obj = self.api.physical_interface_read(
            id=self.right_pnf_pi_obj.uuid)
        self.assertFalse(
            hasattr(
                self.left_pnf_pi_obj,
                "physical_interface_refs"))
        self.assertFalse(
            hasattr(
                self.right_pnf_pi_obj,
                "physical_interface_refs"))

    def test_sa_with_invalid_kvp(self):
        sa_obj = ServiceAppliance('sa-' + self.id(), parent_obj=self.sas_obj)
        kvp_array = []
        kvp = KeyValuePair(
            "left-attachment-point",
            self.default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/1-' +
            self.id())
        kvp_array.append(kvp)
        kvp = KeyValuePair(
            "right-attachment-point",
            self.default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/2-' +
            self.id())
        # The next line is intentionally commented out
        # kvp_array.append(kvp)
        kvps = KeyValuePairs()
        kvps.set_key_value_pair(kvp_array)
        sa_obj.set_service_appliance_properties(kvps)
        sa_obj.set_service_appliance_virtualization_type('physical-device')

        # Add PNF PI refs
        attr = ServiceApplianceInterfaceType(interface_type='left')
        sa_obj.add_physical_interface(self.left_pnf_pi_obj, attr)
        attr = ServiceApplianceInterfaceType(interface_type='right')
        sa_obj.add_physical_interface(self.right_pnf_pi_obj, attr)

        # Create SA should raise exception
        self.assertRaises(
            BadRequest,
            self.api.service_appliance_create,
            sa_obj)

    def test_sa_with_invalid_pr_role(self):
        sa_obj = ServiceAppliance('sa-' + self.id(), parent_obj=self.sas_obj)
        kvp_array = []
        kvp = KeyValuePair(
            "left-attachment-point",
            self.default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/1-' +
            self.id())
        kvp_array.append(kvp)
        kvp = KeyValuePair(
            "right-attachment-point",
            self.default_gsc_name +
            ':' +
            'spine-' +
            self.id() +
            ':' +
            'xe-0/0/2-' +
            self.id())
        kvp_array.append(kvp)
        kvps = KeyValuePairs()
        kvps.set_key_value_pair(kvp_array)
        sa_obj.set_service_appliance_properties(kvps)
        sa_obj.set_service_appliance_virtualization_type('physical-device')

        # Add PNF PI refs
        attr = ServiceApplianceInterfaceType(interface_type='left')
        sa_obj.add_physical_interface(self.left_pnf_pi_obj, attr)
        attr = ServiceApplianceInterfaceType(interface_type='right')
        sa_obj.add_physical_interface(self.right_pnf_pi_obj, attr)

        # Overwrite the role as leaf instead of pnf
        self.pnf_obj.set_physical_router_role('leaf')
        self.api.physical_router_update(self.pnf_obj)
        # Create SA should raise exception
        self.assertRaises(BadRequest,
                          self.api.service_appliance_create,
                          sa_obj)