|
| 1 | +# (C) Datadog, Inc. 2026-present |
| 2 | +# All rights reserved |
| 3 | +# Licensed under a 3-clause BSD style license (see LICENSE) |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +from clickhouse_connect.driver.exceptions import OperationalError |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from datadog_checks.clickhouse import ClickhouseCheck |
| 12 | + from datadog_checks.clickhouse.config_models.instance import SchemaMetrics |
| 13 | + |
| 14 | +from datadog_checks.base import AgentCheck |
| 15 | +from datadog_checks.base.utils.db.utils import DBMAsyncJob |
| 16 | +from datadog_checks.base.utils.tracking import tracked_method |
| 17 | + |
| 18 | +DEFAULT_COLLECTION_INTERVAL = 60 |
| 19 | + |
| 20 | +_TABLE_SIZES_QUERY = """\ |
| 21 | +SELECT |
| 22 | + database, |
| 23 | + name, |
| 24 | + toInt64(total_rows) AS total_rows, |
| 25 | + toInt64(total_bytes) AS total_bytes |
| 26 | +FROM {tables_table} |
| 27 | +WHERE database NOT IN ('system', 'INFORMATION_SCHEMA', 'information_schema') |
| 28 | +LIMIT 1 BY database, name |
| 29 | +""" |
| 30 | + |
| 31 | +_VIEW_REFRESHES_QUERY = """\ |
| 32 | +SELECT |
| 33 | + database, |
| 34 | + view, |
| 35 | + hostName() AS host, |
| 36 | + status, |
| 37 | + exception, |
| 38 | + toInt64(toUnixTimestamp(last_success_time)) AS last_refresh_time, |
| 39 | + toInt64(toUnixTimestamp(next_refresh_time)) AS next_refresh_time, |
| 40 | + toInt64(written_rows) AS written_rows, |
| 41 | + toInt64(written_bytes) AS written_bytes |
| 42 | +FROM {view_refreshes_table} |
| 43 | +LIMIT 1 BY database, view, host |
| 44 | +""" |
| 45 | + |
| 46 | +_VIEW_REFRESH_STATUS_MAP = { |
| 47 | + 'Scheduled': AgentCheck.OK, |
| 48 | + 'Running': AgentCheck.OK, |
| 49 | + 'WaitingForDependencies': AgentCheck.WARNING, |
| 50 | + 'Disabled': AgentCheck.UNKNOWN, |
| 51 | + 'Error': AgentCheck.CRITICAL, |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +def agent_check_getter(self): |
| 56 | + return self._check |
| 57 | + |
| 58 | + |
| 59 | +class ClickhouseTableMetrics(DBMAsyncJob): |
| 60 | + """Per-table size and per-view refresh gauges from system.tables and system.view_refreshes.""" |
| 61 | + |
| 62 | + def __init__(self, check: ClickhouseCheck, config: SchemaMetrics): |
| 63 | + collection_interval = config.collection_interval |
| 64 | + if collection_interval is None or collection_interval <= 0: |
| 65 | + collection_interval = DEFAULT_COLLECTION_INTERVAL |
| 66 | + |
| 67 | + super(ClickhouseTableMetrics, self).__init__( |
| 68 | + check, |
| 69 | + rate_limit=1 / collection_interval, |
| 70 | + run_sync=config.run_sync, |
| 71 | + enabled=config.enabled, |
| 72 | + dbms='clickhouse', |
| 73 | + min_collection_interval=check._config.min_collection_interval, |
| 74 | + expected_db_exceptions=(Exception,), |
| 75 | + job_name='clickhouse-table-metrics', |
| 76 | + ) |
| 77 | + self._check = check |
| 78 | + self._config = config |
| 79 | + self._collection_interval = collection_interval |
| 80 | + self._db_client = None |
| 81 | + self._view_refreshes_unsupported_logged = False |
| 82 | + self._view_refreshes_permission_logged = False |
| 83 | + self._view_refreshes_skip = False |
| 84 | + |
| 85 | + def cancel(self): |
| 86 | + super(ClickhouseTableMetrics, self).cancel() |
| 87 | + self._close_db_client() |
| 88 | + |
| 89 | + def _close_db_client(self): |
| 90 | + if self._db_client: |
| 91 | + try: |
| 92 | + self._db_client.close() |
| 93 | + except Exception as e: |
| 94 | + self._log.debug("Error closing table-metrics client: %s", e) |
| 95 | + self._db_client = None |
| 96 | + |
| 97 | + def _execute_query(self, query: str) -> list: |
| 98 | + if self._db_client is None: |
| 99 | + self._db_client = self._check.create_dbm_client() |
| 100 | + self._db_client.set_client_setting('max_execution_time', self._collection_interval) |
| 101 | + try: |
| 102 | + return self._db_client.query(query).result_rows |
| 103 | + except OperationalError as e: |
| 104 | + self._log.warning("Connection error on table-metrics query, will reconnect: %s", e) |
| 105 | + self._close_db_client() |
| 106 | + raise |
| 107 | + |
| 108 | + @tracked_method(agent_check_getter=agent_check_getter) |
| 109 | + def run_job(self): |
| 110 | + self._emit_table_size_gauges() |
| 111 | + self._collect_view_refresh_metrics() |
| 112 | + |
| 113 | + def _emit_table_size_gauges(self) -> None: |
| 114 | + try: |
| 115 | + rows = self._execute_query(_TABLE_SIZES_QUERY.format(tables_table=self._check.get_system_table('tables'))) |
| 116 | + except Exception: |
| 117 | + self._log.exception("Failed to collect clickhouse table sizes") |
| 118 | + return |
| 119 | + |
| 120 | + # Drop the instance-level `db:` base tag (the connection database) so each |
| 121 | + # per-table series carries exactly one `db:` tag — the table's own database. |
| 122 | + base_tags = [t for t in self._check.tags if not t.startswith('db:')] |
| 123 | + for database, name, total_rows, total_bytes in rows: |
| 124 | + entity_tags = base_tags + [f'db:{database}', f'table:{name}'] |
| 125 | + self._check.gauge('table.rows', int(total_rows or 0), tags=entity_tags) |
| 126 | + self._check.gauge('table.bytes', int(total_bytes or 0), tags=entity_tags) |
| 127 | + |
| 128 | + def _collect_view_refresh_metrics(self) -> None: |
| 129 | + if self._view_refreshes_skip: |
| 130 | + return |
| 131 | + try: |
| 132 | + rows = self._check.execute_query_raw( |
| 133 | + _VIEW_REFRESHES_QUERY.format(view_refreshes_table=self._check.get_system_table('view_refreshes')) |
| 134 | + ) |
| 135 | + except Exception as e: |
| 136 | + self._handle_view_refreshes_error(e) |
| 137 | + return |
| 138 | + |
| 139 | + # Drop the instance-level `db:` base tag (the connection database) so each |
| 140 | + # per-view series carries exactly one `db:` tag — the view's own database. |
| 141 | + base_tags = [t for t in self._check.tags if not t.startswith('db:')] |
| 142 | + for database, view_name, host, status, _exception, last_time, next_time, written_rows, written_bytes in rows: |
| 143 | + view_tags = base_tags + [f'db:{database}', f'view:{view_name}', f'host:{host}'] |
| 144 | + refresh_status = _VIEW_REFRESH_STATUS_MAP.get(status, AgentCheck.UNKNOWN) |
| 145 | + self._check.gauge('view.refresh.status', refresh_status, tags=view_tags) |
| 146 | + self._check.gauge('view.refresh.last_time', int(last_time or 0), tags=view_tags) |
| 147 | + self._check.gauge('view.refresh.next_time', int(next_time or 0), tags=view_tags) |
| 148 | + self._check.gauge('view.refresh.rows', int(written_rows or 0), tags=view_tags) |
| 149 | + self._check.gauge('view.refresh.bytes', int(written_bytes or 0), tags=view_tags) |
| 150 | + |
| 151 | + def _handle_view_refreshes_error(self, e: Exception) -> None: |
| 152 | + lowered = str(e).lower() |
| 153 | + if 'unknown table' in lowered or 'unknowntable' in lowered or 'unknown_table' in lowered: |
| 154 | + if not self._view_refreshes_unsupported_logged: |
| 155 | + self._log.info( |
| 156 | + "system.view_refreshes not present (ClickHouse < 24.3); refresh status will not be populated." |
| 157 | + ) |
| 158 | + self._view_refreshes_unsupported_logged = True |
| 159 | + self._view_refreshes_skip = True |
| 160 | + elif 'not enough privileges' in lowered or 'access_denied' in lowered: |
| 161 | + if not self._view_refreshes_permission_logged: |
| 162 | + self._log.warning( |
| 163 | + "Agent user lacks SELECT on system.view_refreshes; refresh status will not be populated. " |
| 164 | + "Grant with: GRANT SELECT ON system.view_refreshes TO <agent_user>. " |
| 165 | + "Restart the agent after granting access." |
| 166 | + ) |
| 167 | + self._view_refreshes_permission_logged = True |
| 168 | + self._view_refreshes_skip = True |
| 169 | + else: |
| 170 | + self._log.exception("Unexpected error querying system.view_refreshes") |
0 commit comments