Exemplo n.º 1
0
 def _set_allowed_address_pairs(self, intf):
     aap_list = []
     for aap_entry in intf.get(self.ALLOWED_ADDRESS_PAIRS, None) or []:
         aap = vnc_api.AllowedAddressPair()
         if aap_entry.get(self.PREFIX, None):
             cidr = aap_entry.get(self.PREFIX).split('/')
             if len(cidr) == 1:
                 if (vnc_api.IPAddress(cidr[0]).version == 4):
                     subnet = vnc_api.SubnetType(cidr[0], 32)
                 elif (vnc_api.IPAddress(cidr[0]).version == 6):
                     subnet = vnc_api.SubnetType(cidr[0], 128)
             elif len(cidr) == 2:
                 subnet = vnc_api.SubnetType(cidr[0], int(cidr[1]))
             else:
                 LOG.warn(
                     _("'Invalid allowed address ip %s.") %
                     aap_entry.get(self.PREFIX))
                 raise
         aap.set_ip(subnet)
         aap.set_mac(aap_entry.get(self.MAC_ADDRESS, None))
         if not aap_entry.get(self.MAC_ADDRESS, None):
             aap.set_mac("")
         else:
             aap.set_mac(aap_entry.get(self.MAC_ADDRESS))
         if not aap_entry.get(self.ADDRESS_MODE, None):
             aap.set_address_mode("active-active")
         else:
             aap.set_address_mode(aap_entry.get(self.ADDRESS_MODE))
         aap_list.append(aap)
     if aap_list:
         aaps = vnc_api.AllowedAddressPairs()
         aaps.set_allowed_address_pair(aap_list)
         return aaps
     return None
