-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
mysql.py
1397 lines (1229 loc) · 68.5 KB
/
mysql.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
# (C) Datadog, Inc. 2010-2017
# (C) Datadog, Inc. Patrick Galbraith <patg@patg.net> 2013
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
import re
import traceback
from contextlib import closing, contextmanager
from collections import defaultdict
# 3p
from six import iteritems
import pymysql
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
# project
from datadog_checks.checks import AgentCheck
from datadog_checks.config import _is_affirmative
GAUGE = "gauge"
RATE = "rate"
COUNT = "count"
MONOTONIC = "monotonic_count"
PROC_NAME = 'mysqld'
# Vars found in "SHOW STATUS;"
STATUS_VARS = {
# Command Metrics
'Slow_queries': ('mysql.performance.slow_queries', RATE),
'Questions': ('mysql.performance.questions', RATE),
'Queries': ('mysql.performance.queries', RATE),
'Com_select': ('mysql.performance.com_select', RATE),
'Com_insert': ('mysql.performance.com_insert', RATE),
'Com_update': ('mysql.performance.com_update', RATE),
'Com_delete': ('mysql.performance.com_delete', RATE),
'Com_replace': ('mysql.performance.com_replace', RATE),
'Com_load': ('mysql.performance.com_load', RATE),
'Com_insert_select': ('mysql.performance.com_insert_select', RATE),
'Com_update_multi': ('mysql.performance.com_update_multi', RATE),
'Com_delete_multi': ('mysql.performance.com_delete_multi', RATE),
'Com_replace_select': ('mysql.performance.com_replace_select', RATE),
# Connection Metrics
'Connections': ('mysql.net.connections', RATE),
'Max_used_connections': ('mysql.net.max_connections', GAUGE),
'Aborted_clients': ('mysql.net.aborted_clients', RATE),
'Aborted_connects': ('mysql.net.aborted_connects', RATE),
# Table Cache Metrics
'Open_files': ('mysql.performance.open_files', GAUGE),
'Open_tables': ('mysql.performance.open_tables', GAUGE),
# Network Metrics
'Bytes_sent': ('mysql.performance.bytes_sent', RATE),
'Bytes_received': ('mysql.performance.bytes_received', RATE),
# Query Cache Metrics
'Qcache_hits': ('mysql.performance.qcache_hits', RATE),
'Qcache_inserts': ('mysql.performance.qcache_inserts', RATE),
'Qcache_lowmem_prunes': ('mysql.performance.qcache_lowmem_prunes', RATE),
# Table Lock Metrics
'Table_locks_waited': ('mysql.performance.table_locks_waited', GAUGE),
'Table_locks_waited_rate': ('mysql.performance.table_locks_waited.rate', RATE),
# Temporary Table Metrics
'Created_tmp_tables': ('mysql.performance.created_tmp_tables', RATE),
'Created_tmp_disk_tables': ('mysql.performance.created_tmp_disk_tables', RATE),
'Created_tmp_files': ('mysql.performance.created_tmp_files', RATE),
# Thread Metrics
'Threads_connected': ('mysql.performance.threads_connected', GAUGE),
'Threads_running': ('mysql.performance.threads_running', GAUGE),
# MyISAM Metrics
'Key_buffer_bytes_unflushed': ('mysql.myisam.key_buffer_bytes_unflushed', GAUGE),
'Key_buffer_bytes_used': ('mysql.myisam.key_buffer_bytes_used', GAUGE),
'Key_read_requests': ('mysql.myisam.key_read_requests', RATE),
'Key_reads': ('mysql.myisam.key_reads', RATE),
'Key_write_requests': ('mysql.myisam.key_write_requests', RATE),
'Key_writes': ('mysql.myisam.key_writes', RATE),
}
# Possibly from SHOW GLOBAL VARIABLES
VARIABLES_VARS = {
'Key_buffer_size': ('mysql.myisam.key_buffer_size', GAUGE),
'Key_cache_utilization': ('mysql.performance.key_cache_utilization', GAUGE),
'max_connections': ('mysql.net.max_connections_available', GAUGE),
'query_cache_size': ('mysql.performance.qcache_size', GAUGE),
'table_open_cache': ('mysql.performance.table_open_cache', GAUGE),
'thread_cache_size': ('mysql.performance.thread_cache_size', GAUGE)
}
INNODB_VARS = {
# InnoDB metrics
'Innodb_data_reads': ('mysql.innodb.data_reads', RATE),
'Innodb_data_writes': ('mysql.innodb.data_writes', RATE),
'Innodb_os_log_fsyncs': ('mysql.innodb.os_log_fsyncs', RATE),
'Innodb_mutex_spin_waits': ('mysql.innodb.mutex_spin_waits', RATE),
'Innodb_mutex_spin_rounds': ('mysql.innodb.mutex_spin_rounds', RATE),
'Innodb_mutex_os_waits': ('mysql.innodb.mutex_os_waits', RATE),
'Innodb_row_lock_waits': ('mysql.innodb.row_lock_waits', RATE),
'Innodb_row_lock_time': ('mysql.innodb.row_lock_time', RATE),
'Innodb_row_lock_current_waits': ('mysql.innodb.row_lock_current_waits', GAUGE),
'Innodb_current_row_locks': ('mysql.innodb.current_row_locks', GAUGE),
'Innodb_buffer_pool_bytes_dirty': ('mysql.innodb.buffer_pool_dirty', GAUGE),
'Innodb_buffer_pool_bytes_free': ('mysql.innodb.buffer_pool_free', GAUGE),
'Innodb_buffer_pool_bytes_used': ('mysql.innodb.buffer_pool_used', GAUGE),
'Innodb_buffer_pool_bytes_total': ('mysql.innodb.buffer_pool_total', GAUGE),
'Innodb_buffer_pool_read_requests': ('mysql.innodb.buffer_pool_read_requests', RATE),
'Innodb_buffer_pool_reads': ('mysql.innodb.buffer_pool_reads', RATE),
'Innodb_buffer_pool_pages_utilization': ('mysql.innodb.buffer_pool_utilization', GAUGE),
}
# Calculated from "SHOW MASTER LOGS;"
BINLOG_VARS = {
'Binlog_space_usage_bytes': ('mysql.binlog.disk_use', GAUGE),
}
# Additional Vars found in "SHOW STATUS;"
# Will collect if [FLAG NAME] is True
OPTIONAL_STATUS_VARS = {
'Binlog_cache_disk_use': ('mysql.binlog.cache_disk_use', GAUGE),
'Binlog_cache_use': ('mysql.binlog.cache_use', GAUGE),
'Handler_commit': ('mysql.performance.handler_commit', RATE),
'Handler_delete': ('mysql.performance.handler_delete', RATE),
'Handler_prepare': ('mysql.performance.handler_prepare', RATE),
'Handler_read_first': ('mysql.performance.handler_read_first', RATE),
'Handler_read_key': ('mysql.performance.handler_read_key', RATE),
'Handler_read_next': ('mysql.performance.handler_read_next', RATE),
'Handler_read_prev': ('mysql.performance.handler_read_prev', RATE),
'Handler_read_rnd': ('mysql.performance.handler_read_rnd', RATE),
'Handler_read_rnd_next': ('mysql.performance.handler_read_rnd_next', RATE),
'Handler_rollback': ('mysql.performance.handler_rollback', RATE),
'Handler_update': ('mysql.performance.handler_update', RATE),
'Handler_write': ('mysql.performance.handler_write', RATE),
'Opened_tables': ('mysql.performance.opened_tables', RATE),
'Qcache_total_blocks': ('mysql.performance.qcache_total_blocks', GAUGE),
'Qcache_free_blocks': ('mysql.performance.qcache_free_blocks', GAUGE),
'Qcache_free_memory': ('mysql.performance.qcache_free_memory', GAUGE),
'Qcache_not_cached': ('mysql.performance.qcache_not_cached', RATE),
'Qcache_queries_in_cache': ('mysql.performance.qcache_queries_in_cache', GAUGE),
'Select_full_join': ('mysql.performance.select_full_join', RATE),
'Select_full_range_join': ('mysql.performance.select_full_range_join', RATE),
'Select_range': ('mysql.performance.select_range', RATE),
'Select_range_check': ('mysql.performance.select_range_check', RATE),
'Select_scan': ('mysql.performance.select_scan', RATE),
'Sort_merge_passes': ('mysql.performance.sort_merge_passes', RATE),
'Sort_range': ('mysql.performance.sort_range', RATE),
'Sort_rows': ('mysql.performance.sort_rows', RATE),
'Sort_scan': ('mysql.performance.sort_scan', RATE),
'Table_locks_immediate': ('mysql.performance.table_locks_immediate', GAUGE),
'Table_locks_immediate_rate': ('mysql.performance.table_locks_immediate.rate', RATE),
'Threads_cached': ('mysql.performance.threads_cached', GAUGE),
'Threads_created': ('mysql.performance.threads_created', MONOTONIC)
}
# Status Vars added in Mysql 5.6.6
OPTIONAL_STATUS_VARS_5_6_6 = {
'Table_open_cache_hits': ('mysql.performance.table_cache_hits', RATE),
'Table_open_cache_misses': ('mysql.performance.table_cache_misses', RATE),
}
# Will collect if [extra_innodb_metrics] is True
OPTIONAL_INNODB_VARS = {
'Innodb_active_transactions': ('mysql.innodb.active_transactions', GAUGE),
'Innodb_buffer_pool_bytes_data': ('mysql.innodb.buffer_pool_data', GAUGE),
'Innodb_buffer_pool_pages_data': ('mysql.innodb.buffer_pool_pages_data', GAUGE),
'Innodb_buffer_pool_pages_dirty': ('mysql.innodb.buffer_pool_pages_dirty', GAUGE),
'Innodb_buffer_pool_pages_flushed': ('mysql.innodb.buffer_pool_pages_flushed', RATE),
'Innodb_buffer_pool_pages_free': ('mysql.innodb.buffer_pool_pages_free', GAUGE),
'Innodb_buffer_pool_pages_total': ('mysql.innodb.buffer_pool_pages_total', GAUGE),
'Innodb_buffer_pool_read_ahead': ('mysql.innodb.buffer_pool_read_ahead', RATE),
'Innodb_buffer_pool_read_ahead_evicted': ('mysql.innodb.buffer_pool_read_ahead_evicted', RATE),
'Innodb_buffer_pool_read_ahead_rnd': ('mysql.innodb.buffer_pool_read_ahead_rnd', GAUGE),
'Innodb_buffer_pool_wait_free': ('mysql.innodb.buffer_pool_wait_free', MONOTONIC),
'Innodb_buffer_pool_write_requests': ('mysql.innodb.buffer_pool_write_requests', RATE),
'Innodb_checkpoint_age': ('mysql.innodb.checkpoint_age', GAUGE),
'Innodb_current_transactions': ('mysql.innodb.current_transactions', GAUGE),
'Innodb_data_fsyncs': ('mysql.innodb.data_fsyncs', RATE),
'Innodb_data_pending_fsyncs': ('mysql.innodb.data_pending_fsyncs', GAUGE),
'Innodb_data_pending_reads': ('mysql.innodb.data_pending_reads', GAUGE),
'Innodb_data_pending_writes': ('mysql.innodb.data_pending_writes', GAUGE),
'Innodb_data_read': ('mysql.innodb.data_read', RATE),
'Innodb_data_written': ('mysql.innodb.data_written', RATE),
'Innodb_dblwr_pages_written': ('mysql.innodb.dblwr_pages_written', RATE),
'Innodb_dblwr_writes': ('mysql.innodb.dblwr_writes', RATE),
'Innodb_hash_index_cells_total': ('mysql.innodb.hash_index_cells_total', GAUGE),
'Innodb_hash_index_cells_used': ('mysql.innodb.hash_index_cells_used', GAUGE),
'Innodb_history_list_length': ('mysql.innodb.history_list_length', GAUGE),
'Innodb_ibuf_free_list': ('mysql.innodb.ibuf_free_list', GAUGE),
'Innodb_ibuf_merged': ('mysql.innodb.ibuf_merged', RATE),
'Innodb_ibuf_merged_delete_marks': ('mysql.innodb.ibuf_merged_delete_marks', RATE),
'Innodb_ibuf_merged_deletes': ('mysql.innodb.ibuf_merged_deletes', RATE),
'Innodb_ibuf_merged_inserts': ('mysql.innodb.ibuf_merged_inserts', RATE),
'Innodb_ibuf_merges': ('mysql.innodb.ibuf_merges', RATE),
'Innodb_ibuf_segment_size': ('mysql.innodb.ibuf_segment_size', GAUGE),
'Innodb_ibuf_size': ('mysql.innodb.ibuf_size', GAUGE),
'Innodb_lock_structs': ('mysql.innodb.lock_structs', RATE),
'Innodb_locked_tables': ('mysql.innodb.locked_tables', GAUGE),
'Innodb_locked_transactions': ('mysql.innodb.locked_transactions', GAUGE),
'Innodb_log_waits': ('mysql.innodb.log_waits', RATE),
'Innodb_log_write_requests': ('mysql.innodb.log_write_requests', RATE),
'Innodb_log_writes': ('mysql.innodb.log_writes', RATE),
'Innodb_lsn_current': ('mysql.innodb.lsn_current', RATE),
'Innodb_lsn_flushed': ('mysql.innodb.lsn_flushed', RATE),
'Innodb_lsn_last_checkpoint': ('mysql.innodb.lsn_last_checkpoint', RATE),
'Innodb_mem_adaptive_hash': ('mysql.innodb.mem_adaptive_hash', GAUGE),
'Innodb_mem_additional_pool': ('mysql.innodb.mem_additional_pool', GAUGE),
'Innodb_mem_dictionary': ('mysql.innodb.mem_dictionary', GAUGE),
'Innodb_mem_file_system': ('mysql.innodb.mem_file_system', GAUGE),
'Innodb_mem_lock_system': ('mysql.innodb.mem_lock_system', GAUGE),
'Innodb_mem_page_hash': ('mysql.innodb.mem_page_hash', GAUGE),
'Innodb_mem_recovery_system': ('mysql.innodb.mem_recovery_system', GAUGE),
'Innodb_mem_thread_hash': ('mysql.innodb.mem_thread_hash', GAUGE),
'Innodb_mem_total': ('mysql.innodb.mem_total', GAUGE),
'Innodb_os_file_fsyncs': ('mysql.innodb.os_file_fsyncs', RATE),
'Innodb_os_file_reads': ('mysql.innodb.os_file_reads', RATE),
'Innodb_os_file_writes': ('mysql.innodb.os_file_writes', RATE),
'Innodb_os_log_pending_fsyncs': ('mysql.innodb.os_log_pending_fsyncs', GAUGE),
'Innodb_os_log_pending_writes': ('mysql.innodb.os_log_pending_writes', GAUGE),
'Innodb_os_log_written': ('mysql.innodb.os_log_written', RATE),
'Innodb_pages_created': ('mysql.innodb.pages_created', RATE),
'Innodb_pages_read': ('mysql.innodb.pages_read', RATE),
'Innodb_pages_written': ('mysql.innodb.pages_written', RATE),
'Innodb_pending_aio_log_ios': ('mysql.innodb.pending_aio_log_ios', GAUGE),
'Innodb_pending_aio_sync_ios': ('mysql.innodb.pending_aio_sync_ios', GAUGE),
'Innodb_pending_buffer_pool_flushes': ('mysql.innodb.pending_buffer_pool_flushes', GAUGE),
'Innodb_pending_checkpoint_writes': ('mysql.innodb.pending_checkpoint_writes', GAUGE),
'Innodb_pending_ibuf_aio_reads': ('mysql.innodb.pending_ibuf_aio_reads', GAUGE),
'Innodb_pending_log_flushes': ('mysql.innodb.pending_log_flushes', GAUGE),
'Innodb_pending_log_writes': ('mysql.innodb.pending_log_writes', GAUGE),
'Innodb_pending_normal_aio_reads': ('mysql.innodb.pending_normal_aio_reads', GAUGE),
'Innodb_pending_normal_aio_writes': ('mysql.innodb.pending_normal_aio_writes', GAUGE),
'Innodb_queries_inside': ('mysql.innodb.queries_inside', GAUGE),
'Innodb_queries_queued': ('mysql.innodb.queries_queued', GAUGE),
'Innodb_read_views': ('mysql.innodb.read_views', GAUGE),
'Innodb_rows_deleted': ('mysql.innodb.rows_deleted', RATE),
'Innodb_rows_inserted': ('mysql.innodb.rows_inserted', RATE),
'Innodb_rows_read': ('mysql.innodb.rows_read', RATE),
'Innodb_rows_updated': ('mysql.innodb.rows_updated', RATE),
'Innodb_s_lock_os_waits': ('mysql.innodb.s_lock_os_waits', RATE),
'Innodb_s_lock_spin_rounds': ('mysql.innodb.s_lock_spin_rounds', RATE),
'Innodb_s_lock_spin_waits': ('mysql.innodb.s_lock_spin_waits', RATE),
'Innodb_semaphore_wait_time': ('mysql.innodb.semaphore_wait_time', GAUGE),
'Innodb_semaphore_waits': ('mysql.innodb.semaphore_waits', GAUGE),
'Innodb_tables_in_use': ('mysql.innodb.tables_in_use', GAUGE),
'Innodb_x_lock_os_waits': ('mysql.innodb.x_lock_os_waits', RATE),
'Innodb_x_lock_spin_rounds': ('mysql.innodb.x_lock_spin_rounds', RATE),
'Innodb_x_lock_spin_waits': ('mysql.innodb.x_lock_spin_waits', RATE),
}
GALERA_VARS = {
'wsrep_cluster_size': ('mysql.galera.wsrep_cluster_size', GAUGE),
'wsrep_local_recv_queue_avg': ('mysql.galera.wsrep_local_recv_queue_avg', GAUGE),
'wsrep_flow_control_paused': ('mysql.galera.wsrep_flow_control_paused', GAUGE),
'wsrep_cert_deps_distance': ('mysql.galera.wsrep_cert_deps_distance', GAUGE),
'wsrep_local_send_queue_avg': ('mysql.galera.wsrep_local_send_queue_avg', GAUGE),
}
PERFORMANCE_VARS = {
'query_run_time_avg': ('mysql.performance.query_run_time.avg', GAUGE),
'perf_digest_95th_percentile_avg_us': ('mysql.performance.digest_95th_percentile.avg_us', GAUGE),
}
SCHEMA_VARS = {
'information_schema_size': ('mysql.info.schema.size', GAUGE),
}
REPLICA_VARS = {
'Seconds_Behind_Master': ('mysql.replication.seconds_behind_master', GAUGE),
'Slaves_connected': ('mysql.replication.slaves_connected', GAUGE),
}
SYNTHETIC_VARS = {
'Qcache_utilization': ('mysql.performance.qcache.utilization', GAUGE),
'Qcache_instant_utilization': ('mysql.performance.qcache.utilization.instant', GAUGE),
}
class MySql(AgentCheck):
SERVICE_CHECK_NAME = 'mysql.can_connect'
SLAVE_SERVICE_CHECK_NAME = 'mysql.replication.slave_running'
DEFAULT_MAX_CUSTOM_QUERIES = 20
def __init__(self, name, init_config, agentConfig, instances=None):
AgentCheck.__init__(self, name, init_config, agentConfig, instances)
self.mysql_version = {}
self.qcache_stats = {}
def get_library_versions(self):
return {"pymysql": pymysql.__version__}
def check(self, instance):
host, port, user, password, mysql_sock, \
defaults_file, tags, options, queries, ssl, \
connect_timeout, max_custom_queries = \
self._get_config(instance)
self._set_qcache_stats()
if (not host or not user) and not defaults_file:
raise Exception("Mysql host and user are needed.")
with self._connect(host, port, mysql_sock, user,
password, defaults_file, ssl, connect_timeout, tags) as db:
try:
# Metadata collection
self._collect_metadata(db, host)
# Metric collection
self._collect_metrics(host, db, tags, options, queries, max_custom_queries)
self._collect_system_metrics(host, db, tags)
# keeping track of these:
self._put_qcache_stats()
except Exception as e:
self.log.exception("error!")
raise e
def _get_config(self, instance):
self.host = instance.get('server', '')
self.port = int(instance.get('port', 0))
self.mysql_sock = instance.get('sock', '')
self.defaults_file = instance.get('defaults_file', '')
user = instance.get('user', '')
password = str(instance.get('pass', ''))
tags = instance.get('tags', [])
options = instance.get('options', {}) or {} # options could be None if empty in the YAML
queries = instance.get('queries', [])
ssl = instance.get('ssl', {})
connect_timeout = instance.get('connect_timeout', 10)
max_custom_queries = instance.get('max_custom_queries', self.DEFAULT_MAX_CUSTOM_QUERIES)
return (self.host, self.port, user, password, self.mysql_sock,
self.defaults_file, tags, options, queries, ssl, connect_timeout, max_custom_queries)
def _set_qcache_stats(self):
host_key = self._get_host_key()
qcache_st = self.qcache_stats.get(host_key, (None, None, None))
self._qcache_hits = qcache_st[0]
self._qcache_inserts = qcache_st[1]
self._qcache_not_cached = qcache_st[2]
def _put_qcache_stats(self):
host_key = self._get_host_key()
self.qcache_stats[host_key] = (
self._qcache_hits,
self._qcache_inserts,
self._qcache_not_cached
)
def _get_host_key(self):
if self.defaults_file:
return self.defaults_file
hostkey = self.host
if self.mysql_sock:
hostkey = "{0}:{1}".format(hostkey, self.mysql_sock)
elif self.port:
hostkey = "{0}:{1}".format(hostkey, self.port)
return hostkey
@contextmanager
def _connect(self, host, port, mysql_sock, user, password, defaults_file, ssl, connect_timeout, tags):
self.service_check_tags = [
'server:%s' % (mysql_sock if mysql_sock != '' else host),
'port:%s' % ('unix_socket' if port == 0 else port)
]
if tags is not None:
self.service_check_tags.extend(tags)
db = None
try:
ssl = dict(ssl) if ssl else None
if defaults_file != '':
db = pymysql.connect(
read_default_file=defaults_file,
ssl=ssl,
connect_timeout=connect_timeout
)
elif mysql_sock != '':
self.service_check_tags = [
'server:{0}'.format(mysql_sock),
'port:unix_socket'
] + tags
db = pymysql.connect(
unix_socket=mysql_sock,
user=user,
passwd=password,
connect_timeout=connect_timeout
)
elif port:
db = pymysql.connect(
host=host,
port=port,
user=user,
passwd=password,
ssl=ssl,
connect_timeout=connect_timeout
)
else:
db = pymysql.connect(
host=host,
user=user,
passwd=password,
ssl=ssl,
connect_timeout=connect_timeout
)
self.log.debug("Connected to MySQL")
self.service_check_tags = list(set(self.service_check_tags))
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK,
tags=self.service_check_tags)
yield db
except Exception:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
tags=self.service_check_tags)
raise
finally:
if db:
db.close()
def _collect_metrics(self, host, db, tags, options, queries, max_custom_queries):
# Get aggregate of all VARS we want to collect
metrics = STATUS_VARS
# collect results from db
results = self._get_stats_from_status(db)
results.update(self._get_stats_from_variables(db))
if (not _is_affirmative(options.get('disable_innodb_metrics', False)) and self._is_innodb_engine_enabled(db)):
results.update(self._get_stats_from_innodb_status(db))
innodb_keys = [
'Innodb_page_size',
'Innodb_buffer_pool_pages_data',
'Innodb_buffer_pool_pages_dirty',
'Innodb_buffer_pool_pages_total',
'Innodb_buffer_pool_pages_free',
]
for inno_k in innodb_keys:
results[inno_k] = self._collect_scalar(inno_k, results)
try:
innodb_page_size = results['Innodb_page_size']
innodb_buffer_pool_pages_used = results['Innodb_buffer_pool_pages_total'] - \
results['Innodb_buffer_pool_pages_free']
if 'Innodb_buffer_pool_bytes_data' not in results:
results[
'Innodb_buffer_pool_bytes_data'] = results['Innodb_buffer_pool_pages_data'] * innodb_page_size
if 'Innodb_buffer_pool_bytes_dirty' not in results:
results[
'Innodb_buffer_pool_bytes_dirty'] = results['Innodb_buffer_pool_pages_dirty'] * innodb_page_size
if 'Innodb_buffer_pool_bytes_free' not in results:
results[
'Innodb_buffer_pool_bytes_free'] = results['Innodb_buffer_pool_pages_free'] * innodb_page_size
if 'Innodb_buffer_pool_bytes_total' not in results:
results[
'Innodb_buffer_pool_bytes_total'] = results['Innodb_buffer_pool_pages_total'] * innodb_page_size
if 'Innodb_buffer_pool_pages_utilization' not in results:
results['Innodb_buffer_pool_pages_utilization'] = innodb_buffer_pool_pages_used / \
results['Innodb_buffer_pool_pages_total']
if 'Innodb_buffer_pool_bytes_used' not in results:
results[
'Innodb_buffer_pool_bytes_used'] = innodb_buffer_pool_pages_used * innodb_page_size
except (KeyError, TypeError) as e:
self.log.error("Not all InnoDB buffer pool metrics are available, unable to compute: {0}".format(e))
if _is_affirmative(options.get('extra_innodb_metrics', False)):
self.log.debug("Collecting Extra Innodb Metrics")
metrics.update(OPTIONAL_INNODB_VARS)
# Binary log statistics
if self._get_variable_enabled(results, 'log_bin'):
results[
'Binlog_space_usage_bytes'] = self._get_binary_log_stats(db)
# Compute key cache utilization metric
key_blocks_unused = self._collect_scalar('Key_blocks_unused', results)
key_cache_block_size = self._collect_scalar('key_cache_block_size', results)
key_buffer_size = self._collect_scalar('key_buffer_size', results)
results['Key_buffer_size'] = key_buffer_size
try:
# can be null if the unit is missing in the user config (4 instead of 4G for eg.)
if key_buffer_size != 0:
key_cache_utilization = 1 - ((key_blocks_unused * key_cache_block_size) / key_buffer_size)
results['Key_cache_utilization'] = key_cache_utilization
results['Key_buffer_bytes_used'] = self._collect_scalar(
'Key_blocks_used', results) * key_cache_block_size
results['Key_buffer_bytes_unflushed'] = self._collect_scalar(
'Key_blocks_not_flushed', results) * key_cache_block_size
except TypeError as e:
self.log.error("Not all Key metrics are available, unable to compute: {0}".format(e))
metrics.update(VARIABLES_VARS)
metrics.update(INNODB_VARS)
metrics.update(BINLOG_VARS)
if _is_affirmative(options.get('extra_status_metrics', False)):
self.log.debug("Collecting Extra Status Metrics")
metrics.update(OPTIONAL_STATUS_VARS)
if self._version_compatible(db, host, (5, 6, 6)):
metrics.update(OPTIONAL_STATUS_VARS_5_6_6)
if _is_affirmative(options.get('galera_cluster', False)):
# already in result-set after 'SHOW STATUS' just add vars to collect
self.log.debug("Collecting Galera Metrics.")
metrics.update(GALERA_VARS)
performance_schema_enabled = self._get_variable_enabled(results, 'performance_schema')
above_560 = self._version_compatible(db, host, (5, 6, 0))
if _is_affirmative(options.get('extra_performance_metrics', False)) and above_560 and \
performance_schema_enabled:
# report avg query response time per schema to Datadog
results['perf_digest_95th_percentile_avg_us'] = self._get_query_exec_time_95th_us(db)
results['query_run_time_avg'] = self._query_exec_time_per_schema(db)
metrics.update(PERFORMANCE_VARS)
if _is_affirmative(options.get('schema_size_metrics', False)):
# report avg query response time per schema to Datadog
results['information_schema_size'] = self._query_size_per_schema(db)
metrics.update(SCHEMA_VARS)
if _is_affirmative(options.get('replication', False)):
# Get replica stats
is_mariadb = self._get_is_mariadb(db, host)
replication_channel = options.get('replication_channel')
if replication_channel:
self.service_check_tags.append("channel:{0}".format(replication_channel))
tags.append("channel:{0}".format(replication_channel))
results.update(self._get_replica_stats(db, is_mariadb, replication_channel))
nonblocking = _is_affirmative(options.get('replication_non_blocking_status', False))
results.update(self._get_slave_status(db, above_560, nonblocking))
metrics.update(REPLICA_VARS)
# get slave running form global status page
slave_running_status = AgentCheck.UNKNOWN
slave_running = self._collect_string('Slave_running', results)
binlog_running = results.get('Binlog_enabled', False)
# slaves will only be collected iff user has PROCESS privileges.
slaves = self._collect_scalar('Slaves_connected', results)
slave_io_running = self._collect_type('Slave_IO_Running', results, dict)
slave_sql_running = self._collect_type('Slave_SQL_Running', results, dict)
if slave_io_running:
slave_io_running = any(v.lower().strip() == 'yes' for v in slave_io_running.itervalues())
if slave_sql_running:
slave_sql_running = any(v.lower().strip() == 'yes' for v in slave_sql_running.itervalues())
# MySQL 5.7.x might not have 'Slave_running'. See: https://bugs.mysql.com/bug.php?id=78544
# look at replica vars collected at the top of if-block
if self._version_compatible(db, host, (5, 7, 0)):
if not (slave_io_running is None and slave_sql_running is None):
if slave_io_running and slave_sql_running:
slave_running_status = AgentCheck.OK
elif not slave_io_running and not slave_sql_running:
slave_running_status = AgentCheck.CRITICAL
else:
# not everything is running smoothly
slave_running_status = AgentCheck.WARNING
elif slave_running.lower().strip() == 'off':
if not (slave_io_running is None and slave_sql_running is None):
if not slave_io_running and not slave_sql_running:
slave_running_status = AgentCheck.CRITICAL
# if we don't yet have a status - inspect
if slave_running_status == AgentCheck.UNKNOWN:
if self._is_master(slaves, results): # master
if slaves > 0 and binlog_running:
slave_running_status = AgentCheck.OK
else:
slave_running_status = AgentCheck.WARNING
elif slave_running: # slave (or standalone)
if slave_running.lower().strip() == 'on':
slave_running_status = AgentCheck.OK
else:
slave_running_status = AgentCheck.CRITICAL
# deprecated in favor of service_check("mysql.replication.slave_running")
self.gauge(self.SLAVE_SERVICE_CHECK_NAME, (1 if slave_running_status == AgentCheck.OK else 0), tags=tags)
self.service_check(self.SLAVE_SERVICE_CHECK_NAME, slave_running_status, tags=self.service_check_tags)
# "synthetic" metrics
metrics.update(SYNTHETIC_VARS)
self._compute_synthetic_results(results)
# remove uncomputed metrics
for k in SYNTHETIC_VARS:
if k not in results:
metrics.pop(k, None)
# add duped metrics - reporting some as both rate and gauge
dupes = [('Table_locks_waited', 'Table_locks_waited_rate'),
('Table_locks_immediate', 'Table_locks_immediate_rate')]
for src, dst in dupes:
if src in results:
results[dst] = results[src]
self._submit_metrics(metrics, results, tags)
# Collect custom query metrics
# Max of 20 queries allowed
if isinstance(queries, list):
for index, check in enumerate(queries[:max_custom_queries]):
total_tags = tags + check.get('tags', [])
self._collect_dict(check['type'],
{check['field']: check['metric']},
check['query'],
db,
tags=total_tags)
if len(queries) > max_custom_queries:
self.warning("Maximum number (%s) of custom queries reached. Skipping the rest."
% max_custom_queries)
def _is_master(self, slaves, results):
# master uuid only collected in slaves
master_host = self._collect_string('Master_Host', results)
if slaves > 0 or not master_host:
return True
return False
def _collect_metadata(self, db, host):
version = self._get_version(db, host)
self.service_metadata('version', ".".join(version))
def _submit_metrics(self, variables, dbResults, tags):
for variable, metric in variables.iteritems():
metric_name, metric_type = metric
for tag, value in self._collect_all_scalars(variable, dbResults):
metric_tags = list(tags)
if tag:
metric_tags.append(tag)
if value is not None:
if metric_type == RATE:
self.rate(metric_name, value, tags=metric_tags)
elif metric_type == GAUGE:
self.gauge(metric_name, value, tags=metric_tags)
elif metric_type == COUNT:
self.count(metric_name, value, tags=metric_tags)
elif metric_type == MONOTONIC:
self.monotonic_count(metric_name, value, tags=metric_tags)
def _version_compatible(self, db, host, compat_version):
# some patch version numbers contain letters (e.g. 5.0.51a)
# so let's be careful when we compute the version number
try:
mysql_version = self._get_version(db, host)
except Exception as e:
self.warning("Cannot compute mysql version, assuming it's older.: %s"
% str(e))
return False
self.log.debug("MySQL version %s" % mysql_version)
patchlevel = int(re.match(r"([0-9]+)", mysql_version[2]).group(1))
version = (int(mysql_version[0]), int(mysql_version[1]), patchlevel)
return version >= compat_version
def _get_version(self, db, host):
hostkey = self._get_host_key()
if hostkey in self.mysql_version:
version = self.mysql_version[hostkey]
return version
# Get MySQL version
with closing(db.cursor()) as cursor:
cursor.execute('SELECT VERSION()')
result = cursor.fetchone()
# Version might include a description e.g. 4.1.26-log.
# See
# http://dev.mysql.com/doc/refman/4.1/en/information-functions.html#function_version
version = result[0].split('-')
version = version[0].split('.')
self.mysql_version[hostkey] = version
return version
def _get_is_mariadb(self, db, host):
with closing(db.cursor()) as cursor:
cursor.execute('SELECT VERSION() LIKE "%MariaDB%"')
result = cursor.fetchone()
return result[0] == 1
def _collect_all_scalars(self, key, dictionary):
if key not in dictionary or dictionary[key] is None:
yield None, None
elif isinstance(dictionary[key], dict):
for tag, _ in dictionary[key].iteritems():
yield tag, self._collect_type(tag, dictionary[key], float)
else:
yield None, self._collect_type(key, dictionary, float)
def _collect_scalar(self, key, dict):
return self._collect_type(key, dict, float)
def _collect_string(self, key, dict):
return self._collect_type(key, dict, unicode)
def _collect_type(self, key, dict, the_type):
self.log.debug("Collecting data with %s" % key)
if key not in dict:
self.log.debug("%s returned None" % key)
return None
self.log.debug("Collecting done, value %s" % dict[key])
return the_type(dict[key])
def _collect_dict(self, metric_type, field_metric_map, query, db, tags):
"""
Query status and get a dictionary back.
Extract each field out of the dictionary
and stuff it in the corresponding metric.
query: show status...
field_metric_map: {"Seconds_behind_master": "mysqlSecondsBehindMaster"}
"""
try:
with closing(db.cursor()) as cursor:
cursor.execute(query)
result = cursor.fetchone()
if result is not None:
for field in field_metric_map.keys():
# Get the agent metric name from the column name
metric = field_metric_map[field]
# Find the column name in the cursor description to identify the column index
# http://www.python.org/dev/peps/pep-0249/
# cursor.description is a tuple of (column_name, ..., ...)
try:
col_idx = [d[0].lower() for d in cursor.description].index(field.lower())
self.log.debug("Collecting metric: %s" % metric)
if result[col_idx] is not None:
self.log.debug(
"Collecting done, value %s" % result[col_idx])
if metric_type == GAUGE:
self.gauge(metric, float(
result[col_idx]), tags=tags)
elif metric_type == RATE:
self.rate(metric, float(
result[col_idx]), tags=tags)
else:
self.gauge(metric, float(
result[col_idx]), tags=tags)
else:
self.log.debug(
"Received value is None for index %d" % col_idx)
except ValueError:
self.log.exception("Cannot find %s in the columns %s"
% (field, cursor.description))
except Exception:
self.warning("Error while running %s\n%s" %
(query, traceback.format_exc()))
self.log.exception("Error while running %s" % query)
def _collect_system_metrics(self, host, db, tags):
pid = None
# The server needs to run locally, accessed by TCP or socket
if host in ["localhost", "127.0.0.1", "0.0.0.0"] or db.port == long(0):
pid = self._get_server_pid(db)
if pid:
self.log.debug("System metrics for mysql w\ pid: %s" % pid)
# At last, get mysql cpu data out of psutil or procfs
try:
ucpu, scpu = None, None
if PSUTIL_AVAILABLE:
proc = psutil.Process(pid)
ucpu = proc.cpu_times()[0]
scpu = proc.cpu_times()[1]
if ucpu and scpu:
self.rate("mysql.performance.user_time", ucpu, tags=tags)
# should really be system_time
self.rate("mysql.performance.kernel_time", scpu, tags=tags)
self.rate("mysql.performance.cpu_time", ucpu+scpu, tags=tags)
except Exception:
self.warning("Error while reading mysql (pid: %s) procfs data\n%s"
% (pid, traceback.format_exc()))
def _get_pid_file_variable(self, db):
"""
Get the `pid_file` variable
"""
pid_file = None
try:
with closing(db.cursor()) as cursor:
cursor.execute("SHOW VARIABLES LIKE 'pid_file'")
pid_file = cursor.fetchone()[1]
except Exception:
self.warning("Error while fetching pid_file variable of MySQL.")
return pid_file
def _get_server_pid(self, db):
pid = None
# Try to get pid from pid file, it can fail for permission reason
pid_file = self._get_pid_file_variable(db)
if pid_file is not None:
self.log.debug("pid file: %s" % str(pid_file))
try:
f = open(pid_file)
pid = int(f.readline())
f.close()
except IOError:
self.log.debug("Cannot read mysql pid file %s" % pid_file)
# If pid has not been found, read it from ps
if pid is None and PSUTIL_AVAILABLE:
for proc in psutil.process_iter():
try:
if proc.name() == PROC_NAME:
pid = proc.pid
except (psutil.AccessDenied, psutil.ZombieProcess, psutil.NoSuchProcess):
continue
except Exception:
self.log.exception("Error while fetching mysql pid from psutil")
return pid
def _get_stats_from_status(self, db):
with closing(db.cursor()) as cursor:
cursor.execute("SHOW /*!50002 GLOBAL */ STATUS;")
results = dict(cursor.fetchall())
return results
def _get_stats_from_variables(self, db):
with closing(db.cursor()) as cursor:
cursor.execute("SHOW GLOBAL VARIABLES;")
results = dict(cursor.fetchall())
return results
def _get_binary_log_stats(self, db):
try:
with closing(db.cursor()) as cursor:
cursor.execute("SHOW BINARY LOGS;")
master_logs = dict(cursor.fetchall())
binary_log_space = 0
for key, value in master_logs.iteritems():
binary_log_space += value
return binary_log_space
except (pymysql.err.InternalError, pymysql.err.OperationalError) as e:
self.warning("Privileges error accessing the BINARY LOGS (must grant REPLICATION CLIENT): %s" % str(e))
return None
def _is_innodb_engine_enabled(self, db):
# Whether InnoDB engine is available or not can be found out either
# from the output of SHOW ENGINES or from information_schema.ENGINES
# table. Later is choosen because that involves no string parsing.
try:
with closing(db.cursor()) as cursor:
cursor.execute(
"select engine from information_schema.ENGINES where engine='InnoDB' and \
support != 'no' and support != 'disabled'"
)
return (cursor.rowcount > 0)
except (pymysql.err.InternalError, pymysql.err.OperationalError, pymysql.err.NotSupportedError) as e:
self.warning("Possibly innodb stats unavailable - error querying engines table: %s" % str(e))
return False
def _get_replica_stats(self, db, is_mariadb, replication_channel):
replica_results = defaultdict(dict)
try:
with closing(db.cursor(pymysql.cursors.DictCursor)) as cursor:
if is_mariadb and replication_channel:
cursor.execute("SET @@default_master_connection = '{0}';".format(replication_channel))
cursor.execute("SHOW SLAVE STATUS;")
elif replication_channel:
cursor.execute("SHOW SLAVE STATUS FOR CHANNEL '{0}';".format(replication_channel))
else:
cursor.execute("SHOW SLAVE STATUS;")
for slave_result in cursor.fetchall():
# MySQL <5.7 does not have Channel_Name.
# For MySQL >=5.7 'Channel_Name' is set to an empty string by default
channel = replication_channel or slave_result.get('Channel_Name') or 'default'
for key, value in iteritems(slave_result):
if value is not None:
replica_results[key]['channel:{0}'.format(channel)] = value
except (pymysql.err.InternalError, pymysql.err.OperationalError) as e:
errno, msg = e.args
if errno == 1617 and msg == "There is no master connection '{0}'".format(replication_channel):
# MariaDB complains when you try to get slave status with a
# connection name on the master, without connection name it
# responds an empty string as expected.
# Mysql behaves the same with or without connection name.
pass
else:
self.warning("Privileges error getting replication status (must grant REPLICATION CLIENT): %s" % str(e))
try:
with closing(db.cursor(pymysql.cursors.DictCursor)) as cursor:
cursor.execute("SHOW MASTER STATUS;")
binlog_results = cursor.fetchone()
if binlog_results:
replica_results.update({'Binlog_enabled': True})
except (pymysql.err.InternalError, pymysql.err.OperationalError) as e:
self.warning("Privileges error getting binlog information (must grant REPLICATION CLIENT): %s" % str(e))
return replica_results
def _get_slave_status(self, db, above_560, nonblocking):
"""
Retrieve the slaves' statuses using:
1. The `performance_schema.threads` table. Non-blocking, requires version > 5.6.0
2. The `information_schema.processlist` table. Blocking
"""
try:
with closing(db.cursor()) as cursor:
if above_560 and nonblocking:
# Query `performance_schema.threads` instead of `
# information_schema.processlist` to avoid mutex impact on performance.
cursor.execute("SELECT THREAD_ID, NAME FROM performance_schema.threads WHERE NAME LIKE '%worker'")
else:
cursor.execute("SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND LIKE '%Binlog dump%'")
slave_results = cursor.fetchall()
slaves = 0
for row in slave_results:
slaves += 1
return {'Slaves_connected': slaves}
except (pymysql.err.InternalError, pymysql.err.OperationalError) as e:
self.warning("Privileges error accessing the process tables (must grant PROCESS): %s" % str(e))
return {}
def _are_values_numeric(self, array):
return all([v.isdigit() for v in array])
def _get_stats_from_innodb_status(self, db):
# There are a number of important InnoDB metrics that are reported in
# InnoDB status but are not otherwise present as part of the STATUS
# variables in MySQL. Majority of these metrics are reported though
# as a part of STATUS variables in Percona Server and MariaDB.
# Requires querying user to have PROCESS privileges.
try:
with closing(db.cursor()) as cursor:
cursor.execute("SHOW /*!50000 ENGINE*/ INNODB STATUS")
except (pymysql.err.InternalError, pymysql.err.OperationalError, pymysql.err.NotSupportedError) as e:
self.warning("Privilege error or engine unavailable accessing the INNODB status \
tables (must grant PROCESS): %s" % str(e))
return {}
if cursor.rowcount < 1:
# No data from SHOW ENGINE STATUS, even though the engine is enabled.
# EG: This could be an Aurora Read Instance
self.warning("""'SHOW ENGINE INNODB STATUS' returned no data.
If you are running an Aurora Read Instace, \
this is expected and you should disable the innodb metrics collection""")
return {}
innodb_status = cursor.fetchone()
innodb_status_text = innodb_status[2]
results = defaultdict(int)
# Here we now parse InnoDB STATUS one line at a time
# This is heavily inspired by the Percona monitoring plugins work
txn_seen = False
prev_line = ''
# Only return aggregated buffer pool metrics
buffer_id = -1
for line in innodb_status_text.splitlines():
line = line.strip()
row = re.split(" +", line)
row = [item.strip(',') for item in row]
row = [item.strip(';') for item in row]
row = [item.strip('[') for item in row]
row = [item.strip(']') for item in row]
if line.startswith('---BUFFER POOL'):
buffer_id = long(row[2])
# SEMAPHORES
if line.find('Mutex spin waits') == 0:
# Mutex spin waits 79626940, rounds 157459864, OS waits 698719