Added new script to help clear ZFS labels from a disk
[zfs-ubuntu/.git] / zfs-replicate
1 #!/bin/bash
2
3 # Author: Carl Baldwin & Alan Pippin
4 # Description: This script replicates a remote zfs filesystem to a local zfs pool.
5 #              This script will keep all snapshots in sync, removing the ones
6 #              that have been deleted since the last replicate was performed.
7 #              This script will only send the new, or missing, snapshots since
8 #              the last replicate was performed.
9 # Usage: replicate <hostname> <zfs filesystem>
10
11 # source our configuration
12 config="${0%/*}/zfs-scripts.conf"
13 [ -e "${config}.dist" ] && . ${config}.dist
14 [ -e "${config}" ] && . ${config}
15
16 # command line arg parsing
17 remote=$1
18 remote_fs=$2
19 remote_pool=${2%%/*}
20
21 # return non-zero exit code if any command in the pipe fails
22 set -o pipefail
23
24 # get the backup pool from the command line or the config file if not specified
25 if [[ -n $3 ]]; then
26     backup_pool=$3
27 else
28     backup_pool=${backup_pool%% *} # use the first backup pool if none specified
29 fi
30
31 # Setup our cleanup and exit trap
32 cleanup() {
33   if [[ -e "$local_list" ]]; then
34     rm -f $local_list
35   fi
36   if [[ -e "$remote_list" ]]; then
37     rm -f $remote_list
38   fi
39   $ssh $remote ls -d "$lockdir" > /dev/null 2>&1
40   if [[ $? == 0 ]]; then
41     $ssh $remote rm -rf "$lockdir"
42   fi
43 }
44 fatal_and_exit() {
45   echo -e 2>&1 "$1"
46   # Destroy the current backup markers from the local backup_pool and remote_pool if they exist
47   if [[ -n "$current_backup_marker" ]]; then
48     # Local backup pool current backup marker
49     $zfs list -t snapshot ${backup_pool}/${current_backup_marker} > /dev/null 2>&1
50     if [ $? == 0 ]; then
51       $zfs destroy ${backup_pool}/${current_backup_marker}
52     fi
53     # Remote pool current backup marker
54     $ssh $remote zfs list -t snapshot ${current_backup_marker} > /dev/null 2>&1
55     if [ $? == 0 ]; then
56       $ssh $remote $zfs destroy ${current_backup_marker}
57     fi
58   fi
59   # send email notification
60   if [[ -n "$2" ]]; then
61     echo -e "$1" | $mailx -s "zfs replicate on $hostname failed" "$2"
62   fi
63   # exit
64   exit 1
65 }
66 trap fatal_and_exit INT
67 trap cleanup EXIT
68
69 # Declare a function to handle the replicate operation
70 replicate() {
71   zfs_send="$1"
72   zfs_recv="$zfs receive -vF -d ${backup_pool}/${remote_pool}"
73   glue="$throttle $throttle_opt"
74   if [[ $throttle_enable == 1 && -e $throttle ]]; then
75     # handle using the glue in the local and remote host case properly
76     if [[ -z "$ssh" ]]; then
77       # local host glue case
78       $zfs_send | $glue | $zfs_recv 
79     else
80       # remote host glue case
81       $ssh $remote "$zfs_send | $glue" | $zfs_recv
82     fi
83   else 
84     # no glue case - works for both the local and remote host cases
85     $ssh $remote $zfs_send | $zfs_recv
86   fi
87   # The return code of the zfs_send | zfs_recv operation will be returned to the caller
88 }
89
90 # Make sure we have valid arguments
91 if [[ -z "$remote" ]] || [[ -z "$remote_fs" ]]; then
92   fatal_and_exit "Usage: $0 <hostname> <zfs filesystem>"
93 fi
94
95 # check for localhost
96 if [[ $remote = "localhost" ]]; then
97   remote=""
98   ssh=""
99 fi
100
101 # Make sure the local backup pool and local receiving filesystem exist, or print some errors
102 zpool list -H "$backup_pool" >/dev/null 2>&1
103 if [ $? != 0 ]; then
104   fatal_and_exit "-E- The local backup pool on $hostname, '$backup_pool' doesn't seem to exist." $mailto
105 fi
106 zfs list "$backup_pool/$remote_pool" >/dev/null 2>&1
107 if [ $? != 0 ]; then
108   echo >&2 "-I- The local filesystem for the remote pool, '$backup_pool/$remote_pool' doesn't seem to exist."
109   echo >&2 "    Creating the local filesystem to receive the remote pool into: $backup_pool/$remote_pool"
110   $zfs create $backup_pool/$remote_pool
111   if [ $? != 0 ]; then
112     fatal_and_exit "-E- remote $zfs on $hostname create $backup_pool/$remote_pool command failed" $mailto
113   fi
114 fi
115
116 # Obtain the zpool guid for the local backup pool
117 backup_pool_guid=`zpool get guid $backup_pool 2>&1 | grep $backup_pool | awk '{ print $3 }'`
118 zpool get guid $backup_pool > /dev/null 2>&1
119 if [ $? != 0 ]; then
120   fatal_and_exit "-E- Unable to extract the guid for the local backup pool on $hostname: $backup_pool" $mailto
121 fi
122
123 # Turn on shell verbosity
124 set -x
125
126 # Create the remote lockdir before continuing with the replicate
127 # Spinlock on creating the lock
128 maxsleeptime=60
129 maxattempts=500
130 attempts=0
131 while true; do
132   $ssh $remote mkdir "$lockdir" >/dev/null 2>&1
133   if [ $? != 0 ]; then
134     # Another zfs admin tool is running.
135     # Wait a random amount of time and try again
136     ransleep=$(($RANDOM % $maxsleeptime))
137     sleep $ransleep
138     ((attempts=attempts+1))
139   else 
140     # No other zfs admin tool is running, we can now.
141     break
142   fi
143   if [[ $attempts -gt $maxattempts ]]; then
144     # We've exceeded our maximum while loop count
145     echo "-E- The zfs filesystem has been locked down. Skipping replicate operation."
146     fail_msg=`$ssh $remote ls -ld $lockdir 2>&1`
147     fatal_and_exit "zfs-replicate-all on $hostname unable to obtain zfs admin lock:\n$fail_msg" $mailto
148   fi
149 done
150
151 # Setup our backup marker names
152 current_backup_marker=${remote_fs}@current-backup-${backup_pool_guid}
153 previous_backup_marker=${remote_fs}@previous-backup-${backup_pool_guid}
154
155 # List the snapshots on the remote machine.
156 remote_list=$(mktemp /tmp/replicate.XXXXXX)
157 $ssh $remote \
158     $zfs list -H -t snapshot |
159     grep ^${remote_fs}@ |
160     awk '{print$1}' > $remote_list
161 if [[ $? != 0 ]] && [[ $expect_empty_remote_list == 0 ]]; then
162   echo "-W- Unable to find $remote_fs on the remote host $hostname. Unable to proceed since the"
163   echo "    expect_empty_remote_list option has not been set to allow this, skipping replicate operation."
164   fatal_and_exit "-E- remote $zfs list on $hostname for $remote_fs command failed" $mailto
165 fi
166
167 # List the snapshots on the local machine.
168 # Don't list the current backup marker if it exists on the local side.
169 # If you do, it can mess up the common finding algorithm below.
170 local_list=$(mktemp /tmp/replicate.XXXXXX)
171 $zfs list -H -t snapshot |
172     grep ^${backup_pool}/${remote_fs}@ |
173     grep -v ^${backup_pool}/${current_backup_marker} | 
174     awk "{gsub(/^$backup_pool./,\"\",\$1); print\$1}" > $local_list
175 # If no local snapshots exist, we may need to send the entire filesystem, which we'll do later
176 # So, no error check here as a non-zero return code means the local filesystem or snaps are missing
177 # We'll catch this later on as a case where we need to send the entire filesystem
178
179 # Destroy the current backup marker snapshot on the remote system if it exists
180 grep -q ${current_backup_marker} $remote_list
181 if [ $? == 0 ]; then
182   $ssh $remote $zfs destroy ${current_backup_marker} 
183   if [ $? != 0 ]; then
184     fatal_and_exit "-E- remote $zfs destroy $current_backup_marker on $hostname command failed" $mailto
185   fi
186 fi
187
188 # Create the current backup marker snapshot on the remote system
189 $ssh $remote $zfs snapshot ${current_backup_marker}
190 if [ $? != 0 ]; then
191   fatal_and_exit "-E- remote $zfs snapshot $current_backup_marker on $hostname command failed" $mailto
192 fi
193
194 # Check to see if the previous backup marker exists in the remote snapshot list.
195 # Check to see if the previous backup marker exists in the local snapshot list.
196 # If the previous backup markers exists, perform an incremental replicate. Else:
197 # 1) check to see if a common snapshot exists, and perform an incremental replicate.
198 # 2) if no common snapshot exists, destroy the local filesystem, and perform a full replicate.
199 grep -q ${previous_backup_marker} $remote_list
200 no_markers=$?
201 grep -q ${previous_backup_marker} $local_list
202 no_markers=$(($no_markers || $?))
203
204 if [ $no_markers == 0 ]; then
205   # We found backup markers, incrementally send the new snaps
206
207   # First, rollback the local backup pool to the previous backup marker in case the previous
208   # backup was interrupted for some reason. If we don't do this, the zfs send -R command
209   # below may complain about snaps already existing as it tries to resend from the 
210   # previous backup marker again from a previously interrupted replicate.
211   $zfs rollback -rf ${backup_pool}/${previous_backup_marker} 
212   if [ $? != 0 ]; then
213     sleep 120
214     $zfs rollback -rf ${backup_pool}/${previous_backup_marker}
215     if [ $? != 0 ]; then
216       fatal_and_exit "-E- remote incremental $zfs rollback $backup_pool/$previous_backup_marker command failed on $hostname" $mailto
217     fi
218   fi
219   # Now it should be safe to send the snaps
220   replicate "$zfs send -Rc -I${previous_backup_marker} ${current_backup_marker}"
221   if [ $? != 0 ]; then
222     fatal_and_exit "-E- remote incremental $zfs send $previous_backup_marker command failed on $hostname" $mailto
223   fi
224 else
225   # We didn't find any backup markers, next check to see if we have a common snapshot.
226
227   # See what the most recent snapshot on the remote end is.
228   latest=$(tail -n 1 $remote_list)
229
230   # I did this to make sure that diff would always display the most recent common
231   # Since we're keying off the context of the diff, we need to ensure we will get context
232   # by injecting a known difference in case no others exist in the lists.
233   echo bogus.remote >> $remote_list
234   echo bogus.local  >> $local_list
235   common=$(diff -u $remote_list $local_list | grep '^ ' | tail -n 1)
236
237   if [[ -n "$common" ]]; then
238     # We found a common snapshot, incrementally send the new snaps
239     replicate "$zfs send -Rc -I${common/*@/@} ${current_backup_marker}"
240     if [ $? != 0 ]; then
241       fatal_and_exit "-E- remote incremental $zfs send $(common/*@/@) command failed on $hostname" $mailto
242     fi
243   else
244     # We did not find any markers or a common snapshot
245     # At this point, we'll have to send the entire filesystem
246     # Destroy the local filesystem if it exists before receving the full replicate
247     zfs list ${backup_pool}/${remote_fs} > /dev/null 2>&1
248     if [ $? == 0 ]; then
249       if [[ $destroy_local_filesystem_on_full_replicate == 1 ]]; then
250         $zfs destroy -r ${backup_pool}/${remote_fs}
251         if [ $? != 0 ]; then
252           fatal_and_exit "-E- remote full $zfs destroy $backup_pool/$remote_fs command failed on $hostname" $mailto
253         fi
254       else
255         echo "-W- We need to destroy a local filesystem before receiving a full stream."
256         echo "    However, since the option is set to prevent this, skipping replicate operation."
257         fatal_and_exit "unable to destroy local filesystem:\n$zfs destroy -r ${backup_pool}/${remote_fs} not able to run on $hostname" $mailto
258       fi
259     fi
260     # Send the full filesystem
261     replicate "$zfs send -Rc ${current_backup_marker}"
262     if [ $? != 0 ]; then
263       fatal_and_exit "-E- remote full $zfs send $current_backup_marker command failed on $hostname" $mailto
264     fi
265   fi
266 fi
267  
268 # destroy the previous backup markers now that we've replicated past them
269 # don't check the return codes here because these may not exist, and that is ok
270 $zfs destroy ${backup_pool}/${previous_backup_marker} > /dev/null 2>&1
271 $ssh $remote $zfs destroy ${previous_backup_marker} > /dev/null 2>&1
272 sleep 1
273
274 # Rename the current backup marker to be the previous backup marker
275 $zfs rename ${backup_pool}/${current_backup_marker} ${backup_pool}/${previous_backup_marker}
276 if [ $? != 0 ]; then
277   fatal_and_exit "-E- local $zfs rename $backup_pool/$current_backup_marker command failed on $hostname" $mailto
278 fi
279 $ssh $remote $zfs rename ${current_backup_marker} ${previous_backup_marker}
280 if [ $? != 0 ]; then
281   fatal_and_exit "-E- remote $zfs rename $current_backup_marker command failed on $hostname" $mailto
282 fi