VirtExperiment.pm.in 31.8 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2009-2014, 2016 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file 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 Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33
#
package VirtExperiment;
use strict;
use Carp;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
34 35
use emdb;
use emutil;
36 37 38 39 40
use libtestbed;
use Data::Dumper;
use overload ('""' => 'Stringify');

use vars qw($STORE_FLAGS_DEBUG $STORE_FLAGS_IMPOTENT $STORE_FLAGS_SIMPARSE
41
            $STORE_FLAGS_REPLACE
42 43 44 45 46 47 48 49
	    $LOOKUP_FLAGS_NOLOAD
	    %virtual_tables %experiment_fields
	    $AUTOLOAD @EXPORT_OK);

# Store() flags.
$STORE_FLAGS_DEBUG	= 0x01;
$STORE_FLAGS_IMPOTENT	= 0x02;
$STORE_FLAGS_SIMPARSE	= 0x04;
50
$STORE_FLAGS_REPLACE    = 0x08;
51 52 53 54 55
# Lookup Flags
$LOOKUP_FLAGS_NOLOAD    = 0x01;

# Why, why, why?
@EXPORT_OK = qw($STORE_FLAGS_DEBUG $STORE_FLAGS_IMPOTENT
56 57
		$STORE_FLAGS_SIMPARSE $STORE_FLAGS_REPLACE
                $LOOKUP_FLAGS_NOLOAD);
58 59 60 61 62 63 64 65 66

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

# Cache of instances to avoid regenerating them.
my %virtexperiments   = ();
67
BEGIN { use emutil; emutil::AddCache(\%virtexperiments); }
68 69 70 71 72 73 74
my $debug	      = 0;

#
# Describe the virt tables and their primary keys. 
#
%virtual_tables = 
    ("virt_nodes"		=> [ "vname" ],
75
     "virt_lans"		=> [ "vname", "vnode", "vport"],
76 77 78 79
     "virt_lan_lans"		=> [ "vname" ],
     "virt_lan_settings"	=> [ "vname", "capkey" ],
     "virt_lan_member_settings" => [ "vname", "member", "capkey" ],
     "virt_trafgens"		=> [ "vname", "vnode" ],
80
     "virt_agents"		=> [ "vname", "vname", "vnode" ],
81 82 83 84 85
     "virt_node_desires"	=> [ "vname", "desire" ],
     "virt_node_startloc"	=> [ "vname", "building" ],
     "virt_routes"		=> [ "vname", "src", "dst" ],
     "virt_vtypes"		=> [ "name" ],
     "virt_programs"		=> [ "vname", "vnode" ],
86
     "virt_node_attributes"	=> [ "vname", "attrkey" ],
87
     "virt_node_disks"		=> [ "vname", "diskname" ],
88
     "virt_user_environment"	=> [ "name", "value" ],
89
     "virt_bridges"		=> [ "vname", "vlink", "vport"],
90
     "nseconfigs"		=> [ "vname" ],
91
     "eventlist"		=> [ "idx" ],
92 93 94
     "event_groups"		=> [ "group_name", "agent_name" ],
     "virt_firewalls"		=> [ "fwname", "type", "style" ],
     "firewall_rules"		=> [ "fwname", "ruleno", "rule" ],
95
     "elabinelab_attributes"	=> [ "role", "attrkey", "ordering" ],
96 97
     "virt_tiptunnels"		=> [ "host", "vnode" ],
     "virt_parameters"          => [ "name", "value" ],
98
     "virt_paths"		=> [ "pathname", "segmentname"],
99
     "experiment_blobs"         => [ "path", "action" ],
100 101 102 103 104
     "virt_blobs"               => [ "vblob_id", "filename" ],
     "virt_client_service_ctl"  => [ "vnode", "service_idx", "env", "whence" ],
     "virt_client_service_hooks"=> [ "vnode", "service_idx", "env", "whence",
				     "hook_vblob_id" ],
     "virt_client_service_opts" => [ "vnode", "opt_name", "opt_value" ],
105 106
     "virt_blockstores"		=> [ "vname" ],
     "virt_blockstore_attributes" => [ "vname", "attrkey" ],
107
     "virt_address_allocation"  => [ "pool_id" ],
108 109
);

