Client

Введение

Аспект сохранения резервных копий (и их хранения), безусловно, один из важнейших в информационном мире: кому хочется, чтобы его данные в результате ошибки (программной ли или аппаратной) пропали? Соответственно, средств для создания бэкапов существует великое множество. Перечислю самые, на мой взгляд, необходимые требования к данным средствам:

  • Удобство автоматизации и сам факт наличия таковой. Это требование, впрочем, практически полностью нивелируется наличием Cron’а во всех *nix-дистрибутивах общего назначения. Однако резервное копирование как раз тот самый случай, когда не стоит складывать все яйца в одну корзину.
  • Поддерживаемые носители и сетевые резервные копии. Средство резервного копирования может быть сколь угодно замечательно, но если оно поддерживает только ограниченный набор носителей, на которые позволяется сохранять бэкапы, то оно не стоит и ломаного гроша. Особняком стоит создание бэкапов с помощью сетевых (в том числе и облачных) хранилищ. Здесь появляется такой аспект, как шифрование и передачи данных, и самих бэкапов.
  • Удобство восстановления. Полагаю, здесь комментарии излишни, ибо если произошла потеря данных, их восстановление должно быть как можно более быстрым и безболезненным.
  • Удобство начального конфигурирования. Это требование, конечно, дискуссионно, поскольку настраивается создание бэкапов единожды. Тем не менее люди зачастую производят выбор в пользу куда менее функциональных средств только из-за их простоты.

Bacula

  • Сайт проекта: bacula.org, sf.net/projects/bacula
  • Доступные версии: свободная Bacula
  • Project 5.х и коммерческая Bacula System Enterprise 4.х
  • Лицензия: GNU GPL
  • ОС сервер: Linux, FreeBSD, Open/Solaris
  • ОС клиент: Linux, *BSD, Open/Solaris, Mac OS X, Win

Очень популярная кроссплатформенная система резервного копирования, архивирования и восстановления данных. Построена по клиент-серверной технологии, модульная архитектура делает Bacula достаточно гибким инструментом, позволяющим использовать его как на единичной системе, так и для резервирования данных в разветвленной корпоративной сети. Все настройки осуществляются путем правки конфигурационных файлов.

Некоторое время придется потратить на их изучение, но зато полученные в итоге возможности с лихвой окупят предварительный этап подготовки. Конфиг позволяет задавать практически любые условия, вплоть до характера резервирования для различных типов файлов (например, архивы не сжимать, а просто копировать).

Bacula обладает большим количеством продвинутых возможностей, позволяющих с легкостью находить и восстанавливать утраченные или поврежденные файлы, в том числе и на другую систему. Поддерживаются все возможные стратегии резервирования — полное, инкрементное и дифференциальное.

Сжатие файлов производится на клиентской стороне, что уменьшает трафик и разгружает сервер. Стоит отметить весьма удачный встроенный планировщик и систему приоритета выполнения заданий.

Система резервирования, построенная на Bacula, состоит из трех основных компонентов, которые могут быть развернуты как на одном, так и на нескольких серверах/рабочих станциях:

  • Director (порт 9101) — основной элемент, осуществляющий централизованное управление всеми составляющими Bacula, формирование и запуск заданий по расписанию, также ведет журнал событий;
  • Storage (порт 9103) — демон, отвечающий за непосредственную запись резервируемых данных на носитель (жесткий диск, CD/DVD, ленточный или USB накопитель);
  • File Daemon (порт 9102) — клиентская программа, которая устанавливается на каждом компьютере и по команде Director’а производит резервирование и передачу данных на Storage.

Кроме этого, для отслеживания процесса обмена данными между Direct, Storage, File Daemon и управления работой Bacula администратор устанавливает на свой компьютер Monitor (значок висит в трее) и консоль.

