Skip to content

Commit

Permalink
Add retries for Sentry monitor API calls
Browse files Browse the repository at this point in the history
Refs GH-192
  • Loading branch information
bchopson committed Oct 19, 2023
1 parent aa60cd6 commit afd9ca9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
44 changes: 32 additions & 12 deletions keg_elements/sentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
except ImportError:
requests = None

try:
import urllib3
except ImportError:
urllib3 = None

try:
import yaml
except ImportError:
Expand Down Expand Up @@ -249,6 +254,16 @@ def install_sentry(app, integrations, release=None, event_filter=None, **kwargs)
)


def retry_http_adapter():
retry_strategy = urllib3.util.retry.Retry(
total=3,
backoff_factor=1,
allowed_methods=['POST', 'PUT'],
status_forcelist=[429, 500, 502, 503, 504],
)
return requests.sessions.HTTPAdapter(max_retries=retry_strategy)


class SentryMonitorError(Exception):
pass

Expand Down Expand Up @@ -344,18 +359,23 @@ def url(self):
return base

def make_request(self, payload):
method = requests.put if self.checkin_id else requests.post
resp = method(
self.url,
json=payload,
headers={
'Authorization': f'DSN {self.dsn}',
},
timeout=10,
)
if resp.status_code >= 400:
raise SentryMonitorError(f'{resp.status_code}: {resp.content}')
return resp.json()
with requests.Session() as session:
session.mount('https://', retry_http_adapter())
method = session.put if self.checkin_id else session.post
try:
resp = method(
self.url,
json=payload,
headers={
'Authorization': f'DSN {self.dsn}',
},
timeout=10,
)
if resp.status_code >= 400:
raise SentryMonitorError(f'{resp.status_code}: {resp.content}')
return resp.json()
except requests.exceptions.RetryError as e:
raise SentryMonitorError(str(e))

def ping_status(self, status):
self.status = status
Expand Down
4 changes: 2 additions & 2 deletions keg_elements/tests/test_sentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,11 +425,11 @@ def test_job_network_error(self):
matchers.json_params_matcher({'status': 'in_progress', 'environment': 'testenv'}),
],
)
with pytest.raises(sentry.SentryMonitorError, match='something wrong'):
with pytest.raises(sentry.SentryMonitorError, match='Max retries exceeded'):
with sentry.sentry_monitor_job('myorg', 'monitor-key', do_ping=True):
pass

assert resp_in_progress.call_count == 1
assert resp_in_progress.call_count == 4

@responses.activate
@mock.patch.dict('flask.current_app.config', {
Expand Down

0 comments on commit afd9ca9

Please sign in to comment.