Примеры синхронизации rsync

Algorithm

Determining which files to send

By default, rsync determines which files differ between the sending and receiving systems by checking the modification time and size of each file. If time or size is different between the systems, it transfers the file from the sending to the receiving system. As this only requires reading file directory information, it is quick, but it will miss unusual modifications which change neither.

Rsync performs a slower but comprehensive check if invoked with . This forces a full checksum comparison on every file present on both systems. Barring rare checksum collisions, this avoids the risk of missing changed files at the cost of reading every file present on both systems.

Determining which parts of a file have changed

The rsync utility uses an algorithm invented by Australian computer programmer Andrew Tridgell for efficiently transmitting a structure (such as a file) across a communications link when the receiving computer already has a similar, but not identical, version of the same structure.

The recipient splits its copy of the file into chunks and computes two checksums for each chunk: the MD5 hash, and a weaker but easier to compute ‘rolling checksum’. It sends these checksums to the sender.

The sender computes the checksum for each rolling section in its version of the file having the same size as the chunks used by the recipient’s. While the recipient calculates the checksum only for chunks starting at full multiples of the chunk size, the sender calculates the checksum for all sections starting at any address. If any such rolling checksum calculated by the sender matches a checksum calculated by the recipient, then this section is a candidate for not transmitting the content of section, but only the location in the recipients file instead. In this case the sender uses the more computationally expensive MD5 hash to verify that the sender’s section and recipient’s chunk are equal. Note that the section in the sender must be not at the same start address as the chunk at the recipient. This allows efficient transmission of files which differ by insertions and deletions. The sender then sends the recipient those parts of its file that did not match, along with information on where to merge existing blocks into the recipient’s version. This makes the copies identical.

The rolling checksum used in rsync is based on Mark Adler’s adler-32 checksum, which is used in zlib, and is itself based on Fletcher’s checksum.

If the sender’s and recipient’s versions of the file have many sections in common, the utility needs to transfer relatively little data to synchronize the files. If typical data compression algorithms are used, files that are similar when uncompressed may be very different when compressed, and thus the entire file will need to be transferred. Some compression programs, such as gzip, provide a special «rsyncable» mode which allows these files to be efficiently rsynced, by ensuring that local changes in the uncompressed file yield only local changes in the compressed file.

Rsync supports other key features that aid significantly in data transfers or backup. They include compression and decompression of data block by block using zlib, and support for protocols such as ssh and stunnel.

Variantes

Existen otras utilidades basadas en el algoritmo de rsync.

  • rdiff, que genera archivos delta con la diferencia entre dos archivos, que puede ser aplicada a uno para convertirlo en el otro en cualquier momento.
  • rdiff-backup, que utiliza rdiff para mantener espejos de backup de un directorio a través de una red. Rdiff-backup almacena delta rdiff incrementales, lo que permite recrear el directorio en cualquier punto de backup.

Existen además versiones para otros sistemas operativos, como rsyncX, una versión para Mac OS X que permite transferir forks de recursos, y que en su versión rsyncXCD permite además crear particiones booteables.

Incluso es posible utilizar rsync en Microsoft Windows, a través de Cygwin.

Connection

An rsync process operates by communicating with another rsync process, a sender and a receiver. At startup, an rsync client connects to a peer process. If the transfer is local (that is, between file systems mounted on the same host) the peer can be created with fork, after setting up suitable pipes for the connection. If a remote host is involved, rsync starts a process to handle the connection, typically Secure Shell. Upon connection, a command is issued to start an rsync process on the remote host, which uses the connection thus established. As an alternative, if the remote host runs an rsync daemon, rsync clients can connect by opening a socket on TCP port 873, possibly using a proxy.

Rsync has numerous command line options and configuration files to specify alternative shells, options, commands, possibly with full path, and port numbers. Besides using remote shells, tunnelling can be used to have remote ports appear as local on the server where an rsync daemon runs. Those possibilities allow adjusting security levels to the state of the art, while a naive rsync daemon can be enough for a local network.

Variations

The rdiff utility uses the rsync algorithm to generate delta files with the difference from file A to file B (like the utility diff, but in a different delta format). The delta file can then be applied to file A, turning it into file B (similar to the patch utility). rdiff works well with binary files.

The rdiff-backup script maintains a backup mirror of a file or directory either locally or remotely over the network on another server. rdiff-backup stores incremental rdiff deltas with the backup, with which it is possible to recreate any backup point.

The librsync library used by rdiff is an independent implementation of the rsync algorithm. It does not use the rsync network protocol and does not share any code with the rsync application. It is used by Dropbox, rdiff-backup, duplicity, and other utilities.

The acrosync library is an independent, cross-platform implementation of the rsync network protocol. Unlike librsync, it is wire-compatible with rsync (protocol version 29 or 30). It is released under the Reciprocal Public License and used by the commercial rsync software Acrosync.

