blob: d98fb320fa57e8e8c37729e8593c90bd3f2300b0 [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
15import itertools
16import netaddr
17
18from tempest.lib import exceptions as lib_exc
19
20
21def get_unused_ip_addresses(ports_client, subnets_client,
22 network_id, subnet_id, count):
23
24 """Return a list with the specified number of unused IP addresses
25
26 This method uses the given ports_client to find the specified number of
27 unused IP addresses on the given subnet using the supplied subnets_client
28 """
29
30 ports = ports_client.list_ports(network_id=network_id)['ports']
31 subnet = subnets_client.show_subnet(subnet_id)
32 ip_net = netaddr.IPNetwork(subnet['subnet']['cidr'])
33 subnet_set = netaddr.IPSet(ip_net.iter_hosts())
34 alloc_set = netaddr.IPSet()
35
36 # prune out any addresses already allocated to existing ports
37 for port in ports:
38 for fixed_ip in port.get('fixed_ips'):
39 alloc_set.add(fixed_ip['ip_address'])
40
41 av_set = subnet_set - alloc_set
42 ip_list = [str(ip) for ip in itertools.islice(av_set, count)]
43
44 if len(ip_list) != count:
45 msg = "Insufficient IP addresses available"
46 raise lib_exc.BadRequest(message=msg)
47
48 return ip_list