> 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/observability/alerting.md).

# Alerting

> [!IMPORTANT]
> Alerting for the Cennso Database extension requires the [Prometheus Operator](https://prometheus-operator.dev/).

The Cennso Database extension provides a pre-configured [PrometheusRule](https://prometheus-operator.dev/docs/api-reference/api/#monitoring.coreos.com/v1.PrometheusRule) that allows the alerting system to monitor backup jobs for your MySQL and PostgreSQL database instances. The rule is installed as part of the [`cennso-db-support`](https://docs.cennso.com/cennso/cennso-db/latest/technical-reference/charts/cennso-db-support-chart-configuration.generated.md) Helm chart, which can be deployed when you install the extension package.

You can disable the PrometheusRule using either Cennso Management Console (CMC) or CLI:

## Alerting (CMC)

### CMC

To disable the PrometheusRule, go to **Cennso Management -> Packages**, click on the `Cennso DB Extension` package, and click **Update**. In the configuration form, find the `PrometheusRules Enabled` field and toggle it off.

## Alerting (CLI)

### CLI

To disable the PrometheusRule, set **prometheusRule.enabled** to `false` in the ClusterInstallation configuration:

```yaml
spec:
  forProvider:
    values:
      cennso-db-support:
        prometheusRule:
          enabled: false
```

> [!NOTE]
> You can configure values of the Cennso Database Support chart. For more information about the available configuration options, see the [Cennso Database Support chart reference](https://docs.cennso.com/cennso/cennso-db/latest/technical-reference/charts/cennso-db-support-chart-configuration.generated.md).

The following alert rules are included:

- [XtraBackupJobFailed](#xtrabackupjobfailed) - monitors backup pod failures for all MySQL database instances
- [PgBasebackupJobFailed](#pgbasebackupjobfailed) - monitors backup pod failures for all PostgreSQL database instances

## Alert rules

This section lists the available alert rules that you can use for your Cennso Database instances.

### XtraBackupJobFailed

The **XtraBackupJobFailed** alert fires when any XtraBackup backup pod enters the `Failed` phase.

The alert monitors all Kubernetes pods whose names match the `xtrabackup-*` prefix. This prefix is derived from the naming convention used by the `DBBackup` composition, which creates backup CronJobs named `xtrabackup-{BACKUP-CLAIM-NAME}`. Because the alert uses this naming convention rather than a specific claim name, it automatically covers all `DBBackup` instances deployed to your cluster, including those deployed after the package was installed.

The alert has the following properties:

| Property | Value | Description |
|---|---|---|
| Severity | `critical` | A failed backup leaves the MySQL instance without a recent restore point, so it needs immediate attention. |
| Pending period | `0s` | Specifies how long the condition must hold before the alert fires. The alert fires as soon as a backup pod enters the `Failed` phase. |

When this alert fires, check the following:

1. Find the failing pod on the Core Cluster:

   ```bash
   kubectl -n {DATABASE-NAMESPACE} get pods | grep xtrabackup
   ```

2. Check the pod logs for the failure reason:

   ```bash
   kubectl -n {DATABASE-NAMESPACE} logs {POD-NAME}
   ```

3. Verify that a MySQL replica pod is running. The backup job picks the first pod of the instance that is not the primary, with the same selector as the following command:

   ```bash
   kubectl -n {DATABASE-NAMESPACE} get pods -l 'app.kubernetes.io/instance=ps-db-{DBINSTANCE-NAME},app.kubernetes.io/component=mysql,!mysql.percona.com/primary'
   ```

   If the command lists no pod, or the pod is not `Running` and `Ready`, the backup cannot run. Check the `DBInstance` and its `PerconaServerMySQL` resource.

For more information on configuring backup jobs, see the [Cennso Database Backup](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-db-backup.md) document.

### PgBasebackupJobFailed

The **PgBasebackupJobFailed** alert fires when any PostgreSQL backup pod enters the `Failed` phase.

The alert monitors all Kubernetes pods whose names match the `pg-basebackup-*` prefix. This prefix is derived from the naming convention used by the `PostgreSQLBackup` composition, which creates backup CronJobs named `pg-basebackup-{POSTGRESQLBACKUP-NAME}`. Because the alert uses this naming convention rather than a specific resource name, it automatically covers all `PostgreSQLBackup` resources deployed to your cluster, including those deployed after the package was installed.

The alert has the following properties:

| Property | Value | Description |
|---|---|---|
| Severity | `critical` | A failed backup leaves the PostgreSQL instance without a recent restore point, so it needs immediate attention. |
| Pending period | `0s` | Specifies how long the condition must hold before the alert fires. The alert fires as soon as a backup pod enters the `Failed` phase. |

When this alert fires, check the following:

1. Find the failing pod on the cluster that runs the PostgreSQL instance:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get pods | grep pg-basebackup
   ```

2. Check the pod logs for the failure reason:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} logs {POD-NAME}
   ```

3. Verify that a read replica of the target `PostgreSQLInstance` is ready. The backup job picks a ready replica pod with the same selector as the following command:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get pods -l 'postgres-operator.crunchydata.com/cluster={POSTGRESQLINSTANCE-NAME},postgres-operator.crunchydata.com/role=replica'
   ```

   If the command lists no pod, or the pod is not `Running` and `Ready`, the backup cannot run. A `PostgreSQLInstance` with a single replica has no read replica at all. The job also rejects a replica that does not stream from the primary or lags behind it by more than **spec.maxReplicationLagBytes**. In such a case, you can see an error in the logs.

4. Verify that the restic repository from **spec.resticRepository** is reachable with the credentials from **spec.credentialsSecretRef**. The pod log shows the restic error when it is not. To check the credentials and the repository from your machine, load the `export` lines of the Secret into your shell and list the snapshots:

   ```bash
   eval "$(kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get secret {CREDENTIALS-SECRET-NAME} -o jsonpath='{.data.secret}' | base64 -d)"
   restic -r {RESTIC-REPOSITORY} snapshots
   ```

   Add the same flags as **spec.additionalResticOpts.backupExtraArgs** for a repository with a self-signed certificate. A repository that is only reachable from inside the cluster cannot be checked this way. Instead, run the backup manually and follow its log:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} create job --from=cronjob/pg-basebackup-{POSTGRESQLBACKUP-NAME} pg-basebackup-{POSTGRESQLBACKUP-NAME}-manual
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} logs -f job/pg-basebackup-{POSTGRESQLBACKUP-NAME}-manual
   ```

   Delete the Job afterwards, since it is not covered by the history limits of the CronJob:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} delete job pg-basebackup-{POSTGRESQLBACKUP-NAME}-manual
   ```

## Custom alert rules

In addition to the pre-configured alert rules, you can define your own alert rules in two places:

- In the `cennso-db-support` chart, with the **prometheusRule.additionalRules** option. The chart creates one PrometheusRule on the Management Cluster, where the chart is installed, regardless of where the database clusters run. The rules are not tied to a single database cluster. The Prometheus or ruler that loads this PrometheusRule evaluates rules against all the metrics it can see, so one rule can cover every database cluster.
- In each database cluster, with the **spec.metricsExporter.prometheusRules** option of the `DBInstance` and `PostgreSQLInstance` CRs. The rules are installed separately for each database cluster, on the Kubernetes cluster where the database cluster runs, in the same namespace as the database cluster.

Choose the place based on where your alerting system loads PrometheusRule resources from. For example, a central [ruler](https://grafana.com/docs/mimir/latest/references/architecture/components/ruler/) that runs on the Management Cluster can evaluate the metrics of several Core Clusters but load PrometheusRule resources only from the Management Cluster. Such a ruler does not see the rules created on the Core Clusters. In this case, use the chart option.

### Rules in the cennso-db-support chart

To add your own rules to the PrometheusRule of the `cennso-db-support` chart, fill **prometheusRule.additionalRules** in the ClusterInstallation configuration. The chart adds the rules to the PrometheusRule as a separate group named `cennso-db-additional.rules`. The rules are installed only when **prometheusRule.enabled** is `true`.

The following example adds alerts that fire when a MySQL server uses more than its allowed number of connections. It defines two alerting rules with different thresholds:

- 80% threshold applies to all MySQL clusters except the one identified by the `mysql_instance` label.
- 90% threshold applies only to the MySQL cluster identified by the `mysql_instance` label.

The first rule excludes the labelled MySQL cluster, while the second rule selects only this cluster:

```yaml
spec:
  forProvider:
    values:
      cennso-db-support:
        prometheusRule:
          additionalRules:
            - alert: MySQLConnectionsHigh
              expr: >-
                100 * mysql_global_status_threads_connected{mysql_instance!~"ps-db-{DBINSTANCE-NAME}-mysql-.*"}
                / mysql_global_variables_max_connections > 80
              for: 5m
              labels:
                severity: warning
              annotations:
                summary: "MySQL connections are high on pod {{ $labels.pod }}"
            - alert: MySQLConnectionsHigh
              expr: >-
                100 * mysql_global_status_threads_connected{mysql_instance=~"ps-db-{DBINSTANCE-NAME}-mysql-.*"}
                / mysql_global_variables_max_connections > 90
              for: 5m
              labels:
                severity: warning
              annotations:
                summary: "MySQL connections are high on pod {{ $labels.pod }}"
```

Several rules can have the same alert name. Make sure that their expressions do not select the same MySQL server.

The chart copies the rules without changes, so you can use Prometheus template variables such as `{{ $labels.pod }}` in annotations as they are. Both alerting and recording rules are supported.

The chart rules are evaluated against all metrics the alerting system can see. If the alerting system collects metrics from several clusters, add a label matcher to each expression to specify the clusters you want to monitor.

### Rules per database cluster

To define alert rules based on the metrics of a single database cluster, use the **spec.metricsExporter.prometheusRules** configuration option of the `DBInstance` and `PostgreSQLInstance` CRs. To do that, set the **spec.metricsExporter.prometheusRules.enabled** to `true` and fill the **spec.metricsExporter.prometheusRules.rules** with your custom Prometheus rules.

The following example shows a custom alert rule for a MySQL cluster:

```yaml
spec:
  metricsExporter:
    enabled: true
    prometheusRules:
      enabled: true
      rules:
        - alert: MySQLDown
          expr: mysql_up == 0
          for: 1m
          labels:
            severity: critical
```

The following example shows a custom alert rule for a PostgreSQL cluster:

```yaml
spec:
  metricsExporter:
    enabled: true
    prometheusRules:
      enabled: true
      rules:
        - alert: PostgreSQLDown
          expr: pg_up == 0
          for: 1m
          labels:
            severity: critical
```

The rules are created as one PrometheusRule per database cluster in the namespace set by **spec.namespace**:

| CR | PrometheusRule name |
|---|---|
| `DBInstance` | `mysqld-exporter-{DBINSTANCE-NAME}` |
| `PostgreSQLInstance` | `{POSTGRESQLINSTANCE-NAME}-exporter` |

These rules do not depend on the **prometheusRule.enabled** option of the `cennso-db-support` chart. For more information, see the following documents:

- [Enable metrics collector](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-database-observability.md) for MySQL clusters
- [Enable metrics collector](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql-observability.md) for PostgreSQL clusters
