def _allocate_sockets(environment, host_ip, sock_type, count):
"""Return a list of `count` socket bound to an ephemeral port.
"""
# TODO: this should probably be abstracted away
if environment == 'prod':
port_pool = six.moves.range(PROD_PORT_LOW, PROD_PORT_HIGH + 1)
else:
port_pool = six.moves.range(NONPROD_PORT_LOW, NONPROD_PORT_HIGH + 1)
port_pool = random.sample(port_pool, PORT_SPAN)
# socket objects are closed on GC so we need to return
# them and expect the caller to keep them around while needed
sockets = []
for real_port in port_pool:
if len(sockets) == count:
break
socket_ = socket.socket(socket.AF_INET, sock_type)
try:
socket_.bind((host_ip, real_port))
if sock_type == socket.SOCK_STREAM:
socket_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket_.listen(0)
except socket.error as err:
if err.errno == errno.EADDRINUSE:
continue
raise
sockets.append(socket_)
else:
raise exc.ContainerSetupError('{0} < {1}'.format(len(sockets), count),
app_abort.AbortedReason.PORTS)
return sockets
评论列表
文章目录