Skip to content

Commit a97c53c

Browse files
authored
Added timeout to HTTP requests in CloudResourceContextIntegration (#4120)
The URL that works in EC2 does not work in ECS, this can lead to the HTTP request getting stuck. Fixes #2376
1 parent 7deebf0 commit a97c53c

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

sentry_sdk/integrations/cloud_resource_context.py

+29-7
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
CONTEXT_TYPE = "cloud_resource"
1515

16+
HTTP_TIMEOUT = 2.0
17+
1618
AWS_METADATA_HOST = "169.254.169.254"
1719
AWS_TOKEN_URL = "http://{}/latest/api/token".format(AWS_METADATA_HOST)
1820
AWS_METADATA_URL = "http://{}/latest/dynamic/instance-identity/document".format(
@@ -59,7 +61,7 @@ class CloudResourceContextIntegration(Integration):
5961
cloud_provider = ""
6062

6163
aws_token = ""
62-
http = urllib3.PoolManager()
64+
http = urllib3.PoolManager(timeout=HTTP_TIMEOUT)
6365

6466
gcp_metadata = None
6567

@@ -83,7 +85,13 @@ def _is_aws(cls):
8385
cls.aws_token = r.data.decode()
8486
return True
8587

86-
except Exception:
88+
except urllib3.exceptions.TimeoutError:
89+
logger.debug(
90+
"AWS metadata service timed out after %s seconds", HTTP_TIMEOUT
91+
)
92+
return False
93+
except Exception as e:
94+
logger.debug("Error checking AWS metadata service: %s", str(e))
8795
return False
8896

8997
@classmethod
@@ -131,8 +139,12 @@ def _get_aws_context(cls):
131139
except Exception:
132140
pass
133141

134-
except Exception:
135-
pass
142+
except urllib3.exceptions.TimeoutError:
143+
logger.debug(
144+
"AWS metadata service timed out after %s seconds", HTTP_TIMEOUT
145+
)
146+
except Exception as e:
147+
logger.debug("Error fetching AWS metadata: %s", str(e))
136148

137149
return ctx
138150

@@ -152,7 +164,13 @@ def _is_gcp(cls):
152164
cls.gcp_metadata = json.loads(r.data.decode("utf-8"))
153165
return True
154166

155-
except Exception:
167+
except urllib3.exceptions.TimeoutError:
168+
logger.debug(
169+
"GCP metadata service timed out after %s seconds", HTTP_TIMEOUT
170+
)
171+
return False
172+
except Exception as e:
173+
logger.debug("Error checking GCP metadata service: %s", str(e))
156174
return False
157175

158176
@classmethod
@@ -201,8 +219,12 @@ def _get_gcp_context(cls):
201219
except Exception:
202220
pass
203221

204-
except Exception:
205-
pass
222+
except urllib3.exceptions.TimeoutError:
223+
logger.debug(
224+
"GCP metadata service timed out after %s seconds", HTTP_TIMEOUT
225+
)
226+
except Exception as e:
227+
logger.debug("Error fetching GCP metadata: %s", str(e))
206228

207229
return ctx
208230

0 commit comments

Comments
 (0)