1
0
forked from extern/zsync

first commit

This commit is contained in:
thorsten.spille 2024-02-08 00:40:42 +01:00
parent dbdc41a358
commit 5983d77cd4
7 changed files with 553 additions and 80 deletions

72
DOCUMENTATION_DE.md Normal file
View File

@ -0,0 +1,72 @@
# Konfiguration auf dem Zielserver
1. Öffnen Sie eine SSH-Verbindung zum Zielserver, entweder über die Befehlszeile oder ein SSH-Tool wie PuTTY.
2. Stellen Sie sicher, dass der Zielserver die erforderlichen Voraussetzungen erfüllt. Dazu gehören das Vorhandensein der benötigten Befehle (`zfs`, `ssh`, `grep`) und die korrekte Konfiguration der Pfade (`PATH`-Variable im Script).
3. Erstellen Sie eine Konfigurationsdatei für das Script. Standardmäßig wird die Datei `/etc/bashclub/zsync.conf` verwendet. Sie können jedoch einen anderen Pfad angeben, indem Sie den Parameter `-c` beim Aufruf des Scripts verwenden. Zusätzlich können Sie weitere Konfigurationsdateien erstellen, um unterschiedliche Replikationen einzurichten. Zum Beispiel: `/usr/bin/bashclub-zsync -c /pfad/zur/konfiguration1.conf`, `/usr/bin/bashclub-zsync -c /pfad/zur/konfiguration2.conf`
4. Öffnen Sie die Konfigurationsdatei mit einem Texteditor und passen Sie die folgenden Einstellungen an:
- `source`: Geben Sie den SSH-Adresse des Quellservers an, von dem die Daten repliziert werden sollen. Beispiel: `source=user@host`
- `target`: Geben Sie die Pfad des Ziel-ZFS-Dateisystems auf dem Zielserver an, zu dem die Daten repliziert werden sollen. Beispiel: `target=pool/dataset`
- `sshport`: Geben Sie den SSH-Port des Quellservers an. Standardmäßig ist dies `22`, aber Sie können ihn entsprechend anpassen.
- `tag`: Geben Sie den ZFS-Tag an, der verwendet werden soll, um die zu replizierenden Dateisysteme oder Volumes zu identifizieren. Beispiel: `tag=bashclub:zsync`
- `snapshot_filter`: Geben Sie eine Pipe-separierte Liste von Snapshot-Namenfiltern an, die bestimmen, welche Snapshots repliziert werden sollen. Beispiel: `snapshot_filter="hourly|daily|weekly|monthly"`
- `min_keep`: Geben Sie die Mindestanzahl von Snapshots pro Filter an, die beibehalten werden sollen. Beispiel: `min_keep=3`
- `zfs_auto_snapshot_keep`: Aktiviert das erzeugen eines Snapshots auf der Quelle vor der Replikation, gibt die Anzahl der Snapshots an, die behalten werden sollen. Beispiel: `zfs_auto_snapshot_keep=0` => Deaktiviert die Funktion, `zfs_auto_snapshot_keep=7` behält 7 Snapshots.
- `zfs_auto_snapshot_label`: Definniert das Label des Snapshots, Default-Wert ist `backup` (ergibt: zfs-auto-snap_backup-YYYY-MM-dd-hhmm). Beispiel: `zfs_auto_snapshot_label=backup`
Wiederholen Sie diese Schritte für jede zusätzliche Konfigurationsdatei, um unterschiedliche Replikationen einzurichten.
5. Speichern Sie die Konfigurationsdateien.
6. Überprüfen Sie, ob der Zielserver die erforderlichen ZFS-Datasets oder Volumes enthält, auf die die Daten repliziert werden sollen. Stellen Sie sicher, dass die Namen der Datasets/Volumes dem ZFS-Tag entsprechen, den Sie in den Konfigurationsdateien festgelegt haben.
7. Um das Script automatisch auszuführen, erstellen Sie eine Cronjob-Konfigurationsdatei im Verzeichnis `/etc/cron.d/`. Öffnen Sie eine neue Datei mit einem Texteditor und geben Sie die gewünschte Ausführungszeit und den Befehl ein. Beispiel:
a) Erstellen Sie das Verzeichnis `/var/log/bashclub-zsync`, falls es noch nicht existiert. Verwenden Sie den Befehl:
```plaintext
sudo mkdir -p /var/log/bashclub-zsync
```
b) Öffnen Sie die Cronjob-Konfigurationsdatei mit dem Befehl:
```plaintext
sudo nano /etc/cron.d/bashclub-zsync-cronjob
```
c) Fügen Sie den folgenden Inhalt in die Datei ein:
```plaintext
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
0 * * * * root /usr/bin/bashclub-zsync -c /etc/bashclub/zsync.conf >> /var/log/bashclub-zsync/zsync.log 2>&1
```
In diesem Beispiel wird das Script einmal pro Stunde ausgeführt. Der Befehl `/usr/bin/bashclub-zsync -c /etc/bashclub/zsync.conf` wird als root-Benutzer ausgeführt, und die Ausgabe wird in die Datei `/var/log/bashclub-zsync/zsync.log` umgeleitet.
d) Speichern Sie die Datei und schließen Sie den Texteditor.
Das Script wird nun automatisch gemäß dem angegebenen Intervall ausgeführt, und die Ausgabe wird im angegebenen Logfile gespeichert. Stellen Sie sicher, dass die Dateiberechtigungen für die Cronjob-Konfigurationsdatei korrekt sind, damit sie von Cron erkannt wird.
# Konfiguration auf dem Quellserver
Um ZFS-Dateisysteme und Volumes für die Replikation mit dem bashclub-zsync-Script zu markieren, verwenden Sie das ZFS-Attribut "bashclub:zsync" auf dem Quellserver. Dieses Attribut kann mit dem Parameter "value" konfiguriert werden, der die Werte "subvols", "all" oder "exclude" haben kann.
Hier ist eine Anleitung zur Konfiguration auf dem Quellserver:
1. Identifizieren Sie das ZFS-Dateisystem oder Volume, das Sie für die Replikation markieren möchten.
2. Setzen Sie das ZFS-Attribut "bashclub:zsync" mit dem gewünschten Value-Parameter-Wert. Verwenden Sie den Befehl:
```plaintext
zfs set bashclub:zsync=<value> <datensatz>
```
Ersetzen Sie `<value>` durch einen der folgenden Werte: "subvols", "all" oder "exclude". Ersetzen Sie `<datensatz>` durch den Namen des ZFS-Datensatzes.
- "subvols": Markiert nur Volumes und Dateisysteme in der Hierarchie unterhalb des Datensatzes, für den das Attribut gesetzt ist (schließt den Wurzel-Datensatz aus).
- "all": Markiert alle Volumes und Dateisysteme im ZFS-Datensatz einschließlich des Wurzel-Datensatzes.
- "exclude": Schließt Volumes und Dateisysteme im ZFS-Datensatz aus, für den das Attribut gesetzt ist.
Durch die Markierung mit dem Attribut "bashclub:zsync" wird das betreffende ZFS-Dateisystem oder -Volume für die Replikation mit dem bashclub-zsync-Script berücksichtigt.
Bitte beachten Sie, dass die genaue Syntax und Verwendung des Befehls je nach dem von Ihnen verwendeten Betriebssystem oder der ZFS-Version variieren kann. Stellen Sie sicher, dass Sie über ausreichende Berechtigungen verfügen, um die Konfiguration auf dem Quellserver vorzunehmen.
Um mehrere Replikationen zu unterschiedlichen Hosts mit dem bashclub-zsync-Script auf dem Zielserver zu ermöglichen, können Sie den Namen des ZFS-Attributs "bashclub:zsync" in der Scriptkonfiguration mit dem Parameter "tag" anpassen. Dadurch können Sie verschiedene Replikationen zu unterschiedlichen Hosts einrichten und steuern. Öffnen Sie das bashclub-zsync-Script auf dem Zielserver, suchen Sie nach dem "tag"-Parameter und ändern Sie den Wert in den gewünschten Namen für das ZFS-Attribut. Speichern Sie das Script nach der Änderung. Stellen Sie sicher, dass Sie über ausreichende Berechtigungen verfügen, um das Script zu bearbeiten und die Konfiguration auf dem Zielserver vorzunehmen.

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

