diff --git a/README.md b/README.md index a89b506..1cdce16 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,10 @@ In this guide: -- [Installation](#Installation) +- [Installation](#installation) - [Monitoring Background Jobs](#monitoring-background-jobs) - [Sending Telemetry Events](#sending-telemetry-events) +- [Error Tracking](#error-tracking) - [Configuring Monitors](#configuring-monitors) - [Package Configuration & Env Vars](#package-configuration) - [Command Line Usage](#command-line-usage) @@ -124,6 +125,98 @@ monitor.ping( ) ``` +## Error Tracking + +Cronitor captures exceptions and messages natively with no extra dependency and sends them from a background thread, so your application is never slowed down or interrupted by the network: requests time out after 5 seconds, failures are logged as warnings, and nothing is ever raised to your code. + +Configure `cronitor.ingest_key` using the ingest key from an Error App created in the Cronitor dashboard or via `cronitor.ErrorApp.create(...)`. `cronitor.ingest_url` is optional and defaults to `https://cronitor.link`. Envelopes are posted to `/e`: + +```python +import cronitor + +cronitor.ingest_key = '' +# cronitor.ingest_url = 'https://cronitor.link' # optional +cronitor.environment = 'production' # optional, or CRONITOR_ENVIRONMENT +cronitor.release = '2.4.1' # optional, or CRONITOR_RELEASE +``` + +#### Capturing exceptions and messages + +```python +try: + import_orders() +except Exception as e: + cronitor.capture_exception( + e, + monitor='import-orders', + level='error', + tags={'region': 'us-east-1'}, + extra={'batch': 42}, + fingerprint=['import-orders', 'timeout'], + ) + +cronitor.capture_message( + 'Disk 90% full', + level='warning', + tags={'host': 'worker-1'}, + extra={'mount': '/var'}, + fingerprint='disk-space-warning', +) + +# bound to a monitor and its environment +monitor = cronitor.Monitor('import-orders') +monitor.capture_exception() # inside an except block, defaults to the current exception +monitor.capture_message('Import finished with warnings', level='warning') +``` + +`capture_exception` and `capture_message` return the event id, or `None` if nothing was sent (for example when `cronitor.ingest_key` is not configured). Events include the exception chain (`raise ... from ...`), stack frames with five lines of source context, the hostname, release, and environment. Local variables are never sent. `fingerprint` accepts a string or a list of strings for custom grouping; omit it to use Cronitor's default grouping. + +Queued events are flushed automatically when the process exits. Call `cronitor.flush(timeout=2.0)` to flush earlier, for example at the end of a serverless handler. + +#### Exceptions inside `@cronitor.job` + +When a function decorated with `@cronitor.job` raises, the `fail` ping is sent first (best effort) and an unhandled exception event with the full stack trace follows, bound to the same monitor and run series. + +Auto-capture defaults to `True`. Turn it off globally or per job: + +```python +cronitor.capture_exceptions = False + +@cronitor.job('import-orders', capture_exceptions=False) +def import_orders(): + ... +``` + +Exceptions and messages captured while a `@cronitor.job` runs are bound to that monitor and run automatically via a `ContextVar`. Threads started inside a job do not inherit this binding, so pass `monitor=` and `series=` explicitly to captures made from worker threads (`cronitor.capture.current_job()` returns the active binding). + +#### Managing Error Apps and Error Groups + +Use `cronitor.ErrorApp` and `cronitor.ErrorGroup` with your REST API key (`cronitor.api_key`): + +```python +import cronitor + +cronitor.api_key = 'apiKey123' + +# Create and manage Error Apps +app = cronitor.ErrorApp.create(name='Billing API') +print(app.key, app.ingest_key, app.ingest_url) + +apps = cronitor.ErrorApp.list(page=1, pageSize=50) +app.update(name='Payments API') +app.rotate_key() # refreshes app.ingest_key; the old key stops working immediately +app.delete() + +# Query and triage Error Groups +groups = cronitor.ErrorGroup.list(app='app_0123456789abcdef', status='open', env='production') +group = cronitor.ErrorGroup('err_0123456789abcdef') +print(group.data.title) +group.update(status='resolved', env='production') + +events = group.events(env='production', limit=25) +event = group.event(events['data'][0]['event_id']) +``` + ## Configuring Monitors ### YAML Configuration File @@ -155,7 +248,7 @@ cronitor.timeout = 30 cronitor.apply_config() ``` -The `cronitor.yaml` file includes three top level keys `jobs`, `checks`, `heartbeats`. You can configure monitors under each key by defining [monitors](https://cronitor.io/docs/monitor-api#attributes). +The `cronitor.yaml` file supports four top level keys: `jobs`, `checks`, `heartbeats`, and `errors`. You can configure monitors under each key by defining [monitors](https://cronitor.io/docs/monitor-api#attributes). ```yaml jobs: @@ -197,6 +290,17 @@ heartbeats: alerts: ['deploys-slack'] events: true # send alert when the event occurs +errors: + billing-error-spikes: + trigger: spike + apps: + - app_0123456789abcdef + threshold: 25 + window: 5m + per: fingerprint + notify: + - devops-alert-pagerduty + ``` #### Async Uploads If you are working with large YAML files (300+ monitors), you may hit timeouts when trying to sync monitors in a single http request. This workload to be processed asynchronously by adding the key `async: true` to the config file. The request will immediately return a `batch_key`. If a `webhook_url` parameter is included, Cronitor will POST to that URL with the results of the background processing and will include the `batch_key` matching the one returned in the initial response. @@ -229,6 +333,13 @@ monitors = cronitor.Monitor.put([ 'response.code = 200', 'response.time < 600ms', ] + }, + { + 'type': 'errors', + 'key': 'new-billing-errors', + 'trigger': 'new', + 'apps': ['app_0123456789abcdef'], + 'notify': ['devops-alerts-slack'] } ]) ``` @@ -297,7 +408,14 @@ monitor.delete() # destroy the monitor ## Package Configuration -The package needs to be configured with your account's `API key`, which is available on the [account settings](https://cronitor.io/settings) page. You can also optionally specify an `api_version` and an `environment`. If not provided, your account default is used. These can also be supplied using the environment variables `CRONITOR_API_KEY`, `CRONITOR_API_VERSION`, `CRONITOR_ENVIRONMENT`. +The package needs to be configured with your account's `API key` (for pings and the REST API), which is available on the [account settings](https://cronitor.io/settings) page. You can also optionally specify an `api_version` and an `environment`. If not provided, your account default is used. These can also be supplied using the environment variables `CRONITOR_API_KEY`, `CRONITOR_API_VERSION`, `CRONITOR_ENVIRONMENT`. + +Additional settings: + +- `cronitor.ingest_key`: Error App ingest key used to capture exceptions and messages. +- `cronitor.release` (`CRONITOR_RELEASE`): Release string attached to captured events. +- `cronitor.ingest_url` (`CRONITOR_INGEST_URL`): Host for telemetry pings and error envelopes (default `https://cronitor.link`), e.g. `http://localhost:9100` in development. Envelopes are posted to `/e` on this host. +- `cronitor.capture_exceptions`: Module default for `@cronitor.job` auto-capture (default `True`). ```python import cronitor @@ -306,6 +424,8 @@ import cronitor cronitor.api_key = 'apiKey123' cronitor.api_version = '2020-10-01' cronitor.environment = 'cluster_1_prod' +cronitor.ingest_key = '' +cronitor.release = '2.4.1' ``` ## Command Line Usage diff --git a/cronitor/__init__.py b/cronitor/__init__.py index e48dceb..003d04f 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -10,6 +10,10 @@ import threading from .monitor import Monitor, YAML +from .errors import ErrorApp, ErrorGroup +from . import capture, ingest +from .ingest import flush +from .capture import capture_exception, capture_message logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) @@ -23,6 +27,12 @@ if timeout is not None: timeout = int(timeout) +dsn = os.getenv('CRONITOR_DSN', None) +ingest_key = None +ingest_url = os.getenv('CRONITOR_INGEST_URL') or ingest.DEFAULT_INGEST_URL +release = os.getenv('CRONITOR_RELEASE', None) +capture_exceptions = True + celerybeat_only = False # monitor attributes can be synced at process startup @@ -36,6 +46,12 @@ class MonitorNotFound(Exception): pass +class ErrorAppNotFound(Exception): + pass + +class ErrorGroupNotFound(Exception): + pass + class ConfigValidationError(Exception): pass @@ -54,8 +70,16 @@ class State(object): COMPLETE = 'complete' FAIL = 'fail' -# include_output is deprecated in favor of log_output and can be removed in 5.0 release -def job(key, env=None, log_output=True, include_output=True, attributes=None): +def _safe_ping(monitor, **params): + """Pings are best effort: a telemetry outage must never stop or fail the job.""" + try: + return monitor.ping(**params) + except Exception as e: + logger.warning('Cronitor could not send the %s ping for %s: %s', params.get('state'), monitor.key, e) + return None + + +def job(key, env=None, log_output=True, include_output=True, attributes=None, capture_exceptions=None): if type(attributes) is dict: attributes['key'] = key @@ -68,17 +92,25 @@ def wrapped(*args, **kwargs): monitor = Monitor(key, env=env) # use start as the series param to match run/fail/complete correctly - monitor.ping(state=State.RUN, series=start) + _safe_ping(monitor, state=State.RUN, series=start) + job_env = env or this.environment + token = capture.bind_job(key, start, job_env) try: out = func(*args, **kwargs) except Exception as e: duration = datetime.now().timestamp() - start - monitor.ping(state=State.FAIL, message=str(e), metrics={'duration': duration}, series=start) + _safe_ping(monitor, state=State.FAIL, message=str(e), metrics={'duration': duration}, series=start) + should_capture = this.capture_exceptions if capture_exceptions is None else capture_exceptions + if should_capture: + capture._capture_exception(e, monitor=key, series=start, env=job_env, + mechanism='cronitor.job', handled=False) raise e + finally: + capture.unbind_job(token) duration = datetime.now().timestamp() - start message = str(out) if all([log_output, include_output]) else None - monitor.ping(state=State.COMPLETE, message=message, metrics={'duration': duration}, series=start) + _safe_ping(monitor, state=State.COMPLETE, message=message, metrics={'duration': duration}, series=start) return out return wrapped @@ -102,7 +134,8 @@ def apply_config(rollback=False): job_count = len(monitors.get('jobs', [])) check_count = len(monitors.get('checks', [])) heartbeat_count = len(monitors.get('heartbeats', [])) - total_count = sum([job_count, check_count, heartbeat_count]) + error_count = len(monitors.get('errors', [])) + total_count = sum([job_count, check_count, heartbeat_count, error_count]) logger.info('{} monitor{} {}'.format(total_count, 's' if total_count != 1 else '', 'validated.' if rollback else 'synced.',)) return True except (yaml.YAMLError, ConfigValidationError, APIValidationError, APIError, AuthenticationError) as e: diff --git a/cronitor/_version.py b/cronitor/_version.py new file mode 100644 index 0000000..8e85738 --- /dev/null +++ b/cronitor/_version.py @@ -0,0 +1 @@ +__version__ = '4.10.0' diff --git a/cronitor/capture.py b/cronitor/capture.py new file mode 100644 index 0000000..2e6ed17 --- /dev/null +++ b/cronitor/capture.py @@ -0,0 +1,334 @@ +"""Exception and message capture. + +Events are bound to a monitor and a run with the reserved tags +``cronitor.monitor`` and ``cronitor.series``. Inside ``@cronitor.job`` both are +filled in automatically. +""" +import contextvars +import linecache +import logging +import os +import socket +import sys +import sysconfig +import traceback +import uuid +from collections import namedtuple + +import cronitor +from . import ingest + +_log = logging.getLogger(__name__) + +MONITOR_TAG = 'cronitor.monitor' +SERIES_TAG = 'cronitor.series' + +MAX_VALUE_LENGTH = 4000 +MAX_MESSAGE_LENGTH = 4000 +MAX_TAGS = 50 +MAX_TAG_KEY_LENGTH = 64 +MAX_TAG_VALUE_LENGTH = 400 +MAX_CHAINED_EXCEPTIONS = 10 +MAX_FRAMES = 100 +MAX_LINE_LENGTH = 1000 +CONTEXT_LINES = 5 + +EVENT_LEVELS = { + 'fatal': 'fatal', 'critical': 'fatal', 'error': 'error', 'warning': 'warning', + 'warn': 'warning', 'info': 'info', 'debug': 'debug', +} + +JobContext = namedtuple('JobContext', ['monitor', 'series', 'env']) +_current_job = contextvars.ContextVar('cronitor_job', default=None) + + +def current_job(): + """The (monitor, series, env) of the enclosing ``@cronitor.job``, or None.""" + return _current_job.get() + + +def bind_job(monitor, series, env): + """Bind captures in this context to a run. Returns a token for ``unbind_job``.""" + return _current_job.set(JobContext(monitor, series, env)) + + +def unbind_job(token): + _current_job.reset(token) + + +# public API + +def capture_exception(exc=None, *, monitor=None, series=None, level='error', + tags=None, extra=None, fingerprint=None): + """Send an exception event. ``exc`` defaults to the exception being handled. + + Returns the event id, or None when nothing was sent. + """ + return _capture_exception(exc, monitor=monitor, series=series, level=level, + tags=tags, extra=extra, fingerprint=fingerprint) + + +def capture_message(message, level='info', *, monitor=None, series=None, + tags=None, extra=None, fingerprint=None): + """Send a message event. Returns the event id, or None when nothing was sent.""" + return _capture_message(message, level=level, monitor=monitor, series=series, + tags=tags, extra=extra, fingerprint=fingerprint) + + +# events + +def _capture_exception(exc, monitor=None, series=None, level='error', tags=None, extra=None, + fingerprint=None, env=None, mechanism='generic', handled=True): + try: + exc_info = _exc_info(exc) + if exc_info is None: + return None + event = _base_event(level, monitor, series, tags, extra, fingerprint, env) + event['exception'] = {'values': _exception_values(exc_info, mechanism, handled)} + return _submit_event(event) + except Exception as e: + _log.warning('Cronitor could not capture an exception: %s', e) + return None + + +def _capture_message(message, level='info', monitor=None, series=None, tags=None, extra=None, + fingerprint=None, env=None): + try: + event = _base_event(level, monitor, series, tags, extra, fingerprint, env) + event['message'] = {'formatted': _truncate(_safe_str(message), MAX_MESSAGE_LENGTH)} + return _submit_event(event) + except Exception as e: + _log.warning('Cronitor could not capture a message: %s', e) + return None + + +def _submit_event(event): + if ingest.submit_event(event): + return event['event_id'] + return None + + +def _exc_info(exc): + if exc is None: + exc_info = sys.exc_info() + elif isinstance(exc, BaseException): + exc_info = (type(exc), exc, exc.__traceback__) + elif isinstance(exc, tuple) and len(exc) == 3: + exc_info = exc + else: + _log.warning('Cronitor capture_exception() expects an exception, got %s', type(exc).__name__) + return None + if exc_info[0] is None or exc_info[1] is None: + return None + return exc_info + + +def _binding(monitor, series, env): + """Resolve monitor, series and env: explicit values first, then the enclosing job.""" + job = _current_job.get() + if job is not None and (monitor is None or monitor == job.monitor): + monitor = job.monitor + if series is None: + series = job.series + if env is None: + env = job.env + return monitor, series, env or cronitor.environment + + +def _base_event(level, monitor, series, tags, extra, fingerprint, env): + user_tags = dict(tags or {}) + if monitor is None: + monitor = user_tags.get(MONITOR_TAG) + if series is None: + series = user_tags.get(SERIES_TAG) + monitor, series, env = _binding(monitor, series, env) + + bound = {} + if monitor is not None: + bound[MONITOR_TAG] = monitor + if series is not None: + bound[SERIES_TAG] = series + event_tags = {} + for key, value in list(bound.items()) + list(user_tags.items()): + key = _truncate(_safe_str(key), MAX_TAG_KEY_LENGTH) + if key in event_tags or len(event_tags) >= MAX_TAGS: + continue + event_tags[key] = _truncate(_safe_str(value), MAX_TAG_VALUE_LENGTH) + + event = { + 'event_id': uuid.uuid4().hex, + 'timestamp': ingest.format_timestamp(), + 'platform': 'python', + 'level': EVENT_LEVELS.get(_safe_str(level).lower(), 'error'), + 'server_name': _hostname(), + 'tags': event_tags, + 'extra': dict(extra or {}), + 'sdk': ingest.sdk_info(), + } + if fingerprint is not None: + if isinstance(fingerprint, str): + event['fingerprint'] = [fingerprint] + else: + event['fingerprint'] = [_safe_str(part) for part in fingerprint] + if cronitor.release: + event['release'] = _safe_str(cronitor.release) + if env: + event['environment'] = _safe_str(env) + return event + + +def _walk_chain(exc_info): + """Yield (type, value, tb) newest first, following __cause__, then __context__.""" + exc_type, exc_value, tb = exc_info + seen = set() + while exc_type is not None and exc_value is not None and id(exc_value) not in seen: + yield exc_type, exc_value, tb + seen.add(id(exc_value)) + if exc_value.__cause__ is not None: + cause = exc_value.__cause__ + elif not exc_value.__suppress_context__: + cause = exc_value.__context__ + else: + cause = None + if cause is None: + break + exc_type, exc_value, tb = type(cause), cause, cause.__traceback__ + + +def _exception_values(exc_info, mechanism, handled): + chain = [] + for link in _walk_chain(exc_info): + chain.append(link) + if len(chain) >= MAX_CHAINED_EXCEPTIONS: + break + values = [] + for exc_type, exc_value, tb in reversed(chain): + values.append({ + 'type': getattr(exc_type, '__name__', _safe_str(exc_type)), + 'value': _truncate(_safe_str(exc_value), MAX_VALUE_LENGTH), + 'module': _type_module(exc_type), + 'mechanism': {'type': mechanism, 'handled': handled}, + 'stacktrace': {'frames': _frames(tb)}, + }) + return values + + +def _type_module(exc_type): + module = getattr(exc_type, '__module__', None) + if module in ('builtins', '__builtin__', 'exceptions'): + return None + return module + + +def _frames(tb): + """Frames oldest first, the crash site last. Very deep stacks keep both ends.""" + entries = list(traceback.walk_tb(tb)) + if len(entries) > MAX_FRAMES: + half = MAX_FRAMES // 2 + entries = entries[:half] + entries[-half:] + return [_frame(frame, lineno) for frame, lineno in entries] + + +def _frame(frame, lineno): + code = frame.f_code + path = code.co_filename or '' + module = frame.f_globals.get('__name__') + abs_path = path if path.startswith('<') else os.path.abspath(path) + pre_context, context_line, post_context = _source_context(path, lineno, frame.f_globals) + return { + 'filename': _filename_for_module(module, abs_path), + 'abs_path': abs_path, + 'function': code.co_name, + 'module': module, + 'lineno': lineno, + 'context_line': context_line, + 'pre_context': pre_context, + 'post_context': post_context, + 'in_app': _in_app(abs_path), + } + + +def _source_context(path, lineno, module_globals): + try: + lines = linecache.getlines(path, module_globals) + except Exception: + lines = [] + if not lines or not lineno or lineno > len(lines): + return [], None, [] + index = lineno - 1 + clean = [_truncate(line.rstrip('\r\n'), MAX_LINE_LENGTH) for line in + lines[max(0, index - CONTEXT_LINES):index + CONTEXT_LINES + 1]] + offset = index - max(0, index - CONTEXT_LINES) + return clean[:offset], clean[offset], clean[offset + 1:] + + +def _filename_for_module(module, abs_path): + """A path relative to the top-level package, like Sentry, e.g. myapp/jobs/nightly.py.""" + if not module or abs_path.startswith('<'): + return abs_path + try: + if abs_path.endswith('.pyc'): + abs_path = abs_path[:-1] + base_module = module.split('.', 1)[0] + if base_module == module: + return os.path.basename(abs_path) + base_path = getattr(sys.modules.get(base_module), '__file__', None) + if not base_path: + return abs_path + return abs_path.split(base_path.rsplit(os.sep, 2)[0], 1)[-1].lstrip(os.sep) + except Exception: + return abs_path + + +_stdlib_prefixes = None + + +def _library_prefixes(): + global _stdlib_prefixes + if _stdlib_prefixes is None: + prefixes = set() + paths = sysconfig.get_paths() + for name in ('stdlib', 'platstdlib'): + path = paths.get(name) + if path: + for candidate in (path, os.path.realpath(path)): + prefixes.add(candidate.rstrip(os.sep) + os.sep) + _stdlib_prefixes = tuple(prefixes) + return _stdlib_prefixes + + +def _in_app(abs_path): + if abs_path.startswith('<'): + return not abs_path.startswith('' % type(value).__name__ diff --git a/cronitor/errors.py b/cronitor/errors.py new file mode 100644 index 0000000..996fc72 --- /dev/null +++ b/cronitor/errors.py @@ -0,0 +1,314 @@ +import json + +import cronitor +from .monitor import Struct, retry_session + +API_BASE_URL = 'https://cronitor.io' + + +def _require_api_key(api_key): + key = api_key or cronitor.api_key + if not key: + raise cronitor.AuthenticationError('No api_key detected. Set cronitor.api_key or pass api_key.') + return key + + +def _headers(api_version=None, json_body=False): + headers = {'User-Agent': 'cronitor-python'} + if json_body: + headers['Content-Type'] = 'application/json' + version = api_version or cronitor.api_version + if version: + headers['Cronitor-Version'] = version + return headers + + +def _raise_for_error(resp, not_found_exc=None, not_found_msg=None): + if 200 <= resp.status_code < 300: + return + if resp.status_code in (401, 403): + raise cronitor.AuthenticationError(resp.text) + if resp.status_code in (400, 422): + raise cronitor.APIValidationError(resp.text) + if resp.status_code == 404 and not_found_exc is not None: + raise not_found_exc(not_found_msg) + raise cronitor.APIError('Unexpected error (%s): %s' % (resp.status_code, resp.text)) + + +def _extract_list(body, keys): + if isinstance(body, list): + return body + if isinstance(body, dict): + for key in keys: + if key in body: + return body[key] + return [] + + +class ErrorApp(object): + _req = retry_session(retries=3) + + @classmethod + def _api_url(cls, key=None): + if not key: + return '{}/api/error-apps'.format(API_BASE_URL) + return '{}/api/error-apps/{}'.format(API_BASE_URL, key) + + @classmethod + def create(cls, name, api_key=None, **kwargs): + key = _require_api_key(api_key) + timeout = cronitor.timeout or 10 + payload = dict(kwargs, name=name) + resp = cls._req.post( + cls._api_url(), + auth=(key, ''), + data=json.dumps(payload), + headers=_headers(json_body=True), + timeout=timeout, + ) + _raise_for_error(resp) + data = resp.json() + app = cls(data['key'], api_key=api_key) + app.data = data + return app + + @classmethod + def list(cls, page=1, pageSize=50, auto_paginate=False, api_key=None): + apps = [] + current_page = page + while True: + result = cls._fetch_page(current_page, pageSize, api_key=api_key) + apps.extend(result) + if not auto_paginate or len(result) < pageSize: + break + current_page += 1 + return apps + + @classmethod + def _fetch_page(cls, page, pageSize, api_key=None): + key = _require_api_key(api_key) + timeout = cronitor.timeout or 10 + resp = cls._req.get( + cls._api_url(), + auth=(key, ''), + params={'page': page, 'pageSize': pageSize}, + headers=_headers(), + timeout=timeout, + ) + _raise_for_error(resp) + items = _extract_list(resp.json(), ('error_apps', 'apps', 'data')) + apps = [] + for item in items: + app = cls(item['key'], api_key=api_key) + app.data = item + apps.append(app) + return apps + + def __init__(self, key, api_key=None): + self.key = key + self.api_key = api_key or cronitor.api_key + self._data = None + + @property + def data(self): + if self._data and type(self._data) is not Struct: + self._data = Struct(**self._data) + elif not self._data: + self._data = Struct(**self._fetch()) + return self._data + + @data.setter + def data(self, data): + self._data = Struct(**data) + + def __getattr__(self, name): + if name.startswith('_'): + raise AttributeError(name) + return getattr(self.data, name) + + def _fetch(self, api_key=None): + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + resp = self._req.get( + self._api_url(self.key), + auth=(key, ''), + headers=_headers(json_body=True), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorAppNotFound, "ErrorApp '%s' not found" % self.key) + return resp.json() + + def update(self, name=None, api_key=None, **kwargs): + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + payload = dict(kwargs) + if name is not None: + payload['name'] = name + resp = self._req.patch( + self._api_url(self.key), + auth=(key, ''), + data=json.dumps(payload), + headers=_headers(json_body=True), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorAppNotFound, "ErrorApp '%s' not found" % self.key) + self.data = resp.json() + return self + + def delete(self, api_key=None): + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + resp = self._req.delete( + self._api_url(self.key), + auth=(key, ''), + headers=_headers(), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorAppNotFound, "ErrorApp '%s' not found" % self.key) + return True + + def rotate_key(self, api_key=None): + """Rotate the app's ingest key, refresh this instance, and return ``self``.""" + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + resp = self._req.post( + '{}/rotate-key'.format(self._api_url(self.key)), + auth=(key, ''), + headers=_headers(json_body=True), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorAppNotFound, "ErrorApp '%s' not found" % self.key) + self.data = resp.json() + return self + + +class ErrorGroup(object): + _req = retry_session(retries=3) + + @classmethod + def _api_url(cls, key=None): + if not key: + return '{}/api/errors'.format(API_BASE_URL) + return '{}/api/errors/{}'.format(API_BASE_URL, key) + + @classmethod + def list(cls, app=None, env=None, status=None, level=None, start=None, end=None, + q=None, orderBy=None, page=1, pageSize=50, auto_paginate=False, api_key=None): + filters = {} + for name, value in ( + ('app', app), ('env', env), ('status', status), ('level', level), + ('start', start), ('end', end), ('q', q), ('orderBy', orderBy), + ): + if value is not None: + filters[name] = value + + groups = [] + current_page = page + while True: + result = cls._fetch_page(current_page, pageSize, api_key=api_key, **filters) + groups.extend(result) + if not auto_paginate or len(result) < pageSize: + break + current_page += 1 + return groups + + @classmethod + def _fetch_page(cls, page, pageSize, api_key=None, **filters): + key = _require_api_key(api_key) + timeout = cronitor.timeout or 10 + params = dict(filters, page=page, pageSize=pageSize) + resp = cls._req.get( + cls._api_url(), + auth=(key, ''), + params=params, + headers=_headers(), + timeout=timeout, + ) + _raise_for_error(resp) + items = _extract_list(resp.json(), ('errors', 'data', 'groups')) + groups = [] + for item in items: + group = cls(item['key'], api_key=api_key) + group.data = item + groups.append(group) + return groups + + def __init__(self, key, api_key=None): + self.key = key + self.api_key = api_key or cronitor.api_key + self._data = None + + @property + def data(self): + if self._data and type(self._data) is not Struct: + self._data = Struct(**self._data) + elif not self._data: + self._data = Struct(**self._fetch()) + return self._data + + @data.setter + def data(self, data): + self._data = Struct(**data) + + def __getattr__(self, name): + if name.startswith('_'): + raise AttributeError(name) + return getattr(self.data, name) + + def _fetch(self, api_key=None): + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + resp = self._req.get( + self._api_url(self.key), + auth=(key, ''), + headers=_headers(json_body=True), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorGroupNotFound, "ErrorGroup '%s' not found" % self.key) + return resp.json() + + def update(self, status, env=None, api_key=None): + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + payload = {'status': status} + if env is not None: + payload['env'] = env + resp = self._req.patch( + self._api_url(self.key), + auth=(key, ''), + data=json.dumps(payload), + headers=_headers(json_body=True), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorGroupNotFound, "ErrorGroup '%s' not found" % self.key) + self.data = resp.json() + return self + + def events(self, env=None, app=None, cursor=None, limit=50, api_key=None): + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + params = {'limit': limit} + for name, value in (('env', env), ('app', app), ('cursor', cursor)): + if value is not None: + params[name] = value + resp = self._req.get( + '{}/events'.format(self._api_url(self.key)), + auth=(key, ''), + params=params, + headers=_headers(), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorGroupNotFound, "ErrorGroup '%s' not found" % self.key) + return resp.json() + + def event(self, event_id, api_key=None): + key = _require_api_key(api_key or self.api_key) + timeout = cronitor.timeout or 10 + resp = self._req.get( + '{}/events/{}'.format(self._api_url(self.key), event_id), + auth=(key, ''), + headers=_headers(), + timeout=timeout, + ) + _raise_for_error(resp, cronitor.ErrorGroupNotFound, "Error event '%s' not found" % event_id) + return resp.json() diff --git a/cronitor/ingest.py b/cronitor/ingest.py new file mode 100644 index 0000000..431dbc2 --- /dev/null +++ b/cronitor/ingest.py @@ -0,0 +1,501 @@ +"""Envelope encoding and background transport for exception and message events. + +Payloads use the Sentry envelope format and are sent to the endpoint derived +from ``cronitor.ingest_key`` (or ``cronitor.dsn``) to ``{scheme}://{netloc}/e``. +Sending happens on one daemon thread with a bounded queue, so callers are never +blocked by the network and never see a transport error. +""" +import atexit +import gzip +import json +import logging +import math +import os +import queue +import threading +import time +from datetime import datetime, timezone +from urllib.parse import urlparse + +import cronitor +from ._version import __version__ + +logger = logging.getLogger(__name__) + +DEFAULT_INGEST_URL = 'https://cronitor.link' +SDK_NAME = 'cronitor-python' +SDK_VERSION = __version__ + +MAX_QUEUE_SIZE = 1000 +SEND_TIMEOUT = 5 +SEND_RETRIES = 1 +MAX_RETRY_AFTER = 60.0 +ATEXIT_FLUSH_TIMEOUT = 2.0 +# the server drops event items over 1 MB; oversized events are trimmed to this +MAX_EVENT_BYTES = 900 * 1024 +TRIMMED_FRAMES = 20 + +EVENT_CONTENT_TYPE = 'application/json' + +_start_lock = threading.Lock() + + +def _reset_after_fork(): + # a lock held by another thread at fork time stays locked forever in the child + global _start_lock + _start_lock = threading.Lock() + + +if hasattr(os, 'register_at_fork'): + os.register_at_fork(after_in_child=_reset_after_fork) + + +def base_url(): + """The scheme and host that telemetry pings are sent to, without a trailing slash.""" + return (cronitor.ingest_url or DEFAULT_INGEST_URL).rstrip('/') + + +def parse_dsn(dsn): + """Parse a Sentry-style DSN into ``(ingest_key, envelope_url, normalized_dsn)``. + + Returns None when ``dsn`` is empty or malformed. + """ + if not dsn or not isinstance(dsn, str): + return None + raw = dsn.strip() + if not raw: + return None + try: + parsed = urlparse(raw) + port = parsed.port + except ValueError: + return None + if parsed.scheme not in ('http', 'https') or not parsed.hostname or not parsed.username: + return None + host = '[{}]'.format(parsed.hostname) if ':' in parsed.hostname else parsed.hostname + netloc = '{}:{}'.format(host, port) if port is not None else host + path = parsed.path.strip('/') + if path: + parts = path.rsplit('/', 1) + if len(parts) == 2: + prefix, project_id = '/' + parts[0], parts[1] + else: + prefix, project_id = '', parts[0] + else: + prefix, project_id = '', '1' + url = '{}://{}{}/e'.format(parsed.scheme, netloc, prefix) + public_dsn = '{}://{}@{}{}/{}'.format(parsed.scheme, parsed.username, netloc, prefix, project_id) + return parsed.username, url, public_dsn + + + +def credentials_from_key(key, ingest_url=None): + """Build ``(ingest_key, envelope_url, internal_dsn)`` from an ingest key and host.""" + if not key or not isinstance(key, str): + return None + key = key.strip() + if not key: + return None + raw = ingest_url if ingest_url is not None else cronitor.ingest_url + raw = (raw or DEFAULT_INGEST_URL).strip() + if not raw: + raw = DEFAULT_INGEST_URL + if '://' not in raw: + raw = 'https://' + raw + try: + parsed = urlparse(raw) + port = parsed.port + except ValueError: + return None + if parsed.scheme not in ('http', 'https') or not parsed.hostname: + return None + host = '[{}]'.format(parsed.hostname) if ':' in parsed.hostname else parsed.hostname + netloc = '{}:{}'.format(host, port) if port is not None else host + path = parsed.path.strip('/') + prefix = '/' + path if path else '' + url = '{}://{}{}/e'.format(parsed.scheme, netloc, prefix) + public_dsn = '{}://{}@{}{}/1'.format(parsed.scheme, key, netloc, prefix) + return key, url, public_dsn + + +def sdk_info(): + return {'name': SDK_NAME, 'version': SDK_VERSION} + + +def auth_header(ingest_key): + return 'Sentry sentry_key={}, sentry_version=7, sentry_client={}/{}'.format(ingest_key, SDK_NAME, SDK_VERSION) + + +def request_headers(ingest_key): + return { + 'Content-Type': 'application/x-sentry-envelope', + 'Content-Encoding': 'gzip', + 'User-Agent': 'cronitor-python', + 'X-Sentry-Auth': auth_header(ingest_key), + } + + +def format_timestamp(value=None): + """RFC 3339 in UTC with microseconds and a Z suffix.""" + value = value or datetime.now(timezone.utc) + if value.tzinfo is not None: + value = value.astimezone(timezone.utc) + return value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') + + +def _json_default(value): + try: + return repr(value) + except Exception: + return '' % type(value).__name__ + + +def _json_safe(value, depth=0): + """Copy of value with NaN/Infinity as strings and nesting (and so cycles) cut at 10 levels.""" + if isinstance(value, float) and not math.isfinite(value): + return repr(value) + if isinstance(value, (dict, list, tuple)) and depth >= 10: + return _json_default(value) + if isinstance(value, dict): + return {k: _json_safe(v, depth + 1) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_json_safe(v, depth + 1) for v in value] + return value + + +def _dumps(obj, allow_nan): + return json.dumps(obj, default=_json_default, ensure_ascii=False, separators=(',', ':'), + skipkeys=True, allow_nan=allow_nan) + + +def json_bytes(obj): + """Strict JSON (no NaN or Infinity) as UTF-8. Values json cannot encode become their repr.""" + try: + text = _dumps(obj, allow_nan=False) + except ValueError: + # a non-finite float or a circular reference somewhere in user data + text = _dumps(_json_safe(obj), allow_nan=False) + # 'replace' turns lone surrogates (undecodable bytes in paths or messages) into '?' + return text.encode('utf-8', 'replace') + + +def serialize_envelope(headers, items): + """Build envelope bytes from a header dict and (item_header, payload_bytes) pairs. + + Every item header gets a ``length`` equal to the payload's byte length. + """ + parts = [json_bytes(headers), b'\n'] + for item_headers, payload in items: + item_headers = dict(item_headers, length=len(payload)) + parts.extend([json_bytes(item_headers), b'\n', payload, b'\n']) + return b''.join(parts) + + +def event_bytes(event): + """The event as JSON bytes, trimmed to at most MAX_EVENT_BYTES when possible. + + An oversized event loses, until it fits: every frame's source context, then + ``extra``, then all but the last 20 frames of each exception. + ``extra['_trimmed']`` says what was dropped. The caller's dict is not changed. + """ + payload = json_bytes(event) + if len(payload) <= MAX_EVENT_BYTES: + return payload + try: + event = dict(event) + dropped = [] + for note, trim in _EVENT_TRIMS: + if not trim(event): + continue + dropped.append(note) + extra = event.get('extra') + extra = dict(extra) if isinstance(extra, dict) else {} + extra['_trimmed'] = '%s: event over %d KB' % ('; '.join(dropped), MAX_EVENT_BYTES // 1024) + event['extra'] = extra + payload = json_bytes(event) + if len(payload) <= MAX_EVENT_BYTES: + break + except Exception as e: + logger.warning('Cronitor could not trim an oversized event: %s', e) + return payload + + +def _own_frames(event): + """Give event its own copies of the exception values and frames, and return the frame lists.""" + exception = event.get('exception') or {} + values, frame_lists = [], [] + for value in exception.get('values') or []: + stacktrace = value.get('stacktrace') or {} + if stacktrace.get('frames'): + frames = [dict(frame) for frame in stacktrace['frames']] + value = dict(value, stacktrace=dict(stacktrace, frames=frames)) + frame_lists.append(frames) + values.append(value) + if values: + event['exception'] = dict(exception, values=values) + return frame_lists + + +def _drop_source_context(event): + dropped = False + for frames in _own_frames(event): + for frame in frames: + for key in ('pre_context', 'post_context'): + if key in frame: + del frame[key] + dropped = True + return dropped + + +def _drop_extra(event): + extra = event.get('extra') + if not isinstance(extra, dict) or all(key == '_trimmed' for key in extra): + return False + event['extra'] = {} + return True + + +def _keep_last_frames(event): + cut = False + for frames in _own_frames(event): + if len(frames) > TRIMMED_FRAMES: + del frames[:-TRIMMED_FRAMES] + cut = True + return cut + + +_EVENT_TRIMS = ( + ('source context dropped', _drop_source_context), + ('extra dropped', _drop_extra), + ('frames cut to the last %d per exception' % TRIMMED_FRAMES, _keep_last_frames), +) + + +def event_envelope(payload, event_id, sent_at=None, dsn=None): + headers = {'event_id': event_id, 'sent_at': format_timestamp(sent_at), 'sdk': sdk_info()} + if dsn: + headers['dsn'] = dsn + item = {'type': 'event', 'content_type': EVENT_CONTENT_TYPE} + return serialize_envelope(headers, [(item, payload)]) + + +def _seconds(value): + try: + seconds = float(value) + except (TypeError, ValueError): + return None + return seconds if math.isfinite(seconds) else None + + +def _retry_after(response): + """Seconds to stop sending after a 429, at most MAX_RETRY_AFTER. + + As in Sentry's SDKs, X-Sentry-Rate-Limits wins over Retry-After; the first + field of its first entry is the retry-after in seconds. With neither, the maximum. + """ + headers = getattr(response, 'headers', None) or {} + delay = None + limits = headers.get('X-Sentry-Rate-Limits') + if limits: + delay = _seconds(limits.split(',')[0].split(':')[0]) + if delay is None: + delay = _seconds(headers.get('Retry-After')) + if delay is None: + delay = MAX_RETRY_AFTER + return max(0.0, min(delay, MAX_RETRY_AFTER)) + + +class Transport(object): + """Sends envelopes from a single daemon thread. + + ``send(url, data, headers, timeout)`` performs the HTTP request and returns a + response with ``status_code`` and ``headers``; it is injectable for tests. + ``dropped`` counts the items lost to a full queue or to a rate limit. + """ + + def __init__(self, send=None, maxsize=MAX_QUEUE_SIZE): + self._send = send or self._http_send + self._maxsize = maxsize + self._session = None + self._queue = None + self._thread = None + self._pid = None + self._rate_limited_until = 0.0 + self._reported_rate_limit = False + self._reported_missing_dsn = False + self._reported_invalid_dsn = False + self.dropped = 0 + + # caller side + + def submit_event(self, event, dsn=None): + """Queue one event dict. Returns False when it was not queued.""" + resolved = self._resolve_dsn(dsn) + if resolved is None: + return False + ingest_key, url, public_dsn = resolved + return self._put(('event', url, ingest_key, public_dsn, event['event_id'], event_bytes(event))) + + def flush(self, timeout=2.0): + """Wait up to ``timeout`` seconds for queued items to be sent.""" + if self._thread is None or self._pid != os.getpid() or not self._thread.is_alive(): + return True + deadline = time.monotonic() + timeout + done = threading.Event() + try: + self._queue.put(('flush', done), timeout=timeout) + except queue.Full: + return False + return done.wait(max(0.0, deadline - time.monotonic())) + + def _resolve_dsn(self, dsn): + if dsn is not None: + parsed = parse_dsn(dsn) + if parsed is None and not self._reported_invalid_dsn: + self._reported_invalid_dsn = True + logger.error('Invalid Cronitor DSN. Expected https://@cronitor.link/1.') + return parsed + if cronitor.ingest_key: + parsed = credentials_from_key(cronitor.ingest_key, cronitor.ingest_url) + if parsed is None and not self._reported_invalid_dsn: + self._reported_invalid_dsn = True + logger.error('Invalid cronitor.ingest_key or cronitor.ingest_url.') + return parsed + raw = cronitor.dsn + if not raw: + if not self._reported_missing_dsn: + self._reported_missing_dsn = True + logger.error('No ingest_key detected. Set cronitor.ingest_key to capture exceptions and messages.') + return None + parsed = parse_dsn(raw) + if parsed is None: + if not self._reported_invalid_dsn: + self._reported_invalid_dsn = True + logger.error('Invalid Cronitor DSN. Expected https://@cronitor.link/1.') + return None + return parsed + + def _put(self, item): + try: + self._ensure_worker() + self._queue.put_nowait(item) + return True + except queue.Full: + self.dropped += 1 + if self.dropped == 1 or self.dropped % 1000 == 0: + logger.warning('Cronitor ingest queue is full, %d item(s) dropped so far.', self.dropped) + return False + except Exception as e: + logger.warning('Cronitor could not queue an item: %s', e) + return False + + def _ensure_worker(self): + pid = os.getpid() + if self._pid == pid and self._thread is not None and self._thread.is_alive(): + return + with _start_lock: + if self._pid == pid and self._thread is not None and self._thread.is_alive(): + return + if self._pid != pid or self._queue is None: + # first use, or a forked child: items queued by the parent are not ours to send + self._queue = queue.Queue(maxsize=self._maxsize) + if self._pid != pid: + # nor is its keep-alive session: the sockets are shared with the parent, and a + # connection pool lock held by a parent thread at fork time is never released + self._session = None + self._rate_limited_until = 0.0 + thread = threading.Thread(target=self._run, args=(self._queue,), name='cronitor-ingest') + thread.daemon = True + thread.start() + self._thread = thread + self._pid = pid + _register_atexit() + + # worker side + + def _run(self, q): + while True: + item = q.get() + try: + kind = item[0] + if kind == 'event': + _, url, ingest_key, public_dsn, event_id, payload = item + self._deliver(url, ingest_key, event_envelope(payload, event_id, dsn=public_dsn)) + elif kind == 'flush': + item[1].set() + except Exception as e: + logger.warning('Cronitor could not send an envelope: %s', e) + finally: + q.task_done() + + def _deliver(self, url, ingest_key, body, count=1): + """Send one envelope holding ``count`` items, or drop it while rate limited.""" + left = self._rate_limited_until - time.monotonic() + if left > 0: + # dropped rather than waited out, so the items queued behind it are not + # delayed into the exit flush and lost there + self.dropped += count + if not self._reported_rate_limit: + self._reported_rate_limit = True + logger.warning('Cronitor is rate limited for %.0f more seconds; dropping envelopes until then.', left) + return + try: + response = self._send(url, gzip.compress(body, 6), request_headers(ingest_key), SEND_TIMEOUT) + except Exception as e: + logger.warning('Cronitor could not send an envelope to %s: %s', url, e) + return + status = getattr(response, 'status_code', None) + if not isinstance(status, int): + return + if status == 429: + delay = _retry_after(response) + self._rate_limited_until = time.monotonic() + delay + self._reported_rate_limit = False + logger.warning('Cronitor rate limited the envelope (HTTP 429); not sending for %.0f seconds.', delay) + elif status >= 400: + logger.warning('Cronitor rejected an envelope with HTTP %s.', status) + + def _http_send(self, url, data, headers, timeout): + if self._session is None: + from .monitor import retry_session + self._session = retry_session(retries=SEND_RETRIES) + return self._session.post(url, data=data, headers=headers, timeout=timeout) + + +_transport = Transport() +_atexit_registered = False + + +def get_transport(): + return _transport + + +def set_transport(transport): + """Replace the module transport (for tests or a custom ``send``). Returns the previous one.""" + global _transport + previous, _transport = _transport, transport + return previous + + +def submit_event(event, dsn=None): + return _transport.submit_event(event, dsn=dsn) + + +def flush(timeout=2.0): + """Block up to ``timeout`` seconds while queued events are sent.""" + try: + return _transport.flush(timeout) + except Exception as e: + logger.warning('Cronitor flush failed: %s', e) + return False + + +def _flush_at_exit(): + flush(ATEXIT_FLUSH_TIMEOUT) + + +def _register_atexit(): + global _atexit_registered + if not _atexit_registered: + _atexit_registered = True + atexit.register(_flush_at_exit) diff --git a/cronitor/monitor.py b/cronitor/monitor.py index 657c79d..ce55916 100644 --- a/cronitor/monitor.py +++ b/cronitor/monitor.py @@ -8,6 +8,7 @@ import cronitor +from .ingest import base_url from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter @@ -168,6 +169,18 @@ def ping(self, **params): def ok(self): self.ping(state=cronitor.State.OK) + def capture_exception(self, exc=None, *, series=None, level='error', tags=None, extra=None, fingerprint=None): + """Send an exception event bound to this monitor and its environment.""" + from .capture import _capture_exception + return _capture_exception(exc, monitor=self.key, series=series, level=level, tags=tags, + extra=extra, fingerprint=fingerprint, env=self.env) + + def capture_message(self, message, level='info', *, series=None, tags=None, extra=None, fingerprint=None): + """Send a message event bound to this monitor and its environment.""" + from .capture import _capture_message + return _capture_message(message, level=level, monitor=self.key, series=series, tags=tags, + extra=extra, fingerprint=fingerprint, env=self.env) + def pause(self, hours): if not self.api_key: logger.error('No API key detected. Set cronitor.api_key or initialize Monitor with kwarg api_key.') @@ -207,7 +220,7 @@ def _clean_params(self, params): } def _ping_api_url(self): - return "https://cronitor.link/p/{}/{}".format(self.api_key, self.key) + return "{}/p/{}/{}".format(base_url(), self.api_key, self.key) @classmethod def list(cls, keys=None, page=1, pageSize=100, auto_paginate=False, **filters): diff --git a/cronitor/tests/envelope_parser.py b/cronitor/tests/envelope_parser.py new file mode 100644 index 0000000..69b4086 --- /dev/null +++ b/cronitor/tests/envelope_parser.py @@ -0,0 +1,102 @@ +"""Test helpers: a small reference parser for envelope bytes and a fake send function. + +The parser is intentionally independent of cronitor.ingest so tests check the +bytes on the wire, not the code that produced them. +""" +import gzip +import json +import threading +import time + + +def _reject_constant(name): + raise ValueError('not valid JSON: %s' % name) + + +def parse_envelope(body, compressed=True): + """Parse envelope bytes into (header, [(item_header, payload), ...]). + + Layout: one JSON header line, then for each item a JSON item header line, + exactly `length` payload bytes, and a newline. + """ + raw = gzip.decompress(body) if compressed else body + header_line, sep, rest = raw.partition(b'\n') + if not sep: + raise AssertionError('envelope header is not newline terminated') + header = json.loads(header_line.decode('utf-8')) + items = [] + while rest: + item_header_line, sep, rest = rest.partition(b'\n') + if not sep: + raise AssertionError('item header is not newline terminated') + item_header = json.loads(item_header_line.decode('utf-8')) + if 'length' not in item_header: + raise AssertionError('item header has no length: %r' % item_header) + length = item_header['length'] + if len(rest) < length: + raise AssertionError('payload shorter than length %d' % length) + payload, rest = rest[:length], rest[length:] + if rest[:1] != b'\n': + raise AssertionError('payload is not followed by a newline') + rest = rest[1:] + items.append((item_header, json.loads(payload.decode('utf-8'), parse_constant=_reject_constant))) + return header, items + + +class FakeResponse(object): + def __init__(self, status_code=200, headers=None): + self.status_code = status_code + self.headers = headers or {} + + +class SentRequest(object): + def __init__(self, url, data, headers, timeout): + self.url = url + self.data = data + self.headers = headers + self.timeout = timeout + + @property + def envelope(self): + return parse_envelope(self.data) + + +class RecordingSend(object): + """Injectable send(url, data, headers, timeout) that records every call.""" + + def __init__(self, responses=None, raises=None): + self.calls = [] + self.responses = list(responses or []) + self.raises = raises + self._lock = threading.Lock() + + def __call__(self, url, data, headers, timeout): + with self._lock: + self.calls.append(SentRequest(url, data, headers, timeout)) + if self.raises is not None: + raise self.raises + if self.responses: + return self.responses.pop(0) + return FakeResponse(200) + + def envelopes(self): + return [c.envelope for c in self.calls] + + def items(self, item_type=None): + out = [] + for _, items in self.envelopes(): + for item_header, payload in items: + if item_type is None or item_header['type'] == item_type: + out.append((item_header, payload)) + return out + + def events(self): + return [payload for _, payload in self.items('event')] + + def wait_for(self, count, timeout=2.0): + deadline = time.time() + timeout + while time.time() < deadline: + if len(self.calls) >= count: + return True + time.sleep(0.01) + return len(self.calls) >= count diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py new file mode 100644 index 0000000..07d9ef5 --- /dev/null +++ b/cronitor/tests/test_capture.py @@ -0,0 +1,522 @@ +import json +import logging +import os +import re +import socket +import unittest + +import requests +from unittest.mock import patch + +import cronitor +from cronitor import ingest +from cronitor.tests.envelope_parser import RecordingSend + +FAKE_INGEST_KEY = 'capture_ingest_key_1234' +FAKE_DSN = 'https://%s@cronitor.link/1' % FAKE_INGEST_KEY +HEX32 = re.compile(r'^[0-9a-f]{32}$') +RFC3339_UTC = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$') +FRAME_KEYS = {'filename', 'abs_path', 'function', 'module', 'lineno', + 'context_line', 'pre_context', 'post_context', 'in_app'} + + +def _inner(): + raise ValueError('inner boom') + + +def _outer(): + try: + _inner() + except ValueError as e: + raise RuntimeError('outer boom') from e + + +class CaptureTestCase(unittest.TestCase): + """Installs a recording transport and known settings for each test.""" + + def setUp(self): + self._saved = {name: getattr(cronitor, name) for name in + ('api_key', 'dsn', 'ingest_url', 'environment', 'release', 'capture_exceptions')} + cronitor.api_key = 'rest-api-key' + cronitor.dsn = FAKE_DSN + cronitor.ingest_url = ingest.DEFAULT_INGEST_URL + cronitor.environment = None + cronitor.release = None + cronitor.capture_exceptions = True + self.send = RecordingSend() + self._previous_transport = ingest.set_transport(ingest.Transport(send=self.send)) + + def tearDown(self): + ingest.set_transport(self._previous_transport) + for name, value in self._saved.items(): + setattr(cronitor, name, value) + + def flushed_events(self): + self.assertTrue(cronitor.flush(2.0)) + return self.send.events() + + def only_event(self): + events = self.flushed_events() + self.assertEqual(len(events), 1, events) + return events[0] + + +class PackageLoggerTests(unittest.TestCase): + + def test_cronitor_logger_is_stdlib_logger(self): + self.assertIsInstance(cronitor.logger, logging.Logger) + self.assertIs(cronitor.logger, logging.getLogger('cronitor')) + self.assertFalse(hasattr(cronitor, 'LogHandler')) + self.assertFalse(hasattr(cronitor, 'service')) + + +class CaptureExceptionTests(CaptureTestCase): + + def test_chained_cause_is_two_values_oldest_first(self): + try: + _outer() + except RuntimeError as e: + event_id = cronitor.capture_exception(e) + + self.assertRegex(event_id, HEX32) + self.assertTrue(cronitor.flush(2.0)) + header, items = self.send.envelopes()[0] + self.assertEqual(header['event_id'], event_id) + self.assertEqual(header['dsn'], FAKE_DSN) + self.assertEqual([h['type'] for h, _ in items], ['event']) + event = items[0][1] + self.assertEqual(event['event_id'], event_id) + + values = event['exception']['values'] + self.assertEqual([v['type'] for v in values], ['ValueError', 'RuntimeError']) + self.assertEqual([v['value'] for v in values], ['inner boom', 'outer boom']) + self.assertEqual([v['module'] for v in values], [None, None]) + for value in values: + self.assertEqual(value['mechanism'], {'type': 'generic', 'handled': True}) + + cause_frames = values[0]['stacktrace']['frames'] + self.assertEqual([f['function'] for f in cause_frames], ['_outer', '_inner']) + self.assertEqual(cause_frames[-1]['context_line'].strip(), "raise ValueError('inner boom')") + self.assertEqual(cause_frames[-1]['pre_context'][-1].strip(), 'def _inner():') + + frames = values[1]['stacktrace']['frames'] + self.assertEqual([f['function'] for f in frames], + ['test_chained_cause_is_two_values_oldest_first', '_outer']) + self.assertEqual(frames[-1]['context_line'].strip(), "raise RuntimeError('outer boom') from e") + + here = os.path.abspath(__file__) + for frame in cause_frames + frames: + self.assertEqual(set(frame), FRAME_KEYS) + self.assertEqual(frame['abs_path'], here) + self.assertEqual(frame['filename'], os.path.join('cronitor', 'tests', 'test_capture.py')) + self.assertEqual(frame['module'], __name__) + self.assertIsInstance(frame['lineno'], int) + self.assertTrue(frame['in_app']) + self.assertEqual(len(frame['pre_context']), 5) + self.assertLessEqual(len(frame['post_context']), 5) + self.assertNotIn('vars', frame) + + def test_implicit_context_is_chained(self): + try: + try: + raise KeyError('first') + except KeyError: + raise TypeError('second') + except TypeError as e: + cronitor.capture_exception(e) + values = self.only_event()['exception']['values'] + self.assertEqual([v['type'] for v in values], ['KeyError', 'TypeError']) + + def test_raise_from_none_suppresses_context(self): + try: + try: + raise KeyError('first') + except KeyError: + raise TypeError('second') from None + except TypeError as e: + cronitor.capture_exception(e) + values = self.only_event()['exception']['values'] + self.assertEqual([v['type'] for v in values], ['TypeError']) + + def test_custom_exception_module(self): + try: + raise cronitor.APIError('nope') + except cronitor.APIError as e: + cronitor.capture_exception(e) + value = self.only_event()['exception']['values'][0] + self.assertEqual(value['type'], 'APIError') + self.assertEqual(value['module'], 'cronitor') + + def test_library_frames_are_not_in_app(self): + try: + json.loads('{not json') + except ValueError as e: + cronitor.capture_exception(e) + frames = self.only_event()['exception']['values'][-1]['stacktrace']['frames'] + self.assertTrue(frames[0]['in_app']) + self.assertTrue(frames[-1]['abs_path'].endswith(os.path.join('json', 'decoder.py'))) + self.assertFalse(frames[-1]['in_app']) + self.assertEqual(frames[-1]['module'], 'json.decoder') + + def test_in_app_rules(self): + from cronitor.capture import _in_app + self.assertFalse(_in_app('/venv/lib/python3.8/site-packages/requests/api.py')) + self.assertFalse(_in_app('/usr/lib/python3/dist-packages/yaml/__init__.py')) + self.assertFalse(_in_app(json.__file__)) + self.assertFalse(_in_app('')) + self.assertTrue(_in_app('/srv/app/jobs/nightly.py')) + + def test_defaults_to_current_exception(self): + try: + raise LookupError('current') + except LookupError: + event_id = cronitor.capture_exception() + event = self.only_event() + self.assertEqual(event['event_id'], event_id) + self.assertEqual(event['exception']['values'][0]['type'], 'LookupError') + + def test_no_current_exception_sends_nothing(self): + self.assertIsNone(cronitor.capture_exception()) + self.assertEqual(self.flushed_events(), []) + + def test_event_fields(self): + cronitor.environment = 'production' + cronitor.release = '1.2.3' + try: + raise ValueError('x') + except ValueError as e: + cronitor.capture_exception(e, level='fatal') + event = self.only_event() + self.assertRegex(event['timestamp'], RFC3339_UTC) + self.assertEqual(event['platform'], 'python') + self.assertEqual(event['level'], 'fatal') + self.assertEqual(event['server_name'], socket.gethostname()) + self.assertEqual(event['environment'], 'production') + self.assertEqual(event['release'], '1.2.3') + self.assertEqual(event['sdk'], {'name': 'cronitor-python', 'version': ingest.SDK_VERSION}) + self.assertEqual(event['tags'], {}) + self.assertEqual(event['extra'], {}) + self.assertNotIn('fingerprint', event) + + def test_fingerprint_string_and_list(self): + try: + raise ValueError('a') + except ValueError as e: + cronitor.capture_exception(e, fingerprint='custom-group') + try: + raise ValueError('b') + except ValueError as e: + cronitor.capture_exception(e, fingerprint=['billing', 'timeout', 504]) + first, second = self.flushed_events() + self.assertEqual(first['fingerprint'], ['custom-group']) + self.assertEqual(second['fingerprint'], ['billing', 'timeout', '504']) + + def test_optional_fields_omitted_when_unset(self): + cronitor.capture_message('hello') + event = self.only_event() + self.assertNotIn('environment', event) + self.assertNotIn('release', event) + self.assertNotIn('fingerprint', event) + + def test_value_is_truncated(self): + try: + raise ValueError('v' * 5000) + except ValueError as e: + cronitor.capture_exception(e) + self.assertEqual(len(self.only_event()['exception']['values'][0]['value']), 4000) + + def test_deep_recursion_keeps_both_ends(self): + def recurse(n): + if n == 0: + raise ValueError('bottom') + return recurse(n - 1) + try: + recurse(300) + except ValueError as e: + cronitor.capture_exception(e) + frames = self.only_event()['exception']['values'][0]['stacktrace']['frames'] + self.assertLessEqual(len(frames), 100) + self.assertEqual(frames[0]['function'], 'test_deep_recursion_keeps_both_ends') + self.assertEqual(frames[-1]['context_line'].strip(), "raise ValueError('bottom')") + + def test_not_an_exception_sends_nothing(self): + with self.assertLogs('cronitor.capture', 'WARNING'): + self.assertIsNone(cronitor.capture_exception('not an exception')) + self.assertEqual(self.flushed_events(), []) + + def test_no_dsn_sends_nothing(self): + cronitor.dsn = None + try: + raise ValueError('x') + except ValueError as e: + with self.assertLogs('cronitor.ingest', 'ERROR'): + self.assertIsNone(cronitor.capture_exception(e)) + self.assertEqual(self.flushed_events(), []) + + def test_huge_extra_is_dropped_to_fit_the_size_limit(self): + try: + raise ValueError('x') + except ValueError as e: + event_id = cronitor.capture_exception(e, extra={'blob': 'x' * 2000000}) + self.assertRegex(event_id, HEX32) + event = self.only_event() + self.assertEqual(event['extra'], {'_trimmed': 'source context dropped; extra dropped: event over 900 KB'}) + frame = event['exception']['values'][0]['stacktrace']['frames'][-1] + self.assertEqual(frame['context_line'].strip(), "raise ValueError('x')") + self.assertNotIn('pre_context', frame) + + def test_many_chained_frames_are_trimmed_to_fit(self): + def recurse(n, i): + if n == 0: + raise ValueError('bottom %d' % i) + return recurse(n - 1, i) + + def chain(i): + try: + recurse(150, i) + except ValueError as e: + if i == 0: + raise + try: + chain(i - 1) + except ValueError as cause: + raise e from cause + + try: + chain(9) + except ValueError as e: + with patch('cronitor.ingest.MAX_EVENT_BYTES', 60000): + cronitor.capture_exception(e, extra={'batch': 42}) + self.assertTrue(cronitor.flush(2.0)) + item_header, event = self.send.items('event')[0] + self.assertLessEqual(item_header['length'], 60000) + values = event['exception']['values'] + self.assertEqual(len(values), 10) + for value in values: + frames = value['stacktrace']['frames'] + self.assertEqual(len(frames), 20) + self.assertEqual(frames[-1]['context_line'].strip(), "raise ValueError('bottom %d' % i)") + self.assertTrue(event['extra']['_trimmed'].startswith( + 'source context dropped; extra dropped; frames cut to the last 20 per exception')) + + +class CaptureMessageTests(CaptureTestCase): + + def test_message_event(self): + event_id = cronitor.capture_message('disk almost full') + self.assertTrue(cronitor.flush(2.0)) + header, items = self.send.envelopes()[0] + self.assertEqual(header['event_id'], event_id) + event = items[0][1] + self.assertEqual(event['message'], {'formatted': 'disk almost full'}) + self.assertEqual(event['level'], 'info') + self.assertNotIn('exception', event) + self.assertNotIn('fingerprint', event) + + def test_fingerprint_string_and_list(self): + cronitor.capture_message('first', fingerprint='disk-warning') + cronitor.capture_message('second', fingerprint=['disk', '/var']) + first, second = self.flushed_events() + self.assertEqual(first['fingerprint'], ['disk-warning']) + self.assertEqual(second['fingerprint'], ['disk', '/var']) + + def test_level_and_truncation(self): + cronitor.capture_message('m' * 5000, level='warning') + event = self.only_event() + self.assertEqual(event['level'], 'warning') + self.assertEqual(len(event['message']['formatted']), 4000) + + def test_tags_extra_and_bindings(self): + cronitor.capture_message('hi', monitor='nightly-backup', series='run-1', + tags={'region': 'us-east-1', 'attempt': 2}, extra={'rows': [1, 2], 'obj': object()}) + event = self.only_event() + self.assertEqual(event['tags'], { + 'cronitor.monitor': 'nightly-backup', + 'cronitor.series': 'run-1', + 'region': 'us-east-1', + 'attempt': '2', + }) + self.assertEqual(event['extra']['rows'], [1, 2]) + self.assertTrue(event['extra']['obj'].startswith('