Duplicity is a variation on rdiff-backup that allows for backups without cooperation from the storage server, as with simple storage services like Amazon S3. It works by generating the hashes for each block in advance, encrypting them, and storing them on the server. It then retrieves them when doing an incremental backup. The rest of the data is also stored encrypted for security purposes.

As of macOS 10.5 and later, there is a special or switch which allows retaining much of the HFS file metadata when syncing between two machines supporting this feature. This is achieved by transmitting the Resource Fork along with the Data Fork.

zsync is an rsync-like tool optimized for many downloads per file version. zsync is used by Linux distributions such as Ubuntu for distributing fast changing beta ISO image files. zsync uses the HTTP protocol and .zsync files with pre-calculated rolling hash to minimize server load yet permit diff transfer for network optimization.

Rclone is an open-source tool inspired by rsync that focuses exclusively on cloud storage system providers. It supports more than 50 different providers and provides an rsync-like interface to backup local data to those providers.

Как альтернатива cp/mv

rsync может использоваться как продвинутая альтернатива команде или , особенно при копировании больших файлов.

$ rsync -P источник назначение

Опция эквивалентна , которая оставляет частично перемещённые файлы и показывает шкалу прогресса во время перемещения.

Используйте опцию / для рекурсивного обхода каталогов.

Файлы могут копироваться локально, как при помощи cp, но rsync интересна прежде всего возможностью удалённого копирования файлов, то есть между двумя разными хостами. Удалённые расположения могут быть указаны при помощи синтаксиса хост-двоеточие:

$ rsync источник хост:назначение

или

$ rsync хост:источник назначение

Передача файлов по сети по умолчанию использует протокол SSH и может быть как реальным именем хоста, так и предопределённым профилем/псевдонимом из .

Для быстрого использования разумных значений по умолчанию, можете использовать следующие псевдонимы:

function cpr() {
  rsync --archive -hh --partial --info=stats1 --info=progress2 --modify-window=1 "$@"
} 
function mvr() {
  rsync --archive -hh --partial --info=stats1 --info=progress2 --modify-window=1 --remove-source-files "$@"
}

Примечание: Использование термина контрольная сумма не соответствует поведению опции . Опция ответственна за использование эвристики пропуска файла перед передачей любого файла. Независимо от , контрольная сумма всегда используется для поблочного построения файла, при помощи которого rsync перемещает файл.

Предостережение о замыкающем слэше

По умолчанию Arch использует GNU cp (часть GNU ). Однако rsync следует соглашениям BSD cp, которые особо обрабатывают каталоги источника с замыкающим слэшем «/». Несмотря на то, что

$ rsync -r источник назначение

создаёт каталог «назначение/источник» с содержимым «источника», команда

$ rsync -r источник/ назначение

копирует все файлы из «источник/» напрямую в «назначение», без промежуточного каталога — так же, как при вызове

$ rsync -r источник/. назначение

Это поведение отличается от такового в GNU cp, которая одинаково обрабатывает «источник» и «источник/» (но не «источник/.»). Кроме того, некоторые оболочки автоматически добавляют замыкающий слэш при tab-дополнении имён каталогов. В виду этих обстоятельств, новые или нечастые пользователи rsync могут зачастую забывать про разное поведение rsync и случайно создавать беспорядок или даже перезаписывать важные файлы, оставляя замыкающий слэш в командной строке.

Поэтому имеет смысл использовать сценарий-обёртку, чтобы автоматически удалять замыкающий слэш перед вызовом rsync:

#!/bin/zsh
new_args=();
for i in "$@"; do
    case $i in /) i=/;; */) i=${i%/};; esac
    new_args+=$i;
done
exec rsync "${(@)new_args}"

Этот сценарий может быть размещён где-нибудь в и назначен псевдонимом для rsync в файле инициализации оболочки.

Организуем резервное копирование своих данных с помощью rsync

Регулярное сохранение резервных копий является необычайно важной, но, как правило, игнорируемой рутинной работой. Ни длительность процедуры резервного копирования, ни потребность в наличии большого внешнего хранилища файлов, ни что-либо другое не могут являться оправданием; копирование данных для обеспечения их сохранности должно быть ежедневной процедурой

Чтобы сделать эту задачу безболезненной, используйте для резервного копирования
и удаленный сервер, возможно, предоставляемый вашим провайдером. Каждая из
ваших UNIX-машин может использовать этот механизм, который является идеальным решением
для безопасного хранения ваших данных.

Установите на удаленной машине ключи SSH, демон и создайте модуль
для резервного копирования, разрешающий запись. После этого запустите rsync и, как показано в сценарии
из , создавайте резервные копии, которые едва ли будут занимать много места.

Листинг 9. Создаем ежедневные резервные копии файлов
#!/bin/sh
# This script based on work by Michael Jakl (jakl.michael AT gmail DOTCOM) and used 
# with express permission.
HOST=mymachine.example.com
SOURCE=$HOME
PATHTOBACKUP=home-backup

date=`date "+%Y-%m-%dT%H:%M:%S"`