Для хранения журналов архивных копий используется база данных — PostgreSQL, MySQL или SQLite. Сервер с ролью Director и Storage должен работать под управлением Linux, FreeBSD, Open/Solaris. Список ОС, на которые можно установить клиента, пополнен Windows (32 и 64 bit), *BSD, Mac OS X. Именно такое разнообразие и привело к тому, что Bacula очень популярна в гетерогенных сетях. Соединение между компонентами не защищено, но при необходимости легко настроить SSH туннель, на сайте проекта есть подробное описание.
В настоящее время доступно несколько вариантов консоли управления. Кроме текстовой консоли bconsole, проект предлагает графическую утилиту BAT (Bacula Admin Tool) на Qtбиблиотеках (в Ubuntu в universe) и wx-console на wxWidgets. В отдельном архиве (baculagui) идут: bweb (веб-интерфейс на Perl для выполнения базовых операций), bacula-web (веб-консоль, написанная на PHP), bimagemgr (веб-инструмент для управления записанными на CD данными). Кроме этого, доступен ряд сторонних разработок, например Baculaconf (baculaconf.sf.net) и Webacula (Web + Bacula, webacula.sf.net/ru). Так что из любой точки планеты, используя только веб-браузер, админ может запустить задание и просмотреть текущий статус (выполненные, с ошибками и т.д.), восстановить файлы, управлять хранилищами и многое другое.

По умолчанию для аутентификации компонентов Bacula используется пара логин и пароль (передается CRAM-MD5), но при необходимости довольно просто настроить более защищенную TLS аутентификацию. В общем случае правило iptables для сети 192.168.1.0/24 выглядит так:

Для сервера:

На клиентском компе нужно открыть только 9102 порт:

Админы, не желающие возиться с установкой Bacula, могут воспользоваться специализированным дистрибутивом Bran (branbackup.org, его основой послужил ALT Linux), предназначенным для организации центра хранения информации. Для управления настройками предлагается простой и понятный веб-интерфейс.

Backup and restore VMs using Hyper-V client

Advantages:

  • Runs on the Hyper-V host, so no need to install and setup a client in each VM
  • Uses build-in Hyper-V Resilient Change Tracking (RCT) to track changes to VM disks
  • Creates a virtual client for each VM, so each VM can be backed up with a different frequency
  • Uses production checkpoints to snapshot each VM separately

Disadvantages:

  • Does not work with Hyper-V versions before Hyper-V 2016
  • Hyper-V creates and manages the snapshots itself whereas it might be more efficient to let the Hyper-V VM storage (e.g. NetApp) handle the snapshotting (if present)

Conclusion: Best method if you do not want to run a client in each VM and use Hyper-V >=2016

How to setup/restore:

See the Hyper-V client

0.39:

New features:

  • Linux client without imaging capability
  • MSI installer for the client for 64bit systems
  • Starting backups is now only possible if a server is present and that server allows it
  • Settings which you cannot change are hidden now
  • Prevent system to go to sleep during a backup (Windows)
  • Image backups of multiple volumes (Windows)

Bugfixes:

  • Only submit paths to the backend when a change occured
  • Startup delay is now really in minutes
  • Set default interval for incremental images value to correct text box
  • Timeout running image backups so that a new one can be started manually
  • Save less journal data
  • Do not save empty computernames
  • Made exclude pattern case insensitive on Windows
  • Allow reopening a file after timeout and do not timeout during pause
  • Fixed crash that occurred if a created shadow copy could not be deleted (e.g. hard disk unplugged)
  • Persist image on timeout
  • Correctly delete shadow copies for images with aborted backups

Apache configuration

BackupPC has a web interface that allows you to easily control it. You can access it using Apache and mod_perl or a C wrapper but other webservers like works too.
Install from the official repositories.

Edit Apache configuration

BackupPC’s web UI needs to run as the user backuppc, but Apache normally runs under the user http. There are several ways to fix this. The two demonstrated here are common for single-purpose servers (Apache is only used to serve the BackupPC UI) or for multi-purpose servers (Apache may also server other websites under the regular http user).

Setting up Apache for single-purpose use is a bit easier but not as flexible.

General settings

Edit . Set administrator name:

$Conf{CgiAdminUsers} = 'admin'; 

Next, we need to add a users file and set the admin password:

# htpasswd -c /etc/backuppc/backuppc.users admin