Exemplo n.º 2
0
    def _set_vmi_allowed_addr_pairs(self, vmi_obj, allowed_addr_pairs):
        aap_array = []
        for address_pair in allowed_addr_pairs or []:
            mode = u'active-standby'
            if 'mac_address' not in address_pair:
                address_pair['mac_address'] = ""

            cidr = address_pair['ip_address'].split('/')
            if len(cidr) == 1:
                subnet = vnc_api.SubnetType(cidr[0], 32)
            elif len(cidr) == 2:
                subnet = vnc_api.SubnetType(cidr[0], int(cidr[1]))
            else:
                self._raise_contrail_exception(
                    'BadRequest', resource='port',
                    msg='Invalid address pair argument')

            aap_array.append(vnc_api.AllowedAddressPair(
                subnet,
                address_pair['mac_address'], mode))

        aaps = vnc_api.AllowedAddressPairs()
        if aap_array:
            aaps.set_allowed_address_pair(aap_array)
        vmi_obj.set_virtual_machine_interface_allowed_address_pairs(aaps)
    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)))
        '''
Exemplo n.º 4
0
    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        try:
            obj_0 = self.vnc_lib().dsa_rule_read(
                id=self.resource_id
            )
        except:
            raise Exception(_('dsa-rule %s not found.') % self.name)

        if prop_diff.get(self.DSA_RULE_ENTRY) is not None:
            obj_1 = vnc_api.DiscoveryServiceAssignmentType()
            if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER) is not None:
                obj_2 = vnc_api.DiscoveryPubSubEndPointType()
                if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_TYPE) is not None:
                    obj_2.set_ep_type(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_TYPE))
                if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_ID) is not None:
                    obj_2.set_ep_id(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_ID))
                if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX) is not None:
                    obj_3 = vnc_api.SubnetType()
                    if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX_IP_PREFIX) is not None:
                        obj_3.set_ip_prefix(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX_IP_PREFIX))
                    if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX_IP_PREFIX_LEN) is not None:
                        obj_3.set_ip_prefix_len(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_PREFIX_IP_PREFIX_LEN))
                    obj_2.set_ep_prefix(obj_3)
                if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_VERSION) is not None:
                    obj_2.set_ep_version(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_PUBLISHER, {}).get(self.DSA_RULE_ENTRY_PUBLISHER_EP_VERSION))
                obj_1.set_publisher(obj_2)
            if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER) is not None:
                for index_1 in range(len(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER))):
                    obj_2 = vnc_api.DiscoveryPubSubEndPointType()
                    if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_TYPE) is not None:
                        obj_2.set_ep_type(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_TYPE))
                    if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_ID) is not None:
                        obj_2.set_ep_id(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_ID))
                    if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX) is not None:
                        obj_3 = vnc_api.SubnetType()
                        if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX_IP_PREFIX) is not None:
                            obj_3.set_ip_prefix(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX_IP_PREFIX))
                        if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX_IP_PREFIX_LEN) is not None:
                            obj_3.set_ip_prefix_len(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_PREFIX_IP_PREFIX_LEN))
                        obj_2.set_ep_prefix(obj_3)
                    if prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_VERSION) is not None:
                        obj_2.set_ep_version(prop_diff.get(self.DSA_RULE_ENTRY, {}).get(self.DSA_RULE_ENTRY_SUBSCRIBER, {})[index_1].get(self.DSA_RULE_ENTRY_SUBSCRIBER_EP_VERSION))
                    obj_1.add_subscriber(obj_2)
            obj_0.set_dsa_rule_entry(obj_1)
        if prop_diff.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(prop_diff.get(self.DISPLAY_NAME))

        try:
            self.vnc_lib().dsa_rule_update(obj_0)
        except:
            raise Exception(_('dsa-rule %s could not be updated.') % self.name)
Exemplo n.º 5
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)
Exemplo n.º 6
0
 def _get_rule(ingress, sg, prefix, ethertype):
     sgr_uuid = str(uuid.uuid4())
     if sg:
         addr = vnc_api.AddressType(
             security_group=proj_obj.get_fq_name_str() + ':' + sg)
     elif prefix:
         addr = vnc_api.AddressType(
             subnet=vnc_api.SubnetType(prefix, 0))
     local_addr = vnc_api.AddressType(security_group='local')
     if ingress:
         src_addr = addr
         dst_addr = local_addr
     else:
         src_addr = local_addr
         dst_addr = addr
     rule = vnc_api.PolicyRuleType(
         rule_uuid=sgr_uuid,
         direction='>',
         protocol='any',
         src_addresses=[src_addr],
         src_ports=[vnc_api.PortType(0, 65535)],
         dst_addresses=[dst_addr],
         dst_ports=[vnc_api.PortType(0, 65535)],
         ethertype=ethertype)
     return rule
    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        try:
            obj_0 = self.vnc_lib().namespace_read(id=self.resource_id)
        except:
            raise Exception(_('namespace %s not found.') % self.name)

        if prop_diff.get(self.NAMESPACE_CIDR) is not None:
            obj_1 = vnc_api.SubnetType()
            if prop_diff.get(self.NAMESPACE_CIDR, {}).get(
                    self.NAMESPACE_CIDR_IP_PREFIX) is not None:
                obj_1.set_ip_prefix(
                    prop_diff.get(self.NAMESPACE_CIDR,
                                  {}).get(self.NAMESPACE_CIDR_IP_PREFIX))
            if prop_diff.get(self.NAMESPACE_CIDR, {}).get(
                    self.NAMESPACE_CIDR_IP_PREFIX_LEN) is not None:
                obj_1.set_ip_prefix_len(
                    prop_diff.get(self.NAMESPACE_CIDR,
                                  {}).get(self.NAMESPACE_CIDR_IP_PREFIX_LEN))
            obj_0.set_namespace_cidr(obj_1)
        if prop_diff.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(prop_diff.get(self.DISPLAY_NAME))

        try:
            self.vnc_lib().namespace_update(obj_0)
        except:
            raise Exception(
                _('namespace %s could not be updated.') % self.name)
Exemplo n.º 8
0
def construct_security_group(project):
    security_group = vnc_api.SecurityGroup(name=VNC_VCENTER_DEFAULT_SG,
                                           parent_obj=project)

    security_group_entry = vnc_api.PolicyEntriesType()

    ingress_rule = vnc_api.PolicyRuleType(
        rule_uuid=str(uuid4()),
        direction='>',
        protocol='any',
        src_addresses=[vnc_api.AddressType(
            security_group=':'.join(VNC_VCENTER_DEFAULT_SG_FQN))],
        src_ports=[vnc_api.PortType(0, 65535)],
        dst_addresses=[vnc_api.AddressType(security_group='local')],
        dst_ports=[vnc_api.PortType(0, 65535)],
        ethertype='IPv4',
    )

    egress_rule = vnc_api.PolicyRuleType(
        rule_uuid=str(uuid4()),
        direction='>',
        protocol='any',
        src_addresses=[vnc_api.AddressType(security_group='local')],
        src_ports=[vnc_api.PortType(0, 65535)],
        dst_addresses=[vnc_api.AddressType(subnet=vnc_api.SubnetType('0.0.0.0', 0))],
        dst_ports=[vnc_api.PortType(0, 65535)],
        ethertype='IPv4',
    )

    security_group_entry.add_policy_rule(ingress_rule)
    security_group_entry.add_policy_rule(egress_rule)

    security_group.set_security_group_entries(security_group_entry)
    return security_group
Exemplo n.º 9
0
    def _security_group_rule_neutron_to_vnc(self, sgr_q):
        port_min = 0
        port_max = 65535
        if sgr_q['port_range_min'] is not None:
            port_min = sgr_q['port_range_min']
        if sgr_q['port_range_max'] is not None:
            port_max = sgr_q['port_range_max']

        endpt = [vnc_api.AddressType(security_group='any')]
        if sgr_q['remote_ip_prefix']:
            cidr = sgr_q['remote_ip_prefix'].split('/')
            pfx = cidr[0]
            pfx_len = int(cidr[1])
            endpt = [vnc_api.AddressType(
                subnet=vnc_api.SubnetType(pfx, pfx_len))]
        elif sgr_q['remote_group_id']:
            try:
                sg_obj = sg_handler.SecurityGroupHandler(
                    self._vnc_lib).get_sg_obj(id=sgr_q['remote_group_id'])
            except vnc_exc.NoIdError:
                self._raise_contrail_exception('SecurityGroupNotFound',
                                               id=sgr_q['remote_group_id'],
                                               resource='security_group_rule')

            if sgr_q.get('tenant_id') and (
                    sg_obj.parent_uuid != sgr_q['tenant_id']):
                self._raise_contrail_exception("NotFound")

            endpt = [vnc_api.AddressType(
                security_group=sg_obj.get_fq_name_str())]

        if sgr_q['direction'] == 'ingress':
            dir = '>'
            local = endpt
            remote = [vnc_api.AddressType(security_group='local')]
        else:
            dir = '>'
            remote = endpt
            local = [vnc_api.AddressType(security_group='local')]

        if not sgr_q['protocol']:
            sgr_q['protocol'] = 'any'

        if not sgr_q['remote_ip_prefix'] and not sgr_q['remote_group_id']:
            if not sgr_q['ethertype']:
                sgr_q['ethertype'] = 'IPv4'

        sgr_uuid = str(uuid.uuid4()) if 'id' not in sgr_q else sgr_q['id']

        rule = vnc_api.PolicyRuleType(
            rule_uuid=sgr_uuid, direction=dir,
            protocol=sgr_q['protocol'],
            src_addresses=local,
            src_ports=[vnc_api.PortType(0, 65535)],
            dst_addresses=remote,
            dst_ports=[vnc_api.PortType(port_min, port_max)],
            ethertype=sgr_q['ethertype'])
        return rule
    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        try:
            obj_0 = self.vnc_lib().floating_ip_pool_read(id=self.resource_id)
        except:
            raise Exception(_('floating-ip-pool %s not found.') % self.name)

        if prop_diff.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(prop_diff.get(self.DISPLAY_NAME))
        if prop_diff.get(self.FLOATING_IP_POOL_PREFIXES) is not None:
            obj_1 = vnc_api.FloatingIpPoolType()
            if prop_diff.get(self.FLOATING_IP_POOL_PREFIXES, {}).get(
                    self.FLOATING_IP_POOL_PREFIXES_SUBNET) is not None:
                for index_1 in range(
                        len(
                            prop_diff.get(
                                self.FLOATING_IP_POOL_PREFIXES, {}).get(
                                    self.FLOATING_IP_POOL_PREFIXES_SUBNET))):
                    obj_2 = vnc_api.SubnetType()
                    if prop_diff.get(self.FLOATING_IP_POOL_PREFIXES, {}).get(
                            self.FLOATING_IP_POOL_PREFIXES_SUBNET,
                        {})[index_1].get(
                            self.FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX
                        ) is not None:
                        obj_2.set_ip_prefix(
                            prop_diff.get(
                                self.FLOATING_IP_POOL_PREFIXES,
                                {}).get(self.FLOATING_IP_POOL_PREFIXES_SUBNET,
                                        {})
                            [index_1].get(
                                self.FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX
                            ))
                    if prop_diff.get(self.FLOATING_IP_POOL_PREFIXES, {}).get(
                            self.FLOATING_IP_POOL_PREFIXES_SUBNET,
                        {})[index_1].get(
                            self.FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX_LEN
                        ) is not None:
                        obj_2.set_ip_prefix_len(
                            prop_diff.get(
                                self.FLOATING_IP_POOL_PREFIXES,
                                {}).get(self.FLOATING_IP_POOL_PREFIXES_SUBNET,
                                        {})
                            [index_1].get(
                                self.
                                FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX_LEN)
                        )
                    obj_1.add_subnet(obj_2)
            obj_0.set_floating_ip_pool_prefixes(obj_1)

        try:
            self.vnc_lib().floating_ip_pool_update(obj_0)
        except:
            raise Exception(
                _('floating-ip-pool %s could not be updated.') % self.name)
Exemplo n.º 11
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)
Exemplo n.º 12
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
                                                               ]))
Exemplo n.º 13
0
    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        try:
            obj_0 = self.vnc_lib().subnet_read(id=self.resource_id)
        except:
            raise Exception(_('subnet %s not found.') % self.name)

        if prop_diff.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(prop_diff.get(self.DISPLAY_NAME))
        if prop_diff.get(self.SUBNET_IP_PREFIX) is not None:
            obj_1 = vnc_api.SubnetType()
            if prop_diff.get(self.SUBNET_IP_PREFIX, {}).get(
                    self.SUBNET_IP_PREFIX_IP_PREFIX) is not None:
                obj_1.set_ip_prefix(
                    prop_diff.get(self.SUBNET_IP_PREFIX,
                                  {}).get(self.SUBNET_IP_PREFIX_IP_PREFIX))
            if prop_diff.get(self.SUBNET_IP_PREFIX, {}).get(
                    self.SUBNET_IP_PREFIX_IP_PREFIX_LEN) is not None:
                obj_1.set_ip_prefix_len(
                    prop_diff.get(self.SUBNET_IP_PREFIX,
                                  {}).get(self.SUBNET_IP_PREFIX_IP_PREFIX_LEN))
            obj_0.set_subnet_ip_prefix(obj_1)

        # reference to virtual_machine_interface_refs
        ref_obj_list = []
        ref_data_list = []
        if self.VIRTUAL_MACHINE_INTERFACE_REFS in prop_diff:
            for index_0 in range(
                    len(
                        prop_diff.get(self.VIRTUAL_MACHINE_INTERFACE_REFS)
                        or [])):
                try:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        id=prop_diff.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                except:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        fq_name_str=prop_diff.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                ref_obj_list.append(ref_obj.fq_name)

            obj_0.set_virtual_machine_interface_list(ref_obj_list)
            # End: reference to virtual_machine_interface_refs

        try:
            self.vnc_lib().subnet_update(obj_0)
        except:
            raise Exception(_('subnet %s could not be updated.') % self.name)
Exemplo n.º 14
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
Exemplo n.º 16
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
Exemplo n.º 17
0
    def handle_create(self):
        parent_obj = None
        if parent_obj is None and self.properties.get(self.DOMAIN):
            try:
                parent_obj = self.vnc_lib().domain_read(
                    id=self.properties.get(self.DOMAIN))
            except vnc_api.NoIdError:
                parent_obj = self.vnc_lib().domain_read(
                    fq_name_str=self.properties.get(self.DOMAIN))
            except:
                parent_obj = None

        if parent_obj is None:
            raise Exception('Error: parent is not specified in template!')

        obj_0 = vnc_api.Namespace(name=self.properties[self.NAME],
                                  parent_obj=parent_obj)

        if self.properties.get(self.NAMESPACE_CIDR) is not None:
            obj_1 = vnc_api.SubnetType()
            if self.properties.get(self.NAMESPACE_CIDR, {}).get(
                    self.NAMESPACE_CIDR_IP_PREFIX) is not None:
                obj_1.set_ip_prefix(
                    self.properties.get(self.NAMESPACE_CIDR,
                                        {}).get(self.NAMESPACE_CIDR_IP_PREFIX))
            if self.properties.get(self.NAMESPACE_CIDR, {}).get(
                    self.NAMESPACE_CIDR_IP_PREFIX_LEN) is not None:
                obj_1.set_ip_prefix_len(
                    self.properties.get(self.NAMESPACE_CIDR, {}).get(
                        self.NAMESPACE_CIDR_IP_PREFIX_LEN))
            obj_0.set_namespace_cidr(obj_1)
        if self.properties.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(self.properties.get(self.DISPLAY_NAME))

        try:
            obj_uuid = super(ContrailNamespace, self).resource_create(obj_0)
        except:
            raise Exception(
                _('namespace %s could not be updated.') % self.name)

        self.resource_id_set(obj_uuid)
Exemplo n.º 18
0
    def handle_create(self):
        obj_0 = vnc_api.Subnet(name=self.properties[self.NAME])

        if self.properties.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(self.properties.get(self.DISPLAY_NAME))
        if self.properties.get(self.SUBNET_IP_PREFIX) is not None:
            obj_1 = vnc_api.SubnetType()
            if self.properties.get(self.SUBNET_IP_PREFIX, {}).get(
                    self.SUBNET_IP_PREFIX_IP_PREFIX) is not None:
                obj_1.set_ip_prefix(
                    self.properties.get(self.SUBNET_IP_PREFIX, {}).get(
                        self.SUBNET_IP_PREFIX_IP_PREFIX))
            if self.properties.get(self.SUBNET_IP_PREFIX, {}).get(
                    self.SUBNET_IP_PREFIX_IP_PREFIX_LEN) is not None:
                obj_1.set_ip_prefix_len(
                    self.properties.get(self.SUBNET_IP_PREFIX, {}).get(
                        self.SUBNET_IP_PREFIX_IP_PREFIX_LEN))
            obj_0.set_subnet_ip_prefix(obj_1)

        # reference to virtual_machine_interface_refs
        if self.properties.get(self.VIRTUAL_MACHINE_INTERFACE_REFS):
            for index_0 in range(
                    len(
                        self.properties.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS))):
                try:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        id=self.properties.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                except vnc_api.NoIdError:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        fq_name_str=self.properties.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                obj_0.add_virtual_machine_interface(ref_obj)

        try:
            obj_uuid = super(ContrailSubnet, self).resource_create(obj_0)
        except:
            raise Exception(_('subnet %s could not be updated.') % self.name)

        self.resource_id_set(obj_uuid)
Exemplo n.º 19
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
Exemplo n.º 20
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
Exemplo n.º 21
0
    def handle_create(self):
        obj_0 = vnc_api.InstanceIp(name=self.properties[self.NAME])

        if self.properties.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(self.properties.get(self.DISPLAY_NAME))
        if self.properties.get(self.SERVICE_HEALTH_CHECK_IP) is not None:
            obj_0.set_service_health_check_ip(
                self.properties.get(self.SERVICE_HEALTH_CHECK_IP))
        if self.properties.get(self.SECONDARY_IP_TRACKING_IP) is not None:
            obj_1 = vnc_api.SubnetType()
            if self.properties.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                    self.SECONDARY_IP_TRACKING_IP_IP_PREFIX) is not None:
                obj_1.set_ip_prefix(
                    self.properties.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                        self.SECONDARY_IP_TRACKING_IP_IP_PREFIX))
            if self.properties.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                    self.SECONDARY_IP_TRACKING_IP_IP_PREFIX_LEN) is not None:
                obj_1.set_ip_prefix_len(
                    self.properties.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                        self.SECONDARY_IP_TRACKING_IP_IP_PREFIX_LEN))
            obj_0.set_secondary_ip_tracking_ip(obj_1)
        if self.properties.get(self.INSTANCE_IP_ADDRESS) is not None:
            obj_0.set_instance_ip_address(
                self.properties.get(self.INSTANCE_IP_ADDRESS))
        if self.properties.get(self.INSTANCE_IP_MODE) is not None:
            obj_0.set_instance_ip_mode(
                self.properties.get(self.INSTANCE_IP_MODE))
        if self.properties.get(self.SUBNET_UUID) is not None:
            obj_0.set_subnet_uuid(self.properties.get(self.SUBNET_UUID))
        if self.properties.get(self.INSTANCE_IP_FAMILY) is not None:
            obj_0.set_instance_ip_family(
                self.properties.get(self.INSTANCE_IP_FAMILY))
        if self.properties.get(self.SERVICE_INSTANCE_IP) is not None:
            obj_0.set_service_instance_ip(
                self.properties.get(self.SERVICE_INSTANCE_IP))
        if self.properties.get(self.INSTANCE_IP_SECONDARY) is not None:
            obj_0.set_instance_ip_secondary(
                self.properties.get(self.INSTANCE_IP_SECONDARY))

        # reference to physical_router_refs
        if self.properties.get(self.PHYSICAL_ROUTER_REFS):
            for index_0 in range(
                    len(self.properties.get(self.PHYSICAL_ROUTER_REFS))):
                try:
                    ref_obj = self.vnc_lib().physical_router_read(
                        id=self.properties.get(
                            self.PHYSICAL_ROUTER_REFS)[index_0])
                except vnc_api.NoIdError:
                    ref_obj = self.vnc_lib().physical_router_read(
                        fq_name_str=self.properties.get(
                            self.PHYSICAL_ROUTER_REFS)[index_0])
                obj_0.add_physical_router(ref_obj)

        # reference to virtual_machine_interface_refs
        if self.properties.get(self.VIRTUAL_MACHINE_INTERFACE_REFS):
            for index_0 in range(
                    len(
                        self.properties.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS))):
                try:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        id=self.properties.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                except vnc_api.NoIdError:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        fq_name_str=self.properties.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                obj_0.add_virtual_machine_interface(ref_obj)

        # reference to virtual_network_refs
        if self.properties.get(self.VIRTUAL_NETWORK_REFS):
            for index_0 in range(
                    len(self.properties.get(self.VIRTUAL_NETWORK_REFS))):
                try:
                    ref_obj = self.vnc_lib().virtual_network_read(
                        id=self.properties.get(
                            self.VIRTUAL_NETWORK_REFS)[index_0])
                except vnc_api.NoIdError:
                    ref_obj = self.vnc_lib().virtual_network_read(
                        fq_name_str=self.properties.get(
                            self.VIRTUAL_NETWORK_REFS)[index_0])
                obj_0.add_virtual_network(ref_obj)

        try:
            obj_uuid = super(ContrailInstanceIp, self).resource_create(obj_0)
        except:
            raise Exception(
                _('instance-ip %s could not be updated.') % self.name)

        self.resource_id_set(obj_uuid)
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
Exemplo n.º 23
0
    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        try:
            obj_0 = self.vnc_lib().global_system_config_read(
                id=self.resource_id)
        except:
            raise Exception(
                _('global-system-config %s not found.') % self.name)

        if prop_diff.get(self.CONFIG_VERSION) is not None:
            obj_0.set_config_version(prop_diff.get(self.CONFIG_VERSION))
        if prop_diff.get(self.USER_DEFINED_COUNTER) is not None:
            obj_1 = vnc_api.UserDefinedCounterList()
            if prop_diff.get(self.USER_DEFINED_COUNTER, {}).get(
                    self.USER_DEFINED_COUNTER_COUNTER) is not None:
                for index_1 in range(
                        len(
                            prop_diff.get(self.USER_DEFINED_COUNTER, {}).get(
                                self.USER_DEFINED_COUNTER_COUNTER))):
                    obj_2 = vnc_api.UserDefinedCounter()
                    if prop_diff.get(self.USER_DEFINED_COUNTER, {}).get(
                            self.USER_DEFINED_COUNTER_COUNTER,
                        {})[index_1].get(self.USER_DEFINED_COUNTER_COUNTER_NAME
                                         ) is not None:
                        obj_2.set_name(
                            prop_diff.get(self.USER_DEFINED_COUNTER, {}).get(
                                self.USER_DEFINED_COUNTER_COUNTER,
                                {})[index_1].get(
                                    self.USER_DEFINED_COUNTER_COUNTER_NAME))
                    if prop_diff.get(self.USER_DEFINED_COUNTER, {}).get(
                            self.USER_DEFINED_COUNTER_COUNTER,
                        {})[index_1].get(
                            self.USER_DEFINED_COUNTER_COUNTER_PATTERN
                        ) is not None:
                        obj_2.set_pattern(
                            prop_diff.get(self.USER_DEFINED_COUNTER, {}).get(
                                self.USER_DEFINED_COUNTER_COUNTER,
                                {})[index_1].get(
                                    self.USER_DEFINED_COUNTER_COUNTER_PATTERN))
                    obj_1.add_counter(obj_2)
            obj_0.set_user_defined_counter(obj_1)
        if prop_diff.get(self.ALARM_ENABLE) is not None:
            obj_0.set_alarm_enable(prop_diff.get(self.ALARM_ENABLE))
        if prop_diff.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(prop_diff.get(self.DISPLAY_NAME))
        if prop_diff.get(self.PLUGIN_TUNING) is not None:
            obj_1 = vnc_api.PluginProperties()
            if prop_diff.get(self.PLUGIN_TUNING, {}).get(
                    self.PLUGIN_TUNING_PLUGIN_PROPERTY) is not None:
                for index_1 in range(
                        len(
                            prop_diff.get(self.PLUGIN_TUNING, {}).get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY))):
                    obj_2 = vnc_api.PluginProperty()
                    if prop_diff.get(self.PLUGIN_TUNING, {}).get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY,
                        {})[index_1].get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY_PROPERTY
                        ) is not None:
                        obj_2.set_property(
                            prop_diff.get(self.PLUGIN_TUNING, {}).get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY, {})
                            [index_1].get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY_PROPERTY))
                    if prop_diff.get(self.PLUGIN_TUNING, {}).get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY,
                        {})[index_1].get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY_VALUE
                        ) is not None:
                        obj_2.set_value(
                            prop_diff.get(self.PLUGIN_TUNING, {}).get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY,
                                {})[index_1].get(
                                    self.PLUGIN_TUNING_PLUGIN_PROPERTY_VALUE))
                    obj_1.add_plugin_property(obj_2)
            obj_0.set_plugin_tuning(obj_1)
        if prop_diff.get(self.IBGP_AUTO_MESH) is not None:
            obj_0.set_ibgp_auto_mesh(prop_diff.get(self.IBGP_AUTO_MESH))
        if prop_diff.get(self.IP_FABRIC_SUBNETS) is not None:
            obj_1 = vnc_api.SubnetListType()
            if prop_diff.get(self.IP_FABRIC_SUBNETS, {}).get(
                    self.IP_FABRIC_SUBNETS_SUBNET) is not None:
                for index_1 in range(
                        len(
                            prop_diff.get(self.IP_FABRIC_SUBNETS, {}).get(
                                self.IP_FABRIC_SUBNETS_SUBNET))):
                    obj_2 = vnc_api.SubnetType()
                    if prop_diff.get(self.IP_FABRIC_SUBNETS, {}).get(
                            self.IP_FABRIC_SUBNETS_SUBNET, {})[index_1].get(
                                self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX
                            ) is not None:
                        obj_2.set_ip_prefix(
                            prop_diff.get(self.IP_FABRIC_SUBNETS, {}).get(
                                self.IP_FABRIC_SUBNETS_SUBNET,
                                {})[index_1].get(
                                    self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX))
                    if prop_diff.get(self.IP_FABRIC_SUBNETS, {}).get(
                            self.IP_FABRIC_SUBNETS_SUBNET, {})[index_1].get(
                                self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX_LEN
                            ) is not None:
                        obj_2.set_ip_prefix_len(
                            prop_diff.get(self.IP_FABRIC_SUBNETS, {}).get(
                                self.IP_FABRIC_SUBNETS_SUBNET, {})
                            [index_1].get(
                                self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX_LEN))
                    obj_1.add_subnet(obj_2)
            obj_0.set_ip_fabric_subnets(obj_1)
        if prop_diff.get(self.AUTONOMOUS_SYSTEM) is not None:
            obj_0.set_autonomous_system(prop_diff.get(self.AUTONOMOUS_SYSTEM))

        # reference to bgp_router_refs
        ref_obj_list = []
        ref_data_list = []
        if self.BGP_ROUTER_REFS in prop_diff:
            for index_0 in range(len(
                    prop_diff.get(self.BGP_ROUTER_REFS) or [])):
                try:
                    ref_obj = self.vnc_lib().bgp_router_read(
                        id=prop_diff.get(self.BGP_ROUTER_REFS)[index_0])
                except:
                    ref_obj = self.vnc_lib().bgp_router_read(
                        fq_name_str=prop_diff.get(
                            self.BGP_ROUTER_REFS)[index_0])
                ref_obj_list.append(ref_obj.fq_name)

            obj_0.set_bgp_router_list(ref_obj_list)
            # End: reference to bgp_router_refs

        try:
            self.vnc_lib().global_system_config_update(obj_0)
        except:
            raise Exception(
                _('global-system-config %s could not be updated.') % self.name)
Exemplo n.º 24
0
    def handle_create(self):
        obj_0 = vnc_api.GlobalSystemConfig(name=self.properties[self.NAME])

        if self.properties.get(self.CONFIG_VERSION) is not None:
            obj_0.set_config_version(self.properties.get(self.CONFIG_VERSION))
        if self.properties.get(self.USER_DEFINED_COUNTER) is not None:
            obj_1 = vnc_api.UserDefinedCounterList()
            if self.properties.get(self.USER_DEFINED_COUNTER, {}).get(
                    self.USER_DEFINED_COUNTER_COUNTER) is not None:
                for index_1 in range(
                        len(
                            self.properties.get(
                                self.USER_DEFINED_COUNTER,
                                {}).get(self.USER_DEFINED_COUNTER_COUNTER))):
                    obj_2 = vnc_api.UserDefinedCounter()
                    if self.properties.get(self.USER_DEFINED_COUNTER, {}).get(
                            self.USER_DEFINED_COUNTER_COUNTER,
                        {})[index_1].get(self.USER_DEFINED_COUNTER_COUNTER_NAME
                                         ) is not None:
                        obj_2.set_name(
                            self.properties.get(
                                self.USER_DEFINED_COUNTER,
                                {}).get(self.USER_DEFINED_COUNTER_COUNTER, {})
                            [index_1].get(
                                self.USER_DEFINED_COUNTER_COUNTER_NAME))
                    if self.properties.get(self.USER_DEFINED_COUNTER, {}).get(
                            self.USER_DEFINED_COUNTER_COUNTER,
                        {})[index_1].get(
                            self.USER_DEFINED_COUNTER_COUNTER_PATTERN
                        ) is not None:
                        obj_2.set_pattern(
                            self.properties.get(
                                self.USER_DEFINED_COUNTER,
                                {}).get(self.USER_DEFINED_COUNTER_COUNTER, {})
                            [index_1].get(
                                self.USER_DEFINED_COUNTER_COUNTER_PATTERN))
                    obj_1.add_counter(obj_2)
            obj_0.set_user_defined_counter(obj_1)
        if self.properties.get(self.ALARM_ENABLE) is not None:
            obj_0.set_alarm_enable(self.properties.get(self.ALARM_ENABLE))
        if self.properties.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(self.properties.get(self.DISPLAY_NAME))
        if self.properties.get(self.PLUGIN_TUNING) is not None:
            obj_1 = vnc_api.PluginProperties()
            if self.properties.get(self.PLUGIN_TUNING, {}).get(
                    self.PLUGIN_TUNING_PLUGIN_PROPERTY) is not None:
                for index_1 in range(
                        len(
                            self.properties.get(self.PLUGIN_TUNING, {}).get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY))):
                    obj_2 = vnc_api.PluginProperty()
                    if self.properties.get(self.PLUGIN_TUNING, {}).get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY,
                        {})[index_1].get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY_PROPERTY
                        ) is not None:
                        obj_2.set_property(
                            self.properties.get(self.PLUGIN_TUNING, {}).get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY, {})
                            [index_1].get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY_PROPERTY))
                    if self.properties.get(self.PLUGIN_TUNING, {}).get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY,
                        {})[index_1].get(
                            self.PLUGIN_TUNING_PLUGIN_PROPERTY_VALUE
                        ) is not None:
                        obj_2.set_value(
                            self.properties.get(self.PLUGIN_TUNING, {}).get(
                                self.PLUGIN_TUNING_PLUGIN_PROPERTY,
                                {})[index_1].get(
                                    self.PLUGIN_TUNING_PLUGIN_PROPERTY_VALUE))
                    obj_1.add_plugin_property(obj_2)
            obj_0.set_plugin_tuning(obj_1)
        if self.properties.get(self.IBGP_AUTO_MESH) is not None:
            obj_0.set_ibgp_auto_mesh(self.properties.get(self.IBGP_AUTO_MESH))
        if self.properties.get(self.IP_FABRIC_SUBNETS) is not None:
            obj_1 = vnc_api.SubnetListType()
            if self.properties.get(self.IP_FABRIC_SUBNETS, {}).get(
                    self.IP_FABRIC_SUBNETS_SUBNET) is not None:
                for index_1 in range(
                        len(
                            self.properties.get(
                                self.IP_FABRIC_SUBNETS,
                                {}).get(self.IP_FABRIC_SUBNETS_SUBNET))):
                    obj_2 = vnc_api.SubnetType()
                    if self.properties.get(self.IP_FABRIC_SUBNETS, {}).get(
                            self.IP_FABRIC_SUBNETS_SUBNET, {})[index_1].get(
                                self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX
                            ) is not None:
                        obj_2.set_ip_prefix(
                            self.properties.get(
                                self.IP_FABRIC_SUBNETS,
                                {}).get(self.IP_FABRIC_SUBNETS_SUBNET, {})
                            [index_1].get(
                                self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX))
                    if self.properties.get(self.IP_FABRIC_SUBNETS, {}).get(
                            self.IP_FABRIC_SUBNETS_SUBNET, {})[index_1].get(
                                self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX_LEN
                            ) is not None:
                        obj_2.set_ip_prefix_len(
                            self.properties.get(
                                self.IP_FABRIC_SUBNETS,
                                {}).get(self.IP_FABRIC_SUBNETS_SUBNET, {})
                            [index_1].get(
                                self.IP_FABRIC_SUBNETS_SUBNET_IP_PREFIX_LEN))
                    obj_1.add_subnet(obj_2)
            obj_0.set_ip_fabric_subnets(obj_1)
        if self.properties.get(self.AUTONOMOUS_SYSTEM) is not None:
            obj_0.set_autonomous_system(
                self.properties.get(self.AUTONOMOUS_SYSTEM))

        # reference to bgp_router_refs
        if self.properties.get(self.BGP_ROUTER_REFS):
            for index_0 in range(len(self.properties.get(
                    self.BGP_ROUTER_REFS))):
                try:
                    ref_obj = self.vnc_lib().bgp_router_read(
                        id=self.properties.get(self.BGP_ROUTER_REFS)[index_0])
                except vnc_api.NoIdError:
                    ref_obj = self.vnc_lib().bgp_router_read(
                        fq_name_str=self.properties.get(
                            self.BGP_ROUTER_REFS)[index_0])
                obj_0.add_bgp_router(ref_obj)

        try:
            obj_uuid = super(ContrailGlobalSystemConfig,
                             self).resource_create(obj_0)
        except:
            raise Exception(
                _('global-system-config %s could not be updated.') % self.name)

        self.resource_id_set(obj_uuid)
Exemplo n.º 25
0
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
    def handle_create(self):
        parent_obj = None
        if parent_obj is None and self.properties.get(self.VIRTUAL_NETWORK):
            try:
                parent_obj = self.vnc_lib().virtual_network_read(
                    id=self.properties.get(self.VIRTUAL_NETWORK))
            except vnc_api.NoIdError:
                parent_obj = self.vnc_lib().virtual_network_read(
                    fq_name_str=self.properties.get(self.VIRTUAL_NETWORK))
            except:
                parent_obj = None

        if parent_obj is None:
            raise Exception('Error: parent is not specified in template!')

        obj_0 = vnc_api.FloatingIpPool(name=self.properties[self.NAME],
                                       parent_obj=parent_obj)

        if self.properties.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(self.properties.get(self.DISPLAY_NAME))
        if self.properties.get(self.FLOATING_IP_POOL_PREFIXES) is not None:
            obj_1 = vnc_api.FloatingIpPoolType()
            if self.properties.get(self.FLOATING_IP_POOL_PREFIXES, {}).get(
                    self.FLOATING_IP_POOL_PREFIXES_SUBNET) is not None:
                for index_1 in range(
                        len(
                            self.properties.get(
                                self.FLOATING_IP_POOL_PREFIXES, {}).get(
                                    self.FLOATING_IP_POOL_PREFIXES_SUBNET))):
                    obj_2 = vnc_api.SubnetType()
                    if self.properties.get(
                            self.FLOATING_IP_POOL_PREFIXES,
                        {}).get(
                            self.FLOATING_IP_POOL_PREFIXES_SUBNET,
                            {})[index_1].get(
                                self.FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX
                            ) is not None:
                        obj_2.set_ip_prefix(
                            self.properties.get(
                                self.FLOATING_IP_POOL_PREFIXES,
                                {}).get(self.FLOATING_IP_POOL_PREFIXES_SUBNET,
                                        {})
                            [index_1].get(
                                self.FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX
                            ))
                    if self.properties.get(
                            self.FLOATING_IP_POOL_PREFIXES,
                        {}).get(
                            self.FLOATING_IP_POOL_PREFIXES_SUBNET, {}
                        )[index_1].get(
                            self.FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX_LEN
                        ) is not None:
                        obj_2.set_ip_prefix_len(
                            self.properties.get(
                                self.FLOATING_IP_POOL_PREFIXES,
                                {}).get(self.FLOATING_IP_POOL_PREFIXES_SUBNET,
                                        {})
                            [index_1].get(
                                self.
                                FLOATING_IP_POOL_PREFIXES_SUBNET_IP_PREFIX_LEN)
                        )
                    obj_1.add_subnet(obj_2)
            obj_0.set_floating_ip_pool_prefixes(obj_1)

        try:
            obj_uuid = super(ContrailFloatingIpPool,
                             self).resource_create(obj_0)
        except:
            raise Exception(
                _('floating-ip-pool %s could not be updated.') % self.name)

        self.resource_id_set(obj_uuid)
Exemplo n.º 27
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)
my_vpg.set_virtual_port_group_type('access')
Exemplo n.º 28
0
    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        try:
            obj_0 = self.vnc_lib().instance_ip_read(id=self.resource_id)
        except:
            raise Exception(_('instance-ip %s not found.') % self.name)

        if prop_diff.get(self.DISPLAY_NAME) is not None:
            obj_0.set_display_name(prop_diff.get(self.DISPLAY_NAME))
        if prop_diff.get(self.SERVICE_HEALTH_CHECK_IP) is not None:
            obj_0.set_service_health_check_ip(
                prop_diff.get(self.SERVICE_HEALTH_CHECK_IP))
        if prop_diff.get(self.SECONDARY_IP_TRACKING_IP) is not None:
            obj_1 = vnc_api.SubnetType()
            if prop_diff.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                    self.SECONDARY_IP_TRACKING_IP_IP_PREFIX) is not None:
                obj_1.set_ip_prefix(
                    prop_diff.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                        self.SECONDARY_IP_TRACKING_IP_IP_PREFIX))
            if prop_diff.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                    self.SECONDARY_IP_TRACKING_IP_IP_PREFIX_LEN) is not None:
                obj_1.set_ip_prefix_len(
                    prop_diff.get(self.SECONDARY_IP_TRACKING_IP, {}).get(
                        self.SECONDARY_IP_TRACKING_IP_IP_PREFIX_LEN))
            obj_0.set_secondary_ip_tracking_ip(obj_1)
        if prop_diff.get(self.INSTANCE_IP_ADDRESS) is not None:
            obj_0.set_instance_ip_address(
                prop_diff.get(self.INSTANCE_IP_ADDRESS))
        if prop_diff.get(self.INSTANCE_IP_MODE) is not None:
            obj_0.set_instance_ip_mode(prop_diff.get(self.INSTANCE_IP_MODE))
        if prop_diff.get(self.SUBNET_UUID) is not None:
            obj_0.set_subnet_uuid(prop_diff.get(self.SUBNET_UUID))
        if prop_diff.get(self.INSTANCE_IP_FAMILY) is not None:
            obj_0.set_instance_ip_family(prop_diff.get(
                self.INSTANCE_IP_FAMILY))
        if prop_diff.get(self.SERVICE_INSTANCE_IP) is not None:
            obj_0.set_service_instance_ip(
                prop_diff.get(self.SERVICE_INSTANCE_IP))
        if prop_diff.get(self.INSTANCE_IP_SECONDARY) is not None:
            obj_0.set_instance_ip_secondary(
                prop_diff.get(self.INSTANCE_IP_SECONDARY))

        # reference to physical_router_refs
        ref_obj_list = []
        ref_data_list = []
        if self.PHYSICAL_ROUTER_REFS in prop_diff:
            for index_0 in range(
                    len(prop_diff.get(self.PHYSICAL_ROUTER_REFS) or [])):
                try:
                    ref_obj = self.vnc_lib().physical_router_read(
                        id=prop_diff.get(self.PHYSICAL_ROUTER_REFS)[index_0])
                except:
                    ref_obj = self.vnc_lib().physical_router_read(
                        fq_name_str=prop_diff.get(
                            self.PHYSICAL_ROUTER_REFS)[index_0])
                ref_obj_list.append(ref_obj.fq_name)

            obj_0.set_physical_router_list(ref_obj_list)
            # End: reference to physical_router_refs

        # reference to virtual_machine_interface_refs
        ref_obj_list = []
        ref_data_list = []
        if self.VIRTUAL_MACHINE_INTERFACE_REFS in prop_diff:
            for index_0 in range(
                    len(
                        prop_diff.get(self.VIRTUAL_MACHINE_INTERFACE_REFS)
                        or [])):
                try:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        id=prop_diff.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                except:
                    ref_obj = self.vnc_lib().virtual_machine_interface_read(
                        fq_name_str=prop_diff.get(
                            self.VIRTUAL_MACHINE_INTERFACE_REFS)[index_0])
                ref_obj_list.append(ref_obj.fq_name)

            obj_0.set_virtual_machine_interface_list(ref_obj_list)
            # End: reference to virtual_machine_interface_refs

        # reference to virtual_network_refs
        ref_obj_list = []
        ref_data_list = []
        if self.VIRTUAL_NETWORK_REFS in prop_diff:
            for index_0 in range(
                    len(prop_diff.get(self.VIRTUAL_NETWORK_REFS) or [])):
                try:
                    ref_obj = self.vnc_lib().virtual_network_read(
                        id=prop_diff.get(self.VIRTUAL_NETWORK_REFS)[index_0])
                except:
                    ref_obj = self.vnc_lib().virtual_network_read(
                        fq_name_str=prop_diff.get(
                            self.VIRTUAL_NETWORK_REFS)[index_0])
                ref_obj_list.append(ref_obj.fq_name)

            obj_0.set_virtual_network_list(ref_obj_list)
            # End: reference to virtual_network_refs

        try:
            self.vnc_lib().instance_ip_update(obj_0)
        except:
            raise Exception(
                _('instance-ip %s could not be updated.') % self.name)
    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
Exemplo n.º 30
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()