28
28
from google .auth import environment_vars
29
29
from google .auth import exceptions
30
30
from google .auth import metrics
31
+ from google .auth ._exponential_backoff import ExponentialBackoff
31
32
32
33
_LOGGER = logging .getLogger (__name__ )
33
34
34
35
# 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
36
37
# the new variable first; if not set, the system falls back
37
38
# to the old variable.
38
39
_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):
119
120
# could lead to false negatives in the event that we are on GCE, but
120
121
# the metadata resolution was particularly slow. The latter case is
121
122
# "unlikely".
122
- retries = 0
123
123
headers = _METADATA_HEADERS .copy ()
124
124
headers [metrics .API_CLIENT_HEADER ] = metrics .mds_ping ()
125
125
126
- while retries < retry_count :
126
+ backoff = ExponentialBackoff (total_attempts = retry_count )
127
+
128
+ for attempt in backoff :
127
129
try :
128
130
response = request (
129
131
url = _METADATA_IP_ROOT , method = "GET" , headers = headers , timeout = timeout
@@ -139,11 +141,10 @@ def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
139
141
_LOGGER .warning (
140
142
"Compute Engine Metadata server unavailable on "
141
143
"attempt %s of %s. Reason: %s" ,
142
- retries + 1 ,
144
+ attempt ,
143
145
retry_count ,
144
146
e ,
145
147
)
146
- retries += 1
147
148
148
149
return False
149
150
@@ -179,7 +180,7 @@ def get(
179
180
180
181
Returns:
181
182
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
183
184
returned as a string.
184
185
185
186
Raises:
@@ -198,8 +199,9 @@ def get(
198
199
199
200
url = _helpers .update_query (base_url , query_params )
200
201
201
- retries = 0
202
- while retries < retry_count :
202
+ backoff = ExponentialBackoff (total_attempts = retry_count )
203
+
204
+ for attempt in backoff :
203
205
try :
204
206
response = request (url = url , method = "GET" , headers = headers_to_use )
205
207
break
@@ -208,11 +210,10 @@ def get(
208
210
_LOGGER .warning (
209
211
"Compute Engine Metadata server unavailable on "
210
212
"attempt %s of %s. Reason: %s" ,
211
- retries + 1 ,
213
+ attempt ,
212
214
retry_count ,
213
215
e ,
214
216
)
215
- retries += 1
216
217
else :
217
218
raise exceptions .TransportError (
218
219
"Failed to retrieve {} from the Google Compute Engine "
0 commit comments