2828from google .auth import environment_vars
2929from google .auth import exceptions
3030from google .auth import metrics
31+ from google .auth ._exponential_backoff import ExponentialBackoff
3132
3233_LOGGER = logging .getLogger (__name__ )
3334
3435# Environment variable GCE_METADATA_HOST is originally named
35- # GCE_METADATA_ROOT. For compatiblity reasons, here it checks
36+ # GCE_METADATA_ROOT. For compatibility reasons, here it checks
3637# the new variable first; if not set, the system falls back
3738# to the old variable.
3839_GCE_METADATA_HOST = os .getenv (environment_vars .GCE_METADATA_HOST , None )
@@ -119,11 +120,12 @@ def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
119120 # could lead to false negatives in the event that we are on GCE, but
120121 # the metadata resolution was particularly slow. The latter case is
121122 # "unlikely".
122- retries = 0
123123 headers = _METADATA_HEADERS .copy ()
124124 headers [metrics .API_CLIENT_HEADER ] = metrics .mds_ping ()
125125
126- while retries < retry_count :
126+ backoff = ExponentialBackoff (total_attempts = retry_count )
127+
128+ for attempt in backoff :
127129 try :
128130 response = request (
129131 url = _METADATA_IP_ROOT , method = "GET" , headers = headers , timeout = timeout
@@ -139,11 +141,10 @@ def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
139141 _LOGGER .warning (
140142 "Compute Engine Metadata server unavailable on "
141143 "attempt %s of %s. Reason: %s" ,
142- retries + 1 ,
144+ attempt ,
143145 retry_count ,
144146 e ,
145147 )
146- retries += 1
147148
148149 return False
149150
@@ -179,7 +180,7 @@ def get(
179180
180181 Returns:
181182 Union[Mapping, str]: If the metadata server returns JSON, a mapping of
182- the decoded JSON is return . Otherwise, the response content is
183+ the decoded JSON is returned . Otherwise, the response content is
183184 returned as a string.
184185
185186 Raises:
@@ -198,8 +199,9 @@ def get(
198199
199200 url = _helpers .update_query (base_url , query_params )
200201
201- retries = 0
202- while retries < retry_count :
202+ backoff = ExponentialBackoff (total_attempts = retry_count )
203+
204+ for attempt in backoff :
203205 try :
204206 response = request (url = url , method = "GET" , headers = headers_to_use )
205207 break
@@ -208,11 +210,10 @@ def get(
208210 _LOGGER .warning (
209211 "Compute Engine Metadata server unavailable on "
210212 "attempt %s of %s. Reason: %s" ,
211- retries + 1 ,
213+ attempt ,
212214 retry_count ,
213215 e ,
214216 )
215- retries += 1
216217 else :
217218 raise exceptions .TransportError (
218219 "Failed to retrieve {} from the Google Compute Engine "
0 commit comments