110
# 
111
# The experiment table is special. Only certain fields are allowed to
112
# be updated.
113 114
#
%experiment_fields = ("multiplex_factor"	=> 1,
115
		      "packing_strategy"        => 1,
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
		      "forcelinkdelays"		=> 1,
		      "uselinkdelays"		=> 1,
		      "usewatunnels"		=> 1,
		      "uselatestwadata"		=> 1,
		      "wa_delay_solverweight"	=> 1,
		      "wa_bw_solverweight"	=> 1,
		      "wa_plr_solverweight"	=> 1,
		      "cpu_usage"		=> 1,
		      "mem_usage"		=> 1,
		      "allowfixnode"		=> 1,
		      "encap_style"		=> 1,
		      "jail_osname"		=> 1,
		      "delay_osname"		=> 1,
		      "sync_server"		=> 1,
		      "use_ipassign"		=> 1,
		      "ipassign_args"		=> 1,
		      "usemodelnet"		=> 1,
		      "modelnet_cores"		=> 1,
		      "modelnet_edges"		=> 1,
		      "elab_in_elab"		=> 1,
		      "elabinelab_eid"		=> 1,
		      "elabinelab_cvstag"	=> 1,
		      "elabinelab_singlenet"	=> 1,
		      "security_level"		=> 1,
		      "delay_capacity"		=> 1,
141
		      "dpdb"			=> 1,
142 143
		      "nonfsmounts"		=> 1,
		      "nfsmounts"		=> 1);
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

#
# Grab the virtual topo for an experiment.
#
sub Lookup($$;$)
{
    my ($class, $experiment, $flags) = @_;
    $flags = 0
	if (!defined($flags));
    
    my $noload = ($flags & $LOOKUP_FLAGS_NOLOAD ? 1 : 0);

    return undef
	if (!ref($experiment));

    my $idx = $experiment->idx();

    # Look in cache first
    return $virtexperiments{"$idx"}
        if (exists($virtexperiments{"$idx"}));

    my $self              = {};
    $self->{'EXPERIMENT'} = $experiment;
    bless($self, $class);

    # Load all the virt tables.
    foreach my $tablename (keys(%virtual_tables)) {
171 172 173 174
	my $table = VirtExperiment::VirtTable->Create($self, $tablename);
	if (!defined($table)) {
	    carp("Could not create table object for $tablename");
	    return undef;
175
	}
176 177 178 179 180
	if (!$noload) {
	    if ($table->Load() != 0) {
		carp("Could not load rows for $table");
		return undef;
	    }
181
	}
182
	$self->{'TABLES'}->{$tablename} = $table;	
183 184 185 186 187 188 189 190 191 192 193 194 195
    }

    # Make a copy of the experiment DBrow, and delete all the stuff we
    # are not allowed to change through this interface.
    my $dbrow  = $experiment->dbrow();
    my $newrow = {}; 

    foreach my $key (keys(%{ $dbrow })) {
	$newrow->{$key} = $dbrow->{$key}
	    if (exists($experiment_fields{$key}));
    }
    $self->{'DBROW'} = $newrow;

196 197 198
    # Add to cache.
    $virtexperiments{"$idx"} = $self;

199 200 201 202 203
    return $self;
}
# accessors
sub experiment($)       { return $_[0]->{'EXPERIMENT'}; }
sub dbrow($)            { return $_[0]->{'DBROW'}; }
204
sub table($$)		{ return $_[0]->{'TABLES'}->{$_[1]}; }
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
sub pid($)		{ return $_[0]->experiment()->pid(); }
sub pid_idx($)		{ return $_[0]->experiment()->pid_idx(); }
sub eid($)		{ return $_[0]->experiment()->eid(); }
sub exptidx($)		{ return $_[0]->experiment()->idx(); }

# To avoid wrtting out all the methods.
sub AUTOLOAD {
    my $self = shift;
    my $type = ref($self) or croak "$self is not an object";

    my $name = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    unless (exists($experiment_fields{$name})) {
	carp("No such slot '$name' field in class $type");
	return undef;
    }
    if (@_) {
	return $self->{'DBROW'}->{$name} = shift;
    }
    else {
	return $self->{'DBROW'}->{$name};
    }
}

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{'DBROW'}      = undef;
    $self->{'EXPERIMENT'} = undef;
}

