forked from wentasah/novaboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
novaboot
executable file
·1697 lines (1336 loc) · 54.4 KB
/
novaboot
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
use strict;
use warnings;
use warnings (exists $ENV{NOVABOOT_TEST} ? (FATAL => 'all') : ());
use Getopt::Long qw(GetOptionsFromString);
use Pod::Usage;
use File::Basename;
use File::Spec;
use IO::Handle;
use Time::HiRes("usleep");
use Socket;
use FileHandle;
use IPC::Open2;
use POSIX qw(:errno_h);
use Cwd qw(getcwd abs_path);
use Expect;
# always flush
$| = 1;
my $invocation_dir = $ENV{PWD} || getcwd();
## Configuration file handling
# Default configuration
$CFG::hypervisor = "";
$CFG::hypervisor_params = "serial";
$CFG::genisoimage = "genisoimage";
$CFG::qemu = 'qemu-system-i386 -cpu coreduo -smp 2';
$CFG::default_target = 'qemu';
%CFG::targets = (
'qemu' => '--qemu',
"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',
"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',
"localhost" => '--scriptmod=s/console=tty[A-Z0-9,]+// --server=/boot/novaboot/$NAME --grub2 --grub-prefix=/boot/novaboot/$NAME --grub2-prolog=" set root=\'(hd0,msdos1)\'"',
"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\""',
"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"',
);
chomp(my $nproc = `nproc`);
$CFG::scons = "scons -j$nproc";
$CFG::make = "make -j$nproc";
my $builddir;
sub read_config($) {
my ($cfg) = @_;
{
package CFG; # Put config data into a separate namespace
my $rc = do($cfg);
# Check for errors
if ($@) {
die("ERROR: Failure compiling '$cfg' - $@");
} elsif (! defined($rc)) {
die("ERROR: Failure reading '$cfg' - $!");
} elsif (! $rc) {
die("ERROR: Failure processing '$cfg'");
}
}
$builddir = File::Spec->rel2abs($CFG::builddir, dirname($cfg)) if defined $CFG::builddir;
print STDERR "novaboot: Read $cfg\n";
}
my @cfgs;
{
# We don't use $0 here, because it points to the novaboot itself and
# not to the novaboot script. The problem with this approach is that
# when a script is run as "novaboot <options> <script>" then $ARGV[0]
# contains the first option. Hence the -f check.
my $dir = File::Spec->rel2abs($ARGV[0] && -f $ARGV[0] ? dirname($ARGV[0]) : '', $invocation_dir);
while ((-d $dir || -l $dir ) && $dir ne "/") {
push @cfgs, "$dir/.novaboot" if -r "$dir/.novaboot";
my @dirs = File::Spec->splitdir($dir);
$dir = File::Spec->catdir(@dirs[0..$#dirs-1]);
}
}
my $cfg = $ENV{'NOVABOOT_CONFIG'};
Getopt::Long::Configure(qw/no_ignore_case pass_through/);
GetOptions ("config|c=s" => \$cfg);
read_config($_) foreach $cfg or reverse @cfgs;
## Command line handling
my $explicit_target;
GetOptions ("target|t=s" => \$explicit_target);
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, $uboot, $uboot_init);
$rsync_flags = '';
$rom_prefix = 'rom://';
$stty = 'raw -crtscts -onlcr 115200';
my @expect_seen = ();
sub handle_expect
{
my ($n, $v) = @_;
push(@expect_seen, '-re') if $n eq "expect-re";
push(@expect_seen, $v);
}
sub handle_send
{
my ($n, $v) = @_;
unless (@expect_seen) { die("No --expect before --send"); }
my $ret = ($n eq "sendcont") ? exp_continue : 0;
unshift(@expect_raw, sub { shift->send(eval("\"$v\"")); $ret; });
unshift(@expect_raw, @expect_seen);
@expect_seen = ();
}
Getopt::Long::Configure(qw/no_ignore_case no_pass_through/);
my %opt_spec;
%opt_spec = (
"amt=s" => \$amt,
"append|a=s" => \@append,
"bender|b" => \$bender,
"build-dir=s" => sub { my ($n, $v) = @_; $builddir = File::Spec->rel2abs($v); },
"concat" => \$concat,
"chainloader=s" => \@chainloaders,
"dhcp-tftp|d" => \$dhcp_tftp,
"dump" => \$dump_opt,
"dump-config" => \$dump_config,
"exiton=s" => \@exiton,
"expect=s" => \&handle_expect,
"expect-re=s" => \&handle_expect,
"expect-raw=s" => sub { my ($n, $v) = @_; unshift(@expect_raw, eval($v)); },
"gen-only" => \$gen_only,
"grub|g:s" => \$grub_config,
"grub-preamble=s"=> \$grub_preamble,
"grub-prefix=s" => \$grub_prefix,
"grub2:s" => \$grub2_config,
"grub2-prolog=s" => \$grub2_prolog,
"ider" => \$ider,
"iprelay=s" => \$iprelay,
"iso:s" => \$iso_image,
"kernel|k=s" => \$kernel_opt,
"interactive|i" => \$interactive,
"name=s" => \$config_name_opt,
"make|m:s" => \$make,
"no-file-gen" => \$no_file_gen,
"off" => \$off_opt,
"on" => \$on_opt,
"pulsar|p:s" => \$pulsar,
"pulsar-root=s" => \$pulsar_root,
"qemu|Q:s" => \$qemu,
"qemu-append=s" => \$qemu_append,
"qemu-flags|q=s" => \$qemu_flags_cmd,
"remote-cmd=s" => \$remote_cmd,
"remote-expect=s"=> \$remote_expect,
"reset-cmd=s" => \$reset_cmd,
"rsync-flags=s" => \$rsync_flags,
"scons:s" => \$scons,
"scriptmod=s" => \@scriptmod,
"send=s" => \&handle_send,
"sendcont=s" => \&handle_send,
"serial|s:s" => \$serial,
"server:s" => \$server,
"strip-rom" => sub { $rom_prefix = ''; },
"stty=s" => \$stty,
"uboot" => \$uboot,
"uboot-init=s" => \$uboot_init,
"h" => \$help,
"help" => \$man,
);
# First process target options
{
my $t = defined($explicit_target) ? $explicit_target : $CFG::default_target;
if ($t) {
exists $CFG::targets{$t} or die("Unknown target '$t' (valid targets are: ".join(", ", sort keys(%CFG::targets)).")");
GetOptionsFromString($CFG::targets{$t}, %opt_spec);
}
}
# Then process other command line options - some of them may override
# what was specified by the target
GetOptions %opt_spec or die("Error in command line arguments");
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
### Dump sanitized configuration (if requested)
if ($dump_config) {
use Data::Dumper;
$Data::Dumper::Indent=1;
print "# This file is in perl syntax.\n";
foreach my $key(sort(keys(%CFG::))) { # See "Symbol Tables" in perlmod(1)
if (defined ${$CFG::{$key}}) { print Data::Dumper->Dump([${$CFG::{$key}}], ["*$key"]); }
if ( @{$CFG::{$key}}) { print Data::Dumper->Dump([\@{$CFG::{$key}}], ["*$key"]); }
if ( %{$CFG::{$key}}) { print Data::Dumper->Dump([\%{$CFG::{$key}}], ["*$key"]); }
}
print "1;\n";
exit;
}
### Sanitize configuration
if ($interactive && !-t STDIN) {
die("novaboot: Interactive mode not supported when not on terminal");
}
if (defined $config_name_opt && scalar(@ARGV) > 1) { die "You cannot use --name with multiple scripts"; }
# Default options
if (defined $serial) {
$serial ||= "/dev/ttyUSB0";
$ENV{NB_SERIAL} = $serial;
}
if (defined $grub_config) { $grub_config ||= "menu.lst"; }
if (defined $grub2_config) { $grub2_config ||= "grub.cfg"; }
## Parse the novaboot script(s)
my @scripts;
my $file;
my $EOF;
my $last_fn = '';
my ($modules, $variables, $generated, $continuation);
my $skip_reading = defined($on_opt) || defined($off_opt);
while (!$skip_reading && ($_ = <>)) {
if ($ARGV ne $last_fn) { # New script
die "Missing EOF in $last_fn" if $file;
die "Unfinished line in $last_fn" if $continuation;
$last_fn = $ARGV;
push @scripts, { 'filename' => $ARGV,
'modules' => $modules = [],
'variables' => $variables = {},
'generated' => $generated = []};
}
chomp();
next if /^#/ || /^\s*$/; # Skip comments and empty lines
$_ =~ s/^[[:space:]]*// if ($continuation);
if (/\\$/) { # Line continuation
$continuation .= substr($_, 0, length($_)-1);
next;
}
if ($continuation) { # Last continuation line
$_ = $continuation . $_;
$continuation = '';
}
foreach my $mod(@scriptmod) { eval $mod; }
if ($file && $_ eq $EOF) { # Heredoc end
undef $file;
next;
}
if ($file) { # Heredoc content
push @{$file}, "$_\n";
next;
}
if (/^([A-Z_]+)=(.*)$/) { # Internal variable
$$variables{$1} = $2;
push(@exiton, $2) if ($1 eq "EXITON");
next;
}
if (s/^load *//) { # Load line
die("novaboot: '$last_fn' line $.: Missing file name\n") unless /^[^ <]+/;
if (/^([^ ]*)(.*?)[[:space:]]*<<([^ ]*)$/) { # Heredoc start
push @$modules, "$1$2";
$file = [];
push @$generated, {filename => $1, content => $file};
$EOF = $3;
next;
}
if (/^([^ ]*)(.*?)[[:space:]]*< ?(.*)$/) { # Command substitution
push @$modules, "$1$2";
push @$generated, {filename => $1, command => $3};
next;
}
push @$modules, $_;
next;
}
if (/^run (.*)/) { # run line
push @$generated, {command => $1};
next;
}
die("novaboot: Cannot parse script '$last_fn' line $.. Didn't you forget 'load' keyword?\n");
}
# use Data::Dumper;
# print Dumper(\@scripts);
foreach my $script (@scripts) {
$modules = $$script{modules};
@$modules[0] =~ s/^[^ ]*/$kernel_opt/ if $kernel_opt;
@$modules[0] .= ' ' . join(' ', @append) if @append;
my $kernel;
if (exists $variables->{KERNEL}) {
$kernel = $variables->{KERNEL};
} else {
if ($CFG::hypervisor) {
$kernel = $CFG::hypervisor . " ";
if (exists $variables->{HYPERVISOR_PARAMS}) {
$kernel .= $variables->{HYPERVISOR_PARAMS};
} else {
$kernel .= $CFG::hypervisor_params;
}
}
}
@$modules = ($kernel, @$modules) if $kernel;
@$modules = (@chainloaders, @$modules);
@$modules = ("bin/boot/bender", @$modules) if ($bender || defined $ENV{'NOVABOOT_BENDER'});
}
if ($dump_opt) {
foreach my $script (@scripts) {
print join("\n", @{$$script{modules}})."\n";
}
exit(0);
}
## Helper functions
sub generate_configs($$$) {
my ($base, $generated, $filename) = @_;
if ($base) { $base = "$base/"; };
foreach my $g(@$generated) {
if (exists $$g{content}) {
my $config = $$g{content};
my $fn = $$g{filename};
open(my $f, '>', $fn) || die("$fn: $!");
map { s|\brom://([^ ]*)|$rom_prefix$base$1|g; print $f "$_"; } @{$config};
close($f);
print "novaboot: Created $fn\n";
} elsif (exists $$g{command} && ! $no_file_gen) {
$ENV{SRCDIR} = dirname(File::Spec->rel2abs( $filename, $invocation_dir ));
if (exists $$g{filename}) {
system_verbose("( $$g{command} ) > $$g{filename}");
} else {
system_verbose($$g{command});
}
}
}
}
sub generate_grub_config($$$$;$)
{
my ($filename, $title, $base, $modules_ref, $preamble) = @_;
if ($base) { $base = "$base/"; };
open(my $fg, '>', $filename) or die "$filename: $!";
print $fg "$preamble\n" if $preamble;
print $fg "title $title\n" if $title;
#print $fg "root $base\n"; # root doesn't really work for (nd)
my $first = 1;
foreach (@$modules_ref) {
if ($first) {
$first = 0;
my ($kbin, $kcmd) = split(' ', $_, 2);
$kcmd = '' if !defined $kcmd;
print $fg "kernel ${base}$kbin $kcmd\n";
} else {
s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
print $fg "module $base$_\n";
}
}
close($fg);
print("novaboot: Created $builddir/$filename\n");
return $filename;
}
sub generate_syslinux_config($$$$)
{
my ($filename, $title, $base, $modules_ref) = @_;
if ($base && $base !~ /\/$/) { $base = "$base/"; };
open(my $fg, '>', $filename) or die "$filename: $!";
print $fg "LABEL $title\n";
#TODO print $fg "MENU LABEL $human_readable_title\n";
my ($kbin, $kcmd) = split(' ', @$modules_ref[0], 2);
if (system("file $kbin|grep 'Linux kernel'") == 0) {
my $initrd = @$modules_ref[1];
die('To many "load" lines for Linux kernel') if (scalar @$modules_ref > 2);
print $fg "LINUX $base$kbin\n";
print $fg "APPEND $kcmd\n";
print $fg "INITRD $base$initrd\n";
} else {
print $fg "KERNEL mboot.c32\n";
my @append;
foreach (@$modules_ref) {
s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
push @append, "$base$_";
print $fg "APPEND ".join(' --- ', @append)."\n";
}
}
#TODO print $fg "TEXT HELP\n";
#TODO print $fg "some help here\n";
#TODO print $fg "ENDTEXT\n";
close($fg);
print("novaboot: Created $builddir/$filename\n");
return $filename;
}
sub generate_grub2_config($$$$;$$)
{
my ($filename, $title, $base, $modules_ref, $preamble, $prolog) = @_;
if ($base && substr($base,-1,1) ne '/') { $base = "$base/"; };
open(my $fg, '>', $filename) or die "$filename: $!";
print $fg "$preamble\n" if $preamble;
$title ||= 'novaboot';
print $fg "menuentry $title {\n";
print $fg "$prolog\n" if $prolog;
my $first = 1;
foreach (@$modules_ref) {
if ($first) {
$first = 0;
my ($kbin, $kcmd) = split(' ', $_, 2);
$kcmd = '' if !defined $kcmd;
print $fg " multiboot ${base}$kbin $kcmd\n";
} else {
my @args = split;
# GRUB2 doesn't pass filename in multiboot info so we have to duplicate it here
$_ = join(' ', ($args[0], @args));
s|\brom://|$rom_prefix|g; # We do not need to translate path for GRUB2
print $fg " module $base$_\n";
}
}
print $fg "}\n";
close($fg);
print("novaboot: Created $builddir/$filename\n");
return $filename;
}
sub generate_pulsar_config($$)
{
my ($filename, $modules_ref) = @_;
open(my $fg, '>', $filename) or die "$filename: $!";
print $fg "root $pulsar_root\n" if defined $pulsar_root;
my $first = 1;
my ($kbin, $kcmd);
foreach (@$modules_ref) {
if ($first) {
$first = 0;
($kbin, $kcmd) = split(' ', $_, 2);
$kcmd = '' if !defined $kcmd;
} else {
my @args = split;
s|\brom://|$rom_prefix|g;
print $fg "load $_\n";
}
}
# Put kernel as last - this is needed for booting Linux and has no influence on non-Linux OSes
print $fg "exec $kbin $kcmd\n";
close($fg);
print("novaboot: Created $builddir/$filename\n");
return $filename;
}
sub shell_cmd_string(@)
{
return join(' ', map((/^[-_=a-zA-Z0-9\/\.\+]+$/ ? "$_" : "'$_'"), @_));
}
sub exec_verbose(@)
{
print "novaboot: Running: ".shell_cmd_string(@_)."\n";
exec(@_);
}
sub system_verbose($)
{
my $cmd = shift;
print "novaboot: Running: $cmd\n";
my $ret = system($cmd);
if ($ret & 0x007f) { die("Command terminated by a signal"); }
if ($ret & 0xff00) {die("Command exit with non-zero exit code"); }
if ($ret) { die("Command failure $ret"); }
}
## WvTest handline
if (exists $variables->{WVDESC}) {
print "Testing \"$variables->{WVDESC}\" in $last_fn:\n";
} elsif ($last_fn =~ /\.wv$/) {
print "Testing \"all\" in $last_fn:\n";
}
## Connect to the target and check whether it is not occupied
# We have to do this before file generation phase, because file
# generation is intermixed with file deployment phase and we want to
# check whether the target is not used by somebody else before
# deploying files. Otherwise, we may rewrite other user's files on a
# boot server.
my $exp; # Expect object to communicate with the target over serial line
my ($target_reset, $target_power_on, $target_power_off);
if (defined $iprelay) {
my $IPRELAY;
$iprelay =~ /([.0-9]+)(:([0-9]+))?/;
my $addr = $1;
my $port = $3 || 23;
my $paddr = sockaddr_in($port, inet_aton($addr));
my $proto = getprotobyname('tcp');
socket($IPRELAY, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
print "novaboot: Connecting to IP relay... ";
connect($IPRELAY, $paddr) || die "connect: $!";
print "done\n";
$exp = Expect->init(\*$IPRELAY);
$exp->log_stdout(1);
while (1) {
print $exp "\xFF\xF6"; # AYT
my $connected = $exp->expect(20, # Timeout in seconds
'<iprelayd: connected>',
'-re', '<WEB51 HW[^>]*>');
last if $connected;
}
sub relaycmd($$) {
my ($relay, $onoff) = @_;
die unless ($relay == 1 || $relay == 2);
my $cmd = ($relay == 1 ? 0x5 : 0x6) | ($onoff ? 0x20 : 0x10);
return "\xFF\xFA\x2C\x32".chr($cmd)."\xFF\xF0";
}
sub relayconf($$) {
my ($relay, $onoff) = @_;
die unless ($relay == 1 || $relay == 2);
my $cmd = ($relay == 1 ? 0xdf : 0xbf) | ($onoff ? 0x00 : 0xff);
return "\xFF\xFA\x2C\x97".chr($cmd)."\xFF\xF0";
}
sub relay($$;$) {
my ($relay, $onoff, $can_giveup) = @_;
my $confirmation = '';
$exp->log_stdout(0);
print $exp relaycmd($relay, $onoff);
my $confirmed = $exp->expect(20, # Timeout in seconds
relayconf($relay, $onoff));
if (!$confirmed) {
if ($can_giveup) {
print("Relay confirmation timeout - ignoring\n");
} else {
die "Relay confirmation timeout";
}
}
$exp->log_stdout(1);
}
$target_reset = sub {
relay(2, 1, 1); # Reset the machine
usleep(100000);
relay(2, 0);
};
$target_power_off = sub {
relay(1, 1); # Press power button
usleep(6000000); # Long press to switch off
relay(1, 0);
};
$target_power_on = sub {
relay(1, 1); # Press power button
usleep(100000); # Short press
relay(1, 0);
};
}
elsif ($serial) {
my $CONN;
system_verbose("stty -F $serial $stty");
open($CONN, "+<", $serial) || die "open $serial: $!";
$exp = Expect->init(\*$CONN);
}
elsif ($remote_cmd) {
print "novaboot: Running: $remote_cmd\n";
$exp = Expect->spawn($remote_cmd);
}
elsif (defined $amt) {
require LWP::UserAgent;
require LWP::Authen::Digest;
sub genXML {
my ($host, $username, $password, $schema, $className, $pstate) = @_;
#AMT numbers for PowerStateChange (MNI => bluescreen on windows;-)
my %pstates = ("on" => 2,
"standby" => 4,
"hibernate" => 7,
"off" => 8,
"reset" => 10,
"MNI" => 11);
return <<END;
<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">
<s:Header><a:To>http://$host:16992/wsman</a:To>
<w:ResourceURI s:mustUnderstand="true">$schema</w:ResourceURI>
<a:ReplyTo><a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>
<a:Action s:mustUnderstand="true">$schema$className</a:Action>
<w:MaxEnvelopeSize s:mustUnderstand="true">153600</w:MaxEnvelopeSize>
<a:MessageID>uuid:709072C9-609C-4B43-B301-075004043C7C</a:MessageID>
<w:Locale xml:lang="en-US" s:mustUnderstand="false" />
<w:OperationTimeout>PT60.000S</w:OperationTimeout>
<w:SelectorSet><w:Selector Name="Name">Intel(r) AMT Power Management Service</w:Selector></w:SelectorSet>
</s:Header><s:Body>
<p:RequestPowerStateChange_INPUT xmlns:p="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService">
<p:PowerState>$pstates{$pstate}</p:PowerState>
<p:ManagedElement><a:Address>http://$host:16992/wsman</a:Address>
<a:ReferenceParameters><w:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem</w:ResourceURI>
<w:SelectorSet><w:Selector Name="Name">ManagedSystem</w:Selector></w:SelectorSet>
</a:ReferenceParameters></p:ManagedElement>
</p:RequestPowerStateChange_INPUT>
</s:Body></s:Envelope>
END
}
sub sendPOST {
my ($host, $username, $password, $content) = @_;
my $ua = LWP::UserAgent->new();
$ua->agent("novaboot");
my $req = HTTP::Request->new(POST => "http://$host:16992/wsman");
my $res = $ua->request($req);
die ("Unexpected AMT response: " . $res->status_line) unless $res->code == 401;
my ($realm) = $res->header("WWW-Authenticate") =~ /Digest realm="(.*?)"/;
$ua->credentials("$host:16992", $realm, $username => $password);
# Create a request
$req = HTTP::Request->new(POST => "http://$host:16992/wsman");
$req->content_type('application/x-www-form-urlencoded');
$req->content($content);
$res = $ua->request($req);
die ("AMT power change request failed: " . $res->status_line) unless $res->is_success;
$res->content() =~ /<g:ReturnValue>(\d+)<\/g:ReturnValue>/;
return $1;
}
sub powerChange {
my ($host, $username, $password, $pstate)=@_;
my $schema="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService";
my $className="/RequestPowerStateChange";
my $content = genXML($host, $username, $password ,$schema, $className, $pstate);
return sendPOST($host, $username, $password, $content);
}
my ($user,$amt_password,$host,$port) = ($amt =~ /(?:(.*?)(?::(.*))?@)?([^:]*)(?::([0-9]*))?/);;
$user ||= "admin";
$amt_password ||= $ENV{'AMT_PASSWORD'} || die "AMT password not specified";
$host || die "AMT host not specified";
$port ||= 16994;
$target_power_off = sub {
$exp->close();
my $result = powerChange($host,$user,$amt_password, "off");
die "AMT power off failed (ReturnValue $result)" if $result != 0;
};
$target_power_on = sub {
my $result = powerChange($host,$user,$amt_password, "on");
die "AMT power on failed (ReturnValue $result)" if $result != 0;
};
$target_reset = sub {
if (defined $ider) {
print "novaboot: Generating image of FD.\n";
system_verbose("dd if=/dev/zero of=fd.img bs=512 count=200");
my $ider_cmd= "amtider -f fd.img -c ider.iso -u $user -p $amt_password $host $port" ;
my $ider_pid = fork();
print "novaboot: Running: $ider_cmd\n" =~ s/\Q$amt_password\E/???/r if ($ider_pid == 0);
exec($ider_cmd) if ($ider_pid == 0);
die "IDE redirection failed" if ($ider_pid == 0);
}
my $result = powerChange($host,$user,$amt_password, "reset");
if ($result != 0) {
print STDERR "Warning: Cannot reset $host, trying power on. ";
$result = powerChange($host,$user,$amt_password, "on");
}
die "AMT reset failed (ReturnValue $result)" if $result != 0;
};
if (defined $ider) {
$iso_image="ider.iso";
}
my $cmd = "amtterm -u $user -p $amt_password $host $port";
print "novaboot: Running: $cmd\n" =~ s/\Q$amt_password\E/???/r;
$exp = Expect->spawn($cmd);
$exp->expect(10, "RUN_SOL") || die "Expect for 'RUN_SOL' timed out";
}
if ($remote_expect) {
$exp->expect(10, $remote_expect) || die "Expect for '$remote_expect' timed out";
}
if (defined $reset_cmd) {
$target_reset = sub {
system_verbose($reset_cmd);
};
}
if (defined $on_opt && defined $target_power_on) {
&$target_power_on();
exit;
}
if (defined $off_opt && defined $target_power_off) {
print "novaboot: Switching the target off...\n";
&$target_power_off();
exit;
}
$builddir ||= dirname(File::Spec->rel2abs( ${$scripts[0]}{filename})) if scalar @scripts;
if (defined $builddir) {
chdir($builddir) or die "Can't change directory to $builddir: $!";
print "novaboot: Entering directory `$builddir'\n";
}
## File generation phase
my (%files_iso, $menu_iso, $filename);
my $config_name = '';
foreach my $script (@scripts) {
$filename = $$script{filename};
$modules = $$script{modules};
$generated = $$script{generated};
$variables = $$script{variables};
($config_name = $filename) =~ s#.*/##;
$config_name = $config_name_opt if (defined $config_name_opt);
if (exists $variables->{BUILDDIR}) {
$builddir = File::Spec->rel2abs($variables->{BUILDDIR});
chdir($builddir) or die "Can't change directory to $builddir: $!";
print "novaboot: Entering directory `$builddir'\n";
}
my $prefix;
($prefix = $grub_prefix) =~ s/\$NAME/$config_name/ if defined $grub_prefix;
$prefix ||= $builddir;
# TODO: use $grub_prefix as first parameter if some switch is given
generate_configs('', $generated, $filename);
### Generate bootloader configuration files
my @bootloader_configs;
push @bootloader_configs, generate_grub_config($grub_config, $config_name, $prefix, $modules, $grub_preamble) if (defined $grub_config);
push @bootloader_configs, generate_grub2_config($grub2_config, $config_name, $prefix, $modules, $grub_preamble, $grub2_prolog) if (defined $grub2_config);
push @bootloader_configs, generate_pulsar_config('config-'.($pulsar||'novaboot'), $modules) if (defined $pulsar);
### Run scons or make
{
my @files = map({ ($file) = m/([^ ]*)/; $file; } @$modules);
# Filter-out generated files
my @to_build = grep({ my $file = $_; !scalar(grep($file eq ($$_{filename} || ''), @$generated)) } @files);
system_verbose($scons || $CFG::scons." ".join(" ", @to_build)) if (defined $scons);
system_verbose($make || $CFG::make ." ".join(" ", @to_build)) if (defined $make);
}
### Copy files (using rsync)
if (defined $server && !defined($gen_only)) {
(my $real_server = $server) =~ s/\$NAME/$config_name/;
my ($hostname, $path) = split(":", $real_server, 2);
if (! defined $path) {
$path = $hostname;
$hostname = "";
}
my $files = join(" ", map({ ($file) = m/([^ ]*)/; $file; } ( @$modules, @bootloader_configs)));
map({ my $file = (split)[0]; die "$file: $!" if ! -f $file; } @$modules);
my $istty = -t STDOUT && ($ENV{'TERM'} || 'dumb') ne 'dumb';
my $progress = $istty ? "--progress" : "";
system_verbose("rsync $progress -RLp $rsync_flags $files $real_server");
if ($server =~ m|/\$NAME$| && $concat) {
my $cmd = join("; ", map { "( cd $path/.. && cat */$_ > $_ )" } @bootloader_configs);
system_verbose($hostname ? "ssh $hostname '$cmd'" : $cmd);
}
}
### Prepare ISO image generation
if (defined $iso_image) {
generate_configs("(cd)", $generated, $filename);
my $menu;
generate_syslinux_config(\$menu, $config_name, "/", $modules);
$menu_iso .= "$menu\n";
map { ($file,undef) = split; $files_iso{$file} = 1; } @$modules;
}
}
## Generate ISO image
if (defined $iso_image) {
system_verbose("mkdir -p isolinux");
system_verbose('cp /usr/lib/syslinux/isolinux.bin /usr/lib/syslinux/mboot.c32 /usr/lib/syslinux/menu.c32 isolinux');
open(my $fh, ">isolinux/isolinux.cfg");
if ($#scripts) {
print $fh "TIMEOUT 50\n";
print $fh "DEFAULT menu\n";
} else {
print $fh "DEFAULT $config_name\n";
}
print $fh "$menu_iso";
close($fh);
my $files = join(" ", map("$_=$_", (keys(%files_iso), 'isolinux/isolinux.bin', 'isolinux/isolinux.cfg', 'isolinux/mboot.c32', 'isolinux/menu.c32')));
$iso_image ||= "$config_name.iso";
# Note: We use -U flag below to "Allow 'untranslated' filenames,
# completely violating the ISO9660 standards". Without this
# option, isolinux is not able to read files names for example
# bzImage-3.0.
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");
print("ISO image created: $builddir/$iso_image\n");
}
exit(0) if defined $gen_only;
## Boot the system using various methods and send serial output to stdout
if (scalar(@scripts) > 1 && ( defined $dhcp_tftp || defined $serial || defined $iprelay)) {
die "You cannot do this with multiple scripts simultaneously";
}
if ($variables->{WVTEST_TIMEOUT}) {
print "wvtest: timeout ", $variables->{WVTEST_TIMEOUT}, "\n";
}
sub trim($) {
my ($str) = @_;
$str =~ s/^\s+|\s+$//g;
return $str
}
### Start in Qemu
if (defined $qemu) {
# Qemu
$qemu ||= $variables->{QEMU} || $CFG::qemu;
my @qemu_flags = split(" ", $qemu);
$qemu = shift(@qemu_flags);
@qemu_flags = split(/ +/, trim($variables->{QEMU_FLAGS})) if exists $variables->{QEMU_FLAGS};
@qemu_flags = split(/ +/, trim($qemu_flags_cmd)) if $qemu_flags_cmd;
push(@qemu_flags, split(/ +/, trim($qemu_append || '')));
if (defined $iso_image) {
# Boot NOVA with grub (and test the iso image)
push(@qemu_flags, ('-cdrom', $iso_image));
} else {
# Boot NOVA without GRUB
# Non-patched qemu doesn't like commas, but NUL can live with pluses instead of commans
foreach (@$modules) {s/,/+/g;}
generate_configs("", $generated, $filename);
if (scalar @$modules) {
my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
$kcmd = '' if !defined $kcmd;
my $dtb;
@$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
my $initrd = join ",", @$modules;
push(@qemu_flags, ('-kernel', $kbin, '-append', $kcmd));
push(@qemu_flags, ('-initrd', $initrd)) if $initrd;
push(@qemu_flags, ('-dtb', $dtb)) if $dtb;
}
}
push(@qemu_flags, qw(-serial stdio)); # Redirect serial output (for collecting test restuls)
unshift(@qemu_flags, ('-name', $config_name));
print "novaboot: Running: ".shell_cmd_string($qemu, @qemu_flags)."\n";
$exp = Expect->spawn(($qemu, @qemu_flags)) || die("exec() failed: $!");
}
### Local DHCPD and TFTPD
my ($dhcpd_pid, $tftpd_pid);
if (defined $dhcp_tftp)
{
generate_configs("(nd)", $generated, $filename);
system_verbose('mkdir -p tftpboot');
generate_grub_config("tftpboot/os-menu.lst", $config_name, "(nd)", \@$modules, "timeout 0");
open(my $fh, '>', 'dhcpd.conf');
my $mac = `cat /sys/class/net/eth0/address`;
chomp $mac;
print $fh "subnet 10.23.23.0 netmask 255.255.255.0 {
range 10.23.23.10 10.23.23.100;
filename \"bin/boot/grub/pxegrub.pxe\";
next-server 10.23.23.1;
}
host server {
hardware ethernet $mac;
fixed-address 10.23.23.1;
}";
close($fh);
system_verbose("sudo ip a add 10.23.23.1/24 dev eth0;
sudo ip l set dev eth0 up;
sudo touch dhcpd.leases");
# We run servers by forking ourselves, because the servers end up
# in our process group and get killed by signals sent to the
# process group (e.g. Ctrl-C on terminal).
$dhcpd_pid = fork();
exec_verbose("sudo dhcpd -d -cf dhcpd.conf -lf dhcpd.leases -pf dhcpd.pid") if ($dhcpd_pid == 0);
$tftpd_pid = fork();
exec_verbose("sudo in.tftpd --foreground --secure -v -v -v --pidfile tftpd.pid $builddir") if ($tftpd_pid == 0);
# Kill server when we die
$SIG{__DIE__} = sub { system_verbose('sudo pkill --pidfile=dhcpd.pid');
system_verbose('sudo pkill --pidfile=tftpd.pid'); };
}
### Reset target (IP relay, AMT, ...)
if (defined $target_reset) {
print "novaboot: Reseting the test box... ";
&$target_reset();
print "done\n";
}
### U-boot conversation
if (defined $uboot) {
print "novaboot: Waiting for uBoot prompt...\n";
$exp->log_stdout(1);
#$exp->exp_internal(1);
$exp->expect(20,
[qr/Hit any key to stop autoboot:/, sub { $exp->send("\n"); exp_continue; }],
'=> ') || die "No uBoot prompt deteceted";
$exp->send("$uboot_init\n") if $uboot_init;
$exp->expect(10, '=> ') || die "uBoot prompt timeout";
my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
my $dtb;
@$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
my $initrd = shift @$modules;
my $kern_addr = '800000';
my $initrd_addr = '-';
my $dtb_addr = '';
$exp->send("tftp $kern_addr $kbin\n");
$exp->expect(10,
[qr/#/, sub { exp_continue; }],
'=> ') || die "Kernel load failed";
if (defined $dtb) {
$dtb_addr = '7f0000';
$exp->send("tftp $dtb_addr $dtb\n");
$exp->expect(10,
[qr/#/, sub { exp_continue; }],
'=> ') || die "Device tree load failed";
}
if (defined $initrd) {
$initrd_addr = 'b00000';
$exp->send("tftp $initrd_addr $initrd\n");
$exp->expect(10,
[qr/#/, sub { exp_continue; }],
'=> ') || die "Initrd load failed";
}
$exp->send("set bootargs '$kcmd'\n");
$exp->expect(5, '=> ') || die "uBoot prompt timeout";
$exp->send("bootm $kern_addr $initrd_addr $dtb_addr\n");
$exp->expect(5, "\n") || die "uBoot command timeout";
}
### Serial line interaction
if (defined $exp) {
# Serial line of the target is available
my $interrupt = 'Ctrl-C';
if ($interactive && !@exiton) {
$interrupt = '"~~."';
}
print "novaboot: Serial line interaction (press $interrupt to interrupt)...\n";
$exp->log_stdout(1);
if (@exiton) {
$exp->expect(undef, @expect_raw, @exiton);
} else {
my @inputs = ($exp);
if (-t STDIN) { # Set up bi-directional communication if we run on terminal
my $infile = new IO::File;
$infile->IO::File::fdopen(*STDIN,'r');
my $in_object = Expect->exp_init($infile);
$in_object->set_group($exp);
if ($interactive) {
$in_object->set_seq('~~\.', sub { print "novaboot: Escape sequence detected\r\n"; undef; });
$in_object->manual_stty(0); # Use raw terminal mode
} else {