rsync -az --link-dest=$PATHTOBACKUP/current $SOURCE $HOST:PATHTOBACKUP/back-$date

ssh $HOST "rm $PATHTOBACKUP/current && ln -s back-$date $PATHTOBACKUP/current"

Замените именем вашего сервера резервного копирования, а – директорией,
которую вы хотите сохранять. Замените на имя модуля. (Также три последние
строки сценария можно заключить в цикл и, изменяя переменную , делать резервные
копии множества директорий). Данный сценарий работает следующим образом.

  • Сначала в переменную помещается строка вида
    , содержащая текущую дату и время; эта строка будет
    уникально идентифицировать каждую резервную копию.
  • Главную работу здесь выполняет команда rsync. Параметры сохраняют всю
    информацию о файлах и выполняют сжатие данных перед их передачей, а параметр
    указывает, что если какой-либо файл не
    менялся, нужно не копировать его в новый экземпляр резервной копии, а создать
    жесткую ссылку, указывающую на этот файл в существующем архиве. Другими словами,
    новая резервная копия содержит только файлы, претерпевшие изменения, остальные
    файлы являются ссылками.

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

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

  • В последнем шаге мы изменяем организацию резервных копий на удаленной машине, чтобы сделать вновь созданный архив текущим архивом и таким образом минимизировать различия, которые нужно будет записать во время следующего выполнения сценария. В последней команде удаляется текущий архив, (который является просто жесткой ссылкой) и создается символическая ссылка с тем же именем, указывающая на новый архив.

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

Настройка

Открываем конфигурационный файл rsync:

vi /etc/rsyncd.conf

И настраиваем его, примерно, следующим образом:

max connections = 10
exclude = lost+found/
dont compress   = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2 *.rar *.7z *.mp3 *.jpg
 

    path = /data1/
    comment = Public folders
    read only = yes
    list = yes
    auth users = rsync_d1
    secrets file = /etc/rsyncd.scrt
    hosts allow = localhost 192.168.0.15 192.168.0.20
    hosts deny = *
 

    uid = root
    gid = root
    path = /data2/
    comment = Private folders
    read only = yes
    list = yes
    auth users = rsync_d2, backup
    secrets file = /etc/rsyncd.scrt
    hosts allow = localhost 192.168.0.16 192.168.0.21
    hosts deny = *

где первая группа параметров являются общими настройками:

  • max connections — максимальное число одновременных подключений. Стоит задать, чтобы не перегружать сервер.
  • exclude — папки, которые стоит исключить из синхронизации. В конкретном примере каталог для размещения восстановленных после проверки диска файлов.
  • dont compress — указываем, какие файлы не нужно сжимать при отправке. Имеет смысл указать те, сжатие которых не даст результата, например, архивы, сжатые аудио и изображения.

а также каждый ресурс настраивается отдельно (в нашем примере data1 и data2):

  • uid — пользователь, от которого будет выполнена синхронизация для конкретного ресурса.
  • gid — группа, от которой будет выполнена синхронизация для конкретного ресурса.
  • path — путь до ресурса, для которого выполняется синхронизация.
  • comment — описание для удобства.
  • read only — режим для чтения; позволяет защитить данные от удаления или изменения.
  • list — разрешает или запрещает чтения содержимого каталога. Если запрещено (no), синхронизация может выполняться для конкретно перечисленных файлов.
  • auth users — проверка подлинности, вводом логина с паролем.
  • secrets file — файл, в котором размещены логин и пароль.
  • hosts allow — перечисление хостов, с которых разрешено обращаться к rsync серверу.
  • hosts deny — перечисление хостов, с которых запрещено обращаться к rsync серверу (в данном примере, со всех, кроме разрешенных).

Создаем файл для аутентификации:

vi /etc/rsyncd.scrt

rsync_d1:password1
rsync_d2:password2
backup:password3

* где rsync_d1:password1 — соответственно, пользователь rsync_d1 с паролем password1.

В целях безопасности, устанавливаем доступ только для владельца:

chmod 600 /etc/rsyncd.scrt

Перезапускаем сервис одной из команд:

systemctl restart rsyncd

/etc/init.d/rsync restart

service rsyncd restart

Добавляем порты в брандмауэр.

Firewalld:

firewall-cmd —permanent —add-port=873/tcp

firewall-cmd —permanent —add-port=22/tcp

firewall-cmd —reload

Iptables:

iptables -I INPUT 1 -p tcp —dport 873 -j ACCEPT

iptables -I INPUT 1 -p tcp —dport 22 -j ACCEPT

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:

rsync -qaHAXS SOURCE_DIR DESTINATION_DIR

And their meaning is (from the manpage):

-H, --hard-links      preserve hard links
-A, --acls            preserve ACLs (implies -p)
-X, --xattrs          preserve extended attributes
-S, --sparse          handle sparse files efficiently

Additionally, use 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 ‘s recursive option:

diff -r SOURCE_DIR DESTINATION_DIR

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.

Добавить комментарий

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

Adblock
detector