#
# Create a new experiment virtual topology. This means loading the
# experiment, but not any of the virt tables. We never create a new
# "experiment" via this path, just a new virt topology for an existing
# experiment.
#
sub CreateNew($$)
{
    my ($class, $experiment) = @_;

    return VirtExperiment->Lookup($experiment, $LOOKUP_FLAGS_NOLOAD);
}

#
# Add a new empty table row. Caller must populate it.
#
254
sub NewTableRow($$$)
255
{
256
    my ($self, $tablename, $argref) = @_;
257 258 259 260 261 262
    
    return undef
	if (! ref($self));
    return undef
	if (!exists($virtual_tables{$tablename}));

263 264 265 266 267
    my $table = $self->{'TABLES'}->{$tablename};
    my $row   = $table->NewRow($argref);
    if (!defined($row)) {
	carp("Could not create new table row in $self");
	return undef;
268
    }
269
    return $row;
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
}

#
# Store the experiment back to the DB. Includes the experiment table itself.
#
sub Store($;$)
{
    my ($self, $flags) = @_;
    $flags = 0
	if (!defined($flags));
    
    my $debug    = ($flags & $STORE_FLAGS_DEBUG ? 1 : 0);
    my $impotent = ($flags & $STORE_FLAGS_IMPOTENT ? 1 : 0);
    my $simparse = ($flags & $STORE_FLAGS_SIMPARSE ? 1 : 0);
    my $exptidx  = $self->exptidx();
    my $pid      = $self->pid();
    my $eid      = $self->eid();

    # If these are the results of parsing the nse specifications,
    # we do not expect updates to the experiments table.
    goto skip
	if ($simparse);

    #
    # Delete anything we are not allowed to set via this interface.
    #
    my $dbrow = $self->dbrow();
    
    foreach my $key (keys(%{ $dbrow })) {
	delete($dbrow->{$key})
	    if (! exists($experiment_fields{$key}));
    }

    #
    # Get the default values for the required fields.
    #
    my $describe_result =
	DBQueryWarn("describe experiments");
    return -1
	if (!defined($describe_result) || !$describe_result->numrows);

    #
    # Insert the default values for slots that we do not have
    # so that we can set them properly in the DB query.
    #
    while (my $rowref = $describe_result->fetchrow_hashref()) {
	my $slot  = $rowref->{"Field"};
	my $value = $rowref->{"Default"};

	if (exists($experiment_fields{$slot}) &&
	    ! exists($dbrow->{$slot})) {
	    $dbrow->{$slot} = (defined($value) ? $value : "NULL");
	}
    }

    my @setlist  = ();
    
    foreach my $key (keys(%{ $dbrow })) {
	my $val = $dbrow->{$key};

	# Always skip these; they come from the experiment object. Prevents
	# users from messing up the DB with a bogus XML file.
	next
	    if ($key eq "pid" ||$key eq "eid" || $key eq "idx");

	if (!defined($val) ||
	    $val eq "NULL" || $val eq "__NULL__" || $val eq "") {
	    push(@setlist, "$key=NULL");
	}
	else {
	    # Sanity check the fields.
	    if (TBcheck_dbslot($val, "experiments", $key,
342 343
			       TBDB_CHECKDBSLOT_WARN()|
			       TBDB_CHECKDBSLOT_ERROR())) {
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
		$val = DBQuoteSpecial($val);
		    
		push(@setlist, "$key=$val");
	    }
	    else {
		carp("Illegal characters in table data: experiments:".
		     "$key - $val");
		return -1;
	    }
	}	    
    }
    my $query =
	"update experiments ".
	"set " . join(",", @setlist) . " where idx='$exptidx'";

    print "$query\n"
	if ($debug);

    return -1
	if (!$impotent && !DBQueryWarn($query));
  skip:

    #
    # And then the virt table rows. First need to delete them all.
    #
    if (!$impotent) {
	#
	# Need this below:
	#
	my $query_result =
	    DBQueryWarn("select idx from event_objecttypes where type='NSE'");
	return -1
	    if (!defined($query_result) || !$query_result->numrows);
	my ($nse_objtype) = $query_result->fetchrow_array();
	
	foreach my $tablename (keys(%virtual_tables)) {
	    if ($simparse) {
		#
		# 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 ($tablename eq "nseconfigs") {
		    DBQueryWarn("delete from $tablename ". 
				"where eid='$eid' and pid='$pid' and ".
				"vname!='fullsim'")
			or return -1;
		}
		elsif ($tablename eq "eventlist" ||
		       $tablename 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
		    #
		    DBQueryWarn("delete from $tablename ". 
				"where pid='$pid' and eid='$eid' and ".
				"objecttype='$nse_objtype'")
			or return -1;
		} 
	    }
	    else {
		#
		# In normal mode all rows deleted. During the nse parse,
		# leave the other tables alone.
		#
		DBQueryWarn("delete from $tablename ".
			    "where eid='$eid' and pid='$pid'")
		    or return -1;
	    }
	}
    }
