> 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/operation-guides/backup.md).

# Back up and restore

This guide describes how to use the `DBBackup` Custom Resource to:

- [Perform a backup of a database](#perform-a-backup-of-a-database)
- [Restore a database from a backup](#restore-a-database-from-a-backup)

## Perform a backup of a database

This section describes how you can prepare backups of your database deployed using the [Cennso Database Instance](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-database.md).

> [!IMPORTANT]
> The backup job runs against a read replica instead of the primary, so the target `DBInstance` must run at least one read replica, with **spec.mysql.size** set to `2` or more. If the cluster runs only a single instance, the backup job cannot find a pod to back up and fails with the error: `ERROR: No read replica found. Backup can be performed only on a read replica.`. For more information, see the [Configuration restrictions](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-db-backup.md#configuration-restrictions) section.

To deploy a Cennso Database Backup, execute the following steps:

1. Prepare the Kubernetes secret in the Kubernetes namespace where your MySQL cluster is up and running. This secret should contain the list of environment variables with the data needed for the authorisation at a [Restic](https://restic.net/) backend. To prepare a secret, create a file, for example `secret.data`, with the list of environment variables which you need to authorise at a restic backend. For example:

   ```bash
   export AWS_ACCESS_KEY_ID={MY_ACCESS_KEY}
   export AWS_SECRET_ACCESS_KEY={MY_SECRET_ACCESS_KEY}
   export RESTIC_PASSWORD={RESTIC_PASSWORD}
   ```

   > [!NOTE]
   > To find information about all supported environment variables, see the [official documentation](https://restic.readthedocs.io/en/stable/030_preparing_a_new_repo.html).

   At the next step, encode the contents of the file to `base64`:

   ```bash
   cat secret.data | base64 -w0
   ```

   Create a Kubernetes secret file `secret.yaml` and put the output of the previous command to the **data.secret** field. For example:

   ```yaml
   apiVersion: v1
   kind: Secret
   metadata:
     name: {SECRET-NAME}
     namespace: {NAMESPACE-WITH-MYSQL-CLUSTER}
   type: Opaque
   data:
     secret: ZXhwb3J0IEFXU19BQ0NFU1NfS0VZX0lEPWNvbnNvbGUKZXhwb3J0IEFXU19TRUNSRVRfQUNDRVNTX0tFWT1jb25zb2xlMTIzCmV4cG9ydCBSRVNUSUNfUEFTU1dPUkQ9cm9vdHBhc3MxMjMK
   ```

   Apply this secret to the Core Cluster where you want to perform backups using the following command:

   ```bash
   kubectl apply -f secret.yaml -n {NAMESPACE-WITH-MYSQL-CLUSTER}
   ```

2. Prepare the `DBBackup` Custom Resource (CR) to deploy the Cennso Database Backup in your Management Cluster. This CR defines the connection to the Core Cluster and the backup job configuration. For example:

   ```yaml
   apiVersion: db.contrib.cennso.com/v1alpha1
   kind: DBBackup
   metadata:
     name: {DB-BACKUP-CLAIM-NAME}
     namespace: cennso-infra
   spec:
     connectionSecretRef:
       name: {CORE-CLUSTER-NAME}
       namespace: cennso-infra
     namespace: {NAMESPACE-WITH-MYSQL-CLUSTER}
     schedule: "0 0 * * *"
     activeDeadlineSeconds: 7200
     backoffLimit: 2
     successfulJobsHistoryLimit: 1
     failedJobsHistoryLimit: 3
     resticRepository: "s3:http://minio:9000/mysql-backup"
     credentialsSecretRef:
       name: {SECRET-NAME}
     backupDirectory: "/var/lib/mysql/backup/db-backup"
     additionalResticOpts:
       initExtraArgs: ""
       backupExtraArgs: ""
       pruneRepository: false
       pruneExtraArgs: ""
     xtradbExtraArgs: "--tables-exclude=\"{DATABASE-NAME}.{TABLE-NAME}\""
   ```

   > [!IMPORTANT]
   > The DBBackup resource has restrictions on some configurable values. For more information, see the [Configuration restrictions](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-db-backup.md#configuration-restrictions) section.

3. Apply the prepared CR to your Management Cluster:

   ```bash
   kubectl apply -f database-backup-cr.yaml
   ```

4. Check your Core Cluster for the created Kubernetes CronJob to check if backups are configured to run at the specified time:

   ```bash
   kubectl get cronjobs -n {NAMESPACE-WITH-MYSQL-CLUSTER}
   ```

The example above shows the Custom Resource that creates a Kubernetes CronJob. This CronJob performs a backup of the database deployed in the Core Cluster specified by the `{CORE-CLUSTER-NAME}` and located in the namespace specified by the `{NAMESPACE-WITH-MYSQL-CLUSTER}`. It performs a backup each day at `00:00`. The `{SECRET-NAME}` must specify the name of the Kubernetes secret which you created in the previous step.

For more information about available configuration options, see the [Cennso Database Backup](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-db-backup.md) document.

## Restore a database from a backup

If your database or the data was corrupted in a way that you can not continue to run MySQL instances on existing data files, you have to restore the database from a backup.

To restore the database from a backup, you must deploy a new MySQL cluster using the instructions given in the [Deploy Cennso Database](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-database.md) document or scale the existing cluster to zero instances. To learn how to deploy a new MySQL cluster, read the [Installation](https://docs.cennso.com/cennso/cennso-db/latest/installation.md) and [Deploy Cennso Database](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-database.md) documents. To scale down your existing cluster, you can use the command line or [Cennso Management Console](https://docs.cennso.com/cennso/cmc/latest.md):

   > [!IMPORTANT]
   > Be sure you know the node names where the MySQL instances are deployed before you scale down your database cluster. If you are using the Cennso Management Console, you can find the nodes where your MySQL instances are deployed at the **Cennso Management -> Configurations**. Choose the `DBInstance` related to your MySQL cluster and check the nodes at the specification tab. If you are using the CLI, you can use the following command to get the nodes on the Core Cluster where your MySQL cluster is deployed:
   >
   > ```bash
   > kubectl get pods -n {NAMESPACE-WITH-MYSQL-CLUSTER} -l app.kubernetes.io/component=mysql -o wide -o custom-columns='POD:.metadata.name,NODE:.spec.nodeName'
   > ```

### Restore a database from a backup (CMC)

### CMC

To scale down the MySQL cluster using CMC:

1. Go to **Cennso Management -> Configurations**.
2. Use filters at the top menu to select the `DBInstance` kind. Then, choose the `DBInstance` related to your MySQL cluster.
3. Press the `Edit` button and switch to the **Specification** tab.
4. Set the value of the **MySQL cluster size** to `0`.

### Restore a database from a backup (CLI)

### CLI

To scale down the MySQL cluster using CLI, set the **spec.mysql.size** value to `0` in the `PerconaServerMySQL` related to your database cluster and wait until all MySQL instances are terminated. To find the needed `PerconaServerMySQL` resource, use the following command:

```bash
kubectl get perconaservermysql -n {NAMESPACE-WITH-DATABASE-CLUSTER}
```

After this, follow the next steps to restore your database from a backup:

1. Go to nodes where the MySQL cluster is deployed and remove the broken MySQL [datadir](https://dev.mysql.com/doc/refman/8.0/en/data-directory.html):

   ```bash
   rm -rf /var/lib/mysql/*
   ```

2. Go to the node where the primary MySQL instance is intended to run after restoring the backup. Find the snapshot ID in Restic from which you want to restore and fetch it to the node:

   ```bash
   export AWS_ACCESS_KEY_ID={AWS_KEY_ID}
   export AWS_SECRET_ACCESS_KEY={AWS_SECRET_ACCESS_KEY}
   export RESTIC_PASSWORD={RESTIC_PASSWORD}

   mkdir -p /var/lib/mysql/restore

   restic restore -r {RESTIC_ENDPOINT} {RESTIC-SNAPSHOT-ID} --target=/var/lib/mysql/restore
   ```

3. Restore the backup using the [`xtrabackup`](https://docs.percona.com/percona-xtrabackup/8.0/index.html) command:

   ```bash
   shopt -s extglob dotglob
   rm -rf /var/lib/mysql/!(restore)

   xtrabackup --prepare --target-dir=/var/lib/mysql/restore/var/lib/mysql/backup/db-backup
   xtrabackup --force-non-empty-directories --copy-back --datadir=/var/lib/mysql --target-dir=/var/lib/mysql/restore/var/lib/mysql/backup/db-backup
   ```

   > [!NOTE]
   > If you set the `--compress` option in the **spec.xtradbExtraArgs** of the `DBBackup` Custom Resource, you should decompress the backup before restoring from it. To do that, use the following commands:
   >
   > ```bash
   > shopt -s extglob dotglob
   > rm -rf /var/lib/mysql/!(restore)
   >
   > xtrabackup --decompress --target-dir=/var/lib/mysql/restore/var/lib/mysql/backup/db-backup
   > xtrabackup --prepare --target-dir=/var/lib/mysql/restore/var/lib/mysql/backup/db-backup
   > xtrabackup --force-non-empty-directories --copy-back --datadir=/var/lib/mysql --target-dir=/var/lib/mysql/restore/var/lib/mysql/backup/db-backup
   > ```

4. Delete the directory with the backup:

   ```bash
   rm -rf /var/lib/mysql/restore
   ```

5. From now on, you can scale your MySQL cluster to the desired number of instances again. To do this, you can use the Cennso Management Console or the CLI. Repeat step 1 above to set the number of MySQL instances as expected.

   > [!IMPORTANT]
   > In addition, it is highly recommended to enable [MySQL CLONE](https://dev.mysql.com/doc/refman/8.0/en/clone-plugin.html) and disable [binary-donor](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/binary-donor.md) after you restore the backup.
   >
   > To enable `CLONE` operations, you can set the **CLONE_REQUIRED_ON_ASYNC_CLUSTER** environment variable to `true` in the `PerconaServerMySQL` resource related to your MySQL cluster.
   > To disable `binary-donor`, scale its deployments to `0`.
   >
   > After the database cluster is up and running and the `CLONE` operation finishes, you can set the value of the **CLONE_REQUIRED_ON_ASYNC_CLUSTER** back to `false` and enable `binary-donor` again. After restarting the MySQL instances, you should have a ready MySQL cluster with restored data.

   For more information on how to validate your MySQL cluster, see the [Validate the MySQL cluster](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-database-validation.md) document.
