Меню Рубрики

Time machine for linux

Time Machine: бекапим OS X Lion на Ubuntu 12.04 LTS сервер


Если кто не знает, Time Machine — это такой замечательный бэкап-сервис из коробки для Apple OS X, тут и тут можно почитать поподробнее. Если у вас есть мак, и вы не пользуетесь «машиной времени», то это совершенно напрасно. Time Machine делает постоянные дифференциальные бэкапы, поэтому она удобна даже в случае прекрасной жизни ваших HDD / SSD. Можно в любой момент открутить назад историю и восстановить случайно удаленный файл, или, что еще важнее, предыдущую версию измененного файла.

Предполагается, что пользователи будут использовать либо обычный жесткий диск, либо специальный сетевой девайс Time Capsule. Традиционный внешний жесткий диск — решение для очень организованных людей, которые регулярно (хотя бы ежедневно) будут его подключать для автоматического бэкапа, иначе польза от тайм машины будет весьма ограничена (хотя прошлогодний бэкап все же лучше, чем совсем ничего). С тайм-капсулой будет гораздо удобнее и надежнее. Кроме функции бэкапа, она может выполнять еще и функцию сетевой шары, раздачи Wi-Fi (фактически Time Capsule — это Wi-Fi роутер с HDD). Но устройство стоит денег, и оно не такое универсальное. Мне захотелось прикрутить на свой сервер работающий на Ubuntu возможность делать бэкапы тайм-машиной. И это не так сложно, о чем и будет эта заметка.

Итак у нас Ubuntu 12.04 LTS. Необходимая нам функциональность находится в пакете netatalk, это опенсорсная реализация протокола AppleTalk, также нам понадобится поставить пакет avahi-daemon для реализации zeroconf инфраструктуры в нашей сети, в данном случае это имитация любимого яблочной техникой Bonjour.

avahi-daemon можно поставить сразу:

