dbackup 33.3 KB
Newer Older
Nigel Kukard's avatar
Nigel Kukard committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/perl -w
# Copyright (c) 2010-2012, AllWorldIT
# 
# 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/>.
#
#
# Author: Nigel Kukard <nkukard@lbsd.net>


# TODO:
# - USE incremental backups!!!! fucking awesome


use strict;
use Compress::Zlib;
27
use Config::IniFiles;
Nigel Kukard's avatar
Nigel Kukard committed
28
29
30
31
32
33
34
35
36
37
38
39
use Cwd;
use Fcntl qw (:mode);
use File::Find;
use File::Path qw( rmtree mkpath );
use File::Spec;
use Getopt::Long;
use POSIX qw (strftime);
use Data::Dumper;
use MIME::Base64;



Nigel Kukard's avatar
Nigel Kukard committed
40
my $VERSION = "0.0.5";
Nigel Kukard's avatar
Nigel Kukard committed
41
42
43
44
# System dirs we don't care about
my @defaultSystemExcl = ("/dev","/run","/proc","/sys","/tmp","/var/tmp");
# These should be backed up separately
my @defaultDataExcl = ("/var/lib/mysql","/var/lib/pgsql");
45
46
47
# Main config
my %config;

Nigel Kukard's avatar
Nigel Kukard committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69


# Backup constants
use constant {
	ST_FILE_CHANGED 	=> 1,
	ST_DIR_NEW	=> 2,
	ST_DIR_SYS	=> 4,
	ST_DIR_CHANGED	=> 8,
	ST_FILE_ATTR_CHANGED	=> 16,
	ST_FILE_NEW	=> 32,
};



print(STDERR "DBackup v$VERSION, Copyright (c) 2010-2012, AllWorldIT\n\n");


# Grab options
my %optctl = ();
GetOptions(\%optctl,
	"help",

70
71
	"config=s",

Nigel Kukard's avatar
Nigel Kukard committed
72
73
74
75
76
77
78
79
	"backup",
	"compress:s",
	"exclude-system",
	"exclude-system-path=s@",
	"exclude-system-dir=s@",

	"exclude-data",
	"exclude-data-dir=s@",
80
81
	
	"exclude-files=s@",
Nigel Kukard's avatar
Nigel Kukard committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

	"restore",
	"tar-keep-newer",
	"tar-keep-old-files",
);

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

# 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;
}

# Make sure we only have 2 additional args
if (@ARGV > 2 || @ARGV < 2) {
		print(STDERR "ERROR: Invalid number of arguments\n\n");
		displayHelp();
		exit 1;
}

# Check both dirs exist...
if (! -d $ARGV[0]) {
	print(STDERR "ERROR: Source directory '".$ARGV[0]."' does not exist!\n\n");
	exit 1;
}
if (! -d $ARGV[1]) {
	print(STDERR "ERROR: Destination directory '".$ARGV[1]."' does not exist!\n\n");
	exit 1;
}

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
# Check config file exists
if (defined($optctl{'config'})) {
	if (! -f $optctl{'config'}) {
		print(STDERR "ERROR: Configuration file '".$optctl{'config'}."' NOT found!\n");
		exit 1;
	}

	# Use config file, ignore case
	tie my %inifile, 'Config::IniFiles', (
			-file => $optctl{'config'},
			-nocase => 1
	) or die "Failed to open config file '".$optctl{'config'}."': ".join("\n",@Config::IniFiles::errors);

	# Check if we actually have something...
	if (defined($inifile{'backup'})) {
		# Loop with config items
		foreach my $item (keys %{$inifile{'backup'}}) {
			$config{$item} = $inifile{'backup'}{$item};
		}
	}
}

# Setup config defaults...
if (!defined($config{'compress'})) {
	# Choose default compression method
	if (-x "/bin/xz" || -x "/usr/bin/xz") {
		$config{'compress'} = "xz";
	} else {
		$config{'compress'} = "bzip2";
	}
}

if (!defined($config{'exclude-system'})) {
	$config{'exclude-system'} = 0;
}

if (!defined($config{'exclude-system-path'})) {
	# Quick hack to see if we have a cmdline option
	if (!defined($optctl{'exclude-system-path'})) {
		$config{'exclude-system-path'} = ["/"];
	} else {
		$config{'exclude-system-path'} = [];
	}
} else {
	$config{'exclude-system-path'} = toArray($config{'exclude-system-path'});
}

if (!defined($config{'exclude-system-dir'})) {
	$config{'exclude-system-dir'} = [];
} else {
	$config{'exclude-system-dir'} = toArray($config{'exclude-system-dir'});
}

if (!defined($config{'exclude-data-dir'})) {
	$config{'exclude-data-dir'} = [];
} else {
	$config{'exclude-data-dir'} = toArray($config{'exclude-data-dir'});
}

if (!defined($config{'exclude-files'})) {
	$config{'exclude-files'} = [];
} else {
	$config{'exclude-files'} = toArray($config{'exclude-data'});
}


