> For the complete documentation index, see [llms.txt](https://docs.cennso.com/cennso/cennso-db/latest/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-database-observability.md).

# Enable metrics collector

You can use [Prometheus mysqld exporter](https://github.com/percona/mysqld_exporter) to gather metrics from the deployed MySQL database instances. The Cennso Database extension provides the mysqld-exporter deployment per MySQL instance.

> [!NOTE]
> Do not mix the MySQL instance with `DBInstance`. The MySQL instance refers to a single MySQL database server deployed within the MySQL cluster described by the `DBInstance`.

You can enable mysqld-exporter using the following configuration option:

```yaml
apiVersion: db.contrib.cennso.com/v1alpha1
kind: DBInstance
metadata:
  name: mysql-cluster
spec:
  metricsExporter:
    enabled: false
```

If **spec.metricsExporter.enabled** is set to `true`, a mysqld-exporter instance is deployed for each MySQL server instance as a separate pod on the same node as the corresponding MySQL instance. The node of each MySQL instance depends on its storage configuration, as described in the [Storage configuration](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-db-instance.md#storage-configuration) section of the Cennso Database Instance document.

The following example shows how you can deploy a mysqld-exporter instance for your MySQL cluster:

```yaml
apiVersion: db.contrib.cennso.com/v1alpha1
kind: DBInstance
metadata:
  name: {DATABASE-CLUSTER-NAME}
  namespace: cennso-infra
spec:
  connectionSecretRef:
    name: {CORE-CLUSTER-NAME}
    namespace: cennso-infra
  namespace: {DATABASE-CLUSTER-NAMESPACE}
  storage:
    capacity: 20Gi
    className: mysql-cluster-storage
  instances:
    0:
      storage:
        node: {NODE-0-NAME}
        path: /opt/local-path-provisioner/mysql-cluster/mysql-instance-0
    1:
      storage:
        node: {NODE-1-NAME}
        path: /opt/local-path-provisioner/mysql-cluster/mysql-instance-1
  metricsExporter:
    enabled: true
    chart:
      name: prometheus-mysql-exporter
      version: "2.12.0"
      registry: oci://registry.cennso.com/cennso/charts
      pullSecretRef: cennso-pull-secret
    image:
      registry: registry.cennso.com
      repository: cennso/percona-mysqld-exporter
      tag: v3.6.0-cennso-1.0.0
    imagePullSecretRef:
      name: cennso-pull-secret
    scrapeInterval: "30s"
    scrapeTimeout: "10s"
    additionalRelabelings:
      - action: replace
        replacement: custom-instance-metric
        targetLabel: custom_metric_label
    logLevel: "info"
    collectors:
      global_status: true
      global_variables: true
      engine_innodb_status: true
      slave_status: true
      binlog_size: true
      info_schema.query_response_time: false
    prometheusRules:
      enabled: false
      rules:
        - alert: MysqlDown
          expr: mysql_up == 0
          for: 5m
          labels:
            severity: critical
          annotations:
            summary: MySQL down (instance {{ $labels.instance }})
            description: "MySQL instance is down on {{ $labels.instance }}\n  VALUE = {{ $value }}\n  LABELS = {{ $labels }}"
```

> [!NOTE]
> For more information about all the configuration options except the **spec.metricsExporter**, see the [Deploy Cennso Database Instance](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-database.md#deploy-cennso-database-instance) document.

Using the example above, you can deploy the MySQL cluster, which consists of two MySQL instances deployed on the nodes specified by `{NODE-0-NAME}` and `{NODE-1-NAME}`. Together with the MySQL server instances, two mysql-exporter instances are deployed on the same nodes to collect metrics from the MySQL servers.

## Relabeling rules

By default, each mysql-exporter instance provides the following [relabeling](https://grafana.com/docs/alloy/latest/reference/components/prometheus/prometheus.relabel/) rules:

```yaml
- sourceLabels: [__meta_kubernetes_pod_annotation_cennso_com_monitor_db_instance]
  action: replace
  targetLabel: pod
- targetLabel: mysql_instance
  replacement: "ps-db-{{ CR_NAME }}-mysql-{{ MYSQL_INSTANCE_POD_INDEX }}"
- targetLabel: instance
  replacement: "ps-db-{{ CR_NAME }}-mysql-{{ MYSQL_INSTANCE_POD_INDEX }}"
```

Using the relabeling rules described above, you can use the `mysql_instance` or `instance` label to refer to a MySQL server instance name. In addition, you can specify your relabeling rules using the **spec.metricsExporter.additionalRelabelings** configuration options.

## Metric collectors

The following metric collectors settings are set by default:

- `global_status`
- `global_variables`
- `engine_innodb_status`
- `slave_status`
- `binlog_size`

To enable a different set of collectors, use the **spec.metricsExporter.collectors** configuration option. For more information about the available collectors, see the [official documentation](https://github.com/percona/mysqld_exporter/blob/pmm-3.6.0/README.md#collector-flags).

## Prometheus rules

To configure additional [Prometheus rules](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/), use the **spec.metricsExporter.prometheusRules** configuration option. To do that, set the **spec.metricsExporter.prometheusRules.enabled** to `true` and fill the **spec.metricsExporter.prometheusRules.rules** with your custom Prometheus rules. The rules are created as one PrometheusRule named `mysqld-exporter-{DATABASE-CLUSTER-NAME}` in the namespace set by **spec.namespace**. For examples, see the [Custom alert rules](https://docs.cennso.com/cennso/cennso-db/latest/observability/alerting.md#custom-alert-rules) section.

## Metrics based on custom queries

> [!NOTE]
> Each mysqld-exporter instance runs custom queries against its own MySQL instance and exposes the results as metrics that Prometheus can scrape. The results are reported per MySQL instance and are not aggregated across the cluster.

In addition to the built-in [collectors](https://github.com/percona/mysqld_exporter/blob/pmm-3.6.0/README.md#collector-flags), you can expose Prometheus metrics for arbitrary SQL statements using the **spec.metricsExporter.customQueries** configuration option.

By default, custom queries are disabled (the **spec.metricsExporter.customQueries** configuration option is set to the empty string - `""`). When the value of this configuration option is set, the mysqld-exporter is launched with the `--collect.custom_query.hr` flag and reads the YAML definitions from a Kubernetes ConfigMap mounted at `/etc/mysqld-exporter/custom-queries/hr`. The ConfigMap is created and reconciled automatically for each MySQL instance.

The value is an inline YAML document. Each top-level key defines a metric namespace used as the metric name prefix. Each namespace must contain a `query` and a `metrics` key. The `query` key specifies an SQL query that is executed to build data points for the metrics. The `metrics` key is a YAML array which contains the column name from the SQL query result and specifies how the value of this column is used. The usage of the value should be under the `usage` key. The possible values of the `usage` key are:

| Usage | Description |
| --- | --- |
| `LABEL` | The column value becomes a Prometheus label dimension on every emitted sample |
| `GAUGE` | The column value is emitted as a gauge sample |
| `COUNTER` | The column value is emitted as a counter sample |
| `DURATION` | The column value is a text duration, for example `1h2m3s` or `250ms`, emitted as a gauge in milliseconds |
| `DISCARD` | The column is ignored |

The following example exposes five custom metrics:

```yaml
spec:
  metricsExporter:
    enabled: true
    customQueries: |
      mysql_slow_queries_total:
        query: "SHOW GLOBAL STATUS LIKE 'Slow_queries'"
        metrics:
          - Variable_name:
              usage: "LABEL"
          - Value:
              usage: "COUNTER"
              description: "Total number of slow queries since server start"

      mysql_table_size_bytes:
        query: |
          SELECT table_schema, table_name, engine,
                 data_length, index_length,
                 data_length + index_length AS total_size
          FROM information_schema.tables
          WHERE table_schema NOT IN ('mysql','information_schema','performance_schema','sys')
        metrics:
          - table_schema:
              usage: "LABEL"
          - table_name:
              usage: "LABEL"
          - engine:
              usage: "LABEL"
          - data_length:
              usage: "GAUGE"
              description: "Data file size in bytes"
          - index_length:
              usage: "GAUGE"
              description: "Index file size in bytes"
          - total_size:
              usage: "GAUGE"
              description: "Total data + index size in bytes"

      mysql_connections_by_user:
        query: |
          SELECT user, host, COUNT(*) AS connections
          FROM information_schema.processlist
          GROUP BY user, host
        metrics:
          - user:
              usage: "LABEL"
          - host:
              usage: "LABEL"
          - connections:
              usage: "GAUGE"
              description: "Number of open connections per user/host"
```

The example above produces the following metrics:

- `mysql_slow_queries_total_value{Variable_name="Slow_queries"} value` 
- `mysql_table_size_bytes_data_length{table_schema="...", table_name="...", engine="..."} value`
- `mysql_table_size_bytes_index_length{table_schema="...", table_name="...", engine="..."} value`
- `mysql_table_size_bytes_total_size{table_schema="...", table_name="...", engine="..."} value`
- `mysql_connections_by_user_connections{user="...", host="..."} value`

The emitted metric name follows the pattern `{namespace}_{column}` for every non-`LABEL` and non-`DISCARD` value column, and `{namespace}_{column}_milliseconds` for `DURATION` columns.

> [!NOTE]
> Every custom query is executed on every Prometheus scrape, so avoid statements that are expensive to run or that lock tables. Use **spec.metricsExporter.scrapeInterval** to reduce the load if needed.

For more examples of the YAML schema, see the [`queries-mysqld.yml`](https://github.com/percona/mysqld_exporter/blob/pmm-3.6.0/queries-mysqld.yml).