The BackupPC-Webfrontend is initially configured so that you can only access it from the localhost. If you want to access it from all machines in your network, you have to edit . Edit the line:

Require ip 127.0.0.1

to:

Require ip 127.0.0.1 192.168.0

where you have to replace 192.168.0 to your corresponding IP-Adresses you want to gain access from.
After one of the configuration steps below has also been performed, start the Apache service.

Single-purpose Apache settings

Install AUR from the official repositories.

Edit the Apache configuration file to load mod_perl, tell Apache to run as user backuppc and to include :

/etc/httpd/conf/httpd.conf
 LoadModule perl_module modules/mod_perl.so
 User backuppc
 Group backuppc
 Include conf/extra/backuppc.conf

Multi-purpose Apache settings

Instead of globally changing the Apache user and group like in the example above, we will instead make Apache run just the BackupPC CGI script as the backuppc user and leave the default user alone. This method uses mod_cgi to call a wrapper written in C instead of using the extra mod_perl dependency. You still need to have itself installed so the wrapper can run the BackupPC scripts.

Make sure Apache can run CGI programs (the line loading mod_cgi is not commented) and that it reads the BackupPC configuration by including it in :

/etc/httpd/conf/httpd.conf
 LoadModule cgi_module modules/mod_cgi.so
 ...
 Include conf/extra/backuppc.conf
The webserver user and the suid problem

The current setup of BackupPC, the webserver needs to run as backuppc user and this can be a problem on many setups where the webserver is used for other sites. In the past one could suid a Perl script, but it was blocked globally due security problems several years ago. To workaround that, perl-suid was used, but again blocked due the same problem more recently, scripts cannot be run securely with suid bit. Still there is another way, this time using a simple binary program that is suid as a launcher, that will run the backuppc Perl scripts already with the correct user. This isolates the Perl script from the environment and it is considered safe.

You need to replace the original backuppc CGI with the below C code compiled program and move the backuppc CGI to another place.

Move the real CGI to the lib directory .

Save the C code below to a file named wrapper.c (please update the CGI path if needed) and compile it with:

$ gcc -o BackupPC_Admin wrapper.c

The wrapper C code:

#include <unistd.h>
#define REAL_PATH "/usr/share/backuppc/lib/real-BackupPC_Admin.cgi"
int main(ac, av)
char **av;
{
   execv(REAL_PATH, av);
   return 0;
}

Place the new binary in the cgi-bin directory and chown the binary CGI to and set the suid bit:

# chown backuppc:http /usr/share/backuppc/cgi-bin/BackupPC_Admin
# chmod 4750 /usr/share/backuppc/cgi-bin/BackupPC_Admin

Do not forget to clear the suid bit on the original Perl script if it was set (or the CGI page will not load):

# chmod 0755 /usr/share/backuppc/lib/real-BackupPC_Admin.cgi

Keep your web server with its usual user and backup should now be able to run correctly.

Note: Keep in mind that the fix described in this section will be overwritten at every package upgrade, resulting in the BackupPC_Admin page displaying a message similar to Error: Wrong user: my userid is 33, instead of 126(backuppc). You will have to reapply the whole modification manually again to fix it.

Запуск резервного копирования вручную

Чтобы запустить процесс резервного копирования вручную, выберите свой клиент в раскрывающемся меню Hosts в верхнем левом углу.

На экране появится сводная страница клиента. Нажмите Start Full Backup в разделе User Actions. Затем подтвердите запуск.

Выполнение резервного копирования не займёт много времени (конечно, это зависит от объёма копируемой информации).

Файлы будут храниться в:

Это значение будет выведено на экран в разделе Backup Summary в сведениях Host summary.

Кнопка Browse backups в верхнем левом углу позволяет просмотреть файловую систему, скопированную BackupPC.

При помощи этого инструмента можно просмотреть файловую систему и выбрать файлы, которые нужно восстановить.

Where are the backups saved?

The backups are saved in the path you set during installation or in the web-interface. In this path there is one directory per client. Directly in this directory there are the image backups. They have the pattern . is the imaged partition. DD the date. MM the month. YY the year. HH the hour and MM the minute.
The file backups are in subdirectories with the pattern `YYMMDD-HHMM` (see above for explanation). `current` is a symbolic link to the most current finished file backup. The backups are ordered chronological if you sort by file or directory name. In the directory ‘clients’ there are links to the most current file backup of each client.

