Need to be root to destroy snapshots
[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 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 ]; then
162   fatal_and_exit "-E- remote $zfs list on $hostname command failed" $mailto
163 fi
164
165 # List the snapshots on the local machine.
166 # Don't list the current backup marker if it exists on the local side.
167 # If you do, it can mess up the common finding algorithm below.
168 local_list=$(mktemp /tmp/replicate.XXXXXX)
169 $zfs list -H -t snapshot |
170     grep ^${backup_pool}/${remote_fs}@ |
171     grep -v ^${backup_pool}/${current_backup_marker} | 
172     awk "{gsub(/^$backup_pool./,\"\",\$1); print\$1}" > $local_list
173 # If no local snapshots exist, we may need to send the entire filesystem, which we'll do later
174 # So, no error check here as a non-zero return code means the local filesystem or snaps are missing
175 # We'll catch this later on as a case where we need to send the entire filesystem
176
177 # Destroy the current backup marker snapshot on the remote system if it exists
178 grep -q ${current_backup_marker} $remote_list
179 if [ $? == 0 ]; then
180   $ssh $remote $zfs destroy ${current_backup_marker} 
181   if [ $? != 0 ]; then
182     fatal_and_exit "-E- remote $zfs destroy on $hostname command failed" $mailto
183   fi
184 fi
185
186 # Create the current backup marker snapshot on the remote system
187 $ssh $remote $zfs snapshot ${current_backup_marker}
188 if [ $? != 0 ]; then
189   fatal_and_exit "-E- remote $zfs snapshot on $hostname command failed" $mailto
190 fi
191
192 # Check to see if the previous backup marker exists in the remote snapshot list.
193 # Check to see if the previous backup marker exists in the local snapshot list.
194 # If the previous backup markers exists, perform an incremental replicate. Else:
195 # 1) check to see if a common snapshot exists, and perform an incremental replicate.
196 # 2) if no common snapshot exists, destroy the local filesystem, and perform a full replicate.
197 grep -q ${previous_backup_marker} $remote_list
198 no_markers=$?
199 grep -q ${previous_backup_marker} $local_list
200 no_markers=$(($no_markers || $?))
201
202 if [ $no_markers == 0 ]; then
203   # We found backup markers, incrementally send the new snaps
204
205   # First, rollback the local backup pool to the previous backup marker in case the previous
206   # backup was interrupted for some reason. If we don't do this, the zfs send -R command
207   # below may complain about snaps already existing as it tries to resend from the 
208   # previous backup marker again from a previously interrupted replicate.
209   $zfs rollback -rf ${backup_pool}/${previous_backup_marker} 
210   if [ $? != 0 ]; then
211     sleep 120
212     $zfs rollback -rf ${backup_pool}/${previous_backup_marker}
213     if [ $? != 0 ]; then
214       fatal_and_exit "-E- remote incremental $zfs rollback command failed on $hostname" $mailto
215     fi
216   fi
217   # Now it should be safe to send the snaps
218   replicate "$zfs send -Rc -I${previous_backup_marker} ${current_backup_marker}"
219   if [ $? != 0 ]; then
220     fatal_and_exit "-E- remote incremental $zfs send command failed on $hostname" $mailto
221   fi
222 else
223   # We didn't find any backup markers, next check to see if we have a common snapshot.
224
225   # See what the most recent snapshot on the remote end is.
226   latest=$(tail -n 1 $remote_list)
227
228   # I did this to make sure that diff would always display the most recent common
229   # Since we're keying off the context of the diff, we need to ensure we will get context
230   # by injecting a known difference in case no others exist in the lists.
231   echo bogus.remote >> $remote_list
232   echo bogus.local  >> $local_list
233   common=$(diff -u $remote_list $local_list | grep '^ ' | tail -n 1)
234
235   if [[ -n "$common" ]]; then
236     # We found a common snapshot, incrementally send the new snaps
237     replicate "$zfs send -Rc -I${common/*@/@} ${current_backup_marker}"
238     if [ $? != 0 ]; then
239       fatal_and_exit "-E- remote incremental $zfs send command failed on $hostname" $mailto
240     fi
241   else
242     # We did not find any markers or a common snapshot
243     # At this point, we'll have to send the entire filesystem
244     # Destroy the local filesystem if it exists before receving the full replicate
245     zfs list ${backup_pool}/${remote_fs} > /dev/null 2>&1
246     if [ $? == 0 ]; then
247       if [[ $destroy_local_filesystem_on_full_replicate == 1 ]]; then
248         $zfs destroy -r ${backup_pool}/${remote_fs}
249         if [ $? != 0 ]; then
250           fatal_and_exit "-E- remote full $zfs destroy command failed on $hostname" $mailto
251         fi
252       else
253         echo "-W- We need to destroy a local filesystem before receiving a full stream."
254         echo "    However, since the option is set to prevent this, skipping replicate operation."
255         fatal_and_exit "unable to destroy local filesystem:\n$zfs destroy -r ${backup_pool}/${remote_fs} not able to run on $hostname" $mailto
256       fi
257     fi
258     # Send the full filesystem
259     replicate "$zfs send -Rc ${current_backup_marker}"
260     if [ $? != 0 ]; then
261       fatal_and_exit "-E- remote full $zfs send command failed on $hostname" $mailto
262     fi
263   fi
264 fi
265  
266 # destroy the previous backup markers now that we've replicated past them
267 # don't check the return codes here because these may not exist, and that is ok
268 $zfs destroy ${backup_pool}/${previous_backup_marker} > /dev/null 2>&1
269 $ssh $remote $zfs destroy ${previous_backup_marker} > /dev/null 2>&1
270 sleep 1
271
272 # Rename the current backup marker to be the previous backup marker
273 $zfs rename ${backup_pool}/${current_backup_marker} ${backup_pool}/${previous_backup_marker}
274 if [ $? != 0 ]; then
275   fatal_and_exit "-E- local $zfs rename command failed on $hostname" $mailto
276 fi
277 $ssh $remote $zfs rename ${current_backup_marker} ${previous_backup_marker}
278 if [ $? != 0 ]; then
279   fatal_and_exit "-E- remote $zfs rename command failed on $hostname" $mailto
280 fi