Allocates a floating IP to the tenant.

        You must provide a pool name or id for which you would like to
        allocate a floating IP.

        :returns: FloatingIp object corresponding to an allocated floating IP
170850
def allocate(self, pool, tenant_id=None, **params):
        
        if not tenant_id:
            tenant_id = self.request.user.project_id
        create_dict = {'floating_network_id': pool,
                       'tenant_id': tenant_id}
        if 'subnet_id' in params:
            create_dict['subnet_id'] = params['subnet_id']
        if 'floating_ip_address' in params:
            create_dict['floating_ip_address'] = params['floating_ip_address']
        if 'description' in params:
            create_dict['description'] = params['description']
        if 'dns_domain' in params:
            create_dict['dns_domain'] = params['dns_domain']
        if 'dns_name' in params:
            create_dict['dns_name'] = params['dns_name']
        fip = self.client.create_floatingip(
            {'floatingip': create_dict}).get('floatingip')
        self._set_instance_info(fip)
        return FloatingIp(fip)
286023
def list_pools(self):
        
        search_opts = {'router:external': True}
        return [FloatingIpPool(pool) for pool
                in self.client.list_networks(**search_opts).get('networks')]
760708
def delete_floatingip(self, floatingip_id):
        '''
        
        '''
        ret = self.network_conn.delete_floatingip(floatingip_id)
        return ret if ret else True
1315343
def list(self, all_tenants=False, **search_opts):
        
        if not all_tenants:
            tenant_id = self.request.user.tenant_id
            # In Neutron, list_floatingips returns Floating IPs from
            # all tenants when the API is called with admin role, so
            # we need to filter them with tenant_id.
            search_opts['tenant_id'] = tenant_id
            port_search_opts = {'tenant_id': tenant_id}
        else:
            port_search_opts = {}
        fips = self.client.list_floatingips(**search_opts)
        fips = fips.get('floatingips')
        # Get port list to add instance_id to floating IP list
        # instance_id is stored in device_id attribute
        ports = port_list(self.request, **port_search_opts)
        port_dict = collections.OrderedDict([(p['id'], p) for p in ports])
        for fip in fips:
            self._set_instance_info(fip, port_dict.get(fip['port_id']))
        return [FloatingIp(fip) for fip in fips]
247313
def floating_ip_delete(self, floating_ip):
        '''
        
        '''
        ip = self.floating_ip_show(floating_ip)
        nt_ks = self.compute_conn
        return nt_ks.floating_ips.delete(ip)
1292124
def get(self, floating_ip_id):
        
        fip = self.client.show_floatingip(floating_ip_id).get('floatingip')
        self._set_instance_info(fip)
        return FloatingIp(fip)
949977
def id_pools_ipv4_subnets(self):
        
        if not self.__id_pools_ipv4_subnets:
            self.__id_pools_ipv4_subnets = IdPoolsIpv4Subnets(self.__connection)
        return self.__id_pools_ipv4_subnets
1239122
def allocate_elastic_ip(self):
        
        log = logging.getLogger(self.cls_logger + '.allocate_elastic_ip')

        # Attempt to allocate a new elastic IP
        log.info('Attempting to allocate an elastic IP...')
        try:
            response = self.client.allocate_address(
                    DryRun=False,
                    Domain='vpc'
            )
        except ClientError:
            _, ex, trace = sys.exc_info()
            msg = 'Unable to allocate a new elastic IP address\n{e}'.format(e=str(ex))
            log.error(msg)
            raise AWSAPIError, msg, trace

        allocation_id = response['AllocationId']
        public_ip = response['PublicIp']
        log.info('Allocated Elastic IP with ID {a} and Public IP address {p}'.
                 format(a=allocation_id, p=public_ip))

        # Verify the Address was allocated successfully
        log.info('Verifying the elastic IP address was allocated and is available '
                 'for use...')
        ready = False
        verification_timer = [2]*60 + [5]*60 + [10]*18
        num_checks = len(verification_timer)
        for i in range(0, num_checks):
            wait_time = verification_timer[i]
            try:
                self.client.describe_addresses(
                        DryRun=False,
                        AllocationIds=[allocation_id]
                )
            except ClientError:
                _, ex, trace = sys.exc_info()
                log.info('Elastic IP address {p} with Allocation ID {a} is not available for use, trying again in '
                         '{w} sec...\n{e}'.format(p=public_ip, a=allocation_id, w=wait_time, e=str(ex)))
                time.sleep(wait_time)
            else:
                log.info('Elastic IP {p} with Allocation ID {a} is available for use'.format(
                    p=public_ip, a=allocation_id))
                ready = True
                break
        if ready:
            return {'AllocationId': allocation_id, 'PublicIp': public_ip}
        else:
            msg = 'Unable to verify existence of new Elastic IP {p} with Allocation ID: {a}'. \
                format(p=public_ip, a=allocation_id)
            log.error(msg)
            raise EC2UtilError(msg)
