# Создание и восстановление резервной копии с помощью barman

21. Утилита barman содержит два типа конфиг. Свой и для каждого кластера PostgreSQL. Посмотрим на них

```
postgres$ cat /etc/barman.conf
postgres$ ls /etc/barman.d/
total 20
drwxr-xr-x   2 root root 4096 Apr  5 05:55 ./
drwxr-xr-x. 82 root root 4096 Apr  5 05:55 ../
-rw-r--r--   1 root root  947 Nov  4 08:55 passive-server.conf-template
-rw-r--r--   1 root root 1565 Nov  4 08:55 ssh-server.conf-template
-rw-r--r--   1 root root 1492 Nov  4 08:55 streaming-server.conf-template
```

22. Создадим роль в PostgreSQL для выполнения бекапов и дадим ему соответствующие права

```sql
postgres$ psql
psql (12.6)
Type "help" for help.
5432=> 
CREATE ROLE backup WITH PASSWORD 'backup' LOGIN REPLICATION SUPERUSER;
CREATE ROLE
```

23. Выйдем из-под пользователя postgres и зайдем под пользователем root

```
postgres$ exit
student$ sudo -i
```

24. Создадим файл backup и внесем туда данные

```conf
root$ nano /etc/barman.d/pg_backup.conf
[pg_backup]
description = "PostgreSQL DB"
conninfo = host=localhost port=5432 user=backup password=backup dbname=template1
streaming_archiver = true
streaming_conninfo = host=localhost port=5432 user=backup password=backup
backup_method = postgres
slot_name = pg_backup
```

25. Проверим работу barman

```log
root$ barman check pg_backup
Server pg_backup:
    WAL archive: FAILED (please make sure WAL shipping is setup)
    PostgreSQL: OK
    superuser or standard user with backup privileges: OK
    PostgreSQL streaming: OK
    wal_level: OK
    replication slot: FAILED (replication slot 'pg_backup' doesn't exist. Please execute 'barman receive-wal --create-slot pg_backup')
    directories: OK
    retention policy settings: OK
    backup maximum age: OK (no last_backup_maximum_age provided)
    compression settings: OK
    failed backups: OK (there are 0 failed backups)
    minimum redundancy requirements: OK (have 0 backups, expected at least 0)
    pg_basebackup: OK
    pg_basebackup compatible: OK
    pg_basebackup supports tablespaces mapping: OK
    systemid coherence: OK (no system Id stored on disk)
    pg_receivexlog: OK
    pg_receivexlog compatible: OK
    receive-wal running: FAILED (See the Barman log file for more details)
    archiver errors: OK
```

Видим, что у нас много ошибок и предупреждений. Давайте исправим их.

26. Создадим слот репликации pg_backup

```
root$ barman receive-wal --create-slot pg_backup
Creating physical replication slot 'pg_backup' on server 'pg_backup'
Replication slot 'pg_backup' created
```

27. Проверим работу barman

```log
root$ barman check pg_backup
Server pg_backup:
    PostgreSQL: OK
    superuser or standard user with backup privileges: OK
    PostgreSQL streaming: OK
    wal_level: OK
    replication slot: OK
    directories: OK
    retention policy settings: OK
    backup maximum age: OK (no last_backup_maximum_age provided)
    compression settings: OK
    failed backups: OK (there are 0 failed backups)
    minimum redundancy requirements: OK (have 0 backups, expected at least 0)
    pg_basebackup: OK
    pg_basebackup compatible: OK
    pg_basebackup supports tablespaces mapping: OK
    systemid coherence: OK (no system Id stored on disk)
    pg_receivexlog: OK
    pg_receivexlog compatible: OK
    receive-wal running: OK
    archiver errors: OK
```

28. Создадим резервную копию

```log
root$ sudo -u barman barman backup pg_backup
Starting backup using postgres method for server pg_backup in /var/lib/barman/pg_backup/base/20210405T094734
Backup start at LSN: 0/3000060 (000000010000000000000003, 00000060)
Starting backup copy via pg_basebackup for 20210405T094734
Copy done (time: 3 seconds)
Finalising the backup.
This is the first backup for server pg_backup
WAL segments preceding the current backup have been found:
    000000010000000000000001 from server pg_backup has been removed
    000000010000000000000002 from server pg_backup has been removed
Backup size: 24.2 MiB
Backup end at LSN: 0/5000000 (000000010000000000000004, 00000000)
Backup completed (start time: 2021-04-05 09:47:34.216170, elapsed time: 3 seconds)
Processing xlog segments from streaming for pg_backup
    000000010000000000000003
WARNING: IMPORTANT: this backup is classified as WAITING_FOR_WALS, meaning that Barman has not received yet all the required WAL files for the backup consistency.
This is a common behaviour in concurrent backup scenarios, and Barman automatically set the backup as DONE once all the required WAL files have been archived.
Hint: execute the backup command with '--wait'
```

29. О чем говорит это предупреждение? Давайте исправим такую ошибку

```
root$ barman switch-wal pg_backup
The WAL file 000000010000000000000005 has been closed on server 'pg_backup'
```

30. Посмотрим список резервных копий

```
root$ barman list-backup pg_backup
pg_backup 20210405T094734 - Mon Apr  5 09:47:37 2021 - Size: 40.2 MiB - WAL Size: 1s6.0 MiB
```

31. Давайте восстановим резервную копию. Делаем «кустарно». Прошу гнилыми помидорами не закидывать. Данные скрипт приводится в качестве примера в тестовом окружении. В рабочей среде нужно делать всё через ssh.

```log
root$ sudo -u postgres pg_ctl -D /var/lib/pgsql/12/main5432 stop

root$ chown -R barman:barman /var/lib/pgsql

root$ barman recover pg_backup 20210405T094734 /var/lib/pgsql/12/main5432
Starting local restore for server pg_backup using backup 20210405T094734
Destination directory: /var/lib/pgsql/12/main5432
Copying the base backup.
Copying required WAL segments.
Generating archive status files
Identify dangerous settings in destination directory.

Recovery completed (start time: 2021-04-05 10:41:58.225068, elapsed time: 1 second)

Your PostgreSQL server has been successfully prepared for recovery!

root$ chown -R postgres:postgres /var/lib/pgsql
```

32. Переходим к пользователю postgres и запускаем кластер PostgreSQL

```log
root$ exit

student$ sudo -u postgres -i

postgres$ pg_ctl -D /var/lib/pgsql/12/main5432 start
waiting for server to start....2021-04-05 10:48:09.751 UTC [2776] LOG:  starting PostgreSQL 12.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
2021-04-05 10:48:09.752 UTC [2776] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2021-04-05 10:48:09.755 UTC [2776] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2021-04-05 10:48:09.762 UTC [2776] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
2021-04-05 10:48:09.779 UTC [2776] LOG:  redirecting log output to logging collector process
2021-04-05 10:48:09.779 UTC [2776] HINT:  Future log output will appear in directory "log".
 done
server started
```

33. Проверяем работу кластера и данные в таблице test

```sql
postgres$ psql -p5433 -d wal_g

5433=> select * from test;
id |  name
----+---------
  2 | Value 2
  3 | Value 3
  1 | Value 4
(3 rows)
5433=> \q
```
