blob: fd0391d7cdd20654c88dbb6d3e63d489110c81d4 [file] [log] [blame]
Ryan Tidwell1964a262016-05-04 15:13:23 -07001# Copyright 2016 Hewlett Packard Enterprise Development Company
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
Ryan Tidwell1964a262016-05-04 15:13:23 -070015import netaddr
16
17from tempest.lib import exceptions as lib_exc
18
19
20def get_unused_ip_addresses(ports_client, subnets_client,
21 network_id, subnet_id, count):
22
23 """Return a list with the specified number of unused IP addresses
24
25 This method uses the given ports_client to find the specified number of
26 unused IP addresses on the given subnet using the supplied subnets_client
27 """
28
29 ports = ports_client.list_ports(network_id=network_id)['ports']
30 subnet = subnets_client.show_subnet(subnet_id)
31 ip_net = netaddr.IPNetwork(subnet['subnet']['cidr'])
32 subnet_set = netaddr.IPSet(ip_net.iter_hosts())
33 alloc_set = netaddr.IPSet()
34
35 # prune out any addresses already allocated to existing ports
36 for port in ports:
37 for fixed_ip in port.get('fixed_ips'):
38 alloc_set.add(fixed_ip['ip_address'])
39
40 av_set = subnet_set - alloc_set
Kevin Benton6f455aa2016-07-13 16:20:06 -070041 addrs = []
42 for cidr in reversed(av_set.iter_cidrs()):
43 for ip in reversed(cidr):
44 addrs.append(str(ip))
45 if len(addrs) == count:
46 return addrs
47 msg = "Insufficient IP addresses available"
48 raise lib_exc.BadRequest(message=msg)