comparison env/lib/python3.7/site-packages/planemo/network_util.py @ 0:26e78fe6e8c4 draft

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