backstep-traceback 77.8 KB
Newer Older
1 2
#!/usr/bin/perl
# backstep-traceback - Client software for the AWIT Backstep server
Nigel Kukard's avatar
Nigel Kukard committed
3
# Copyright (c) 2010-2017, AllWorldIT
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.



Nigel Kukard's avatar
Nigel Kukard committed
20 21 22 23 24 25 26 27
=encoding utf8

=head1 NAME

backstep-traceback - Backstep Traceback is a disk snapshotting and backup utility.

=head1 SYNOPSIS

28
	backstep-traceback <GENERAL OPTIONS> <OPERATION MODE> ...
Nigel Kukard's avatar
Nigel Kukard committed
29 30 31 32 33 34 35 36 37 38 39

=cut

=head1 DESCRIPTION

Backstep Traceback is a disk snapshotting and backup utility.

=cut



40 41 42
use strict;
use warnings;
use Data::Dumper;
43
use Fcntl;
44
use File::Copy;
45 46
use File::Path qw( rmtree make_path );
use Getopt::Long;
47
use IO::Handle;
48
use IPC::Open3;
49 50 51 52 53
# Check IO::Pty is installed
if  (!eval {require IO::Pty; 1;}) {
	print STDERR "You're missing IO::Pty, try 'apt-get install libio-pty-perl'\n";
	exit 1;
}
54
use IO::Select;
55
use POSIX qw(WNOHANG strftime EAGAIN);
Nigel Kukard's avatar
Nigel Kukard committed
56
use Sys::Hostname;
57 58 59



Nigel Kukard's avatar
Nigel Kukard committed
60
our $VERSION = "1.3.3";
61 62

# Constants
Nigel Kukard's avatar
Nigel Kukard committed
63 64 65 66 67 68
sub LOG_DEBUG { return 5; }
sub LOG_INFO  { return 4; }
sub LOG_NOTICE  { return 3; }
sub LOG_WARNING  { return 2; }
sub LOG_ERROR  { return 1; }
sub BUFFER_SIZE  { return 1024; }
Nigel Kukard's avatar
Nigel Kukard committed
69

70 71 72 73

# Defaults
my %globalConfig = (
	'log-level' => LOG_NOTICE,
Nigel Kukard's avatar
Nigel Kukard committed
74 75
	'email' => undef,
	'email-subject' => undef,
76 77 78 79 80 81 82 83 84

	'use-rsync' => 1,
	'use-dbackup' => 0,

	'port' => undef,
	'pubkey' => undef,

	'lvm-snapshot' => [ ],
	'exclude-lvm-snapshot' => [ ],
85
	'no-lvm-warning' => 0,
86 87 88
	'bind-mount' => [ ],
	'xattrs' => 0,
	'acls' => 0,
89

90 91
	'compress' => undef,

92
	'bwlimit' => 0,
93 94 95
	'deltas' => 0,
	'safe' => 0,
	'verify' => 0,
96
	'copy-backup-filter' => '/.backup-filter',
97 98
	'append-backup-filter' => 0,
	'prepend-backup-filter' => 0,
99
	'create-timestamp-file' => 0,
100 101 102
	'rsync-quiet' => 0,

	'zabbix' => '',
103
	'zabbix-config' => '/etc/zabbix/zabbix_agentd.conf',
104 105 106 107 108 109 110 111 112 113 114

	'ignore-load' => 0,
	'nice' => 20,
	'io-class' => 3,
	'io-priority' => undef,
	'max-load' => 4,
	'max-cpu' => 80,
);



115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
=head1 GENERAL OPTIONS

C<backstep-traceback> provides the below commandline options...


=head2 --help|?

	Display this help information.

=head2 --version

	Display version information.

=head2 --debug

	Enable debugging information.

=head2 --quiet

	Operate in quiet mode and only output logs if there was an warning or worse error.

=head2 --log-level=<LEVEL>

	Display errors of this priority and higher: 5 = debug, 4 = info, 3 = notice 2 = warning, 1 = error

=head2 --email=<EMAIL>

	Email address to send report to.

=head2 --email-subject=<SUBJECT>

	Extra string to include in subject.


=head1 OPERATION MODE

Backstep Traceback runs in only one operation mode at a time...

=head2 --backup <DEST>

	Do a backup to <DEST>.

=head2 --restore <SOURCE> <DEST>

	Restore <SOURCE> to <DEST>. The <DEST> location is always a local path.

=head2 --use-rsync

	Use rsync to backup/restore. This is default.

=head2 --use-dbackup

	Use dbackup to backup/restore.

=head2 --ignore-load

	Do not use nice/ionice/cputool and completely ignore load on the system.


=head1 BACKUP OPTIONS

When using --backup, the following options are available...

=head2 --lvm-snapshot=<VG/LV|VG>

	Snapshot logical volume. This option takes a full LV name a/b or a VG wich which will result in all LV's being added for that
	VG.

=head2 --exclude-lvm-snapshot=<VG/LV>

	Exclude logical volume from snapshot.

=head2 --no-lvm-warning

	Do not warn if we're not backing all the LVM volumes.

=head2 --bind-mount=<SOURCE>:<DEST>

	Bind mount SOURCE to DEST NB: DEST is suffixed to the temporary mount mount.

=head2 --xattrs

	Backup extended attributes.

=head2 --acls

	Backup posix access control lists.

=head2 --copy-backup-filter[=<BF-FILE>]

	Copy this backup filter to each mounted volume root. Default '/.backup-filter'.

=head2 --append-backup-filter

	Append to any existing backup filter insted of overwriting it.

=head2 --prepend-backup-filter

213
	Prepend to any existing backup filter insted of overwriting it.
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320


=head1 ZABBIX OPTIONS

Zabbix options...


=head2 --zabbix=[XX]

	Send info to Zabbix, item format is:
			custom.backstep.client[XX,timestamp]
			custom.backstep.client[XX,duration]

=head2 --zabbix-config=<CONFIG-FILE>

	Zabbix configuration file. Default is '/etc/zabbix/zabbix_agentd.conf'.


=head1 SSH OPTIONS

SSH options are provided for below...


=head2 --port=<PORT>

	SSH server port.

=head2 --pubkey=<PUBKEY>

	SSH public key.


=head1 DBACKUP OPTIONS

DBackup otpions can be specified below...

=head2 -compress=<ALGO>

	Compression algorithm to use for the backup.


=head1 RSYNC OPTIONS

Options for rsync can be specified using these options...


=head2 --bwlimit=<LIMIT>

	Bandwidth limit. In Kbyte/s.

=head2 --deltas

	Sync file changes only

=head2 --safe

	Do the transfer in a safe transaction.

=head2 --verify[=<COUNT>]

	Checksum verify backup. VERY SLOW!

=head2 --rsync-verbose

	Make Rsync more verbose


=head1 NICE OPTIONS

Options to specify the NICE value for this process to run under are below...


=head2 --nice=<NICE>

	NICE level to run process at. 20 is low, -19 is high. Default: 20.


=head1 IONICE OPTIONS

You can re-nice the IO priority below...


=head2 --io-class=<0-3>

	0 is none, 1 is realtime, 2 is Best effort, 3 is idle. Default: 3.

=head2 --io-prioirty=<0-7>

	0 is high, 7 is low.


=head1 CPUTOOL OPTIONS

Options can be specified to use with cputool below...


=head2 --max-load=<LOAD>

	When load exceeds this amount the process will be paused. Default: 4.

=head2 --max-cpu=<CPU%>

	Maximum CPU time to allocate to the process. Default: 80.


=cut

321 322 323
# Grab options
my %optctl = ();
GetOptions(\%optctl,
324 325
	"help|?",
	"version",
326 327

	"debug",
Nigel Kukard's avatar
Nigel Kukard committed
328
	"quiet",
329
	"log-level=i",
Nigel Kukard's avatar
Nigel Kukard committed
330 331
	"email=s",
	"email-subject=s",
332 333 334 335 336 337 338 339 340 341 342 343

	"backup",
	"restore",

	"use-rsync",
	"use-dbackup",

	"port=i",
	"pubkey=s",

	"lvm-snapshot=s@",
	"exclude-lvm-snapshot=s@",
344
	"no-lvm-warning",
345
	"bind-mount=s@",
346 347
	"xattrs",
	"acls",
348

349
	"compress",
350 351 352 353 354

	"bwlimit=i",
	"deltas",
	"safe",
	"verify:i",
355
	"copy-backup-filter",
356 357
	"append-backup-filter",
	"prepend-backup-filter",
358
	"create-timestamp-file",
359
	"rsync-quiet",
360

361
	"zabbix=s",
362
	"zabbix-config=s",
363

364
	"ignore-load",
365 366 367 368 369 370 371 372 373 374 375 376 377
	"nice=i",
	"io-class=i",
	"io-priority=i",
	"max-load=f",
	"max-cpu=i",
) or exit 1;

# Check for help
if (defined($optctl{'help'})) {
	displayHelp();
	exit 0;
}

378 379 380 381 382 383
# Check for version
if (defined($optctl{'version'})) {
	displayVersion();
	exit 0;
}

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
# Check for invalid combination
if (defined($optctl{'backup'}) && defined($optctl{'restore'})) {
	print(STDERR "ERROR: Cannot backup AND restore at the same time\n\n");
	displayHelp();
	exit 1;
}
if (!defined($optctl{'backup'}) && !defined($optctl{'restore'})) {
	print(STDERR "ERROR: You must specify --backup or --restore\n\n");
	displayHelp();
	exit 1;
}
# Check backup has one parameter which is the destination
if (defined($optctl{'backup'}) && @ARGV != 1) {
		print(STDERR "ERROR: $0 [args] --backup <DESTINATION>\n\n");
		displayHelp();
		exit 1;
} elsif (defined($optctl{'restore'}) && @ARGV != 2) {
		print(STDERR "ERROR: $0 [args] --restore <SOURCE> <DESTINATION>\n\n");
		displayHelp();
		exit 1;
}

