-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathtest_statements.py
More file actions
2254 lines (1974 loc) · 89.7 KB
/
Copy pathtest_statements.py
File metadata and controls
2254 lines (1974 loc) · 89.7 KB
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
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import datetime
import re
import threading
import time
from collections import Counter, namedtuple
from concurrent.futures.thread import ThreadPoolExecutor
import mock
import psycopg
import pytest
from dateutil import parser
from psycopg import ClientCursor
from semver import VersionInfo
from datadog_checks.base.utils.db.sql import compute_sql_signature
from datadog_checks.base.utils.db.utils import DBMAsyncJob
from datadog_checks.base.utils.serialization import json
from datadog_checks.base.utils.time import UTC
from datadog_checks.postgres.config import PostgresConfig
from datadog_checks.postgres.statement_samples import (
DBExplainError,
StatementTruncationState,
)
from datadog_checks.postgres.statements import (
PG_STAT_STATEMENTS_METRICS_COLUMNS,
# PG_STAT_STATEMENTS_TIMING_COLUMNS,
# PG_STAT_STATEMENTS_TIMING_COLUMNS_LT_17,
PostgresStatementMetrics,
StatementMetrics,
_row_key,
)
from datadog_checks.postgres.util import payload_pg_version
from datadog_checks.postgres.version_utils import V12
from .common import (
DB_NAME,
HOST,
PASSWORD_ADMIN,
PORT_REPLICA2,
POSTGRES_LOCALE,
POSTGRES_VERSION,
USER_ADMIN,
_get_expected_replication_tags,
_get_expected_tags,
)
from .utils import WaitGroup, _get_conn, _get_superconn, requires_over_10, requires_over_13, run_one_check
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures('dd_environment')]
CLOSE_TO_ZERO_INTERVAL = 0.0000001
SAMPLE_QUERIES = [
# (username, password, dbname, query, arg)
("bob", "bob", "datadog_test", "SELECT city FROM persons WHERE city = %s", "hello"),
(
"bob",
"bob",
"datadog_test",
"SELECT hello_how_is_it_going_this_is_a_very_long_table_alias_name.personid, "
"hello_how_is_it_going_this_is_a_very_long_table_alias_name.lastname "
"FROM persons hello_how_is_it_going_this_is_a_very_long_table_alias_name JOIN persons B "
"ON hello_how_is_it_going_this_is_a_very_long_table_alias_name.personid = B.personid WHERE B.city = %s",
"hello",
),
(USER_ADMIN, PASSWORD_ADMIN, "dogs", "SELECT * FROM breed WHERE name = %s", "Labrador"),
]
dbm_enabled_keys = ["dbm", "deep_database_monitoring"]
@pytest.fixture(autouse=True)
def stop_orphaned_threads():
# make sure we shut down any orphaned threads and create a new Executor for each test
DBMAsyncJob.executor.shutdown(wait=True)
DBMAsyncJob.executor = ThreadPoolExecutor()
@pytest.mark.parametrize("dbm_enabled_key", dbm_enabled_keys)
@pytest.mark.parametrize("dbm_enabled", [True, False])
def test_dbm_enabled_config(integration_check, dbm_instance, dbm_enabled_key, dbm_enabled):
# test to make sure we continue to support the old key
for k in dbm_enabled_keys:
dbm_instance.pop(k, None)
dbm_instance[dbm_enabled_key] = dbm_enabled
check = integration_check(dbm_instance)
assert check._config.dbm_enabled == dbm_enabled
@requires_over_10
def test_statement_metrics_multiple_pgss_rows_single_query_signature(
aggregator,
integration_check,
dbm_instance,
datadog_agent,
):
# don't need samples for this test
dbm_instance['query_samples'] = {'enabled': False}
dbm_instance['query_activity'] = {'enabled': False}
dbm_instance['query_metrics']['incremental_query_metrics'] = True
connections = {}
def normalize_query(q):
# Remove the quotes from below:
normalized = ""
for s in ["'one'", "'two'"]:
if s in q:
normalized = q.replace(s, "?")
break
return normalized
def obfuscate_sql(query, options=None):
if query.startswith('SET application_name'):
return json.dumps({'query': normalize_query(query), 'metadata': {}})
return json.dumps({'query': query, 'metadata': {}})
queries = ["SET application_name = %s", "SET application_name = %s"]
# These queries will have the same query signature but different queryids in pg_stat_statements
def _run_query(idx):
query = queries[idx]
user = "bob"
password = "bob"
dbname = "datadog_test"
if dbname not in connections:
connections[dbname] = psycopg.connect(
host=HOST, dbname=dbname, user=user, password=password, cursor_factory=ClientCursor
)
args = ('two',)
if idx == 1:
args = ('one',)
connections[dbname].cursor().execute(query, args)
check = integration_check(dbm_instance)
check._connect()
# Execute the query with the mocked obfuscate_sql. The result should produce an event payload with the metadata.
with mock.patch.object(datadog_agent, 'obfuscate_sql', passthrough=True) as mock_agent:
mock_agent.side_effect = obfuscate_sql
check = integration_check(dbm_instance)
check._connect()
# Seed a bunch of calls into pg_stat_statements
for _ in range(10):
_run_query(1)
_run_query(0)
run_one_check(check, cancel=False)
# Call one query
_run_query(0)
run_one_check(check, cancel=False)
aggregator.reset()
# Call other query that maps to same query signature
_run_query(1)
run_one_check(check, cancel=False)
obfuscated_param = '?'
query0 = queries[0] % (obfuscated_param,)
query_signature = compute_sql_signature(query0)
events = aggregator.get_event_platform_events("dbm-metrics")
assert len(events) > 0
matching_rows = [r for r in events[0]['postgres_rows'] if r['query_signature'] == query_signature]
assert len(matching_rows) == 1
assert matching_rows[0]['calls'] == 1
for conn in connections.values():
conn.close()
statement_samples_keys = ["query_samples", "statement_samples"]
@pytest.mark.parametrize("statement_samples_key", statement_samples_keys)
@pytest.mark.parametrize("statement_samples_enabled", [True, False])
@pytest.mark.parametrize("query_activity_enabled", [True, False])
def test_statement_samples_enabled_config(
integration_check, dbm_instance, statement_samples_key, statement_samples_enabled, query_activity_enabled
):
# test to make sure we continue to support the old key
for k in statement_samples_keys:
dbm_instance.pop(k, None)
dbm_instance[statement_samples_key] = {'enabled': statement_samples_enabled}
# check that if either activity OR regular samples (explain plans) is enabled, statement_samples is enabled
dbm_instance["query_activity"]["enabled"] = query_activity_enabled
check = integration_check(dbm_instance)
assert check.statement_samples._enabled == statement_samples_enabled or query_activity_enabled
@pytest.mark.parametrize(
"version,expected_payload_version",
[
(VersionInfo(*[9, 6, 0]), "v9.6.0"),
(None, ""),
],
)
def test_statement_metrics_version(integration_check, dbm_instance, version, expected_payload_version):
if version:
check = integration_check(dbm_instance)
check.version = version
check._connect()
assert payload_pg_version(check.version) == expected_payload_version
else:
with mock.patch(
'datadog_checks.postgres.postgres.PostgreSql.load_version', new_callable=mock.MagicMock
) as patched_version:
patched_version.return_value = None
check = integration_check(dbm_instance)
check._connect()
assert payload_pg_version(check.version) == expected_payload_version
@pytest.mark.parametrize("dbstrict,ignore_databases", [(True, []), (False, ['dogs']), (False, [])])
@pytest.mark.parametrize("pg_stat_statements_view", ["pg_stat_statements", "datadog.pg_stat_statements()"])
@pytest.mark.parametrize("track_io_timing_enabled", [True, False])
def test_statement_metrics(
aggregator,
integration_check,
dbm_instance,
dbstrict,
ignore_databases,
pg_stat_statements_view,
datadog_agent,
track_io_timing_enabled,
):
dbm_instance['dbstrict'] = dbstrict
dbm_instance['ignore_databases'] = ignore_databases
dbm_instance['pg_stat_statements_view'] = pg_stat_statements_view
# don't need samples for this test
dbm_instance['query_samples'] = {'enabled': False}
dbm_instance['query_activity'] = {'enabled': False}
connections = {}
def _run_queries():
for user, password, dbname, query, arg in SAMPLE_QUERIES:
if dbname not in connections:
connections[dbname] = psycopg.connect(
host=HOST, dbname=dbname, user=user, password=password, autocommit=True, cursor_factory=ClientCursor
)
connections[dbname].cursor().execute(query, (arg,))
check = integration_check(dbm_instance)
check._connect()
run_one_check(check, cancel=False)
# We can't change track_io_timing at runtime, but we can change what the integration thinks the runtime value is
# This must be done after the first check since postgres settings are loaded from the database then
check.pg_settings["track_io_timing"] = "on" if track_io_timing_enabled else "off"
_run_queries()
run_one_check(check, cancel=False)
_run_queries()
run_one_check(check, cancel=False)
def _should_catch_query(dbname):
# we can always catch it if the query originals in the same DB
# when dbstrict=True we expect to only capture those queries for the initial database to which the
# agent is connecting
if POSTGRES_VERSION.split('.')[0] == "9" and pg_stat_statements_view == "pg_stat_statements":
# cannot catch any queries from other users
# only can see own queries
return False
if dbstrict and dbname != dbm_instance['dbname'] or dbname in ignore_databases:
return False
return True
events = aggregator.get_event_platform_events("dbm-metrics")
assert len(events) == 2
event = events[1] # first item is from the initial dummy check to load pg_settings
assert event['host'] == 'stubbed.hostname'
assert event['timestamp'] > 0
assert event['ddagentversion'] == datadog_agent.get_version()
assert event['ddagenthostname'] == datadog_agent.get_hostname()
assert event['min_collection_interval'] == dbm_instance['query_metrics']['collection_interval']
expected_dbm_metrics_tags = set(_get_expected_tags(check, dbm_instance, with_host=False))
assert set(event['tags']) == expected_dbm_metrics_tags
obfuscated_param = '?' if POSTGRES_VERSION.split('.')[0] == "9" else '$1'
assert len(aggregator.metrics("postgresql.pg_stat_statements.max")) != 0
assert len(aggregator.metrics("postgresql.pg_stat_statements.count")) != 0
dbm_samples = aggregator.get_event_platform_events("dbm-samples")
for username, _, dbname, query, _ in SAMPLE_QUERIES:
expected_query = query % obfuscated_param
query_signature = compute_sql_signature(expected_query)
matching_rows = [r for r in event['postgres_rows'] if r['query_signature'] == query_signature]
if not _should_catch_query(dbname):
assert len(matching_rows) == 0
continue
# metrics
assert len(matching_rows) == 1
row = matching_rows[0]
assert row['calls'] == 1
assert row['datname'] == dbname
assert row['rolname'] == username
assert row['query'] == expected_query
available_columns = set(row.keys())
metric_columns = available_columns & PG_STAT_STATEMENTS_METRICS_COLUMNS
# if track_io_timing_enabled:
# if float(POSTGRES_VERSION) >= 17.0:
# assert (available_columns & PG_STAT_STATEMENTS_TIMING_COLUMNS) == PG_STAT_STATEMENTS_TIMING_COLUMNS
# else:
# assert (
# available_columns & PG_STAT_STATEMENTS_TIMING_COLUMNS_LT_17
# ) == PG_STAT_STATEMENTS_TIMING_COLUMNS_LT_17
# else:
# assert (available_columns & PG_STAT_STATEMENTS_TIMING_COLUMNS) == set()
for col in metric_columns:
assert type(row[col]) in (float, int)
# full query text
fqt_events = [e for e in dbm_samples if e.get('dbm_type') == 'fqt']
assert len(fqt_events) > 0
matching = [e for e in fqt_events if e['db']['query_signature'] == query_signature]
assert len(matching) == 1
fqt_event = matching[0]
assert fqt_event['ddagentversion'] == datadog_agent.get_version()
assert fqt_event['ddsource'] == "postgres"
assert fqt_event['db']['statement'] == expected_query
assert fqt_event['postgres']['datname'] == dbname
assert fqt_event['postgres']['rolname'] == username
assert fqt_event['timestamp'] > 0
assert fqt_event['host'] == 'stubbed.hostname'
assert set(fqt_event['ddtags'].split(',')) == expected_dbm_metrics_tags | {
"db:" + fqt_event['postgres']['datname'],
"rolname:" + fqt_event['postgres']['rolname'],
}
for conn in connections.values():
conn.close()
@pytest.mark.parametrize(
"input_cloud_metadata,output_cloud_metadata",
[
({}, {}),
(
{
'azure': {
'deployment_type': 'flexible_server',
'name': 'test-server.database.windows.net',
},
},
{
'azure': {
'deployment_type': 'flexible_server',
'name': 'test-server.database.windows.net',
'managed_authentication': {'enabled': False},
},
},
),
(
{
'azure': {
'deployment_type': 'flexible_server',
'fully_qualified_domain_name': 'test-server.database.windows.net',
},
},
{
'azure': {
'deployment_type': 'flexible_server',
'name': 'test-server.database.windows.net',
'managed_authentication': {'enabled': False},
},
},
),
(
{
'aws': {
'instance_endpoint': 'foo.aws.com',
},
'azure': {
'deployment_type': 'flexible_server',
'name': 'test-server.database.windows.net',
},
},
{
'aws': {'instance_endpoint': 'foo.aws.com', 'managed_authentication': {'enabled': False}},
'azure': {
'deployment_type': 'flexible_server',
'name': 'test-server.database.windows.net',
'managed_authentication': {'enabled': False},
},
},
),
(
{
'gcp': {
'project_id': 'foo-project',
'instance_id': 'bar',
'extra_field': 'included',
},
},
{
'gcp': {
'project_id': 'foo-project',
'instance_id': 'bar',
'extra_field': 'included',
},
},
),
],
)
def test_statement_metrics_cloud_metadata(
aggregator, integration_check, dbm_instance, input_cloud_metadata, output_cloud_metadata, datadog_agent
):
dbm_instance['pg_stat_statements_view'] = "pg_stat_statements"
# don't need samples for this test
dbm_instance['query_samples'] = {'enabled': False}
dbm_instance['query_activity'] = {'enabled': False}
# very low collection interval for test purposes
dbm_instance['query_metrics'] = {'enabled': True, 'run_sync': True, 'collection_interval': 0.1}
if input_cloud_metadata:
for k, v in input_cloud_metadata.items():
dbm_instance[k] = v
connections = {}
def _run_queries():
for user, password, dbname, query, arg in SAMPLE_QUERIES:
if dbname not in connections:
connections[dbname] = psycopg.connect(host=HOST, dbname=dbname, user=user, password=password)
connections[dbname].cursor().execute(query, (arg,))
check = integration_check(dbm_instance)
check._connect()
_run_queries()
run_one_check(check)
_run_queries()
run_one_check(check)
events = aggregator.get_event_platform_events("dbm-metrics")
assert len(events) == 1, "should capture exactly one metrics payload"
event = events[0]
assert event['host'] == 'stubbed.hostname'
assert event['timestamp'] > 0
assert event['ddagentversion'] == datadog_agent.get_version()
assert event['ddagenthostname'] == datadog_agent.get_hostname()
assert event['min_collection_interval'] == dbm_instance['query_metrics']['collection_interval']
assert event['cloud_metadata'] == output_cloud_metadata, "wrong cloud_metadata"
for conn in connections.values():
conn.close()
@requires_over_13
def test_wal_metrics(aggregator, integration_check, dbm_instance):
dbm_instance['pg_stat_statements_view'] = "pg_stat_statements"
# don't need samples for this test
dbm_instance['query_samples'] = {'enabled': False}
dbm_instance['query_activity'] = {'enabled': False}
# very low collection interval for test purposes
dbm_instance['query_metrics'] = {'enabled': True, 'run_sync': True, 'collection_interval': 0.1}
connections = {}
def _run_queries():
for user, password, dbname, query, arg in SAMPLE_QUERIES:
if dbname not in connections:
connections[dbname] = psycopg.connect(host=HOST, dbname=dbname, user=user, password=password)
connections[dbname].cursor().execute(query, (arg,))
check = integration_check(dbm_instance)
check._connect()
_run_queries()
run_one_check(check)
_run_queries()
run_one_check(check)
events = aggregator.get_event_platform_events("dbm-metrics")
assert len(events) == 1, "should capture exactly one metrics payload"
event = events[0]
assert all('wal_bytes' in entry for entry in event['postgres_rows'])
assert all('wal_fpi' in entry for entry in event['postgres_rows'])
assert all('wal_bytes' in entry for entry in event['postgres_rows'])
for conn in connections.values():
conn.close()
def test_statement_metrics_with_duplicates(aggregator, integration_check, dbm_instance, datadog_agent):
# don't need samples for this test
dbm_instance['query_samples'] = {'enabled': False}
dbm_instance['query_activity'] = {'enabled': False}
# very low collection interval for test purposes
dbm_instance['query_metrics'] = {'enabled': True, 'run_sync': True, 'collection_interval': 0.1}
# The query signature matches the normalized query returned by the mock agent and would need to be
# updated if the normalized query is updated
query = 'select * from pg_stat_activity where application_name = ANY(%s);'
query_signature = 'a478c1e7aaac3ff2'
normalized_query = 'select * from pg_stat_activity where application_name = ANY(array [ ? ])'
def obfuscate_sql(query, options=None):
if 'select * from pg_stat_activity where application_name' in query:
return normalized_query
return query
check = integration_check(dbm_instance)
check._connect()
# Execute the query once to begin tracking it. Execute again between checks to track the difference.
# This should result in a single metric for that query_signature having a value of 2
with check.db() as conn:
with conn.cursor() as cursor:
with mock.patch.object(datadog_agent, 'obfuscate_sql', passthrough=True) as mock_agent:
mock_agent.side_effect = obfuscate_sql
cursor.execute(query, (['app1', 'app2'],))
cursor.execute(query, (['app1', 'app2', 'app3'],))
check.check(dbm_instance)
cursor.execute(query, (['app1', 'app2'],))
cursor.execute(query, (['app1', 'app2', 'app3'],))
run_one_check(check)
events = aggregator.get_event_platform_events("dbm-metrics")
assert len(events) == 1
event = events[0]
matching = [e for e in event['postgres_rows'] if e['query_signature'] == query_signature]
assert len(matching) == 1
row = matching[0]
assert row['calls'] == 2
@pytest.fixture
def bob_conn():
conn = psycopg.connect(host=HOST, dbname=DB_NAME, user="bob", password="bob")
yield conn
conn.close()
@pytest.fixture
def dbm_instance(pg_instance):
pg_instance['dbm'] = True
pg_instance['min_collection_interval'] = 0.2
pg_instance['pg_stat_activity_view'] = "datadog.pg_stat_activity()"
pg_instance['query_samples'] = {'enabled': True, 'run_sync': True, 'collection_interval': 0.2}
pg_instance['query_activity'] = {'enabled': True, 'collection_interval': 0.2}
# Set collection_interval close to 0. This is needed if the test runs the check multiple times.
# This prevents DBMAsync from skipping job executions, as it is designed
# to not execute jobs more frequently than their collection period.
pg_instance['query_metrics'] = {'enabled': True, 'run_sync': True, 'collection_interval': CLOSE_TO_ZERO_INTERVAL}
pg_instance['collect_resources'] = {'enabled': False}
return pg_instance
@pytest.fixture
def dbm_instance_replica2(pg_instance):
pg_instance['dbm'] = True
pg_instance['port'] = PORT_REPLICA2
pg_instance['min_collection_interval'] = 1
pg_instance['pg_stat_activity_view'] = "datadog.pg_stat_activity()"
pg_instance['query_samples'] = {'enabled': True, 'run_sync': True, 'collection_interval': 1}
pg_instance['query_activity'] = {'enabled': True, 'collection_interval': 1}
pg_instance['query_metrics'] = {'enabled': True, 'run_sync': True, 'collection_interval': 0.2}
pg_instance['collect_resources'] = {'enabled': False}
return pg_instance
@pytest.mark.parametrize(
"dbname,expected_db_explain_error",
[
("datadog_test", None),
("dogs", None),
("dogs_noschema", DBExplainError.invalid_schema),
("dogs_nofunc", DBExplainError.failed_function),
],
)
def test_get_db_explain_setup_state(integration_check, dbm_instance, dbname, expected_db_explain_error):
check = integration_check(dbm_instance)
check._connect()
db_explain_error, err = check.statement_samples._get_db_explain_setup_state(dbname)
assert db_explain_error == expected_db_explain_error
failed_explain_test_repeat_count = 5
@pytest.mark.parametrize(
"query",
[
"SELECT * FROM pg_class",
"SET LOCAL datestyle TO postgres; SELECT * FROM pg_class",
],
)
def test_successful_explain(
integration_check,
dbm_instance,
aggregator,
query,
):
dbname = "datadog_test"
# Don't need metrics for this one
dbm_instance['query_metrics']['enabled'] = False
dbm_instance['query_samples']['explain_parameterized_queries'] = False
check = integration_check(dbm_instance)
check._connect()
# run check so all internal state is correctly initialized
run_one_check(check)
# clear out contents of aggregator so we measure only the metrics generated during this specific part of the test
aggregator.reset()
db_explain_error, err = check.statement_samples._get_db_explain_setup_state(dbname)
assert db_explain_error is None
assert err is None
plan, *rest = check.statement_samples._run_and_track_explain(dbname, query, query, "7231596c8b5536d1")
assert plan is not None
plan = plan['Plan']
assert plan['Node Type'] == 'Seq Scan'
assert plan['Relation Name'] == 'pg_class'
@pytest.mark.parametrize(
"query,expected_error_tag,explain_function_override,expected_fail_count,skip_on_versions",
[
(
"select * from fake_table",
"error:explain-undefined_table-<class 'psycopg.errors.UndefinedTable'>",
None,
1,
None,
),
(
"select * from fake_schema.fake_table",
"error:explain-undefined_table-<class 'psycopg.errors.UndefinedTable'>",
None,
1,
None,
),
(
"select * from pg_settings where name = $1",
"error:explain-parameterized_query-<class 'psycopg.errors.UndefinedParameter'>",
None,
1,
None,
),
(
"select * from pg_settings where name = 'this query is truncated' limi",
"error:explain-database_error-<class 'psycopg.errors.SyntaxError'>",
None,
1,
None,
),
(
"select * from persons",
"error:explain-database_error-<class 'psycopg.errors.InsufficientPrivilege'>",
"datadog.explain_statement_noaccess",
failed_explain_test_repeat_count,
None,
),
(
"update persons set firstname='firstname' where personid in (2, 1); select pg_sleep(1);",
"error:explain-database_error-<class 'psycopg.errors.InvalidCursorDefinition'>",
None,
1,
None,
),
],
)
def test_failed_explain_handling(
integration_check,
dbm_instance,
aggregator,
query,
expected_error_tag,
explain_function_override,
expected_fail_count,
skip_on_versions,
):
dbname = "datadog_test"
# Don't need metrics for this one
dbm_instance['query_metrics']['enabled'] = False
dbm_instance['query_samples']['explain_parameterized_queries'] = False
if explain_function_override:
dbm_instance['query_samples']['explain_function'] = explain_function_override
check = integration_check(dbm_instance)
check._connect()
if skip_on_versions is not None and float(POSTGRES_VERSION) in skip_on_versions:
pytest.skip("not relevant for postgres {version}".format(version=POSTGRES_VERSION))
# run check so all internal state is correctly initialized
run_one_check(check)
# clear out contents of aggregator so we measure only the metrics generated during this specific part of the test
aggregator.reset()
db_explain_error, err = check.statement_samples._get_db_explain_setup_state(dbname)
assert db_explain_error is None
assert err is None
for _ in range(failed_explain_test_repeat_count):
check.statement_samples._run_and_track_explain(dbname, query, query, "7231596c8b5536d1")
expected_tags = _get_expected_tags(
check, dbm_instance, with_host=False, with_db=True, agent_hostname='stubbed.hostname'
) + [expected_error_tag]
aggregator.assert_metric(
'dd.postgres.statement_samples.error',
count=failed_explain_test_repeat_count,
tags=expected_tags,
hostname='stubbed.hostname',
)
aggregator.assert_metric(
'dd.postgres.run_explain.error',
count=expected_fail_count,
tags=expected_tags,
hostname='stubbed.hostname',
)
@pytest.mark.parametrize("pg_stat_activity_view", ["pg_stat_activity", "datadog.pg_stat_activity()"])
@pytest.mark.parametrize(
"user,password,dbname,query,arg,expected_error_tag,expected_collection_errors,expected_statement_truncated,"
"expected_warnings",
[
(
"bob",
"bob",
"datadog_test",
"SELECT city FROM persons WHERE city = %s",
"hello",
None,
None,
StatementTruncationState.not_truncated.value,
[],
),
(
"dd_admin",
"dd_admin",
"dogs",
"SELECT * FROM breed WHERE name = %s",
"Labrador",
None,
None,
StatementTruncationState.not_truncated.value,
[],
),
(
"dd_admin",
"dd_admin",
"dogs_noschema",
"SELECT * FROM kennel WHERE id = %s",
123,
"error:explain-no_plans_possible",
[{'code': 'invalid_schema', 'message': "<class 'psycopg.errors.InvalidSchemaName'>"}],
StatementTruncationState.not_truncated.value,
[],
),
(
"dd_admin",
"dd_admin",
"dogs_nofunc",
"SELECT * FROM kennel WHERE id = %s",
123,
"error:explain-failed_function-<class 'psycopg.errors.UndefinedFunction'>",
[{'code': 'failed_function', 'message': "<class 'psycopg.errors.UndefinedFunction'>"}],
StatementTruncationState.not_truncated.value,
[
"Unable to collect execution plans in dbname=dogs_nofunc. Check that the function "
"datadog.explain_statement exists in the database. See "
"https://docs.datadoghq.com/database_monitoring/setup_postgres/troubleshooting#undefined-explain-function"
" for more details: function datadog.explain_statement(unknown) does not exist\nLINE 1: "
"... DDIGNORE */ /* service='datadog-agent' */ SELECT datadog.ex...\n"
" ^\nHINT: No function matches the given "
"name and argument types. You might need to add explicit type casts.\ncode=undefined-explain-function"
" dbname=dogs_nofunc host=stubbed.hostname",
],
),
(
"bob",
"bob",
"datadog_test",
"SELECT city as city0, city as city1, city as city2, city as city3, "
"city as city4, city as city5, city as city6, city as city7, city as city8, city as city9, "
"city as city10, city as city11, city as city12, city as city13, city as city14, city as city15, "
"city as city16, city as city17, city as city18, city as city19, city as city20, city as city21, "
"city as city22, city as city23, city as city24, city as city25, city as city26, city as city27, "
"city as city28, city as city29, city as city30, city as city31, city as city32, city as city33, "
"city as city34, city as city35, city as city36, city as city37, city as city38, city as city39, "
"city as city40, city as city41, city as city42, city as city43, city as city44, city as city45, "
"city as city46, city as city47, city as city48, city as city49, city as city50, city as city51, "
"city as city52, city as city53, city as city54, city as city55, city as city56, city as city57, "
"city as city58, city as city59, city as city60, city as city61 "
"FROM persons WHERE city = %s",
# Use some multi-byte characters (the euro symbol) so we can validate that the code is correctly
# looking at the length in bytes when testing for truncated statements
"€€€€€€€€€€€€€€€€€€€€€€€€€€",
"error:explain-query_truncated-track_activity_query_size=1024",
[{'code': 'query_truncated', 'message': 'track_activity_query_size=1024'}],
StatementTruncationState.truncated.value,
[],
),
],
)
@pytest.mark.parametrize(
"dbstrict,ignore_databases", [(True, []), (False, []), (False, ['foo']), (False, ['postgres'])]
)
@pytest.mark.parametrize(
"collect_raw_query_statement",
[True, False],
)
def test_statement_samples_collect(
aggregator,
integration_check,
dbm_instance,
pg_stat_activity_view,
user,
password,
dbname,
query,
arg,
expected_error_tag,
expected_collection_errors,
expected_statement_truncated,
datadog_agent,
expected_warnings,
dbstrict,
ignore_databases,
collect_raw_query_statement,
):
dbm_instance['pg_stat_activity_view'] = pg_stat_activity_view
dbm_instance['query_metrics']['enabled'] = False
dbm_instance['dbstrict'] = dbstrict
dbm_instance['dbname'] = dbname
dbm_instance['ignore_databases'] = ignore_databases
dbm_instance['collect_raw_query_statement'] = {'enabled': collect_raw_query_statement}
check = integration_check(dbm_instance)
check._connect()
conn = psycopg.connect(
host=HOST, dbname=dbname, user=user, password=password, autocommit=True, cursor_factory=ClientCursor
)
conn.execute("SET client_encoding TO UTF8")
# we are able to see the full query (including the raw parameters) in pg_stat_activity because psycopg uses
# the simple query protocol, sending the whole query as a plain string to postgres.
# if a client is using the extended query protocol with prepare then the query would appear as
# leave connection open until after the check has run to ensure we're able to see the query in
# pg_stat_activity
try:
conn.cursor().execute(query, (arg,))
run_one_check(check)
additional_tags = {"raw_query_statement": "enabled"} if collect_raw_query_statement else {}
tags = _get_expected_tags(check, dbm_instance, with_host=False, db=dbname, **additional_tags)
dbm_samples = aggregator.get_event_platform_events("dbm-samples")
expected_query = query % ('\'' + arg + '\'' if isinstance(arg, str) else arg)
# Find matching events by checking if the expected query starts with the event statement. Using this
# instead of a direct equality check covers cases of truncated statements
matching = [
e
for e in dbm_samples
if e['db']['statement'].encode("utf-8") in expected_query.encode("utf-8") and e['dbm_type'] == 'plan'
]
if POSTGRES_VERSION.split('.')[0] == "9" and pg_stat_activity_view == "pg_stat_activity":
# pg_monitor role exists only in version 10+
assert len(matching) == 0, "did not expect to catch any events"
return
if expected_error_tag:
if len(matching) > 0:
event = matching[0]
assert event['db']['plan']['definition'] is None, "did not expect to collect an execution plan"
aggregator.assert_metric(
"dd.postgres.statement_samples.error",
tags=tags + [expected_error_tag, 'agent_hostname:stubbed.hostname'],
hostname='stubbed.hostname',
)
else:
assert len(matching) == 1, "missing captured event for query: {query}".format(query=query)
event = matching[0]
assert event['db']['query_truncated'] == expected_statement_truncated
assert set(event['ddtags'].split(',')) == set(tags)
assert event['db']['plan']['definition'] is not None, "missing execution plan"
assert 'Plan' in json.loads(event['db']['plan']['definition']), "invalid json execution plan"
# we expect to get a duration because the connections are in "idle" state
assert event['duration']
# validate the events to ensure we've provided an explanation for not providing an exec plan
for event in matching:
assert event['ddagentversion'] == datadog_agent.get_version()
if event['db']['plan']['definition'] is None:
assert event['db']['plan']['collection_errors'] == expected_collection_errors
else:
assert event['db']['plan']['collection_errors'] is None
assert check.warnings == expected_warnings
raw_plan_events = [
e
for e in dbm_samples
if e['db']['statement'].encode("utf-8") in expected_query.encode("utf-8") and e['dbm_type'] == 'rqp'
]
if collect_raw_query_statement:
if expected_error_tag:
assert len(raw_plan_events) == 0
else:
raw_plan_event = raw_plan_events[0]
assert set(raw_plan_event['ddtags'].split(',')) == set(tags)
assert raw_plan_event['db']['plan']['definition'] is not None, "missing raw execution plan"
assert 'Plan' in json.loads(raw_plan_event['db']['plan']['definition']), "invalid json execution plan"
assert raw_plan_event['db']['plan']['raw_signature'] is not None, "missing raw plan signature"
assert event['db']['plan']['raw_signature'] is not None, "missing raw plan signature"
else:
assert len(raw_plan_events) == 0
finally:
conn.close()
@pytest.mark.parametrize("pg_stat_statements_view", ["pg_stat_statements", "datadog.pg_stat_statements()"])
@pytest.mark.parametrize(
"metadata,expected_metadata_payload",
[
(
{'tables_csv': 'persons', 'commands': ['SELECT'], 'comments': ['-- Test comment']},
{'tables': ['persons'], 'commands': ['SELECT'], 'comments': ['-- Test comment']},
),
(
{'tables_csv': '', 'commands': None, 'comments': None},
{'tables': None, 'commands': None, 'comments': None},
),
],
)
def test_statement_metadata(
aggregator,
integration_check,
dbm_instance,
datadog_agent,
pg_stat_statements_view,
metadata,
expected_metadata_payload,
):
"""Tests for metadata in both samples and metrics"""
dbm_instance['pg_stat_statements_view'] = pg_stat_statements_view
dbm_instance['query_samples']['run_sync'] = True
dbm_instance['query_metrics']['run_sync'] = True
# This prevents DBMAsync from skipping job executions, as a job should not be executed
# more frequently than its collection period.
dbm_instance['query_samples']['collection_interval'] = CLOSE_TO_ZERO_INTERVAL
# If query or normalized_query changes, the query_signatures for both will need to be updated as well.
query = '''
-- Test comment
SELECT city FROM persons WHERE city = 'hello'
'''
# Samples will match to the non normalized query signature
query_signature = '8074f7d4fee9fbdf'
normalized_query = 'SELECT city FROM persons WHERE city = ?'
# Metrics will match to the normalized query signature
normalized_query_signature = 'ca85e8d659051b3a'
def obfuscate_sql(query, options=None):
if query.startswith('SELECT city FROM persons WHERE city'):
return json.dumps({'query': normalized_query, 'metadata': metadata})
return json.dumps({'query': query, 'metadata': metadata})
check = integration_check(dbm_instance)
check._connect()
conn = psycopg.connect(host=HOST, dbname="datadog_test", user="bob", password="bob")
cursor = conn.cursor()
# Execute the query with the mocked obfuscate_sql. The result should produce an event payload with the metadata.
with mock.patch.object(datadog_agent, 'obfuscate_sql', passthrough=True) as mock_agent:
mock_agent.side_effect = obfuscate_sql
cursor.execute(
query,
)
run_one_check(check)
cursor.execute(
query,
)
run_one_check(check)
# Test samples metadata, metadata in samples is an object under `db`.
samples = aggregator.get_event_platform_events("dbm-samples")
matching_samples = [s for s in samples if s['db']['query_signature'] == query_signature]