C netatalk чуть сложнее, на момент написания заметки уже вышла релизная версия 2.2.2 с кучей новых фиксов (см. http://netatalk.sourceforge.net), а в репах убунты все еще была версия полугодовалой давности 2.2.1. Я захотел поставить версию новее. Это можно сделать сборкой из исходников, но в тот момент можно было сделать и по-другому. На launchpad уже появился готовенький пакет 2.2.2, так что качаем его и ставим.

Далее необходимо сконфигурировать сервисы.

Создаем файл afpd.service, который описывает конкретные сервисы раздаваемые по AppleTalk Filing Protocol демоном afpd:

со следующим содержимым:

Здесь можно изменить имя сервиса и иконку удаленного компьютера, которые отображаются в Finder на маке, за них отвечают строки

, где %h — имя компьютера (host);
, где вместо Xserve можно поставить: Macmini, iMac, MacPro, Xserve, MacBook, MacBookPro, MacBookAir.

Далее конфигурируем netatalk. Конфиг в /etc/default/netatalk можно не менять, все должно работать и так. А вот /etc/netatalk/AppleVolumes.default нужно изменить.

Переходим в конец файла (Ctrl + V бегать по страницам быстрее).

, где /data/backups/TimeMachine — путь к каталогу, в котором будут храниться бекапы;
«TimeMachine» — имя расшаренного ресурса.
В options должно быть tm — ресурс для тайм-машины.
allow:alex — пользователь, имеющий доступ к каталогу. Он (в данном случае alex) должен быть на вашем сервере (я еще для удобства сделал так, чтобы пользователь на убунте и на маке имел одно имя), создать пользователя можно с помощью команды useradd.

Можно добавить еще разделяемую шару, например:

Тут в опциях уже не надо указывать tm.
Здесь dperm:0777 fperm:0666 — права на создаваемые каталоги и файлы,
allow:@shares — доступ только пользователям входящим в группу shares (создать группу можно с помощью groupadd, а добавить пользователя в существующую группу usermod -a -G groupname username)

Права и группа — для того, чтобы данной шарой можно было удобно пользоваться несколькими людьми. Для этого людям создаются учетки, и им добавляется группа shares. К сожалению, я не нашел возможности сделать как в самбе, чтобы новые файлы создавались от имени группы, поэтому пришлось дать полные права для others, иначе файлы, созданные одним человеком не могли бы редактироваться другими.

PS
Хотя нет, без напильника не обошлось. Т.е. сразу нифига не заработало, симптом такой: в файндере пробуем подключиться к шаре, а он говорит, что там ничего и нет, куда подключаться? Оказалось, что afpd не стартанул толком.

Источник

Time machine for linux

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Linux Time Machine

Install | Uninstall | TL;DR | Features | How does it work | Restore | Retention | Usage | FAQ | Disclaimer | License

timemachine is a tiny and stable KISS driven and POSIX compliant script that mimics the behavior of OSX’s timemachine. It uses rsync to incrementally back up your data to a different directory, hard disk or remote server via SSH. All operations are incremental, atomic and automatically resumable.

By default it uses the rsync options: —recursive , —perms , —owner , —group , —times and —links . In case your target filesystem does not support any of those options or you cannot use them due to missing permission, you can explicitly disable them via —no-perms , —no-owner , —no-group , —no-times , and —copy-links . See FAQ for examples.

Motivation

The goal of this project is to have a cross-operating system and minimal as possible backup script that can be easily reviewed by anyone without great effort. Additionally it should provide one task only and do it well without the need of external requirements and only rely on default installed tools.

Using POSIX.1-2008 argument syntax:

Feature Description
SSH or local Local backups as well as backups via SSH are supported.
Incremental Backups are always done incrementally using rsync’s ability to hardlink to previous backup directories. You can nevertheless always see the full backup on the file system of any incrementally made backup without having to generate it. This will also be true when deleting any of the previously created backup directories. See the Backups section for how this is achieved via rsync.

Incremental Backups also mean that only the changes on your source, compared to what is already on the target, have to be backed up. This will save you time as well as disk space on the target disk. Partial When backing up, files are transmitted partially, so in case a 2GB movie file backup is interrupted the next run will pick up exactly where it left off at that file and will not start to copy it from scratch. Resumable Not only is this script keeping partial files, but also the whole backup run is also resumable. Whenever there is an unfinished backup and you start timemachine again, it will automatically resume it. It will resume any previously failed backup as long as it finally succeeds. Atomic [1] The whole backup procedure is atomic. Only if and when the backup procedure succeeds, it is then properly named and symlinked. Any non-successful backup directory is either waiting to be resumed or to be deleted.

  • [1] The backup process is atomic, but not the backup itself. rsync copies files as it finds them and in the meantime there could already be changes on the source. To achieve an atomic backup, either back up from a read-only volume or from a snapshot.

ℹ️ How does it work?

The following directory structure will be created:

current will always link to the latest created backup. All backups are incremental except the first created one. You can nevertheless safely remove all previous folders and the remaining folders will still have all of their content.

Except for the first one, backups are always and automatically done incrementally, so the least amount of space is consumed. Due to rsync ‘s ability, every directory will still contain all files, even though they are just incremental backups. This is archived via hardlinks.

You can also safely delete the initial full backup directory without having to worry about losing any of your full backup data:

rsync and hardlinks are magic 🙂

Failure handling and resume

In case the timemachine script aborts (self-triggered, disk unavailable or for any other reason) you can simply run it again to automatically resume the last failed run.

This is due to the fact that the backup process is atomic. During a non-complete run, all data will be stored in a directory named .inprogress/ . This will hold all already transferred data and will be picked up during the next run. Once the backup is complete, it will be renamed and symlinked to current .

No special software is required to restore your data. Backed up files can be easily browsed and thus copied back to where you need them. Recall the backup directory structure:

Chose a backup directory and simply copy them to where you need it:

As decribed above this project is KISS driven and only tries to do one job: back up your data.

Retention is a delicate topic as you want to be sure that data is removed as intended. For this there are already well-established tools that do an excellent job and have proven themselves over time: tmpreaper and tmpwatch.

The script is written and maintained with maximum care. In order to retain a reliable and stable backup solution, a lot of effort goes into a vast amount of integration and regression tests. These tests not only give you measurable confidence, but also help new contributors to not accidentally introduce new or old bugs.

The following can be used as an example crontab entry. It assumes you have an external disk (NFS, USB, etc..) that mounts at /backup . Before adding the crontab entry, ensure the filesystem in /backup is mounted and use:

This guards against accidentally backing up to an unmounted directory

Next, add the following to crontab using crontab -e as whichever user you intend to run the backup script as. You may need to place this in the root crontab if you are backing up sensitive files that only root can read

This will cause timemachine to run at 2AM once per day. Since timemachine keeps track of backups with granularity up to the hour, minute and second, you could have it run more than once per day if you want backups to run more often.

Should I add trailing directory slashes ( / )?

Trailing directory slashes only matter for the source directory and will not make a difference if added to the destination directory.

How to dry-run the backup?

How to use a non-standard SSH port?

How to use SSH aliases from

How to speed up remote backups?

How to preserve ACLs?

How to preserve extended attributes?

How to disable preserving file and directory permissions?

How to disable preserving modification time?

How to copy the content instead of a symlink?

How to ensure all files in the back up have the ownership of current user?

Backups are one of the most important things. We all care about our data and want it to be safe, so do not blindly trust scripts when it comes to backups! Do review the code, it is not too complex and kept as short as possible. Have a look at how much effort goes into the integration tests to provide measurable stability.

Learn about rsync it is a very powerful tool and you might even be able to just use this for backups.

There are many other backup solutions out there that might be a better fit for your needs. Do your own research, look at GitHub issues, source code, integration tests and try them out as well.

Contributing

See Contributing guidelines to help to improve this project.

Copyright (c) 2017 cytopia

Источник

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

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

  • Программа для заполнения 3 ндфл для mac os
  • Программа для записи образа на флешку для mac os
  • Программа для записи образа на диск для mac os
  • Программа для записи дисков для mac os
  • Программа для записи видео со звуком с экрана mac os