Commit f70812a3 by Dudás Ádám

vm: extract generic functionality

vm: refactor find_unused_port function
parent fb783308
...@@ -40,12 +40,26 @@ ACCESS_METHODS = [(key, name) for key, (name, port, transport) ...@@ -40,12 +40,26 @@ ACCESS_METHODS = [(key, name) for key, (name, port, transport)
VNC_PORT_RANGE = (2000, 65536) # inclusive start, exclusive end VNC_PORT_RANGE = (2000, 65536) # inclusive start, exclusive end
def find_unused_port(port_range, used_ports=[]):
"""Find an unused port in the specified range.
The list of used ports can be specified optionally.
:param port_range: a tuple representing a port range (w/ exclusive end)
e.g. (6000, 7000) represents ports 6000 through 6999
"""
ports = xrange(*port_range)
used = set(used_ports)
unused = (port for port in ports if port not in used)
return next(unused, None) # first or None
def find_unused_vnc_port(): def find_unused_vnc_port():
used = set(Instance.objects.values_list('vnc_port', flat=True)) port = find_unused_port(
for p in xrange(*VNC_PORT_RANGE): port_range=VNC_PORT_RANGE,
if p not in used: used_ports=Instance.objects.values_list('vnc_port', flat=True))
return p
else: if port is None:
raise Exception("No unused port could be found for VNC.") raise Exception("No unused port could be found for VNC.")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment