Avoid allocating ports from ip_local_port_range

Ports within ip_local_port_range can be used by the local side
of connections.  Avoid using them as there should be no downside
from using narrower port range thanks to ExclusiveResource
allocators.

Change-Id: I30e8e40073117e63bf9a99f13000d83a87e64f29
Closes-Bug: #1551288
This commit is contained in:
IWAMOTO Toshihiro 2016-05-23 18:35:05 +09:00
parent 87517709f2
commit 91a983f40a
2 changed files with 14 additions and 3 deletions

View File

@ -180,7 +180,12 @@ def _get_source_ports_from_ss_output(output):
return ports
def get_unused_port(used, start=1024, end=65535):
def get_unused_port(used, start=1024, end=None):
if end is None:
port_range = utils.execute(
['sysctl', '-n', 'net.ipv4.ip_local_port_range'])
end = int(port_range.split()[0]) - 1
candidates = set(range(start, end + 1))
return random.choice(list(candidates - used))

View File

@ -53,7 +53,7 @@ class PortAllocationTestCase(base.DietTestCase):
def test_get_free_namespace_port(self):
ss_output2 = ss_output
for p in range(1024, 65535):
for p in range(1024, 32767):
ss_output2 += ss_output_template % p
with mock.patch('neutron.agent.linux.ip_lib.IPWrapper') \
@ -63,4 +63,10 @@ class PortAllocationTestCase(base.DietTestCase):
ipwrapper.return_value = m
result = net_helpers.get_free_namespace_port(
n_const.PROTO_NAME_TCP)
self.assertEqual(65535, result)
self.assertEqual(32767, result)
def test_get_unused_port(self):
with mock.patch('neutron.agent.linux.utils.execute') as ex:
ex.return_value = "2048\t61000"
result = net_helpers.get_unused_port(set(range(1025, 2048)))
self.assertEqual(1024, result)