419

420
    foreach my $tablename (keys(%virtual_tables)) {
421 422 423 424 425
	if (exists($self->{'TABLES'}->{$tablename})) {
	    my $table = $self->{'TABLES'}->{$tablename};
	    if ($table->Store($flags) != 0) {
		carp("Could not store table $table");
		return -1;
426 427 428 429 430 431
	    }
	}
    }
    return 0;
}

432 433 434 435 436 437 438 439 440 441 442 443 444
#
# Find a particular row in a table.
#
sub Find($$@)
{
    my $self = shift();
    my $tablename = shift();
    my @args = @_;

    if (!exists($self->{'TABLES'}->{$tablename})) {
	warn("Find: unknown table search: $tablename");
	return undef;
    }
445 446
    my $table = $self->{'TABLES'}->{$tablename};
    return $table->Find(@args);
447 448 449
}

#
450
# Return a table.
451
#
452
sub Table($$)
453
{
454 455
    my $self = shift();
    my $tablename = shift();
456

457 458 459
    if (!exists($self->{'TABLES'}->{$tablename})) {
	warn("Table: unknown table: $tablename");
	return undef;
460
    }
461
    return $self->{'TABLES'}->{$tablename};
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
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

    delete($virtexperiments{$self->exptidx()});
}

#
# Dump the contents of virt tables.
#
sub Dump($)
{
    my ($self) = @_;

    my $dbrow = $self->dbrow();

    print $self . "\n";
    foreach my $key (keys(%{ $dbrow })) {
	my $val = $dbrow->{$key};
	$val = "NULL"
	    if (!defined($val));
	    
	print "  $key : $val\n";
    }

    foreach my $tablename (keys(%virtual_tables)) {
493 494 495
	if (exists($self->{'TABLES'}->{$tablename})) {
	    my $table = $self->{'TABLES'}->{$tablename};
	    $table->Dump();
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
	}
    }
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    return -1;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid   = $self->pid();
    my $eid   = $self->eid();
    my $idx   = $self->exptidx();

    return "[VirtExperiment: $pid/$eid/$idx]";
}

############################################################################
#
529 530 531 532 533 534 535
# VirtTable wraps up a bunch of table rows.
#
package VirtExperiment::VirtTable;
use Carp;
use English;
use overload ('""' => 'Stringify');
use libdb;
536
use emutil;
537 538
use VirtExperiment;

539 540
my %dbslotnames = ();

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
#
# A table 
#
sub Create($$$)
{
    my ($class, $virtexperiment, $tablename) = @_;

    $class = ref($class) || $class;
    my $experiment = $virtexperiment->experiment();
    my $slotnames;

    #
    # See if we have loaded the DB defs for this table.
    #
    my $varname = $tablename . "_dbdefs";
556 557
    if (defined($dbslotnames{$varname})) {
	$slotnames = $dbslotnames{$varname};
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
    }
    else {
	$slotnames = {};

	my $describe_result =
	    DBQueryWarn("describe $tablename");

	return -1
	    if (!defined($describe_result) || !$describe_result->numrows);

	#
	# Record the default values for slots.
	#
	while (my $rowref = $describe_result->fetchrow_hashref()) {
	    my $slot  = $rowref->{"Field"};
	    my $value = $rowref->{"Default"};

	    $slotnames->{$slot} = $value;
	}
577
	$dbslotnames{$varname} = $slotnames;
578 579 580 581 582 583 584 585 586
    }
    
    my $self = {};
    $self->{'TABLENAME'}  = $tablename;
    $self->{'EXPERIMENT'} = $experiment;
    $self->{'VIRTEXPT'}   = $virtexperiment;
    $self->{'SLOTNAMES'}  = $slotnames;
    $self->{'TABLEHASH'}  = {};
    $self->{'TABLELIST'}  = [];
587
    $self->{'COUNTER'}    = 1;
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    bless($self, $class);

    return $self;
}
sub experiment($)       { return $_[0]->{'EXPERIMENT'}; }
sub virtexperiment($)   { return $_[0]->{'VIRTEXPT'}; }
sub tablename($)        { return $_[0]->{'TABLENAME'}; }
sub slotnames($)        { return $_[0]->{'SLOTNAMES'}; }
sub tablelist($)        { return $_[0]->{'TABLELIST'}; }
sub tablehash($)        { return $_[0]->{'TABLEHASH'}; }

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{'TABLENAME'}  = undef;
    $self->{'EXPERIMENT'} = undef;
    $self->{'VIRTEXPT'}   = undef;
    $self->{'SLOTNAMES'}  = undef;
    $self->{'TABLEHASH'}  = undef;
    $self->{'TABLELIST'}  = undef;
