xmlconvert.in 16.8 KB
Newer Older
1 2 3 4
#!/usr/bin/perl -wT

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2004 University of Utah and the Flux Group.
6 7 8 9 10
# All rights reserved.
#

use English;
use Getopt::Std;
11
use XML::Parser;
12 13 14
use RPC::XML;
use RPC::XML::Parser;

15 16 17 18
#
# Convert between XML and DB representation of a virtual experiment.
# Very simple, no DTDs, DOMs, XSLs, etc. Just the facts ...
#
19 20 21 22
# XXX We do not regex the data carefully enough before inserting it into
# the DB. We run quotemeta() over it, but we should be more careful about
# per-slot checks.
#
23 24
sub usage()
{
25
    print STDOUT "Usage: xmlconvert [-x <xmlfile> [-n] [-p]] [-d] pid eid\n";
26 27 28
 
    exit(-1);
}
29
my $optlist  = "x:ndsp";
30
my $fromxml  = 0;
31
my $fromparser = 0;
32
my $impotent = 0;
33
my $debug    = 0;
34 35 36
# Results of parsing nse specifications. Therefore different treatment.
# In particular, we don't expect updates to the experiments table
my $simparse = 0;
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

#
# Configure variables
#
my $TB       = "@prefix@";
my $TBOPS    = "@TBOPSEMAIL@";

# Locals
my $xmlfile;
my $pid;
my $eid;

# This goes at the beginning of the output.
my $XMLHEADER = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";

#
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
# These are the virtual tables that make up an experiment.  Each one
# could have multiple rows, each of which will be a hash table.
#
my %virtual_tables = 
    ("experiments"		=> { rows  => undef, 
				     tag   => "experiment",
				     attrs => [ ] },
     "virt_nodes"		=> { rows  => undef, 
				     tag   => "nodes",
				     attrs => [ "vname" ]},
     "virt_lans"		=> { rows  => undef, 
				     tag   => "lans",
				     attrs => [ "vname" ]},
     "virt_lan_settings"	=> { rows  => undef, 
				     tag   => "lan_settings",
				     attrs => [ "vname", "capkey" ]},
     "virt_lan_member_settings" => { rows  => undef, 
				     tag   => "lan_member_settings",
				     attrs => [ "vname", "member", "capkey" ]},
     "virt_trafgens"		=> { rows  => undef, 
				     tag   => "trafgens",
				     attrs => [ "vname", "vnode" ]},
     "virt_agents"		=> { rows  => undef, 
				     tag   => "agents",
				     attrs => [ "vname", "vnode" ]},
     "virt_node_desires"	=> { rows  => undef, 
				     tag   => "node_desires",
				     attrs => [ "vname", "desire" ]},
     "virt_routes"		=> { rows  => undef, 
				     tag   => "routes",
				     attrs => [ "vname", "src", "dst" ]},
     "virt_vtypes"		=> { rows  => undef, 
				     tag   => "vtypes",
				     attrs => [ "name" ]},
     "virt_programs"		=> { rows  => undef, 
				     tag   => "programs",
				     attrs => [ "vname", "vnode" ]},
     "nseconfigs"		=> { rows  => undef, 
				     tag   => "nseconfigs",
				     attrs => [ "vname" ]},
     "eventlist"		=> { rows  => undef, 
				     tag   => "events",
				     attrs => [ "vname" ]});
    
97 98 99 100

# XXX
# The experiment table is special. Only certain fields are allowed to
# be updated. Not sure what the right approach for this is.
101
# Note that I regex the data before inserting it below.
102
#
103 104 105 106 107 108 109
my %experiment_fields = ("multiplex_factor"		=> 1,
			 "forcelinkdelays"		=> 1,
			 "uselinkdelays"		=> 1,
			 "usewatunnels"			=> 1,
			 "uselatestwadata"		=> 1,
			 "wa_delay_solverweight"	=> 1,
			 "wa_bw_solverweight"		=> 1,
110
			 "wa_plr_solverweight"		=> 1,
111 112
			 "cpu_usage"			=> 1,
			 "mem_usage"			=> 1,
113
			 "allowfixnode"			=> 1,
114
			 "veth_encapsulate"		=> 1,
115 116
			 "jail_osname"			=> 1,
			 "delay_osname"			=> 1,
117 118 119
			 "sync_server"			=> 1,
		         "use_ipassign"			=> 1,
		         "ipassign_args"		=> 1);
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

