serializers.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import logging
  2. import re
  3. import uuid
  4. from datetime import datetime
  5. from urllib.parse import parse_qs
  6. from anonymizeip import anonymize_ip
  7. from django.conf import settings
  8. from django.utils.timezone import make_aware
  9. from ipware import get_client_ip
  10. from rest_framework import serializers
  11. from rest_framework.exceptions import ErrorDetail, ValidationError
  12. from apps.environments.models import Environment
  13. from apps.releases.models import Release
  14. from .models import Span, TransactionEvent, TransactionGroup
  15. logger = logging.getLogger(__name__)
  16. class FlexibleDateTimeField(serializers.DateTimeField):
  17. """Supports both DateTime and unix epoch timestamp"""
  18. def to_internal_value(self, value):
  19. try:
  20. return make_aware(datetime.fromtimestamp(float(value)))
  21. except (ValueError, TypeError):
  22. return super().to_internal_value(value)
  23. class ErrorValueDetail(ErrorDetail):
  24. """Extended ErrorDetail with validation value"""
  25. value = None
  26. def __new__(cls, string, code=None, value=None):
  27. self = super().__new__(cls, string, code)
  28. self.value = value
  29. return self
  30. def __repr__(self):
  31. return "ErrorDetail(string=%r, code=%r, value=%r)" % (
  32. str(self),
  33. self.code,
  34. self.value,
  35. )
  36. class BaseSerializer(serializers.Serializer):
  37. def process_user(self, project, data):
  38. """Fetch user data from SDK event and request"""
  39. user = data.get("user", {})
  40. if self.context and self.context.get("request"):
  41. client_ip, is_routable = get_client_ip(self.context["request"])
  42. if user or is_routable:
  43. if is_routable:
  44. if project.should_scrub_ip_addresses:
  45. client_ip = anonymize_ip(client_ip)
  46. user["ip_address"] = client_ip
  47. return user
  48. class ForgivingFieldMixin:
  49. def update_handled_errors_context(self, errors: list):
  50. if errors:
  51. handled_errors = self.context.get("handled_errors", {})
  52. self.context["handled_errors"] = handled_errors | {self.field_name: errors}
  53. class ForgivingHStoreField(ForgivingFieldMixin, serializers.HStoreField):
  54. def run_child_validation(self, data):
  55. result = {}
  56. errors: list = []
  57. for key, value in data.items():
  58. if value is None:
  59. continue
  60. key = str(key)
  61. try:
  62. result[key] = self.child.run_validation(value)
  63. except ValidationError as e:
  64. for detail in e.detail:
  65. errors.append(ErrorValueDetail(str(detail), detail.code, value))
  66. if errors:
  67. self.update_handled_errors_context(errors)
  68. return result
  69. class QueryStringField(serializers.ListField):
  70. """
  71. Can be given as unparsed string, dictionary, or list of tuples
  72. Should store as List[List[str]] where inner List is always of length 2
  73. """
  74. child = serializers.ListField(child=serializers.CharField())
  75. def to_internal_value(self, data):
  76. if isinstance(data, str) and data:
  77. qs = parse_qs(data)
  78. result = []
  79. for key, values in qs.items():
  80. for value in values:
  81. result.append([key, value])
  82. return result
  83. elif isinstance(data, dict):
  84. return [[key, value] for key, value in data.items()]
  85. elif isinstance(data, list):
  86. result = []
  87. for item in data:
  88. if isinstance(item, list) and len(item) >= 2:
  89. result.append(item[:2])
  90. return result
  91. return None
  92. class RequestSerializer(serializers.Serializer):
  93. env = serializers.DictField(
  94. child=serializers.CharField(allow_blank=True, allow_null=True), required=False
  95. )
  96. # Dict values can be both str and List[str]
  97. headers = serializers.DictField(required=False)
  98. url = serializers.CharField(required=False, allow_blank=True)
  99. method = serializers.CharField(required=False, allow_blank=True)
  100. query_string = QueryStringField(required=False, allow_null=True)
  101. class ForgivingDisallowRegexField(ForgivingFieldMixin, serializers.CharField):
  102. """Disallow bad matches, set disallow_regex kwarg to use"""
  103. def __init__(self, **kwargs):
  104. self.disallow_regex = kwargs.pop("disallow_regex", None)
  105. super().__init__(**kwargs)
  106. def to_internal_value(self, data):
  107. data = super().to_internal_value(data)
  108. if self.disallow_regex:
  109. pattern = re.compile(self.disallow_regex)
  110. if pattern.match(data) is None:
  111. error = ErrorValueDetail(
  112. "invalid characters in string", "invalid_data", data
  113. )
  114. self.update_handled_errors_context([error])
  115. return None
  116. return data
  117. class SentrySDKEventSerializer(BaseSerializer):
  118. """Represents events coming from a OSS sentry SDK client"""
  119. breadcrumbs = serializers.JSONField(required=False)
  120. fingerprint = serializers.ListField(child=serializers.CharField(), required=False)
  121. tags = ForgivingHStoreField(required=False)
  122. event_id = serializers.UUIDField(required=False, default=uuid.uuid4)
  123. extra = serializers.JSONField(required=False)
  124. request = RequestSerializer(required=False)
  125. server_name = serializers.CharField(required=False)
  126. sdk = serializers.JSONField(required=False)
  127. platform = serializers.CharField(required=False)
  128. release = serializers.CharField(required=False, allow_null=True, allow_blank=True)
  129. environment = ForgivingDisallowRegexField(
  130. required=False, allow_null=True, disallow_regex=r"^[^\n\r\f\/]*$"
  131. )
  132. _meta = serializers.JSONField(required=False)
  133. def set_environment(self, name: str, project) -> str:
  134. if not project.environment_id and name:
  135. environment, _ = Environment.objects.get_or_create(
  136. name=name[: Environment._meta.get_field("name").max_length],
  137. organization=project.organization,
  138. )
  139. environment.projects.add(project)
  140. project.environment_id = environment.id
  141. return environment.name
  142. return name
  143. def set_release(self, version: str, project) -> str:
  144. """
  145. Set project.release_id if not already so
  146. Create needed Release if necessary
  147. """
  148. if not project.release_id and version:
  149. release, _ = Release.objects.get_or_create(
  150. version=version, organization=project.organization
  151. )
  152. release.projects.add(project)
  153. project.release_id = release.id
  154. return release.version
  155. return version
  156. class TransactionGroupSerializer(serializers.ModelSerializer):
  157. avgDuration = serializers.IntegerField(source="avg_duration", read_only=True)
  158. transactionCount = serializers.IntegerField(
  159. source="transaction_count", read_only=True
  160. )
  161. class Meta:
  162. model = TransactionGroup
  163. fields = [
  164. "id",
  165. "transaction",
  166. "project",
  167. "op",
  168. "method",
  169. "avgDuration",
  170. "transactionCount",
  171. ]
  172. class SpanSerializer(serializers.ModelSerializer):
  173. spanId = serializers.CharField(source="span_id", read_only=True)
  174. parentSpanId = serializers.CharField(source="parent_span_id", read_only=True)
  175. startTimestamp = serializers.DateTimeField(source="start_timestamp", read_only=True)
  176. start_timestamp = FlexibleDateTimeField(write_only=True)
  177. timestamp = FlexibleDateTimeField(write_only=True)
  178. description = serializers.CharField(required=False)
  179. class Meta:
  180. model = Span
  181. fields = [
  182. "spanId",
  183. "span_id",
  184. "parent_span_id",
  185. "parentSpanId",
  186. "op",
  187. "description",
  188. "startTimestamp",
  189. "start_timestamp",
  190. "timestamp",
  191. "tags",
  192. "data",
  193. ]
  194. extra_kwargs = {
  195. "start_timestamp": {"write_only": True},
  196. "span_id": {"write_only": True},
  197. "parent_span_id": {"write_only": True},
  198. }
  199. def to_internal_value(self, data):
  200. # Coerce tags to strings
  201. # Must be done here to avoid failing child CharField validation
  202. if tags := data.get("tags"):
  203. data["tags"] = {key: str(value) for key, value in tags.items()}
  204. return super().to_internal_value(data)
  205. def validate_description(self, value):
  206. # No documented max length here, so we truncate
  207. max_length = self.Meta.model._meta.get_field("description").max_length
  208. if value and len(value) > max_length:
  209. logger.warning("Span description truncation %s", value)
  210. return value[:max_length]
  211. return value
  212. class TransactionEventSerializer(SentrySDKEventSerializer):
  213. type = serializers.CharField(required=False)
  214. contexts = serializers.JSONField()
  215. measurements = serializers.JSONField(required=False)
  216. spans = serializers.ListField(
  217. child=SpanSerializer(), required=False, allow_empty=True
  218. )
  219. start_timestamp = FlexibleDateTimeField()
  220. timestamp = FlexibleDateTimeField()
  221. transaction = serializers.CharField()
  222. def create(self, validated_data):
  223. data = validated_data
  224. contexts = data["contexts"]
  225. project = self.context.get("project")
  226. trace_id = contexts["trace"]["trace_id"]
  227. tags = []
  228. release = self.set_release(data.get("release"), project)
  229. if project.release_id:
  230. tags.append(("release", release))
  231. environment = self.set_environment(data.get("environment"), project)
  232. if project.environment_id:
  233. tags.append(("environment", environment))
  234. if data.get("tags"):
  235. tags += [(k, v) for k, v in data["tags"].items()]
  236. defaults = {}
  237. defaults["tags"] = {tag[0]: [tag[1]] for tag in tags}
  238. group, group_created = TransactionGroup.objects.get_or_create(
  239. project=self.context.get("project"),
  240. transaction=data["transaction"],
  241. op=contexts["trace"].get("op", ""),
  242. method=data.get("request", {}).get("method"),
  243. defaults=defaults,
  244. )
  245. # Merge tags, only save if necessary
  246. update_group = False
  247. if not group_created:
  248. for tag in tags:
  249. if tag[0] not in group.tags:
  250. new_tag_value = tag[1]
  251. # Coerce to List[str]
  252. if isinstance(new_tag_value, str):
  253. new_tag_value = [new_tag_value]
  254. group.tags[tag[0]] = new_tag_value
  255. update_group = True
  256. elif tag[1] not in group.tags[tag[0]]:
  257. group.tags[tag[0]].append(tag[1])
  258. update_group = True
  259. if update_group:
  260. group.save(update_fields=["tags"])
  261. transaction = TransactionEvent.objects.create(
  262. group=group,
  263. data={
  264. "request": data.get("request"),
  265. "sdk": data.get("sdk"),
  266. "platform": data.get("platform"),
  267. },
  268. trace_id=trace_id,
  269. event_id=data["event_id"],
  270. timestamp=data["timestamp"],
  271. start_timestamp=data["start_timestamp"],
  272. duration=(data["timestamp"] - data["start_timestamp"]).total_seconds()
  273. * 1000,
  274. tags={tag[0]: tag[1] for tag in tags},
  275. )
  276. first_span = SpanSerializer(
  277. data=contexts["trace"]
  278. | {
  279. "start_timestamp": data["start_timestamp"],
  280. "timestamp": data["timestamp"],
  281. }
  282. )
  283. if settings.ENABLE_PERFORMANCE_SPANS:
  284. is_valid = first_span.is_valid()
  285. if is_valid:
  286. spans = data.get("spans", []) + [first_span.validated_data]
  287. else:
  288. spans = data.get("spans")
  289. if spans:
  290. Span.objects.bulk_create(
  291. [
  292. Span(
  293. transaction=transaction,
  294. **span,
  295. )
  296. for span in spans
  297. ]
  298. )
  299. return transaction
  300. class TransactionSerializer(serializers.ModelSerializer):
  301. eventId = serializers.UUIDField(source="pk")
  302. startTimestamp = serializers.DateTimeField(source="start_timestamp")
  303. transaction = serializers.SerializerMethodField()
  304. op = serializers.SerializerMethodField()
  305. method = serializers.SerializerMethodField()
  306. class Meta:
  307. model = TransactionEvent
  308. fields = (
  309. "eventId",
  310. "timestamp",
  311. "startTimestamp",
  312. "transaction",
  313. "op",
  314. "method",
  315. )
  316. def get_transaction(self, obj):
  317. return obj.group.transaction
  318. def get_op(self, obj):
  319. return obj.group.op
  320. def get_method(self, obj):
  321. return obj.group.transaction
  322. class TransactionDetailSerializer(TransactionSerializer):
  323. spans = SpanSerializer(source="span_set", many=True)
  324. class Meta(TransactionSerializer.Meta):
  325. fields = TransactionSerializer.Meta.fields + ("spans",)