Ryan Tidwell | 1964a26 | 2016-05-04 15:13:23 -0700 | [diff] [blame] | 1 | # 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 Tidwell | 1964a26 | 2016-05-04 15:13:23 -0700 | [diff] [blame] | 15 | import netaddr |
| 16 | |
| 17 | from tempest.lib import exceptions as lib_exc |
| 18 | |
| 19 | |
| 20 | def 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 | |
zhufl | 8458dde | 2016-08-25 11:29:13 +0800 | [diff] [blame^] | 40 | # exclude gateway_ip of subnet |
| 41 | gateway_ip = subnet['subnet']['gateway_ip'] |
| 42 | if gateway_ip: |
| 43 | alloc_set.add(gateway_ip) |
| 44 | |
Ryan Tidwell | 1964a26 | 2016-05-04 15:13:23 -0700 | [diff] [blame] | 45 | av_set = subnet_set - alloc_set |
Kevin Benton | 6f455aa | 2016-07-13 16:20:06 -0700 | [diff] [blame] | 46 | addrs = [] |
| 47 | for cidr in reversed(av_set.iter_cidrs()): |
| 48 | for ip in reversed(cidr): |
| 49 | addrs.append(str(ip)) |
| 50 | if len(addrs) == count: |
| 51 | return addrs |
| 52 | msg = "Insufficient IP addresses available" |
| 53 | raise lib_exc.BadRequest(message=msg) |