# Handle debugging
if (defined($optctl{'debug'})) {
	$globalConfig{'log-level'} = LOG_DEBUG;
}
Nigel Kukard's avatar
Nigel Kukard committed
410 411 412
if (defined($optctl{'quiet'})) {
	$globalConfig{'log-level'} = LOG_WARNING;
}
413 414 415 416 417
# Handle log level
if (defined($optctl{'log-level'})) {
	$globalConfig{'log-level'} = $optctl{'log-level'};
}

Nigel Kukard's avatar
Nigel Kukard committed
418 419 420 421 422 423 424 425
# Handle emailing of report
if (defined($optctl{'email'})) {
	$globalConfig{'email'} = $optctl{'email'};
}
if (defined($optctl{'email-subject'})) {
	$globalConfig{'email-subject'} = $optctl{'email-subject'};
}

426 427 428 429 430 431 432
# Decide the method to use when backing up
if (defined($optctl{'use-rsync'}) && defined($optctl{'use-dbackup'})) {
	print(STDERR "ERROR: --use-rsync and --use-dbackup cannot both be used\n\n");
	exit 1;
}
if (defined($optctl{'use-rsync'})) {
	$globalConfig{'use-dbackup'} = 0;
Nigel Kukard's avatar
Nigel Kukard committed
433
	$globalConfig{'use-rsync'} = 0;
434 435 436
}
if (defined($optctl{'use-dbackup'})) {
	$globalConfig{'use-rsync'} = 0;
Nigel Kukard's avatar
Nigel Kukard committed
437
	$globalConfig{'use-dbackup'} = 1;
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
}

# Decide on server details based on commandline options
if (defined($optctl{'server'})) {
	$globalConfig{'server'} = $optctl{'server'};
}
if (defined($optctl{'port'})) {
	$globalConfig{'port'} = int($optctl{'port'});
}
if (defined($optctl{'pubkey'})) {
	$globalConfig{'pubkey'} = $optctl{'pubkey'};
}

# LVM snapshot stuff
if (defined($optctl{'lvm-snapshot'})) {
	push(@{$globalConfig{'lvm-snapshot'}},@{$optctl{'lvm-snapshot'}});
	if (defined($optctl{'restore'})) {
		print(STDERR "ERROR: Option --lvm-snapshot ignored while using --restore\n\n");
		exit 1;
	}
}
if (defined($optctl{'exclude-lvm-snapshot'})) {
	push(@{$globalConfig{'exclude-lvm-snapshot'}},@{$optctl{'exclude-lvm-snapshot'}});
	if (defined($optctl{'restore'})) {
		print(STDERR "ERROR: Option --exclude-lvm-snapshot ignored while using --restore\n\n");
		exit 1;
	}
}
466 467 468
if (defined($optctl{'no-lvm-warning'})) {
	$globalConfig{'no-lvm-warning'} = 1;
}
469 470 471 472 473 474 475 476 477 478 479 480 481
# Bind mounts
if (defined($optctl{'bind-mount'})) {
	push(@{$globalConfig{'bind-mount'}},@{$optctl{'bind-mount'}});
	if (defined($optctl{'restore'})) {
		print(STDERR "ERROR: Option --bind-mount ignored while using --restore\n\n");
		exit 1;
	}
}
if (defined($optctl{'xattrs'})) {
	$globalConfig{'xattrs'} = 1;
}
if (defined($optctl{'acls'})) {
	$globalConfig{'acls'} = 1;
482 483
}

484 485 486 487 488
# DBackup
if (defined($optctl{'compress'})) {
	$globalConfig{'compress'} = $optctl{'compress'};
}

489 490 491
# RSync
if (defined($optctl{'bwlimit'})) {
	$globalConfig{'bwlimit'} = int($optctl{'bwlimit'});
492
	if (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
493
		print(STDERR "ERROR: Option --bwlimit ignored while using --use-dbackup\n\n");
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
		exit 1;
	}
}
if (defined($optctl{'deltas'})) {
	$globalConfig{'deltas'} = 1;
	if (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
		print(STDERR "ERROR: Option --deltas ignored while using --use-dbackup\n\n");
		exit 1;
	}
}
if (defined($optctl{'safe'})) {
	$globalConfig{'safe'} = 1;
	if (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
		print(STDERR "ERROR: Option --safe ignored while using --use-dbackup\n\n");
		exit 1;
	}
}
511 512
# Check our backup filter file exists
if (defined($optctl{'copy-backup-filter'})) {
513 514 515 516 517
	# Check if we have an argument
	if ($optctl{'copy-backup-filter'} ne "1") {
		$globalConfig{'copy-backup-filter'} = $optctl{'copy-backup-filter'};
	}
	# Make sure it exists
518
	if (! -e $globalConfig{'copy-backup-filter'}) {
519
		printf(STDERR "ERROR: Option --copy-backup-filter specified with non-existent file '%s'\n\n",
520 521 522 523 524 525 526 527
				$globalConfig{'copy-backup-filter'});
		exit 1;
	}
} else {
	if (! -e $globalConfig{'copy-backup-filter'}) {
		$globalConfig{'copy-backup-filter'} = undef;
	}
}
528 529 530 531 532 533 534 535 536 537 538 539
if (defined($optctl{'append-backup-filter'})) {
	$globalConfig{'append-backup-filter'} = 1;
	if (!defined($globalConfig{'copy-backup-filter'})) {
		print(STDERR "WARNING Option --append-backup-filter only really makes sense when --copy-backup-filter is used\n\n");
	}
}
if (defined($optctl{'prepend-backup-filter'})) {
	$globalConfig{'prepend-backup-filter'} = 1;
	if (!defined($globalConfig{'copy-backup-filter'})) {
		print(STDERR "WARNING Option --prepend-backup-filter only really makes sense when --copy-backup-filter is used\n\n");
	}
}
540

541 542 543 544 545 546 547
if (defined($optctl{'create-timestamp-file'})) {
	$globalConfig{'create-timestamp-file'} = 1;
	if (!$globalConfig{'safe'}) {
		print(STDERR "WARNING Option --create-timestamp-file only really makes sense when --safe is used\n\n");
	}
}

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
if (defined($optctl{'rsync-quiet'})) {
	$globalConfig{'rsync-quiet'} = 1;
	if (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
		print(STDERR "ERROR: Option --rsync-quiet ignored while using --use-dbackup\n\n");
		exit 1;
	}
}

if (defined($optctl{'verify'})) {
	$globalConfig{'verify'} = int($optctl{'verify'});
	if (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
		print(STDERR "ERROR: Option --verify ignored while using --use-dbackup\n\n");
		exit 1;
	}
}

if (defined($optctl{'zabbix'})) {
	$globalConfig{'zabbix'} = $optctl{'zabbix'};
Nigel Kukard's avatar
Nigel Kukard committed
566
	if (!checkPATH("zabbix_sender")) {
567
		print(STDERR "ERROR: 'zabbix_sender' used by the --zabbix option not found in PATH\n\n");
568 569 570 571 572 573
		exit 1;
	}
	if (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
		print(STDERR "ERROR: Option --acls ignored while using --use-dbackup\n\n");
		exit 1;
	}
574 575 576

	if (defined($optctl{'zabbix-config'})) {
		$globalConfig{'zabbix-config'} = $optctl{'zabbix-config'};
Nigel Kukard's avatar
Nigel Kukard committed
577
	}
578 579
	if (! -f $globalConfig{'zabbix-config'}) {
		print(STDERR "ERROR: Cannot access zabbix config file '".$globalConfig{'zabbix-config'}."'\n\n");
Nigel Kukard's avatar
Nigel Kukard committed
580 581
		exit 1;
	}
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
}

if (defined($optctl{'ignore-load'})) {
	$globalConfig{'ignore-load'} = 1;
}

if (defined($optctl{'nice'})) {
	$globalConfig{'nice'} = int($optctl{'nice'});
	if (!checkPATH("nice")) {
		print(STDERR "ERROR: --nice used by 'nice' not found in PATH\n\n");
		exit 1;
	}
}

if (defined($optctl{'io-class'})) {
	$globalConfig{'io-class'} = int($optctl{'io-class'});
	if (!checkPATH("ionice")) {
		print(STDERR "ERROR: --io-class used by 'ionice' not found in PATH\n\n");
		exit 1;
	}
}
if (defined($optctl{'io-priority'})) {
	$globalConfig{'io-priority'} = int($optctl{'io-priority'});
	if (!checkPATH("ionice")) {
		print(STDERR "ERROR: --io-class used by 'ionice' not found in PATH\n\n");
		exit 1;
	}
}

if (defined($optctl{'max-load'})) {
	$globalConfig{'max-load'} = int($optctl{'max-load'});
	if (!checkPATH("cputool")) {
		print(STDERR "ERROR: --max-load used by 'cputool' not found in PATH\n\n");
		exit 1;
	}
}
if (defined($optctl{'max-cpu'})) {
	$globalConfig{'max-cpu'} = int($optctl{'max-cpu'});
	if (!checkPATH("cputool")) {
		print(STDERR "ERROR: --max-cpu used by 'cputool' not found in PATH\n\n");
		exit 1;
	}
}

# Setup signal handlers
Nigel Kukard's avatar
Nigel Kukard committed
627
## no critic (Variables::RequireLocalizedPunctuationVars)
628 629 630 631 632 633
$SIG{INT} = \&sig_INT;
$SIG{TERM} = \&sig_INT;
$SIG{HUP} = \&sig_HUP;
$SIG{USR1} = \&sig_USR1;
$SIG{USR2} = \&sig_USR2;
#$SIG{CHLD} = \&sig_CHLD; # NK: NOT USED ATM as we wait patiently
Nigel Kukard's avatar
Nigel Kukard committed
634
## use critic
635

Nigel Kukard's avatar
Nigel Kukard committed
636 637
# Email report contents
my @globalEmailReport = ();
638
# Children exit codes
639
my %globalChildren = ();
640
# LV's we've created which need to be torn down
641
my %globalCreatedLVSnapshots = ();
642 643 644 645 646
my @globalCreatedPartitions = ();
my @globalMountedFilesystems = ();
my @globalCreatedDirs = ();


647 648
# Autoflush STDERR
STDERR->autoflush(1);
649

650 651
printLog(LOG_NOTICE,"AWIT-Backstep-Traceback v$VERSION");

652 653 654
# If we backing up, lets go for it
if (defined($optctl{'backup'})) {

Nigel Kukard's avatar
Nigel Kukard committed
655 656 657
	my $res = doBackup(@ARGV);
	printLog(LOG_NOTICE,"Exiting normally: $res");
	exit $res;
658 659 660 661

# If we restoring, do that
} elsif (defined($optctl{'restore'})) {

Nigel Kukard's avatar
Nigel Kukard committed
662 663 664
	my $res = doRestore(@ARGV);
	printLog(LOG_NOTICE,"Exiting normally: $res");
	exit $res;
665 666
}

Nigel Kukard's avatar
Nigel Kukard committed
667
printLog(LOG_ERROR,"Nothing to do??");
668

Nigel Kukard's avatar
Nigel Kukard committed
669
exit 1;
670 671


672 673 674 675
# Display version
sub displayVersion
{
	print("$VERSION\n");
Nigel Kukard's avatar
Nigel Kukard committed
676 677

	return;
678
}
679

Nigel Kukard's avatar
Nigel Kukard committed
680

681
# Display usage
682 683
sub displayHelp
{
684
	print(STDERR<<EOF);
Nigel Kukard's avatar
Nigel Kukard committed
685
AWIT-Backstep-Traceback v$VERSION - Copyright (c) 2010-2017, AllWorldIT
686 687


688 689 690 691
Usage: $0 <options>

    General Options:
      --help                             What you seeing now.
692
      --version                          Display version.
693
      --debug                            Enable debugging.
Nigel Kukard's avatar
Nigel Kukard committed
694
      --quiet                            Makes us quiet, except for errors.
Nigel Kukard's avatar
Nigel Kukard committed
695
      --log-level=<LEVEL>                5 = debug, 4 = info, 3 = notice
696
                                         2 = warning, 1 = error
Nigel Kukard's avatar
Nigel Kukard committed
697 698
      --email=<ADDRESS>                  Email address to send report to.
      --email-subject=<SUBJECT>          Extra string to include in subject.
699 700 701 702 703 704 705 706 707 708

    Operation Mode:
      --backup <DEST>                    Do a backup.
      --restore <SOURCE> <DEST>          Restore a backup.
      --use-rsync                        Use Rsync to backup/restore. Default.
      --use-dbackup                      Use dbackup to backup/restore.
      --ignore-load                      Don't use nice/ionice/cputool and
                                         ignore load.

    Backup Options:
709 710 711 712
      --lvm-snapshot=<VG/LV|VG>          Snapshot logical volume. This option
                                         takes a full LV name a/b or a VG wich
                                         which will result in all LV's being
                                         added for that VG.
713
      --exclude-lvm-snapshot=<VG/LV>     Exclude logical volume from snapshot.
714 715
      --no-lvm-warning                   Do not warn if we're not backing all
                                         the LVM volumes.
716 717 718
      --bind-mount=<SOURCE>:<DEST>       Bind mount SOURCE to DEST
                                         NB: DEST is suffixed to the temporary
                                         mount mount.
719 720
      --xattrs                           Backup extended attributes.
      --acls                             Backup posix access control lists.
721 722 723 724 725
      --copy-backup-filter[=<BF-FILE>]   Copy this backup filter to each
                                         mounted volume root.
                                         Default '/.backup-filter'
      --append-backup-filter             Append to any existing backup filter
                                         insted of overwriting it.
726
      --prepend-backup-filter            Prepend to any existing backup filter
727
                                         insted of overwriting it.
728

Nigel Kukard's avatar
Nigel Kukard committed
729 730 731 732
    Zabbix Options:
      --zabbix=[XX]                      Send info to Zabbix, item format is:
                                         custom.backstep.client[XX,timestamp]
                                         custom.backstep.client[XX,duration]
733 734
      --zabbix-config=<CONFIG-FILE>      Zabbix configuration file. Default is
                                         '/etc/zabbix/zabbix_agentd.conf'.
Nigel Kukard's avatar
Nigel Kukard committed
735

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
    SSH Options:
      --port=<PORT>                      SSH server port.
      --pubkey=<PUBKEY>                  SSH public key.

    DBackup Options:
      --compress=<ALGO>                  Compression algorithm to use for the
                                         backup.

    Rsync Options:
      --bwlimit=<LIMIT>                  Bandwidth limit. In Kbyte/s.
      --deltas                           Sync file changes only"
      --safe                             Do the transfer in a safe transaction.
      --verify[=<COUNT>]                 Checksum verify backup. VERY SLOW!
      --rsync-verbose                    Make Rsync more verbose

    Nice Options:
      --nice=<NICE>                      NICE level to run process at.
                                         20 is low, -19 is high. Default: 20.

    IONice Options:
      --io-class=<0-3>                   0 is none, 1 is realtime, 2 is Best
                                         effort, 3 is idle. Default: 3.
      --io-prioirty=<0-7>                0 is high, 7 is low.


    CPUTool Options:
762
      --max-load=<LOAD>                  When load exceeds this amount the
763
                                         process will be paused. Default: 4.
764
      --max-cpu=<CPU%>                   Maximum CPU time to allocate to the
765 766 767
                                         process. Default: 80.

EOF
Nigel Kukard's avatar
Nigel Kukard committed
768 769

	return;
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
}