609
    $self->{'COUNTER'}    = undef;
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
}

#
# Lookup the rows for a table from the DB.
#
sub Load($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $experiment = $self->experiment();
    my $exptidx    = $experiment->idx();
    my $tablename  = $self->tablename();
    
    return -1
	if (!exists($VirtExperiment::virtual_tables{$tablename}));

    my $query_result =
	DBQueryWarn("select * from $tablename where exptidx=$exptidx");

    return -1
	if (!defined($query_result));
    return 0
	if (!$query_result->numrows);

    while (my $row = $query_result->fetchrow_hashref()) {
	my $tablerow = $self->NewRow($row);
	if (!defined($tablerow)) {
	    return -1;
	}
    }
    return 0;
}

#
# Create a new table row.
#
sub NewRow($$)
{
    my ($self, $argref) = @_;
    
    my $tablename  = $self->tablename();
    my $class = "VirtExperiment::VirtTableRow::$tablename";
    my $obj   = $class->Create($self);

    #
    # These are the required keys, they must be defined for the new row
    # to make any sense. Other slots can be filled in later of course.
    #
    my @pkeys = @{$VirtExperiment::virtual_tables{$tablename}};
    my @pvals = ();
    foreach my $key (@pkeys) {
	if (!exists($argref->{$key})) {
665 666 667 668
	    if ($tablename eq "eventlist" && $key eq "idx") {
		$argref->{$key} = $self->{'COUNTER'}++;
	    }
	    else {
669
		carp("Missing table key $key for new table in $tablename");
670 671
		return undef;
	    }
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
	}
	push(@pvals, $argref->{$key});
    }
    # This is the full key. Make sure it does not already exist.
    my $akey = join(":", @pvals);
    if (exists($self->{'TABLEHASH'}->{$akey})) {
	carp("Already have entry for '$akey' in $self");
	return undef;
    }
    foreach my $key (keys(%{$argref})) {
	$obj->$key($argref->{$key});
    }

    # Add to list of rows for this table.
    push(@{ $self->{'TABLELIST'} }, $obj);
    # And to the hash array using the pkey.
    $self->{'TABLEHASH'}->{$akey} = $obj;

    return $obj;
}

#
# Dump out rows for table.
#
sub Dump($)
{
    my ($self) = @_;

    my @rows = @{ $self->{'TABLELIST'} };

    return
	if (!@rows);
	    
    foreach my $rowref (@rows) {
	$rowref->Dump();
    }
}

#
# Store rows for table.
#
713
sub Store($$)
714
{
715
    my ($self,$flags) = @_;
716 717 718 719 720 721 722

    my @rows = @{ $self->{'TABLELIST'} };

    return 0
	if (!@rows);
	    
    foreach my $rowref (@rows) {
723
	$rowref->Store($flags) == 0
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
	    or return -1;
    }
    return 0;
}

#
# Return list of rows.
#
sub Rows($)
{
    my ($self) = @_;
    my @rows   = @{ $self->{'TABLELIST'} };

    return @rows;
}