Nigel Kukard's avatar
Nigel Kukard committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# Check compression
if (defined($optctl{'compress'})) {
	# Why use --compress with --restore?
	if (defined($optctl{'restore'})) {
		print(STDERR "WARNING: The use of --compress with --restore does not make sense\n");
	}

	# Make sure its valid
	if (
				$optctl{'compress'} ne "xz" &&
				$optctl{'compress'} ne "bzip2" &&
				$optctl{'compress'} ne "gzip" &&
				$optctl{'compress'} ne "none"
	) {	
		print(STDERR "ERROR: Compression is invalid, valid values are: xz bzip2 gzip none\n\n");
		displayHelp();
		exit 1;
	}
202
	$config{'compress'} = $optctl{'compress'};
Nigel Kukard's avatar
Nigel Kukard committed
203
204
}

205
206
207
208
209
210
211

# Process our exclusion lists...
if (defined($optctl{'exclude-system'})) {
	$config{'exclude-system'} = 1;
}
if (defined($optctl{'exclude-system-path'})) {
	push(@{$config{'exclude-system-path'}},@{$optctl{'exclude-system-path'}});
Nigel Kukard's avatar
Nigel Kukard committed
212
}
213
214
if (defined($optctl{'exclude-system-dir'})) {
	push(@{$config{'exclude-system-dir'}},@{$optctl{'exclude-system-dir'}});
Nigel Kukard's avatar
Nigel Kukard committed
215
216
}
# Do similar for data dirs
217
218
219
220
221
222
if (defined($optctl{'exclude-data-dir'})) {
	push(@{$config{'exclude-data-dir'}},@{$optctl{'exclude-data-dir'}});
}
# And file filter
if (defined($optctl{'exclude-files'})) {
	push(@{$config{'exclude-files'}},@{$optctl{'exclude-files'}});
Nigel Kukard's avatar
Nigel Kukard committed
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
}

# Sanitize the source and dest
my $sourceDir = File::Spec->rel2abs($ARGV[0]);
my $destDir = File::Spec->rel2abs($ARGV[1]);


# Backup function
sub backup
{
	our ($source,$dest) = @_;


	# State infor for current dir
	our %doBackup;
	our %srcFileList;
	our %srcDirList;
	# Original .state file read in during backup
	our %origFileList;
	our %origDirList;
	our %origPathAttribs;
	# New attributes
	our %newPathAttribs;


	# Preprocess dir
	sub backup_preprocess {
		my @list = @_;

		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Check if this dir should be backed up or not....
		if ( -f "$source/$path/.nodbackup" ) {
			printLog("S: Path '[$source]/($path)' EXCLUDED from backup with .nodbackup\n");
			return ();
		}
		# Exclude trash folders
		if ( "$source/$path" =~ /(\.Trash-[0-9]{4})$/) {
			printLog("S: Path '[$source]/($path)' EXCLUDED from backup, Linux trash folder\n");
			return ();
		}

		# Make sure even if we processing empty dirs that we actually record it
		if (!defined($srcFileList{$path})) {
			# Just set to empty hash ref
			$srcFileList{$path} = {};
		}

		# Exclude system directories
273
		if ($config{'exclude-system'}) {
Nigel Kukard's avatar
Nigel Kukard committed
274
			# Loop through system dirs
275
			foreach my $sysdir (@{$config{'exclude-system-path'}}) {
Nigel Kukard's avatar
Nigel Kukard committed
276
				# Loop with system paths
277
				foreach my $excl (@defaultSystemExcl,@{$config{'exclude-system-dir'}}) {
Nigel Kukard's avatar
Nigel Kukard committed
278
					# Sanitize path
279
					my $testPath = File::Spec->rel2abs("$sysdir/$excl");
Nigel Kukard's avatar
Nigel Kukard committed
280
					# Check...
281
					if ("/$path" eq $testPath) {
Nigel Kukard's avatar
Nigel Kukard committed
282
283
284
285
286
287
						printLog("S: Path '[$source]/($path)' is a system directory, ignoring files\n");
						$doBackup{$path} |= ST_DIR_SYS;
						return ();
					}
				}
				# Check if we excluding data dirs
288
				if (defined($config{'exclude-data'})) {
Nigel Kukard's avatar
Nigel Kukard committed
289
					# Loop with data dirs
290
					foreach my $excl (@defaultDataExcl,@{$config{'exclude-data-dir'}}) {
Nigel Kukard's avatar
Nigel Kukard committed
291
						# Sanitize path
292
						my $testPath = File::Spec->rel2abs("$sysdir/$excl");
Nigel Kukard's avatar
Nigel Kukard committed
293
						# Check...
294
						if ("/$path" eq $testPath) {
Nigel Kukard's avatar
Nigel Kukard committed
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
321
322
323
324
325
326
327
							printLog("S: Path '[$source]/($path)' is a data directory, ignoring files\n");
							$doBackup{$path} |= ST_DIR_SYS;
							return ();
						}
					}
				}
			}
		}

		# Check if this dir exists on the backup, if not we need to back it up obviously...
		if ( ! -d "$dest/$path") {
#			printLog("B: Path '[$dest]/($path)' does not exist\n");
			$doBackup{$path} |= ST_DIR_NEW;
		# This can probably only be because a backup was continued
		} elsif ( ! -f "$dest/$path/.dbackup-state" ) {
			# First backup will never have the main dir .dbackup-state file existing
			if ($path ne "") {
				print(STDERR "WARNING: State file '$dest/$path/.dbackup-state' does not exist\n");
			}
#			printLog("B: Path '[$dest]/($path)' needs to be backed up\n");
			$doBackup{$path} |= ST_DIR_NEW;
		}

		# Cannot read in for new dirs can we...
		if (($doBackup{$path} & ST_DIR_NEW) != ST_DIR_NEW) {
			# Load state file
			loadStateFile("$dest/$path/.dbackup-state",$path,\%origFileList,\%origDirList,\%origPathAttribs);

			# Check we have at least the version attribute
			if (!defined($origPathAttribs{$path}) || !defined($origPathAttribs{$path}->{'dbackup.version'})) {
				print(STDERR "ERROR: No dbackup version information found in '$source/$path/.dbackup-state', IGNORING\n");
				delete($origDirList{$path});
				delete($origFileList{$path});
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
			}
		}

		# Apply filter...
		if ((@{$config{'exclude-files'}}) > 0) {
			my @newList;
			foreach my $item (@list) {
				my $match = 0;
				# Apply only to files
				if ( -f "$source/$path/$item") {
					# Loop with exclude filters
					foreach my $filter (@{$config{'exclude-files'}}) {
						# Check for match
						if ($item =~ $filter) {
#							printLog("S: Path '[$source]/($path)/$item' matches file exclude filter, ignoring\n");
							# XXX: NK - If this ws backed up before and now not, dir has changed?
							$match = 1;
							last;
						}
					}
				}
				# If not matched, add to new list
				if (!$match) {
					push(@newList,$item);
				}
Nigel Kukard's avatar
Nigel Kukard committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
			}
		}

		return @list;
	}

	# Process files
	sub backup_process {
		my $name = $File::Find::name;
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Store current filename
		my $item = $_;

		# We use lstat so we don't follow symlinks that don't exist
		my @stat = lstat($name);
		# Split it up
		my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,
				$ctime,$blksize,$blocks) = @stat;

		# Process directory
		if (S_ISDIR($mode)) {
			# Skip over main dir
			if ($item eq ".") {
				return;
			}

			# Make sure sub dirs have a santized name
			my $ppath = ($path ne "") ? "$path/$item" : $item;

			# Set default flags to nothing...
			$doBackup{$ppath} = 0;

			# Ok, lets see whats going on with the dir
			if (!defined($origDirList{$path}->{$item})) {
#				printLog("S: Directory '[$source]/($path)/$item' is new\n");
				$doBackup{$path} |= ST_DIR_CHANGED;

			# Check if mtime matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'mtime'}) ||
					$origDirList{$path}->{$item}->{'mtime'} ne $mtime
			) {
				printLog("S: Directory '[$source]/($path)/$item' was modified\n"); 
				$doBackup{$path} |= ST_DIR_CHANGED;
			# Check if uid matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'uid'}) ||
					$origDirList{$path}->{$item}->{'uid'} ne $uid
			) {
				printLog("S: Directory '[$source]/($path)/$item' UID was changed\n"); 
				$doBackup{$path} |= ST_DIR_CHANGED;
			# Check if gid matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'gid'}) ||
					$origDirList{$path}->{$item}->{'gid'} ne $gid
			) {
				printLog("S: Directory '[$source]/($path)/$item' GID was changed\n"); 
				$doBackup{$path} |= ST_DIR_CHANGED;
			# Check if mode matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'mode'}) ||
					$origDirList{$path}->{$item}->{'mode'} ne $mode
			) {
				printLog("S: Directory '[$source]/($path)/$item' MODE was changed\n"); 
				$doBackup{$path} |= ST_DIR_CHANGED;
			}

			# Record details...	
			$srcDirList{$path}->{$item}->{'size'} = $size;
			$srcDirList{$path}->{$item}->{'ctime'} = $ctime;
			$srcDirList{$path}->{$item}->{'atime'} = $atime;
			$srcDirList{$path}->{$item}->{'mtime'} = $mtime;
			$srcDirList{$path}->{$item}->{'uid'} = $uid;
			$srcDirList{$path}->{$item}->{'gid'} = $gid;
			$srcDirList{$path}->{$item}->{'mode'} = $mode;

			return;
		}

		# Initialize file state
		my $state = 0;

		# Check if file does not exists on backup
		if (!defined($origFileList{$path}->{$item})) {
			if (($doBackup{$path} & ST_DIR_NEW) != ST_DIR_NEW) {
				printLog("S: File '[$source]/($path)/$item' is new\n");
			}
			$state |= ST_FILE_NEW;

		# Check if size matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'size'}) ||
				$origFileList{$path}->{$item}->{'size'} ne $size
		) {
			printLog("S: File '[$source]/($path)/$item' has different size\n"); 
			$state |= ST_FILE_CHANGED;

		#
		# NK: Does not like chmod changes to files???
		#
		# Check if ctime matches
#		} elsif (
#				!defined($origFileList{$path}->{$item}->{'ctime'}) ||
#				$origFileList{$path}->{$item}->{'ctime'} ne $ctime
#		) {
#			printLog("S: File '[$source]/($path)/$item' was recreated\n"); 
#			$state |= ST_FILE_CHANGED;

		# Check if mtime matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'mtime'}) ||
				$origFileList{$path}->{$item}->{'mtime'} ne $mtime
		) {
			printLog("S: File '[$source]/($path)/$item' was modified\n"); 
			$state |= ST_FILE_CHANGED;

		# Check if uid matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'uid'}) ||
				$origFileList{$path}->{$item}->{'uid'} ne $uid
		) {
			printLog("S: File '[$source]/($path)/$item' UID was changed\n"); 
			$state |= ST_FILE_ATTR_CHANGED

		# Check if gid matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'gid'}) ||
				$origFileList{$path}->{$item}->{'gid'} ne $gid
		) {
			printLog("S: File '[$source]/($path)/$item' GID was changed\n"); 
			$state |= ST_FILE_ATTR_CHANGED;

		# Check if mode matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'mode'}) ||
				$origFileList{$path}->{$item}->{'mode'} ne $mode
		) {
			printLog("S: File '[$source]/($path)/$item' MODE was changed\n"); 
			$state |= ST_FILE_ATTR_CHANGED;
		}

		# Update state of path, this is used below, the $state is used to track WHAT changed
		if ($state) {
			$doBackup{$path} |= ST_FILE_CHANGED;
		}

		# Record details...	
		$srcFileList{$path}->{$item}->{'size'} = $size;
		$srcFileList{$path}->{$item}->{'ctime'} = $ctime;
		$srcFileList{$path}->{$item}->{'atime'} = $atime;
		$srcFileList{$path}->{$item}->{'mtime'} = $mtime;
		$srcFileList{$path}->{$item}->{'uid'} = $uid;
		$srcFileList{$path}->{$item}->{'gid'} = $gid;
		$srcFileList{$path}->{$item}->{'mode'} = $mode;
		$srcFileList{$path}->{$item}->{'_state'} = $state;
	}


	# Time to do stuff
	sub backup_postprocess {
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;
		# Get current lists
		my $curDirList = $srcDirList{$path};
		my $curFileList = $srcFileList{$path};

		# Compare the two file lists, we know what was added, lets see if anything was removed
		foreach my $fname (keys %{$origFileList{$path}}) {
			if (!defined($srcFileList{$path}->{$fname})) {
				printLog("File '[$source]/($path)/$fname' removed\n");
				$doBackup{$path} |= ST_FILE_CHANGED;
			}
		}

		# Create backup dir
		if (($doBackup{$path} & ST_DIR_NEW) == ST_DIR_NEW && ! -d "$dest/$path") {
			mkpath("$dest/$path");
		}

		# Check if we need to backup this dir
		if (($doBackup{$path} & ST_FILE_CHANGED) == ST_FILE_CHANGED) {
			printLog("B: Path '[$source]/$path' backing up\n");

			# If we not backing up a system dir, we create a manifest and backup the files
			if (($doBackup{$path} & ST_DIR_SYS) != ST_DIR_SYS) {
				# Did file contents change?
				my $changedFiles = 0;
				my $changedAttrs = 0;
				my @newFiles = ();
				my @manifestList;

				# Take a look quick...
				foreach my $item (sort keys %{$curFileList}) {
					# Lets see whats happened...
					if (($curFileList->{$item}->{'_state'} & ST_FILE_NEW) == ST_FILE_NEW) {
						push(@newFiles,$item);
					}
					if (($curFileList->{$item}->{'_state'} & ST_FILE_CHANGED) == ST_FILE_CHANGED) {
						$changedFiles = 1;
					}
					if (($curFileList->{$item}->{'_state'} & ST_FILE_ATTR_CHANGED) == ST_FILE_ATTR_CHANGED) {
						$changedAttrs = 1;
					}
				}

				# If we don't have a sequence, this is a new backup?
				if (!defined($newPathAttribs{$path}->{'sequence'} = $origPathAttribs{$path}->{'sequence'})) {
					$newPathAttribs{$path}->{'sequence'} = 0;
					@manifestList = keys %{$curFileList};
				} else {
					# If this is new files, then just inc the counter
					if (@newFiles > 0 && !$changedFiles && !$changedAttrs) {
						$newPathAttribs{$path}->{'sequence'}++;
						@manifestList = @newFiles;
					# If files changed we blow everything away
					} else {
						$newPathAttribs{$path}->{'sequence'} = 0;
						# Remove old files	
						removeBackups(
								"$dest/$path",
								$origPathAttribs{$path}->{'format'},
								$origPathAttribs{$path}->{'compression'},
								$origPathAttribs{$path}->{'sequence'}
						);
						@manifestList = keys %{$curFileList};
					}
				}


				# Get current sequence
				my $seq = $newPathAttribs{$path}->{'sequence'};

				# File list to backup
				open(MANIFEST,"> $dest/$path/dbackup$seq.manifest")
						or die "Failed to open '$dest/$path/dbackup$seq.manifest': $!";
				foreach my $item (@manifestList) {
					# If this is not the top dir, use /
					if ($path ne "") {
						print(MANIFEST "$path/$item\0");
					# If it is, don't use /
					} else {
						print(MANIFEST "$item\0");
					}
				}
				close(MANIFEST);

				# Setup tar args
				my @tarArgs = ();
				my $tarExt;
604
				if ($config{'compress'} eq "xz") {
Nigel Kukard's avatar
Nigel Kukard committed
605
606
					push(@tarArgs,"--xz");
					$tarExt = ".xz";
607
				} elsif ($config{'compress'} eq "bzip2") {
Nigel Kukard's avatar
Nigel Kukard committed
608
609
					push(@tarArgs,"--bzip2");
					$tarExt = ".bz2";
610
				} elsif ($config{'compress'} eq "gzip") {
Nigel Kukard's avatar
Nigel Kukard committed
611
612
					push(@tarArgs,"--gzip");
					$tarExt = ".gz";
613
				} elsif ($config{'compress'} eq "none") {
Nigel Kukard's avatar
Nigel Kukard committed
614
615
616
617
618
					$tarExt = "";
				}

				# Save format and compression
				$newPathAttribs{$path}->{'format'} = "tar";
619
				$newPathAttribs{$path}->{'compression'} = $config{'compress'};
Nigel Kukard's avatar
Nigel Kukard committed
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747

				# Change dir and start backup
				system(
					"tar", 
					"--create",
					"--verbose",
					# Output file
					"--file", "$dest/$path/dbackup$seq.tar$tarExt",
					# cd into here first...
					"--directory", "$source",
					# Read file list from here
					"--null",
					"--files-from", "$dest/$path/dbackup$seq.manifest",
					"--no-unquote",
					# Do not recurse
					"--no-recursion",
					# Output to this file
					"--index-file", "$dest/$path/dbackup$seq.index",
					# Incremental options
#					"--listed-incremental", "$dest/$path/dbackup.snar",
#					"--no-check-device",
					@tarArgs
				);
				if ($? == -1) {
					printLog("   - Failed to execute: $!\n");
					exit 1;
				} elsif ($? & 127) {
					printLog("  - Child died with signal %d\n",($? & 127));
					exit 1;
				} else {
					my $retcode = $? >> 8;
					# If tar died, lets die too
					if ($retcode == 2) {
						print(STDERR "ERROR: tar died with error code $retcode\n");
						exit 1;
					}
				}
			# if (($doBackup{$path} & ST_DIR_SYS) != ST_DIR_SYS) {
			} else {
					# Remove old files	
					removeBackups(
							"$dest/$path",
							$origPathAttribs{$path}->{'format'},
							$origPathAttribs{$path}->{'compression'},
							$origPathAttribs{$path}->{'sequence'}
					);
			}
		} # if (($doBackup{$path} & ST_FILE_CHANGED) == ST_FILE_CHANGED) {


		# Check if we need to record directory changes...
		if (
					($doBackup{$path} & ST_FILE_CHANGED) == ST_FILE_CHANGED ||
					($doBackup{$path} & ST_DIR_CHANGED) == ST_DIR_CHANGED ||
					($doBackup{$path} & ST_DIR_NEW) == ST_DIR_NEW
		) {
			# If we have a revision, bump it
			if (defined($newPathAttribs{$path}->{'revision'} = $origPathAttribs{$path}->{'revision'})) {
				$newPathAttribs{$path}->{'revision'} = $origPathAttribs{$path}->{'revision'} + 1;
			} else {
				$newPathAttribs{$path}->{'revision'} = 0;
			}

#			printLog("B: Writing state '[$source]/$path' - revision ".$newPathAttribs{$path}->{'revision'}."\n");

			# Write out state, we do this AFTER we have backed up, so if we stopped, we can just  continue
			my $gz = gzopen("$dest/$path/.dbackup-state","wb")
					or die "Failed to open '$dest/$path/.dbackup-state': $!";
			# Write out attributes
			$gz->gzwrite(join("\0",
					"a",
					"dbackup.version",
					$VERSION
				)."\n"
			);
			# Loop with attributes
			foreach my $item (keys %{$newPathAttribs{$path}}) {
				$gz->gzwrite(join("\0",
						"a",
						$item,
						$newPathAttribs{$path}->{$item}	
					)."\n"
				);
			}
			# Loop with directory list
			foreach my $item (sort keys %{$curDirList}) {
				my $ename = encode_base64($item);
				$ename =~ s/\n//g;
				# Save state of source files
				$gz->gzwrite(join("\0",
						"d",
						$ename,
						$curDirList->{$item}->{'ctime'},
						$curDirList->{$item}->{'atime'},
						$curDirList->{$item}->{'mtime'},
						$curDirList->{$item}->{'uid'},
						$curDirList->{$item}->{'gid'},
						$curDirList->{$item}->{'mode'}
					)."\n"
				);
			}
			# Loop with file list
			foreach my $item (sort keys %{$curFileList}) {
				my $ename = encode_base64($item);
				$ename =~ s/\n//g;
				# Save state of source files
				$gz->gzwrite(join("\0",
						"f",
						$ename,
						$curFileList->{$item}->{'size'},
						$curFileList->{$item}->{'ctime'},
						$curFileList->{$item}->{'atime'},
						$curFileList->{$item}->{'mtime'},
						$curFileList->{$item}->{'uid'},
						$curFileList->{$item}->{'gid'},
						$curFileList->{$item}->{'mode'}
					)."\n"
				);
			}
			# Finally close
			$gz->gzclose();
		}

		# State clear
		delete($origFileList{$path});
	}

	printLog("BACKUP START: $source => $dest\n");
748
749
	printLog("Compression: ".$config{'compress'}."\n");

Nigel Kukard's avatar
Nigel Kukard committed
750
	# Check if we excluding system files
751
752
753
	if ($config{'exclude-system'}) {
		printLog("Exclude System Paths: ".join(", ",@{$config{'exclude-system-path'}})."\n");
		printLog("Exclude System Dirs: ".join(", ",@defaultSystemExcl,@{$config{'exclude-system-dir'}})."\n");
Nigel Kukard's avatar
Nigel Kukard committed
754
		# If we excluding data too...
755
756
		if ($config{'exclude-data'}) {
			printLog("Exclude Data Dirs: ".join(", ",@defaultDataExcl,@{$config{'exclude-data-dir'}})."\n");
Nigel Kukard's avatar
Nigel Kukard committed
757
758
		}
	}
759
	printLog("Exclude Files: ".join(", ",@{$config{'exclude-files'}})."\n");
Nigel Kukard's avatar
Nigel Kukard committed
760
761
762
763
764
765
766
767
768
769
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057

	# We need an entry for our main dir before we start
	$doBackup{""} = 0;

	# This basically does our backup for us...
	find (
		{ 
			preprocess => \&backup_preprocess,
			wanted => \&backup_process,
			postprocess => \&backup_postprocess
		},
		$source
	);


	printLog("Processing stale directories...\n");
	my @rmlist;
	# Total item by item
	find (
		{ 
			wanted => sub { },
			# We just need post processing ...
			postprocess => sub {
				# Strip first part of the path
				(my $path = $File::Find::dir) =~ s#^$dest/?##;
				# Does this dir exist on the backup, but not on the fileserver?
				if (!defined($srcFileList{$path})) {
					printLog("Remove path '[$dest]/$path'\n");
					push(@rmlist,"$dest/$path");
				}
			},
		},
		$dest
	);

	printLog("Removing paths...\n");
	foreach my $rmitem ( @rmlist ) {
   		rmtree($rmitem);
	}

	printLog("BACKUP END\n");
}


# Do backup
if (defined($optctl{'backup'})) {
	backup($sourceDir,$destDir);

} elsif (defined($optctl{'restore'})) {
	restore($sourceDir,$destDir);

} else {
	print(STDERR "ERROR: No command given\n\n");
	displayHelp();
	exit 1;
}


# Restore function
sub restore
{
	our ($source,$dest) = @_;

	# State infor for current dir
#	our %doBackup;
#	our %srcFileList;
#	our %srcDirList;
	our %origFileList;
	our %origDirList;
	our %origPathAttribs;


	# Preprocess dir
	sub restore_preprocess {
		my @list = @_;

		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Check if we have all our source files
		if ( ! -f "$source/$path/.dbackup-state" ) {
			printLog("S: Path '[$source]/($path)' is MISSING .dbackup-state\n");
			return @list;
		}

		# Load state file
		loadStateFile("$source/$path/.dbackup-state",$path,\%origFileList,\%origDirList,\%origPathAttribs);

		# Check we have at least the version attribute
		if (!defined($origPathAttribs{$path}) || !defined($origPathAttribs{$path}->{'dbackup.version'})) {
			print(STDERR "ERROR: No dbackup version information found in '$source/$path/.dbackup-state', IGNORING\n");
			delete($origDirList{$path});
			delete($origFileList{$path});
			return @list;
		}

		# During our check, we need to create the dir, we may not have a backup file
		# so we do it here.
		if ( ! -d "$dest/$path") {
			printLog("R: Path '[$dest]/($path)' creating directory\n");
			mkpath("$dest/$path");
		}

		# The lack of a sequence number probably means we didn't output any tar files during backup
		if (!defined($origPathAttribs{$path}->{'sequence'})) {
			return @list;
		}

		# Loop through backup sequences
		for (my $seq = 0; $seq <= $origPathAttribs{$path}->{'sequence'}; $seq++) {
			printLog("R: Path '[$dest]/$path' restoring files ".($seq+1)." of ".
					($origPathAttribs{$path}->{'sequence'}+1)."\n");

			# Args for tar
			my @tarArgs = ();

			my $tarExt;
			if ($origPathAttribs{$path}->{'compression'} eq "xz") {
				push(@tarArgs,"--xz");
				$tarExt = ".xz";
			} elsif ($origPathAttribs{$path}->{'compression'} eq "bzip2") {
				push(@tarArgs,"--bzip2");
				$tarExt = ".bz2";
			} elsif ($origPathAttribs{$path}->{'compression'} eq "gzip") {
				push(@tarArgs,"--gzip");
				$tarExt = ".gz";
			} elsif ($origPathAttribs{$path}->{'compression'} eq "none") {
				$tarExt = "";
			}

			# Check what type of backup we did
			if ( ! -f "$source/$path/dbackup$seq.tar$tarExt" ) {
				# If we have any other part of the backup, show a message
				if (
							( -f "$source/$path/dbackup$seq.index" || 
							-f "$source/$path/dbackup$seq.manifest" ||
							-f "$source/$path/dbackup$seq.snar" ) && $seq > 0
				) {
					# NK: Maybe add this to debug log?
					#printLog("S: Path '[$source]/($path)' IGNORING DUE TO NO BACKUP FILE\n");
					print(STDERR "ERROR: Backup file '$source/$path/dbackup$seq.tar$tarExt' not found\n");
				}

				return @list;
			}

			# Check we have files we need/created
			if ( ! -f "$source/$path/dbackup$seq.index" ) {
				print(STDERR "ERROR: Manifest file '$source/$path/dbackup$seq.index' not found\n");
				return @list;
			}
			if ( ! -f "$source/$path/dbackup$seq.manifest" ) {
				print(STDERR "ERROR: Manifest file '$source/$path/dbackup$seq.manifest' not found\n");
				return @list;
			}

			# Other tar options
			if (defined($optctl{'tar-keep-newer'})) {
				push(@tarArgs,"--keep-newer-files");
			}
			if (defined($optctl{'tar-keep-old-files'})) {
				push(@tarArgs,"--keep-old-files");
			}

			# Change dir and start backup
			system(
				"tar", 
				"--extract",
				# Output file
				"--file", "$source/$path/dbackup$seq.tar$tarExt",
				# cd into here first...
				"--directory", "$dest",
				# Read file list from here
				"--null",
				"--files-from", "$source/$path/dbackup$seq.manifest",
				"--no-unquote",
				# Do not recurse
				"--no-recursion",
				# Incremental options
#			"--incremental",
				@tarArgs
			);
			if ($? == -1) {
				printLog("   - Failed to execute: $!\n");
				exit 1;
			} elsif ($? & 127) {
				printLog("  - Child died with signal %d\n",($? & 127));
				exit 1;
			} else {
				my $retcode = $? >> 8;
				# If tar died, lets die too
				if ($retcode == 2) {
					print(STDERR "ERROR: tar died with error code $retcode\n");
					exit 1;
				}
			}
		}

		return @list;
	}

	# Process files
	sub restore_process {
		my $name = $File::Find::name;
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Store current filename
		my $item = $_;

#		print(STDERR "PROCESS: Path = $path, Name = $name, Item = $item)\n");
	}


	# Time to do stuff
	sub restore_postprocess {
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		printLog("R: Path '[$dest]/$path' restoring attributes\n");

		# Loop with directories in this path
		foreach my $dname (keys %{$origDirList{$path}}) {
			# Set dir
			my $dir = $origDirList{$path}->{$dname};

			# Full dirname
			my $fdirname = "$dest/$path/$dname";

			# Restore attribs
			if (!chown($dir->{'uid'},$dir->{'gid'},$fdirname)) {
				print(STDERR "ERROR: Failed to chown(".$dir->{'uid'}.",".$dir->{'gid'}.") '$fdirname': $!\n");
			}
			if (!chmod($dir->{'mode'},$fdirname)) {
				print(STDERR "ERROR: Failed to chmod(".$dir->{'mode'}.") '$fdirname': $!\n");
			}
			if (!utime($dir->{'atime'},$dir->{'mtime'},$fdirname)) {
				print(STDERR "ERROR: Failed to utime(".$dir->{'atime'}.",".$dir->{'mtime'}.") '$fdirname': $!\n");
			}
		}

		# Loop with files in this path
		foreach my $fname (keys %{$origFileList{$path}}) {
			# Set dir
			my $file = $origFileList{$path}->{$fname};

			# Full dirname
			my $ffilename = "$dest/$path/$fname";

			# Restore attribs
			if (!chown($file->{'uid'},$file->{'gid'},$ffilename)) {
				print(STDERR "ERROR: Failed to chown(".$file->{'uid'}.",".$file->{'gid'}.") '$ffilename': $!\n");
			}
			if (!chmod($file->{'mode'},$ffilename)) {
				print(STDERR "ERROR: Failed to chmod(".$file->{'mode'}.") '$ffilename': $!\n");
			}
			if (!utime($file->{'atime'},$file->{'mtime'},$ffilename)) {
				print(STDERR "ERROR: Failed to utime(".$file->{'atime'}.",".$file->{'mtime'}.") '$ffilename': $!\n");
			}
		}
	}

	printLog("RESTORE START: $source => $dest\n");

	# This basically does our backup for us...
	find (
		{ 
			preprocess => \&restore_preprocess,
			wanted => \&restore_process,
			postprocess => \&restore_postprocess
		},
		$source
	);

	printLog("RESTORE END\n");
}


# Display log line
sub printLog {
	my $msg = shift;

	printf(STDERR "%s: %s", strftime('%F %T',localtime()), $msg);
}



# Display usage
sub displayHelp {
	# Build some strings we need
	my $systemDirStr = join (", ",@defaultSystemExcl);
	my $dataDirStr = join (", ",@defaultDataExcl);

	print(STDERR<<EOF);
Usage: $0 [args] <src> <dst>

    General Options:
      --help                             What you seeing now.
Nigel Kukard's avatar
Nigel Kukard committed
1058
      --config=file                      Config file to use.
Nigel Kukard's avatar
Nigel Kukard committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074

    Backing Options:
      --backup|-b                        Backup src to dst.
      --compress=<xz|bz2|gz|none>        Compression method to use defaults
                                         to using xz, or bzip2 if xz unavail.

      --exclude-system                   Exclude system paths from backup.
      --exclude-system-dir=dir           Exclude an additioanl directory. Look
                                         below for default list.
      --exclude-system-path=path         Exclude another system path. This
                                         defaults to / and this option will
                                         override that.
      --exclude-data                     Additionally exclude all data dirs
                                         listed below.
      --exclude-data-dir=dir             Exclude an additional directory.

1075
1076
      --exclude-files=pcre               PCRE to exclude files from backup.

Nigel Kukard's avatar
Nigel Kukard committed
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
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
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
    Restore Options:
      --restore|-r                       Restore src to dst.
      --tar-keep-newer                   Do not overwrite newer files.
      --tar-keep-old-files               Don't replace existing files.


Builtins:
---------
    system-dirs:
      $systemDirStr

    data-dirs:
      $dataDirStr
EOF
} 


#
# LIBRARY
#

sub loadStateFile {
		my ($statefile,$key,$fileList,$dirList,$pathAttribs) = @_;


		# Read in backup state file, we do it here because we may not have a backup file
		# to restore
		my $gz = gzopen($statefile,"rb") 
				or die "FATAL ERROR: Failed to open '$statefile': $!";
		# Read in file list
		my $line;
		while ($gz->gzreadline($line) > 0) {
			chomp($line);
			# Pull out array of items
			my @aline = split(/\0/,$line);
			my $type = shift(@aline);
			# Check if its defined
			if (defined($type)) {
				# If its a file...
				if ($type eq "f") {
					my ($ename,$size,$ctime,$atime,$mtime,$uid,$gid,$mode) = @aline;
					my $name = decode_base64($ename);
					# Setup our hash
					$fileList->{$key}->{$name}->{'size'} = $size;
					$fileList->{$key}->{$name}->{'ctime'} = $ctime;
					$fileList->{$key}->{$name}->{'atime'} = $atime;
					$fileList->{$key}->{$name}->{'mtime'} = $mtime;
					$fileList->{$key}->{$name}->{'uid'} = $uid;
					$fileList->{$key}->{$name}->{'gid'} = $gid;
					$fileList->{$key}->{$name}->{'mode'} = $mode;
				# If its a dir
				} elsif ($type eq "d") {
					my ($ename,$ctime,$atime,$mtime,$uid,$gid,$mode) = @aline;
					my $name = decode_base64($ename);
					# Setup our hash
					$dirList->{$key}->{$name}->{'ctime'} = $ctime;
					$dirList->{$key}->{$name}->{'atime'} = $atime;
					$dirList->{$key}->{$name}->{'mtime'} = $mtime;
					$dirList->{$key}->{$name}->{'uid'} = $uid;
					$dirList->{$key}->{$name}->{'gid'} = $gid;
					$dirList->{$key}->{$name}->{'mode'} = $mode;
				# Attribute
				} elsif ($type eq "a") {
					my ($name,$value) = @aline;
					$pathAttribs->{$key}->{$name} = $value;
				# Unknown
				} else {
					print(STDERR "ERROR: Invalid type '$type' in '$statefile'\n");
					exit 1;
				}
			}
		}
		# Close gzip file
		$gz->gzclose();
}


sub removeBackups
{
	my ($path,$format,$compression,$seqs) = @_;


	# Loop through backup sequences
	for (my $i = 0; $i <= $seqs; $i++) {

		my $tarExt;
		if ($compression eq "xz") {
			$tarExt = ".xz";
		} elsif ($compression eq "bzip2") {
			$tarExt = ".bz2";
		} elsif ($compression eq "gzip") {
			$tarExt = ".gz";
		} elsif ($compression eq "none") {
			$tarExt = "";
		}

		# Unlink backup files
		if (-f "$path/dbackup$i.tar$tarExt") {
			unlink("$path/dbackup$i.tar$tarExt")
					or die "ERROR: Failed to remove file '$path/dbackup$i.tar$tarExt': $!";
		}
		# Unlink manifest
		if (-f "$path/dbackup$i.manifest") {
			unlink("$path/dbackup$i.manifest")
					or die "ERROR: Failed to remove file '$path/dbackup$i.manifest': $!";
		}
		# Unlink index
		if (-f "$path/dbackup$i.index") {
			unlink("$path/dbackup$i.index")
					or die "ERROR: Failed to remove file '$path/dbackup$i.index': $!";
		}
		# Unlink snar
		if (-f "$path/dbackup$i.snar") {
			unlink("$path/dbackup$i.snar")
					or die "ERROR: Failed to remove file '$path/dbackup$i.snar': $!";
		}

	}
}

1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
sub toArray
{
	my $param = shift;

	if (ref $param eq "ARRAY") {
		return $param;
	} else {
		return [$param];
	}
}
Nigel Kukard's avatar
Nigel Kukard committed
1207
1208

# vim: ts=4