- rsync
- Contents
- Installation
- Front-ends
- As cp/mv alternative
- Trailing slash caveat
- As a backup utility
- Automated backup
- Automated backup with SSH
- Automated backup with NetworkManager
- Automated backup with systemd and inotify
- Differential backup on a week
- Snapshot backup
- Full system backup
- Restore a backup
- File system cloning
- rsync daemon
- Example configuration
- Sharing from a list of files
- Организация backup-сервера. Linux, ZFS и rsync
- 1. ZFS с компрессией и дедубликацией
- 2. Rsync на сервере
- 3. Rsync на клиентах
- 4. Восстановление
- 5. Заключение
rsync
rsync is an open source utility that provides fast incremental file transfer.
Contents
Installation
rsync must be installed on both the source and the destination machine.
Front-ends
- Grsync — GTK front-end.
https://www.opbyte.it/grsync/ || grsync
- gutback — rsync wrapper written in Shell.
https://github.com/gutenye/gutbackup || gutbackupAUR
- JotaSync — Java Swing GUI for rsync with integrated scheduler.
https://trixon.se/projects/jotasync/ || jotasyncAUR
- luckyBackup — Qt front-end written in C++.
http://luckybackup.sourceforge.net/index.html || luckybackupAUR
Other tools using rsync are rdiff-backup and osync AUR .
As cp/mv alternative
rsync can be used as an advanced alternative for the cp or mv command, especially for copying larger files:
The -P option is the same as —partial —progress , which keeps partially transferred files and shows a progress bar during transfer.
You may want to use the -r / —recursive option to recurse into directories.
Files can be copied locally as with cp, but the motivating purpose of rsync is to copy files remotely, i.e. between two different hosts. Remote locations can be specified with a host-colon syntax:
Network file transfers use the SSH protocol by default and host can be a real hostname or a predefined profile/alias from .ssh/config .
Whether transferring files locally or remotely, rsync first creates a file-list containing information (by default, it is the file size and last modification timestamp) which will then be used to determine if a file needs to be constructed. For each file to be constructed, a weak and strong checksum is found for all blocks such that each block is of length S bytes, non-overlapping, and has an offset which is divisible by S. Using this information a large file can be constructed using rsync without having to transfer the entire file. For a more detailed practical explanation and detailed mathematical explanation refer to how rsync works and the rsync algorithm, respectively.
To use sane defaults quickly, you could use some aliases:
Trailing slash caveat
Arch by default uses GNU cp (part of GNU coreutils ). However, rsync follows the convention of BSD cp, which gives special treatment to source directories with a trailing slash «/». Although
creates a directory «destination/source» with the contents of «source», the command
copies all of the files in «source/» directly into «destination», with no intervening subdirectory — just as if you had invoked it as
This behavior is different from that of GNU cp, which treats «source» and «source/» identically (but not «source/.»). Also, some shells automatically append the trailing slash when tab-completing directory names. Because of these factors, there can be a tendency among new or occasional rsync users to forget about rsync’s different behavior, and inadvertently create a mess or even overwrite important files by leaving the trailing slash on the command line.
Thus it can be prudent to use a wrapper script to automatically remove trailing slashes before invoking rsync:
This script can be put somewhere in the path, and aliased to rsync in the shell init file.
As a backup utility
The rsync protocol can easily be used for backups, only transferring files that have changed since the last backup. This section describes a very simple scheduled backup script using rsync, typically used for copying to removable media.
Automated backup
For the sake of this example, the script is created in the /etc/cron.daily directory, and will be run on a daily basis if a cron daemon is installed and properly configured. Configuring and using cron is outside the scope of this article.
First, create a script containing the appropriate command options:
-a indicates that files should be archived, meaning that most of their characteristics are preserved (but not ACLs, hard links or extended attributes such as capabilities) —delete means files deleted on the source are to be deleted on the backup as well
Here, /path/to/backup should be changed to what needs to be backed-up (e.g. /home ) and /location/of/backup is where the backup should be saved (e.g. /media/disk ).
Finally, the script must be executable:
Automated backup with SSH
If backing-up to a remote host using SSH, use this script instead:
-e ssh tells rsync to use SSH remoteuser is the user on the host remotehost -a groups all these options -rlptgoD (recursive, links, perms, times, group, owner, devices)
Automated backup with NetworkManager
This script starts a backup when network connection is established.
First, create a script containing the appropriate command options:
-a group all this options -rlptgoD recursive, links, perms, times, group, owner, devices —files-from read the relative path of /path/to/backup from this file —bwlimit limit I/O bandwidth; KBytes per second
Automated backup with systemd and inotify
Instead of running time interval backups with time based schedules, such as those implemented in cron, it is possible to run a backup every time one of the files you are backing up changes. systemd.path units use inotify to monitor the filesystem, and can be used in conjunction with systemd.service files to start any process (in this case your rsync backup) based on a filesystem event.
First, create the systemd.path file that will monitor the files you are backing up:
Then create a systemd.service file that will be activated when it detects a change. By default a service file of the same name as the path unit (in this case backup.path ) will be activated, except with the .service extension instead of .path (in this case backup.service ).
Now all you have to do is start/enable backup.path like a normal systemd service and it will start monitoring file changes and automatically start backup.service .
Differential backup on a week
This is a useful option of rsync, resulting in a full backup (on each run) and keeping a differential backup copy of changed files only in a separate directory for each day of a week.
First, create a script containing the appropriate command options:
—inplace implies —partial update destination files in-place
Snapshot backup
The same idea can be used to maintain a tree of snapshots of your files. In other words, a directory with date-ordered copies of the files. The copies are made using hardlinks, which means that only files that did change will occupy space. Generally speaking, this is the idea behind Apple’s TimeMachine.
This basic script is easy to implement and creates quick incremental snapshots using the —link-dest option to hardlink unchanged files:
There must be a symlink to a full backup already in existence as a target for —link-dest . If the most recent snapshot is deleted, the symlink will need to be recreated to point to the most recent snapshot. If —link-dest does not find a working symlink, rsync will proceed to copy all source files instead of only the changes.
A more sophisticated version keeps an up-to-date full backup $SNAP/latest and in case a certain number of files has changed since the last full backup, it creates a snapshot $SNAP/$DATETAG of the current full-backup utilizing cp -al to hardlink unchanged files:
To make things really, really simple this script can be run from a systemd/Timers unit.
Full system backup
This section is about using rsync to transfer a copy of the entire / tree, excluding a few selected directories. This approach is considered to be better than disk cloning with dd since it allows for a different size, partition table and filesystem to be used, and better than copying with cp -a as well, because it allows greater control over file permissions, attributes, Access Control Lists and extended attributes.
rsync will work even while the system is running, but files changed during the transfer may or may not be transferred, which can cause undefined behavior of some programs using the transferred files.
This approach works well for migrating an existing installation to a new hard drive or SSD.
Run the following command as root to make sure that rsync can access all system files and preserve the ownership:
By using the -aAX set of options, the files are transferred in archive mode which ensures that symbolic links, devices, permissions, ownerships, modification times, ACLs, and extended attributes are preserved, assuming that the target file system supports the feature. The option -H preserves hard links, but uses more memory.
The —exclude option causes files that match the given patterns to be excluded. The directories /dev , /proc , /sys , /tmp , and /run are included in the above command, but the contents of those directories are excluded. This is because they are populated on boot, but the directories themselves are not created. /lost+found is filesystem-specific. The command above depends on brace expansion available in both the bash and zsh shells. When using a different shell, —exclude patterns should be repeated manually. Quoting the exclude patterns will avoid expansion by the shell, which is necessary, for example, when backing up over SSH. Ending the excluded paths with * ensures that the directories themselves are created if they do not already exist.
You may want to include additional rsync options, or remove some, such as the following. See rsync(1) for the full list.
- If you run on a system with very low memory, consider removing -H option; however, it should be no problem on most modern machines. There can be many hard links on the file system depending on the software used (e.g. if you are using Flatpak). Many hard links reside under the /usr/ directory.
- You may want to add rsync’s —delete option if you are running this multiple times to the same backup directory. In this case make sure that the source path does not end with /* , or this option will only have effect on the files inside the subdirectories of the source directory, but it will have no effect on the files residing directly inside the source directory.
- If you use any sparse files, such as virtual disks, Docker images and similar, you should add the -S option.
- The —numeric-ids option will disable mapping of user and group names; instead, numeric group and user IDs will be transfered. This is useful when backing up over SSH or when using a live system to backup different system disk.
- Choosing —info=progress2 option instead of -v will show the overall progress info and transfer speed instead of the list of files being transferred.
- To avoid crossing a filesystem boundary when recursing, add the option -x / —one-file-system . This will prevent backing up any mount point in the hierarchy.
Restore a backup
If you wish to restore a backup, use the same rsync command that was executed but with the source and destination reversed.
File system cloning
rsync provides a way to do a copy of all data in a file system while preserving as much information as possible, including the file system metadata. It is a procedure of data cloning on a file system level where source and destination file systems do not need to be of the same type. It can be used for backing up, file system migration or data recovery.
rsync’s archive mode comes close to being fit for the job, but it does not back up the special file system metadata such as access control lists, extended attributes or sparse file properties. For successful cloning at the file system level, some additional options need to be provided:
And their meaning is (from the manpage):
Additionally, use -x if you have other filesystems mounted under the tree that you want to exclude from the copy. Produced copy can be simply reread and checked (for example after a data recovery attempt) at the file system level with diff ‘s recursive option:
It is possible to do a successful file system migration by using rsync as described in this article and updating the fstab and bootloader as described in Migrate installation to new hardware. This essentially provides a way to convert any root file system to another one.
rsync daemon
rsync can be run as daemon on a server listening on port 873 .
Edit the template /etc/rsyncd.conf , configure a share and start the rsyncd.service .
Usage from client, e.g. list server content:
transfer file from client to server:
Consider iptables to open port 873 and user authentication.
Example configuration
Sharing from a list of files
Inside the file list, all the intermediary paths are necessary, except when the *** wildcard is used:
Источник
Организация backup-сервера. Linux, ZFS и rsync
TL;DR:
Статья о настройке бекапа линуксовых серверов. В качестве хранилища используется раздел ZFS с включенными дедубликацией и компрессией. Ежедневно делаются снапшоты, которые сохраняются в течение недели (7 штук). Ежемесячные снапшоты хранятся в течение года (еще 12 штук). В качестве транспорта выступает rsync: на сервере он запущен демоном, на клиентах он запускается из crontab.
Так получилось, что у меня есть пара серверов, на которых под KVM живут виртуальные машины. Хотелось бекапить образы этих машин в сеть, но так, чтобы выполнялись условия:
- Хранить все бекапы за последнюю неделю.
- Хранить в течении года ежемесячные бекапы.
- Никаких сторонних бекап-агентов. На клиентах только стандартное и проверенное поколениями админов ПО.
- Экономно расходовать место в хранилище. Желательна компрессия и дедубликация данных.
- Все файлы должны быть доступны без дополнительных инструментов и оболочек. Идеальный вариант: каждый бекап в отдельном каталоге.
Можно ли всё это совместить? Да, и очень просто.
Все компьютеры, о которых идет речь в этой статье, являются серверами. Но как-то глупо и длинно делить их на “сервер, который хранит бекапы” и “сервер, бекапы которого хранит сервер, который хранит бекапы”. Поэтому первый я буду называть просто сервером, а второй уже начал называть клиентом.
1. ZFS с компрессией и дедубликацией
Наиболее привычная для меня ОС – Linux. Всё то же самое без особых изменений должно подойти и к Solaris, и к FreeBSD, в которых ZFS есть давно и что называется “из коробки”. Но Linux мне ближе и роднее, а проект по портированию на него ZFS выглядит уже достаточно зрелым. За год экспериментов у меня не было с ним заметных проблем. Поэтому поставил на сервер Debian Wheezy, подключил официальный репозитарий проекта и установил нужные пакеты.
Создал пул, указав что zfs у меня будет на /dev/md1 и что монтировать эту файловую систему я хочу к каталогу /mnt/backup:
По имени устройства /dev/md1 можно заметить, что я использую линуксовый software raid. Да, я знаю, что у ZFS есть свой способ создавать зеркала. Но поскольку на этой машине уже есть одно зеркало (для корневого раздела) и оно сделано штатным mdadm, то и для второго зеркала я предпочту использовать его же.
Включил дедубликацию и компрессию, сделал видимым каталог со снапшотами:
Положил в /usr/local/bin скрипт для создания снапшотов:
Этот скрипт добавил в crontab для ежедневного запуска. Чтобы содержимое снапшота соответствовало его дате, скрипт лучше запускать ближе к концу суток. Например, в 23:55.
Четвертое число месяца выбрано почти случайно. Запускал я всё этого третьего августа и хотелось поскорее сделать бекап, который будет храниться год. Следующий день был четвертым.
Снапшоты будут сохраняться в каталоге /mnt/backup/.zfs/snapshot. Каждый снапшот – отдельный каталог с именем в виде даты на момент создания этого снапшота. Внутри снапшота полная копия каталога /mnt/backup в том виде, в котором он был в этот момент.
2. Rsync на сервере
Традиционно rsync настраивают для работы поверх ssh. На клиентах настраивается авторизация по ключам (и без пароля), а эти ключи складываются на бекап-сервер. Сервер ходит по ssh на клиентов и забирает с них файлы. Преимущество этого подхода – шифрование трафика. Но мне не нравится идея с беспарольным входом по ssh (особенно в свете последних уязвимостей в bash). Так же мне не нравится идея инициировать бекап со стороны сервера: иногда перед бекапом на клиенте хочется выполнить какой-нибудь скрипт (например, сбросить дамп mysql), и только после завершения этого скрипта начинать бекап. Поэтому мой выбор – rsync, запущенный демоном на сервере и запускаемый из crontab на клиентах.
Поставил на сервер rsync (штатный, из репозитария), и чтобы он запускался при старте системы, написал в /etc/default/rsync:
Создал на сервере /etc/rsyncd.conf такого содержания:
192.168.xxx.xxx и 192.168.xxx.yyy – это адреса тех серверов, которые будут бекапиться. Зовут их kvm01 и kvm02. Их файлы будут лежать в /mnt/backup/kvm01 и /mnt/backup/kvm02. Поэтому:
3. Rsync на клиентах
Минимально необходимый скрипт для копирования файлов с клиента kvm02 на сервер с адресом 192.168.xxx.zzz будет выглядеть примерно так:
Разумется, если речь идет о бекапе виртуальных машин, то этот скрипт стоит пополнить командами создания и удаления LVM-снапшота, монтирования и отмонтирования его содержимого и так далее. Но эта тема уже выходит за рамки данной статьи.
4. Восстановление
Для восстановления файлов из бекапа клиента KVM01 за 4 августа 2014 года достаточно будет на сервере перейти в каталог /mnt/backup/.zfs/snapshot/2014-08-04/kvm01/ и скопировать оттуда файлы любым привычным способом. Каждый конкретный бекап выглядит как обычный каталог, доступный только для чтения. Для поиска определенного файла в этом бекапе можно использовать стандартные утилиты, такие как find или grep.
5. Заключение
Сейчас на сервере 9 снапшотов: 7 ежедневных и 2 ежемесячных. Плюс сегодняшний бекап, снапшот с которого снимется вечером. Размер раздела с бекапами составляет 1.8T. Общий объем файлов — 3.06T. Физически занимают на диске они 318G. Суммарный объем сегодняшнего бекапа — 319G. Да, 10 бекапов на ZFS с компрессией и дедубликацией занимают места меньше, чем один бекап занимал бы на файловой системе без этих полезных свойств.
Поскольку сам rsync не занимается шифрованием передаваемых данных, высовывать такую схему без изменений в интернет небезопасно. Добавить шифрование можно, пустив трафик через ipsec или stunnel, например.
Выше я написал, что заметных проблем с ZFS у меня не было. На самом деле, одна проблема была. Однажды ночью, когда оба клиента активно бекапились, сервер дважды сообщил в dmesg, что task rsync blocked for more than 120 seconds. При этом оба бекапа успешно завершились, ничего не зависло, данные не потерялись. Подозреваю, что это проявление знаменитого бага 12309. Разнес бекапы по времени, с тех пор проблема не повторялась.
Источник