#
# Find a particular row in a table.
#
sub Find($@)
{
    my $self = shift();
    my @args = @_;
    my $tablename = $self->tablename();

    # No members.
    return undef
	if (! @{ $self->{'TABLELIST'} });

    # Get the slotnames that determine the lookup from the table above.
    if (!exists($VirtExperiment::virtual_tables{$tablename})) {
	warn("Find: No entry in virtual_tables for $tablename");
	return undef;
    }
    my @pkeys = @{ $VirtExperiment::virtual_tables{$tablename} };
    if (scalar(@pkeys) != scalar(@args)) {
	warn("Find: Wrong number of arguments for lookup in $self");
	return undef;
    }
    # This is the full key. 
    my $akey = join(":", @args);

    return $self->{'TABLEHASH'}->{$akey};
}

#
# Delete a row in a table. Do not call this. Utility for below.
#
sub _deletetablerow($$)
{
    my ($self, $row) = @_;

    my $tablename = $self->tablename();
    my @newrows   = ();

    my @rows = @{ $self->{'TABLELIST'} };
    foreach my $rowref (@rows) {
	push(@newrows, $rowref)
	    if (! ($rowref->SameRow($row)));
    }
784
    $self->{'TABLELIST'} = \@newrows;
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

    my @keys = keys(%{ $self->{'TABLEHASH'} });
    foreach my $key (@keys) {
	my $ref = $self->{'TABLEHASH'}->{$key};
	
	if ($ref->SameRow($row)) {
	    delete($self->{'TABLEHASH'}->{$key});
	    last;
	}
    }
    return 0;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;

    my $table = $self->tablename();
    my $pid   = ($self->experiment() ? $self->experiment()->pid() : "?");
    my $eid   = ($self->experiment() ? $self->experiment()->eid() : "?");
    my $idx   = ($self->experiment() ? $self->experiment()->idx() : "?");

    return "[$table: $pid/$eid/$idx]";
}


############################################################################
#
# VirtTableRow is a superclass to avoid a bunch of typing. It wraps up DB
817 818 819 820 821 822 823 824 825
# table rows with methods, but without having to type all the stuff out
# for each virt table.
#
package VirtExperiment::VirtTableRow;
use Carp;
use English;
use overload ('""' => 'Stringify');
use vars qw($AUTOLOAD);
use libdb;
826
use emutil;
827 828 829 830 831 832 833 834 835 836 837 838
use VirtExperiment;

sub AUTOLOAD {
    my $self = shift;
    my $type = ref($self) or croak "$self is not an object";

    my $name = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    my $row = $self->tablerow();

    unless (exists($self->{'SLOTNAMES'}->{$name})) {
839
	print STDERR "No such slot '$name' field in class $type\n";
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
	return undef;
    }
    if (@_) {
	return $self->{'TABLEROW'}->{$name} = shift;
    }
    else {
	return $self->{'TABLEROW'}->{$name};
    }
}

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{'TABLEROW'}   = undef;
    $self->{'TABLENAME'}  = undef;
    $self->{'EXPERIMENT'} = undef;
857
    $self->{'TABLE'}      = undef;
858 859 860
    $self->{'SLOTNAMES'}  = undef;
}

861 862 863 864 865 866 867
sub SameRow($$)
{
    my ($this, $that) = @_;

    return $this->tablerow() == $that->tablerow();
}

868 869 870 871 872
#
# A table row. 
#
sub Create($$$)
{
873
    my ($class, $table, $tablerow) = @_;
874 875

    $class = ref($class) || $class;
876
    my $experiment = $table->experiment();
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    my $tablename;
    my $slotnames;

    # The intent is to allow contruction of a virtual topo from scratch.
    $tablerow = {} if (!defined($tablerow));

    if ($class =~ /^VirtExperiment::VirtTableRow::(.*)$/) {
	$tablename = $1;
    }
    else {
	croak("$class is not in correct format");
    }

    #
    # See if we have loaded the DB defs for this table.
    #
    my $varname = $tablename . "_dbdefs";
894 895
    if (defined($dbslotnames{$varname})) {
	$slotnames = $dbslotnames{$varname};
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
    }
    else {
	$slotnames = {};

	my $describe_result =
	    DBQueryWarn("describe $tablename");

	return -1
	    if (!defined($describe_result) || !$describe_result->numrows);

	#
	# Record the default values for slots.
	#
	while (my $rowref = $describe_result->fetchrow_hashref()) {
	    my $slot  = $rowref->{"Field"};
	    my $value = $rowref->{"Default"};

	    $slotnames->{$slot} = $value;
	}
915
	$dbslotnames{$varname} = $slotnames;
916 917 918 919 920 921
    }
    
    my $self = {};
    $self->{'TABLEROW'}   = $tablerow;
    $self->{'TABLENAME'}  = $tablename;
    $self->{'EXPERIMENT'} = $experiment;
922
    $self->{'TABLE'}      = $table;
923 924 925 926 927 928
    $self->{'SLOTNAMES'}  = $slotnames;
    bless($self, $class);

    return $self;
}
sub experiment($)       { return $_[0]->{'EXPERIMENT'}; }
929
sub table($)            { return $_[0]->{'TABLE'}; }
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
sub tablename($)        { return $_[0]->{'TABLENAME'}; }
sub tablerow($)         { return $_[0]->{'TABLEROW'}; }
sub slotnames($)        { return $_[0]->{'SLOTNAMES'}; }

