def create(self,
               v4subnet,
               v4gateway,
               v6subnet=None,
               v6gateway=None,
               rtList=None):
        try:
            ipam_obj = self.vnc_client.network_ipam_read(fq_name=[
                'default-domain', 'default-project', 'default-network-ipam'
            ])
        except Exception as e:
            logging.debug('ERROR: %s' % (str(e)))
            return
        cidr = v4subnet.split('/')
        subnet = vnc_api.SubnetType(ip_prefix=cidr[0],
                                    ip_prefix_len=int(cidr[1]))

        v4DnsServer = IPNetwork(v4subnet)[-2]

        if v4gateway:
            ipam_subnet = vnc_api.IpamSubnetType(subnet=subnet,
                                                 default_gateway=v4gateway)
        else:
            ipam_subnet = vnc_api.IpamSubnetType(
                subnet=subnet, dns_server_address=v4DnsServer)

        if v6subnet:
            v6DnsServer = IPNetwork(v6subnet)[-2]
            v6cidr = v6subnet.split('/')
            v6subnet = vnc_api.SubnetType(ip_prefix=v6cidr[0],
                                          ip_prefix_len=int(v6cidr[1]))
            if v6gateway:
                v6gateway = v6gateway.split('/')[0]
                ipam_v6subnet = vnc_api.IpamSubnetType(
                    subnet=v6subnet, default_gateway=v6gateway)
            else:
                ipam_v6subnet = vnc_api.IpamSubnetType(
                    subnet=v6subnet, dns_server_address=v6DnsServer)
            self.obj.add_network_ipam(ref_obj=ipam_obj,
                                      ref_data=vnc_api.VnSubnetsType(
                                          [ipam_subnet, ipam_v6subnet]))
        else:
            self.obj.add_network_ipam(ref_obj=ipam_obj,
                                      ref_data=vnc_api.VnSubnetsType(
                                          [ipam_subnet]))

        if rtList:
            rtObj = vnc_api.RouteTargetList()
            self.obj.set_route_target_list(rtObj)
            for rt in rtList:
                rtObj.add_route_target('target:%s' % (rt))
        try:
            self.vnc_client.virtual_network_create(self.obj)
        except Exception as e:
            logging.debug('ERROR: %s' % (str(e)))
        '''
Example #2
0
    def handle_create(self):
        try:
            vn_obj = self.vnc_lib().virtual_network_read(
                id=self.properties[self.NETWORK])
        except vnc_api.NoIdError:
            vn_obj = self.vnc_lib().virtual_network_read(
                fq_name_str=self.properties[self.NETWORK])

        net = netaddr.IPNetwork(self.properties[self.IP_PREFIX])
        if self.properties[self.ENABLE_DHCP] == "True":
            enable_dhcp = True
        else:
            enable_dhcp = False
        ipam = self._get_ipam()
        subnets = self._get_subnets(vn_obj, ipam)
        subnet_uuid = str(uuid.uuid4())
        subnet = vnc_api.IpamSubnetType(
            subnet_name=self.properties[self.NAME],
            subnet=vnc_api.SubnetType(str(net.ip), net.prefixlen),
            default_gateway=self.properties[self.DEFAULT_GATEWAY],
            allocation_pools=self.properties[self.ALLOCATION_POOLS],
            enable_dhcp=enable_dhcp,
            dns_nameservers=self.properties[self.DNS_NAMESERVERS],
            host_routes=self.properties[self.HOST_ROUTES],
            subnet_uuid=subnet_uuid)
        if subnets:
            subnets.append(subnet)
            vn_obj._pending_field_updates.add('network_ipam_refs')
        else:
            vn_obj.add_network_ipam(ipam, vnc_api.VnSubnetsType([subnet]))
        self.vnc_lib().virtual_network_update(vn_obj)
        self.resource_id_set(subnet_uuid)
Example #3
0
def create_VirtualNetwork(network_name, network_subnet, network_mask, vnc, domain, project_name):

        """ FUNCTION TO CREATE VIRTUAL-NETWORK """

        project = vnc.project_read(fq_name = [domain, project_name])

        vn_obj = vnc_api.VirtualNetwork(name=network_name, parent_obj=project)
        vn_obj.add_network_ipam(vnc_api.NetworkIpam(),
                        vnc_api.VnSubnetsType([vnc_api.IpamSubnetType(subnet = vnc_api.SubnetType(network_subnet,network_mask))]))

        vnc.virtual_network_create(vn_obj)

        print 'Network "{}" created successfully\n'.format(network_name)
Example #4
0
 def createSubnet(self, subnet, gateway=None):
     try:
         ipam_obj = self.vnc_client.network_ipam_read(fq_name=[
             'default-domain', 'default-project', 'default-network-ipam'
         ])
     except Exception as e:
         print 'ERROR: %s' % (str(e))
         return
     cidr = subnet.split('/')
     subnet = vnc_api.SubnetType(ip_prefix=cidr[0],
                                 ip_prefix_len=int(cidr[1]))
     ipam_subnet = vnc_api.IpamSubnetType(subnet=subnet,
                                          default_gateway=gateway)
     self.obj.add_network_ipam(ref_obj=ipam_obj,
                               ref_data=vnc_api.VnSubnetsType([ipam_subnet
                                                               ]))
Example #5
0
    def create_vn(self, vn_name, vn_subnetmask, vn_gw):
        print "Create virtual_network %s" % vn_name

        project = self._vnc_lib.project_read(
            fq_name=[self._domain, self._tenant_name])
        vn_obj = vnc_api.VirtualNetwork(name=vn_name, parent_obj=project)
        vn_subnet = vn_subnetmask.split('/')[0]
        vn_mask = int(vn_subnetmask.split('/')[1])

        vn_obj.add_network_ipam(
            vnc_api.NetworkIpam(),
            vnc_api.VnSubnetsType([
                vnc_api.IpamSubnetType(subnet=vnc_api.SubnetType(
                    vn_subnet, vn_mask),
                                       default_gateway=vn_gw)
            ]))
        self._vnc_lib.virtual_network_create(vn_obj)
Example #6
0
 def add_ipam(self,
              name='default-network-ipam',
              tenant='default-project',
              subnet=None):
     fq_name = [self.domain, tenant, name]
     cidr = self.get_subnet()
     print "Allocated CIDR for this Virtual Network is {}".format(cidr)
     print "Adding the subnet to the IPAM"
     try:
         ipam_obj = self.vnc_handle.network_ipam_read(fq_name=fq_name)
         (prefix, netlen) = cidr.split('/')
         subnet = vnc_api.SubnetType(ip_prefix=prefix,
                                     ip_prefix_len=int(netlen))
         ipam_subnet = vnc_api.IpamSubnetType(subnet=subnet,
                                              default_gateway=None)
         return (ipam_obj, ipam_subnet)
     except vnc_exc.NoIdError:
         print "Error reading the IPAM"
         raise
def virtual_network_locate(vn_name):
    fq_name = vn_name.split(':')
    try:
        vn_instance = client.virtual_network_read(fq_name=fq_name)
        print "Virtual network '%s' already exists" % vn_name
        return vn_instance
    except vnc_api.NoIdError:
        pass

    vn_name = fq_name[2]
    vn_instance = vnc_api.VirtualNetwork(vn_name)
    vn_instance.add_network_ipam(
        vnc_api.NetworkIpam(),
        vnc_api.VnSubnetsType([
            vnc_api.IpamSubnetType(subnet=vnc_api.SubnetType('20.1.1.0', 24))
        ]))
    client.virtual_network_create(vn_instance)
    print "Virtual network '%s' created" % vn_name
    return vn_instance
Example #8
0
def createVirtualNetwork(tenant, vnName, v4subnet, rt):
    project = vnc_client.project_read(fq_name_str = 'default-domain:' + tenant)
    vn = vnc_api.VirtualNetwork(name = vnName,
                    parent_obj = project)
    ipam_obj = vnc_client.network_ipam_read(fq_name = ['default-domain',
                                           'default-project', 'default-network-ipam'])
    cidr = v4subnet.split('/')
    subnet = vnc_api.SubnetType(ip_prefix = cidr[0],
                ip_prefix_len = int(cidr[1]))
    v4DnsServer = str(IPNetwork(v4subnet)[+2])
    v4gateway = str(IPNetwork(v4subnet)[+1])
    ipam_subnet = vnc_api.IpamSubnetType(subnet = subnet, dns_server_address = v4DnsServer,
                default_gateway = v4gateway, enable_dhcp = False)
    vn.add_network_ipam(ref_obj = ipam_obj,
                 ref_data = vnc_api.VnSubnetsType([ipam_subnet]))
    rtObj = vnc_api.RouteTargetList()
    vn.set_route_target_list(rtObj)
    rtObj.add_route_target('target:%s' %(rt))
    vnc_client.virtual_network_create(vn)
    vnObj = vnc_client.virtual_network_read(fq_name_str = 'default-domain:' + tenant + ':' + vnName)
    return vnObj
    def create(self):
        """Create a vm and vmi, find or create a network, and attach
        the vmi to a new veth interface

        Arguments:

          vm_name   name of the vm to create
          net_name  name of the netwok to arrach to
          subnet    x.x.x.x/len - optional if network already exists
          netns     Network namespace where the veth interface is bound to.  Defaults to net_name    

        Returns:

          A dict with the following elements:
          
          port_id  uuid of port
          ip
          veth     name of veth interface
          netns    Network namespace where the veth interface is bound to
          
        """
        
        # remember what to clean up if things go wrong
        port_created = False
        veth_created = False
        netns_created = False
        ip_created = False
        vmi_created = False
        vnet_created = False
        vm_created = False

        try:
            # sanity check
            net_name = self.args.get('net_name')
            if not net_name:
                raise ValueError("Network name argument is required")

            # sanitize netns since it gets passed to the shell
            netns = self.args.get('netns')
            if not netns:
                netns = net_name
            if not re.match(r'^[-.\w]+$', netns):
                raise ValueError("netns=[%s] must be a valid namespace name"
                                 + " (a single word)" % netns)

            
            vnc_client = self.vnc_connect()

            proj_fq_name = self.args['project'].split(':')

            # find or create the VM
            vm_fq_name = proj_fq_name + [ self.args['vm_name'] ]

            # debug
            #import pdb; pdb.set_trace()

            try:
                vm = vnc_client.virtual_machine_read(fq_name = vm_fq_name)
                if vm:
                    raise ValueError(("Virtual machine named %s already exists."
                                      + "  Use --delete to delete it")
                                     % self.args['vm_name'])
            except vnc_api.NoIdError:
                # create vm if necessary
                vm = vnc_api.VirtualMachine(':'.join(vm_fq_name),
                                            fq_name=vm_fq_name)
                vnc_client.virtual_machine_create(vm)
                vm = vnc_client.virtual_machine_read(fq_name = vm_fq_name)
                vm_created = True
                
            # find or create the network
            vnet_fq_name = proj_fq_name + [ net_name ]
            vnet_created = False
            try:
                vnet = vnc_client.virtual_network_read(fq_name = vnet_fq_name)
            except vnc_api.NoIdError:
                # create the network if it doesn't exist
                vnet = vnc_api.VirtualNetwork(vnet_fq_name[-1],
                                              parent_type = 'project',
                                              fq_name = vnet_fq_name)

                # add a subnet
                ipam = vnc_client.network_ipam_read(
                    fq_name = ['default-domain',
                               'default-project',
                               'default-network-ipam'])
                (prefix, plen) = self.args['subnet'].split('/')
                subnet = vnc_api.IpamSubnetType(
                    subnet = vnc_api.SubnetType(prefix, int(plen)))
                vnet.add_network_ipam(ipam, vnc_api.VnSubnetsType([subnet]))

                vnc_client.virtual_network_create(vnet)
                vnet_created = True

            # find or create the vmi
            vmi_fq_name = vm.fq_name + ['0']
            vmi_created = False
            try:
                vmi = vnc_client.virtual_machine_interface_read(
                    fq_name = vmi_fq_name)
            except vnc_api.NoIdError:
                vmi = vnc_api.VirtualMachineInterface(
                    parent_type = 'virtual-machine',
                    fq_name = vmi_fq_name)
                vmi_created = True
            vmi.set_virtual_network(vnet)
            if vmi_created:
                vnc_client.virtual_machine_interface_create(vmi)
            else:
                vnc_client.virtual_machine_interface_update(vmi)
            # re-read the vmi to get its mac addresses
            vmi = vnc_client.virtual_machine_interface_read(
                fq_name = vmi_fq_name)
            # create an IP for the VMI if it doesn't already have one
            ips = vmi.get_instance_ip_back_refs()
            if not ips:
                ip = vnc_api.InstanceIp(vm.name + '.0')
                ip.set_virtual_machine_interface(vmi)
                ip.set_virtual_network(vnet)
                ip_created = vnc_client.instance_ip_create(ip)

            # Create the veth port.  Create a veth pair.  Put one end
            # in the VMI port and the other in a network namespace
            
            # get the ip, mac, and gateway from the vmi
            ip_uuid = vmi.get_instance_ip_back_refs()[0]['uuid']
            ip = vnc_client.instance_ip_read(id=ip_uuid).instance_ip_address
            mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
            subnet = vnet.network_ipam_refs[0]['attr'].ipam_subnets[0]
            gw = subnet.default_gateway
            dns = gw # KLUDGE - that's the default, but some networks
                     # have other DNS configurations
            ipnetaddr = netaddr.IPNetwork("%s/%s" %
                                          (subnet.subnet.ip_prefix,
                                           subnet.subnet.ip_prefix_len))
            
            # set up the veth pair with one part for vrouter and one
            # for the netns

            # find a name that's not already used in the default or
            # netns namespaces
            link_exists = link_exists_func('', netns)
            veth_vrouter = new_interface_name(suffix=vnet.uuid, prefix="ve1",
                                              exists_func=link_exists)
            veth_host = new_interface_name(suffix=vnet.uuid, prefix="ve0",
                                           exists_func=link_exists)
            
            sudo("ip link add %s type veth peer name %s",
                 (veth_vrouter, veth_host))
            veth_created = True
            try:
                sudo("ip netns add %s", (netns,))
                netns_created = True
            except ProcessExecutionError:
                pass
            
            sudo("ip link set %s netns %s",
                 (veth_host, netns))
            sudo("ip netns exec %s ip link set dev %s address %s",
                 (netns, veth_host, mac))
            sudo("ip netns exec %s ip address add %s broadcast %s dev %s",
                 (netns,
                  ("%s/%s" % (ip, subnet.subnet.ip_prefix_len)),
                  ipnetaddr.broadcast, veth_host))
            sudo("ip netns exec %s ip link set dev %s up",
                 (netns, veth_host))
            sudo("ip netns exec %s route add default gw %s dev %s",
                 (netns, gw, veth_host))
            sudo("ip link set dev %s up", (veth_vrouter,))

            # make a namespace-specific resolv.conf
            resolv_conf = "/etc/netns/%s/resolv.conf" % netns
            resolv_conf_body = "nameserver %s\n" % dns
            sudo("mkdir -p %s", (os.path.dirname(resolv_conf),))
            sudo("tee %s", (resolv_conf,), process_input=resolv_conf_body)

            # finally, create the Contrail port
            port = instance_service.ttypes.Port(
                uuid_from_string(vmi.uuid),
                uuid_from_string(vm.uuid), 
                veth_vrouter,
                ip,
                uuid_from_string(vnet.uuid),
                mac,
                )
            rpc = vrouter_rpc()
            rpc.AddPort([port])
            port_created = True
            
            return(dict(
                port_id = uuid_array_to_str(port.port_id),
                vm_id = vm.uuid,
                net_id = vnet.uuid,
                vmi_id = vmi.uuid,
                veth = veth_host,
                netns = netns,
                ip = ip,
                mac = mac,
                gw = gw,
                dns = dns,
                netmask = str(ipnetaddr.netmask),
                broadcast = str(ipnetaddr.broadcast),
                ))

        except:
            # something went wrong, clean up
            if port_created:
                rpc.DeletePort(port.port_id)
            if veth_created:
                sudo("ip link delete %s", (veth_vrouter,),
                     check_exit_code=False)
            if netns_created:
                sudo("ip netns delete %s", (netns,), check_exit_code=False)
            if ip_created:
                vnc_client.instance_ip_delete(id=ip_created)
            if vmi_created:
                vnc_client.virtual_machine_interface_delete(id=vmi.uuid)
            if vnet_created:
                vnc_client.virtual_network_delete(id=vnet.uuid)
            if vm_created:
                vnc_client.virtual_machine_delete(id=vm.uuid)
            raise
Example #10
0
    switch=str(pi[0])
    phy_intf = str(pi[1])
    my_pi=vh.physical_interface_read(fq_name=[u'default-global-system-config', str(switch), str(phy_intf)])
    my_pis.append(my_pi)
my_vn_ids=[]
my_vmi_ids=[]
tag_list = [(1002, 'untagged')]
print ("Creating %s VNs"%no_of_vns)
for i in range(1, no_of_vns+1):
    print ("Creating VN number %s"%i)
    vn_name = 'vn_' + str(i)
    ip_prefix = '193.168.' + str(i) + '.0'
    dns_ip = '193.168.' + str(i) + '.254'
    obj_0 = vnc_api.VirtualNetwork(name=vn_name,parent_obj=my_proj)
    obj_1 = vnc_api.VnSubnetsType()
    obj_2 = vnc_api.IpamSubnetType()
    obj_3 = vnc_api.SubnetType()
    obj_3.set_ip_prefix(ip_prefix)
    obj_3.set_ip_prefix_len('24')
    obj_2.set_subnet(obj_3)
    obj_2.set_enable_dhcp(False)
    obj_2.set_addr_from_start(True)
    obj_2.set_dns_server_address(str(dns_ip))
    obj_1.add_ipam_subnets(obj_2)
    obj_0.add_network_ipam(my_ipam, obj_1)
    obj_0.set_virtual_network_category('routed')
    vn_id = vh.virtual_network_create(obj_0)
    my_vn_ids.append(vn_id)

print ("Creating a VPG")
my_vpg=vnc_api.VirtualPortGroup(name='my-vpg',parent_obj=my_fab)
Example #11
0
    def _subnet_neutron_to_vnc(subnet_q):
        if not subnet_q.get('cidr'):
            ContrailResourceHandler._raise_contrail_exception(
                'BadRequest', msg='cidr is empty', resource='subnet')

        cidr = netaddr.IPNetwork(subnet_q['cidr'])
        pfx = str(cidr.network)
        pfx_len = int(cidr.prefixlen)
        if pfx_len == 0 and cidr.version == 4:
            ContrailResourceHandler._raise_contrail_exception(
                'BadRequest', resource='subnet', msg="Invalid prefix len")
        if cidr.version != 4 and cidr.version != 6:
            ContrailResourceHandler._raise_contrail_exception(
                'BadRequest', resource='subnet', msg='Unknown IP family')
        elif cidr.version != int(subnet_q['ip_version']):
            msg = ("cidr '%s' does not match the ip_version '%s'" %
                   (subnet_q['cidr'], subnet_q['ip_version']))
            ContrailResourceHandler._raise_contrail_exception(
                'InvalidInput', error_message=msg, resource='subnet')

        if 'gateway_ip' in subnet_q:
            default_gw = subnet_q['gateway_ip']
            gw_ip_obj = netaddr.IPAddress(default_gw)
            if default_gw != '0.0.0.0':
                if gw_ip_obj not in cidr or gw_ip_obj.words[-1] == 255 or (
                        gw_ip_obj.words[-1] == 0):
                    ContrailResourceHandler._raise_contrail_exception(
                        'BadRequest',
                        resource='subnet',
                        msg="Invalid Gateway ip address")
        else:
            # Assigned first+1 from cidr
            default_gw = str(netaddr.IPAddress(cidr.first + 1))

        if cidr.version == 4 and 'ipv6_address_mode' in subnet_q:
            ContrailResourceHandler._raise_contrail_exception(
                'BadRequest',
                resource='subnet',
                msg="Invalid address mode with version")

        if 'allocation_pools' in subnet_q:
            alloc_pools = subnet_q['allocation_pools']
            alloc_cidrs = []
            for pool in alloc_pools:
                try:
                    ip_start = netaddr.IPAddress(pool['start'])
                    ip_end = netaddr.IPAddress(pool['end'])
                except netaddr.core.AddrFormatError:
                    ContrailResourceHandler._raise_contrail_exception(
                        'BadRequest',
                        resource='subnet',
                        msg="Invalid IP address in allocation pool")
                if ip_start >= ip_end:
                    ContrailResourceHandler._raise_contrail_exception(
                        'BadRequest',
                        resource='subnet',
                        msg='Invalid address in allocation pool')

                if ip_start not in cidr or ip_end not in cidr:
                    ContrailResourceHandler._raise_contrail_exception(
                        'BadRequest',
                        resource='subnet',
                        msg="Pool addresses not in subnet range")
                # Check if the pool overlaps with other pools
                for rng in alloc_cidrs:
                    if rng['start'] <= ip_start and ip_end <= rng['end']:
                        ContrailResourceHandler._raise_contrail_exception(
                            'BadRequest',
                            resource='subnet',
                            msg='Pool addresses invalid')
                    elif (rng['start'] >= ip_start and
                          (rng['start'] <= ip_end)) or (
                              rng['end'] >= ip_start and
                              (rng['end'] <= ip_end)):
                        ContrailResourceHandler._raise_contrail_exception(
                            'OverlappingAllocationPools',
                            pool_2="%s-%s" % (ip_start, ip_end),
                            pool_1="%s-%s" % (rng['start'], rng['end']),
                            subnet_cidr=str(cidr))
                alloc_cidrs.append({'start': ip_start, 'end': ip_end})

            gw_ip_obj = netaddr.IPAddress(default_gw)
            for rng in alloc_cidrs:
                st = rng['start']
                end = rng['end']
                if st <= gw_ip_obj and end >= gw_ip_obj:
                    ContrailResourceHandler._raise_contrail_exception(
                        'GatewayConflictWithAllocationPools',
                        ip_address=default_gw,
                        pool=str(cidr),
                        msg='Gw ip is part of allocation pools')

        else:
            # Assigned by address manager
            alloc_pools = None

        dhcp_option_list = None
        if 'dns_nameservers' in subnet_q and subnet_q['dns_nameservers']:
            dhcp_options = []
            dns_servers = " ".join(subnet_q['dns_nameservers'])
            if dns_servers:
                dhcp_options.append(
                    vnc_api.DhcpOptionType(dhcp_option_name='6',
                                           dhcp_option_value=dns_servers))
            if dhcp_options:
                dhcp_option_list = vnc_api.DhcpOptionsListType(dhcp_options)

        host_route_list = None
        if 'host_routes' in subnet_q and subnet_q['host_routes']:
            host_routes = []
            for host_route in subnet_q['host_routes']:
                SubnetMixin._check_ip_matches_version(
                    [host_route['destination'], host_route['nexthop']],
                    cidr.version)

                host_routes.append(
                    vnc_api.RouteType(prefix=host_route['destination'],
                                      next_hop=host_route['nexthop']))
            if host_routes:
                host_route_list = vnc_api.RouteTableType(host_routes)

        if 'enable_dhcp' in subnet_q:
            dhcp_config = subnet_q['enable_dhcp']
        else:
            dhcp_config = None
        sn_name = subnet_q.get('name')
        subnet_vnc = vnc_api.IpamSubnetType(subnet=vnc_api.SubnetType(
            pfx, pfx_len),
                                            default_gateway=default_gw,
                                            enable_dhcp=dhcp_config,
                                            dns_nameservers=None,
                                            allocation_pools=alloc_pools,
                                            addr_from_start=True,
                                            dhcp_option_list=dhcp_option_list,
                                            host_routes=host_route_list,
                                            subnet_name=sn_name,
                                            subnet_uuid=str(uuid.uuid4()))

        return subnet_vnc
Example #12
0
#vnet_fq_name = [u'default-domain', u'vCenter', u'vn3'])
vnet_fq_name = proj_fq_name + [net_name]
try:
    vnet = vnc.virtual_network_read(fq_name=vnet_fq_name)
    print "[SUCCESS] VNET: %s Has Exsited!" % net_name
except vnc_api.NoIdError:
    print "[WARN] VNET: %s Doesn't Exist! Creating ..." % net_name
    vnet = vnc_api.irtualNetwork(net_name,
                                 parent_type='project',
                                 fq_name=vnet_fq_name)
    # add a subnet
    subnet_fq_name = proj_fq_name + [ipam_network]
    ipam = vnc.network_ipam_read(subnet_fq_name)

    (prefix, plen) = subnet_name.split('/')
    subnet = vnc_api.IpamSubnetType(
        subnet=vnc_api.SubnetType(prefix, int(plen)))
    vnet.add_network_ipam(ipam, vnc_api.VnSubnetsType([subnet]))
    vnc.virtual_network_create(vnet)
finally:
    vnet = vnc.virtual_network_read(fq_name=vnet_fq_name)
    print "[INFO] VNET: %s fq_name: %s" % (net_name, vnet.fq_name)

# find or create the vminterface
print "=========>>> CREATE VM INTERFACE ... ..."
vmi_created = False
vmi_fq_name = vm_instance.fq_name + [vmi_name]
try:
    vm_interface = vnc.virtual_machine_interface_read(fq_name=vmi_fq_name)
    print "[SUCCESS] VM_Interface: %s Has Exsited!" % vmi_name
except vnc_api.NoIdError:
    print "[WARN] VM_Interface: %s Doesn't Exsit! Creating ... " % vmi_name
vnc = vnc_api.VncApi(username="******",
                     password="******",
                     tenant_name="admin",
                     api_server_host="Contrail_IP")
tenant = vnc.project_read(fq_name=['default-domain', 'vCenter'])
ipam = vnc.network_ipam_read(
    fq_name=['default-domain', 'vCenter', 'vCenter-ipam'])

for subnet in subnets:
    start_addr = str(subnet[10])
    end_addr = str(subnet[100])
    vn = vnc_api.VirtualNetwork(name="Customer_" + str(network_number),
                                parent_obj=tenant)
    cidr = str(subnet)
    print subnet, "RD", str(AS) + ":" + str(network_number)
    prefix, prefix_len = cidr.split('/')
    subnet = vnc_api.SubnetType(ip_prefix=prefix, ip_prefix_len=prefix_len)
    alloc_pools = []
    alloc_pools.append(
        vnc_api.AllocationPoolType(start=start_addr, end=end_addr))
    ipam_subnet = vnc_api.IpamSubnetType(subnet=subnet,
                                         advertise_default=True,
                                         allocation_pools=alloc_pools)
    vn.set_network_ipam(ref_obj=ipam,
                        ref_data=vnc_api.VnSubnetsType([ipam_subnet]))
    route_targets = vnc_api.RouteTargetList(
        ['target:' + str(AS) + ":" + str(network_number)])
    vn.set_route_target_list(route_targets)
    vnc.virtual_network_create(vn)
    network_number = network_number + 1
Example #14
0
from vnc_api import vnc_api
vnc_lib = vnc_api.VncApi(api_server_host='10.10.7.149')
vn_blue_obj = vnc_api.VirtualNetwork('vn-blue')
vn_blue_obj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([vnc_api.IpamSubnetType(subnet = vnc_api.SubnetType('10.0.2.0', 24))]))
vnc_lib.virtual_network_create(vn_blue_obj)

vn_red_obj = vnc_api.VirtualNetwork('vn-red')
vn_red_obj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([vnc_api.IpamSubnetType(subnet = vnc_api.SubnetType('10.0.3.0', 24))]))
vnc_lib.virtual_network_create(vn_red_obj)
policy_obj = vnc_api.NetworkPolicy('policy-red-blue',network_policy_entries = vnc_api.PolicyEntriesType([vnc_api.PolicyRuleType(direction='<>',action_list = vnc_api.ActionListType(simple_action='pass'), protocol = 'tcp',src_addresses = [vnc_api.AddressType(virtual_network = vn_blue_obj.get_fq_name_str())], src_ports = [vnc_api.PortType(-1, -1)],dst_addresses = [vnc_api.AddressType(virtual_network = vn_red_obj.get_fq_name_str())], dst_ports = [vnc_api.PortType(80, 80)])]))
vnc_lib.network_policy_create(policy_obj)

vn_blue_obj.add_network_policy(policy_obj, vnc_api.VirtualNetworkPolicyType(sequence=vnc_api.SequenceType(0, 0)))
vn_red_obj.add_network_policy(policy_obj, vnc_api.VirtualNetworkPolicyType(sequence=vnc_api.SequenceType(0, 0)))

vnc_lib.virtual_network_update(vn_blue_obj)
vnc_lib.virtual_network_update(vn_red_obj)

print vnc_lib.virtual_network_read(id = vn_blue_obj.uuid)


print vnc_lib.virtual_networks_list()