# Function which actually does our backup
sub doBackup
{
	my $destination = shift;


	# Grab start time of backup
	my $start = time();

	printLog(LOG_NOTICE,"Backup pre-flight check...");

	# Grab temporary portion of a name
	my $tmp = sprintf("%s_%s",time(),$$);
	my $tmpDir = sprintf("/root/tmp/BACKSTEP_TRACEBACK_%s",$tmp);

	# Exit status of this function
	my $exitStatus = 0;

	# NBDs needed to backup qemu disk images
	my $nbdsNeeded = 0;

	#
	# LVM Stuff
	#

	# If we have LVM volumes, check that each one exists
	my $logicalVolumes = {};
	if (defined($globalConfig{'lvm-snapshot'}) && @{$globalConfig{'lvm-snapshot'}}) {

		# We need kpartx for this
		if (! -x '/sbin/kpartx') {
			printLog(LOG_ERROR,"Cannot find '/sbin/kpartx': Maybe you forgot 'apt-get install kpartx'?");
			# Set result and end backup
			$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
808
			goto THE_END;
809 810
		}

811 812 813 814
		# Grab logical volumes
		if (!defined($logicalVolumes = lvmGetLogicalVolumes())) {
			# Set result and end backup
			$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
815
			goto THE_END;
816
		}
817 818
		# Loop with LVM snapshots to backup and tag each one as being queued for backup
		foreach my $lvName (@{$globalConfig{'lvm-snapshot'}}) {
819 820 821 822 823
			# Split off volume group and logical volume
			my ($vgName,$lvNameShort) = split('/',$lvName);

			# IF we have a full LV name
			if (defined($lvNameShort)) {
824 825
				printLog(LOG_INFO,"LVM:  - Adding explicitly specified LV '%s' to backup",$lvName);

826 827 828 829 830
				# Check if it exists
				if (!defined($logicalVolumes->{$lvName})) {
					printLog(LOG_ERROR,"Cannot find LV '%s' on system, ABORTING!",$lvName);
					# Set result and end backup
					$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
831
					goto THE_END;
832 833 834 835 836 837
				}
				# If it does we're going to back it up!
				$logicalVolumes->{$lvName}->{'_backup'} = 1;

			# Looks like we only have a VG name
			} else {
838 839
				printLog(LOG_INFO,"LVM:  - Looking for LV's in VG '%s'...",$vgName);

840 841 842 843 844 845 846 847
				# Running lvName match list
				my @matchList;

				# This means we need to loop through all the LV's and add the ones which match
				foreach my $cLvName (keys %{$logicalVolumes}) {
					my $cLogicalVolume = $logicalVolumes->{$cLvName};
					# Check for match
					if ($cLogicalVolume->{'vg_name'} eq $vgName) {
848
						printLog(LOG_INFO,"LVM:    - Found LV '%s'",$cLvName);
849 850 851 852
						push(@matchList,$cLvName);
					}
				}
				# Check if we have no match results
853 854
				if (@matchList < 1) {
					printLog(LOG_ERROR,"Cannot find any LV's in VG '%s' on system, ABORTING!",$vgName);
855 856
					# Set result and end backup
					$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
857
					goto THE_END;
858 859 860 861
				}

				# Add all matched LV's for backup
				foreach my $cLVName (@matchList) {
862
					printLog(LOG_NOTICE,"LVM:  - Adding LV '%s' from volume group '%s' to backup",$cLVName,$lvName);
863 864
					$logicalVolumes->{$cLVName}->{'_backup'} = 1;
				}
865
			}
866

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
		}

		# Loop with LVM snapshots to exclude from the backup
		foreach my $lvName (@{$globalConfig{'exclude-lvm-snapshot'}}) {
			# Check if it exists
			if (!defined($logicalVolumes->{$lvName})) {
				printLog(LOG_WARNING,"Cannot find LV '%s' to exclude on system, ABORTING!",$lvName);
			} else {
				# Set not to backup
				$logicalVolumes->{$lvName}->{'_backup'} = 0;
			}
		}

		# Loop through LV's and check if there are any not being backed up and not on our exclusion list
		foreach my $lvName (keys %{$logicalVolumes}) {
			if (!defined($logicalVolumes->{$lvName}->{'_backup'})) {
883 884 885 886
				# Check if we should not warn about this
				if (!defined($globalConfig{'no-lvm-warning'})) {
					printLog(LOG_WARNING,"System LV '%s' not being backed up or excluded from backup",$lvName);
				}
887 888 889 890 891
				$logicalVolumes->{$lvName}->{'_backup'} = -1;
			}
		}
	}

Nigel Kukard's avatar
Nigel Kukard committed
892
	# If we have bind mounts, verify each of them
893 894 895 896 897 898 899 900 901
	my $bindMounts = {};
	if (defined($globalConfig{'bind-mount'}) && @{$globalConfig{'bind-mount'}}) {
		foreach my $bmount (@{$globalConfig{'bind-mount'}}) {
			my ($source,$dest) = split(/:/,$bmount);
			# Check we have both items
			if (!defined($source) || !defined($dest)) {
				printLog(LOG_ERROR,"Invalid format of bind mount '%s', it should be /path/to/source:/dest/path",$bmount);
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
902
				goto THE_END;
903 904 905 906 907 908
			}
			# Make sure first one exists
			if (! -d $source) {
				printLog(LOG_ERROR,"Source '%s' of bind mount '%s' must exist",$source,$bmount);
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
909
				goto THE_END;
910 911 912 913 914 915 916 917 918 919 920
			}

			$bindMounts->{$source} = $dest;
		}
	}

	# Make sure we have NBD loaded
	if ($nbdsNeeded) {
		# Make sure module is loaded
		if (! -d '/sys/module/nbd') {
			printLog(LOG_NOTICE,"Loading module 'nbd'");
921
			my ($res,@data) = runCommand("/sbin/modprobe","nbd","max_part=16","nbds_max=16",{"unkillable"=>1});
922 923 924 925 926 927
			# Check result, it should be 0
			if ($res) {
				# If not, output the error
				printLog(LOG_ERROR,"Failed to modprobe 'nbd': %s",$data[1]);
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
928
				goto THE_END;
929 930 931 932 933 934 935 936 937 938 939
			}
			printLog(LOG_ERROR,"Loaded kernel module 'nbd'");
		}
		# Make sure we have enough nbds
		if (open(my $NBDS_MAX_FH,"<","/sys/module/nbd/parameters/nbds_max")) {
			my $nbdsMax = <$NBDS_MAX_FH>;
			close($NBDS_MAX_FH);
			if ($nbdsMax < $nbdsNeeded) {
				printLog(LOG_ERROR,"System does not have enough NBDs to do this backup");
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
940
				goto THE_END;
941 942 943 944 945
			}
		} else {
			printLog(LOG_ERROR,"Failed to open '/sys/module/nbd/parameters/nbds_max': $!");
			# Set result and end backup
			$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
946
			goto THE_END;
947 948 949 950 951 952 953 954 955
		}
		# Make sure we have at least 8 partitions supported
		if (open(my $NBDS_MAX_PART_FH,"<","/sys/module/nbd/parameters/max_part")) {
			my $nbdsMaxPart = <$NBDS_MAX_PART_FH>;
			close($NBDS_MAX_PART_FH);
			if ($nbdsMaxPart < 8) {
				printLog(LOG_ERROR,"System does not have enough NBD partitions to do this backup");
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
956
				goto THE_END;
957 958 959 960 961
			}
		} else {
			printLog(LOG_ERROR,"Failed to open '/sys/module/nbd/parameters/nbds_max': $!");
			# Set result and end backup
			$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
962
			goto THE_END;
963 964 965 966 967
		}
	}

	printLog(LOG_NOTICE,"Backup pre-flight looks good!");

Nigel Kukard's avatar
Nigel Kukard committed
968 969 970 971 972 973 974

	# TODO - qemu images

	# 1: proxmox snapshot
	# 2: libvirt snapshot


975 976 977 978 979 980 981 982 983 984 985 986 987
	# If we have logical volumes we need to prepare them
	if (keys %{$logicalVolumes}) {

		printLog(LOG_NOTICE,"LVM: Snapshotting volumes");

		# Loop with LV's and snapshot them
		foreach my $lvName (keys %{$logicalVolumes}) {
			# Only go for what we have specifically selected for backup
			next if ($logicalVolumes->{$lvName}->{'_backup'} != 1);

			my $logicalVolume = $logicalVolumes->{$lvName};

			my $snapshotName = sprintf("%s_TRACEBACK_%s",$logicalVolume->{'lv_name'},$tmp);
988 989 990
			# Set snapshot size to 95% of our ratio of the available space
			my $snapshotSize = sprintf('%.0f',
						($logicalVolume->{'lv_size'} / $logicalVolume->{'vg_size'}) * $logicalVolume->{'vg_free'} * 0.95
991
			);
992 993 994 995
			# If our snapshot size is very big, we may want to set it to just 10% of its size
			if ($snapshotSize > (my $size = $logicalVolume->{'lv_size'} * 0.10)) {
				$snapshotSize = sprintf('%.0f',$size);
			}
996 997

			printLog(LOG_NOTICE,"LVM:  - Snapshotting: $lvName ($snapshotSize MiB)");
998 999 1000 1001 1002
			if (my $error = lvmCreateSnapshot($logicalVolume->{'vg_name'},$logicalVolume->{'lv_name'},$snapshotSize,$snapshotName)) {
				# If not, output the error
				printLog(LOG_ERROR,"LVM:    - Failed to snapshot LV '%s': %s",$lvName,$error);
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1003
				goto THE_END;
1004 1005 1006 1007 1008 1009 1010 1011 1012
			}

			# Update LV details
			$logicalVolume->{'_backup_snapshot_size'} = $snapshotSize;
			$logicalVolume->{'_backup_snapshot_name'} = $snapshotName;
			$logicalVolume->{'_backup_snapshot_full_name'} = sprintf('%s/%s',$logicalVolume->{'vg_name'},$snapshotName);
			$logicalVolume->{'_backup_snapshot_device'} = sprintf('%s/%s',"/dev",$logicalVolume->{'_backup_snapshot_full_name'});

			# Grab block device attributes
Nigel Kukard's avatar
Nigel Kukard committed
1013
			printLog(LOG_INFO,"LVM:    - Querying device LV '%s'",$snapshotName);
1014 1015 1016 1017 1018 1019
			my $snapshotAttributes = blockGetAttributes($logicalVolume->{'_backup_snapshot_device'});
			if (ref($snapshotAttributes) ne "HASH") {
				# If not, output the error
				printLog(LOG_ERROR,"LVM:    - Failed to get attributes for '%s': %s",$lvName,$snapshotAttributes);
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1020
				goto THE_END;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
			}
			$logicalVolume->{'_backup_snapshot_attributes'} = $snapshotAttributes;

			# Check if we have a filesystem
			if (defined($snapshotAttributes->{'ID_FS_TYPE'})) {
				my $filesystemType = $snapshotAttributes->{'ID_FS_TYPE'};
				# Make sure we know about its type...
				if (!fsSupported($filesystemType)) {
					printLog(LOG_ERROR,"LVM:      - Filesystem '%s' of LV '%s' has no official support!",$filesystemType,
							$lvName);
					# Set result and end backup
					$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1033
					goto THE_END;
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
				}
				printLog(LOG_INFO,"LVM:      - Filesystem is '%s'",$filesystemType);

			# Check if we have a partition table, if we do, probe...
			} elsif (defined($snapshotAttributes->{'ID_PART_TABLE_TYPE'})) {
				# Get partitions on LV
				printLog(LOG_NOTICE,"LVM:    - Probing partitions");
				my $partitions = blockGetPartitions($logicalVolume->{'_backup_snapshot_device'});
				if (!defined($partitions) || !@{$partitions}) {
					printLog(LOG_ERROR,"LVM:      - No partitions detected on '%s' (%s)",$lvName,
							$logicalVolume->{'_backup_snapshot_device'});
					# Set result and end backup
					$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1047
					goto THE_END;
1048 1049 1050 1051 1052 1053 1054 1055
				}
				# Create partitions
				printLog(LOG_INFO,"LVM:    - Creating partitions: %s",join(', ',@{$partitions}));
				if (my $error = blockCreatePartitions($logicalVolume->{'_backup_snapshot_device'})) {
					printLog(LOG_ERROR,"LVM:      - Failed to create partitions for '%s' (%s)",$lvName,
							$logicalVolume->{'_backup_snapshot_device'});
					# Set result and end backup
					$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1056
					goto THE_END;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
				}

				# Probe partitions
				foreach my $partitionName (@{$partitions}) {
					printLog(LOG_INFO,"LVM:    - Querying partition '%s'",$partitionName);
					my $partitionDevice = sprintf('%s/%s','/dev/mapper',$partitionName);
					my $partitionAttributes = blockGetAttributes($partitionDevice);
					if (ref($partitionAttributes) ne "HASH") {
						# If not, output the error
						printLog(LOG_ERROR,"LVM:      - Failed to get attributes for '%s': %s",$partitionDevice,$partitionAttributes);
						# Set result and end backup
						$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1069
						goto THE_END;
1070 1071 1072 1073 1074 1075 1076
					}
					# Make sure we know about this partition
					my $filesystemType = $partitionAttributes->{'ID_FS_TYPE'};
					if (!defined($filesystemType)) {
						printLog(LOG_ERROR,"LVM:      - Filesystem of partition '%s' cannot be detected",$partitionName);
						# Set result and end backup
						$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1077
						goto THE_END;
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
					}
					# Skip swap
					if ($filesystemType eq "swap") {
						printLog(LOG_DEBUG,"LVM:      - Skipping swap partition '%s'",$partitionName);
						next;
					}
					# Make sure we know about its type...
					if (!fsSupported($filesystemType)) {
						printLog(LOG_ERROR,"LVM:      - Filesystem '%s' of partition '%s' has no official support!",$filesystemType,
								$partitionName);
						# Set result and end backup
						$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1090
						goto THE_END;
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
					}
					printLog(LOG_INFO,"LVM:      - Filesystem of partition '%s' is '%s'",$partitionName,$filesystemType);
					# Save the data we just got
					$logicalVolume->{'_backup_snapshot_partitions'}->{$partitionName} = {
						'device' => $partitionDevice,
						'attributes' => $partitionAttributes
					};
				}

			# If we not a filesystem or a partition table we need to abort...
			} else {
				printLog(LOG_NOTICE,"LVM:    - LV '%s' is of unknown type",$snapshotName);
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1105
				goto THE_END;
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
			}
		}

		printLog(LOG_NOTICE,"LVM: Ready!");
	}

	# If we have LV's
	if (keys %{$logicalVolumes}) {
		# Loop with LV's and snapshot them
		printLog(LOG_NOTICE,"LVM: Mounting LVM volumes");
		foreach my $lvName (keys %{$logicalVolumes}) {
			my $logicalVolume = $logicalVolumes->{$lvName};

			# Loop with partitions
			if (defined($logicalVolume->{'_backup_snapshot_partitions'})) {
				foreach my $partitionName (keys %{$logicalVolume->{'_backup_snapshot_partitions'}}) {
					my $partition = $logicalVolume->{'_backup_snapshot_partitions'}->{$partitionName};
					my $filesystemType = $partition->{'attributes'}->{'ID_FS_TYPE'};

					# Determine filesystem name to use
					my $filesystemName;
					if (defined(my $label = $partition->{'attributes'}->{'ID_FS_LABEL'})) {
						$filesystemName = $label;
					} elsif (defined(my $uuid = $partition->{'attributes'}->{'ID_FS_UUID'})) {
						$filesystemName = $uuid;
					} else {
						printLog(LOG_ERROR,"LVM:      - Unable to determine a filesystem name for LV '%s' partition '%s'",$lvName,
								$partitionName);
						# Set result and end backup
						$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1136
						goto THE_END;
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
					}

					# Grab mount paths
					my $mountPoint = sprintf('LVM/%s/%s',$logicalVolume->{'lv_full_name'},$filesystemName);
					my $mountPath = sprintf('%s/%s',$tmpDir,$mountPoint);

					printLog(LOG_NOTICE,"LVM:  - Mounting '%s'",$mountPath);

					# Mount filesystem
					if (my $error = fsMount($partition->{'device'},$filesystemType,$mountPath)) {
						printLog(LOG_ERROR,"LVM:      - Failed to mount '%s' (%s) as '%s': $error",$partitionName,$filesystemType,
								$mountPath);
						# Set result and end backup
						$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1151
						goto THE_END;
1152
					}
1153 1154 1155

					# Save our mount point
					push(@{$logicalVolume->{'_backup_mount_points'}},$mountPath);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
				}

			# Mount main device if it is not a partition
			} elsif (defined(my $filesystemType = $logicalVolume->{'_backup_snapshot_attributes'}->{'ID_FS_TYPE'})) {
				# Determine filesystem name to use
				my $filesystemName;
				if (defined(my $label = $logicalVolume->{'_backup_snapshot_attributes'}->{'ID_FS_LABEL'})) {
					$filesystemName = $label;
				} elsif (defined(my $uuid = $logicalVolume->{'_backup_snapshot_attributes'}->{'ID_FS_UUID'})) {
					$filesystemName = $uuid;
				} else {
					printLog(LOG_ERROR,"LVM:      - Unable to determine a filesystem name for LV '%s'",$lvName);
					# Set result and end backup
					$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1170
					goto THE_END;
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
				}

				# Grab mount paths
				my $mountPoint = sprintf('LVM/%s/%s',$logicalVolume->{'lv_full_name'},$filesystemName);
				my $mountPath = sprintf('%s/%s',$tmpDir,$mountPoint);

				printLog(LOG_NOTICE,"LVM:  - Mounting '%s'",$mountPath);

				# Mount filesystem
				if (my $error = fsMount($logicalVolume->{'_backup_snapshot_device'},$filesystemType,$mountPath)) {
					printLog(LOG_ERROR,"LVM:      - Failed to mount '%s' (%s) as '%s': $error",$lvName,$filesystemType,
							$mountPath);
					# Set result and end backup
					$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1185
					goto THE_END;
1186
				}
1187 1188

				# Save our mount point
1189
				push(@{$logicalVolume->{'_backup_mount_points'}},$mountPath);
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
			}
		}
	}

	# If we have bind mounts...
	if (keys %{$bindMounts}) {
		# Loop with bind mounts
		printLog(LOG_NOTICE,"BIND-MOUNT: Mounting bind mounts");
		foreach my $source (keys %{$bindMounts}) {
			my $dest = $bindMounts->{$source};

			# Grab mount path
			my $mountPath = sprintf('%s/%s',$tmpDir,$dest);

			printLog(LOG_NOTICE,"BIND-MOUNT:  - Mounting '%s' as '%s'",$source,$mountPath);

			# Mount filesystem
			if (my $error = fsBindMount($source,$mountPath)) {
				printLog(LOG_ERROR,"LVM:      - Failed to bind-mount '%s' as '%s': $error",$source,$mountPath);
				# Set result and end backup
				$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1211
				goto THE_END;
1212 1213 1214 1215
			}
		}
	}

Nigel Kukard's avatar
Nigel Kukard committed
1216 1217 1218 1219
	# TODO - qemu images
	# 3: qemu image mount to nbd  QEMU/


1220 1221
	# Launch backup tool
	if (defined($globalConfig{'use-rsync'}) && $globalConfig{'use-rsync'}) {
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
		# Loop with logical volumes
		foreach my $lvName (keys %{$logicalVolumes}) {
			my $logicalVolume = $logicalVolumes->{$lvName};
			# Look for ones mounted
			if (defined($logicalVolume->{'_backup_mount_points'})) {
				# Loop with backup mounts
				foreach my $mountPoint (@{$logicalVolume->{'_backup_mount_points'}}) {
					# If we don't have a backup filter, copy it in
					if (defined($globalConfig{'copy-backup-filter'}) && $globalConfig{'copy-backup-filter'}) {
						my $backupFilter = $globalConfig{'copy-backup-filter'};
1232 1233 1234 1235 1236 1237 1238 1239
						my $backupFilterDest = sprintf('%s/%s',$mountPoint,".backup-filter");
						# Check if they have a backup filter
						if (! -e $backupFilterDest) {
							printLog(LOG_INFO,"RSYNC: - Copying backup filter '%s' to '%s'",$backupFilter,$backupFilterDest);
							if (!copy($backupFilter,$backupFilterDest)) {
								printLog(LOG_INFO,"RSYNC:   - Failed copying: %s",$!);
								# Set result and end backup
								$exitStatus = 1;
Nigel Kukard's avatar
Nigel Kukard committed
1240
								goto THE_END;
1241
							}
1242
						} else {
1243 1244 1245 1246
							# Append backup filter data to exiting backup filter
							if (defined($globalConfig{'append-backup-filter'}) && $globalConfig{'append-backup-filter'}) {
								printLog(LOG_INFO,"RSYNC: - Appending backup filter '%s' to '%s'",$backupFilter,$backupFilterDest);
								# Open the destination
Nigel Kukard's avatar
Nigel Kukard committed
1247
								## no critic (InputOutput::RequireBriefOpen)
1248
								if (open(my $BACKUPFILTERDEST,">>",$backupFilterDest)) {
Nigel Kukard's avatar
Nigel Kukard committed
1249
								## use critic
1250
									# Open the source
Nigel Kukard's avatar
Nigel Kukard committed
1251
									## no critic (InputOutput::RequireBriefOpen)
1252
									if (open(my $BACKUPFILTER,"<",$backupFilter)) {
Nigel Kukard's avatar
Nigel Kukard committed
1253
									## use critic
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
										# Write out a little comment so we know we actually had data appended
										print($BACKUPFILTERDEST "\n#\n# BACKSTEP-TRACEBACK: APPEND DATA FROM $backupFilter\n#\n\n");
										# Append each line
										while (my $line = <$BACKUPFILTER>) {
											print($BACKUPFILTERDEST $line);
										}
										close($BACKUPFILTER);
									} else {
										printLog(LOG_INFO,"RSYNC:   - Failed opening backup filter source: %s",$!);
									}
									close($BACKUPFILTERDEST);
								} else {
									printLog(LOG_INFO,"RSYNC:   - Failed opening backup filter destination: %s",$!);
								}
							# Prepend backup filter data to exiting backup filter
							} elsif (defined($globalConfig{'prepend-backup-filter'}) && $globalConfig{'prepend-backup-filter'}) {
1270
								printLog(LOG_INFO,"RSYNC: - Prepending backup filter '%s' to '%s'",$backupFilter,$backupFilterDest);
1271 1272
								# Open the destination
								my $origBackupFilterData = "";
Nigel Kukard's avatar
Nigel Kukard committed
1273
								## no critic (InputOutput::RequireBriefOpen)
1274 1275 1276 1277 1278 1279 1280
								if (open(my $BACKUPFILTERORIG,"<",$backupFilterDest)) {
									# Read original data
									while (my $line = <$BACKUPFILTERORIG>) {
										$origBackupFilterData .= $line;
									}
									close($BACKUPFILTERORIG);
									# Open the destination
Nigel Kukard's avatar
Nigel Kukard committed
1281
									## no critic (InputOutput::RequireBriefOpen)
1282
									if (open(my $BACKUPFILTERDEST,">",$backupFilterDest)) {
Nigel Kukard's avatar
Nigel Kukard committed
1283
									## use critic
1284
										# Open the source
Nigel Kukard's avatar
Nigel Kukard committed
1285
										## no critic (InputOutput::RequireBriefOpen)
1286
										if (open(my $BACKUPFILTER,"<",$backupFilter)) {
Nigel Kukard's avatar
Nigel Kukard committed
1287
										## use critic
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
											# Write out a little comment so we know we actually had data prepended
											print($BACKUPFILTERDEST
													"\n#\n# BACKSTEP-TRACEBACK: PREPEND DATA FROM $backupFilter\n#\n\n");
											# Append each line
											while (my $line = <$BACKUPFILTER>) {
												print($BACKUPFILTERDEST $line);
											}
											close($BACKUPFILTER);
											# Write out a little comment so we know we actually had data appended
											print($BACKUPFILTERDEST
													"\n#\n# BACKSTEP-TRACEBACK: ORIGINAL FILTER DATA $backupFilterDest\n#\n\n");
											print($BACKUPFILTERDEST $origBackupFilterData);
										} else {
											printLog(LOG_INFO,"RSYNC:   - Failed opening backup filter source: %s",$!);
										}
										close($BACKUPFILTERDEST);
									} else {
										printLog(LOG_INFO,"RSYNC:   - Failed opening backup filter destination: %s",$!);
									}
								} else {
									printLog(LOG_INFO,"RSYNC:   - Failed opening original backup filter: %s",$!);
								}
							} else {
								printLog(LOG_INFO,"RSYNC: - Backup filter '%s' already exists, NOT copying!",$backupFilterDest);
							}
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
						}
					}
					# Check if we need to create a timestamp file
					if (defined($globalConfig{'create-timestamp-file'}) && $globalConfig{'create-timestamp-file'}) {
						my $timestampFileName = sprintf('%s/%s',$mountPoint,".backstep-traceback.timestamp");
						printLog(LOG_INFO,"RSYNC: - Creating timestamp file '%s'",$timestampFileName);
						if (open(my $TSF,">",$timestampFileName)) {
							print($TSF $start);
							close($TSF);
						} else {
							printLog(LOG_INFO,"RSYNC: - Failed to create timestamp file: %s",$!);
1324 1325 1326 1327 1328 1329
						}
					}
				}
			}
		}

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
		($exitStatus) = rsync("$tmpDir/",$destination);
	} elsif (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
		($exitStatus) = dbackup("$tmpDir/",$destination);
	}

	# Grab end time of backup
	my $end = time();
	my $duration = $end - $start;

	printLog(LOG_NOTICE,"STATS: Backup took %is, exit status %i",$duration,$exitStatus);

Nigel Kukard's avatar
Nigel Kukard committed
1341
THE_END:
1342
	doCleanup();
Nigel Kukard's avatar
Nigel Kukard committed
1343 1344 1345 1346 1347 1348

	# Check if we need to report to zabbix
	if (defined($globalConfig{'zabbix'}) && $globalConfig{'zabbix'}) {
		zabbixReport($duration,$exitStatus);
	}

Nigel Kukard's avatar
Nigel Kukard committed
1349 1350 1351 1352 1353
	# Check if we need to email our report
	if (defined($globalConfig{'email'}) && $globalConfig{'email'}) {
		emailReport($exitStatus);
	}

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
	return $exitStatus;
}



# Function which actually does our restoration
sub doRestore
{
	my ($source,$destination) = @_;


	# Grab start time of backup
	my $start = time();

	printLog(LOG_NOTICE,"Restore pre-flight check...");

	# Exit status of this function
	my $exitStatus = 0;

	# Launch restore tool
	if (defined($globalConfig{'use-rsync'}) && $globalConfig{'use-rsync'}) {
		($exitStatus) = rsync($source,$destination,);
	} elsif (defined($globalConfig{'use-dbackup'}) && $globalConfig{'use-dbackup'}) {
		($exitStatus) = dbackup($source,$destination);
	}

	# Grab end time of backup
	my $end = time();
	my $duration = $end - $start;

	printLog(LOG_NOTICE,"STATS: Restore took %is, exit status %i",$duration,$exitStatus);

	doCleanup();
	return $exitStatus;
}



# Cleanup everything behind us
sub doCleanup
{
Nigel Kukard's avatar
Nigel Kukard committed
1395
	# Wait for children to exit first of all
1396
	my @children = keys %globalChildren;
Nigel Kukard's avatar
Nigel Kukard committed
1397 1398 1399 1400
	if (@children) {
		printLog(LOG_NOTICE,"CLEANUP: Waiting for children to exit: %s",join(',',@children));
		# Loop with children
		foreach my $pid (@children) {
1401 1402 1403 1404 1405 1406 1407
			# Check if we don't have a exit status
			if (defined($globalChildren{$pid}->{'res'})) {
				printLog(LOG_INFO,"CLEANUP:   - Child $pid already dead");
				delete($globalChildren{$pid});
				next;
			}

1408 1409 1410 1411 1412 1413 1414 1415
			# If this is an unkillable process, just wait...
			if (defined($globalChildren{$pid}->{'unkillable'})) {
				printLog(LOG_INFO,"CLEANUP:   - Waiting for $pid (unkillable)");
				# Wait forever
				waitpid($pid,0);
				goto KILLED;
			}

Nigel Kukard's avatar
Nigel Kukard committed
1416 1417
			printLog(LOG_INFO,"CLEANUP:   - Checking $pid");
			# Check if they ready to reap
1418 1419
			if (waitpid($pid,WNOHANG)) {
				goto KILLED;
Nigel Kukard's avatar
Nigel Kukard committed
1420
			}
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443

			# If not, send a TERM
			printLog(LOG_INFO,"CLEANUP:   - Killing $pid (SIGTERM)");
			kill('TERM',$pid);
			printLog(LOG_INFO,"CLEANUP:   - Waiting for $pid");
			sleep(2);
			# And finally wait ...
			if (waitpid($pid,WNOHANG)) {
				goto KILLED;
			}

			# If not, send a KILL
			printLog(LOG_INFO,"CLEANUP:   - Killing $pid (SIGKILL)");
			kill('KILL',$pid);
			printLog(LOG_INFO,"CLEANUP:   - Waiting for $pid");
			sleep(2);
			# And finally wait ...
			if (waitpid($pid,WNOHANG)) {
				goto KILLED;
			}

			printLog(LOG_ERROR,"CLEANUP:   - Failed to get rid of child $pid");
KILLED:
1444
			# Remove child
1445
			delete($globalChildren{$pid});
Nigel Kukard's avatar
Nigel Kukard committed
1446 1447 1448
		}
	}

1449 1450 1451
	# Check if we have mounted any filesystems
	if (@globalMountedFilesystems) {
		while (my $mountPoint = pop(@globalMountedFilesystems)) {
Nigel Kukard's avatar
Nigel Kukard committed
1452
			printLog(LOG_INFO,"CLEANUP: Unmounting filesystem '$mountPoint'");
1453
			if (my $error = fsUnmount($mountPoint)) {
Nigel Kukard's avatar
Nigel Kukard committed
1454
				printLog(LOG_ERROR,"CLEANUP:   - ERROR: Unmounting filesystem '$mountPoint': $error");
1455 1456 1457 1458 1459 1460
			}
		}
	}
	# Check if we have any partitions
	if (@globalCreatedPartitions) {
		while (my $device = pop(@globalCreatedPartitions)) {
Nigel Kukard's avatar
Nigel Kukard committed
1461
			printLog(LOG_INFO,"CLEANUP: Removing partitions for '$device'");
1462
			if (my $error = blockDestroyPartitions($device)) {
Nigel Kukard's avatar
Nigel Kukard committed
1463
				printLog(LOG_ERROR,"CLEANUP:   - ERROR: Removing partitions for '$device': $error");
1464 1465 1466
			}
		}
	}
1467

1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
	# Check if we have any global LV's
	if (keys %globalCreatedLVSnapshots) {
		# Check snapshot usage
		my $lvsEnd;
		# Grab logical volumes after we're done, we want to see the usage below
		if (defined($lvsEnd = lvmGetLogicalVolumes())) {
			foreach my $lvName (keys %globalCreatedLVSnapshots) {
				# Grab our logical volume
				my $logicalVolume = $lvsEnd->{$lvName};
				# Grab the name of the original
				my $originalVolumeName = $globalCreatedLVSnapshots{$lvName}->{'source'};
				# Check for running out space
				my $used = $logicalVolume->{'snap_percent'};
				if ($used > 90) {
					printLog(LOG_WARNING,"LVM: Snapshot of '%s' has %s%% usage",$originalVolumeName,$used);
				} elsif ($used > 75) {
					printLog(LOG_WARNING,"LVM: Snapshot of '%s' has %s%% usage",$originalVolumeName,$used);
				} elsif ($used > 50) {
					printLog(LOG_NOTICE,"LVM: Snapshot of '%s' has %s%% usage",$originalVolumeName,$used);
				} else {
					printLog(LOG_INFO,"LVM: Snapshot of '%s' has %s%% usage",$originalVolumeName,$used);
				}
1490
			}
1491 1492
		}

1493
		# Loop with each of the created LV's
1494 1495
		foreach my $lvName (keys %globalCreatedLVSnapshots) {
			printLog(LOG_NOTICE,"CLEANUP: Removing LV snapshot '$lvName'");
1496
			if (my $error = lvmDestroyLogicalVolume($lvName)) {
Nigel Kukard's avatar
Nigel Kukard committed
1497
				printLog(LOG_ERROR,"CLEANUP:   - ERROR: Removing LV '$lvName': $error");
1498
			}
1499 1500
			# Remove Lockfile
			unlink($globalCreatedLVSnapshots{$lvName}->{'lockfile'});
1501 1502
			# Remove snapshot
			delete($globalCreatedLVSnapshots{$lvName});
1503 1504
		}
	}
1505 1506 1507 1508

	# Check if we have created any directories
	if (@globalCreatedDirs) {
		while (my $dir = pop(@globalCreatedDirs)) {
Nigel Kukard's avatar
Nigel Kukard committed
1509
			printLog(LOG_INFO,"CLEANUP: Removing directory '$dir'");
1510
			if (!rmdir($dir)) {
Nigel Kukard's avatar
Nigel Kukard committed
1511
				printLog(LOG_ERROR,"CLEANUP:   - ERROR: Removing '$dir': $!");
1512 1513 1514
			}
		}
	}
Nigel Kukard's avatar
Nigel Kukard committed
1515 1516

	return;
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
}