#
# Store a single table row to the DB.
#
sub Store($;$)
{
    my ($self, $flags) = @_;
    $flags = 0
	if (!defined($flags));
    
    my $debug    = ($flags & $VirtExperiment::STORE_FLAGS_DEBUG ? 1 : 0);
    my $impotent = ($flags & $VirtExperiment::STORE_FLAGS_IMPOTENT ? 1 : 0);
    my $simparse = ($flags & $VirtExperiment::STORE_FLAGS_SIMPARSE ? 1 : 0);
946
    my $replace  = ($flags & $VirtExperiment::STORE_FLAGS_REPLACE ? 1 : 0);
947
    my $tablename= $self->tablename();
948 949 950
    my $row      = $self->tablerow();
    my $pid      = $self->experiment()->pid();
    my $eid      = $self->experiment()->eid();
951
    my $exptidx  = $self->experiment()->idx();
952 953

    # These are the required keys, they must be defined.
954 955
    my %pkeys   =
	map { $_ => $_ } @{$VirtExperiment::virtual_tables{$tablename}};
956 957
    
    my @fields  = ("exptidx", "pid", "eid");
958
    my @values  = ("'$exptidx'", "'$pid'", "'$eid'");
959

960 961 962 963 964 965 966 967 968
    foreach my $key (keys(%{ $row })) {
	my $val = $row->{$key};

	# Always skip these; they come from the experiment object. Prevents
	# users from messing up the DB with a bogus XML file.
	next
	    if ($key eq "pid" ||$key eq "eid" || $key eq "exptidx");
	
	if ($key eq "idx") {
969 970 971 972 973
	    # This test for eventlist.
	    if ($tablename eq "eventlist") {
		push(@values, "NULL");
	    }
	    elsif ($val =~ /^\d*$/) {
974 975 976
		push(@values, DBQuoteSpecial($val));
	    }
	    else {
977 978
		carp("Illegal characters in table data: ".
		     "$tablename:$key - $val\n");
979 980 981 982 983 984 985 986 987 988 989
		return -1;
	    }
	}
	elsif (!defined($val) || $val eq "NULL") {
	    push(@values, "NULL");
	}
	elsif ($val eq "") {
	    push(@values, "''");
	}
	else {
	    # Sanity check the fields.
990
	    if (TBcheck_dbslot($val, $tablename, $key,
991 992
			       TBDB_CHECKDBSLOT_WARN()|
			       TBDB_CHECKDBSLOT_ERROR())) {
993 994 995
		push(@values, DBQuoteSpecial($val));
	    }
	    else {
996 997
		carp("Illegal characters in table data for $tablename:\n".
		     "    $key - $val: ". TBFieldErrorString() . "\n");
998 999 1000
		return -1;
	    }
	}
1001 1002 1003
	# If a key remove from the list; we got it.
	delete($pkeys{$key})
	    if (exists($pkeys{$key}));
1004 1005 1006 1007 1008 1009 1010
	push(@fields, $key);
    }
    if (keys(%pkeys)) {
	carp("Missing primary keys in $self");
	return -1;
    }
    my $query;
1011
    if ($simparse || $replace) {
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
	#
	# 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
	#
	$query =
1022
	    "replace into $tablename (" . join(",", @fields) . ") ".
1023 1024 1025 1026
	    "values (" . join(",", @values) . ") ";
    }
    else {
	$query =
1027
	    "insert into $tablename (" . join(",", @fields) . ") ".
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
	    "values (" . join(",", @values) . ") ";
    }
  
    print "$query\n"
	if ($debug);

    return -1
	if (!$impotent && !DBQueryWarn($query));

    return 0;
}

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
#
# Delete a row.
#
sub Delete($;$)
{
    my ($self, $flags) = @_;
    $flags = 0
	if (!defined($flags));
    
    my $debug    = ($flags & $VirtExperiment::STORE_FLAGS_DEBUG ? 1 : 0);
    my $impotent = ($flags & $VirtExperiment::STORE_FLAGS_IMPOTENT ? 1 : 0);
    my $exptidx  = $self->experiment()->idx();
1052 1053
    my $table    = $self->table();
    my $tablename= $self->tablename();
1054 1055 1056
    my $row      = $self->tablerow();

    # These are the keys for the table.
1057 1058
    my %pkeys   =
	map { $_ => $_ } @{$VirtExperiment::virtual_tables{$tablename}};
1059 1060 1061 1062 1063 1064

    # Gets values for the keys, to use in the query below.
    foreach my $key (keys(%pkeys)) {
	$pkeys{$key} = $row->{$key};
    }

1065
    my $query = "delete from $tablename where exptidx=$exptidx and ".
1066 1067 1068 1069 1070 1071 1072 1073 1074
	join(" and ", map("$_='" . $pkeys{$_} . "'", keys(%pkeys)));
    
    print "$query\n"
	if ($debug);

    if (!$impotent) {
	return -1
	    if (!DBQueryWarn($query));

1075
	$table->_deletetablerow($self);
1076 1077 1078 1079
    }
    return 0;
}

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
#
# Dump the contents of virt tables.
#
sub Dump($)
{
    my ($self) = @_;

    my $dbrow = $self->tablerow();

    print $self . "\n";
    foreach my $key (keys(%{ $dbrow })) {
	my $val = $dbrow->{$key};
	$val = "NULL"
	    if (!defined($val));
	    
	print "  $key : $val\n";
    }
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;

    my $table = $self->tablename();
    my $row   = $self->tablerow();
    my $pid   = ($self->experiment() ? $self->experiment()->pid() : "?");
    my $eid   = ($self->experiment() ? $self->experiment()->eid() : "?");
    my $idx   = ($self->experiment() ? $self->experiment()->idx() : "?");

    my @keys   = @{ $VirtExperiment::virtual_tables{$table} };
    my @values = map { $row->{$_} } @keys;
    @values    = map { (defined($_) ? $_ : "NULL") } @values;
    my $keystr = join(",", @values);

    return "[$table: $pid/$eid/$idx $keystr]";
}