Бэкапы нужно обязательно разворачивать и проверять

Мало просто настраивать мониторинг бэкапов и оповещения. Я регулярно вручную проверяю все бэкапы. Да, это очень хлопотно, но другого выхода я не вижу. Если я этого не делаю, то перестаю спокойно спать.

Вот свежий , когда большая продуктовая база бэкапилась, но бэкап не проверялся. Автору повезло, что потерял только несколько записей. А мог и всю таблицу. Там, где можно, я автоматизирую разворачивание на запасном сервере с помощью простых bash скриптов. У меня бывали всякие ситуации, когда бэкапы по каким-то причинам переставали делаться. Если они физически отсутствуют, я получаю уведомление от zabbix. Но этого мало.

Особенно важно проверять дампы баз. Физическое наличие файла с дампом не означает, что вы без проблем его развернете

Надо проверять данные, заливая дамп в базу. Это единственный способ убедиться, что данные реально есть и они актуальны.

Установка BackupPC

Пакет BackupPC доступен в стандартных репозиториях Ubuntu.

Поскольку данная программа копирует данные с клиентской машины на сервер, нужно установить её на сервер А.

Запустите следующее через терминал:

Во время установки программа спросит, какой вид конфигурации почтового сервера нужно применить. Выберите Local only, чтобы настроить локальный почтовый сервер.

На следующей странице нужно указать Sytem mail name (например, localhost).

Далее нужно выбрать apache2, чтобы настроить Apache для использования BackupPC.

На следующей странице нажмите Enter, чтобы продолжить установку.

Бэкап всей Linux системы flyback

FlyBack основывится на использовании Rsync и является приблизительной моделью Apple Time Machine. Как и многие утилиты дополнительного копирования, базирующиеся на Rsync, пакет использует инкрементные резервные копии файлов, какие позже могут использоваться для восстановления. Создан на основе Rsync. Он создает инкрементные дополнительные копии файлов, как и другие резервные копии на основе Rsync, которые могут быть реконструированы позже. Хронологическое представление файловой системы, которое позволяет просматривать или извлекать раздельные файлы или каталоги по одному.

Они представляют вид стандартного файлового менеджера, который позволяет добавочным элементам управления перемещаться вперед и назад. FlyBack предоставляет хронологический взгляд на файловую систему, что случит возможным просматривать или искать в резервных копиях даже отдельные файлы. Flyback даётся пользователю в виде стандартного файл менеджера, учитывающей особенности конкретной файловой системы, но с добавочными возможностями двигаться во времени вперед или назад.

Server

UrBackup Server runs on GNU/Linux, Windows and FreeBSD.

There are some considerations however if you want advanced features like compression or block level deduplication.

File compression

If you want the backups to be compressed the underlying file system has to do that for UrBackup. In most cases this means the operating system has to support that. Since Windows Server 2003/XP Windows has, with NTFS, compression capability.

In Linux following filesystems support compression:

  • ReiserFS: This is not in the standard kernel
  • Fuse plugin: Like fusecompress
  • ZFSOnLinux
  • btrfs

Or use UrBackup server on FreeBSD/FreeNAS with ZFS.

Hard links

The backup file system has to be able to handle hard links and symbolic links. NTFS is able to handle both (Symbolic links (junctions) are supported since Windows Vista). All Linux/Unix file systems support hard links and symbolic links. FAT/ReFS does not support this.

Large files

The client images are saved into one large file. The file system has to be able to handle them.
On Windows NTFS supports very large files. You will not have any problems there. On Linux you have to enable the large file support in the kernel and for the specific file system. Nowadays this is enabled per default. Then the maximum file size depends on the used file system. With ext3 it can be as small as 16GB if the drive is formatted with a small block size. Usually it is 2TB though (with standard block size).

Deduplication