#
# INTERNALS
#



# Display log line
sub printLog {
	my ($level,$msg,@args) = @_;


	# Work out level txt all nicely
	my $levelTxt = "UNKNOWN";
	if ($level == LOG_DEBUG) {
		$levelTxt = "DEBUG";
	} elsif ($level == LOG_INFO) {
		$levelTxt = "INFO";
	} elsif ($level == LOG_NOTICE) {
		$levelTxt = "NOTICE";
	} elsif ($level == LOG_WARNING) {
		$levelTxt = "WARNING";
	} elsif ($level == LOG_ERROR) {
		$levelTxt = "ERROR";
	}

	# Check log level
Nigel Kukard's avatar
Nigel Kukard committed
1547
	my $logLine = sprintf("%s%8s: $msg\n", strftime('%F %T',localtime()), $levelTxt, @args);
1548
	if ($level <= $globalConfig{'log-level'}) {
Nigel Kukard's avatar
Nigel Kukard committed
1549 1550 1551 1552 1553
		print(STDERR $logLine);
	}
	# Add to our email report
	if (defined($globalConfig{'email'}) && $globalConfig{'email'} && $level <= LOG_NOTICE) {
		push(@globalEmailReport,$logLine);
1554
	}
Nigel Kukard's avatar
Nigel Kukard committed
1555 1556

	return;
1557 1558 1559 1560 1561 1562 1563 1564 1565
}