#
# Turn off line buffering on output
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/usr/bin:/sbin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;

#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
150 151 152
if (defined($options{"p"})) {
    $fromparser = 1;
}
153 154 155
if (defined($options{"s"})) {
    $simparse = 1;
}
156 157 158 159 160 161 162 163 164 165 166
if (defined($options{"x"})) {
    $fromxml = 1;
    $xmlfile = $options{"x"};

    if ($xmlfile =~ /^([-\w\/\.]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in argument: $xmlfile.");
    }
    if (defined($options{"n"})) {
167
	$impotent = 1;
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    }    
}
if (@ARGV != 2) {
    usage();
}
$pid   = $ARGV[0];
$eid   = $ARGV[1];

# Taint Check.
if ($pid =~ /^([-\w]+)$/) {
    $pid = $1;
}
else {
    fatal("Bad data in argument: $pid.");
}
if ($eid =~ /^([-\w]+)$/) {
    $eid = $1;
}
else {
    fatal("Bad data in argument: $eid.");
}

190 191 192 193 194 195
my %event_objtypes;
my $query_result = DBQueryFatal("select idx,type from event_objecttypes");
while (my ($idx,$type) = $query_result->fetchrow_array()) {
    $event_objtypes{$type} = $idx;
}

196 197
# Do it
if ($fromxml) {
198
    readXML($pid, $eid, $xmlfile, $fromparser);
199 200 201 202 203 204 205 206 207 208 209
}
else {
    writeXML($pid, $eid);
}
exit(0);

#
# Read in XML and convert to DB representation, doing lots of checks!
# This code is silly. Overly stylized (one tag per line!). Should
# use the XML::Parser package instead. But this was easy and fun for a
# first cut. 
210 211 212 213 214 215 216 217
#
# State variables for parsing code below.
my $current_expt;
my $current_table;
my $current_row;
my $current_slot;
my $current_data;

218 219
sub readXML($$$$) {
    my ($pid, $eid, $xmlfile, $fromparser) = @_;
220 221 222 223 224 225 226
    my %experiment;

    if ($xmlfile ne "-") {
	open(STDIN, "< $xmlfile")
	    or fatal("opening $xmlfile for STDIN: $!");
    }

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    if ($fromparser) {
	#
	# Create a parser.
	#
	my $parser = new XML::Parser(Style => 'Tree');
	$parser->setHandlers('Start'   => \&StartElement,
			     'End'     => \&EndElement,
			     'Char'    => \&ProcessElement);

	fatal($@)
	    if (eval { $parser->parse(*STDIN); return 1; } != 1);
    }
    else {
	#
	# Convert data structure into table rows.
	#
	my $resp = RPC::XML::Parser->new()->parse(STDIN);
	if (!ref($resp)) {
	    fatal("Could not parse XML input!");
	}
	my $exp = $resp->value->value;
248

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
	if (!exists($exp->{"experiment"}) ||
	    !exists($exp->{"experiment"}->{"settings"})) {
	    fatal("Missing experiment settings structure!");
	}
	$virtual_tables{"experiments"}->{"rows"} =
	    [ $exp->{"experiment"}->{"settings"} ];

	foreach my $table (keys(%virtual_tables)) {
	    my $tag = $virtual_tables{$table}{"tag"};

	    if (exists($exp->{"experiment"}->{$tag})) {
		$virtual_tables{$table}->{"rows"} =
		    $exp->{"experiment"}->{$tag};
	    }
	}
    }
265 266 267 268 269 270 271 272 273 274 275 276 277

    # If these are the results of parsing the nse specifications,
    # we don't expect updates to the experiments table
    my %experiments_table;
    if ( ! $simparse ) {

	#
	# Verify. 
	#
	# Must be exactly one experiments table row, and we prune out lots
	# of stuff that is not allowed. Note that we never insert a
	# experiment, but only allow updates of certain values. 
	#
278
	if (scalar(@{ $virtual_tables{"experiments"}->{"rows"} }) != 1) {
279 280
	    fatal("Must be exactly one experiments table row!");
	}
281
	%experiments_table = %{@{$virtual_tables{"experiments"}->{"rows"}}[0]};
282 283 284 285
	foreach my $key (keys(%experiments_table)) {
	    delete($experiments_table{$key})
		if (!exists($experiment_fields{$key}));
	}
286 287 288 289 290 291 292 293
    }

    #
    # Okay, a hokey DoS check. Do not allow more than 10000 total rows!
    # Why so many? Well, Rob likes to generate lots of events!
    #
    my $count = 0;
    foreach my $table (keys(%virtual_tables)) {
294 295
	$count += scalar(@{$virtual_tables{$table}->{"rows"}})
	    if (defined($virtual_tables{$table}->{"rows"}));
296
    }
297
    if ($count > 100000) {
298 299 300 301 302
	fatal("Too many rows of data!");
    }

    #
    # Okay, thats all the checking we do! There is not much that can
303 304
    # screw up the DB just by inserting rows into the allowed set of
    # virtual experiment tables, since we ignore the pid/eid in the xml. 
305
    #
306 307
    # First the experiments table, which gets an update statement, if there
    # is anything to update.
308
    #
309
    if ( (! $simparse) && scalar(keys(%experiments_table))) {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	my @setlist  = ();

	my $describe_result =
	    DBQueryFatal("describe experiments");

	#
	# Need to find the default values for slots that are not sent to
	# us in the xml so that we can set them properly.
	#
	while (my $rowref = $describe_result->fetchrow_hashref()) {
	    my $slot  = $rowref->{"Field"};
	    my $value = $rowref->{"Default"};

	    if (exists($experiment_fields{$slot}) &&
		! exists($experiments_table{$slot})) {
		$experiments_table{$slot} =
		    (defined($value) ? $value : "NULL");
	    }
	}
329

330 331
	foreach my $key (keys(%experiments_table)) {
	    my $val = $experiments_table{$key};
332

333
	    if ($val eq "NULL" || $val eq "") {
334 335 336
		push(@setlist, "$key=NULL");
	    }
	    else {
337 338
		# Sanity check the fields.
		if (TBcheck_dbslot($val, "experiments", $key,
339
			TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
340 341 342
		    push(@setlist, "$key='$val'");
		}
		else {
343 344
		    fatal("Illegal characters in table data: ".
			  "experiments:$key - $val");
345
		}
346
	    }	    
347
	}
348 349 350 351 352 353 354 355
	my $query = "update experiments ".
	            "set " . join(",", @setlist) . " " .
		    "where eid='$eid' and pid='$pid'";

	print "$query\n"
	    if ($debug);
	DBQueryFatal($query)
	    if (!$impotent);
356 357 358 359 360 361 362
    }

    #
    # Now all the other tables, which get inserts. Need to delete all the
    # old info too.
    #
    foreach my $table (keys(%virtual_tables)) {
363 364 365 366
	# Don't want to muck with this table! Done above. 
	next
	    if ($table eq "experiments");

367 368 369 370 371 372
	# Delete only during the initial parsing and not
	# during parsing of nse specifications
	if ( ! $simparse ) {
	    DBQueryFatal("delete from $table ".
			 "where eid='$eid' and pid='$pid'")
		if (!$impotent);
373 374 375 376 377 378 379 380 381 382 383 384
	} else {
	    # The nseconfigs table is special. During a
	    # simparse, we need delete all rows for the
	    # experiment except the one with the vname
	    # 'fullsim'. This row is essentially virtual
	    # info and does not change across swapins
	    # where as the other rows depend on the
	    # mapping
	    if ( !$impotent && ($table eq "nseconfigs") ) {
		DBQueryFatal("delete from $table ". 
		             "where eid='$eid' and pid='$pid' and ".
			     "vname!='fullsim'")
385 386 387 388 389 390 391 392 393 394
	    } elsif ( !$impotent && (($table eq "eventlist") ||
				       ($table eq "virt_agents")) ) {
	        # Both eventlist and virt_agents need to be cleared
		# for NSE event objecttype since entries in this
		# table depend on the particular mapping
		my $nse_objtype = $event_objtypes{"NSE"};
		DBQueryFatal("delete from $table ". 
		             "where pid='$pid' and eid='$eid' and ".
			     "objecttype='$nse_objtype'");
	    } 
395
	}
396
	next
397
	    if (!defined($virtual_tables{$table}->{"rows"}));
398

399
	foreach my $rowref (@{$virtual_tables{$table}->{"rows"}}) {
400 401 402 403
	    my %rowhash = %{ $rowref };
	    my @fields  = ("pid", "eid");
	    my @values  = ("'$pid'", "'$eid'");

404 405 406 407
	    # If no actual rows, then skip. Might happen.
	    last
		if (! scalar(keys(%rowhash)));

408
	    foreach my $key (keys(%rowhash)) {
409
		my $val = $rowhash{$key};
410 411 412 413

		if ($val eq "NULL") {
		    push(@values, "NULL");
		}
414 415 416
		elsif ($val eq "") {
		    push(@values, "''");
		}
417
		else {
418 419 420 421 422 423 424 425 426 427
		    # Sanity check the fields.
		    if (TBcheck_dbslot($val, $table, $key,
				 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
			push(@values, DBQuoteSpecial($val));
		    }
		    else {
			fatal("Illegal characters in table data: ".
			      "$table:$key - $val");
		    }
		}
428 429
		push(@fields, $key);
	    }
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
	    # If we are called after an nseparse, we need to
	    # use replace coz some of the tables such as 
	    # virt_agents and eventlist are not truly
	    # virtual tables. That is coz they contain the
	    # vnode field which is the same as the vname
	    # field in the reserved table. For simulated
	    # nodes, the mapping may change across swapins
	    # and the event may have to be delivered to a
	    # different simhost
	    if ( $simparse ) {
		$query = "replace into $table (" . join(",", @fields) . ") ".
		"values (" . join(",", @values) . ") ";
	    } else {
		$query = "insert into $table (" . join(",", @fields) . ") ".
		"values (" . join(",", @values) . ") ";
	    }
446 447 448 449

	    print "$query\n"
		if ($debug);
	    DBQueryFatal($query)
450
		if (!$impotent);
451 452 453 454 455
	}
    }
    return 0;
}

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
#
# XML::Parser routines.
#
#
# Start an element.
# 
sub StartElement ($$$)
{
    my ($expat, $element, %attrs) = @_;

    if ($element eq "virtual_experiment") {
	fatal("Out of sync at experiment start: $element")
	    if (defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	$current_expt = "$pid/$eid";
	
	#
	# Sanity check pid/eid.
	#
	if ((exists($attrs{'pid'}) && $attrs{'pid'} ne $pid) ||
	    (exists($attrs{'eid'}) && $attrs{'eid'} ne $eid)) {
	    fatal("pid/eid mismatch!");
	}
    }
    elsif (exists($virtual_tables{$element})) {
	#
	# A new table start.
	#
	fatal("Out of sync at element start: $element")
	    if (!defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	$current_table = $element;

493 494
	if (! defined($virtual_tables{$element}->{"rows"})) {
	    $virtual_tables{$element}->{"rows"} = [];
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
	}
	print "Starting new table: $element\n"
	    if ($debug);
    }
    elsif ($element eq "row") {
	fatal("Out of sync at row start: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	$current_row = {};
    }
    else {
	fatal("Out of sync at slot start: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		defined($current_slot));
	$current_slot = $element;
	$current_data = "";
    }
}

#
# End an element.
# 
sub EndElement ($$)
{
    my ($expat, $element) = @_;

    if ($element eq "virtual_experiment") {
	fatal("Out of sync at experiment start: $element")
	    if (!defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	undef($current_expt);
    }
    elsif (exists($virtual_tables{$element})) {
	#
	# A table termination.
	#
	fatal("Out of sync at element end: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	undef($current_table);
    }
    elsif ($element eq "row") {
	fatal("Out of sync at row end: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		defined($current_slot));

	print "Adding new row to table $current_table\n"
	    if ($debug);
	
554
	push(@{ $virtual_tables{$current_table}->{"rows"} }, $current_row);
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
	undef($current_row);
    }
    else {
	fatal("Out of sync at slot end: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		!defined($current_slot));
    
	#
	# Always ignore pid/eid.
	#
	if ($current_slot ne "pid" && $current_slot ne "eid") {
	    print "    Entering new slot: $current_slot: $current_data\n"
		if ($debug);
	    $current_row->{$current_slot} = $current_data;
	}
	undef($current_slot);
	undef($current_data);
    }
}

#
# Process stuff inside a slot.
# 
sub ProcessElement ($$)
{
    my ($expat, $string) = @_;

    if (defined($current_slot)) {
	$current_data .= xmldecode($string);
    }
}

589 590 591 592 593 594 595 596 597 598 599 600 601 602
#
# Convert a virtual experiment representation into XML and spit it out.
# The DB holds the data of course.
#
sub writeXML($$) {
    my ($pid, $eid) = @_;

    my $query_result =
	DBQueryFatal("select * from experiments ".
		     "where eid='$eid' and pid='$pid'");

    if (! $query_result->numrows) {
	fatal("No such experiment $pid/$eid exists!");
    }
603 604
    my $exp = {};
    $exp->{"experiment"}->{"settings"} = $query_result->fetchrow_hashref();
605

606 607 608
    foreach my $key (keys(%{ $exp->{"experiment"}->{"settings"} })) {
	$exp->{"experiment"}->{"settings"}->{$key} = ""
	    if (!defined($exp->{"experiment"}->{"settings"}->{$key}));
609 610
    }

611 612 613 614 615 616 617 618
    #
    # Read in a set of tables that live at top level.
    # 
    foreach my $table (keys(%virtual_tables)) {
	next
	    if ($table eq "experiments");
	
	my $tag = $virtual_tables{$table}{"tag"};
619

620 621 622 623 624 625 626 627 628 629 630 631 632 633
	if (!exists($exp->{"experiment"}->{$tag})) {
	    $exp->{"experiment"}->{$tag} = [];
	}
	$query_result =
	    DBQueryFatal("select * from $table ".
			 "where eid='$eid' and pid='$pid'");

	while (my $rowref = $query_result->fetchrow_hashref()) {
	    foreach my $key (keys(%{ $rowref })) {
		$rowref->{$key} = ""
		    if (!defined($rowref->{$key}));
	    }
	    push(@{ $exp->{"experiment"}->{$tag} }, $rowref);
	}
634 635
    }

636 637
    my $foo = new RPC::XML::response($exp);
    print $foo->as_string();
638
    
639
    return 0;
640 641 642 643 644 645 646 647 648 649 650 651
}

#
# Convert from/to XML special chars. Not many of them ...
# 
sub xmlencode($)
{
    my ($string) = @_;

    my %specialchars = ('&' => '&amp;',
			'<' => '&lt;',
			'>' => '&gt;',
652 653 654
			"'" => '&#39;',
			"]" => '&#93;',
			'"' => '&#34;');
655 656 657 658 659 660 661 662 663 664 665 666

    $string =~ s/([&<>"'])/$specialchars{$1}/ge;
    return $string;
}

sub xmldecode($)
{
    my ($string) = @_;

    my %specialchars = ('&amp;'  => '&',
			'&lt;'   => '<',
			'&gt;'   => '>',
667 668 669
			'&#39;'  => "'",
			'&#93;'  => ']',
			'&#34;'  => '"');
670 671 672 673 674 675 676 677 678 679 680 681 682

    $string =~ s/(&\w+;)/$specialchars{$1}/ge;
    return $string;
}

# Die
sub fatal($)
{
    my ($msg) = @_;

    die("*** $0:\n".
	"    $msg\n");
}