import json
import linecache
import logging
import os
import sys
import threading
import subprocess
from datetime import datetime
import sentry_sdk
from sentry_sdk._compat import urlparse, text_type, implements_str, PY2
from sentry_sdk._types import MYPY
if MYPY:
from types import FrameType
from types import TracebackType
from typing import Any
from typing import Callable
from typing import Dict
from typing import ContextManager
from typing import Iterator
from typing import List
from typing import Optional
from typing import Set
from typing import Tuple
from typing import Union
from typing import Type
from sentry_sdk._types import ExcInfo, EndpointType
epoch = datetime(1970, 1, 1)
# The logger is created here but initialized in the debug support module
logger = logging.getLogger("sentry_sdk.errors")
MAX_STRING_LENGTH = 512
MAX_FORMAT_PARAM_LENGTH = 128
def json_dumps(data):
# type: (Any) -> bytes
"""Serialize data into a compact JSON representation encoded as UTF-8."""
return json.dumps(data, allow_nan=False, separators=(",", ":")).encode("utf-8")
def _get_debug_hub():
# type: () -> Optional[sentry_sdk.Hub]
# This function is replaced by debug.py
pass
def get_default_release():
# type: () -> Optional[str]
"""Try to guess a default release."""
release = os.environ.get("SENTRY_RELEASE")
if release:
return release
with open(os.path.devnull, "w+") as null:
try:
release = (
subprocess.Popen(
["git", "rev-parse", "--short", "HEAD"],
stdout=subprocess.PIPE,
stderr=null,
stdin=null,
)
.communicate()[0]
.strip()
.decode("utf-8")
)
except (OSError, IOError):
pass
if release:
return release
for var in (
"HEROKU_SLUG_COMMIT",
"SOURCE_VERSION",
"CODEBUILD_RESOLVED_SOURCE_VERSION",
"CIRCLE_SHA1",
"GAE_DEPLOYMENT_ID",
):
release = os.environ.get(var)
if release:
return release
return None
def get_default_environment(
release=None, # type: Optional[str]
):
# type: (...) -> Optional[str]
rv = os.environ.get("SENTRY_ENVIRONMENT")
if rv:
return rv
if release is not None:
return "production"
return None
class CaptureInternalException(object):
__slots__ = ()
def __enter__(self):
# type: () -> ContextManager[Any]
return self
def __exit__(self, ty, value, tb):
# type: (Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]) -> bool
if ty is not None and value is not None:
capture_internal_exception((ty, value, tb))
return True
_CAPTURE_INTERNAL_EXCEPTION = CaptureInternalException()
def capture_internal_exceptions():
# type: () -> ContextManager[Any]
return _CAPTURE_INTERNAL_EXCEPTION
def capture_internal_exception(exc_info):
# type: (ExcInfo) -> None
hub = _get_debug_hub()
if hub is not None:
hub._capture_internal_exception(exc_info)
def to_timestamp(value):
# type: (datetime) -> float
return (value - epoch).total_seconds()
def format_timestamp(value):
# type: (datetime) -> str
return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def event_hint_with_exc_info(exc_info=None):
# type: (Optional[ExcInfo]) -> Dict[str, Optional[ExcInfo]]
"""Creates a hint with the exc info filled in."""
if exc_info is None:
exc_info = sys.exc_info()
else:
exc_info = exc_info_from_error(exc_info)
if exc_info[0] is None:
exc_info = None
return {"exc_info": exc_info}
class BadDsn(ValueError):
"""Raised on invalid DSNs."""
@implements_str
class Dsn(object):
"""Represents a DSN."""
def __init__(self, value):
# type: (Union[Dsn, str]) -> None
if isinstance(value, Dsn):
self.__dict__ = dict(value.__dict__)
return
parts = urlparse.urlsplit(text_type(value))
if parts.scheme not in (u"http", u"https"):
raise BadDsn("Unsupported scheme %r" % parts.scheme)
self.scheme = parts.scheme
if parts.hostname is None:
raise BadDsn("Missing hostname")
self.host = parts.hostname
if parts.port is None:
self.port = self.scheme == "https" and 443 or 80
else:
self.port = parts.port
if not parts.username:
raise BadDsn("Missing public key")
self.public_key = parts.username
self.secret_key = parts.password
path = parts.path.rsplit("/", 1)
try:
self.project_id = text_type(int(path.pop()))
except (ValueError, TypeError):
raise BadDsn("Invalid project in DSN (%r)" % (parts.path or "")[1:])
self.path = "/".join(path) + "/"
@property
def netloc(self):
# type: () -> str
"""The netloc part of a DSN."""
rv = self.host
if (self.scheme, self.port) not in (("http", 80), ("https", 443)):
rv = "%s:%s" % (rv, self.port)
return rv
def to_auth(self, client=None):
# type: (Optional[Any]) -> Auth
"""Returns the auth info object for this dsn."""
return Auth(
scheme=self.scheme,
host=self.netloc,
path=self.path,
project_id=self.project_id,
public_key=self.public_key,
secret_key=self.secret_key,
client=client,
)
def __str__(self):
# type: () -> str
return "%s://%s%s@%s%s%s" % (
self.scheme,
self.public_key,
self.secret_key and "@" + self.secret_key or "",
self.netloc,
self.path,
self.project_id,
)
class Auth(object):
"""Helper object that represents the auth info."""
def __init__(
self,
scheme,
host,
project_id,
public_key,
secret_key=None,
version=7,
client=None,
path="/",
):
# type: (str, str, str, str, Optional[str], int, Optional[Any], str) -> None
self.scheme = scheme
self.host = host
self.path = path
self.project_id = project_id
self.public_key = public_key
self.secret_key = secret_key
self.version = version
self.client = client
@property
def store_api_url(self):
# type: () -> str
"""Returns the API url for storing events.
Deprecated: use get_api_url instead.
"""
return self.get_api_url(type="store")
def get_api_url(
self, type="store" # type: EndpointType
):
# type: (...) -> str
"""Returns the API url for storing events."""
return "%s://%s%sapi/%s/%s/" % (
self.scheme,
self.host,
self.path,
self.project_id,
type,
)
def to_header(self, timestamp=None):
# type: (Optional[datetime]) -> str
"""Returns the auth header a string."""
rv = [("sentry_key", self.public_key), ("sentry_version", self.version)]
if timestamp is not None:
rv.append(("sentry_timestamp", str(to_timestamp(timestamp))))
if self.client is not None:
rv.append(("sentry_client", self.client))
if self.secret_key is not None:
rv.append(("sentry_secret", self.secret_key))
return u"Sentry " + u", ".join("%s=%s" % (key, value) for key, value in rv)
class AnnotatedValue(object):
__slots__ = ("value", "metadata")
def __init__(self, value, metadata):
# type: (Optional[Any], Dict[str, Any]) -> None
self.value = value
self.metadata = metadata
if MYPY:
from typing import TypeVar
T = TypeVar("T")
Annotated = Union[AnnotatedValue, T]
def get_type_name(cls):
# type: (Optional[type]) -> Optional[str]
return getattr(cls, "__qualname__", None) or getattr(cls, "__name__", None)
def get_type_module(cls):
# type: (Optional[type]) -> Optional[str]
mod = getattr(cls, "__module__", None)
if mod not in (None, "builtins", "__builtins__"):
return mod
return None
def should_hide_frame(frame):
# type: (FrameType) -> bool
try:
mod = frame.f_globals["__name__"]
if mod.startswith("sentry_sdk."):
return True
except (AttributeError, KeyError):
pass
for flag_name in "__traceback_hide__", "__tracebackhide__":
try:
if frame.f_locals[flag_name]:
return True
except Exception:
pass
return False
def iter_stacks(tb):
# type: (Optional[TracebackType]) -> Iterator[TracebackType]
tb_ = tb # type: Optional[TracebackType]
while tb_ is not None:
if not should_hide_frame(tb_.tb_frame):
yield tb_
tb_ = tb_.tb_next
def get_lines_from_file(
filename, # type: str
lineno, # type: int
loader=None, # type: Optional[Any]
module=None, # type: Optional[str]
):
# type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]
context_lines = 5
source = None
if loader is not None and hasattr(loader, "get_source"):
try:
source_str = loader.get_source(module) # type: Optional[str]
except (ImportError, IOError):
source_str = None
if source_str is not None:
source = source_str.splitlines()
if source is None:
try:
source = linecache.getlines(filename)
except (OSError, IOError):
return [], None, []
if not source:
return [], None, []
lower_bound = max(0, lineno - context_lines)
upper_bound = min(lineno + 1 + context_lines, len(source))
try:
pre_context = [
strip_string(line.strip("\r\n")) for line in source[lower_bound:lineno]
]
context_line = strip_string(source[lineno].strip("\r\n"))
post_context = [
strip_string(line.strip("\r\n"))
for line in source[(lineno + 1) : upper_bound]
]
return pre_context, context_line, post_context
except IndexError:
# the file may have changed since it was loaded into memory
return [], None, []
def get_source_context(
frame, # type: FrameType
tb_lineno, # type: int
):
# type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]
try:
abs_path = frame.f_code.co_filename # type: Optional[str]
except Exception:
abs_path = None
try:
module = frame.f_globals["__name__"]
except Exception:
return [], None, []
try:
loader = frame.f_globals["__loader__"]
except Exception:
loader = None
lineno = tb_lineno - 1
if lineno is not None and abs_path:
return get_lines_from_file(abs_path, lineno, loader, module)
return [], None, []
def safe_str(value):
# type: (Any) -> str
try:
return text_type(value)
except Exception:
return safe_repr(value)
if PY2:
def safe_repr(value):
# type: (Any) -> str
try:
rv = repr(value).decode("utf-8", "replace")
# At this point `rv` contains a bunch of literal escape codes, like
# this (exaggerated example):
#
# u"\\x2f"
#
# But we want to show this string as:
#
# u"/"
try:
# unicode-escape does this job, but can only decode latin1. So we
# attempt to encode in latin1.
return rv.encode("latin1").decode("unicode-escape")
except Exception:
# Since usually strings aren't latin1 this can break. In those
# cases we just give up.
return rv
except Exception:
# If e.g. the call to `repr` already fails
return u"