Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add retry to _metadata.ping() #323

Merged
merged 1 commit into from
Feb 15, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 additions & 13 deletions google/auth/compute_engine/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,15 @@
_METADATA_DEFAULT_TIMEOUT = 3


def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT):
def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
"""Checks to see if the metadata server is available.

Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
timeout (int): How long to wait for the metadata server to respond.
retry_count (int): How many times to attempt connecting to metadata
server using above timeout.

Returns:
bool: True if the metadata server is reachable, False otherwise.
Expand All @@ -68,18 +70,23 @@ def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT):
# could lead to false negatives in the event that we are on GCE, but
# the metadata resolution was particularly slow. The latter case is
# "unlikely".
try:
response = request(
url=_METADATA_IP_ROOT, method='GET', headers=_METADATA_HEADERS,
timeout=timeout)

metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
return (response.status == http_client.OK and
metadata_flavor == _METADATA_FLAVOR_VALUE)

except exceptions.TransportError:
_LOGGER.info('Compute Engine Metadata server unavailable.')
return False
retries = 0
while retries < retry_count:
try:
response = request(
url=_METADATA_IP_ROOT, method='GET', headers=_METADATA_HEADERS,
timeout=timeout)

metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
return (response.status == http_client.OK and
metadata_flavor == _METADATA_FLAVOR_VALUE)

except exceptions.TransportError:
_LOGGER.info('Compute Engine Metadata server unavailable on'
'attempt %s of %s', retries+1, retry_count)
retries += 1

return False


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