> 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/troubleshooting/db-instance-deletion.md).

# Accidental deletion of a `DB Instance` composition

This document explains how to handle the accidental deletion of a `DB Instance` composition.

Each `DB Instance` causes the `DB Operator` to spin up `N` dedicated MySQL replicas, with one considered the primary. When the `DB Instance` object is deleted, the `DB Operator` deletes all Kubernetes objects related to the deleted `DB Instance`, such as Stateful Sets, Services, Deployments, etc. The database data stored on the MySQL instance volumes and the Kubernetes secrets containing the management user passwords are not deleted.

When a `DB Instance` is bootstrapped, a set of management users along with matching credentials are created and stored within the database:

```yaml
---
kind: Secret
type: Opaque
apiVersion: v1
metadata:
  name: internal-ps-db-{DATABASE_NAME}
  namespace: {NAMESPACE_NAME}
data:
  heartbeat: {HEARTBEAT_USER_PASSWORD}
  monitor: {MONITOR_USER_PASSWORD}
  operator: {OPERATOR_USER_PASSWORD}
  orchestrator: {ORCHESTRATOR_USER_PASSWORD}
  replication: {REPLICATION_USER_PASSWORD}
  root: {ROOT_USER_PASSWORD}
  xtrabackup: {XTRABACKUP_USER_PASSWORD}
```

> [!NOTE]
> Deleting the `DB Instance` does not delete this Kubernetes secret or the `ps-db-{DATABASE_NAME}-secrets` secret that it is created from. If you recreate the `DB Instance` with the same name, it reuses the existing secrets and the existing data.

The problem described in this document occurs when both secrets are lost, for example deleted manually, while the database data is kept. The users and their passwords stored in these secrets still remain in the database, but the passwords are no longer available in the cluster.

When you recreate the `DB Instance`, `DB Operator` creates a new Kubernetes secret and tries to create the users and the passwords in the `DB Instance` upon bootstrap. This fails because the intended users already exist in the database. A common symptom is the following error message in the readiness probe:

   ```
    ping DB: Error 1045 (28000): Access denied for user ‘operator’@‘IP’ (using password: YES)
   ```

There are two ways to recover from this situation:

- Remove the existing database data, let the `DB Instance` bootstrap, then use a backup to restore the data. To remove the data, delete the database files from the node-local paths of the MySQL instances. If the volumes are provided by the storage class, delete the `datadir-ps-db-{DATABASE_NAME}-mysql-{INSTANCE_NUMBER}` Persistent Volume Claims instead.
- Overwrite the existing passwords during the `DB Instance` bootstrap.

The best option depends on factors such as time constraints, backup availability, and the ability to restore from the backup.

The second recovery option is described below. Recovery using an available backup is not covered in this document.

## Overwrite the existing passwords during the `DB Instance` bootstrap

1. Patch the StatefulSet template of the `DB Instance` to allow access to the `mysql` container. Then, remove all lifecycle-related helpers from the `mysql` container configuration, including:

   - `lifecycle`
   - `livenessProbe`
   - `readinessProbe`
   - `startupProbe`

   To apply this, run the following command:

   ```bash
   export NAMESPACE={DATABASE_INSTANCE_NAMESPACE}
   export STATEFULSET={STATEFULSET_NAME}
   kubectl -n $NAMESPACE patch statefulset $STATEFULSET -p '{"spec":{"template":{"spec":{"containers":[{"name":"mysql","livenessProbe":null}]}}}}'
   kubectl -n $NAMESPACE patch statefulset $STATEFULSET -p '{"spec":{"template":{"spec":{"containers":[{"name":"mysql","readinessProbe":null}]}}}}'
   kubectl -n $NAMESPACE patch statefulset $STATEFULSET -p '{"spec":{"template":{"spec":{"containers":[{"name":"mysql","startupProbe":null}]}}}}'
   kubectl -n $NAMESPACE patch statefulset $STATEFULSET -p '{"spec":{"template":{"spec":{"containers":[{"name":"mysql","lifecycle":null}]}}}}'
   ```

   Then, update the `command` field of the `mysql` container to keep it running without starting the actual database process:

   ```bash
   export NAMESPACE={DATABASE_INSTANCE_NAMESPACE}
   export STATEFULSET={STATEFULSET_NAME}
   kubectl -n $NAMESPACE patch statefulset $STATEFULSET -p '{"spec":{"template":{"spec":{"containers":[{"name":"mysql","command":["tini","--","while true; do sleep 3600; done"]}]}}}}'
   ```

   Finally, remove the `xtrabackup` and `heartbeat` containers:

   ```bash
   export NAMESPACE={DATABASE_INSTANCE_NAMESPACE}
   export STATEFULSET={STATEFULSET_NAME}
   kubectl -n $NAMESPACE patch statefulset $STATEFULSET -p '{"spec":{"template":{"spec":{"containers":[{"name":"xtrabackup","$patch":"delete"}]}}}}'
   kubectl -n $NAMESPACE patch statefulset $STATEFULSET -p '{"spec":{"template":{"spec":{"containers":[{"name":"heartbeat","$patch":"delete"}]}}}}'
   ```

