Skip to content

Instantly share code, notes, and snippets.

@geek-at
Last active January 1, 2022 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geek-at/f4534066bebff3fd67022d8295e5f3e0 to your computer and use it in GitHub Desktop.
Save geek-at/f4534066bebff3fd67022d8295e5f3e0 to your computer and use it in GitHub Desktop.
PHP script to receive all zfs snapshot of dataset from remote machine to local
<?php
$remoteIP = $argv[1];
$remoteDataset = $argv[2];
$localDataset = $argv[3];
if($argc!=4) exit('usage: php sync.php <remote ip> <remote dataset> <local dataset>'.PHP_EOL);
$cmd_zfs = "zfs list -t snapshot $remoteDataset | cut -d ' ' -f 1 | cut -d '@' -f 2 | tail -n +2";
$cmd_zfs_local = "zfs list -t snapshot $localDataset | cut -d ' ' -f 1 | cut -d '@' -f 2 | tail -n +2";
$cmd_ssh = "ssh $remoteIP $cmd_zfs";
$remotesnapshots = [];
exec($cmd_ssh,$remotesnapshots);
$localsnapshots = [];
exec($cmd_zfs_local,$localsnapshots);
$tosync = array_diff($remotesnapshots,$localsnapshots);
if(count($tosync)<1) exit("[i] Nothing to sync. Exiting\n");
$snapshot = end($tosync);
$lastincommon = getLastInCommon($remotesnapshots,$localsnapshots,$snapshot);
if(!$lastincommon)
{
echo "[i] Don't have any snapshots of that dataset yet. I'll sync initial\n";
$firstsnap = $remotesnapshots[0];
$synccmd = "ssh $remoteIP zfs send -w $remoteDataset@$firstsnap | zfs receive -F $localDataset";
echo "$synccmd\n";
system($synccmd);
exit();
}
echo "[i] Syncing from $lastincommon to $snapshot\n";
$synccmd = "ssh $remoteIP zfs send -w -I $remoteDataset@$lastincommon $remoteDataset@$snapshot | zfs receive -F $localDataset";
echo "$synccmd\n";
system($synccmd);
function getLastInCommon($remote,$local,$target)
{
$incommon = [];
foreach($remote as $key=>$rsnap)
{
foreach($local as $lkey=>$lsnap)
{
if($rsnap == $lsnap)
$incommon[] = $rsnap;
if($lsnap==$target) break;
}
}
return end($incommon);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment