Imported Upstream version 3.2.0
[debian/amanda] / installcheck / Installcheck / Run.pm
1 # vim:ft=perl
2 # Copyright (c) 2008, 2009, 2010 Zmanda, Inc.  All Rights Reserved.
3 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License version 2 as published
6 # by the Free Software Foundation.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11 # for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # Contact information: Zmanda Inc, 465 S. Mathilda Ave., Suite 300
18 # Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
19
20 package Installcheck::Run;
21
22 =head1 NAME
23
24 Installcheck::Run - utilities to set up and run amanda dumps and restores
25
26 =head1 SYNOPSIS
27
28   use Installcheck::Run;
29
30   my $testconf = Installcheck::Run::setup();
31   # make any modifications you'd like to the configuration
32   $testconf->write();
33
34   ok(Installcheck::Run::run('amdump', 'TESTCONF'), "amdump completes successfully");
35
36   # It's generally polite to clean up your mess, although the test
37   # framework will clean up if your tests crash
38   Installcheck::Run::cleanup();
39
40   SKIP: {
41     skip "Expect.pm not installed", 7
42         unless $Installcheck::Run::have_expect;
43
44     my $exp = Installcheck::Run::run_expect('amflush', 'TESTCONF');
45     $exp->expect(..);
46     # ..
47   }
48
49 =head1 USAGE
50
51 High-level tests generally depend on a full-scale run of Amanda --
52 a fairly messy project.  This module simplifies that process by
53 abstracting away the mess.  It takes care of:
54
55 =over
56
57 =item Setting up a holding disk;
58
59 =item Setting up several vtapes; and
60
61 =item Setting up a DLE pointing to a reasonably-sized subdirectory of the build directory.
62
63 =back
64
65 Most of this magic is in C<setup()>, which returns a configuration object from
66 C<Installcheck::Config>, allowing the test to modify that configuration before
67 writing it out.  The hostname for the DLE is "localhost", and the disk name is
68 available in C<$Installcheck::Run::diskname>.  This DLE has a subdirectory
69 C<dir> which can be used as a secondary, smaller DLE if needed.
70
71 This module also provides a convenient Perlish interface for running Amanda
72 commands: C<run($app, $args, ...)>.  This function runs $app (from $sbindir if
73 $app is not an absolute path), and returns true if the application exited with
74 a status of zero.  The stdout and stderr of the application are left in
75 C<$Installcheck::Run::stdout> and C<stderr>, respectively.
76
77 To check that a run is successful, and return its stdout (chomped), use
78 C<run_get($app, $args, ...)>.  This function returns C<''> if the application
79 returns a nonzero exit status.  Since many Amanda applications send normal
80 output to stderr, use C<run_get_err($app, $args, ...)> to check that a run is
81 successful and return its stderr.  Similarly, C<run_err> checks that a run
82 returns a nonzero exit status, and then returns its stderr, chomped.  If you
83 need both, use a bare C<run> and then check C<$stderr> and C<$stdout> as needed.
84
85 C<run> and friends can be used whether or not this module's C<setup>
86 was invoked.
87
88 Finally, C<cleanup()> cleans up from a run, deleting all backed-up
89 data, holding disks, and configuration.  It's just good-neighborly
90 to call this before your test script exits.
91
92 =head2 VTAPES
93
94 This module sets up a configuration with three 30M vtapes, replete with
95 the proper vtape directories.  These are controlled by C<chg-disk>.
96 The tapes are not labeled, and C<autolabel> is not set by
97 default, although C<labelstr> is set to C<TESTCONF[0-9][0-9]>.
98
99 The vtapes are created in <$Installcheck::Run::taperoot>, a subdirectory of
100 C<$Installcheck::TMP> for ease of later deletion.  The subdirectory for each
101 slot is available from C<vtape_dir($slot)>, while the parent directory is
102 available from C<vtape_dir()>.  C<load_vtape($slot)> will "load" the indicated
103 slot just like chg-disk would, and return the resulting path.
104
105 =head2 HOLDING
106
107 The holding disk is C<$Installcheck::Run::holdingdir>.  It is a 15M holding disk,
108 with a chunksize of 1M (to help exercise the chunker).
109
110 =head2 DISKLIST
111
112 The disklist is empty by default.  Use something like the following
113 to add an entry:
114
115   $testconf->add_dle("localhost $diskname installcheck-test");
116
117 The C<installcheck-test> dumptype specifies
118   auth "local"
119   compress none
120   program "GNUTAR"
121
122 but of course, it can be modified by the test module.
123
124 =head2 INTERACTIVE APPLICATIONS
125
126 This package provides a rudimentary wrapper around C<Expect.pm>, which is not
127 typically included in a perl installation.  Consult C<$have_expect> to see if
128 this module is installed, and skip any Expect-based tests if it is not.
129
130 Otherwise, C<run_expect> takes arguments just like C<run>, but returns an Expect
131 object which you can use as you would like.
132
133 =head2 DIAGNOSTICS
134
135 If your test runs 'amdump', a nonzero exit status may not be very helpful.  The
136 function C<amdump_diag> will attempt to figure out what went wrong and display
137 useful information for the user via diag().  If it is given an argument, then
138 it will C<BAIL_OUT> with that message, causing L<Test::Harness> to stop running
139 tests.  Otherwise, it will simply die(), which will only terminate this
140 particular test script.
141
142 =cut
143
144 use Installcheck;
145 use Installcheck::Config;
146 use Amanda::Paths;
147 use File::Path;
148 use IPC::Open3;
149 use Cwd qw(abs_path getcwd);
150 use Carp;
151 use POSIX qw( WIFEXITED );
152 use Test::More;
153 use Amanda::Config qw( :init );
154 use Amanda::Util qw(slurp);
155
156 require Exporter;
157
158 @ISA = qw(Exporter);
159 @EXPORT_OK = qw(setup
160     run run_get run_get_err run_err
161     cleanup
162     $diskname $taperoot $holdingdir
163     $stdout $stderr $exit_code
164     load_vtape vtape_dir
165     amdump_diag run_expect );
166 @EXPORT = qw(exp_continue exp_continue_timeout);
167
168 # global variables
169 our $stdout = '';
170 our $stderr = '';
171
172 our $have_expect;
173
174 BEGIN {
175     eval "use Expect;";
176     if ($@) {
177         $have_expect = 0;
178         sub ignore() { };
179         *exp_continue = *ignore;
180         *exp_continue_timeout = *ignore;
181     } else {
182         $have_expect = 1;
183     }
184 };
185
186 # common paths (note that Installcheck::Dumpcache assumes these do not change)
187 our $diskname = "$Installcheck::TMP/backmeup";
188 our $taperoot = "$Installcheck::TMP/vtapes";
189 our $holdingdir ="$Installcheck::TMP/holding";
190
191 sub setup {
192     my $new_vtapes = shift;
193     my $testconf = Installcheck::Config->new();
194
195     (-d $diskname) or setup_backmeup();
196     if ($new_vtapes) {
197         setup_new_vtapes($testconf, 3);
198     } else {
199         setup_vtapes($testconf, 3);
200     }
201     setup_holding($testconf, 25);
202     setup_disklist($testconf);
203
204     return $testconf;
205 }
206
207 # create the 'backmeup' data
208 sub setup_backmeup {
209     my $dir_structure = {
210         '1megabyte' => 1024*1024,
211         '1kilobyte' => 1024,
212         '1byte' => 1,
213         'dir' => {
214             'ff' => 182,
215             'gg' => 2748,
216             'subdir' => {
217                 'subsubdir' => {
218                     '10k' => 1024*10,
219                 },
220             },
221         },
222     };
223
224     rmtree($diskname);
225     mkpath($diskname) or die("Could not create $name");
226
227     # pick a file for 'random' data -- /dev/urandom or, failing that,
228     # Amanda's ChangeLog.
229     my $randomfile = "/dev/urandom";
230     if (!-r $randomfile) {
231         $randomfile = "../ChangeLog";
232     }
233
234     my $rfd;
235     $create = sub {
236         my ($parent, $contents) = @_;
237         while (my ($name, $val) = each(%$contents)) {
238             my $name = "$parent/$name";
239             if (ref($val) eq 'HASH') {
240                 mkpath($name) or die("Could not create $name");
241                 $create->($name, $val);
242             } else {
243                 my $bytes_needed = $val+0;
244                 open(my $wfd, ">", $name) or die("Could not open $name: $!");
245
246                 # read bytes from a source file as a source of "random" data..
247                 while ($bytes_needed) {
248                     my $buf;
249                     if (!defined($rfd)) {
250                         open($rfd, "<", "$randomfile") or die("Could not open $randomfile");
251                     }
252                     my $to_read = $bytes_needed>10240? 10240:$bytes_needed;
253                     my $bytes_read = sysread($rfd, $buf, $to_read);
254                     print $wfd $buf;
255                     if ($bytes_read < $to_read) {
256                         close($rfd);
257                         $rfd = undef;
258                     }
259
260                     $bytes_needed -= $bytes_read;
261                 }
262             }
263         }
264     };
265
266     $create->($diskname, $dir_structure);
267 }
268
269 sub setup_vtapes {
270     my ($testconf, $ntapes) = @_;
271     if (-d $taperoot) {
272         rmtree($taperoot);
273     }
274
275     # make each of the tape directories
276     for (my $i = 1; $i < $ntapes+1; $i++) {
277         my $tapepath = "$taperoot/slot$i";
278         mkpath("$tapepath");
279     }
280
281     load_vtape(1);
282
283     # set up the appropriate configuration
284     $testconf->add_param("tapedev", "\"file:$taperoot\"");
285     $testconf->add_param("tpchanger", "\"chg-disk\"");
286     $testconf->add_param("changerfile", "\"$CONFIG_DIR/TESTCONF/ignored-filename\"");
287     $testconf->add_param("labelstr", "\"TESTCONF[0-9][0-9]\"");
288     $testconf->add_param("tapecycle", "$ntapes");
289
290     # this overwrites the existing TEST-TAPE tapetype
291     $testconf->add_tapetype('TEST-TAPE', [
292         'length' => '30 mbytes',
293         'filemark' => '4 kbytes',
294     ]);
295 }
296
297 sub setup_new_vtapes {
298     my ($testconf, $ntapes) = @_;
299     if (-d $taperoot) {
300         rmtree($taperoot);
301     }
302
303     # make each of the tape directories
304     for (my $i = 1; $i < $ntapes+1; $i++) {
305         my $tapepath = "$taperoot/slot$i";
306         mkpath("$tapepath");
307     }
308
309     load_vtape(1);
310
311     # set up the appropriate configuration
312     $testconf->add_param("tpchanger", "\"chg-disk:$taperoot\"");
313     $testconf->add_param("labelstr", "\"TESTCONF[0-9][0-9]\"");
314     $testconf->add_param("tapecycle", "$ntapes");
315
316     # this overwrites the existing TEST-TAPE tapetype
317     $testconf->add_tapetype('TEST-TAPE', [
318         'length' => '30 mbytes',
319         'filemark' => '4 kbytes',
320     ]);
321 }
322
323 sub setup_holding {
324     my ($testconf, $mbytes) = @_;
325
326     if (-d $holdingdir) {
327         rmtree($holdingdir);
328     }
329     mkpath($holdingdir);
330
331     $testconf->add_holdingdisk("hd1", [
332         'directory' => "\"$holdingdir\"",
333         'use' => "$mbytes mbytes",
334         'chunksize' => "1 mbyte",
335     ]);
336 }
337
338 sub setup_disklist {
339     my ($testconf) = @_;
340
341     $testconf->add_dumptype("installcheck-test", [
342         'auth' => '"local"',
343         'compress' => 'none',
344         'program' => '"GNUTAR"',
345     ]);
346 }
347
348 sub vtape_dir {
349     my ($slot) = @_;
350     if (defined($slot)) {
351         return "$taperoot/slot$slot";
352     } else {
353         return "$taperoot";
354     }
355 }
356
357 sub load_vtape {
358     my ($slot) = @_;
359
360     # make the data/ symlink from our taperoot
361     unlink("$taperoot/data");
362     symlink(vtape_dir($slot), "$taperoot/data")
363         or die("Could not create 'data' symlink: $!");
364
365     return $taperoot;
366 }
367
368 sub run {
369     my $app = shift;
370     my @args = @_;
371     my $errtempfile = "$Installcheck::TMP/stderr$$.out";
372
373     # use a temporary file for error output -- this eliminates synchronization
374     # problems between reading stderr and stdout
375     local (*INFH, *OUTFH, *ERRFH);
376     open(ERRFH, ">", $errtempfile);
377
378     $app = "$sbindir/$app" unless ($app =~ qr{/});
379     my $pid = IPC::Open3::open3("INFH", "OUTFH", ">&ERRFH",
380         "$app", @args);
381
382     # immediately close the child's stdin
383     close(INFH);
384
385     # read from stdout until it's closed
386     $stdout = do { local $/; <OUTFH> };
387     close(OUTFH);
388
389     # and wait for the kid to die
390     waitpid $pid, 0 or croak("Error waiting for child process to die: $@");
391     my $status = $?;
392     close(ERRFH);
393
394     # fetch stderr from the temporary file
395     $stderr = slurp($errtempfile);
396     unlink($errtempfile);
397
398     # and return true if the exit status was zero
399     $exit_code = $status >> 8;
400     return WIFEXITED($status) && $exit_code == 0;
401 }
402
403 sub run_get {
404     if (!run @_) {
405         my $detail = '';
406         # prefer to put stderr in the output
407         if ($stderr) {
408             $detail .= "\nstderr is:\n$stderr";
409         } else {
410             if ($stdout and length($stdout) < 1024) {
411                 $detail .= "\nstdout is:\n$stdout";
412             }
413         }
414         Test::More::diag("run unexpectedly failed; no output to compare$detail");
415         return '';
416     }
417
418     my $ret = $stdout;
419     chomp($ret);
420     return $ret;
421 }
422
423 sub run_get_err {
424     if (!run @_) {
425         my $detail = "\nstderr is:\n$stderr";
426         Test::More::diag("run unexpectedly failed; no output to compare$detail");
427         return '';
428     }
429
430     my $ret = $stderr;
431     chomp($ret);
432     return $ret;
433 }
434
435 sub run_err {
436     if (run @_) {
437         Test::More::diag("run unexpectedly succeeded; no output to compare");
438         return '';
439     }
440
441     my $ret = $stderr;
442     chomp($ret);
443     return $ret;
444 }
445
446 sub cleanup {
447     Installcheck::Config::cleanup();
448
449     if (-d $taperoot) {
450         rmtree($taperoot);
451     }
452     if (-d $holdingdir) {
453         rmtree($holdingdir);
454     }
455 }
456
457 sub run_expect {
458     my $app = shift;
459     my @args = @_;
460
461     die "Expect.pm not found" unless $have_expect;
462
463     $app = "$sbindir/$app" unless ($app =~ qr{^/});
464     my $exp = Expect->new("$app", @args);
465
466     return $exp;
467 }
468
469 sub amdump_diag {
470     my ($msg) = @_;
471
472     # try running amreport
473     my $report = "failure-report.txt";
474     unlink($report);
475     my @logfiles = <$CONFIG_DIR/TESTCONF/log/log.*>;
476     if (@logfiles > 0) {
477         run('amreport', 'TESTCONF', '-f', $report, '-l', $logfiles[$#logfiles]);
478         if (-f $report) {
479             open(my $fh, "<", $report) or return;
480             for my $line (<$fh>) {
481                 Test::More::diag($line);
482             }
483             unlink($report);
484             goto bail;
485         }
486     }
487
488     # maybe there was a config error
489     config_init($CONFIG_INIT_EXPLICIT_NAME, "TESTCONF");
490     my ($cfgerr_level, @cfgerr_errors) = config_errors();
491     if ($cfgerr_level >= $CFGERR_WARNINGS) {
492         foreach (@cfgerr_errors) {
493             Test::More::diag($_);
494         }
495         goto bail;
496     }
497
498     # huh.
499     Test::More::diag("no amreport available, and no config errors");
500
501 bail:
502     if ($msg) {
503         Test::More::BAIL_OUT($msg);
504     } else {
505         die("amdump failed; cannot continue");
506     }
507 }
508
509 1;