With deduplication data blocks which are the same in different files are saved only once on the hard disk. ZFS is able to do that. There are also professional storage systems which do deduplication — sometimes in hardware. Btrfs does support offline deduplication. There are some other fuse file systems which support deduplication but those do not seem to be stable or performant.
If ZFS is chosen you should put enough RAM into the backup server otherwise deduplication will cause a huge slowdown. UrBackup can be configured to accommodate a slow deduplicated backup storage.
Another option is to use the Windows Server offline deduplication (and compression) available since Windows Server 2012 (with NTFS).

UrBackup can also use btrfs in a way that makes deduplication sometimes unnecessary. See .

Резервное копирование по SSH

Для использования протокола Настройка и использование SSH для резервного копирования данных с клиентского компьютера, следует создать ключи доступа.

Сервер

# su - backuppc
$ mkdir .ssh
$ cd .ssh
$ ssh-keygen -t rsa -C remuserbak@backuppc

на все вопросы просто жмем клавишу Enter

$ chmod 600 id_rsa
$ ls -l 
-rw------- 1 backuppc backuppc 1675 Фев 12 14:59 id_rsa
-rw-r--r-- 1 backuppc backuppc  401 Фев 12 14:59 id_rsa.pub

С приватным ключом id_rsa программа BackupPC будет подключаться к клиентским компьютерам. На клиентские компьютер должен быть перенесён публичный ключ, сделаем это при помощи утилиты Настройка и использование SSH-copy-id, она автоматически создаст файл authorized_keys с нашим ключем в директории .ssh. Например:

ssh-copy-id -i id_rsa.pub remuserbak@<IP клиента>

Клиент Ubuntu 16.04.3 LTS

Создаем пользователя от имени которого будет производиться копирование данных и задаем ему сложный пароль. Пароль нам понадобится один раз для копирования ssh ключа.

adduser remuserbak
usermod -aG sudo,adm remuserbak

Даем права на запуск sudo без пароля пользователю remuserbak. В самый конец файла добавляем строчку

> visudo
remuserbak ALL=NOPASSWD: bintar, usrbinrsync

Переносим публичный ключ, сделаем это при помощи утилиты SSH-copy-id. Для этого на сервере, где установлен сервер BackupPC, от имени пользователя, от которого запускается демон backuppc, запускаем утилиту ssh-copy-id

su - backuppc
ssh-copy-id -i .sshid_rsa.pub remuserbak@xxx.xxx.xxx.xxx

Для того того что все работает, подключитесь к клиентскому компьютеру используя команду

ssh 'remuserbak@xxx.xxx.xxx.xxx'

Дальнейшая настройка происходит через веб-интерфейс

http://backuppc_server_ip/backuppc
  1. Страница Edit Hosts добавляем адрес клиента и имя пользователя, от которого будет совершаться копирование данных, в нашем примере это пользователь remuserbak
  2. В настройках клиента, на странице Xfer Settings указываем XferMethod = Использование rsync в примерах, в параметре RsyncShareName задаем директории для копирования
  3. Не забываем заменить пользователя root на remuserbak в строках RsyncClientCmd и RsyncClientRestoreCmd. Эти изменения можно задать как глобально для всего сервера BackupPC, так и индивидуально для каждого клиента. Не забываем явно для каждого клиента задавать путь к sudo.

    $Conf{RsyncClientCmd} = '$sshPath -q -x -l remuserbak $host /usr/bin/sudo $rsyncPath $argList+';
    $Conf{RsyncClientRestoreCmd} = '$sshPath -q -x -l remuserbak $host /usr/bin/sudo $rsyncPath $argList+';
  4. Всё!

1.4 beta 1

Major changes:

  • New Status screen which shows the current connection status, progress, an ETA, and current servers
  • Client side hash performance improvements
  • Server public key authentication additionally to the server identity
  • Use fully qualified domain names as default computer names in new installs

