serializers.py 13 KB

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