]> rtime.felk.cvut.cz Git - novaboot.git/blob - novaboot
09612aa1fb3279f8ef040b7ba9c97c5d653c335c
[novaboot.git] / novaboot
1 #!/usr/bin/perl -w
2
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 2 of the License, or
6 # (at your option) any later version.
7
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 use strict;
17 use warnings;
18 use warnings (exists $ENV{NOVABOOT_TEST} ? (FATAL => 'all') : ());
19 use Getopt::Long qw(GetOptionsFromString GetOptionsFromArray);
20 use Pod::Usage;
21 use File::Basename;
22 use File::Spec;
23 use IO::Handle;
24 use Time::HiRes("usleep");
25 use Socket;
26 use FileHandle;
27 use IPC::Open2;
28 use POSIX qw(:errno_h);
29 use Cwd qw(getcwd abs_path);
30 use Expect;
31
32 # always flush
33 $| = 1;
34
35 my $invocation_dir = $ENV{PWD} || getcwd();
36
37 ## Configuration file handling
38
39 # Default configuration
40 $CFG::hypervisor = "";
41 $CFG::hypervisor_params = "serial";
42 $CFG::genisoimage = "genisoimage";
43 $CFG::qemu = 'qemu-system-i386 -cpu coreduo -smp 2';
44 $CFG::default_target = 'qemu';
45 %CFG::targets = (
46     'qemu' => '--qemu',
47     "tud" => '--server=erwin.inf.tu-dresden.de:~sojka/boot/novaboot --rsync-flags="--chmod=Dg+s,ug+w,o-w,+rX --rsync-path=\"umask 002 && rsync\"" --grub --grub-prefix=(nd)/tftpboot/sojka/novaboot --grub-preamble="timeout 0" --concat --iprelay=141.76.48.80:2324 --scriptmod=s/\\\\bhostserial\\\\b/hostserialpci/g',
48     "novabox" => '--server=rtime.felk.cvut.cz:/srv/tftp/novaboot --rsync-flags="--chmod=Dg+s,ug+w,o-w,+rX --rsync-path=\"umask 002 && rsync\"" --pulsar --iprelay=147.32.86.92:2324',
49     "localhost" => '--scriptmod=s/console=tty[A-Z0-9,]+// --server=/boot/novaboot/$NAME --grub2 --grub-prefix=/boot/novaboot/$NAME --grub2-prolog="  set root=\'(hd0,msdos1)\'"',
50     "ryuglab" => '--server=pc-sojkam.felk.cvut.cz:/srv/tftp --uboot --uboot-init="mw f0000b00 \${psc_cfg}; sleep 1" --remote-cmd="ssh -tt pc-sojkam.felk.cvut.cz \"sterm -d -s 115200 /dev/ttyUSB0\""',
51     "ryulocal" => '--dhcp-tftp --serial --uboot --uboot-init="dhcp; mw f0000b00 \${psc_cfg}; sleep 1" --reset-cmd="if which dtrrts; then dtrrts $NB_SERIAL 0 1; sleep 0.1; dtrrts $NB_SERIAL 1 1; fi"',
52
53     );
54 chomp(my $nproc = `nproc`);
55 $CFG::scons = "scons -j$nproc";
56 $CFG::make = "make -j$nproc";
57
58 my $builddir;
59
60 sub read_config($) {
61     my ($cfg) = @_;
62     {
63         package CFG; # Put config data into a separate namespace
64         my $rc = do($cfg);
65
66         # Check for errors
67         if ($@) {
68             die("ERROR: Failure compiling '$cfg' - $@");
69         } elsif (! defined($rc)) {
70             die("ERROR: Failure reading '$cfg' - $!");
71         } elsif (! $rc) {
72             die("ERROR: Failure processing '$cfg'");
73         }
74     }
75     $builddir = File::Spec->rel2abs($CFG::builddir, dirname($cfg)) if defined $CFG::builddir;
76     print STDERR "novaboot: Read $cfg\n";
77 }
78
79 my @cfgs;
80 {
81     # We don't use $0 here, because it points to the novaboot itself and
82     # not to the novaboot script. The problem with this approach is that
83     # when a script is run as "novaboot <options> <script>" then $ARGV[0]
84     # contains the first option. Hence the -f check.
85     my $dir = File::Spec->rel2abs($ARGV[0] && -f $ARGV[0] ? dirname($ARGV[0]) : '', $invocation_dir);
86     while ((-d $dir || -l $dir ) && $dir ne "/") {
87         push @cfgs, "$dir/.novaboot" if -r "$dir/.novaboot";
88         my @dirs = File::Spec->splitdir($dir);
89         $dir = File::Spec->catdir(@dirs[0..$#dirs-1]);
90     }
91 }
92 my $cfg = $ENV{'NOVABOOT_CONFIG'};
93 Getopt::Long::Configure(qw/no_ignore_case pass_through/);
94 GetOptions ("config|c=s" => \$cfg);
95 read_config($_) foreach $cfg or reverse @cfgs;
96
97 ## Command line handling
98
99 my $explicit_target;
100 GetOptions ("target|t=s" => \$explicit_target);
101
102 my ($amt, @append, $bender, @chainloaders, $concat, $config_name_opt, $dhcp_tftp, $dump_opt, $dump_config, @exiton, @expect_raw, $gen_only, $grub_config, $grub_prefix, $grub_preamble, $grub2_prolog, $grub2_config, $help, $ider, $iprelay, $iso_image, $interactive, $kernel_opt, $make, $man, $no_file_gen, $off_opt, $on_opt, $pulsar, $pulsar_root, $qemu, $qemu_append, $qemu_flags_cmd, $remote_cmd, $remote_expect, $reset_cmd, $rom_prefix, $rsync_flags, @scriptmod, $scons, $serial, $server, $stty, $tftp, $tftp_port, $uboot, @uboot_init);
103
104 $rsync_flags = '';
105 $rom_prefix = 'rom://';
106 $stty = 'raw -crtscts -onlcr 115200';
107
108 my @expect_seen = ();
109 sub handle_expect
110 {
111     my ($n, $v) = @_;
112     push(@expect_seen, '-re') if $n eq "expect-re";
113     push(@expect_seen, $v);
114 }
115
116 sub handle_send
117 {
118     my ($n, $v) = @_;
119     unless (@expect_seen) { die("No --expect before --send"); }
120     my $ret = ($n eq "sendcont") ? exp_continue : 0;
121     unshift(@expect_raw, sub { shift->send(eval("\"$v\"")); $ret; });
122     unshift(@expect_raw, @expect_seen);
123     @expect_seen = ();
124 }
125
126 my %opt_spec;
127 %opt_spec = (
128     "amt=s"          => \$amt,
129     "append|a=s"     => \@append,
130     "bender|b"       => \$bender,
131     "build-dir=s"    => sub { my ($n, $v) = @_; $builddir = File::Spec->rel2abs($v); },
132     "concat"         => \$concat,
133     "chainloader=s"  => \@chainloaders,
134     "dhcp-tftp|d"    => \$dhcp_tftp,
135     "dump"           => \$dump_opt,
136     "dump-config"    => \$dump_config,
137     "exiton=s"       => \@exiton,
138     "expect=s"       => \&handle_expect,
139     "expect-re=s"    => \&handle_expect,
140     "expect-raw=s"   => sub { my ($n, $v) = @_; unshift(@expect_raw, eval($v)); },
141     "gen-only"       => \$gen_only,
142     "grub|g:s"       => \$grub_config,
143     "grub-preamble=s"=> \$grub_preamble,
144     "grub-prefix=s"  => \$grub_prefix,
145     "grub2:s"        => \$grub2_config,
146     "grub2-prolog=s" => \$grub2_prolog,
147     "ider"           => \$ider,
148     "iprelay=s"      => \$iprelay,
149     "iso:s"          => \$iso_image,
150     "kernel|k=s"     => \$kernel_opt,
151     "interactive|i"  => \$interactive,
152     "name=s"         => \$config_name_opt,
153     "make|m:s"       => \$make,
154     "no-file-gen"    => \$no_file_gen,
155     "off"            => \$off_opt,
156     "on"             => \$on_opt,
157     "pulsar|p:s"     => \$pulsar,
158     "pulsar-root=s"  => \$pulsar_root,
159     "qemu|Q:s"       => \$qemu,
160     "qemu-append=s"  => \$qemu_append,
161     "qemu-flags|q=s" => \$qemu_flags_cmd,
162     "remote-cmd=s"   => \$remote_cmd,
163     "remote-expect=s"=> \$remote_expect,
164     "reset-cmd=s"    => \$reset_cmd,
165     "rsync-flags=s"  => \$rsync_flags,
166     "scons:s"        => \$scons,
167     "scriptmod=s"    => \@scriptmod,
168     "send=s"         => \&handle_send,
169     "sendcont=s"     => \&handle_send,
170     "serial|s:s"     => \$serial,
171     "server:s"       => \$server,
172     "strip-rom"      => sub { $rom_prefix = ''; },
173     "stty=s"         => \$stty,
174     "tftp"           => \$tftp,
175     "tftp-port=i"    => \$tftp_port,
176     "uboot:s"        => \$uboot,
177     "uboot-init=s"   => \@uboot_init,
178     "h"              => \$help,
179     "help"           => \$man,
180     );
181
182 # First process target options
183 {
184     my $t = defined($explicit_target) ? $explicit_target : $CFG::default_target;
185     my @target_expanded;
186     Getopt::Long::Configure(qw/no_ignore_case pass_through/);
187     while ($t) {
188         exists $CFG::targets{$t} or die("Unknown target '$t' (valid targets are: ".join(", ", sort keys(%CFG::targets)).")");
189
190         undef $explicit_target;
191         my ($ret, $remaining_args) = GetOptionsFromString ($CFG::targets{$t}, ("target|t=s" => \$explicit_target));
192         if (!$ret) { die "Error parsing target $t option"; }
193         push(@target_expanded, @$remaining_args);
194         $t = $explicit_target;
195     }
196     Getopt::Long::Configure(qw/no_ignore_case no_pass_through/);
197     GetOptionsFromArray(\@target_expanded, %opt_spec) or die ("Error in target definition");
198 }
199
200 # Then process other command line options - some of them may override
201 # what was specified by the target
202 GetOptions %opt_spec or die("Error in command line arguments");
203 pod2usage(1) if $help;
204 pod2usage(-exitstatus => 0, -verbose => 2) if $man;
205
206 ### Dump sanitized configuration (if requested)
207
208 if ($dump_config) {
209     use Data::Dumper;
210     $Data::Dumper::Indent=1;
211     print "# This file is in perl syntax.\n";
212     foreach my $key(sort(keys(%CFG::))) { # See "Symbol Tables" in perlmod(1)
213         if (defined ${$CFG::{$key}}) { print Data::Dumper->Dump([${$CFG::{$key}}], ["*$key"]); }
214         if (        @{$CFG::{$key}}) { print Data::Dumper->Dump([\@{$CFG::{$key}}], ["*$key"]); }
215         if (        %{$CFG::{$key}}) { print Data::Dumper->Dump([\%{$CFG::{$key}}], ["*$key"]); }
216     }
217     print "1;\n";
218     exit;
219 }
220
221 ### Sanitize configuration
222
223 if ($interactive && !-t STDIN) {
224     die("novaboot: Interactive mode not supported when not on terminal");
225 }
226
227 if (defined $config_name_opt && scalar(@ARGV) > 1) { die "You cannot use --name with multiple scripts"; }
228
229 if ($ider) {
230     $iso_image //= ''; # IDE-R needs an ISO image
231     if (!defined $amt) { die "Error: --ider requires --amt"; }
232 }
233
234 # Default options
235 if (defined $serial) {
236     $serial ||= "/dev/ttyUSB0";
237     $ENV{NB_SERIAL} = $serial;
238 }
239 if (defined $grub_config) { $grub_config ||= "menu.lst"; }
240 if (defined $grub2_config) { $grub2_config ||= "grub.cfg"; }
241
242 ## Parse the novaboot script(s)
243 my @scripts;
244 my $file;
245 my $EOF;
246 my $last_fn = '';
247 my ($modules, $variables, $generated, $continuation);
248 my $skip_reading = defined($on_opt) || defined($off_opt);
249 while (!$skip_reading && ($_ = <>)) {
250     if ($ARGV ne $last_fn) { # New script
251         die "Missing EOF in $last_fn" if $file;
252         die "Unfinished line in $last_fn" if $continuation;
253         $last_fn = $ARGV;
254         push @scripts, { 'filename' => $ARGV,
255                          'modules' => $modules = [],
256                          'variables' => $variables = {},
257                          'generated' => $generated = []};
258
259     }
260     chomp();
261     next if /^#/ || /^\s*$/;    # Skip comments and empty lines
262
263     $_ =~ s/^[[:space:]]*// if ($continuation);
264
265     if (/\\$/) {                # Line continuation
266         $continuation .= substr($_, 0, length($_)-1);
267         next;
268     }
269
270     if ($continuation) {        # Last continuation line
271         $_ = $continuation . $_;
272         $continuation = '';
273     }
274
275     foreach my $mod(@scriptmod) { eval $mod; }
276
277     if ($file && $_ eq $EOF) {  # Heredoc end
278         undef $file;
279         next;
280     }
281     if ($file) {                # Heredoc content
282         push @{$file}, "$_\n";
283         next;
284     }
285     if (/^([A-Z_]+)=(.*)$/) {   # Internal variable
286         $$variables{$1} = $2;
287         push(@exiton, $2) if ($1 eq "EXITON");
288         next;
289     }
290     if (s/^load *//) {          # Load line
291         die("novaboot: '$last_fn' line $.: Missing file name\n") unless /^[^ <]+/;
292         if (/^([^ ]*)(.*?)[[:space:]]*<<([^ ]*)$/) { # Heredoc start
293             push @$modules, "$1$2";
294             $file = [];
295             push @$generated, {filename => $1, content => $file};
296             $EOF = $3;
297             next;
298         }
299         if (/^([^ ]*)(.*?)[[:space:]]*< ?(.*)$/) { # Command substitution
300             push @$modules, "$1$2";
301             push @$generated, {filename => $1, command => $3};
302             next;
303         }
304         push @$modules, $_;
305         next;
306     }
307     if (/^run (.*)/) {          # run line
308         push @$generated, {command => $1};
309         next;
310     }
311
312     die("novaboot: Cannot parse script '$last_fn' line $.. Didn't you forget 'load' keyword?\n");
313 }
314 # use Data::Dumper;
315 # print Dumper(\@scripts);
316
317 foreach my $script (@scripts) {
318     $modules = $$script{modules};
319     @$modules[0] =~ s/^[^ ]*/$kernel_opt/ if $kernel_opt;
320     @$modules[0] .= ' ' . join(' ', @append) if @append;
321
322     my $kernel;
323     if (exists $variables->{KERNEL}) {
324         $kernel = $variables->{KERNEL};
325     } else {
326         if ($CFG::hypervisor) {
327             $kernel = $CFG::hypervisor . " ";
328             if (exists $variables->{HYPERVISOR_PARAMS}) {
329                 $kernel .= $variables->{HYPERVISOR_PARAMS};
330             } else {
331                 $kernel .= $CFG::hypervisor_params;
332             }
333         }
334     }
335     @$modules = ($kernel, @$modules) if $kernel;
336     @$modules = (@chainloaders, @$modules);
337     @$modules = ("bin/boot/bender", @$modules) if ($bender || defined $ENV{'NOVABOOT_BENDER'});
338 }
339
340 if ($dump_opt) {
341     foreach my $script (@scripts) {
342         print join("\n", @{$$script{modules}})."\n";
343     }
344     exit(0);
345 }
346
347 ## Helper functions
348
349 sub generate_configs($$$) {
350     my ($base, $generated, $filename) = @_;
351     if ($base) { $base = "$base/"; };
352     foreach my $g(@$generated) {
353       if (exists $$g{content}) {
354         my $config = $$g{content};
355         my $fn = $$g{filename};
356         open(my $f, '>', $fn) || die("$fn: $!");
357         map { s|\brom://([^ ]*)|$rom_prefix$base$1|g; print $f "$_"; } @{$config};
358         close($f);
359         print "novaboot: Created $fn\n";
360       } elsif (exists $$g{command} && ! $no_file_gen) {
361         $ENV{SRCDIR} = dirname(File::Spec->rel2abs( $filename, $invocation_dir ));
362         if (exists $$g{filename}) {
363             system_verbose("( $$g{command} ) > $$g{filename}");
364         } else {
365             system_verbose($$g{command});
366         }
367       }
368     }
369 }
370
371 sub generate_grub_config($$$$;$)
372 {
373     my ($filename, $title, $base, $modules_ref, $preamble) = @_;
374     if ($base) { $base = "$base/"; };
375     open(my $fg, '>', $filename) or die "$filename: $!";
376     print $fg "$preamble\n" if $preamble;
377     print $fg "title $title\n" if $title;
378     #print $fg "root $base\n"; # root doesn't really work for (nd)
379     my $first = 1;
380     foreach (@$modules_ref) {
381         if ($first) {
382             $first = 0;
383             my ($kbin, $kcmd) = split(' ', $_, 2);
384             $kcmd = '' if !defined $kcmd;
385             print $fg "kernel ${base}$kbin $kcmd\n";
386         } else {
387             s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
388             print $fg "module $base$_\n";
389         }
390     }
391     close($fg);
392     print("novaboot: Created $builddir/$filename\n");
393     return $filename;
394 }
395
396 sub generate_syslinux_config($$$$)
397 {
398     my ($filename, $title, $base, $modules_ref) = @_;
399     if ($base && $base !~ /\/$/) { $base = "$base/"; };
400     open(my $fg, '>', $filename) or die "$filename: $!";
401     print $fg "LABEL $title\n";
402     #TODO print $fg "MENU LABEL $human_readable_title\n";
403
404     my ($kbin, $kcmd) = split(' ', @$modules_ref[0], 2);
405
406     if (system("file $kbin|grep 'Linux kernel'") == 0) {
407         my $initrd = @$modules_ref[1];
408         die('To many "load" lines for Linux kernel') if (scalar @$modules_ref > 2);
409         print $fg "LINUX $base$kbin\n";
410         print $fg "APPEND $kcmd\n";
411         print $fg "INITRD $base$initrd\n";
412     } else {
413         print $fg "KERNEL mboot.c32\n";
414         my @append;
415         foreach (@$modules_ref) {
416             s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
417             push @append, "$base$_";
418             print $fg "APPEND ".join(' --- ', @append)."\n";
419         }
420     }
421     #TODO print $fg "TEXT HELP\n";
422     #TODO print $fg "some help here\n";
423     #TODO print $fg "ENDTEXT\n";
424     close($fg);
425     print("novaboot: Created $builddir/$filename\n");
426     return $filename;
427 }
428
429 sub generate_grub2_config($$$$;$$)
430 {
431     my ($filename, $title, $base, $modules_ref, $preamble, $prolog) = @_;
432     if ($base && substr($base,-1,1) ne '/') { $base = "$base/"; };
433     open(my $fg, '>', $filename) or die "$filename: $!";
434     print $fg "$preamble\n" if $preamble;
435     $title ||= 'novaboot';
436     print $fg "menuentry $title {\n";
437     print $fg "$prolog\n" if $prolog;
438     my $first = 1;
439     foreach (@$modules_ref) {
440         if ($first) {
441             $first = 0;
442             my ($kbin, $kcmd) = split(' ', $_, 2);
443             $kcmd = '' if !defined $kcmd;
444             print $fg "  multiboot ${base}$kbin $kcmd\n";
445         } else {
446             my @args = split;
447             # GRUB2 doesn't pass filename in multiboot info so we have to duplicate it here
448             $_ = join(' ', ($args[0], @args));
449             s|\brom://|$rom_prefix|g; # We do not need to translate path for GRUB2
450             print $fg "  module $base$_\n";
451         }
452     }
453     print $fg "}\n";
454     close($fg);
455     print("novaboot: Created $builddir/$filename\n");
456     return $filename;
457 }
458
459 sub generate_pulsar_config($$)
460 {
461     my ($filename, $modules_ref) = @_;
462     open(my $fg, '>', $filename) or die "$filename: $!";
463     print $fg "root $pulsar_root\n" if defined $pulsar_root;
464     my $first = 1;
465     my ($kbin, $kcmd);
466     foreach (@$modules_ref) {
467         if ($first) {
468             $first = 0;
469             ($kbin, $kcmd) = split(' ', $_, 2);
470             $kcmd = '' if !defined $kcmd;
471         } else {
472             my @args = split;
473             s|\brom://|$rom_prefix|g;
474             print $fg "load $_\n";
475         }
476     }
477     # Put kernel as last - this is needed for booting Linux and has no influence on non-Linux OSes
478     print $fg "exec $kbin $kcmd\n";
479     close($fg);
480     print("novaboot: Created $builddir/$filename\n");
481     return $filename;
482 }
483
484 sub shell_cmd_string(@)
485 {
486     return join(' ', map((/^[-_=a-zA-Z0-9\/\.\+]+$/ ? "$_" : "'$_'"), @_));
487 }
488
489 sub exec_verbose(@)
490 {
491     print "novaboot: Running: ".shell_cmd_string(@_)."\n";
492     exec(@_);
493     exit(1); # should not be reached
494 }
495
496 sub system_verbose($)
497 {
498     my $cmd = shift;
499     print "novaboot: Running: $cmd\n";
500     my $ret = system($cmd);
501     if ($ret & 0x007f) { die("Command terminated by a signal"); }
502     if ($ret & 0xff00) {die("Command exit with non-zero exit code"); }
503     if ($ret) { die("Command failure $ret"); }
504 }
505
506 ## WvTest handline
507
508 if (exists $variables->{WVDESC}) {
509     print "Testing \"$variables->{WVDESC}\" in $last_fn:\n";
510 } elsif ($last_fn =~ /\.wv$/) {
511     print "Testing \"all\" in $last_fn:\n";
512 }
513
514 ## Connect to the target and check whether it is not occupied
515
516 # We have to do this before file generation phase, because file
517 # generation is intermixed with file deployment phase and we want to
518 # check whether the target is not used by somebody else before
519 # deploying files. Otherwise, we may rewrite other user's files on a
520 # boot server.
521
522 my $exp; # Expect object to communicate with the target over serial line
523
524 my ($target_reset, $target_power_on, $target_power_off);
525 my ($amt_user, $amt_password, $amt_host, $amt_port);
526
527 if (defined $iprelay) {
528     my $IPRELAY;
529     $iprelay =~ /([.0-9]+)(:([0-9]+))?/;
530     my $addr = $1;
531     my $port = $3 || 23;
532     my $paddr   = sockaddr_in($port, inet_aton($addr));
533     my $proto   = getprotobyname('tcp');
534     socket($IPRELAY, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
535     print "novaboot: Connecting to IP relay... ";
536     connect($IPRELAY, $paddr)    || die "connect: $!";
537     print "done\n";
538     $exp = Expect->init(\*$IPRELAY);
539     $exp->log_stdout(1);
540
541     while (1) {
542         print $exp "\xFF\xF6";  # AYT
543         my $connected = $exp->expect(20, # Timeout in seconds
544                                      '<iprelayd: connected>',
545                                      '-re', '<WEB51 HW[^>]*>');
546         last if $connected;
547     }
548
549     sub relaycmd($$) {
550         my ($relay, $onoff) = @_;
551         die unless ($relay == 1 || $relay == 2);
552
553         my $cmd = ($relay == 1 ? 0x5 : 0x6) | ($onoff ? 0x20 : 0x10);
554         return "\xFF\xFA\x2C\x32".chr($cmd)."\xFF\xF0";
555     }
556
557     sub relayconf($$) {
558         my ($relay, $onoff) = @_;
559         die unless ($relay == 1 || $relay == 2);
560         my $cmd = ($relay == 1 ? 0xdf : 0xbf) | ($onoff ? 0x00 : 0xff);
561         return "\xFF\xFA\x2C\x97".chr($cmd)."\xFF\xF0";
562     }
563
564     sub relay($$;$) {
565         my ($relay, $onoff, $can_giveup) = @_;
566         my $confirmation = '';
567         $exp->log_stdout(0);
568         print $exp relaycmd($relay, $onoff);
569         my $confirmed = $exp->expect(20, # Timeout in seconds
570                                      relayconf($relay, $onoff));
571         if (!$confirmed) {
572             if ($can_giveup) {
573                 print("Relay confirmation timeout - ignoring\n");
574             } else {
575                 die "Relay confirmation timeout";
576             }
577         }
578         $exp->log_stdout(1);
579     }
580
581     $target_reset = sub {
582         relay(2, 1, 1); # Reset the machine
583         usleep(100000);
584         relay(2, 0);
585     };
586
587     $target_power_off = sub {
588         relay(1, 1);            # Press power button
589         usleep(6000000);        # Long press to switch off
590         relay(1, 0);
591     };
592
593     $target_power_on = sub {
594         relay(1, 1);            # Press power button
595         usleep(100000);         # Short press
596         relay(1, 0);
597     };
598 }
599 elsif ($serial) {
600     my $CONN;
601     system_verbose("stty -F $serial $stty");
602     open($CONN, "+<", $serial) || die "open $serial: $!";
603     $exp = Expect->init(\*$CONN);
604 }
605 elsif ($remote_cmd) {
606     print "novaboot: Running: $remote_cmd\n";
607     $exp = Expect->spawn($remote_cmd);
608 }
609 elsif (defined $amt) {
610     require LWP::UserAgent;
611     require LWP::Authen::Digest;
612
613     sub genXML {
614         my ($host, $username, $password, $schema, $className, $pstate) = @_;
615         #AMT numbers for PowerStateChange (MNI => bluescreen on windows;-)
616         my %pstates = ("on"        => 2,
617                        "standby"   => 4,
618                        "hibernate" => 7,
619                        "off"       => 8,
620                        "reset"     => 10,
621                        "MNI"       => 11);
622         return <<END;
623                 <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
624                 <s:Header><a:To>http://$host:16992/wsman</a:To>
625                 <w:ResourceURI s:mustUnderstand="true">$schema</w:ResourceURI>
626                 <a:ReplyTo><a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>
627                 <a:Action s:mustUnderstand="true">$schema$className</a:Action>
628                 <w:MaxEnvelopeSize s:mustUnderstand="true">153600</w:MaxEnvelopeSize>
629                 <a:MessageID>uuid:709072C9-609C-4B43-B301-075004043C7C</a:MessageID>
630                 <w:Locale xml:lang="en-US" s:mustUnderstand="false" />
631                 <w:OperationTimeout>PT60.000S</w:OperationTimeout>
632                 <w:SelectorSet><w:Selector Name="Name">Intel(r) AMT Power Management Service</w:Selector></w:SelectorSet>
633                 </s:Header><s:Body>
634                 <p:RequestPowerStateChange_INPUT xmlns:p="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService">
635                 <p:PowerState>$pstates{$pstate}</p:PowerState>
636                 <p:ManagedElement><a:Address>http://$host:16992/wsman</a:Address>
637                 <a:ReferenceParameters><w:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem</w:ResourceURI>
638                 <w:SelectorSet><w:Selector Name="Name">ManagedSystem</w:Selector></w:SelectorSet>
639                 </a:ReferenceParameters></p:ManagedElement>
640                 </p:RequestPowerStateChange_INPUT>
641                 </s:Body></s:Envelope>
642 END
643     }
644
645     sub sendPOST {
646         my ($host, $username, $password, $content) = @_;
647
648         my $ua = LWP::UserAgent->new();
649         $ua->agent("novaboot");
650
651         my $req = HTTP::Request->new(POST => "http://$host:16992/wsman");
652         my $res = $ua->request($req);
653         die ("Unexpected AMT response: " . $res->status_line) unless $res->code == 401;
654
655         my ($realm) = $res->header("WWW-Authenticate") =~ /Digest realm="(.*?)"/;
656         $ua->credentials("$host:16992", $realm, $username => $password);
657
658         # Create a request
659         $req = HTTP::Request->new(POST => "http://$host:16992/wsman");
660         $req->content_type('application/x-www-form-urlencoded');
661         $req->content($content);
662         $res = $ua->request($req);
663         die ("AMT power change request failed: " . $res->status_line) unless $res->is_success;
664         $res->content() =~ /<g:ReturnValue>(\d+)<\/g:ReturnValue>/;
665         return $1;
666     }
667
668     sub powerChange  {
669         my ($host, $username, $password, $pstate)=@_;
670         my $schema="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService";
671         my $className="/RequestPowerStateChange";
672         my $content = genXML($host, $username, $password ,$schema, $className, $pstate);
673         return sendPOST($host, $username, $password, $content);
674     }
675
676     ($amt_user,$amt_password,$amt_host,$amt_port) = ($amt =~ /(?:(.*?)(?::(.*))?@)?([^:]*)(?::([0-9]*))?/);;
677     $amt_user ||= "admin";
678     $amt_password ||= $ENV{'AMT_PASSWORD'} || die "AMT password not specified";
679     $amt_host || die "AMT host not specified";
680     $amt_port ||= 16994;
681
682
683     $target_power_off = sub {
684         $exp->close();
685         my $result = powerChange($amt_host,$amt_user,$amt_password, "off");
686         die "AMT power off failed (ReturnValue $result)" if $result != 0;
687     };
688
689     $target_power_on = sub {
690         my $result = powerChange($amt_host,$amt_user,$amt_password, "on");
691         die "AMT power on failed (ReturnValue $result)" if $result != 0;
692     };
693
694     $target_reset = sub {
695         my $result = powerChange($amt_host,$amt_user,$amt_password, "reset");
696         if ($result != 0) {
697             print STDERR "Warning: Cannot reset $amt_host, trying power on. ";
698             $result = powerChange($amt_host,$amt_user,$amt_password, "on");
699         }
700         die "AMT reset failed (ReturnValue $result)" if $result != 0;
701     };
702
703     my $cmd = "amtterm -u $amt_user -p $amt_password $amt_host $amt_port";
704     print "novaboot: Running: $cmd\n" =~ s/\Q$amt_password\E/???/r;
705     $exp = Expect->spawn($cmd);
706     $exp->expect(10, "RUN_SOL") || die "Expect for 'RUN_SOL' timed out";
707
708 }
709
710
711 if ($remote_expect) {
712     $exp->expect(10, $remote_expect) || die "Expect for '$remote_expect' timed out";
713 }
714
715 if (defined $reset_cmd) {
716     $target_reset = sub {
717         system_verbose($reset_cmd);
718     };
719 }
720
721 if (defined $on_opt && defined $target_power_on) {
722     &$target_power_on();
723     exit;
724 }
725 if (defined $off_opt && defined $target_power_off) {
726     print "novaboot: Switching the target off...\n";
727     &$target_power_off();
728     exit;
729 }
730
731 $builddir ||= dirname(File::Spec->rel2abs( ${$scripts[0]}{filename})) if scalar @scripts;
732 if (defined $builddir) {
733     chdir($builddir) or die "Can't change directory to $builddir: $!";
734     print "novaboot: Entering directory `$builddir'\n";
735 }
736
737 ## File generation phase
738 my (%files_iso, $menu_iso, $filename);
739 my $config_name = '';
740
741 foreach my $script (@scripts) {
742     $filename = $$script{filename};
743     $modules = $$script{modules};
744     $generated = $$script{generated};
745     $variables = $$script{variables};
746
747     ($config_name = $filename) =~ s#.*/##;
748     $config_name = $config_name_opt if (defined $config_name_opt);
749
750     if (exists $variables->{BUILDDIR}) {
751         $builddir = File::Spec->rel2abs($variables->{BUILDDIR});
752         chdir($builddir) or die "Can't change directory to $builddir: $!";
753         print "novaboot: Entering directory `$builddir'\n";
754     }
755
756     my $prefix;
757     ($prefix = $grub_prefix) =~ s/\$NAME/$config_name/ if defined $grub_prefix;
758     $prefix ||= $builddir;
759     # TODO: use $grub_prefix as first parameter if some switch is given
760     generate_configs('', $generated, $filename);
761
762 ### Generate bootloader configuration files
763     my @bootloader_configs;
764     push @bootloader_configs, generate_grub_config($grub_config, $config_name, $prefix, $modules, $grub_preamble) if (defined $grub_config);
765     push @bootloader_configs, generate_grub2_config($grub2_config, $config_name, $prefix, $modules, $grub_preamble, $grub2_prolog) if (defined $grub2_config);
766     push @bootloader_configs, generate_pulsar_config('config-'.($pulsar||'novaboot'), $modules) if (defined $pulsar);
767
768 ### Run scons or make
769     {
770         my @files = map({ ($file) = m/([^ ]*)/; $file; } @$modules);
771         # Filter-out generated files
772         my @to_build = grep({ my $file = $_; !scalar(grep($file eq ($$_{filename} || ''), @$generated)) } @files);
773
774         system_verbose($scons || $CFG::scons." ".join(" ", @to_build)) if (defined $scons);
775         system_verbose($make  || $CFG::make ." ".join(" ", @to_build)) if (defined $make);
776     }
777
778 ### Copy files (using rsync)
779     if (defined $server && !defined($gen_only)) {
780         (my $real_server = $server) =~ s/\$NAME/$config_name/;
781
782         my ($hostname, $path) = split(":", $real_server, 2);
783         if (! defined $path) {
784             $path = $hostname;
785             $hostname = "";
786         }
787         my $files = join(" ", map({ ($file) = m/([^ ]*)/; $file; } ( @$modules, @bootloader_configs)));
788         map({ my $file = (split)[0]; die "$file: $!" if ! -f $file; } @$modules);
789         my $istty = -t STDOUT && ($ENV{'TERM'} || 'dumb') ne 'dumb';
790         my $progress = $istty ? "--progress" : "";
791         system_verbose("rsync $progress -RLp $rsync_flags $files $real_server");
792         if ($server =~ m|/\$NAME$| && $concat) {
793             my $cmd = join("; ", map { "( cd $path/.. && cat */$_ > $_ )" } @bootloader_configs);
794             system_verbose($hostname ? "ssh $hostname '$cmd'" : $cmd);
795         }
796     }
797
798 ### Prepare ISO image generation
799     if (defined $iso_image) {
800         generate_configs("(cd)", $generated, $filename);
801         my $menu;
802         generate_syslinux_config(\$menu, $config_name, "/", $modules);
803         $menu_iso .= "$menu\n";
804         map { ($file,undef) = split; $files_iso{$file} = 1; } @$modules;
805     }
806 }
807
808 ## Generate ISO image
809 if (defined $iso_image) {
810     system_verbose("mkdir -p isolinux");
811     # FIXME: Does somebody need support for older syslinux (without ldlinux etc.)?
812     system_verbose('cp /usr/lib/ISOLINUX/isolinux.bin /usr/lib/syslinux/modules/bios/mboot.c32 /usr/lib/syslinux/modules/bios/libcom32.c32 /usr/lib/syslinux/modules/bios/menu.c32 /usr/lib/syslinux/modules/bios/ldlinux.c32 isolinux');
813     open(my $fh, ">isolinux/isolinux.cfg");
814     if ($#scripts) {
815         print $fh "TIMEOUT 50\n";
816         print $fh "DEFAULT menu\n";
817     } else {
818         print $fh "DEFAULT $config_name\n";
819     }
820     print $fh "$menu_iso";
821     close($fh);
822
823     my $files = join(" ", map("$_=$_", (keys(%files_iso), 'isolinux/isolinux.bin', 'isolinux/isolinux.cfg', 'isolinux/libcom32.c32', 'isolinux/mboot.c32', 'isolinux/ldlinux.c32', 'isolinux/menu.c32')));
824     $iso_image ||= "$config_name.iso";
825
826     # Note: We use -U flag below to "Allow 'untranslated' filenames,
827     # completely violating the ISO9660 standards". Without this
828     # option, isolinux is not able to read files names for example
829     # bzImage-3.0.
830     system_verbose("$CFG::genisoimage -R -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -hide-rr-moved -U -o $iso_image -graft-points $files");
831     print("ISO image created: $builddir/$iso_image\n");
832 }
833
834 exit(0) if defined $gen_only;
835
836 ## Boot the system using various methods and send serial output to stdout
837
838 if (scalar(@scripts) > 1 && ( defined $dhcp_tftp || defined $serial || defined $iprelay)) {
839     die "You cannot do this with multiple scripts simultaneously";
840 }
841
842 if ($variables->{WVTEST_TIMEOUT}) {
843     print "wvtest: timeout ", $variables->{WVTEST_TIMEOUT}, "\n";
844 }
845
846 sub trim($) {
847     my ($str) = @_;
848     $str =~ s/^\s+|\s+$//g;
849     return $str
850 }
851
852 ### Start in Qemu
853
854 if (defined $qemu) {
855     # Qemu
856     $qemu ||= $variables->{QEMU} || $CFG::qemu;
857     my @qemu_flags = split(" ", $qemu);
858     $qemu = shift(@qemu_flags);
859
860     @qemu_flags = split(/ +/, trim($variables->{QEMU_FLAGS})) if exists $variables->{QEMU_FLAGS};
861     @qemu_flags = split(/ +/, trim($qemu_flags_cmd)) if $qemu_flags_cmd;
862     push(@qemu_flags, split(/ +/, trim($qemu_append || '')));
863
864     if (defined $iso_image) {
865         # Boot NOVA with grub (and test the iso image)
866         push(@qemu_flags, ('-cdrom', $iso_image));
867     } else {
868         # Boot NOVA without GRUB
869
870         # Non-patched qemu doesn't like commas, but NUL can live with pluses instead of commans
871         foreach (@$modules) {s/,/+/g;}
872         generate_configs("", $generated, $filename);
873
874         if (scalar @$modules) {
875             my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
876             $kcmd = '' if !defined $kcmd;
877             my $dtb;
878             @$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
879             my $initrd = join ",", @$modules;
880
881             push(@qemu_flags, ('-kernel', $kbin, '-append', $kcmd));
882             push(@qemu_flags, ('-initrd', $initrd)) if $initrd;
883             push(@qemu_flags, ('-dtb', $dtb)) if $dtb;
884         }
885     }
886     push(@qemu_flags,  qw(-serial stdio)); # Redirect serial output (for collecting test restuls)
887     unshift(@qemu_flags, ('-name', $config_name));
888     print "novaboot: Running: ".shell_cmd_string($qemu, @qemu_flags)."\n";
889     $exp = Expect->spawn(($qemu, @qemu_flags)) || die("exec() failed: $!");
890 }
891
892 ### Local DHCPD and TFTPD
893
894 my ($dhcpd_pid, $tftpd_pid);
895
896 $tftp=1 if $tftp_port;
897
898 if (defined $dhcp_tftp)
899 {
900     generate_configs("(nd)", $generated, $filename);
901     system_verbose('mkdir -p tftpboot');
902     generate_grub_config("tftpboot/os-menu.lst", $config_name, "(nd)", \@$modules, "timeout 0");
903     open(my $fh, '>', 'dhcpd.conf');
904     my $mac = `cat /sys/class/net/eth0/address`;
905     chomp $mac;
906     print $fh "subnet 10.23.23.0 netmask 255.255.255.0 {
907                       range 10.23.23.10 10.23.23.100;
908                       filename \"bin/boot/grub/pxegrub.pxe\";
909                       next-server 10.23.23.1;
910 }
911 host server {
912         hardware ethernet $mac;
913         fixed-address 10.23.23.1;
914 }";
915     close($fh);
916     system_verbose("sudo ip a add 10.23.23.1/24 dev eth0;
917             sudo ip l set dev eth0 up;
918             sudo touch dhcpd.leases");
919
920     # We run servers by forking ourselves, because the servers end up
921     # in our process group and get killed by signals sent to the
922     # process group (e.g. Ctrl-C on terminal).
923     $dhcpd_pid = fork();
924     exec_verbose("sudo dhcpd -d -cf dhcpd.conf -lf dhcpd.leases -pf dhcpd.pid") if ($dhcpd_pid == 0);
925 }
926
927 if (defined $dhcp_tftp || defined $tftp) {
928     $tftp_port ||= 69;
929     # Unfortunately, tftpd requires root privileges even with
930     # non-privileged (>1023) port due to initgroups().
931     system_verbose("sudo in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid  --address :$tftp_port $builddir");
932
933     # Kill server when we die
934     $SIG{__DIE__} = sub { system_verbose('sudo pkill --pidfile=dhcpd.pid') if (defined $dhcp_tftp);
935                           system_verbose('sudo pkill --pidfile=tftpd.pid'); };
936
937     # We have to kill tftpd explicitely, because it is not in our process group
938     $SIG{INT} = sub { system_verbose('sudo pkill --pidfile=tftpd.pid'); exit(0); };
939 }
940
941 ### AMT IDE-R
942 if (defined $ider) {
943     my $ider_cmd= "amtider -c $iso_image -u $amt_user -p $amt_password $amt_host $amt_port"  ;
944     print "novaboot: Running: $ider_cmd\n" =~ s/\Q$amt_password\E/???/r;
945     my $ider_pid = fork();
946     if ($ider_pid == 0) {
947         exec($ider_cmd);
948         die "IDE redirection failed";
949     }
950     # FIXME: This collides with --tftp option. Hopefully, nobody needs
951     # to use both simultaneously.
952     $SIG{__DIE__} = sub { system_verbose('kill $ider_pid'); };
953 }
954
955 ### Reset target (IP relay, AMT, ...)
956
957 if (defined $target_reset) {
958     print "novaboot: Reseting the test box... ";
959     &$target_reset();
960     print "done\n";
961 }
962
963 ### U-boot conversation
964 if (defined $uboot) {
965     my $uboot_prompt = $uboot || '=> ';
966     print "novaboot: Waiting for uBoot prompt...\n";
967     $exp->log_stdout(1);
968     #$exp->exp_internal(1);
969     $exp->expect(20,
970                  [qr/Hit any key to stop autoboot:/, sub { $exp->send("\n"); exp_continue; }],
971                  $uboot_prompt) || die "No uBoot prompt deteceted";
972     while (@uboot_init) {
973         my $cmd = shift @uboot_init;
974         $exp->send("$cmd\n");
975         $exp->expect(10, $uboot_prompt) || die "uBoot prompt timeout";
976     }
977
978     # Boot the system if there are some load lines in the script
979     if (scalar(@$modules) > 0) {
980         my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
981         my $dtb;
982         @$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
983         my $initrd = shift @$modules;
984
985         my $kern_addr = '800000';
986         my $initrd_addr = '-';
987         my $dtb_addr = '';
988
989         $exp->send("tftp $kern_addr $kbin\n");
990         $exp->expect(10,
991                      [qr/#/, sub { exp_continue; }],
992                      $uboot_prompt) || die "Kernel load failed";
993         if (defined $dtb) {
994             $dtb_addr = '7f0000';
995             $exp->send("tftp $dtb_addr $dtb\n");
996             $exp->expect(10,
997                          [qr/#/, sub { exp_continue; }],
998                          $uboot_prompt) || die "Device tree load failed";
999         }
1000         if (defined $initrd) {
1001             $initrd_addr = 'b00000';
1002             $exp->send("tftp $initrd_addr $initrd\n");
1003             $exp->expect(10,
1004                          [qr/#/, sub { exp_continue; }],
1005                          $uboot_prompt) || die "Initrd load failed";
1006         }
1007         $exp->send("set bootargs '$kcmd'\n");
1008         $exp->expect(5, $uboot_prompt)  || die "uBoot prompt timeout";
1009         $exp->send("bootm $kern_addr $initrd_addr $dtb_addr\n");
1010         $exp->expect(5, "\n")  || die "uBoot command timeout";
1011     }
1012 }
1013
1014 ### Serial line interaction
1015 if (defined $exp) {
1016     # Serial line of the target is available
1017     my $interrupt = 'Ctrl-C';
1018     if ($interactive && !@exiton) {
1019         $interrupt = '"~~."';
1020     }
1021     my $note = (-t STDIN) ? '' : '- only target->host ';
1022     print "novaboot: Serial line interaction $note(press $interrupt to interrupt)...\n";
1023     $exp->log_stdout(1);
1024     if (@exiton) {
1025         $exp->expect(undef, @expect_raw, @exiton);
1026     } else {
1027         my @inputs = ($exp);
1028         if (-t STDIN) { # Set up bi-directional communication if we run on terminal
1029             my $infile = new IO::File;
1030             $infile->IO::File::fdopen(*STDIN,'r');
1031             my $in_object = Expect->exp_init($infile);
1032             $in_object->set_group($exp);
1033
1034             if ($interactive) {
1035                 $in_object->set_seq('~~\.', sub { print "novaboot: Escape sequence detected\r\n"; undef; });
1036                 $in_object->manual_stty(0);       # Use raw terminal mode
1037             } else {
1038                 $in_object->manual_stty(1);       # Do not modify terminal settings
1039             }
1040             push(@inputs, $in_object);
1041         }
1042         #use Data::Dumper;
1043         #print Dumper(\@expect_raw);
1044         $exp->expect(undef, @expect_raw) if @expect_raw;
1045         Expect::interconnect(@inputs) unless defined($exp->exitstatus);
1046     }
1047 }
1048
1049 ## Kill dhcpc or tftpd
1050 if (defined $dhcp_tftp || defined $tftp) {
1051     die("novaboot: This should kill servers on background\n");
1052 }
1053
1054 ## Documentation
1055
1056 =head1 NAME
1057
1058 novaboot - A tool for booting various operating systems on various hardware or in qemu
1059
1060 =head1 SYNOPSIS
1061
1062 B<novaboot> --help
1063
1064 B<novaboot> [option]... [--] script...
1065
1066 B<./script> [option]...
1067
1068 =head1 DESCRIPTION
1069
1070 This program makes booting of an operating system (e.g. NOVA or Linux)
1071 as simple as running a local program. It facilitates booting on local
1072 or remote hosts or in emulators such as qemu. Novaboot operation is
1073 controlled by command line options and by a so called novaboot script,
1074 which can be thought as a generalization of bootloader configuration
1075 files (see L</"NOVABOOT SCRIPT SYNTAX">). Based on this input,
1076 novaboot setups everything for the target host to boot the desired
1077 configuration, i.e. it generates the bootloader configuration file in
1078 the proper format, deploy the binaries and other needed files to
1079 required locations, perhaps on a remote boot server and reset the
1080 target host. Finally, target host's serial output is redirected to
1081 standard output if that is possible.
1082
1083 Typical way of using novaboot is to make the novaboot script
1084 executable and set its first line to I<#!/usr/bin/env novaboot>. Then,
1085 booting a particular OS configuration becomes the same as executing a
1086 local program - the novaboot script.
1087
1088 For example, with C<novaboot> you can:
1089
1090 =over 3
1091
1092 =item 1.
1093
1094 Run an OS in Qemu. This is the default action when no other action is
1095 specified by command line switches. Thus running C<novaboot ./script>
1096 (or C<./script> as described above) will run Qemu and make it boot the
1097 configuration specified in the F<script>.
1098
1099 =item 2.
1100
1101 Create a bootloader configuration file (currently supported
1102 bootloaders are GRUB, GRUB2, Pulsar and U-Boot) and copy it with all
1103 other files needed for booting to a remote boot server.
1104
1105  ./script --server=192.168.1.1:/tftp --iprelay=192.168.1.2
1106
1107 This command copies files to the TFTP server and uses
1108 TCP/IP-controlled relay to reset the target host and receive its
1109 serial output.
1110
1111 =item 3.
1112
1113 Run DHCP and TFTP server on developer's machine to PXE-boot the target
1114 host from it. E.g.
1115
1116  ./script --dhcp-tftp
1117
1118 When a PXE-bootable machine is connected via Ethernet to developer's
1119 machine, it will boot the configuration described in I<script>.
1120
1121 =item 4.
1122
1123 Create bootable ISO images. E.g.
1124
1125  novaboot --iso -- script1 script2
1126
1127 The created ISO image will have GRUB bootloader installed on it and
1128 the boot menu will allow selecting between I<script1> and I<script2>
1129 configurations.
1130
1131 =back
1132
1133 Note that the options needed for a specific target can be stored in a
1134 L</"CONFIGURATION FILE">. Then it is sufficient to use only the B<-t>
1135 option to specify the name of the target.
1136
1137 =head1 PHASES AND OPTIONS
1138
1139 Novaboot performs its work in several phases. Each phase can be
1140 influenced by several options, certain phases can be skipped. The list
1141 of phases (in the execution order) and the corresponding options
1142 follow.
1143
1144 =head2 Configuration reading phase
1145
1146 After starting, novaboot reads configuration files. By default, it
1147 searches for files named F<.novaboot> starting from the directory of
1148 the novaboot script (or working directory, see bellow) and continuing
1149 upwards up to the root directory. The configuration files are read in
1150 order from the root directory downwards with latter files overriding
1151 settings from the former ones.
1152
1153 In certain cases, the location of the novaboot script cannot be
1154 determined in this early phase. This happens either when the script is
1155 read from the standard input or when novaboot is invoked explicitly
1156 and options precede the script name, as in the example L</"4."> above.
1157 In this case the current working directory is used as a starting point
1158 for configuration file search.
1159
1160 =over 8
1161
1162 =item -c, --config=I<filename>
1163
1164 Use the specified configuration file instead of the default one(s).
1165
1166 =back
1167
1168 =head2 Command line processing phase
1169
1170 =over 8
1171
1172 =item --dump-config
1173
1174 Dump the current configuration to stdout end exits. Useful as an
1175 initial template for a configuration file.
1176
1177 =item -h, --help
1178
1179 Print short (B<-h>) or long (B<--help>) help.
1180
1181 =item -t, --target=I<target>
1182
1183 This option serves as a user configurable shortcut for other novaboot
1184 options. The effect of this option is the same as the options stored
1185 in the C<%targets> configuration variable under key I<target>. See
1186 also L</"CONFIGURATION FILE">.
1187
1188 =back
1189
1190 =head2 Script preprocessing phase
1191
1192 This phases allows to modify the parsed novaboot script before it is
1193 used in the later phases.
1194
1195 =over 8
1196
1197 =item -a, --append=I<parameters>
1198
1199 Append a string to the first C<load> line in the novaboot script. This
1200 can be used to append parameters to the kernel's or root task's
1201 command line. Can appear multiple times.
1202
1203 =item -b, --bender
1204
1205 Use F<bender> chainloader. Bender scans the PCI bus for PCI serial
1206 ports and stores the information about them in the BIOS data area for
1207 use by the kernel.
1208
1209 =item --chainloader=I<chainloader>
1210
1211 Chainloader that is loaded before the kernel and other files specified
1212 in the novaboot script. E.g. 'bin/boot/bender promisc'.
1213
1214 =item --dump
1215
1216 Print the modules to boot and their parameters after this phase
1217 finishes. Then exit. This is useful for seeing the effect of other
1218 options in this section.
1219
1220 =item -k, --kernel=F<file>
1221
1222 Replace the first word on the first C<load> line in the novaboot
1223 script with F<file>.
1224
1225 =item --scriptmod=I<perl expression>
1226
1227 When novaboot script is read, I<perl expression> is executed for every
1228 line (in $_ variable). For example, C<novaboot
1229 --scriptmod=s/sigma0/omega6/g> replaces every occurrence of I<sigma0>
1230 in the script with I<omega6>.
1231
1232 When this option is present, it overrides I<$script_modifier> variable
1233 from the configuration file, which has the same effect. If this option
1234 is given multiple times all expressions are evaluated in the command
1235 line order.
1236
1237 =back
1238
1239 =head2 File generation phase
1240
1241 In this phase, files needed for booting are generated in a so called
1242 I<build directory> (see L</--build-dir>). In most cases configuration
1243 for a bootloader is generated automatically by novaboot. It is also
1244 possible to generate other files using I<heredoc> or I<"<"> syntax in
1245 novaboot scripts. Finally, binaries can be generated in this phases by
1246 running C<scons> or C<make>.
1247
1248 =over 8
1249
1250 =item --build-dir=I<directory>
1251
1252 Overrides the default build directory location.
1253
1254 The default build directory location is determined as follows: If the
1255 configuration file defines the C<$builddir> variable, its value is
1256 used. Otherwise, it is the directory that contains the first processed
1257 novaboot script.
1258
1259 See also L</BUILDDIR> variable.
1260
1261 =item -g, --grub[=I<filename>]
1262
1263 Generates grub bootloader menu file. If the I<filename> is not
1264 specified, F<menu.lst> is used. The I<filename> is relative to the
1265 build directory (see B<--build-dir>).
1266
1267 =item --grub-preamble=I<prefix>
1268
1269 Specifies the I<preable> that is at the beginning of the generated
1270 GRUB or GRUB2 config files. This is useful for specifying GRUB's
1271 timeout.
1272
1273 =item --grub-prefix=I<prefix>
1274
1275 Specifies I<prefix> that is put in front of every file name in GRUB's
1276 F<menu.lst>. The default value is the absolute path to the build directory.
1277
1278 If the I<prefix> contains string $NAME, it will be replaced with the
1279 name of the novaboot script (see also B<--name>).
1280
1281 =item --grub2[=I<filename>]
1282
1283 Generate GRUB2 menuentry in I<filename>. If I<filename> is not
1284 specified F<grub.cfg> is used. The content of the menuentry can be
1285 customized with B<--grub-preable>, B<--grub2-prolog> or
1286 B<--grub_prefix> options.
1287
1288 In order to use the the generated menuentry on your development
1289 machine that uses GRUB2, append the following snippet to
1290 F</etc/grub.d/40_custom> file and regenerate your grub configuration,
1291 i.e. run update-grub on Debian/Ubuntu.
1292
1293   if [ -f /path/to/nul/build/grub.cfg ]; then
1294     source /path/to/nul/build/grub.cfg
1295   fi
1296
1297 =item --grub2-prolog=I<prolog>
1298
1299 Specifies text I<preable> that is put at the beginning of the entry
1300 GRUB2 entry.
1301
1302 =item -m, --make[=make command]
1303
1304 Runs C<make> to build files that are not generated by novaboot itself.
1305
1306 =item --name=I<string>
1307
1308 Use the name I<string> instead of the name of the novaboot script.
1309 This name is used for things like a title of grub menu or for the
1310 server directory where the boot files are copied to.
1311
1312 =item --no-file-gen
1313
1314 Do not run external commands to generate files (i.e. "<" syntax and
1315 C<run> keyword). This switch does not influence generation of files
1316 specified with "<<WORD" syntax.
1317
1318 =item -p, --pulsar[=mac]
1319
1320 Generates pulsar bootloader configuration file named F<config-I<mac>>
1321 The I<mac> string is typically a MAC address and defaults to
1322 I<novaboot>.
1323
1324 =item --scons[=scons command]
1325
1326 Runs C<scons> to build files that are not generated by novaboot
1327 itself.
1328
1329 =item --strip-rom
1330
1331 Strip I<rom://> prefix from command lines and generated config files.
1332 The I<rom://> prefix is used by NUL. For NRE, it has to be stripped.
1333
1334 =item --gen-only
1335
1336 Exit novaboot after file generation phase.
1337
1338 =back
1339
1340 =head2 Target connection check
1341
1342 If supported by the target, the connection to it is made and it is
1343 checked whether the target is not occupied by another novaboot
1344 user/instance.
1345
1346 =over 8
1347
1348 =item --amt=I<"[user[:password]@]host[:port]>
1349
1350 Use Intel AMT technology to control the target machine. WS management
1351 is used to powercycle it and Serial-Over-Lan (SOL) for input/output.
1352 The hostname or (IP address) is given by the I<host> parameter. If
1353 I<password> is not specified, environment variable AMT_PASSWORD is
1354 used. The I<port> specifies a TCP port for SOL. If not specified, the
1355 default is 16992. Default I<user> is admin.
1356
1357 =item --ider
1358
1359 Use Intel AMT technology for IDE redirection. This allows the target
1360 machine to boot from nonvaboot created ISO image.
1361
1362 The experimental I<amtider> utility needed by this option can be
1363 obtained from https://github.com/wentasah/amtterm.
1364
1365 =item --iprelay=I<addr[:port]>
1366
1367 Use TCP/IP relay and serial port to access the target's serial port
1368 and powercycle it. The IP address of the relay is given by I<addr>
1369 parameter. If I<port> is not specified, it default to 23.
1370
1371 Note: This option is supposed to work with HWG-ER02a IP relays.
1372
1373 =item -s, --serial[=device]
1374
1375 Target's serial line is connected to host's serial line (device). The
1376 default value for device is F</dev/ttyUSB0>.
1377
1378 The value of this option is exported in NB_NOVABOOT environment
1379 variable to all subprocesses run by C<novaboot>.
1380
1381 =item --stty=I<settings>
1382
1383 Specifies settings passed to C<stty> invoked on the serial line
1384 specified with B<--serial> option. If this option is not given,
1385 C<stty> is called with C<raw -crtscts -onlcr 115200> settings.
1386
1387 =item --remote-cmd=I<cmd>
1388
1389 Command that mediates connection to the target's serial line. For
1390 example C<ssh server 'cu -l /dev/ttyS0'>.
1391
1392 =item --remote-expect=I<string>
1393
1394 Wait for reception of I<string> after establishing the the remote
1395 connection before continuing.
1396
1397
1398 =back
1399
1400 =head2 File deployment phase
1401
1402 In some setups, it is necessary to copy the files needed for booting
1403 to a particular location, e.g. to a TFTP boot server or to the
1404 F</boot> partition.
1405
1406 =over 8
1407
1408 =item -d, --dhcp-tftp
1409
1410 Turns your workstation into a DHCP and TFTP server so that the OS can
1411 be booted via PXE BIOS (or similar mechanism) on the test machine
1412 directly connected by a plain Ethernet cable to your workstation.
1413
1414 The DHCP and TFTP servers requires root privileges and C<novaboot>
1415 uses C<sudo> command to obtain those. You can put the following to
1416 I</etc/sudoers> to allow running the necessary commands without asking
1417 for password.
1418
1419  Cmnd_Alias NOVABOOT = /bin/ip a add 10.23.23.1/24 dev eth0, /bin/ip l set dev eth0 up, /usr/sbin/dhcpd -d -cf dhcpd.conf -lf dhcpd.leases -pf dhcpd.pid, /usr/sbin/in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid *, /usr/bin/touch dhcpd.leases, /usr/bin/pkill --pidfile=dhcpd.pid, /usr/bin/pkill --pidfile=tftpd.pid
1420  your_login ALL=NOPASSWD: NOVABOOT
1421
1422 =item --tftp
1423
1424 Starts a TFTP server on your workstation. This is similar to
1425 B<--dhcp-tftp> except that DHCP server is not started.
1426
1427 The TFTP server require root privileges and C<novaboot> uses C<sudo>
1428 command to obtain those. You can put the following to I</etc/sudoers>
1429 to allow running the necessary commands without asking for password.
1430
1431  Cmnd_Alias NOVABOOT =  /usr/sbin/in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid *, /usr/bin/pkill --pidfile=tftpd.pid
1432  your_login ALL=NOPASSWD: NOVABOOT
1433
1434 =item --tftp-port=I<port>
1435
1436 Port to run the TFTP server on. Implies B<--tftp>.
1437
1438 =item --iso[=filename]
1439
1440 Generates the ISO image that boots NOVA system via GRUB. If no filename
1441 is given, the image is stored under I<NAME>.iso, where I<NAME> is the name
1442 of the novaboot script (see also B<--name>).
1443
1444 =item --server[=[[user@]server:]path]
1445
1446 Copy all files needed for booting to another location (implies B<-g>
1447 unless B<--grub2> is given). The files will be copied (by B<rsync>
1448 tool) to the directory I<path>. If the I<path> contains string $NAME,
1449 it will be replaced with the name of the novaboot script (see also
1450 B<--name>).
1451
1452 =item --concat
1453
1454 If B<--server> is used and its value ends with $NAME, then after
1455 copying the files, a new bootloader configuration file (e.g. menu.lst)
1456 is created at I<path-wo-name>, i.e. the path specified by B<--server>
1457 with $NAME part removed. The content of the file is created by
1458 concatenating all files of the same name from all subdirectories of
1459 I<path-wo-name> found on the "server".
1460
1461 =item --rsync-flags=I<flags>
1462
1463 Specifies which I<flags> are appended to F<rsync> command line when
1464 copying files as a result of I<--server> option.
1465
1466 =back
1467
1468 =head2 Target power-on and reset phase
1469
1470 =over 8
1471
1472 =item --on, --off
1473
1474 Switch on/off the target machine and exit. The script (if any) is
1475 completely ignored. Currently it works only with B<--iprelay> or
1476 B<--amt>.
1477
1478 =item -Q, --qemu[=I<qemu-binary>]
1479
1480 Boot the configuration in qemu. Optionally, the name of qemu binary
1481 can be specified as a parameter.
1482
1483 =item --qemu-append=I<flags>
1484
1485 Append I<flags> to the default qemu flags (QEMU_FLAGS variable or
1486 C<-cpu coreduo -smp 2>).
1487
1488 =item -q, --qemu-flags=I<flags>
1489
1490 Replace the default qemu flags (QEMU_FLAGS variable or C<-cpu coreduo
1491 -smp 2>) with I<flags> specified here.
1492
1493 =item --reset-cmd=I<cmd>
1494
1495 Command that resets the target.
1496
1497 =back
1498
1499 =head2 Interaction with the bootloader on the target
1500
1501 =over 8
1502
1503 =item --uboot[=I<prompt>]
1504
1505 Interact with uBoot bootloader to boot the thing described in the
1506 novaboot script. I<prompt> specifies the U-Boot's prompt (default is
1507 "=> ", other common prompts are "U-Boot> " or "U-Boot# ").
1508 Implementation of this option is currently tied to a particular board
1509 that we use. It may be subject to changes in the future!
1510
1511 =item --uboot-init
1512
1513 Command(s) to send the U-Boot bootloader before loading the images and
1514 booting them. This option can be given multiple times. After sending
1515 commands from each option novaboot waits for U-Boot I<prompt>.
1516
1517 =back
1518
1519 =head2 Target interaction phase
1520
1521 In this phase, target's serial output is redirected to stdout and if
1522 stdin is a TTY, it is redirected to the target's serial input allowing
1523 interactive work with the target.
1524
1525 =over 8
1526
1527 =item --exiton=I<string>
1528
1529 When I<string> is sent by the target, novaboot exits. This option can
1530 be specified multiple times.
1531
1532 If I<string> is C<-re>, then the next B<--exiton>'s I<string> is
1533 treated as regular expression. For example:
1534
1535     --exiton -re --exiton 'error:.*failed'
1536
1537 =item -i, --interactive
1538
1539 Setup things for interactive use of target. Your terminal will be
1540 switched to raw mode. In raw mode, your system does not process input
1541 in any way (no echoing of entered characters, no interpretation
1542 special characters). This, among others, means that Ctrl-C is passed
1543 to the target and does no longer interrupt novaboot. Use "~~."
1544 sequence to exit novaboot.
1545
1546 =item --expect=I<string>
1547
1548 When I<string> is received from the target, send the string specified
1549 with the subsequent B<--send*> option to the target.
1550
1551 =item --expect-re=I<regex>
1552
1553 When target's output matches regular expression I<regex>, send the
1554 string specified with the subsequent B<--send*> option to the target.
1555
1556 =item --expect-raw=I<perl-code>
1557
1558 Provides direct control over Perl's Expect module.
1559
1560 =item --send=I<string>
1561
1562 Send I<string> to the target after the previously specified
1563 B<--expect*> was matched in the target's output. The I<string> may
1564 contain escape sequences such as "\n".
1565
1566 Note that I<string> is actually interpreted by Perl, so it can contain
1567 much more that escape sequences. This behavior may change in the
1568 future.
1569
1570 Example: C<--expect='login: ' --send='root\n'>
1571
1572 =item --sendcont=I<string>
1573
1574 Similar to B<--send> but continue expecting more input.
1575
1576 Example: C<--expect='Continue?' --sendcont='yes\n'>
1577
1578 =back
1579
1580 =head1 NOVABOOT SCRIPT SYNTAX
1581
1582 The syntax tries to mimic POSIX shell syntax. The syntax is defined
1583 with the following rules.
1584
1585 Lines starting with "#" and empty lines are ignored.
1586
1587 Lines that end with "\" are concatenated with the following line after
1588 removal of the final "\" and leading whitespace of the following line.
1589
1590 Lines of the form I<VARIABLE=...> (i.e. matching '^[A-Z_]+=' regular
1591 expression) assign values to internal variables. See L</VARIABLES>
1592 section.
1593
1594 Lines starting with C<load> keyword represent modules to boot. The
1595 word after C<load> is a file name (relative to the build directory
1596 (see B<--build-dir>) of the module to load and the remaining words are
1597 passed to it as the command line parameters.
1598
1599 When the C<load> line ends with "<<WORD" then the subsequent lines
1600 until the line containing solely WORD are copied literally to the file
1601 named on that line. This is similar to shell's heredoc feature.
1602
1603 When the C<load> line ends with "< CMD" then command CMD is executed
1604 with F</bin/sh> and its standard output is stored in the file named on
1605 that line. The SRCDIR variable in CMD's environment is set to the
1606 absolute path of the directory containing the interpreted novaboot
1607 script.
1608
1609 Lines starting with C<run> keyword contain shell commands that are run
1610 during file generation phase. This is the same as the "< CMD" syntax
1611 for C<load> keyboard except that the command's output is not
1612 redirected to a file. The ordering of commands is the same as they
1613 appear in the novaboot script.
1614
1615 Example (Linux):
1616
1617   #!/usr/bin/env novaboot
1618   load bzImage console=ttyS0,115200
1619   run  make -C buildroot
1620   load rootfs.cpio < gen_cpio buildroot/images/rootfs.cpio "myapp->/etc/init.d/S99myapp"
1621
1622 Example (NOVA User Land - NUL):
1623
1624   #!/usr/bin/env novaboot
1625   WVDESC=Example program
1626   load bin/apps/sigma0.nul S0_DEFAULT script_start:1,1 \
1627                            verbose hostkeyb:0,0x60,1,12,2
1628   load bin/apps/hello.nul
1629   load hello.nulconfig <<EOF
1630   sigma0::mem:16 name::/s0/log name::/s0/timer name::/s0/fs/rom ||
1631   rom://bin/apps/hello.nul
1632   EOF
1633
1634 This example will load three modules: F<sigma0.nul>, F<hello.nul> and
1635 F<hello.nulconfig>. sigma0 receives some command line parameters and
1636 F<hello.nulconfig> file is generated on the fly from the lines between
1637 C<<<EOF> and C<EOF>.
1638
1639 =head2 VARIABLES
1640
1641 The following variables are interpreted in the novaboot script:
1642
1643 =over 8
1644
1645 =item BUILDDIR
1646
1647 Novaboot chdir()s to this directory before file generation phase. The
1648 directory name specified here is relative to the build directory
1649 specified by other means (see L</--build-dir>).
1650
1651 =item EXITON
1652
1653 Assigning this variable has the same effect as specifying L</--exiton>
1654 option.
1655
1656 =item HYPERVISOR_PARAMS
1657
1658 Parameters passed to hypervisor. The default value is "serial", unless
1659 overridden in configuration file.
1660
1661 =item KERNEL
1662
1663 The kernel to use instead of the hypervisor specified in the
1664 configuration file with the C<$hypervisor> variable. The value should
1665 contain the name of the kernel image as well as its command line
1666 parameters. If this variable is defined and non-empty, the variable
1667 HYPERVISOR_PARAMS is not used.
1668
1669 =item QEMU
1670
1671 Use a specific qemu binary (can be overridden with B<-Q>) and flags
1672 when booting this script under qemu. If QEMU_FLAGS variable is also
1673 specified flags specified in QEMU variable are replaced by those in
1674 QEMU_FLAGS.
1675
1676 =item QEMU_FLAGS
1677
1678 Use specific qemu flags (can be overridden with B<-q>).
1679
1680 =item WVDESC
1681
1682 Description of the wvtest-compliant program.
1683
1684 =item WVTEST_TIMEOUT
1685
1686 The timeout in seconds for WvTest harness. If no complete line appears
1687 in the test output within the time specified here, the test fails. It
1688 is necessary to specify this for long running tests that produce no
1689 intermediate output.
1690
1691 =back
1692
1693 =head1 CONFIGURATION FILE
1694
1695 Novaboot can read its configuration from one or more files. By
1696 default, novaboot looks for files named F<.novaboot> as described in
1697 L</Configuration reading phase>. Alternatively, its location can be
1698 specified with the B<-c> switch or with the NOVABOOT_CONFIG
1699 environment variable. The configuration file has perl syntax and
1700 should set values of certain Perl variables. The current configuration
1701 can be dumped with the B<--dump-config> switch. Some configuration
1702 variables can be overridden by environment variables (see below) or by
1703 command line switches.
1704
1705 Supported configuration variables include:
1706
1707 =over 8
1708
1709 =item $builddir
1710
1711 Build directory location relative to the location of the configuration
1712 file.
1713
1714 =item $default_target
1715
1716 Default target (see below) to use when no target is explicitly
1717 specified on command line with the B<--target> option.
1718
1719 =item %targets
1720
1721 Hash of shortcuts to be used with the B<--target> option. If the hash
1722 contains, for instance, the following pair of values
1723
1724  'mybox' => '--server=boot:/tftproot --serial=/dev/ttyUSB0 --grub',
1725
1726 then the following two commands are equivalent:
1727
1728  ./script --server=boot:/tftproot --serial=/dev/ttyUSB0 --grub
1729  ./script -t mybox
1730
1731 =back
1732
1733 =head1 ENVIRONMENT VARIABLES
1734
1735 Some options can be specified not only via config file or command line
1736 but also through environment variables. Environment variables override
1737 the values from configuration file and command line parameters
1738 override the environment variables.
1739
1740 =over 8
1741
1742 =item NOVABOOT_CONFIG
1743
1744 Name of the novaboot configuration file to use instead of the default
1745 one(s).
1746
1747 =item NOVABOOT_BENDER
1748
1749 Defining this variable has the same meaning as B<--bender> option.
1750
1751 =back
1752
1753 =head1 AUTHORS
1754
1755 Michal Sojka <sojka@os.inf.tu-dresden.de>