예제 #1
0
class TestXenaChassisShell(unittest.TestCase):

    session = None

    def setUp(self):
        self.session = CloudShellAPISession('localhost', 'admin', 'admin',
                                            'Global')

    def tearDown(self):
        for resource in self.session.GetResourceList('Testing').Resources:
            self.session.DeleteResource(resource.Name)

    def testHelloWorld(self):
        pass

    def test_xena_chassis(self):
        self._get_inventory('xena-chassis', xena_chassis['xena-chassis'])

    def _get_inventory(self, name, properties):
        attributes = [
            AttributeNameValue('Xena Chassis Shell 2G.Password',
                               properties['password'])
        ]
        resource = create_autoload_resource(self.session,
                                            'Xena Chassis Shell 2G',
                                            properties['address'], name,
                                            attributes)
        self.session.AutoLoad(resource.Name)
        resource_details = self.session.GetResourceDetails(resource.Name)
        assert (len(resource_details.ChildResources) == properties['modules'])
        self.session.DeleteResource(resource.Name)
예제 #2
0
def test_autoload_session(session: CloudShellAPISession,
                          autoload_resource: ResourceInfo,
                          dut: List[str]) -> None:
    """Test indirect (shell) auto load command."""
    session.AutoLoad(autoload_resource.Name)
    resource_details = session.GetResourceDetails(autoload_resource.Name)
    assert len(resource_details.ChildResources) == 1
    assert resource_details.ChildResources[0].FullAddress == f"{dut[0]}/M1"
class TestIxiaChassis2GShell(unittest.TestCase):

    session = None

    def setUp(self):
        self.session = CloudShellAPISession('localhost', 'admin', 'admin',
                                            'Global')

    def tearDown(self):
        for resource in self.session.GetResourceList('Testing').Resources:
            self.session.DeleteResource(resource.Name)

    def testHelloWorld(self):
        pass

    def test_win_ixos(self):
        self._get_inventory('win-ixos', ixia_chassis['win-ixos'])

    def test_lin_ixos(self):
        self._get_inventory('lin-ixos', ixia_chassis['lin-ixos'])

    def test_all(self):
        for key, value in ixia_chassis.items():
            self._get_inventory(key, value)

    def _get_inventory(self, name, properties):
        self.resource = self.session.CreateResource(
            resourceFamily='CS_TrafficGeneratorChassis',
            resourceModel='Ixia Chassis Shell 2G',
            resourceName=name,
            resourceAddress=properties['address'],
            folderFullPath='Testing',
            parentResourceFullPath='',
            resourceDescription='should be removed after test')
        self.session.UpdateResourceDriver(self.resource.Name,
                                          'Ixia Chassis Shell 2G')
        attributes = [
            AttributeNameValue('Ixia Chassis Shell 2G.Controller Address',
                               properties['controller']),
            AttributeNameValue('Ixia Chassis Shell 2G.Controller TCP Port',
                               properties['port']),
            AttributeNameValue('Ixia Chassis Shell 2G.Client Install Path', '')
        ]
        self.session.SetAttributesValues(
            ResourceAttributesUpdateRequest(self.resource.Name, attributes))
        self.session.AutoLoad(self.resource.Name)
        resource_details = self.session.GetResourceDetails(self.resource.Name)
        assert (len(resource_details.ChildResources) == properties['modules'])
        self.session.DeleteResource(self.resource.Name)
class TestIxiaChassis2GShell(object):

    session = None

    def setup(self):
        self.session = CloudShellAPISession('localhost', 'admin', 'admin',
                                            'Global')

    def teardown(self):
        for resource in self.session.GetResourceList('Testing').Resources:
            self.session.DeleteResource(resource.Name)

    def test_hello_world(self):
        pass

    def test_all(self):
        for key, value in ixchariot_servers.items():
            self._get_inventory(key, value)

    def _get_inventory(self, name, properties):
        self.resource = self.session.CreateResource(
            resourceFamily='CS_TrafficGeneratorChassis',
            resourceModel='IxChariot Server Shell 2G',
            resourceName=name,
            resourceAddress=properties['address'],
            folderFullPath='Testing',
            parentResourceFullPath='',
            resourceDescription='should be removed after test')
        self.session.UpdateResourceDriver(self.resource.Name,
                                          'IxChariot Server Shell 2G')
        attributes = [
            AttributeNameValue('IxChariot Server Shell 2G.Client Install Path',
                               properties['client_install_path']),
            AttributeNameValue('IxChariot Server Shell 2G.User',
                               properties['user']),
            AttributeNameValue('IxChariot Server Shell 2G.Password',
                               properties['password'])
        ]
        self.session.SetAttributesValues(
            ResourceAttributesUpdateRequest(self.resource.Name, attributes))
        self.session.AutoLoad(self.resource.Name)
        resource_details = self.session.GetResourceDetails(self.resource.Name)
        assert (len(resource_details.ChildResources) == properties['modules'])
        self.session.DeleteResource(self.resource.Name)
