Skip to content

Commit 7a62768

Browse files
rmbarrontheacodes
authored andcommitted
Add retry to _metadata.ping() (#323)
1 parent ae7e4f3 commit 7a62768

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

google/auth/compute_engine/_metadata.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,15 @@
5151
_METADATA_DEFAULT_TIMEOUT = 3
5252

5353

54-
def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT):
54+
def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
5555
"""Checks to see if the metadata server is available.
5656
5757
Args:
5858
request (google.auth.transport.Request): A callable used to make
5959
HTTP requests.
6060
timeout (int): How long to wait for the metadata server to respond.
61+
retry_count (int): How many times to attempt connecting to metadata
62+
server using above timeout.
6163
6264
Returns:
6365
bool: True if the metadata server is reachable, False otherwise.
@@ -68,18 +70,23 @@ def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT):
6870
# could lead to false negatives in the event that we are on GCE, but
6971
# the metadata resolution was particularly slow. The latter case is
7072
# "unlikely".
71-
try:
72-
response = request(
73-
url=_METADATA_IP_ROOT, method='GET', headers=_METADATA_HEADERS,
74-
timeout=timeout)
75-
76-
metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
77-
return (response.status == http_client.OK and
78-
metadata_flavor == _METADATA_FLAVOR_VALUE)
79-
80-
except exceptions.TransportError:
81-
_LOGGER.info('Compute Engine Metadata server unavailable.')
82-
return False
73+
retries = 0
74+
while retries < retry_count:
75+
try:
76+
response = request(
77+
url=_METADATA_IP_ROOT, method='GET', headers=_METADATA_HEADERS,
78+
timeout=timeout)
79+
80+
metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
81+
return (response.status == http_client.OK and
82+
metadata_flavor == _METADATA_FLAVOR_VALUE)
83+
84+
except exceptions.TransportError:
85+
_LOGGER.info('Compute Engine Metadata server unavailable on'
86+
'attempt %s of %s', retries+1, retry_count)
87+
retries += 1
88+
89+
return False
8390

8491

8592
def get(request, path, root=_METADATA_ROOT, recursive=False):

0 commit comments

Comments
 (0)