2. Delete all pods of the affected `DB Instance`. Kubernetes will re-create the pods in their patched version.

3. Attach to the `mysql` container:

   ```bash
   kubectl exec -it {MYSQL_POD_NAME} -c mysql -n {NAMESPACE} -- bash
   ```

4. Create a file with recovery script called `/tmp/recovery.sh`:

   ```bash
   #!/bin/bash
   #set -eo pipefail
   #shopt -s nullglob
   #set -o xtrace

   # taken from percona-startup-scripts
   file_env() {
      #set +o xtrace
      local var="$1"
      local fileVar="${var}_FILE"
      local def="${2:-}"
      if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
         echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
         exit 1
      fi
      local val="$def"
      if [ "${!var:-}" ]; then
         val="${!var}"
      elif [ "${!fileVar:-}" ]; then
         val="$(<"${!fileVar}")"
      elif [ "${3:-}" ] && [ -f "/etc/mysql/mysql-users-secret/$3" ]; then
         val="$(</etc/mysql/mysql-users-secret/"$3")"
      fi
      export "$var"="$val"
      unset "$fileVar"
      #set -o xtrace
   }

   file_env 'MYSQL_ROOT_PASSWORD' '' 'root'
   file_env 'MYSQL_ROOT_HOST' '%'
   file_env 'MONITOR_HOST' 'localhost'
   file_env 'MONITOR_PASSWORD' 'monitor' 'monitor'
   file_env 'XTRABACKUP_PASSWORD' '' 'xtrabackup'
   file_env 'REPLICATION_PASSWORD' '' 'replication'
   file_env 'ORC_TOPOLOGY_PASSWORD' '' 'orchestrator'
   file_env 'OPERATOR_ADMIN_PASSWORD' '' 'operator'
   file_env 'XTRABACKUP_PASSWORD' '' 'xtrabackup'
   file_env 'HEARTBEAT_PASSWORD' '' 'heartbeat'

   (
   cat <<-EOSQL
   -- fix passwords
   ALTER USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}';
   ALTER USER 'operator'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${OPERATOR_ADMIN_PASSWORD}';
   ALTER USER 'xtrabackup'@'localhost' IDENTIFIED BY '${XTRABACKUP_PASSWORD}';
   ALTER USER 'monitor'@'${MONITOR_HOST}' IDENTIFIED BY '${MONITOR_PASSWORD}';
   ALTER USER 'replication'@'%' IDENTIFIED BY '${REPLICATION_PASSWORD}';
   ALTER USER 'orchestrator'@'%' IDENTIFIED BY '${ORC_TOPOLOGY_PASSWORD}';
   ALTER USER 'heartbeat'@'localhost' IDENTIFIED BY '${HEARTBEAT_PASSWORD}';

   FLUSH PRIVILEGES;

   EOSQL
   )
   ```

   The script resets internal MySQL user passwords directly within the container. Since the `mysql` process is not running (due to the overridden `command`), this allows you to enter the container safely and manually start MySQL with controlled conditions.

   The `/tmp/recovery.sh` script:

   - Loads user passwords securely from environment variables or mounted secrets.
   - Uses these values to update MySQL internal user accounts with new passwords.
   - Ensures MySQL permissions are refreshed using `FLUSH PRIVILEGES`.

5. Run the `/tmp/recovery.sh` script:

   ```bash
   bash /tmp/recovery.sh | tee /tmp/pw.sql
   cd /var/lib/mysql && mysqld_safe --datadir=`pwd` --console --skip-networking --init-file=/tmp/pw.sql &
   tail -f *.err
   ```

   Once the log shows a success, send a [`TERM` signal](https://man7.org/linux/man-pages/man7/signal.7.html) to the `mysqld` PID to stop the server:

   ```bash
   ps w | grep mysqld
   kill -TERM {MYSQLD_PID}
   exit
   ```

   > [!NOTE]
   > Repeat steps 3, 4, and 5 for each `MySQL` pod in the affected `DB Instance`.

6. Set the **replica** parameter of the `PerconaServerMySQL` Kubernetes resource for the affected `DB Instance` to `0`.

7. Delete the StatefulSet of the affected `DB Instance`. Once the patched StatefulSet and its related resources are removed (Persistent Volumes are preserved), the operator will recreate a new one using the original configuration.

8. Set the **replica** parameter of the `PerconaServerMySQL` Kubernetes resource for the affected `DB Instance` back to the original production value (usually `2`). The `DB Operator` monitoring this resource will detect the change and recreate the StatefulSet with the default configuration.

At this point, the credentials stored in the database should match those in the corresponding Kubernetes Secret, allowing all components to start functioning correctly.