# Convert a possible string to an array, or return the array if it is indeed an array
sub toArray
{
	my $param = shift;

Nigel Kukard's avatar
Nigel Kukard committed
1566
	if (ref($param) eq "ARRAY") {
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
		return $param;
	} else {
		return [ split(/\n/,$param) ];
	}
}



# Run a command fork()'d
sub runCommandForked {
	my @args = @_;


	# Fork of parent to return and child to run command
	my $pid = fork();
	if (!$pid) {
		runCommand(@args);
		exit;
	}
}


Nigel Kukard's avatar
Nigel Kukard committed
1589

1590 1591 1592 1593
# Run a command
# One can specify an options hash either as the first parameter or the last
# This hash has a few options...
#	write_stdout => 1		Write STDOUT to terminal
1594
#	write_stdout_to_stderr => 1		Write STDOUT to terminal as STDERR
1595 1596 1597
#	write_stderr => 1		Write STDERR to terminal
#	nobuffer_stdout => 1	Do not return STDOUT in a buffer
#	nobuffer_stderr => 1	Do not return STDERR in a buffer
1598
#	pipe_array => \@array	Pipe array to program
Nigel Kukard's avatar
Nigel Kukard committed
1599 1600 1601
#	stderr_func => coderef	Function to use to write to stderr
#	stdout_func => coderef	Function to use to write to stdout
# 	return_fds => 1			Return array with STDIN, STDOUT, STDERR FD's
Nigel Kukard's avatar
Nigel Kukard committed
1602 1603
sub runCommand
{
Nigel Kukard's avatar
Nigel Kukard committed
1604
	my (@args) = @_;
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614


	# Check if we have options specified
	my $options;
	if (ref($args[0]) eq "HASH") {
		$options = shift(@args);
	} elsif (ref($args[-1]) eq "HASH") {
		$options = pop(@args);
	}

1615 1616 1617 1618
	# Use full path as first item
	$args[0] = checkPATH($args[0]);

	# Spawn child
Nigel Kukard's avatar
Nigel Kukard committed
1619
	my ($pid,$CSTDIN,$CSTDOUT,$CSTDERR);
1620
	eval {
Nigel Kukard's avatar
Nigel Kukard committed
1621
		$pid = fork3(\$CSTDIN,\$CSTDOUT,\$CSTDERR,@args);
1622 1623 1624 1625
	};
	if ($@) {
		return (-1,"",$@);
	}
1626 1627

	# Save our child PID
1628 1629 1630 1631
	$globalChildren{$pid} = { };
	if (defined($options->{'unkillable'}) && $options->{'unkillable'}) {
		$globalChildren{$pid}->{'unkillable'} = 1;
	}
1632 1633 1634 1635 1636 1637 1638 1639 1640

	# Set non-blocking
	$CSTDIN->blocking(0);
	$CSTDOUT->blocking(0);
	$CSTDERR->blocking(0);

	# Autoflush to stdin
	$CSTDIN->autoflush(1);

Nigel Kukard's avatar
Nigel Kukard committed
1641 1642 1643 1644 1645 1646
	# Check if all we're doing is returning the FDs
	if (defined($options->{'return_fds'})) {
		# Everything is now the calling processes problem
		return ($CSTDIN,$CSTDOUT,$CSTDERR);
	}

1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
	# Create our select lists
	my $selectREAD = IO::Select->new();
	$selectREAD->add($CSTDOUT,$CSTDERR);
	my $selectWRITE = IO::Select->new();
	if (defined($options->{'pipe_array'})) {
		$selectWRITE->add($CSTDIN);
	}
	my $selectEXCEPT = IO::Select->new();
	$selectEXCEPT->add($CSTDOUT,$CSTDERR,$CSTDIN);

	# Initialize buffers
	my $stdInFD = fileno($CSTDIN);
	my $stdOutFD = fileno($CSTDOUT);
	my $stdErrFD = fileno($CSTDERR);
	my %buffers = (
		$stdInFD => "",
		$stdOutFD => "",
		$stdErrFD => ""
	);
1666

1667 1668 1669 1670 1671 1672 1673 1674
	# Loop while we not exiting
	my $exit = 0;
	while (!$exit) {
		my ($readFDs,$writeFDs,$exceptionFDs) = IO::Select::select($selectREAD,$selectWRITE,$selectEXCEPT);
		if (!defined($readFDs)) {
			$exit = 1;
			last;
		}
1675

1676 1677 1678
		# Loop with handles available for reading
		foreach my $handle (@{$readFDs}) {
			my $handleFD = fileno($handle);
1679

1680
			READ_LOOP: {  # Wow ... perl really sucks for using last; in a do { } while ();
1681 1682 1683
				my $nread;

				# Loop while there is data being read
1684 1685 1686 1687 1688 1689
				do {
					$nread = sysread($handle,my $data,BUFFER_SIZE);
					# We need to try again just now
					if (!defined($nread) && $! == EAGAIN) {
						$nread = 0;
						last;
1690
					}
1691 1692 1693 1694 1695
					# Pipe closed?
					if (!defined($nread) || !$nread) {
						$selectREAD->remove($handle);
						$selectEXCEPT->remove($handle);
						last;
1696
					}
1697 1698 1699
					# Check if we need to output stdout
					if ($handleFD == $stdOutFD) {
						if (defined($options->{'write_stdout'})) {
Nigel Kukard's avatar
Nigel Kukard committed
1700 1701 1702 1703 1704 1705
							# Check if we have a function to use
							if (defined($options->{'stdout_func'})) {
								$options->{'stdout_func'}->($data);
							} else {
								print STDOUT $data;
							}
1706 1707
						}
						if (defined($options->{'write_stdout_to_stderr'})) {
Nigel Kukard's avatar
Nigel Kukard committed
1708 1709 1710 1711 1712 1713
							# Check if we have a function to use
							if (defined($options->{'stderr_func'})) {
								$options->{'stderr_func'}->($data);
							} else {
								print STDERR $data;
							}
1714 1715 1716 1717 1718
						}
						# Wipe buffers if we have to
						if (!defined($options->{'nobuffer_stdout'})) {
							$buffers{$handleFD} .= $data;
						}
1719
					}
1720 1721 1722
					# Check if we need to output stderr
					if ($handleFD == $stdErrFD) {
						if (defined($options->{'write_stderr'})) {
Nigel Kukard's avatar
Nigel Kukard committed
1723 1724 1725 1726 1727 1728
							# Check if we have a function to use
							if (defined($options->{'stderr_func'})) {
								$options->{'stderr_func'}->($data);
							} else {
								print STDERR $data;
							}
1729 1730 1731 1732 1733
						}
						# Wipe buffers if we have to
						if (!defined($options->{'nobuffer_stderr'})) {
							$buffers{$handleFD} .= $data;
						}
1734
					}
1735 1736 1737 1738

				} while ($nread == BUFFER_SIZE);

			} # READ_LOOP
Nigel Kukard's avatar
Nigel Kukard committed
1739

1740
		}
1741 1742 1743 1744

		# Loop with handles available for writing
		foreach my $handle (@{$writeFDs}) {
			my $handleFD = fileno($handle);
1745

1746
			WRITE_LOOP: {  # Wow ... perl really sucks for using last; in a do { } while ();
1747 1748 1749
				my $nwritten; my $nwrite;

				# Loop writing out until we don't write out our full buffer, or we hit a problem or end of the buffer data
1750 1751
				do {
					my $nleft = length($buffers{$handleFD}) // 0;
1752

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
					# If we don't have anything left, try get some more data
					if (!$nleft && defined($options->{'pipe_array'})) {
						$buffers{$handleFD} = shift(@{$options->{'pipe_array'}});
					}
					# Calculate how much is left & check if the data has run out, if it has remove & close
					if (!($nleft = length($buffers{$handleFD}))) {
						$selectWRITE->remove($handle);
						$selectEXCEPT->remove($handle);
						close($handle);
						last;
					}
Nigel Kukard's avatar
Nigel Kukard committed
1764

1765 1766 1767 1768
					# Make sure we don't exceed the maximum buffer size
					if (($nwrite = $nleft) > BUFFER_SIZE) {
						$nwrite = BUFFER_SIZE;
					}
1769

1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
					# Write buffer
					if (!defined($nwritten = syswrite($handle,$buffers{$handleFD},$nwrite))) {
						# Pipe closed?
						$selectWRITE->remove($handle);
						$selectEXCEPT->remove($handle);
						last;
					}

					# Chop data off buffer
					$buffers{$handleFD} = substr($buffers{$handleFD},$nwritten);

				# Loop while we're writing out the full buffer
				} while ($nwritten == $nwrite);
1783

1784
			} # WRITE_LOOP
1785

1786 1787
		}

Nigel Kukard's avatar
Nigel Kukard committed
1788
		# Loop with exception handles
1789 1790
		foreach my $handle (@{$exceptionFDs}) {
			my $handleFD = fileno($handle);
1791

1792 1793 1794
			$selectWRITE->remove($handle);
			$selectREAD->remove($handle);
			$selectEXCEPT->remove($handle);
Nigel Kukard's avatar
Nigel Kukard committed
1795
			close($handle);
1796
		}
1797

1798 1799 1800 1801 1802
		# If we have no more handles to read from, including STDERR, exit
		if (!$selectREAD->handles()) {
			$exit = 1;
		}
	}
1803

1804 1805
	# Check if child has exited
	my $ret;
1806 1807 1808 1809
	if (defined($globalChildren{$pid}) && defined($globalChildren{$pid}->{'res'})) {
		# Grab return code from $globalChildren populated by our reaper
		$ret = $globalChildren{$pid}->{'res'};
		delete($globalChildren{$pid});
1810
	} else {
1811
		# Wait on this ourselves
1812
		my $res = waitpid($pid,0);
1813 1814
		$ret = $?;
		# Cleanup here too
1815
		delete($globalChildren{$pid});
1816
	}
1817 1818 1819

	# Return the buffers we read
	return ($ret,$buffers{$stdOutFD},$buffers{$stdErrFD});
1820 1821 1822 1823
}



