def setUp(self):
        super(NuagePortTestsVSDManaged, self).setUp()

        # Create VSD managed subnet
        user_enterprise = self.session.user.enterprises.get_first(
            filter='name == "{}"'.format(utils.get_vsd_net_parition_name()))

        self.l3domain = utils.create_l3_domain(self, user_enterprise)

        zone = self.l3domain.create_child(
            vspk.NUZone(name=utils.get_random_name()))[0]

        subnet = zone.create_child(
            vspk.NUSubnet(name=utils.get_random_name(),
                          address='10.0.0.0',
                          netmask='255.255.255.0'))[0]

        cmd_create = ('subnet create -f json --network {network} '
                      '--net-partition {net_partition} --nuagenet {nuagenet} '
                      '--subnet-range {subnet_range} {subnet_name}'.format(
                          network=self.NETWORK_NAME,
                          net_partition=user_enterprise.id,
                          nuagenet=subnet.id,
                          subnet_range='10.0.0.0/24',
                          subnet_name=utils.get_random_name()))
        create_output = json.loads(self.openstack(cmd_create))
        self.addCleanup(self.openstack,
                        'subnet delete {}'.format(create_output['id']))
Esempio n. 2
0
    def _create_subnet(self, network, cidr):
        user_enterprise = self.session.user.enterprises.get_first(
            filter='name == "{}"'.format(utils.get_vsd_net_parition_name()))

        # Create VSD managed subnet
        l3domain = utils.create_l3_domain(self, user_enterprise)
        zone = l3domain.create_child(
            vspk.NUZone(name=utils.get_random_name()))[0]
        subnet = zone.create_child(
            vspk.NUSubnet(name=utils.get_random_name(),
                          address=str(cidr.ip),
                          netmask=str(cidr.netmask)))[0]

        cmd_create = ('subnet create -f json --network {network} '
                      '--net-partition {net_partition} --nuagenet {nuagenet} '
                      '--subnet-range {subnet_range} {subnet_name}'
                      .format(network=network,
                              net_partition=user_enterprise.id,
                              nuagenet=subnet.id,
                              subnet_range=cidr,
                              subnet_name=utils.get_random_name()))
        create_output = json.loads(self.openstack(cmd_create))
        self.addCleanup(self.openstack,
                        'subnet delete {}'.format(create_output['id']))

        return create_output, l3domain
    def _create_shared_fip_subnet(self, session, address, netmask):
        shared_enterprise = session.user.enterprises.get_first(
            filter='name == "Shared Infrastructure"')
        l3_domain_template_shared_infra = \
            shared_enterprise.domain_templates.get_first(
                filter='name == "Shared Domain template"')
        shared_l3_domain = shared_enterprise.create_child(
            vspk.NUDomain(name=utils.get_random_name(),
                          template_id=l3_domain_template_shared_infra.id))[0]
        self.addCleanup(shared_l3_domain.delete)

        zone = shared_l3_domain.zones.get_first()

        shared_subnet = zone.create_child(
            vspk.NUSubnet(name=utils.get_random_name(),
                          address=address,
                          netmask=netmask,
                          resource_type="FLOATING"))[0]
        self.addCleanup(shared_subnet.delete)

        return shared_subnet
    def _create_topology(self, network, cidr, is_l3=True):
        user_enterprise = self.session.user.enterprises.get_first(
            filter='name == "{}"'.format(utils.get_vsd_net_parition_name()))

        # Create VSD managed subnet
        if is_l3:
            l3domain = utils.create_l3_domain(self, user_enterprise)
            zone = l3domain.create_child(
                vspk.NUZone(name=utils.get_random_name()))[0]
            vsd_subnet = zone.create_child(
                vspk.NUSubnet(name=utils.get_random_name(),
                              address=str(cidr.ip),
                              netmask=str(cidr.netmask)))[0]
        else:
            l3domain = None
            vsd_subnet = utils.create_l2_domain(self,
                                                user_enterprise,
                                                address=str(cidr.ip),
                                                netmask=str(cidr.netmask),
                                                gateway=str(cidr.ip + 1))
        subnet_create_str = ('subnet create -f json --network {network} '
                             '--net-partition {net_partition} '
                             '--nuagenet {nuagenet} '
                             '--subnet-range {subnet_range} {subnet_name}')
        if not is_l3:
            subnet_create_str += ' --gateway None'

        cmd_create = subnet_create_str.format(
            network=network,
            net_partition=user_enterprise.id,
            nuagenet=vsd_subnet.id,
            subnet_range=cidr,
            subnet_name=utils.get_random_name())
        subnet = json.loads(self.openstack(cmd_create))
        self.addCleanup(self.openstack,
                        'subnet delete {}'.format(subnet['id']))

        return subnet, l3domain or vsd_subnet
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
#    nosslcheck = args.nosslcheck
    verbose = args.verbose
    ips = []
    if args.ips:
        ips = args.ips
    macs = args.macs
    subnets = args.subnets
    uuid = args.uuid

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level)
    logger = logging.getLogger(__name__)

    # Sanity checks
    if len(macs) > 0 and len(macs) != len(subnets):
        logger.critical('The amount of macs is not equal to the amount of subnets, which is an invalid configuration.')
        return 1

    if len(ips) > 0 and len(macs) != len(ips):
        logger.critical('Some IPs are specified, but not the same amount as macs and subnets, which is an invalid configuration.')
        return 1

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug('No command line Nuage password received, requesting Nuage password from user')
        nuage_password = getpass.getpass(prompt='Enter password for Nuage host {0:s} for user {1:s}: '.format(nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server {0:s}:{1:d} with username {2:s}'.format(nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username, password=nuage_password, enterprise=nuage_enterprise, api_url="https://{0:s}:{1:d}".format(nuage_host, nuage_port))
        nc.start()

    except Exception as e:
        logger.error('Could not connect to Nuage host {0:s} with user {1:s} and specified password'.format(nuage_host, nuage_username))
        logger.critical('Caught exception: {0:s}'.format(str(e)))
        return 1

    logger.debug('Trying to fetch VM with ID {0:s}'.format(uuid))
    vm = vsdk.NUVM(id=uuid)
    vm.fetch()

    for mac in macs:
        index = macs.index(mac)
        subnet_id = subnets[index]
        subnet_type = None
        logger.info('Handling mac address {0:s} connection to subnet or L2 domain {1:s}'.format(mac, subnet_id))

        logger.debug('Trying to fetch subnet for ID {0:s}'.format(subnet_id))
        try:
            subnet = vsdk.NUSubnet(id=subnet_id)
            subnet.fetch()
            subnet_type = 'SUBNET'
        except:
            logger.debug('Subnet with ID {0:s} does not exist, looking for a L2 domain'.format(subnet_id))
            try:
                subnet = vsdk.NUL2Domain(id=subnet_id)
                subnet.fetch()
                subnet_type = 'L2DOMAIN'
            except:
                logger.error('Subnet with ID {0:s} can not be found as an subnet in an L3 domain or as an L2 domain, skipping mac {1:s} and subnet {2:s} and continuing to the next pair'.format(subnet_id, mac, subnet_id))
                continue

        vm_interface = vsdk.NUVMInterface()
        if len(ips) > 0:
            vm_interface.ip_address = ips[index]
        vm_interface.mac = mac
        vm_interface.name = 'if-{0:s}'.format(mac).replace(':','-')
        vm_interface.attached_network_id = subnet_id
        vm_interface.attached_network_type = subnet_type

        logger.debug('Creating interface {0:s} on VM {1:s}'.format(vm_interface.name, vm.name))
        try:
            vm.create_child(vm_interface)
        except Exception as e:
            logger.error('Failed to create interface {0:s} on VM {1:s}: {2:s}'.format(vm_interface.name, vm.name, str(e)))

    logger.info('Successfully added interfaces to VM {0:s}'.format(vm.name))
    return 0
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    #    nosslcheck = args.nosslcheck
    verbose = args.verbose
    external = args.external
    ips = []
    if args.ips:
        ips = args.ips
    macs = args.macs
    name = args.name
    subnets = args.subnets
    uuid = args.uuid

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Sanity checks
    if len(macs) > 0 and len(macs) != len(subnets):
        logger.critical(
            'The amount of macs is not equal to the amount of subnets, which is an invalid configuration.'
        )
        return 1

    if len(ips) > 0 and len(macs) != len(ips):
        logger.critical(
            'Some IPs are specified, but not the same amount as macs and subnets, which is an invalid configuration.'
        )
        return 1

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' %
                    (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username,
                               password=nuage_password,
                               enterprise=nuage_enterprise,
                               api_url="https://%s:%s" %
                               (nuage_host, nuage_port))
        nc.start()

    except Exception as e:
        logger.error(
            'Could not connect to Nuage host %s with user %s and specified password'
            % (nuage_host, nuage_username))
        logger.critical('Caught exception: %s' % str(e))
        return 1

    # Handling each mac/subnet combination and creating the necessary vPorts and VM Interfaces
    vports = []
    vm_interfaces = []
    for mac in macs:
        index = macs.index(mac)
        subnet_id = subnets[index]
        logger.info(
            'Handling mac address %s connection to subnet or L2 domain %s' %
            (mac, subnet_id))

        logger.debug('Trying to fetch subnet for ID %s' % subnet_id)
        try:
            subnet = vsdk.NUSubnet(id=subnet_id)
            subnet.fetch()
        except:
            logger.debug(
                'Subnet with ID %s does not exist, looking for a L2 domain' %
                subnet_id)
            try:
                subnet = vsdk.NUL2Domain(id=subnet_id)
                subnet.fetch()
            except:
                logger.error(
                    'Subnet with ID %s can not be found as an subnet in an L3 domain or as an L2 domain, skipping mac %s and subnet %s and continuing to the next pair'
                    % (subnet_id, mac, subnet_id))
                continue

        # Creating vPort in subnet
        logger.debug('Creating vPort %s-vPort-%s in subnet %s (%s)' %
                     (name, index, subnet.name, subnet_id))
        vport = vsdk.NUVPort(name='%s-vPort-%s' % (name, index),
                             address_spoofing='INHERITED',
                             type='VM',
                             description='Automatically created, do not edit.')
        if external:
            vport.external_id = '%s-vPort-%s' % (name, index)
        subnet.create_child(vport)
        vports.append(vport)

        # Creating VMInterface
        logger.debug(
            'Creating VMInterface object %s-vm-interface-%s for mac %s with vPort ID %s'
            % (name, index, mac, vport.id))
        vm_interface = vsdk.NUVMInterface(name='%s-vm-interface-%s' %
                                          (name, index),
                                          vport_id=vport.id,
                                          mac=mac)
        if external:
            vm_interface.external_id = '%s-vm-interface-%s' % (name, index)
        if len(ips) > 0:
            vm_interface.ip_address = ips[index]
        vm_interfaces.append(vm_interface)

    # Creating VM
    logger.info('Creating VM %s with UUID %s' % (name, uuid))
    vm = vsdk.NUVM(name=name, uuid=uuid, interfaces=vm_interfaces)
    if external:
        vm.external_id = uuid
    try:
        logger.debug('Trying to save VM %s.' % name)
        nc.user.create_child(vm)
    except Exception as e:
        logger.critical('VM %s can not be created because of error %s' %
                        (name, str(e)))
        logger.debug('Cleaning up the vPorts')
        for vport in vports:
            logger.debug('Deleting vPort %s' % vport.name)
            vport.delete()
        return 1

    logger.info(
        'Created all necessary entities in the appropriate subnets or L2 domains for VM %s'
        % name)
    return 0
Esempio n. 7
0
import logging

from vspk import v6 as vsdk
from vspk.utils import set_log_level

set_log_level(logging.ERROR)

session = vsdk.NUVSDSession(username='******',
                            password='******',
                            enterprise='csp',
                            api_url='https://localhost:8443')
session.start()
csproot = session.user

# Get a subnet.
# Note: We don't need to fetch information to add a new child to this subnet
subnet = vsdk.NUSubnet(id='c7a1a893-a3ad-4844-94a6-d89537f4cd3c')

# Create a DHCP option for the given subnet
dhcp_option = vsdk.NUDHCPOption(actual_type=4,
                                actual_values=['192.0.2.15', '198.51.100.12'])
subnet.create_child(dhcp_option)