908414
def get_in_subnet_id(cls, tenant_id):
        
        if 'in' not in cls.ip_db_obj:
            LOG.error("Fabric not prepared for tenant %s", tenant_id)
            return None
        db_obj = cls.ip_db_obj.get('in')
        in_subnet_dict = cls.get_in_ip_addr(tenant_id)
        sub = db_obj.get_subnet(in_subnet_dict.get('subnet'))
        return sub.subnet_id
930516
def _ip_int_from_prefix(self, prefixlen=None):
        
        if prefixlen is None:
            prefixlen = self._prefixlen
        return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
830115
def get_connection_pool(self, pool_id, *args, **kwargs):
        
        assert isinstance(pool_id, (str, unicode))
        if not hasattr(self, '_pools'):
            self._pools = {}
        if pool_id not in self._pools:
            self._pools[pool_id] = ConnectionPool(*args, **kwargs)
        # logging.debug("%s: _connections = %d", pool_id, self._pools[pool_id]._connections)
        return self._pools[pool_id]
452975
def check_allocate_ip(self, obj, direc):
        
        subnet_lst = self.os_helper.get_all_subnets_cidr(no_mask=True)
        ip_next = obj.allocate_subnet(subnet_lst)
        if ip_next is None:
            LOG.error("Unable to allocate a subnet for direction %s",
                      direc)
        return ip_next
490729
def get_ip(self):
        
        json_scheme = self.gen_def_json_scheme('GetPurchasedIpAddresses')
        json_obj = self.call_method_post(method='GetPurchasedIpAddresses ', json_scheme=json_scheme)
        self.iplist = IpList()
        for ip in json_obj['Value']:
            r = Ip()
            r.ip_addr = ip['Value']
            r.resid = ip['ResourceId']
            r.serverid = ip['ServerId'] if 'None' not in str(ip['ServerId']) else None
            self.iplist.append(r)
470210
def allocate_subnet(self, subnet_lst, net_id=None):
        

        session = db.get_session()
        query_str = None
        for sub in subnet_lst:
            sub_que = (self.model.subnet_address != sub)
            if query_str is not None:
                query_str = query_str & sub_que
            else:
                query_str = sub_que
        with session.begin(subtransactions=True):
            select = (session.query(self.model).filter(
                (self.model.allocated == 0) & query_str))

            # Selected segment can be allocated before update by someone else,
            # We retry until update success or DB_MAX_RETRIES retries
            for attempt in range(DB_MAX_RETRIES + 1):
                alloc = select.first()
                if not alloc:
                    LOG.info("No subnet resource available")
                    return
                count = (session.query(self.model).
                         filter_by(subnet_address=alloc.subnet_address,
                         allocated=False).update({"allocated": True,
                                                  "network_id": net_id}))
                if count:
                    return alloc.subnet_address

        LOG.error("ERROR: Failed to allocate subnet for net %(net)s",
                  {'net': net_id})
        return None
699855
def _allocate_address(self, instance):
        
        connection = self._connect()
        free_addresses = [ ip for ip in connection.get_all_addresses() if not ip.instance_id]
        if not free_addresses:
            try:
                address = connection.allocate_address()
            except Exception as ex:
                log.error("Unable to allocate a public IP address to instance `%s`",
                          instance.id)
                return None

        try:
            address = free_addresses.pop()
            instance.use_ip(address)
            return address.public_ip
        except Exception as ex:
            log.error("Unable to associate IP address %s to instance `%s`",
                      address, instance.id)
            return None
483255
def assign_floating_ip(self, ip_addr, droplet_id):
        
        if self.api_version == 2:
            params = {'type': 'assign','droplet_id': droplet_id}

            json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST')
            return json['action']
        else:
            raise DoError(v2_api_required_str)
1294608
def ip(self) -> Optional[str]:
        
        ips = self.ips
        if ips and len(ips) > 0:
            return ips[0]
        if self._transport:
            return cast(
                str,
                self._transport.get_extra_info("peername"),
            )
        return None