Nigel Kukard's avatar
Nigel Kukard committed
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
# Implementation of open3
sub fork3
{
	my ($STDINref,$STDOUTref,$STDERRref,@args) = @_;


	# Check if we have options specified
	my $options;
	if (ref($args[0]) eq "HASH") {
		$options = shift(@args);
	} elsif (ref($args[-1]) eq "HASH") {
		$options = pop(@args);
	}

	# Open our pipes
1839 1840 1841
	my $pipeSTDIN = IPC::Pipe->new();
	my $pipeSTDOUT = IPC::Pipe->new();
	my $pipeSTDERR = IPC::Pipe->new();
Nigel Kukard's avatar
Nigel Kukard committed
1842 1843

	# Try fork
Nigel Kukard's avatar
Nigel Kukard committed
1844
	if (defined(my $pid = fork())) {
Nigel Kukard's avatar
Nigel Kukard committed
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
		# We're the parent
		if ($pid) {
			# Set handles
			$$STDINref = $pipeSTDIN->writer();
			$$STDOUTref = $pipeSTDOUT->reader();
			$$STDERRref = $pipeSTDERR->reader();

			return $pid;
		}
	} else {
		die "Failed to fork: $!";
	}

	# Set handles
	my $STDIN = $pipeSTDIN->reader();
	my $STDOUT = $pipeSTDOUT->writer();
	my $STDERR = $pipeSTDERR->writer();

	# Re-open system handles
1864 1865 1866
	open(STDIN,"<&=",$STDIN->fileno());
	open(STDOUT,">&=",$STDOUT->fileno());
	open(STDERR,">&=",$STDERR->fileno());
Nigel Kukard's avatar
Nigel Kukard committed
1867 1868 1869 1870

	# Check if we have a sub to call
	if (defined(my $code = $options->{'child_on_fork'})) {
		# Execute the code
1871
		@args = $code->(@args);
Nigel Kukard's avatar
Nigel Kukard committed
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
	}

	# Try exec
	exec { $args[0] } @args;

	die "Failed to exec: $!";
}



1882 1883 1884 1885
# Grab our logical volumes
sub lvmGetLogicalVolumes
{
	my @dataColumns = qw(
Nigel Kukard's avatar
Nigel Kukard committed
1886
		lv_name vg_name
1887 1888 1889 1890
		uuid
		lv_path
		origin
		lv_size
1891 1892
		vg_size
		vg_free
1893
		lv_attr
1894
		snap_percent
1895 1896 1897 1898
	);

	# Grab logical volumes
	my ($res,@data) = runCommand(
1899
		"/sbin/lvs",
1900 1901 1902 1903 1904 1905
			"--separator", "#",
			"--noheadings",
			"--units", "m",
			"--unbuffered",
			"--nosuffix",
			"--options",
1906 1907
			join(',',@dataColumns),
		{'unkillable'=>1}
1908 1909 1910 1911 1912
	);
	# Check result, it should be 0
	if ($res) {
		# If not, output the error
		printLog(LOG_ERROR,"Failed to run 'lvs': %s",$data[1]);
Nigel Kukard's avatar
Nigel Kukard committed
1913
		return;
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
	}

	my %logicalVolumes = ( );
	foreach my $line (split(/\n/,$data[0])) {
		my %logicalVolume;
		# Split off columns
		my @data = split('#',$line);
		# Pull in data
		for (my $i = 0; $i < @dataColumns; $i++) {
			$logicalVolume{$dataColumns[$i]} = $data[$i];
		}
		# Cleanup whitespaces on first column
		$logicalVolume{$dataColumns[0]} =~ s/\s//g;
Nigel Kukard's avatar
Nigel Kukard committed
1927 1928 1929 1930
		# Logical volume name
		my $lvName = sprintf("%s/%s",$logicalVolume{'vg_name'},$logicalVolume{'lv_name'});
		# Not all versions of lvs support this, so lets create it ourselves
		$logicalVolume{'lv_full_name'} = $lvName;
1931 1932 1933 1934 1935 1936
		# If we have attributes, then split off the bits
		if (defined($logicalVolume{'lv_attr'})) {
			# Decipher the attrs
			$logicalVolume{'lv_attr_bits'} = [ split('',$logicalVolume{'lv_attr'}) ];
		}
		# Add to our hash
Nigel Kukard's avatar
Nigel Kukard committed
1937
		$logicalVolumes{$lvName} = \%logicalVolume;
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
	}

	return \%logicalVolumes;
}



# Snapshot LVM volume
sub lvmCreateSnapshot
{
	my ($snapshotSourceVG,$snapshotSourceLV,$snapshotSize,$snapshotDestLV) = @_;


Nigel Kukard's avatar
Nigel Kukard committed
1951
	# Grab source and destination
1952 1953 1954
	my $snapshotSource = sprintf('%s/%s',$snapshotSourceVG,$snapshotSourceLV);
	my $snapshotDest = sprintf('%s/%s',$snapshotSourceVG,$snapshotDestLV);

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979

	# Lock volume
	my $runDir;
	if (-d "/run") {
		$runDir = "/run";
	} else {
		$runDir = "/var/run";
	}
	# Lockfile paths
	my $lockDir = sprintf("%s/%s",$runDir,"backstep-traceback");
	(my $lockFileName = $snapshotSource) =~ s,/,--,;
	my $lockF