3 ### Remove an LVM snapshot, without falling foul of LVM bugs
5 ### (c) 2011 Mark Wooding
8 ###----- Licensing notice ---------------------------------------------------
10 ### This program is free software; you can redistribute it and/or modify
11 ### it under the terms of the GNU General Public License as published by
12 ### the Free Software Foundation; either version 2 of the License, or
13 ### (at your option) any later version.
15 ### This program is distributed in the hope that it will be useful,
16 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ### GNU General Public License for more details.
20 ### You should have received a copy of the GNU General Public License
21 ### along with this program; if not, write to the Free Software Foundation,
22 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 use Getopt::Long qw(:config gnu_compat bundling no_ignore_case);
30 use Time::HiRes qw(time);
32 our $VERSION = "@VERSION@";
34 ###--------------------------------------------------------------------------
37 ## Error handling and reporting.
38 (our $QUIS = $0) =~ s:^.*/::;
40 sub whine ($) { my ($msg) = @_; print STDERR "$QUIS: $msg\n"; }
41 sub burble ($) { my ($msg) = @_; whine $msg if $DEBUG; }
42 sub fail ($) { my ($msg) = @_; whine $msg; exit $! || ($? >> 8) || 255; }
44 ## Cleanups. Call `cleanup BLOCK' to arrange to have BLOCK executed at the
45 ## end of the program.
47 sub runcleanups { for my $f (@CLEANUP) { &$f } }
49 $SIG{INT} = $SIG{TERM} = sub {
52 $SIG{$sig} = 'DEFAULT';
55 sub cleanup (&) { unshift @CLEANUP, $_[0]; }
57 sub fixint ($) { my ($x) = @_; return $x =~ /^0/ ? oct $x : $x + 0; }
59 ###--------------------------------------------------------------------------
65 ## Return a sysfs path for a device DEV.
68 my $st = stat $dev or fail "stat ($dev): $!";
70 if (S_ISBLK($st->mode)) { $kind = "block"; }
71 elsif (S_ISCHR($st->mode)) { $kind = "char"; }
72 else { fail "$dev is not a device"; }
73 my ($maj, $min) = (($st->rdev >> 8) & 0xff, $st->rdev & 0xff);
74 (my $whole = realpath "/sys/dev/$kind/$maj:$min") =~ s:^/sys/:/:;
80 sub dmtable_update () {
83 ## Update the device-mapper table in %DMTAB.
85 burble "re-read device-mapper table";
87 open my $dt, "-|", "dmsetup", "table" or fail "open (dm table): $!";
88 while (my $line = $dt->getline) {
89 my ($dev, $rest) = split /[:\s]+/, $line, 2;
90 push @{$DMTAB{$dev}}, [split ' ', $rest];
92 close $dt or fail "dmsetup table failed (rc = $?)";
98 ## Return the device-mapper node name for the sysfs path SYSPATH.
101 open my $f, "<", "/sys$sys/dm/name" or fail "open ($sys/dm/name): $!";
102 chomp (my $name = $f->getline);
107 ###--------------------------------------------------------------------------
111 ## sel TIMEOUT, [READS, WRITES, EXCEPTIONS]
113 ## Wait for at most TIMEOUT seconds (indefinitely if TIMEOUT is `undef').
114 ## Each of READS, WRITES and EXCEPTIONS is a listref containing FILE => SUB
115 ## pairs: if the FILE is readable (writable, has an exceptional condition)
116 ## then the SUB is invoked.
118 my ($t, $r, $w, $x) = @_;
122 ## Read the arguments and build a data structure.
123 for my $i ([$r, \$vr, \%r], [$w, \$vw, \%w], [$x, \$vx, \%x]) {
124 my ($a, $v, $h) = @$i;
128 my ($f, $g) = splice @a, 0, 2;
131 vec($$v, $fd, 1) = 1;
135 ## Do the wait and sift through the results.
136 defined select $vr, $vw, $vx, $t or fail "select: $!";
137 for my $i ([$vr, \%r], [$vw, \%w], [$vx, \%x]) {
139 while (my ($f, $g) = each %$h) {
140 if (vec $v, $f, 1) { &$g; }
146 ## doread FILE, [LEN]
148 ## Read LEN bytes (or a default amount) from FILE. If the file ends,
149 ## return undef. If reading would block then return an empty string.
150 ## Otherwise return he stuff.
153 $n = sysread $f, my $buf, $n // 4096;
154 if (!defined $n) { return "" if $! == EAGAIN; fail "read: $!"; }
155 elsif (!$n) { return undef; }
156 else { return $buf; }
160 ## run WHAT, PROG, ARGS...
162 ## Run PROG, passing it ARGS. Fails if PROG exits nonzero.
164 my ($what, $prog, @args) = @_;
165 system($prog, @args) == 0 or fail "$prog ($what) failed (rc = $?)";
169 ## capture PROG, ARGS...
171 ## Run PROG, passing it ARGS. Returns exit status, stdout, and stderr, as
174 my ($prog, @args) = @_;
175 my ($out, $err) = ("", "");
176 my ($outpipe_in, $outpipe_out, $errpipe_in, $errpipe_out);
177 pipe $outpipe_in, $outpipe_out or fail "pipe ($prog out): $!";
178 pipe $errpipe_in, $errpipe_out or fail "pipe ($prog err): $!";
179 defined (my $kid = fork) or fail "fork ($prog): $!";
182 and close $errpipe_in
183 and open STDOUT, ">&", $outpipe_out
184 and open STDERR, ">&", $errpipe_out
185 and exec $prog, @args
186 or fail "exec $prog: $!";
192 for my $i ([\$outpipe_in, \$out, "out"],
193 [\$errpipe_in, \$err, "err"]) {
194 my ($p, $b, $w) = @$i;
195 push @r, $$p => sub {
196 my $buf = doread $$p;
197 if (defined $buf) { $$b .= $buf; }
198 else { close $$p; $$p = undef; }
204 waitpid $kid, 0 or fail "waitpid ($prog): $!";
205 return $?, $out, $err;
208 ###--------------------------------------------------------------------------
209 ### Monitoring udev events.
211 sub umon_create (@) {
212 ## umon_create ARGS...
214 ## Create a udev monitor, with the given `udevadm monitor' arguments, and
215 ## return an object. We always select only kernel events. We try to wait
216 ## for the monitor to start up before returning. Don't trust this: use
217 ## `umon_sync' anyway.
222 ## Start the monitor process.
223 $u->{KID} = open($u->{PIPE}, "-|",
225 "udevadm", "monitor", "--kernel", "--property", @args)
226 or fail "open (umon): $!";
227 cleanup { kill 9, $u->{KID} };
228 $u->{PIPE}->blocking(0) or fail "set non-blocking (umon): $!";
230 ## Wait for the end of the preamble, indicated by the first blank line.
231 ## From observation with strace(1), this means that the monitor has
232 ## successfully attached itself to its netlink socket and is ready to fetch
241 [ $u->{PIPE} => sub {
242 defined (my $b = doread $u->{PIPE}) or fail "read (umon): eof";
244 if ($buf =~ /\n\n(.*)$/) { $ok = 1; $buf = $1; }
248 if ($now >= $end) { fail "umon timeout"; }
259 ## Read events from UMON, as a list of hash references mapping properties
265 defined (my $buf = doread $u->{PIPE}) or fail "read (umon): end of file";
267 $buf = $u->{BUF} . $buf;
268 my @r = split /\n\n/, $buf, -1;
271 push @s, { map { /^(\w+)=(.*)$/ } split /\n/, $r };
278 ## umon_sync UMON, DEV
280 ## Wait for UMON to report an event about the device DEV (without its
281 ## `/dev/' prefix), triggering periodically just in case it missed one.
282 ## This is useful for synchronizing. Returns the list of events which
283 ## weren't interesting.
290 burble "sync with udev";
294 ## Too late. Trigger a change event and try again.
295 if ($now >= $retry) {
297 run "trigger $dev", "udevadm", "trigger", "--sysname-match=$dev";
300 ## Now read events and see what happens.
303 [ $u->{PIPE} => sub {
304 my @e = umon_read $u;
307 if ($e->{DEVNAME} eq $dev) { $done = 1; push @ev, @e; last; }
308 else { push @ev, $e; }
318 ###--------------------------------------------------------------------------
321 ## Parse the command line.
322 our $USAGE = "usage: $QUIS VGNAME/LVNAME";
323 sub version { print "$QUIS, version $VERSION\n"; }
329 -h, --help Show this help text.
330 -v, --version Show the program version number.
331 -d, --debug Show debugging information.
332 -n, --no-act Don't take corrective actions.
337 GetOptions('help|h|?' => sub { version; help; exit; },
338 'version|v' => sub { version; exit; },
339 'debug|d' => \$DEBUG,
340 'noact|n' => \$NOACT)
342 and @ARGV[0] =~ m:(.+)/(.+):
343 or do { print STDERR $USAGE, "\n"; exit 1; };
344 our ($VG, $LV) = ($1, $2);
346 ## Check that the volume in question actually exists, and is a device-mapper
347 ## device, before we wheel out the big guns.
349 our $SYS = devsys "/dev/$VG/$LV";
350 burble "sysfs name is $SYS";
351 my $t = $DMTAB{dmname $SYS}
352 or fail "/dev/$VG/$LV isn't a device-mapper device";
354 burble "found table...";
355 burble "\t" . join " ", @$_ foreach @$t;
357 $t->[0][2] eq "snapshot" or fail "/dev/$VG/$LV isn't a snapshot";
359 ## Create a udev monitor. We're only interested in disk-shaped block
360 ## devices. (If we use some other device kind for synchronization then this
361 ## filter will have to be broadened.)
362 my $u = umon_create "--subsystem-match=block/disk";
364 ## Prepare for the awful synchronization hack. We need to make sure, below,
365 ## that we've read all of the interesting events resulting from an `lvremove'
366 ## call. To do this, we wait for an event on a different device -- but we
367 ## must avoid being fooled by spurious events on this device. As an attempt
368 ## to minimize the probability of this going wrong, acquire a pet device
369 ## which nobody else is using. The best idea seems to be a loopback device.
370 open my $lopipe, "-|", "losetup", "--show", "--find", "/etc/motd"
371 or fail "open (losetup attach)";
372 chomp (my $lo = $lopipe->getline);
373 { local $/ = undef; <$lopipe>; }
375 $lopipe->close or fail "wait (losetup attach): $!";
376 cleanup { system "losetup", "--detach", "/dev/$lo" };
378 ## Initial synchronization, to make sure stuff works.
381 ## Try to remove the snapshot. Capture stdout and stderr, and relay them if
382 ## nothing serious went wrong.
383 burble "initial attempt to remove snapshot";
384 my ($rc, $out, $err) = capture "lvremove", "--force", "$VG/$LV";
388 burble "lvremove didn't explode (rc = $rc): we're done here";
389 if ($rc >> 8) { $rc >>= 8 }
390 elsif ($rc & 255) { $rc += 128 }
393 burble "initial lvremove failed";
395 ## OK, stuff went wrong. First see if there was a udev cookie left over, and
396 ## if so try to release it. It's important to know that we've read all of
397 ## the relevant uevents, so synchronize again.
398 my @e = umon_sync $u, $lo;
401 $c{($e->{DM_COOKIE} & 0xffff) | 0xd4d0000} = 1
402 if $e->{DEVPATH} eq $SYS && exists $e->{DM_COOKIE};
404 burble "cookies used: " . join ", ", map { sprintf "0x%x", $_ } keys %c;
406 ## Find the used cookies which are still extant, and release them.
407 open $uc, "-|", "dmsetup", "udevcookies" or fail "open (cookies): $!";
410 while (my $l = $uc->getline) {
411 my @f = split ' ', $l;
412 push @leak, $f[0] if $c{fixint $f[0]};
414 close $uc or fail "udevcookies failed (rc = $?)";
416 burble "release leaked cookie $c";
417 run "release cookie", "dmsetup", "udevreleasecookie", $c unless $NOACT;
420 ## If we're very unlucky, the origin volume may still be suspended. Resume
421 ## it now, or the next attempt will get stuck. (Resuming is idempotent, so
422 ## we don't need to check whether it's already running.) Finding the origin
423 ## is annoying: search the device-mapper table for a device with a
424 ## `snapshot-origin' table referencing the same backing store as the
426 my $back = $DMTAB{dmname $SYS}[0][3];
428 burble "backend device $back";
429 for my $dm (keys %DMTAB) {
431 next unless @$t == 1 &&
432 $t->[0][2] eq "snapshot-origin" &&
434 defined $orig and fail "snapshot appears to have multiple origins";
437 defined $orig or fail "couldn't find snapshot origin device";
438 burble "found origin volume $orig; resuming...";
439 run "resume origin $orig", "dmsetup", "resume", $orig unless $NOACT;
441 ## See whether removing the snapshot again helps any.
442 burble "retry snapshot removal";
443 run "retry", "lvremove", "--force", "$VG/$LV" unless $NOACT;
445 ## OK, we're on the way to recovery. The origin device may now be not a
446 ## snapshot-origin any more. Refresh the device-mapper table and inspect it.
448 if (-d "/sys/dev/block/$back") {
449 my $backdm = dmname "/dev/block/$back";
450 if ($DMTAB{$orig}[0][2] ne "snapshot-origin") {
451 burble "origin released but backend $backdm still exists: remove";
452 run "remove backend $backdm", "dmsetup", "remove", $backdm
457 ## All done. There, that wasn't so bad, was it?
458 burble "completed successfully";
461 ###----- That's all, folks --------------------------------------------------