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)))
        '''
示例#2
0
    def _create_vn_ri_vmi(self, obj_count=1):
        vn_objs = []
        ipam_objs = []
        ri_objs = []
        vmi_objs = []
        for i in range(obj_count):
            vn_obj = vnc_api.VirtualNetwork('%s-vn-%s' % (self.id(), i))

            ipam_obj = vnc_api.NetworkIpam('%s-ipam-%s' % (self.id(), i))
            vn_obj.add_network_ipam(ipam_obj, vnc_api.VnSubnetsType())
            self._vnc_lib.network_ipam_create(ipam_obj)
            ipam_objs.append(ipam_obj)

            self._vnc_lib.virtual_network_create(vn_obj)
            vn_objs.append(vn_obj)

            ri_obj = vnc_api.RoutingInstance('%s-ri-%s' % (self.id(), i),
                                             parent_obj=vn_obj)
            self._vnc_lib.routing_instance_create(ri_obj)
            ri_objs.append(ri_obj)

            vmi_obj = vnc_api.VirtualMachineInterface(
                '%s-vmi-%s' % (self.id(), i), parent_obj=vnc_api.Project())
            vmi_obj.add_virtual_network(vn_obj)
            self._vnc_lib.virtual_machine_interface_create(vmi_obj)
            vmi_objs.append(vmi_obj)

        return vn_objs, ipam_objs, ri_objs, vmi_objs
示例#3
0
 def create(self, name, subnet=None):
     print "Inside VN Create"
     fq_name = [self.domain, self.tenant, name]
     try:
         self.vnc_handle.virtual_network_read(fq_name=fq_name)
         print "Virtual Network [{}] already exists".format(
             self.fqn_to_string(fq_name))
         sys.exit(1)
     except vnc_exc.NoIdError:
         print "Creating Virtual Network [{}]".format(
             self.fqn_to_string(fq_name))
         proj_obj = self.get_project()
         self.vn_obj = vnc_api.VirtualNetwork(name=name,
                                              parent_obj=proj_obj)
         prop = vnc_api.VirtualNetworkType(
             forwarding_mode='l2',
             rpf='disable',
         )
         self.vn_obj.set_virtual_network_properties(prop)
         self.vn_obj.set_flood_unknown_unicast(True)
         (self.ipam_obj, self.ipam_subnet) = self.add_ipam()
         self.vn_obj.set_network_ipam(ref_obj=self.ipam_obj,
                                      ref_data=vnc_api.VnSubnetsType(
                                          [self.ipam_subnet]))
         self.vn_uuid = self.vnc_handle.virtual_network_create(self.vn_obj)
         if self.vn_uuid:
             print "Successfully created the virtual network [{}]".format(
                 self.fqn_to_string(fq_name))
             return True
         else:
             print "Error: Cannot create the virtual network"
             return False
示例#4
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)
    def subnet_resource_create(self, subnet_q):
        """Modified copy of SubnetCreateHandler.resource_create method.

        This modified version preserves subnet_uuid given from neutron
        """
        net_id = subnet_q['network_id']
        vn_obj = self.handlers[Hndl.Subnet]._resource_get(id=net_id)
        ipam_fq_name = subnet_q.get('contrail:ipam_fq_name')
        netipam_obj = self.handlers[Hndl.Subnet]._get_netipam_obj(
            ipam_fq_name, vn_obj)
        if not ipam_fq_name:
            ipam_fq_name = netipam_obj.get_fq_name()

        subnet_vnc = (subnet_res_handler.SubnetCreateHandler.
                      _subnet_neutron_to_vnc(subnet_q))
        logger.info("Changing subnet id from %s ==to==> %s" %
                    (subnet_vnc.subnet_uuid, subnet_q['id']))
        subnet_vnc.subnet_uuid = subnet_q['id']
        subnet_key = (
            subnet_res_handler.SubnetCreateHandler._subnet_vnc_get_key(
                subnet_vnc, net_id))

        # Locate list of subnets to which this subnet has to be appended
        net_ipam_ref = None
        ipam_refs = vn_obj.get_network_ipam_refs()
        for ipam_ref in ipam_refs or []:
            if ipam_ref['to'] == ipam_fq_name:
                net_ipam_ref = ipam_ref
                break

        if not net_ipam_ref:
            # First link from net to this ipam
            vnsn_data = vnc_api.VnSubnetsType([subnet_vnc])
            vn_obj.add_network_ipam(netipam_obj, vnsn_data)
        else:  # virtual-network already linked to this ipam
            for subnet in net_ipam_ref['attr'].get_ipam_subnets():
                if self.handlers[Hndl.Subnet].subnet_cidr_overlaps(
                        subnet_vnc, subnet):
                    existing_sn_id = (
                        self.handlers[Hndl.Subnet]._subnet_vnc_read_mapping(
                            key=self.handlers[Hndl.Subnet]._subnet_vnc_get_key(
                                subnet, net_id)))
                    # duplicate !!
                    msg = (
                        ("Cidr %s overlaps with another subnet of subnet %s") %
                        (subnet_q['cidr'], existing_sn_id))
                    self._raise_contrail_exception('BadRequest',
                                                   resource='subnet',
                                                   msg=msg)
            vnsn_data = net_ipam_ref['attr']
            vnsn_data.ipam_subnets.append(subnet_vnc)
            # TODO(): Add 'ref_update' API that will set this field
            vn_obj._pending_field_updates.add('network_ipam_refs')
        self.handlers[Hndl.Subnet]._resource_update(vn_obj)

        # Read in subnet from server to get updated values for gw etc.
        subnet_vnc = self.handlers[Hndl.Subnet]._subnet_read(subnet_key)
        subnet_info = self.handlers[Hndl.Subnet]._subnet_vnc_to_neutron(
            subnet_vnc, vn_obj, ipam_fq_name)
        return subnet_info
示例#6
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)
示例#7
0
    def resource_create(self, context, subnet_q):
        net_id = subnet_q['network_id']
        vn_obj = self._resource_get(id=net_id)
        ipam_fq_name = subnet_q.get('ipam_fq_name')
        netipam_obj = self._get_netipam_obj(ipam_fq_name, vn_obj)
        if not ipam_fq_name:
            ipam_fq_name = netipam_obj.get_fq_name()

        subnet_vnc = self._subnet_neutron_to_vnc(subnet_q)
        subnet_key = self._subnet_vnc_get_key(subnet_vnc, net_id)
        subnet_cidr = '%s/%s' % (subnet_vnc.subnet.get_ip_prefix(),
                                 subnet_vnc.subnet.get_ip_prefix_len())
        cidr_version = netaddr.IPNetwork(subnet_cidr).version

        # Locate list of subnets to which this subnet has to be appended
        net_ipam_ref = None
        ipam_refs = vn_obj.get_network_ipam_refs()
        for ipam_ref in ipam_refs or []:
            if ipam_ref['to'] == ipam_fq_name:
                net_ipam_ref = ipam_ref
                break

        if not net_ipam_ref:
            # First link from net to this ipam
            vnsn_data = vnc_api.VnSubnetsType([subnet_vnc])
            vn_obj.add_network_ipam(netipam_obj, vnsn_data)
        else:  # virtual-network already linked to this ipam
            for subnet in net_ipam_ref['attr'].get_ipam_subnets():
                if self.subnet_cidr_overlaps(subnet_vnc, subnet):
                    existing_sn_id = self._subnet_vnc_read_mapping(
                        key=self._subnet_vnc_get_key(subnet, net_id))
                    # duplicate !!
                    msg = ("Cidr %s overlaps with another subnet of subnet %s"
                           ) % (subnet_q['cidr'], existing_sn_id)
                    self._raise_contrail_exception('BadRequest',
                                                   resource='subnet',
                                                   msg=msg)
            vnsn_data = net_ipam_ref['attr']
            vnsn_data.ipam_subnets.append(subnet_vnc)
            # TODO(): Add 'ref_update' API that will set this field
            vn_obj._pending_field_updates.add('network_ipam_refs')
        self._resource_update(vn_obj)

        # Read in subnet from server to get updated values for gw etc.
        subnet_vnc = self._subnet_read(subnet_key)
        self._apply_subnet_host_routes(subnet_q, subnet_vnc, subnet_cidr,
                                       cidr_version, vn_obj)
        subnet_info = self._subnet_vnc_to_neutron(subnet_vnc, vn_obj,
                                                  ipam_fq_name)

        return subnet_info
示例#8
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
                                                               ]))
示例#9
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)
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
示例#11
0
文件: ppServer.py 项目: Inmarsat/tcc
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
示例#13
0
for pi in pi_list:
    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")
示例#14
0
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
    vm_interface = vnc_api.VirtualMachineInterface(
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
示例#16
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()