comparison env/lib/python3.9/site-packages/planemo/network_util.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 import socket
2 from http.client import BadStatusLine
3 from time import time as now
4
5 from six.moves.urllib.error import URLError
6 from six.moves.urllib.request import urlopen
7
8
9 def get_free_port():
10 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
11 sock.bind(('localhost', 0))
12 port = sock.getsockname()[1]
13 sock.close()
14 return port
15
16
17 def wait_http_service(url, timeout=None):
18 if timeout:
19 end = now() + timeout
20
21 while True:
22 try:
23 if timeout:
24 next_timeout = end - now()
25 if next_timeout < 0:
26 return False
27
28 kwds = {} if timeout is None else dict(timeout=next_timeout)
29 with urlopen(url, **kwds) as r:
30 if r.getcode() != 200:
31 continue
32 return True
33 except socket.error:
34 pass
35 except BadStatusLine:
36 pass
37 except URLError:
38 pass
39
40
41 # code.activestate.com/recipes/576655-wait-for-network-service-to-appear
42 def wait_net_service(server, port, timeout=None):
43 """ Wait for network service to appear.
44
45 :param int timeout: in seconds, if None or 0 wait forever
46 :return: A ``bool`` - if ``timeout`` is ``None`` may return only ``True`` or
47 throw an unhandled network exception.
48 """
49 if port is None:
50 raise TypeError("wait_net_service passed NoneType port value.")
51
52 port = int(port)
53
54 if timeout:
55 end = now() + timeout
56
57 while True:
58 s = socket.socket()
59 # Following line prevents this method from interfering with process
60 # it is waiting for on localhost.
61 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
62 try:
63 if timeout:
64 next_timeout = end - now()
65 if next_timeout < 0:
66 return False
67 else:
68 s.settimeout(next_timeout)
69
70 s.connect((server, port))
71
72 except socket.timeout:
73 # this exception occurs only if timeout is set
74 if timeout:
75 return False
76
77 except socket.error:
78 # if getattr(e, "errno") == 61:
79 # refused_connections += 1
80 s.close()
81 else:
82 s.close()
83 return True