예제 #5
0
    def vmx_orch_hook_during_provisioning(self, context):
        logger = get_qs_logger(log_group=context.reservation.reservation_id, log_file_prefix='vMX')

        logger.info('deploy called')
        api = CloudShellAPISession(host=context.connectivity.server_address,
                                   token_id=context.connectivity.admin_auth_token,
                                   domain=context.reservation.domain)
        resid = context.reservation.reservation_id
        vmxtemplate_resource = context.resource.name

        logger.info('context attrs: ' + str(context.resource.attributes))

        vmxuser = context.resource.attributes['User']
        vmxpassword = api.DecryptPassword(context.resource.attributes['Password']).Value

        vcp_app_template_name = context.resource.attributes['Chassis App']
        vfp_app_template_name_template = context.resource.attributes['Module App']

        internal_vlan_service_name = context.resource.attributes['Internal Network Service'] or 'VLAN Auto'
        vlantype = context.resource.attributes.get('Vlan Type') or 'VLAN'

        ncards = int(context.resource.attributes.get('Number of modules', '1'))

        router_family = context.resource.attributes['Deployed Resource Family']
        router_model = context.resource.attributes['Deployed Resource Model']
        router_driver = context.resource.attributes['Deployed Resource Driver']

        chassis_deployed_model_name = context.resource.attributes['Controller App Resource Model']
        card_deployed_model_name = context.resource.attributes['Card App Resource Model']

        requested_vmx_ip = context.resource.attributes.get('Management IP', 'dhcp')
        username = context.resource.attributes.get('User', 'user')
        userpassword = api.DecryptPassword(context.resource.attributes.get('Password', '')).Value
        rootpassword = userpassword
        userfullname = context.resource.attributes.get('User Full Name', username)

        missing = []
        for a in ['Chassis App', 'Module App', 'Deployed Resource Family', 'Deployed Resource Model']:
            if a not in context.resource.attributes:
                missing.append(a)
        if missing:
            raise Exception('Template resource missing values for attributes: %s' % ', '.join(missing))

        if '%d' not in vfp_app_template_name_template:
            vfp_app_template_name_template += '%d'

        px, py = get_resource_position(api, resid, vmxtemplate_resource)

        vmx_resource = vmxtemplate_resource.replace('Template ', '').replace('Template', '') + '_' + str(randint(1, 10000))
        fakel2name = '%s L2' % vmx_resource

        todeploy = [
            (vcp_app_template_name, '%s_vcp' % vmx_resource, px, py + 100)
        ] + [
            (vfp_app_template_name_template % i, '%s_vfp%d' % (vmx_resource, i), px, py+100+100+100*i)
            for i in range(ncards)
        ]

        for _ in range(5):
            with Mutex(api, resid, logger):
                for template, alias, x, y in todeploy:
                    add_app(api, resid, template, alias, x, y)

            app_aliases = [alias for template, alias, x, y in todeploy]
            api.DeployAppToCloudProviderBulk(resid, app_aliases)

            with Mutex(api, resid, logger):
                logger.info('original app aliases = %s' % str(app_aliases))
                vmname2details = get_details_of_deployed_app_resources(api, resid, app_aliases)

            deployed_vcp = sorted([x for x in vmname2details if 'vcp' in x])
            deployed_vfp = sorted([x for x in vmname2details if 'vfp' in x])
            deployed = deployed_vcp + deployed_vfp

            logger.info('deployed apps = %s' % str(deployed))

            vmxip, mac2nicname, netid50, cpname = post_creation_vm_setup(api,
                                                                                         resid,
                                                                                         deployed,
                                                                                         deployed_vcp,
                                                                                         deployed_vfp,
                                                                                         internal_vlan_service_name,
                                                                                         requested_vmx_ip,
                                                                                         rootpassword,
                                                                                         userfullname,
                                                                                         username,
                                                                                         userpassword,
                                                                                         vmname2details,
                                                                                         vmx_resource,
                                                                                         logger)


            if not vmxip:
                raise Exception('VCP did not receive an IP (requested %s)' % (requested_vmx_ip))

            if not wait_for_ssh_up(api, resid, vmxip, vmxuser, vmxpassword, logger):
                raise Exception('VCP not reachable via SSH within 5 minutes at IP %s -- check management network' % vmxip)

            if ssh_wait_for_ge_interfaces(api, resid, vmxip, vmxpassword, ncards, logger):
                logger.info('All expected ge- interfaces found')
                break

            msg = '%d card(s) not discovered within 3 minutes - recreating VMs' % ncards
            logger.info(msg)
            api.WriteMessageToReservationOutput(resid, msg)

            api.DeleteResources(deployed)
            sleep(10)
        else:
            raise Exception('%d cards were not discovered after 10 minutes in 5 attempts' % ncards)

        for kj in deployed_vfp:
            api.UpdateResourceAddress(kj, kj)

        api.CreateResource(router_family, router_model, vmx_resource, vmxip)
        api.AddResourcesToReservation(resid, [vmx_resource])
        api.SetReservationResourcePosition(resid, vmxtemplate_resource, px, py-50)
        api.SetReservationResourcePosition(resid, vmx_resource, px, py)
        if router_driver:
            api.UpdateResourceDriver(vmx_resource, router_driver)

        try:
            api.RemoveServicesFromReservation(resid, [vmx_resource + ' vMX resource cleanup'])
        except:
            pass
        api.AddServiceToReservation(resid, 'VNF Cleanup Service', vmx_resource + ' vMX resource cleanup', [
            AttributeNameValue('Resources to Delete', ','.join([
                vmx_resource,
            ])),
        ])

        copy_resource_attributes(api, vmxtemplate_resource, vmx_resource)

        for _ in range(5):
            logger.info('Running autoload...')
            try:
                api.AutoLoad(vmx_resource)

                children_flat = get_all_child_resources(api, vmx_resource)
                ge_children_flat = {a: b
                                    for a, b in children_flat.iteritems()
                                    if '/' in a and '-' in a.split('/')[-1]}

                foundcards2ports = defaultdict(list)
                for fullpath, attrs in ge_children_flat.iteritems():
                    foundcards2ports[attrs['ResourceBasename'].split('-')[1]].append(attrs['ResourceBasename'])

                if len(foundcards2ports) >= ncards:
                    logger.info('Autoload found ports: %s' % (foundcards2ports))
                    break
                logger.info('Autoload did not find all cards (%d) or ports per card (10). Retrying in 10 seconds. Found: %s' % (ncards, foundcards2ports))
                sleep(10)
            except Exception as ek:
                logger.info('Autoload error: %s. Retrying in 30 seconds.' % str(ek))
                sleep(30)
        else:
            raise Exception('Autoload did not discover all expected ports - unhandled vMX failure')

        post_autoload_cleanup(api, resid, deployed_vfp, vmname2details, netid50, logger)

        vfpcardidstr2deployedapp3 = {vfpname.split('_')[2].replace('vfp', '').split('-')[0]: vfpname for vfpname in
                                     deployed_vfp}

        def vm_from_ge_port(portname):
            if '/' in portname:
                portname = portname.split('/')[-1]
            return vfpcardidstr2deployedapp3[portname.split('-')[1]]

        logger.info('vfpcardidstr2deployedapp = %s' % str(vfpcardidstr2deployedapp3))

        autoloadport2vmname_nicname = {}
        for ch, attrs in ge_children_flat.iteritems():
            for attr, val in attrs.iteritems():
                if 'mac' in attr.lower() and 'address' in attr.lower():
                    autoloadport2vmname_nicname[ch] = (vm_from_ge_port(ch), mac2nicname.get(val, attrs['ResourceBasename'].split('-')[-1]))

        create_fake_L2(api, fakel2name, vlantype, autoloadport2vmname_nicname)
        try:
            api.RemoveServicesFromReservation(resid, [vmx_resource + ' L2 cleanup'])
        except:
            pass
        api.AddServiceToReservation(resid, 'VNF Cleanup Service', vmx_resource + ' L2 cleanup', [
            AttributeNameValue('Resources to Delete', ','.join([
                fakel2name,
            ])),
        ])

        logger.info('deployed_vcp=%s deployed_vfp=%s deployed=%s' % (deployed_vcp, deployed_vfp, deployed))

        with Mutex(api, resid, logger):
            basename2fullpath = {fullpath.split('/')[-1]: fullpath for fullpath in autoloadport2vmname_nicname}

            def mapfunc(oldpath):
                basename = oldpath.split('/')[-1]
                return basename2fullpath[basename]

            move_connectors_of(api, resid, vmxtemplate_resource, mapfunc, logger)

            api.RemoveResourcesFromReservation(resid, [vmxtemplate_resource])

        logger.info('SUCCESS deploying vMX %s' % vmx_resource)
def test_autoload_session(session: CloudShellAPISession,
                          autoload_resource: ResourceInfo, dut: dut) -> None:
    session.AutoLoad(autoload_resource.Name)
    resource_details = session.GetResourceDetails(autoload_resource.Name)
    assert len(resource_details.ChildResources) == 1
    assert resource_details.ChildResources[0].FullAddress == f"{dut[0]}/M1"
from cloudshell.api.cloudshell_api import CloudShellAPISession
import timeit

user = "******"
password = "******"
server = "localhost"
domain = "Global"

TARGET_RESOURCE_NAME = "tent-switch-test"

api = CloudShellAPISession(host=server, username=user, password=password, domain=domain)

print("starting autoload...")
start_time = timeit.default_timer()
res = api.AutoLoad(resourceFullPath=TARGET_RESOURCE_NAME)
elapsed = timeit.default_timer() - start_time

print("autoload response: {}".format(res))
print("autoload time: {}".format(elapsed))
예제 #8
0
def test_autoload_session(session: CloudShellAPISession,
                          autoload_resource: ResourceInfo) -> None:
    session.AutoLoad(autoload_resource.Name)
    session.GetResourceDetails(autoload_resource.Name)
    print('Done')