Changes:

  • Don’t delete file entries if include/exclude pattern changed, but do not use db during indexing
  • Execute postindex hook directly after indexing
  • Update start time of shadow copy while imaging, so that it does not time out on really long image backups (more than one week)
  • Filter useless error messages in connection with change journal entries
  • Remove need of newline at end of server_idents.txt file
  • Don’t require change journal close for change entry to be written. Increase entry cache time.
  • Be more conservative about which files changed
  • Added Linux version querying. Made windows version querying more maintainable.
  • Setting value (“ALL”) to backup all attached volumes
  • Return error if a directory to backup is or becomes inaccessible. Added flag to mark directories as optional
  • Show that backups are resumed
  • Increased buffer size for hashing
  • More icon states (you can change the icon color if you want)
  • Secured client log and server identities (permissions)
  • Internet client timeouts sooner if backup is running
  • Show “Indexing” instead of “0% done” during indexing on the client.
  • Only allow administrators to change paths and settings
  • Added more change journal indexing logging

Bugfixes:

  • Don’t lower case path in database on Linux
  • Fixed bugs in connection with multiple simultaneous backups with multiple servers
  • Fixed issue with multiple last_backup_time keys

1.3

Changes:

  • Log information about VSS creation and indexing
  • Added Danish as translation (thanks goes to tnywos)
  • Added Ukrainian as translation (thanks goes to Ihor Maydanovich)
  • Added Polish as translation (thanks goes to drpt)
  • Added Portuguese – Brazil as translation (thanks goes to Artur Corumba)
  • Added Italian as translation (thanks goes to paolobeldi)
  • Added Slovak as translation (thanks goes to janda)
  • Added dutch translation (thanks goes to buzzertnl)

Bugfixes:

  • Inform writers when creating Volume Shadow Copies on Windows
  • Correctly handle failed VSS writers (including retrying on retryable errors)
  • Retry snapshot operation if writer failed and has the retryable error
  • Trim identities when loading them from identity file
  • Scan for changed hard links on Windows
  • Always lookup the urbackup\ directory on the filesystem because changes there are ignored in the change journal watcher
  • Automatically add pagefile.sys and hiberfil.sys to the exclude list
  • Fixed problem with gettext (percentage character %)

Alternative lighttpd configuration

/etc/lighttpd/lighttpd.conf
 server.port             = 81
 server.username         = "backuppc"
 server.groupname        = "backuppc"
 server.document-root    = "/srv/http"
 server.errorlog         = "/var/log/lighttpd/error.log"
 dir-listing.activate    = "enable"
 index-file.names        = ( "index.html", "index.php", "index.cgi" )
 mimetype.assign         = ( ".html" => "text/html", ".txt" => "text/plain", ".jpg" => "image/jpeg", ".png" => "image/png", "" => "application/octet-stream" )
 
 server.modules = ("mod_alias", "mod_cgi", "mod_auth", "mod_access" )
 
 alias.url               = ( "/BackupPC_Admin" => "/usr/share/backuppc/cgi-bin/BackupPC_Admin" )
 alias.url               += ( "/backuppc" => "/usr/share/backuppc/html" )
 
 cgi.assign              += ( ".cgi" => "/usr/bin/perl" )
 cgi.assign              += ( "BackupPC_Admin" => "/usr/bin/perl" )
 
 auth.backend = "plain"
 auth.backend.plain.userfile = "/etc/lighttpd/passwd"
 auth.require = ( "/BackupPC_Admin" => ( "method" => "basic", "realm" => "BackupPC", "require" => "user=admin" ) )
/etc/lighttpd/passwd
 admin:yourpassword

And create log file:

# touch /var/log/lighttpd/error.log
# chown backuppc:backuppc /var/log/lighttpd/error.log

2.0.36

Changes:

  • Fix timeout issue with connection encryption
  • Fix sysconf path in client scripts
  • Do not remove shadow copies for image backup after client restart if there are multiple concurrent jobs
  • Read computer name from default setting as fallback
  • Set internet client to not connected if no internet servers are configured
  • Output more detailed error information in sysvol_test
  • Prevent uninitialized device type on error in SYSVOL search
  • Use proper param string escape function to fix e.g. adding paths with ‘+’ in them
  • Fix issue with single file backup being a symbolic link
  • Fix default includes when selecting the second option (backup only documents, pictures, …) in wizard
  • Fix enable_internet_only.bat on Windows
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector