ArchiveMediaSize and ArchiveChunkSize from _search_archive config
[BackupPC.git] / lib / BackupPC / Storage / Text.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Storage::Text package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Storage::Text class that implements
8 #   BackupPC's persistent state storage (config, host info, backup
9 #   and restore info) using text files.
10 #
11 # AUTHOR
12 #   Craig Barratt  <cbarratt@users.sourceforge.net>
13 #
14 # COPYRIGHT
15 #   Copyright (C) 2004-2009  Craig Barratt
16 #
17 #   This program is free software; you can redistribute it and/or modify
18 #   it under the terms of the GNU General Public License as published by
19 #   the Free Software Foundation; either version 2 of the License, or
20 #   (at your option) any later version.
21 #
22 #   This program is distributed in the hope that it will be useful,
23 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
24 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 #   GNU General Public License for more details.
26 #
27 #   You should have received a copy of the GNU General Public License
28 #   along with this program; if not, write to the Free Software
29 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30 #
31 #========================================================================
32 #
33 # Version 3.2.0, released 31 Jul 2010.
34 #
35 # See http://backuppc.sourceforge.net.
36 #
37 #========================================================================
38
39 package BackupPC::Storage::Text;
40
41 use strict;
42 use vars qw(%Conf);
43 use Data::Dumper;
44 use File::Path;
45 use Fcntl qw/:flock/;
46
47 sub new
48 {
49     my $class = shift;
50     my($flds, $paths) = @_;
51
52     my $s = bless {
53         %$flds,
54         %$paths,
55     }, $class;
56     return $s;
57 }
58
59 sub setPaths
60 {
61     my $class = shift;
62     my($paths) = @_;
63
64     foreach my $v ( keys(%$paths) ) {
65         $class->{$v} = $paths->{$v};
66     }
67 }
68
69 sub BackupInfoRead
70 {
71     my($s, $host) = @_;
72     local(*BK_INFO, *LOCK);
73     my(@Backups);
74
75     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{TopDir}/pc/$host/LOCK");
76     if ( open(BK_INFO, "$s->{TopDir}/pc/$host/backups") ) {
77         binmode(BK_INFO);
78         while ( <BK_INFO> ) {
79             s/[\n\r]+//;
80             next if ( !/^(\d+\t(incr|full|partial).*)/ );
81             $_ = $1;
82             @{$Backups[@Backups]}{@{$s->{BackupFields}}} = split(/\t/);
83         }
84         close(BK_INFO);
85     }
86     close(LOCK);
87     #
88     # Default the version field.  Prior to 3.0.0 the xferMethod
89     # field is empty, so we use that to figure out the version.
90     #
91     for ( my $i = 0 ; $i < @Backups ; $i++ ) {
92         next if ( $Backups[$i]{version} ne "" );
93         if ( $Backups[$i]{xferMethod} eq "" ) {
94             $Backups[$i]{version} = "2.1.2";
95         } else {
96             $Backups[$i]{version} = "3.0.0";
97         }
98     }
99     return @Backups;
100 }
101
102 sub BackupInfoWrite
103 {
104     my($s, $host, @Backups) = @_;
105     my($i, $contents, $fileOk);
106
107     #
108     # Generate the file contents
109     #
110     for ( $i = 0 ; $i < @Backups ; $i++ ) {
111         my %b = %{$Backups[$i]};
112         $contents .= join("\t", @b{@{$s->{BackupFields}}}) . "\n";
113     }
114     
115     #
116     # Write the file
117     #
118     return $s->TextFileWrite("$s->{TopDir}/pc/$host/backups", $contents);
119 }
120
121 sub RestoreInfoRead
122 {
123     my($s, $host) = @_;
124     local(*RESTORE_INFO, *LOCK);
125     my(@Restores);
126
127     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{TopDir}/pc/$host/LOCK");
128     if ( open(RESTORE_INFO, "$s->{TopDir}/pc/$host/restores") ) {
129         binmode(RESTORE_INFO);
130         while ( <RESTORE_INFO> ) {
131             s/[\n\r]+//;
132             next if ( !/^(\d+.*)/ );
133             $_ = $1;
134             @{$Restores[@Restores]}{@{$s->{RestoreFields}}} = split(/\t/);
135         }
136         close(RESTORE_INFO);
137     }
138     close(LOCK);
139     return @Restores;
140 }
141
142 sub RestoreInfoWrite
143 {
144     my($s, $host, @Restores) = @_;
145     local(*RESTORE_INFO, *LOCK);
146     my($i, $contents, $fileOk);
147
148     #
149     # Generate the file contents
150     #
151     for ( $i = 0 ; $i < @Restores ; $i++ ) {
152         my %b = %{$Restores[$i]};
153         $contents .= join("\t", @b{@{$s->{RestoreFields}}}) . "\n";
154     }
155
156     #
157     # Write the file
158     #
159     return $s->TextFileWrite("$s->{TopDir}/pc/$host/restores", $contents);
160 }
161
162 sub ArchiveInfoRead
163 {
164     my($s, $host) = @_;
165     local(*ARCHIVE_INFO, *LOCK);
166     my(@Archives);
167
168     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{TopDir}/pc/$host/LOCK");
169     if ( open(ARCHIVE_INFO, "$s->{TopDir}/pc/$host/archives") ) {
170         binmode(ARCHIVE_INFO);
171         while ( <ARCHIVE_INFO> ) {
172             s/[\n\r]+//;
173             next if ( !/^(\d+.*)/ );
174             $_ = $1;
175             @{$Archives[@Archives]}{@{$s->{ArchiveFields}}} = split(/\t/);
176         }
177         close(ARCHIVE_INFO);
178     }
179     close(LOCK);
180     return @Archives;
181 }
182
183 sub ArchiveInfoWrite
184 {
185     my($s, $host, @Archives) = @_;
186     local(*ARCHIVE_INFO, *LOCK);
187     my($i, $contents, $fileOk);
188
189     #
190     # Generate the file contents
191     #
192     for ( $i = 0 ; $i < @Archives ; $i++ ) {
193         my %b = %{$Archives[$i]};
194         $contents .= join("\t", @b{@{$s->{ArchiveFields}}}) . "\n";
195     }
196
197     #
198     # Write the file
199     #
200     return $s->TextFileWrite("$s->{TopDir}/pc/$host/archives", $contents);
201 }
202
203 #
204 # Write a text file as safely as possible.  We write to
205 # a new file, verify the file, and the rename the file.
206 # The previous version of the file is renamed with a
207 # .old extension.
208 #
209 sub TextFileWrite
210 {
211     my($s, $file, $contents) = @_;
212     local(*FD, *LOCK);
213     my($fileOk);
214
215     (my $dir = $file) =~ s{(.+)/(.+)}{$1};
216
217     if ( !-d $dir ) {
218         eval { mkpath($dir, 0, 0775) };
219         return "TextFileWrite: can't create directory $dir" if ( $@ );
220     }
221     if ( open(FD, ">", "$file.new") ) {
222         binmode(FD);
223         print FD $contents;
224         close(FD);
225         #
226         # verify the file
227         #
228         if ( open(FD, "<", "$file.new") ) {
229             binmode(FD);
230             if ( join("", <FD>) ne $contents ) {
231                 return "TextFileWrite: Failed to verify $file.new";
232             } else {
233                 $fileOk = 1;
234             }
235             close(FD);
236         }
237     }
238     if ( $fileOk ) {
239         my $lock;
240         
241         if ( open(LOCK, "$dir/LOCK") || open(LOCK, ">", "$dir/LOCK") ) {
242             $lock = 1;
243             flock(LOCK, LOCK_EX);
244         }
245         if ( -s "$file" ) {
246             unlink("$file.old")           if ( -f "$file.old" );
247             rename("$file", "$file.old")  if ( -f "$file" );
248         } else {
249             unlink("$file") if ( -f "$file" );
250         }
251         rename("$file.new", "$file") if ( -f "$file.new" );
252         close(LOCK) if ( $lock );
253     } else {
254         return "TextFileWrite: Failed to write $file.new";
255     }
256     return;
257 }
258
259 sub ConfigPath
260 {
261     my($s, $host) = @_;
262
263     return "$s->{ConfDir}/config.pl" if ( !defined($host) );
264     if ( $s->{useFHS} ) {
265         return "$s->{ConfDir}/pc/$host.pl";
266     } else {
267         return "$s->{TopDir}/pc/$host/config.pl"
268             if ( -f "$s->{TopDir}/pc/$host/config.pl" );
269         return "$s->{ConfDir}/$host.pl"
270             if ( $host ne "config" && -f "$s->{ConfDir}/$host.pl" );
271         return "$s->{ConfDir}/pc/$host.pl";
272     }
273 }
274
275 sub ConfigDataRead
276 {
277     my($s, $host, $prevConfig) = @_;
278     my($ret, $mesg, $config, @configs);
279
280     #
281     # TODO: add lock
282     #
283     my $conf = $prevConfig || {};
284     my $configPath = $s->ConfigPath($host);
285
286     push(@configs, $configPath) if ( -f $configPath );
287     foreach $config ( @configs ) {
288         %Conf = %$conf;
289         if ( !defined($ret = do $config) && ($! || $@) ) {
290             $mesg = "Couldn't open $config: $!" if ( $! );
291             $mesg = "Couldn't execute $config: $@" if ( $@ );
292             $mesg =~ s/[\n\r]+//;
293             return ($mesg, $conf);
294         }
295         %$conf = %Conf;
296     }
297
298     #
299     # Promote BackupFilesOnly and BackupFilesExclude to hashes
300     #
301     foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
302         next if ( !defined($conf->{$param}) || ref($conf->{$param}) eq "HASH" );
303         $conf->{$param} = [ $conf->{$param} ]
304                                 if ( ref($conf->{$param}) ne "ARRAY" );
305         $conf->{$param} = { "*" => $conf->{$param} };
306     }
307
308     #
309     # Handle backward compatibility with defunct BlackoutHourBegin,
310     # BlackoutHourEnd, and BlackoutWeekDays parameters.
311     #
312     if ( defined($conf->{BlackoutHourBegin}) ) {
313         push(@{$conf->{BlackoutPeriods}},
314              {
315                  hourBegin => $conf->{BlackoutHourBegin},
316                  hourEnd   => $conf->{BlackoutHourEnd},
317                  weekDays  => $conf->{BlackoutWeekDays},
318              }
319         );
320         delete($conf->{BlackoutHourBegin});
321         delete($conf->{BlackoutHourEnd});
322         delete($conf->{BlackoutWeekDays});
323     }
324
325     return (undef, $conf);
326 }
327
328 sub ConfigDataWrite
329 {
330     my($s, $host, $newConf) = @_;
331
332     my $configPath = $s->ConfigPath($host);
333
334     my($err, $contents) = $s->ConfigFileMerge("$configPath", $newConf);
335     if ( defined($err) ) {
336         return $err;
337     } else {
338         #
339         # Write the file
340         #
341         return $s->TextFileWrite($configPath, $contents);
342     }
343 }
344
345 sub ConfigFileMerge
346 {
347     my($s, $inFile, $newConf) = @_;
348     local(*C);
349     my($contents, $skipExpr, $fakeVar);
350     my $done = {};
351
352     if ( -f $inFile ) {
353         #
354         # Match existing settings in current config file
355         #
356         open(C, $inFile)
357             || return ("ConfigFileMerge: can't open/read $inFile", undef);
358         binmode(C);
359
360         while ( <C> ) {
361             if ( /^\s*\$Conf\{([^}]*)\}\s*=(.*)/ ) {
362                 my $var = $1;
363                 $skipExpr = "\$fakeVar = $2\n";
364                 if ( exists($newConf->{$var}) ) {
365                     my $d = Data::Dumper->new([$newConf->{$var}], [*value]);
366                     $d->Indent(1);
367                     $d->Terse(1);
368                     my $value = $d->Dump;
369                     $value =~ s/(.*)\n/$1;\n/s;
370                     $contents .= "\$Conf{$var} = " . $value;
371                     $done->{$var} = 1;
372                 }
373             } elsif ( defined($skipExpr) ) {
374                 $skipExpr .= $_;
375             } else {
376                 $contents .= $_;
377             }
378             if ( defined($skipExpr)
379                     && ($skipExpr =~ /^\$fakeVar = *<</
380                         || $skipExpr =~ /;[\n\r]*$/) ) {
381                 #
382                 # if we have a complete expression, then we are done
383                 # skipping text from the original config file.
384                 #
385                 $skipExpr = $1 if ( $skipExpr =~ /(.*)/s );
386                 eval($skipExpr);
387                 $skipExpr = undef if ( $@ eq "" );
388             }
389         }
390         close(C);
391     }
392
393     #
394     # Add new entries not matched in current config file
395     #
396     foreach my $var ( sort(keys(%$newConf)) ) {
397         next if ( $done->{$var} );
398         my $d = Data::Dumper->new([$newConf->{$var}], [*value]);
399         $d->Indent(1);
400         $d->Terse(1);
401         my $value = $d->Dump;
402         $value =~ s/(.*)\n/$1;\n/s;
403         $contents .= "\$Conf{$var} = " . $value;
404         $done->{$var} = 1;
405     }
406     return (undef, $contents);
407 }
408
409 #
410 # Return the mtime of the config file
411 #
412 sub ConfigMTime
413 {
414     my($s) = @_;
415     return (stat($s->ConfigPath()))[9];
416 }
417
418 #
419 # Returns information from the host file in $s->{ConfDir}/hosts.
420 # With no argument a ref to a hash of hosts is returned.  Each
421 # hash contains fields as specified in the hosts file.  With an
422 # argument a ref to a single hash is returned with information
423 # for just that host.
424 #
425 sub HostInfoRead
426 {
427     my($s, $host) = @_;
428     my(%hosts, @hdr, @fld);
429     local(*HOST_INFO, *LOCK);
430
431     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{ConfDir}/LOCK");
432     if ( !open(HOST_INFO, "$s->{ConfDir}/hosts") ) {
433         print(STDERR "Can't open $s->{ConfDir}/hosts\n");
434         close(LOCK);
435         return {};
436     }
437     binmode(HOST_INFO);
438     while ( <HOST_INFO> ) {
439         s/[\n\r]+//;
440         s/#.*//;
441         s/\s+$//;
442         next if ( /^\s*$/ || !/^([\w\.\\-]+\s+.*)/ );
443         #
444         # Split on white space, except if preceded by \
445         # using zero-width negative look-behind assertion
446         # (always wanted to use one of those).
447         #
448         @fld = split(/(?<!\\)\s+/, $1);
449         #
450         # Remove any \
451         #
452         foreach ( @fld ) {
453             s{\\(\s)}{$1}g;
454         }
455         if ( @hdr ) {
456             if ( defined($host) ) {
457                 next if ( lc($fld[0]) ne lc($host) );
458                 @{$hosts{lc($fld[0])}}{@hdr} = @fld;
459                 close(HOST_INFO);
460                 close(LOCK);
461                 return \%hosts;
462             } else {
463                 @{$hosts{lc($fld[0])}}{@hdr} = @fld;
464             }
465         } else {
466             @hdr = @fld;
467         }
468     }
469     close(HOST_INFO);
470     close(LOCK);
471     return \%hosts;
472 }
473
474 #
475 # Writes new hosts information to the hosts file in $s->{ConfDir}/hosts.
476 # With no argument a ref to a hash of hosts is returned.  Each
477 # hash contains fields as specified in the hosts file.  With an
478 # argument a ref to a single hash is returned with information
479 # for just that host.
480 #
481 sub HostInfoWrite
482 {
483     my($s, $hosts) = @_;
484     my($gotHdr, @fld, $hostText, $contents);
485     local(*HOST_INFO);
486
487     if ( !open(HOST_INFO, "$s->{ConfDir}/hosts") ) {
488         return "Can't open $s->{ConfDir}/hosts";
489     }
490     foreach my $host ( keys(%$hosts) ) {
491         my $name = "$hosts->{$host}{host}";
492         my $rest = "\t$hosts->{$host}{dhcp}"
493                  . "\t$hosts->{$host}{user}"
494                  . "\t$hosts->{$host}{moreUsers}";
495         $name =~ s/ /\\ /g;
496         $rest =~ s/ //g;
497         $hostText->{$host} = $name . $rest;
498     }
499     binmode(HOST_INFO);
500     while ( <HOST_INFO> ) {
501         s/[\n\r]+//;
502         if ( /^\s*$/ || /^\s*#/ ) {
503             $contents .= $_ . "\n";
504             next;
505         }
506         if ( !$gotHdr ) {
507             $contents .= $_ . "\n";
508             $gotHdr = 1;
509             next;
510         }
511         @fld = split(/(?<!\\)\s+/, $1);
512         #
513         # Remove any \
514         #
515         foreach ( @fld ) {
516             s{\\(\s)}{$1}g;
517         }
518         if ( defined($hostText->{$fld[0]}) ) {
519             $contents .= $hostText->{$fld[0]} . "\n";
520             delete($hostText->{$fld[0]});
521         }
522     }
523     foreach my $host ( sort(keys(%$hostText)) ) {
524         $contents .= $hostText->{$host} . "\n";
525         delete($hostText->{$host});
526     }
527     close(HOST_INFO);
528
529     #
530     # Write and verify the new host file
531     #
532     return $s->TextFileWrite("$s->{ConfDir}/hosts", $contents);
533 }
534
535 #
536 # Return the mtime of the hosts file
537 #
538 sub HostsMTime
539 {
540     my($s) = @_;
541     return (stat("$s->{ConfDir}/hosts"))[9];
542 }
543
544 1;