14
14
# KIND, either express or implied. See the License for the
15
15
# specific language governing permissions and limitations
16
16
# under the License.
17
- """The Utils methods."""
17
+
18
+ """Utility functions."""
18
19
19
20
import socket
21
+ import urllib .request
20
22
from collections .abc import Iterable
21
23
from typing import Optional , Union
22
24
@@ -67,8 +69,8 @@ def find_connectable_ip(host: Union[str, bytes, bytearray, None], port: Optional
67
69
port are considered.
68
70
69
71
:Args:
70
- - host - A hostname.
71
- - port - Optional port number.
72
+ - host - hostname
73
+ - port - port number
72
74
73
75
:Returns:
74
76
A single IP address, as a string. If any IPv4 address is found, one is
@@ -100,8 +102,8 @@ def join_host_port(host: str, port: int) -> str:
100
102
example, _join_host_port('::1', 80) == '[::1]:80'.
101
103
102
104
:Args:
103
- - host - A hostname.
104
- - port - An integer port.
105
+ - host - hostname or IP
106
+ - port - port number
105
107
"""
106
108
if ":" in host and not host .startswith ("[" ):
107
109
return f"[{ host } ]:{ port } "
@@ -112,7 +114,8 @@ def is_connectable(port: int, host: Optional[str] = "localhost") -> bool:
112
114
"""Tries to connect to the server at port to see if it is running.
113
115
114
116
:Args:
115
- - port - The port to connect.
117
+ - port - port number
118
+ - host - hostname or IP
116
119
"""
117
120
socket_ = None
118
121
try :
@@ -130,18 +133,22 @@ def is_connectable(port: int, host: Optional[str] = "localhost") -> bool:
130
133
return result
131
134
132
135
133
- def is_url_connectable (port : Union [int , str ]) -> bool :
134
- """Tries to connect to the HTTP server at /status path and specified port
135
- to see if it responds successfully.
136
+ def is_url_connectable (
137
+ port : Union [int , str ],
138
+ host : Optional [str ] = "127.0.0.1" ,
139
+ scheme : Optional [str ] = "http" ,
140
+ ) -> bool :
141
+ """Sends a request to the HTTP server at the /status endpoint to see if it
142
+ responds successfully.
136
143
137
144
:Args:
138
- - port - The port to connect.
145
+ - port - port number
146
+ - host - hostname or IP
147
+ - scheme - URL scheme
139
148
"""
140
- from urllib import request as url_request
141
-
142
149
try :
143
- res = url_request . urlopen (f"http ://127.0.0.1 :{ port } /status" )
144
- return res .getcode () == 200
150
+ with urllib . request . urlopen (f"{ scheme } ://{ host } :{ port } /status" ) as res :
151
+ return res .getcode () == 200
145
152
except Exception :
146
153
return False
147
154
0 commit comments