############################################################################
# And now subclasses for each virtual table.
#
package VirtExperiment::VirtTableRow::virt_nodes;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_lans;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_lan_lans;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_lan_settings;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_lan_member_settings;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_trafgens;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_agents;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_node_desires;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_node_startloc;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_routes;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_vtypes;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_programs;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1183 1184 1185 1186 1187
package VirtExperiment::VirtTableRow::virt_node_attributes;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1188 1189 1190 1191 1192
package VirtExperiment::VirtTableRow::virt_node_disks;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
package VirtExperiment::VirtTableRow::virt_user_environment;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::nseconfigs;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::eventlist;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::event_groups;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_firewalls;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::firewall_rules;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_tiptunnels;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_parameters;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1233 1234 1235 1236 1237
package VirtExperiment::VirtTableRow::elabinelab_attributes;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1238 1239 1240 1241 1242
package VirtExperiment::VirtTableRow::virt_paths;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1243 1244 1245 1246
package VirtExperiment::VirtTableRow::experiment_blobs;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_blobs;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_client_service_ctl;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_client_service_hooks;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_client_service_opts;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;
1268

1269 1270 1271 1272 1273
package VirtExperiment::VirtTableRow::virt_bridges;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
package VirtExperiment::VirtTableRow::virt_blockstores;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

package VirtExperiment::VirtTableRow::virt_blockstore_attributes;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1284 1285 1286 1287 1288
package VirtExperiment::VirtTableRow::virt_address_allocation;
use vars qw(@ISA);
@ISA = "VirtExperiment::VirtTableRow";
use VirtExperiment;

1289 1290
# _Always_ make sure that this 1 is at the end of the file...
1;