-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathsnuba.py
2005 lines (1679 loc) · 68.9 KB
/
snuba.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import dataclasses
import functools
import logging
import os
import re
import time
from collections import namedtuple
from collections.abc import Callable, Collection, Mapping, MutableMapping, Sequence
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from hashlib import sha1
from typing import Any, Protocol, TypeVar
from urllib.parse import urlparse
import sentry_protos.snuba.v1alpha.request_common_pb2
import sentry_sdk
import sentry_sdk.scope
import urllib3
from dateutil.parser import parse as parse_datetime
from django.conf import settings
from django.core.cache import cache
from google.protobuf.message import Message as ProtobufMessage
from snuba_sdk import DeleteQuery, MetricsQuery, Request
from snuba_sdk.legacy import json_to_snql
from sentry.models.environment import Environment
from sentry.models.group import Group
from sentry.models.grouprelease import GroupRelease
from sentry.models.organization import Organization
from sentry.models.project import Project
from sentry.models.projectkey import ProjectKey
from sentry.models.release import Release
from sentry.models.releases.release_project import ReleaseProject
from sentry.net.http import connection_from_url
from sentry.snuba.dataset import Dataset
from sentry.snuba.events import Columns
from sentry.snuba.query_sources import QuerySource
from sentry.snuba.referrer import validate_referrer
from sentry.utils import json, metrics
from sentry.utils.dates import outside_retention_with_modified_start
logger = logging.getLogger(__name__)
# Sentinels
ROUND_UP = object()
ROUND_DOWN = object()
# We limit the number of fields an user can ask for
# in a single query to lessen the load on snuba
MAX_FIELDS = 20
SAFE_FUNCTIONS = frozenset(["NOT IN"])
SAFE_FUNCTION_RE = re.compile(r"-?[a-zA-Z_][a-zA-Z0-9_]*$")
# Match any text surrounded by quotes, can't use `.*` here since it
# doesn't include new lines,
QUOTED_LITERAL_RE = re.compile(r"^'[\s\S]*'$")
MEASUREMENTS_KEY_RE = re.compile(r"^measurements\.([a-zA-Z0-9-_.]+)$")
# Matches span op breakdown field
SPAN_OP_BREAKDOWNS_FIELD_RE = re.compile(r"^spans\.([a-zA-Z0-9-_.]+)$")
# Matches span op breakdown snuba key
SPAN_OP_BREAKDOWNS_KEY_RE = re.compile(r"^ops\.([a-zA-Z0-9-_.]+)$")
# Global Snuba request option override dictionary. Only intended
# to be used with the `options_override` contextmanager below.
# NOT THREAD SAFE!
OVERRIDE_OPTIONS = {
"consistent": os.environ.get("SENTRY_SNUBA_CONSISTENT", "false").lower() in ("true", "1")
}
# Show the snuba query params and the corresponding sql or errors in the server logs
SNUBA_INFO_FILE = os.environ.get("SENTRY_SNUBA_INFO_FILE", "")
def log_snuba_info(content):
if SNUBA_INFO_FILE:
with open(SNUBA_INFO_FILE, "a") as file:
file.writelines(content)
else:
print(content) # NOQA: only prints when an env variable is set
SNUBA_INFO = (
os.environ.get("SENTRY_SNUBA_INFO", "false").lower() in ("true", "1") or SNUBA_INFO_FILE
)
if SNUBA_INFO:
import sqlparse
# There are several cases here where we support both a top level column name and
# a tag with the same name. Existing search patterns expect to refer to the tag,
# so we support <real_column_name>.name to refer to the top level column name.
SENTRY_SNUBA_MAP = {
col.value.alias: col.value.event_name for col in Columns if col.value.event_name is not None
}
TRANSACTIONS_SNUBA_MAP = {
col.value.alias: col.value.transaction_name
for col in Columns
if col.value.transaction_name is not None
}
ISSUE_PLATFORM_MAP = {
col.value.alias: col.value.issue_platform_name
for col in Columns
if col.value.issue_platform_name is not None
}
SPAN_COLUMN_MAP = {
# These are deprecated, keeping them for now while we migrate the frontend
"action": "action",
"description": "description",
"domain": "domain",
"group": "group",
"id": "span_id",
"parent_span": "parent_span_id",
"platform": "platform",
"project": "project_id",
"project.id": "project_id",
"span.action": "action",
"span.description": "description",
# message also maps to span description but gets special handling
# to support wild card searching by default
"message": "description",
"span.domain": "domain",
# DO NOT directly expose span.duration, we should always use the alias
# "span.duration": "duration",
"span.group": "group",
"span.op": "op",
"span.self_time": "exclusive_time",
"span.status": "span_status",
"timestamp": "timestamp",
"trace": "trace_id",
"transaction": "segment_name",
"transaction.id": "transaction_id",
"segment.id": "segment_id",
"transaction.op": "transaction_op",
"user": "user",
"user.id": "sentry_tags[user.id]",
"user.email": "sentry_tags[user.email]",
"user.username": "sentry_tags[user.username]",
"profile.id": "profile_id",
"cache.hit": "sentry_tags[cache.hit]",
"transaction.method": "sentry_tags[transaction.method]",
"system": "sentry_tags[system]",
"raw_domain": "sentry_tags[raw_domain]",
"release": "sentry_tags[release]",
"environment": "sentry_tags[environment]",
"device.class": "sentry_tags[device.class]",
"category": "sentry_tags[category]",
"span.category": "sentry_tags[category]",
"span.status_code": "sentry_tags[status_code]",
"replay_id": "sentry_tags[replay_id]",
"replay.id": "sentry_tags[replay_id]",
"resource.render_blocking_status": "sentry_tags[resource.render_blocking_status]",
"http.response_content_length": "sentry_tags[http.response_content_length]",
"http.decoded_response_content_length": "sentry_tags[http.decoded_response_content_length]",
"http.response_transfer_size": "sentry_tags[http.response_transfer_size]",
"app_start_type": "sentry_tags[app_start_type]",
"browser.name": "sentry_tags[browser.name]",
"origin.transaction": "sentry_tags[transaction]",
"is_transaction": "is_segment",
"sdk.name": "sentry_tags[sdk.name]",
"trace.status": "sentry_tags[trace.status]",
"messaging.destination.name": "sentry_tags[messaging.destination.name]",
"messaging.message.id": "sentry_tags[messaging.message.id]",
"tags.key": "tags.key",
"tags.value": "tags.value",
"user.geo.subregion": "sentry_tags[user.geo.subregion]",
"user.geo.country_code": "sentry_tags[user.geo.country_code]",
}
SPAN_EAP_COLUMN_MAP = {
"id": "span_id",
"span_id": "span_id", # ideally this would be temporary, but unfortunately its heavily hardcoded in the FE
"organization.id": "organization_id",
"project": "project_id",
"project.id": "project_id",
"project_id": "project_id",
"span.action": "attr_str[action]",
# For some reason the decision was made to store description as name? its called description everywhere else though
"span.description": "name",
"description": "name",
# message also maps to span description but gets special handling
# to support wild card searching by default
"message": "name",
"span.domain": "domain",
"span.group": "group",
"span.op": "attr_str[op]",
"span.category": "attr_str[category]",
"span.self_time": "exclusive_time_ms",
"span.status": "attr_str[status]",
"timestamp": "timestamp",
"trace": "trace_id",
"transaction": "segment_name",
"transaction.id": "segment_id",
"is_transaction": "is_segment",
"segment.id": "segment_id",
# We should be able to delete origin.transaction and just use transaction
"origin.transaction": "segment_name",
"span.status_code": "attr_str[status_code]",
"replay.id": "attr_str[replay_id]",
}
METRICS_SUMMARIES_COLUMN_MAP = {
"project": "project_id",
"project.id": "project_id",
"id": "span_id",
"trace": "trace_id",
"metric": "metric_mri",
"timestamp": "end_timestamp",
"segment.id": "segment_id",
"span.duration": "duration_ms",
"span.group": "group",
"min_metric": "min",
"max_metric": "max",
"sum_metric": "sum",
"count_metric": "count",
}
SPAN_COLUMN_MAP.update(
{col.value.alias: col.value.spans_name for col in Columns if col.value.spans_name is not None}
)
SESSIONS_FIELD_LIST = [
"release",
"sessions",
"sessions_crashed",
"users",
"users_crashed",
"project_id",
"org_id",
"environment",
"session.status",
"users_errored",
"users_abnormal",
"sessions_errored",
"sessions_abnormal",
"duration_quantiles",
"duration_avg",
]
SESSIONS_SNUBA_MAP = {column: column for column in SESSIONS_FIELD_LIST}
SESSIONS_SNUBA_MAP.update({"timestamp": "started"})
# This maps the public column aliases to the discover dataset column names.
# Longer term we would like to not expose the transactions dataset directly
# to end users and instead have all ad-hoc queries go through the discover
# dataset.
DISCOVER_COLUMN_MAP = {
col.value.alias: col.value.discover_name
for col in Columns
if col.value.discover_name is not None
}
# Not using the Columns enum here, because there are far fewer columns in the metrics tables
METRICS_COLUMN_MAP = {
"timestamp": "timestamp",
"project_id": "project_id",
"project.id": "project_id",
"organization_id": "org_id",
}
DATASETS: dict[Dataset, dict[str, str]] = {
Dataset.Events: SENTRY_SNUBA_MAP,
Dataset.Transactions: TRANSACTIONS_SNUBA_MAP,
Dataset.Discover: DISCOVER_COLUMN_MAP,
Dataset.Sessions: SESSIONS_SNUBA_MAP,
Dataset.Metrics: METRICS_COLUMN_MAP,
Dataset.MetricsSummaries: METRICS_SUMMARIES_COLUMN_MAP,
Dataset.PerformanceMetrics: METRICS_COLUMN_MAP,
Dataset.SpansIndexed: SPAN_COLUMN_MAP,
Dataset.SpansEAP: SPAN_EAP_COLUMN_MAP,
Dataset.IssuePlatform: ISSUE_PLATFORM_MAP,
Dataset.Replays: {},
}
# Store the internal field names to save work later on.
# Add `group_id` to the events dataset list as we don't want to publicly
# expose that field, but it is used by eventstore and other internals.
DATASET_FIELDS = {
Dataset.Events: list(SENTRY_SNUBA_MAP.values()),
Dataset.Transactions: list(TRANSACTIONS_SNUBA_MAP.values()),
Dataset.Discover: list(DISCOVER_COLUMN_MAP.values()),
Dataset.Sessions: SESSIONS_FIELD_LIST,
Dataset.IssuePlatform: list(ISSUE_PLATFORM_MAP.values()),
Dataset.SpansIndexed: list(SPAN_COLUMN_MAP.values()),
Dataset.SpansEAP: list(SPAN_EAP_COLUMN_MAP.values()),
Dataset.MetricsSummaries: list(METRICS_SUMMARIES_COLUMN_MAP.values()),
}
SNUBA_OR = "or"
SNUBA_AND = "and"
OPERATOR_TO_FUNCTION = {
"LIKE": "like",
"NOT LIKE": "notLike",
"=": "equals",
"!=": "notEquals",
">": "greater",
"<": "less",
">=": "greaterOrEquals",
"<=": "lessOrEquals",
"IS NULL": "isNull",
}
FUNCTION_TO_OPERATOR = {v: k for k, v in OPERATOR_TO_FUNCTION.items()}
def parse_snuba_datetime(value):
"""Parses a datetime value from snuba."""
return parse_datetime(value)
class SnubaError(Exception):
pass
class UnqualifiedQueryError(SnubaError):
"""
Exception raised when a required qualification was not satisfied in the query.
"""
class UnexpectedResponseError(SnubaError):
"""
Exception raised when the Snuba API server returns an unexpected response
type (e.g. not JSON.)
"""
class QueryExecutionError(SnubaError):
"""
Exception raised when a query failed to execute.
"""
class RateLimitExceeded(SnubaError):
"""
Exception raised when a query cannot be executed due to rate limits.
"""
class SchemaValidationError(QueryExecutionError):
"""
Exception raised when a query is not valid.
"""
class QueryMemoryLimitExceeded(QueryExecutionError):
"""
Exception raised when a query would exceed the memory limit.
"""
class QueryIllegalTypeOfArgument(QueryExecutionError):
"""
Exception raised when a function in the query is provided an invalid
argument type.
"""
class QueryMissingColumn(QueryExecutionError):
"""
Exception raised when a column is missing.
"""
class QueryTooManySimultaneous(QueryExecutionError):
"""
Exception raised when a query is rejected due to too many simultaneous
queries being performed on the database.
"""
class QuerySizeExceeded(QueryExecutionError):
"""
The generated query has exceeded the maximum length allowed by clickhouse
"""
class QueryExecutionTimeMaximum(QueryExecutionError):
"""
The query has or will take over 30 seconds to run, exceeding the limit
that has been set
"""
class DatasetSelectionError(QueryExecutionError):
"""
This query has resulted in needing to check multiple datasets in a way
that is not currently handled, clickhouse errors with data being compressed
by different methods when this happens
"""
class QueryConnectionFailed(QueryExecutionError):
"""
The connection to clickhouse has failed, and so the query cannot be run
"""
clickhouse_error_codes_map = {
10: QueryMissingColumn,
43: QueryIllegalTypeOfArgument,
47: QueryMissingColumn,
62: QuerySizeExceeded,
160: QueryExecutionTimeMaximum,
202: QueryTooManySimultaneous,
241: QueryMemoryLimitExceeded,
271: DatasetSelectionError,
279: QueryConnectionFailed,
}
class QueryOutsideRetentionError(Exception):
pass
class QueryOutsideGroupActivityError(Exception):
pass
SnubaTSResult = namedtuple("SnubaTSResult", ("data", "start", "end", "rollup"))
@contextmanager
def timer(name, prefix="snuba.client"):
t = time.time()
try:
yield
finally:
metrics.timing(f"{prefix}.{name}", time.time() - t)
@contextmanager
def options_override(overrides):
"""\
NOT THREAD SAFE!
Adds to OVERRIDE_OPTIONS, restoring previous values and removing
keys that didn't previously exist on exit, so that calls to this
can be nested.
"""
previous = {}
delete = []
for k, v in overrides.items():
try:
previous[k] = OVERRIDE_OPTIONS[k]
except KeyError:
delete.append(k)
OVERRIDE_OPTIONS[k] = v
try:
yield
finally:
for k, v in previous.items():
OVERRIDE_OPTIONS[k] = v
for k in delete:
OVERRIDE_OPTIONS.pop(k)
class RetrySkipTimeout(urllib3.Retry):
"""
urllib3 Retry class does not allow us to retry on read errors but to exclude
read timeout. Retrying after a timeout adds useless load to Snuba.
"""
def increment(
self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None
):
"""
Just rely on the parent class unless we have a read timeout. In that case
immediately give up
"""
if error and isinstance(error, urllib3.exceptions.ReadTimeoutError):
raise error.with_traceback(_stacktrace)
metrics.incr(
"snuba.client.retry",
tags={"method": method, "path": urlparse(url).path if url else None},
)
return super().increment(
method=method,
url=url,
response=response,
error=error,
_pool=_pool,
_stacktrace=_stacktrace,
)
_snuba_pool = connection_from_url(
settings.SENTRY_SNUBA,
retries=RetrySkipTimeout(
total=5,
# Our calls to snuba frequently fail due to network issues. We want to
# automatically retry most requests. Some of our POSTs and all of our DELETEs
# do cause mutations, but we have other things in place to handle duplicate
# mutations.
allowed_methods={"GET", "POST", "DELETE"},
),
timeout=settings.SENTRY_SNUBA_TIMEOUT,
maxsize=10,
)
_query_thread_pool = ThreadPoolExecutor(max_workers=10)
epoch_naive = datetime(1970, 1, 1, tzinfo=None)
def to_naive_timestamp(value):
"""
Convert a time zone aware datetime to a POSIX timestamp (with fractional
component.)
"""
return (value - epoch_naive).total_seconds()
def to_start_of_hour(dt: datetime) -> str:
"""This is a function that mimics toStartOfHour from Clickhouse"""
return dt.replace(minute=0, second=0, microsecond=0).isoformat()
def get_snuba_column_name(name, dataset=Dataset.Events):
"""
Get corresponding Snuba column name from Sentry snuba map, if not found
the column is assumed to be a tag. If name is falsy or name is a quoted literal
(e.g. "'name'"), leave unchanged.
"""
no_conversion = {"group_id", "group_ids", "project_id", "start", "end"}
if name in no_conversion:
return name
if not name or name.startswith("tags[") or QUOTED_LITERAL_RE.match(name):
return name
measurement_name = get_measurement_name(name)
span_op_breakdown_name = get_span_op_breakdown_name(name)
if "measurements_key" in DATASETS[dataset] and measurement_name:
default = f"measurements[{measurement_name}]"
elif "span_op_breakdowns_key" in DATASETS[dataset] and span_op_breakdown_name:
default = f"span_op_breakdowns[{span_op_breakdown_name}]"
else:
default = f"tags[{name}]"
return DATASETS[dataset].get(name, default)
def get_function_index(column_expr, depth=0):
"""
If column_expr list contains a function, returns the index of its function name
within column_expr (and assumption is that index + 1 is the list of arguments),
otherwise None.
A function expression is of the form:
[func, [arg1, arg2]] => func(arg1, arg2)
If a string argument is followed by list arg, the pair of them is assumed
to be a nested function call, with extra args to the outer function afterward.
[func1, [func2, [arg1, arg2], arg3]] => func1(func2(arg1, arg2), arg3)
Although at the top level, there is no outer function call, and the optional
3rd argument is interpreted as an alias for the entire expression.
[func, [arg1], alias] => function(arg1) AS alias
You can also have a function part of an argument list:
[func1, [arg1, func2, [arg2, arg3]]] => func1(arg1, func2(arg2, arg3))
"""
index = None
if isinstance(column_expr, (tuple, list)):
i = 0
while i < len(column_expr) - 1:
# The assumption here is that a list that follows a string means
# the string is a function name
if isinstance(column_expr[i], str) and isinstance(column_expr[i + 1], (tuple, list)):
assert column_expr[i] in SAFE_FUNCTIONS or SAFE_FUNCTION_RE.match(
column_expr[i]
), column_expr[i]
index = i
break
else:
i = i + 1
return index
else:
return None
def get_arrayjoin(column):
match = re.match(r"^(exception_stacks|exception_frames|contexts)\..+$", column)
if match:
return match.groups()[0]
def get_organization_id_from_project_ids(project_ids: Sequence[int]) -> int:
# any project will do, as they should all be from the same organization
try:
# Most of the time the project should exist, so get from cache to keep it fast
organization_id = Project.objects.get_from_cache(pk=project_ids[0]).organization_id
except Project.DoesNotExist:
# But in the case the first project doesn't exist, grab the first non deleted project
project = Project.objects.filter(pk__in=project_ids).values("organization_id").first()
if project is None:
raise UnqualifiedQueryError("All project_ids from the filter no longer exist")
organization_id = project.get("organization_id")
return organization_id
def infer_project_ids_from_related_models(filter_keys: Mapping[str, Sequence[int]]) -> list[int]:
ids = [set(get_related_project_ids(k, filter_keys[k])) for k in filter_keys]
return list(set.union(*ids))
def get_query_params_to_update_for_projects(
query_params: SnubaQueryParams, with_org: bool = False
) -> tuple[int, dict[str, Any]]:
"""
Get the project ID and query params that need to be updated for project
based datasets, before we send the query to Snuba.
"""
if "project_id" in query_params.filter_keys:
# If we are given a set of project ids, use those directly.
project_ids = list(set(query_params.filter_keys["project_id"]))
elif query_params.filter_keys:
# Otherwise infer the project_ids from any related models
with timer("get_related_project_ids"):
project_ids = infer_project_ids_from_related_models(query_params.filter_keys)
elif query_params.conditions:
project_ids = []
for cond in query_params.conditions:
if cond[0] == "project_id":
project_ids = [cond[2]] if cond[1] == "=" else cond[2]
else:
project_ids = []
if not project_ids:
raise UnqualifiedQueryError(
"No project_id filter, or none could be inferred from other filters."
)
organization_id = get_organization_id_from_project_ids(project_ids)
params: dict[str, Any] = {"project": project_ids}
if with_org:
params["organization"] = organization_id
return organization_id, params
def get_query_params_to_update_for_organizations(query_params):
"""
Get the organization ID and query params that need to be updated for organization
based datasets, before we send the query to Snuba.
"""
if "org_id" in query_params.filter_keys:
organization_ids = list(set(query_params.filter_keys["org_id"]))
if len(organization_ids) != 1:
raise UnqualifiedQueryError("Multiple organization_ids found. Only one allowed.")
organization_id = organization_ids[0]
elif "project_id" in query_params.filter_keys:
organization_id, _ = get_query_params_to_update_for_projects(query_params)
elif "key_id" in query_params.filter_keys:
key_ids = list(set(query_params.filter_keys["key_id"]))
project_key = ProjectKey.objects.get(pk=key_ids[0])
organization_id = project_key.project.organization_id
else:
organization_id = None
if not organization_id:
raise UnqualifiedQueryError(
"No organization_id filter, or none could be inferred from other filters."
)
return organization_id, {"organization": organization_id}
def _prepare_start_end(
start: datetime | None,
end: datetime | None,
organization_id: int,
group_ids: Sequence[int] | None,
) -> tuple[datetime, datetime]:
if not start:
start = datetime(2008, 5, 8)
if not end:
end = datetime.utcnow() + timedelta(seconds=1)
# convert to naive UTC datetimes, as Snuba only deals in UTC
# and this avoids offset-naive and offset-aware issues
start = naiveify_datetime(start)
end = naiveify_datetime(end)
expired, start = outside_retention_with_modified_start(
start, end, Organization(organization_id)
)
if expired:
raise QueryOutsideRetentionError("Invalid date range. Please try a more recent date range.")
# if `shrink_time_window` pushed `start` after `end` it means the user queried
# a Group for T1 to T2 when the group was only active for T3 to T4, so the query
# wouldn't return any results anyway
new_start = shrink_time_window(group_ids, start)
# TODO (alexh) this is a quick emergency fix for an occasion where a search
# results in only 1 django candidate, which is then passed to snuba to
# check and we raised because of it. Remove this once we figure out why the
# candidate was returned from django at all if it existed only outside the
# time range of the query
if new_start <= end:
start = new_start
if start > end:
raise QueryOutsideGroupActivityError
return start, end
def _prepare_query_params(query_params: SnubaQueryParams, referrer: str | None = None):
kwargs = deepcopy(query_params.kwargs)
query_params_conditions = deepcopy(query_params.conditions)
with timer("get_snuba_map"):
forward, reverse = get_snuba_translators(
query_params.filter_keys, is_grouprelease=query_params.is_grouprelease
)
if query_params.dataset in [
Dataset.Events,
Dataset.Discover,
Dataset.Sessions,
Dataset.Transactions,
Dataset.Replays,
Dataset.IssuePlatform,
]:
(organization_id, params_to_update) = get_query_params_to_update_for_projects(
query_params, with_org=query_params.dataset == Dataset.Sessions
)
elif query_params.dataset in [Dataset.Outcomes, Dataset.OutcomesRaw]:
(organization_id, params_to_update) = get_query_params_to_update_for_organizations(
query_params
)
else:
raise UnqualifiedQueryError(
"No strategy found for getting an organization for the given dataset."
)
kwargs.update(params_to_update)
for col, keys in forward(deepcopy(query_params.filter_keys)).items():
if keys:
if len(keys) == 1 and None in keys:
query_params_conditions.append((col, "IS NULL", None))
else:
query_params_conditions.append((col, "IN", keys))
start, end = _prepare_start_end(
query_params.start,
query_params.end,
organization_id,
query_params.filter_keys.get("group_id"),
)
kwargs.update(
{
"dataset": query_params.dataset.value,
"from_date": start.isoformat(),
"to_date": end.isoformat(),
"groupby": query_params.groupby,
"conditions": query_params_conditions,
"aggregations": query_params.aggregations,
"granularity": query_params.rollup, # TODO name these things the same
}
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
if referrer:
kwargs["tenant_ids"] = kwargs["tenant_ids"] if "tenant_ids" in kwargs else dict()
kwargs["tenant_ids"]["referrer"] = referrer
kwargs.update(OVERRIDE_OPTIONS)
return kwargs, forward, reverse
class SnubaQueryParams:
"""
Represents the information needed to make a query to Snuba.
`start` and `end`: The beginning and end of the query time window (required)
`groupby`: A list of column names to group by.
`conditions`: A list of (column, operator, literal) conditions to be passed
to the query. Conditions that we know will not have to be translated should
be passed this way (eg tag[foo] = bar).
`filter_keys`: A dictionary of {col: [key, ...]} that will be converted
into "col IN (key, ...)" conditions. These are used to restrict the query to
known sets of project/issue/environment/release etc. Appropriate
translations (eg. from environment model ID to environment name) are
performed on the query, and the inverse translation performed on the
result. The project_id(s) to restrict the query to will also be
automatically inferred from these keys.
`aggregations` a list of (aggregation_function, column, alias) tuples to be
passed to the query.
The rest of the args are passed directly into the query JSON unmodified.
See the snuba schema for details.
"""
def __init__(
self,
dataset=None,
start=None,
end=None,
groupby=None,
conditions=None,
filter_keys=None,
aggregations=None,
rollup=None,
referrer=None,
is_grouprelease=False,
**kwargs,
):
# TODO: instead of having events be the default, make dataset required.
self.dataset = dataset or Dataset.Events
self.start = start or datetime(
2008, 5, 8
) # Date of sentry's first commit. Will be clamped to project retention
# Snuba has end exclusive but our UI wants it generally to be inclusive.
# This shows up in unittests: https://github.com/getsentry/sentry/pull/15939
# We generally however require that the API user is aware of the exclusive
# end.
self.end = end or datetime.utcnow() + timedelta(seconds=1)
self.groupby = groupby or []
self.conditions = conditions or []
self.aggregations = aggregations or []
self.filter_keys = filter_keys or {}
self.rollup = rollup
self.referrer = referrer
self.is_grouprelease = is_grouprelease
self.kwargs = kwargs
def raw_query(
dataset=None,
start=None,
end=None,
groupby=None,
conditions=None,
filter_keys=None,
aggregations=None,
rollup=None,
referrer=None,
is_grouprelease=False,
use_cache=False,
**kwargs,
) -> Mapping[str, Any]:
"""
Sends a query to snuba. See `SnubaQueryParams` docstring for param
descriptions.
"""
if referrer:
kwargs["tenant_ids"] = kwargs.get("tenant_ids") or dict()
kwargs["tenant_ids"]["referrer"] = referrer
snuba_params = SnubaQueryParams(
dataset=dataset,
start=start,
end=end,
groupby=groupby,
conditions=conditions,
filter_keys=filter_keys,
aggregations=aggregations,
rollup=rollup,
is_grouprelease=is_grouprelease,
**kwargs,
)
return bulk_raw_query([snuba_params], referrer=referrer, use_cache=use_cache)[0]
Translator = Callable[[Any], Any]
@dataclasses.dataclass(frozen=True)
class SnubaRequest:
request: Request
referrer: str | None # TODO: this should use the referrer Enum
forward: Translator
reverse: Translator
def __post_init__(self) -> None:
self.validate()
def validate(self):
if self.referrer:
validate_referrer(self.referrer)
@property
def headers(self) -> Mapping[str, str]:
headers: MutableMapping[str, str] = {}
if self.referrer:
headers["referer"] = self.referrer
return headers
LegacyQueryBody = tuple[MutableMapping[str, Any], Translator, Translator]
# TODO: Would be nice to make this a concrete structure
ResultSet = list[Mapping[str, Any]]
def raw_snql_query(
request: Request,
referrer: str | None = None,
use_cache: bool = False,
query_source: (
QuerySource | None
) = None, # TODO: @athena Make this field required after updated all the callsites
) -> Mapping[str, Any]:
"""
Alias for `bulk_snuba_queries`, kept for backwards compatibility.
"""
# XXX (evanh): This function does none of the extra processing that the
# other functions do here. It does not add any automatic conditions, format
# results, nothing. Use at your own risk.
return bulk_snuba_queries(
requests=[request], referrer=referrer, use_cache=use_cache, query_source=query_source
)[0]
def bulk_snuba_queries(
requests: list[Request],
referrer: str | None = None,
use_cache: bool = False,
query_source: (
QuerySource | None
) = None, # TODO: @athena Make this field required after updated all the callsites
) -> ResultSet:
"""
Alias for `bulk_snuba_queries_with_referrers` that uses the same referrer for every request.
"""
metrics.incr("snql.sdk.api", tags={"referrer": referrer or "unknown"})
return bulk_snuba_queries_with_referrers(
[(request, referrer) for request in requests],
use_cache=use_cache,
query_source=query_source,
)
def bulk_snuba_queries_with_referrers(
requests_with_referrers: list[tuple[Request, str | None]],
use_cache: bool = False,
query_source: (
QuerySource | None
) = None, # TODO: @athena Make this field required after updated all the callsites
) -> ResultSet:
"""
The main entrypoint to running queries in Snuba. This function accepts
Requests for either MQL or SnQL queries and runs them on the appropriate endpoint.
Every request is paired with a referrer to be used for that request.
"""
if "consistent" in OVERRIDE_OPTIONS:
for request, _ in requests_with_referrers:
request.flags.consistent = OVERRIDE_OPTIONS["consistent"]
for request, referrer in requests_with_referrers:
if referrer or query_source:
request.tenant_ids = request.tenant_ids or dict()
if referrer:
request.tenant_ids["referrer"] = referrer
if query_source:
request.tenant_ids["query_source"] = query_source.value
snuba_requests = [
SnubaRequest(
request=request,
referrer=referrer,
forward=lambda x: x,
reverse=lambda x: x,
)
for request, referrer in requests_with_referrers
]
return _apply_cache_and_build_results(snuba_requests, use_cache=use_cache)
# TODO: This is the endpoint that accepts legacy (non-SnQL/MQL queries)
# It should eventually be removed
def bulk_raw_query(
snuba_param_list: Sequence[SnubaQueryParams],
referrer: str | None = None,