未验证 提交 68c01ac2 编写于 作者: K kuizhiqing 提交者: GitHub

[LAUNCH] rewrite get free port strategy (#45247)

* rewrite get free port strategy

* hide the old one
上级 194d16c1
...@@ -14,6 +14,8 @@ ...@@ -14,6 +14,8 @@
from .device import Device from .device import Device
import os
import random
import socket import socket
import struct import struct
from contextlib import closing from contextlib import closing
...@@ -28,6 +30,12 @@ class Node(object): ...@@ -28,6 +30,12 @@ class Node(object):
self.free_ports = [] self.free_ports = []
self._allocated_ports = [] self._allocated_ports = []
port_range = os.getenv('PORT_RANGE', '35100:64000')
port_range = port_range.split(':')
self._port_start = int(port_range[0])
self._port_end = int(port_range[1])
self._port_cur = random.randint(self._port_start, self._port_end)
def get_host_ip(self): def get_host_ip(self):
try: try:
self.hostname = socket.gethostname() self.hostname = socket.gethostname()
...@@ -44,21 +52,44 @@ class Node(object): ...@@ -44,21 +52,44 @@ class Node(object):
def get_ports_occupied(self): def get_ports_occupied(self):
return self.free_ports return self.free_ports
def _get_free_port(self, port=0):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', 1, 0))
try:
s.bind(('', port))
return s.getsockname()[1]
except:
return -1
def _update_port_cur(self):
self._port_cur += 1
if self._port_cur > self._port_end:
self._port_cur = self._port_start
def get_free_port(self): def get_free_port(self):
for _ in range(100):
ret = self._get_free_port(self._port_cur)
if ret > 0:
self._update_port_cur()
return ret
else:
self._update_port_cur()
return self._port_cur
'''
def get_free_port2(self):
# for loop to avoid port conflict # for loop to avoid port conflict
for _ in range(100): for _ in range(100):
with closing(socket.socket(socket.AF_INET, port = self._get_free_port()
socket.SOCK_STREAM)) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', 1, 0))
s.bind(('', 0))
port = s.getsockname()[1]
if port in self._allocated_ports: if port in self._allocated_ports:
continue continue
else: else:
self._allocated_ports.append(port) self._allocated_ports.append(port)
return port return port
return port return port
'''
@classmethod @classmethod
def is_server_ready(self, ip, port): def is_server_ready(self, ip, port):
...@@ -72,3 +103,8 @@ class Node(object): ...@@ -72,3 +103,8 @@ class Node(object):
return True return True
else: else:
return False return False
if __name__ == '__main__':
n = Node()
print(n.get_free_ports(10))
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册