-
Notifications
You must be signed in to change notification settings - Fork 526
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 support for Sentry Crons to Celery Beat #1935
Merged
antonpirker
merged 14 commits into
master
from
antonpirker/1932-support-for-sentry-crons
Mar 16, 2023
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
696ac71
Tinkering around
antonpirker f6bf94b
Merge branch 'master' into antonpirker/1932-support-for-sentry-crons
antonpirker 3ec337d
Made flake8 happy
antonpirker b7e0f31
Merge branch 'antonpirker/1932-support-for-sentry-crons' of github.co…
antonpirker 311f3b8
Sending checkin envelop
antonpirker 3d294c0
Some polishing
antonpirker c6bf512
Merge branch 'master' into antonpirker/1932-support-for-sentry-crons
antonpirker cdaf882
Added more data to crons
antonpirker 1607ef1
Preparations for monitor_config
antonpirker ddf775d
Merge branch 'master' into antonpirker/1932-support-for-sentry-crons
antonpirker 8945ad1
Renamed monitor_id to monitor_slug
antonpirker fe26bf9
Added tests and types
antonpirker 5fc4c9a
Documentation
antonpirker 9ed71eb
Merge branch 'master' into antonpirker/1932-support-for-sentry-crons
antonpirker File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
from functools import wraps | ||
import sys | ||
import uuid | ||
|
||
from sentry_sdk import Hub | ||
from sentry_sdk._compat import reraise | ||
from sentry_sdk._types import TYPE_CHECKING | ||
from sentry_sdk.utils import nanosecond_time | ||
|
||
|
||
if TYPE_CHECKING: | ||
from typing import Any, Callable, Dict, Optional | ||
|
||
|
||
class MonitorStatus: | ||
IN_PROGRESS = "in_progress" | ||
OK = "ok" | ||
ERROR = "error" | ||
|
||
|
||
def _create_checkin_event( | ||
monitor_slug=None, check_in_id=None, status=None, duration=None | ||
): | ||
# type: (Optional[str], Optional[str], Optional[str], Optional[float]) -> Dict[str, Any] | ||
options = Hub.current.client.options if Hub.current.client else {} | ||
check_in_id = check_in_id or uuid.uuid4().hex # type: str | ||
# convert nanosecond to millisecond | ||
duration = int(duration * 0.000001) if duration is not None else duration | ||
|
||
checkin = { | ||
"type": "check_in", | ||
"monitor_slug": monitor_slug, | ||
# TODO: Add schedule and schedule_type to monitor config | ||
# "monitor_config": { | ||
# "schedule": "*/10 0 0 0 0", | ||
# "schedule_type": "cron", | ||
# }, | ||
"check_in_id": check_in_id, | ||
"status": status, | ||
"duration": duration, | ||
"environment": options["environment"], | ||
"release": options["release"], | ||
} | ||
|
||
return checkin | ||
|
||
|
||
def capture_checkin(monitor_slug=None, check_in_id=None, status=None, duration=None): | ||
# type: (Optional[str], Optional[str], Optional[str], Optional[float]) -> str | ||
hub = Hub.current | ||
|
||
check_in_id = check_in_id or uuid.uuid4().hex | ||
checkin_event = _create_checkin_event( | ||
monitor_slug=monitor_slug, | ||
check_in_id=check_in_id, | ||
status=status, | ||
duration=duration, | ||
) | ||
hub.capture_event(checkin_event) | ||
|
||
return checkin_event["check_in_id"] | ||
|
||
|
||
def monitor(monitor_slug=None, app=None): | ||
# type: (Optional[str], Any) -> Callable[..., Any] | ||
""" | ||
Decorator to capture checkin events for a monitor. | ||
|
||
Usage: | ||
``` | ||
import sentry_sdk | ||
|
||
app = Celery() | ||
|
||
@app.task | ||
@sentry_sdk.monitor(monitor_slug='my-fancy-slug') | ||
def test(arg): | ||
print(arg) | ||
``` | ||
|
||
This does not have to be used with Celery, but if you do use it with celery, | ||
put the `@sentry_sdk.monitor` decorator below Celery's `@app.task` decorator. | ||
""" | ||
|
||
def decorate(func): | ||
# type: (Callable[..., Any]) -> Callable[..., Any] | ||
if not monitor_slug: | ||
return func | ||
|
||
@wraps(func) | ||
def wrapper(*args, **kwargs): | ||
# type: (*Any, **Any) -> Any | ||
start_timestamp = nanosecond_time() | ||
check_in_id = capture_checkin( | ||
monitor_slug=monitor_slug, status=MonitorStatus.IN_PROGRESS | ||
) | ||
|
||
try: | ||
result = func(*args, **kwargs) | ||
except Exception: | ||
duration = nanosecond_time() - start_timestamp | ||
capture_checkin( | ||
monitor_slug=monitor_slug, | ||
check_in_id=check_in_id, | ||
status=MonitorStatus.ERROR, | ||
duration=duration, | ||
) | ||
exc_info = sys.exc_info() | ||
reraise(*exc_info) | ||
|
||
duration = nanosecond_time() - start_timestamp | ||
capture_checkin( | ||
monitor_slug=monitor_slug, | ||
check_in_id=check_in_id, | ||
status=MonitorStatus.OK, | ||
duration=duration, | ||
) | ||
|
||
return result | ||
|
||
return wrapper | ||
|
||
return decorate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
import mock | ||
import pytest | ||
import uuid | ||
|
||
import sentry_sdk | ||
from sentry_sdk.crons import capture_checkin | ||
|
||
|
||
@sentry_sdk.monitor(monitor_slug="abc123") | ||
def _hello_world(name): | ||
return "Hello, {}".format(name) | ||
|
||
|
||
@sentry_sdk.monitor(monitor_slug="def456") | ||
def _break_world(name): | ||
1 / 0 | ||
return "Hello, {}".format(name) | ||
|
||
|
||
def test_decorator(sentry_init): | ||
sentry_init() | ||
|
||
with mock.patch("sentry_sdk.crons.capture_checkin") as fake_capture_checking: | ||
result = _hello_world("Grace") | ||
assert result == "Hello, Grace" | ||
|
||
# Check for initial checkin | ||
fake_capture_checking.assert_has_calls( | ||
[ | ||
mock.call(monitor_slug="abc123", status="in_progress"), | ||
] | ||
) | ||
|
||
# Check for final checkin | ||
assert fake_capture_checking.call_args[1]["monitor_slug"] == "abc123" | ||
assert fake_capture_checking.call_args[1]["status"] == "ok" | ||
assert fake_capture_checking.call_args[1]["duration"] | ||
assert fake_capture_checking.call_args[1]["check_in_id"] | ||
|
||
|
||
def test_decorator_error(sentry_init): | ||
sentry_init() | ||
|
||
with mock.patch("sentry_sdk.crons.capture_checkin") as fake_capture_checking: | ||
with pytest.raises(Exception): | ||
result = _break_world("Grace") | ||
|
||
assert "result" not in locals() | ||
|
||
# Check for initial checkin | ||
fake_capture_checking.assert_has_calls( | ||
[ | ||
mock.call(monitor_slug="def456", status="in_progress"), | ||
] | ||
) | ||
|
||
# Check for final checkin | ||
assert fake_capture_checking.call_args[1]["monitor_slug"] == "def456" | ||
assert fake_capture_checking.call_args[1]["status"] == "error" | ||
assert fake_capture_checking.call_args[1]["duration"] | ||
assert fake_capture_checking.call_args[1]["check_in_id"] | ||
|
||
|
||
def test_capture_checkin_simple(sentry_init): | ||
sentry_init() | ||
|
||
check_in_id = capture_checkin( | ||
monitor_slug="abc123", | ||
check_in_id="112233", | ||
status=None, | ||
duration=None, | ||
) | ||
assert check_in_id == "112233" | ||
|
||
|
||
def test_capture_checkin_new_id(sentry_init): | ||
sentry_init() | ||
|
||
with mock.patch("uuid.uuid4") as mock_uuid: | ||
mock_uuid.return_value = uuid.UUID("a8098c1a-f86e-11da-bd1a-00112444be1e") | ||
check_in_id = capture_checkin( | ||
monitor_slug="abc123", | ||
check_in_id=None, | ||
status=None, | ||
duration=None, | ||
) | ||
|
||
assert check_in_id == "a8098c1af86e11dabd1a00112444be1e" |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could probably combine both in finally?