138
README.md
View File

@ -1,93 +1,71 @@
---- THIS IS A CLONE OF THE ORIGINAL REPOSITORY ON git.bashclub.org ----
# zsync
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://gitlab.bashclub.org/bashclub/zsync.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://gitlab.bashclub.org/bashclub/zsync/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
ZFS replication script by Thorsten Spille <thorsten@spille-edv.de>
- replicates ZFS filesystems/volumes with user parameter bashclub:zsync (or custom name) configured
- creates optional snapshot before replication (required zfs-auto-znapshot)
- parameter setting uses zfs hierarchy on source
- mirrored replication with existing snapshots (filtered by snapshot_filter)
- pull/local replication only
- auto creates full path on target pool, enforce com.sun:auto-snapshot=false, inherits mountpoint and sets canmount=noauto
- raw replication
- tested on Proxmox VE 7.x/8.x
- ssh cipher auto selection
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
#### Download and make executable
~~~
wget -q --no-cache -O /usr/bin/bashclub-zsync https://git.bashclub.org/bashclub/zsync/raw/branch/dev/bashclub-zsync/usr/bin/bashclub-zsync
chmod +x /usr/bin/bashclub-zsync
bashclub-zsync
~~~
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Configuration
After first execution adjust the default config file `/etc/bashclub/zsync.conf`:
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
~~~
# target path on local machine
target=backup/px1
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
# source host
source=user@host
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
# source host ssh port
sshport=22
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
# tag to mark source filesystem
tag=bashclub:zsync
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
# snapshot name filter
snapshot_filter="hourly|daily|weekly|monthly"
## License
For open source projects, say how it is licensed.
# number of minimum snapshots to keep (per snapshot filter)
min_keep=3
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
# number of zfs snapshots to keep on source (0 = snapshot function disabled)
zfs_auto_snapshot_keep=0
# make snapshot via zfs-auto-snapshot before replication
zfs_auto_snapshot_label="backup"
~~~
### Define a cronjob
#### cron.d example
File: /etc/cron.d/bashclub-zsync
~~~
00 23 * * * root /usr/bin/bashclub-zsync -c /etc/bashclub/zsync.conf > /var/log/bashclub-zsync/zsync.log
~~~
#### cron.{hourly|daily|weekly|monthly}
File: /etc/cron.hourly/bashclub-zsync
~~~
/usr/bin/bashclub-zsync -c /etc/bashclub/zsync.conf > /var/log/bashclub-zsync/zsync.log
~~~
# Author
### Thorsten Spille
[<img src="https://storage.ko-fi.com/cdn/brandasset/kofi_s_tag_dark.png" rel="Support me on Ko-Fi">](https://ko-fi.com/thorakel)

View File

@ -0,0 +1,9 @@
/var/log/bashclub-zsync/*.log {
weekly
rotate 12
compress
delaycompress
missingok
notifempty
create 644 root root
}

View File

@ -0,0 +1,295 @@
#!/bin/bash
#
# bashclub zfs replication script
# Author: (C) 2023 Thorsten Spille <thorsten@spille-edv.de>
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
prog="$(basename $0)"
zfs=$(which zfs)
ssh=$(which ssh)
grep=$(which grep)
uniq=$(which uniq)
cut=$(which cut)
tail=$(which tail)
wc=$(which wc)
tr=$(which tr)
sed=$(which sed)
zfs_auto_snapshot=$(which zfs-auto-snapshot)
rc=0
debug=
#### default config file, can be changed with parameter -c
conf=/etc/bashclub/zsync.conf
#### default values in config file
# replication target on local machine
target=pool/dataset
# ssh address of remote machine
source=user@host
# ssh port of remote machine
sshport=22
# zfs user parameter to identify filesystems/volumes to replicate
tag=bashclub:zsync
# pipe separated list of snapshot name filters
snapshot_filter="hourly|daily|weekly|monthly"
# minimum count of snapshots per filter to keep
min_keep=3
# number of zfs snapshots to keep on source (0 or 1 = snapshot function disabled)
zfs_auto_snapshot_keep=0
# make snapshot via zfs-auto-snapshot before replication
zfs_auto_snapshot_label="backup"
# disable checkzfs with value > 0
checkzfs_disabled=0
# set checkzfs parameter "--prefix"
checkzfs_prefix=zsync
# set checkzfs maximum age of last snapshot in minutes (comma separated => warn,crit)
checkzfs_max_age=1500,6000
# set checkzfs maximum count of snapshots per dataset (comma separated => warn,crit)
checkzfs_max_snapshot_count=150,165
usage() {
cat >&2 <<-EOF
usage: $prog [-h] [-d] [-c CONFIG]
creates a mirrored replication of configured zfs filesystems / volumes
-c CONFIG Configuration file for this script
-d Debug mode
---------------------------------------------------------------------------
(C) 2023 by Spille IT Solutions for bashclub (github.com/bashclub)
Author: Thorsten Spille <thorsten@spille-edv.de>
---------------------------------------------------------------------------
EOF
exit $1
}
while getopts "hdc:" opt; do
case $opt in
h) usage 0 ;;
c) conf=$OPTARG ;;
d) debug=-v ;;
*) usage 1 ;;
esac
done
shift $((OPTIND-1))
function log() {
echo -e "$(date +'%b %d %T') $1"
}
if which checkzfs; then
if [ checkzfs_disabled -eq 0 ]; then
checkzfs=$(which checkzfs)
log "[INFO] installed checkzfs found: $checkzfs"
else
log "[INFO] checkzfs is disabled by configuration."
fi
else
checkzfs_disabled=1
log "[WARN] checkzfs is disabled. for monitoring please install:\n\thttps://github.com/bashclub/check-zfs-replication\n"
fi
# load config file
if [ -f $conf ]; then
log "[INFO] Reading configuration $conf"
source $conf
else
mkdir -p $(dirname $conf)
cat << EOF > $conf
target=$target
source=$source
sshport=$sshport
tag=$tag
snapshot_filter="$snapshot_filter"
min_keep=$min_keep
zfs_auto_snapshot_keep=$zfs_auto_snapshot_keep
zfs_auto_snapshot_label=$zfs_auto_snapshot_label
checkzfs_disabled=$checkzfs_disabled
checkzfs_prefix=$checkzfs_prefix
checkzfs_max_age=$checkzfs_max_age
checkzfs_max_snapshot_count=$checkzfs_max_snapshot_count
EOF
log "[INFO] Initial config file created. Please adjust and restart script. Exiting..."
usage 0
fi
if [[ $source == "" ]]; then
log "[INFO] source is empty, switching to local mode."
ssh=
sshport=
log "[INFO] Configuration:\n\ttarget=$target\n\ttag=$tag\n\tsnapshot_filter=$snapshot_filter\n\tmin_keep=$min_keep\n\ŧzfs_auto_snapshot_keep=$zfs_auto_snapshot_keep\n\tzfs_auto_snapshot_label=$zfs_auto_snapshot_label\n\tcheckzfs_disabled=$checkzfs_disabled\n\tcheckzfs_prefix=$checkzfs_prefix\n\tcheckzfs_max_age=$checkzfs_max_age\n\tcheckzfs_max_snapshot_count=$checkzfs_max_snapshot_count\n"
else
sshport=-p$sshport
log "[INFO] Configuration:\n\ttarget=$target\n\tsource=$source\n\tsshport=$sshport\n\ttag=$tag\n\tsnapshot_filter=$snapshot_filter\n\tmin_keep=$min_keep\n\tzfs_auto_snapshot_keep=$zfs_auto_snapshot_keep\n\tzfs_auto_snapshot_label=$zfs_auto_snapshot_label\n\tcheckzfs_disabled=$checkzfs_disabled\n\tcheckzfs_prefix=$checkzfs_prefix\n\tcheckzfs_max_age=$checkzfs_max_age\n\tcheckzfs_max_snapshot_count=$checkzfs_max_snapshot_count\n"
fi
local_os_id=$($grep -E "^ID=" /etc/os-release | $cut -d'=' -f2)
remote_os_id=$($ssh $source $sshport "grep -E \"^ID=\" /etc/os-release | cut -d'=' -f2")
if [[ $local_os_id == "freebsd" ]]; then
local_aes=$($grep -o AES /var/run/dmesg.boot | $uniq)
else
local_aes=$($grep -m1 -o aes /proc/cpuinfo | $uniq)
fi
if [[ $remote_os_id == "freebsd" ]]; then
remote_aes=$($ssh $source $sshport "grep -o AES /var/run/dmesg.boot | uniq")
else
remote_aes=$($ssh $source $sshport "grep -m1 -o aes /proc/cpuinfo | uniq")
fi
if [[ $local_aes == "aes" ]] && [[ $remote_aes == "aes" ]]; then
if [[ $debug == "-v" ]]; then log "[DEBUG] Switching to cipher aes256-gcm@openssh.com"; fi
sshcipher=-caes256-gcm@openssh.com
else
if [[ $debug == "-v" ]]; then log "[DEBUG] Using default cipher chacha20-poly1305@openssh.com"; fi
sshcipher=-cchacha20-poly1305@openssh.com
fi
include_list="[INFO] Included datasets:\n"
exclude_list="[INFO] Excluded datasets:\n"
checkzfs_headline="[INFO] checkzfs filter:\n"
checkzfs_filter=
IFS=$'\n'
for zvol in $($ssh $sshcipher $sshport $source "zfs get -H -o name,value,source -t filesystem,volume $tag"); do
name=$(echo $zvol | $cut -f1)
if [[ "$(echo $zvol | $cut -f2)" == "subvols" ]]; then
if [[ $(echo $zvol | $grep -vE "local|received") ]]; then
include_list="${include_list}\t${name}\n"
syncvols=("${syncvols[@]}" "$name")
elif [[ $(echo $zvol | $grep "local") ]]; then
checkzfs_filter="#$name/|$checkzfs_filter"
fi
elif [[ "$(echo $zvol | $cut -f2)" == "all" ]]; then
if [[ $(echo $zvol | $grep -v received) ]]; then
include_list="${include_list}\t${name}\n"
syncvols=("${syncvols[@]}" "$name")
fi
if [[ $(echo $zvol | $grep "local") ]]; then
checkzfs_filter="#$name|$checkzfs_filter"
fi
else
exclude_list="${exclude_list}\t${name}\n"
fi
done
log "$include_list"
log "$exclude_list"
log "$checkzfs_headline\ncheckzfs_filter="$checkzfs_filter"
if ! $zfs list $target > /dev/null 2>&1 ; then
log "[DEBUG] $target does not exist. Creating..."
$zfs create -o canmount=noauto -o com.sun:auto-snapshot=false $target
else
log "[DEBUG] $target exists, check auto-snapshot..."
if [[ $($zfs get -H -o value,source com.sun:auto-snapshot $target) != "false local" ]]; then
$zfs set com.sun:auto-snapshot=false $target
fi
fi
if [ $zfs_auto_snapshot_keep -gt 1 ]; then
log "[DEBUG] Running zfs-auto-snapshot"
$ssh $sshcipher $sshport $source "which zfs-auto-snapshot > /dev/null || exit 0 ; zfs-auto-snapshot --quiet --syslog --label=$zfs_auto_snapshot_label --keep=$zfs_auto_snapshot_keep //"
if [[ $snapshot_filter == "" ]]; then
snapshot_filter="$zfs_auto_snapshot_label"
else
snapshot_filter="$snapshot_filter|$zfs_auto_snapshot_label"
fi
fi
for name in "${syncvols[@]}"; do
log "[INFO] Replicate $name"
fstype=$($ssh $sshcipher $sshport $source zfs get -H -o value type $name)
if [[ $fstype == "filesystem" ]]; then
mp=-xmountpoint
cm=-ocanmount=noauto
else
mp=
cm=
fi
if [[ $($ssh $sshcipher $sshport $source "zfs list -H -t snapshot -o name -S creation $name 2>/dev/null | grep -E \"@.*($snapshot_filter)\" | wc -l | tr -d ' '") -gt 0 ]]; then
IFS=$' '
if ! $zfs list -H $target/$name > /dev/null 2>&1 ; then
if [[ $debug == "-v" ]]; then log "[DEBUG] $target/$name does not exist"; fi
prefix=""
for part in $(echo $target/$(echo $name | $cut -d'/' -f1) | $sed "s/\// /g"); do
if [ $($zfs list $prefix$part > /dev/null 2>&1 ; echo $?) -gt 0 ]; then
if [[ $debug == "-v" ]]; then log "[DEBUG] $prefix$part does not exist"; fi
log "[INFO] Creating $prefix$part"
$zfs create -o canmount=noauto $autosnap -p $prefix$part
fi
prefix="$prefix$part/"
done
if [[ $debug == "-v" ]]; then log "[DEBUG] $name - Start initial replication"; fi
IFS=$'\n'
for snap in $($ssh $sshcipher $sshport $source "zfs list -H -t snapshot -o name -S creation $name | grep -E \"@.*($snapshot_filter)\" | tail -1"); do
log "[INFO] Start initial replication: $snap => $target/$(echo $name | $cut -d'/' -f1)"
$ssh $sshcipher $sshport $source "zfs send -w -p $debug $snap" | $zfs receive $mp $cm -x $tag -x com.sun:auto-snapshot $debug -dF $target/$(echo $name | $cut -d'/' -f1)
if [ $? -gt $rc ]; then rc=1; log "[ERROR] initial replication to $target/$name failed."; fi
done
fi
if [[ $debug == "-v" ]]; then log "[DEBUG] $name - Start incremental replication"; fi
guid=$($zfs list -H -o guid -s creation -t snapshot $target/$name | $tail -1)
if [[ $guid != "" ]]; then
last=$($ssh $sshcipher $sshport $source "zfs list -H -o name,guid -t snapshot $name | grep $guid | tail -1 | cut -f1")
if [[ $last != "" ]]; then
IFS=$'\n'
if [[ $fstype == "filesystem" ]] && [[ $($zfs get -H -o value canmount $target/$name) != "noauto" ]]; then
$zfs set canmount=noauto $target/$name
fi
for snap in $($ssh $sshcipher $sshport $source "zfs list -H -o name,guid -s creation -t snapshot $name | grep -E \"@.*($snapshot_filter)\" | grep --after-context=200 $guid | grep -v $guid | cut -f1"); do
log "[INFO] Replicating delta of $last => $snap to $target/$name"
$ssh $sshcipher $sshport $source "zfs send -w $debug -i $last $snap" | zfs receive -x $tag -x com.sun:auto-snapshot -F $debug $target/$name
if [ $? -gt $rc ]; then rc=1; log "[ERROR] incremental replication to $target/$name failed."; fi
last=$snap
done
else
log "[ERROR] No matching snapshot (guid: $guid) found on source filesystem. This can be outdated snapshots on target or a previously deleted and new created dataset $name on the source filesystem."
if [ $rc -eq 0 ]; then rc=1; fi
fi
else
log "[ERROR] No snapshot found on $target/$name to add incremental snapshots to. The target dataset (with all children) needs to be deleted and recreated via replication."
if [ $rc -eq 0 ]; then rc=1; fi
fi
if [[ $debug == "-v" ]]; then log "[DEBUG] $name - Start deletion of old snapshots"; fi
filter=$(echo -e $snapshot_filter | sed "s/|/\n/g")
IFS=$'\n'
for interval in $filter ; do
if [[ $debug == "-v" ]]; then log "[DEBUG] $name - Checking interval $interval"; fi
guid=$($ssh $sshcipher $sshport $source "zfs list -H -o guid,name -S creation -t snapshot $name | grep -E \"@.*$interval\" | cut -f1 | tail -1")
if [[ "$(echo -e "$guid" | sed 's/\n//g')" != "" ]]; then
snaps_to_delete=$($zfs list -H -o name,guid -S creation -t snapshot $target/$name | $grep -E "@.*$interval" | $grep --after-context=200 $guid | $grep -v $guid | $cut -f1)
snap_count=$($zfs list -H -o name,guid -S creation -t snapshot $target/$name | $grep -E "@.*$interval" | $wc -l | $tr -d ' ')
for snap in $snaps_to_delete; do
if [[ $snap_count -gt $min_keep ]]; then
log "[INFO] Deleting $snap"
if [[ $debug == "-v" ]]; then log "[DEBUG] $name - snap_count=$snap_count, min_keep=$min_keep"; fi
$zfs destroy $debug $snap
snap_count=$(expr $snap_count - 1)
else
if [[ $debug == "-v" ]]; then log "[DEBUG] $name - Skipping deletion of $snap. snap_count=$snap_count, min_keep=$min_keep"; fi
fi
done
fi
done
else
if [[ $debug == "-v" ]]; then log "[DEBUG] $name - No snapshots found with filter $snapshot_filter"; fi
fi
done
exit $rc

View File

@ -0,0 +1,107 @@
#!/bin/bash
#
# bashclub zfs replication script config tool
# Author: (C) 2023 Thorsten Spille <thorsten@spille-edv.de>
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
prog="$(basename $0)"
#### default config file, can be changed with parameter -c
action=list
conf=/etc/bashclub/zsync.conf
recursive=0
key=
path=
value=
usage() {
cat >&2 <<-EOF
usage: $prog [-h] [-a ACTION] [-c CONFIG] [-p PATH] [-s KEY[=VALUE]] [-r]
manages the zfs-auto-snapshot and bashclub-zsync config on source
-a ACTION The action, this script shall execute
-c CONFIG Path to the bashclub-zsync config file
-p PATH Path of the zfs dataset on source
-s KEY=VALUE Set value for specified dataset
-r Recursive listing (in combination with -l and -p)
-h Show this help text
---------------------------------------------------------------------------
Details of Parameters:
ACTION: Script actions are 'list' (default), 'set', 'inherit'
CONFIG: Default is $conf
KEY: Following keys can be configured:
zsync => alias for bashclub:zsync
or user defined in bashclub-zsync config
zas => alias for com.sun:auto-snapshot
zasf => alias for com.sun:auto-snapshot:frequent
zash => alias for com.sun:auto-snapshot:hourly
zasd => alias for com.sun:auto-snapshot:daily
zasw => alias for com.sun:auto-snapshot:weekly
zasm => alias for com.sun:auto-snapshot:monthly
zasz => alias for com.sun:auto-snapshot:label
user defined auto-snapshot label in bashclub-zsync config
VALUE: Value can be 'all','subvols','exclude', 'true', 'false'
---------------------------------------------------------------------------
(C) 2023 by Spille IT Solutions for bashclub (github.com/bashclub)
Author: Thorsten Spille <thorsten@spille-edv.de>
---------------------------------------------------------------------------
EOF
exit $1
}
while getopts "hra:c:p:s:" opt; do
case $opt in
h) usage 0 ;;
a) action=$OPTARG ;;
c) conf=$OPTARG ;;
p) path=$OPTARG ;;
s) key=$(echo $OPTARG | cut -d'=' -f 1) value=$(echo $OPTARG | cut -d'=' -f 1) ;;
r) recursive=1 ;;
*) usage 1 ;;
esac
done
shift $((OPTIND-1))
source $conf
if [[ $source == "" ]]; then
ssh=
sshport=
else
sshport=-p$sshport
fi
local_os_id=$($grep -E "^ID=" /etc/os-release | $cut -d'=' -f2)
remote_os_id=$($ssh $source $sshport "grep -E \"^ID=\" /etc/os-release | cut -d'=' -f2")
if [[ $local_os_id == "freebsd" ]]; then
local_aes=$($grep -o AES /var/run/dmesg.boot | $uniq)
else
local_aes=$($grep -m1 -o aes /proc/cpuinfo | $uniq)
fi
if [[ $remote_os_id == "freebsd" ]]; then
remote_aes=$($ssh $source $sshport "grep -o AES /var/run/dmesg.boot | uniq")
else
remote_aes=$($ssh $source $sshport "grep -m1 -o aes /proc/cpuinfo | uniq")
fi
if [[ $local_aes == "aes" ]] && [[ $remote_aes == "aes" ]]; then
sshcipher=-caes256-gcm@openssh.com
else
sshcipher=-cchacha20-poly1305@openssh.com
fi
list (){
if [ $path != *"/"* ]; then
p=$path
if [ $recursive -gt0 ]; then
rec=-r
fi
fi
list=$($ssh $sshcipher $sshport $source "zfs get -H -t filesystem,volume $tag,com.sun:auto-snapshot,com.sun:auto-snapshot:frequent,com.sun:auto-snapshot:hourly,com.sun:auto-snapshot:daily,com.sun:auto-snapshot:weekly,com.sun:auto-snapshot:monthly,com.sun:auto-snapshot:$zfs_auto_snapshot_label $rec $p")
for line in $list; do
done
}

3
zfs_allow Normal file
View File

@ -0,0 +1,3 @@
target: replica create,destroy,receive,userprop,canmount,mountpoint
source: send,snapshot