Lan.pm.in 89 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2014 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 34 35 36
#
package Lan;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

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

# Must come after package declaration!
use libdb;
use libtestbed;
use Node;
37 38
# Doesn't seem to be used presently...
# use Port;
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');
use vars qw(@EXPORT_OK);

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

# Why, why, why?
@EXPORT_OK = qw();

# Cache of instances to avoid regenerating them.
my %lans   = ();

my $debug  = 0;
sub debugging() {return $debug; }

# Set during initial crossover.
my $initialize = 0;

62 63 64 65 66 67
my %LanTables = ("lans"           => ["lanid"],
		 "lan_attributes" => ["lanid", "attrkey"],
		 "lan_members"    => ["lanid", "memberid"],
		 "lan_member_attributes" => ["lanid", "memberid", "attrkey"],
		 "ifaces"         => ["lanid", "ifaceid"]);

68 69 70
#
# Initialize Openflow attributes in lan_attributes table.
#
71
sub InitOpenflowAttributes($$$$)
72
{
73
    my ($class, $exptidx, $vname, $lanid) = @_;
74 75 76 77 78 79 80 81

    my $ofenabled = 0;
    my $ofcontroller = "";
    my $safe_val;
    
    # Add openflow arrtibutes:
    my $query_result =
	DBQueryWarn("select ofenabled, ofcontroller from virt_lans ".
82
		    "where exptidx='$exptidx' and vname='$vname'");
83 84 85
    return 0
	if (!$query_result);	
    ($ofenabled, $ofcontroller) = $query_result->fetchrow_array()
86 87 88
	if ($query_result->numrows);
    $ofcontroller = ""
	if (!$ofenabled || !defined($ofcontroller));
89 90 91 92 93 94 95 96 97 98
	
    #
    # Firstly check if the attribuets are there, if no values, 
    # insert them. This is because the vlan may be created
    # by Lookup many times. The values can be overwritten by
    # the later creation.
    #
    # Process 'ofenabled':
    $query_result =
	DBQueryWarn("select attrvalue from lan_attributes ".
99
		    "where lanid='$lanid' and attrkey='ofenabled'");
100 101 102 103 104 105 106
    return 0
	if (!$query_result);
    if (!$query_result->numrows)
    {
	$safe_val = DBQuoteSpecial($ofenabled);
	$query_result =
	    DBQueryWarn("replace into lan_attributes set ".
107
			"  lanid='$lanid', ".
108 109 110 111 112 113 114 115 116 117
			"  attrkey='ofenabled', ".
			"  attrvalue=$safe_val, ".
			"  attrtype='integer'");
	return 0
	    if (!defined($query_result));	  
    }
    
    # Process 'ofcontroller':
    $query_result =
	DBQueryWarn("select attrvalue from lan_attributes ".
118
		    "where lanid='$lanid' and attrkey='ofcontroller'");
119 120 121 122 123 124 125
    return 0
	if (!$query_result);
    if (!$query_result->numrows)
    {
	$safe_val = DBQuoteSpecial($ofcontroller);
	$query_result =
	    DBQueryWarn("replace into lan_attributes set ".
126
			"  lanid='$lanid', ".
127 128 129 130 131 132 133 134 135 136
			"  attrkey='ofcontroller', ".
			"  attrvalue=$safe_val, ".
			"  attrtype='string'");
	return 0
	    if (!defined($query_result));	  
    }

    # Process 'oflistener':
    $query_result =
	DBQueryWarn("select attrvalue from lan_attributes ".
137
		    "where lanid='$lanid' and attrkey='oflistener'");
138 139 140 141 142 143 144
    return 0
	if (!$query_result);
    if (!$query_result->numrows)
    {
	$safe_val = DBQuoteSpecial("");
	$query_result =
	    DBQueryWarn("replace into lan_attributes set ".
145
			"  lanid='$lanid', ".
146 147 148 149 150 151 152 153 154 155 156
			"  attrkey='oflistener', ".
			"  attrvalue=$safe_val, ".
			"  attrtype='string'");
	return 0
	    if (!defined($query_result));	  
    }
    
    return 1;
}


157 158 159
#
# Lookup and create a class instance to return.
#
160
sub Lookup($$;$$)
161
{
162
    my ($class, $arg1, $arg2, $linkokay) = @_;
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
    my $lanid;
    my $experiment;

    #
    # A single arg is a lanid. Two args is exptidx and vname (lan name).
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
	    $lanid = $1;
	}
	else {
	    return undef;
	}
    }
    elsif (ref($arg1) && ($arg2 =~ /^[-\w]*$/)) {
	# Assumed to be an experiment object.
	$experiment = $arg1;
	$arg1 = $experiment->idx();
    }
    elsif (! (($arg1 =~ /^\d*$/) && ($arg2 =~ /^[-\w]*$/))) {
	return undef;
    }

    #
    # Two args means lookup by exptidx,vname.
    #
    if (defined($arg2)) {
190
	my $clause = (!defined($linkokay) ? "and link is null" : "");
191 192
	my $result =
	    DBQueryWarn("select lanid from lans ".
193
			"where exptidx='$arg1' and vname='$arg2' $clause");
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

	return undef
	    if (! $result || !$result->numrows);

	($lanid) = $result->fetchrow_array();
    }

    # Look in cache first
    return $lans{"$lanid"}
        if (exists($lans{"$lanid"}));
    
    my $query_result =
	DBQueryWarn("select * from lans where lanid='$lanid'");

    return undef
	if (!$query_result || !$query_result->numrows);

    my $self         = {};
    $self->{'LAN'}   = $query_result->fetchrow_hashref();
    $self->{"ATTRS"} = {};
    $self->{"EXPT"}  = $experiment;

216
    return undef
217
    	if (!Lan->InitOpenflowAttributes($self->{'LAN'}->{'exptidx'}, $self->{'LAN'}->{'vname'}, $lanid));
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
    #
    # Grab the attributes for this lan now.
    #
    $query_result =
	DBQueryWarn("select * from lan_attributes where lanid='$lanid'");
    return undef
	if (!$query_result);

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $key = $rowref->{'attrkey'};
	
	$self->{"ATTRS"}->{$key} = $rowref;
    }

    bless($self, $class);
    
    # Add to cache. 
    $lans{"$lanid"} = $self;

    return $self;
}

# accessors
sub field($$)     { return ((! ref($_[0])) ? -1 : $_[0]->{'LAN'}->{$_[1]}); }
sub pid($)	  { return field($_[0], 'pid'); }
sub eid($)	  { return field($_[0], 'eid'); }
sub exptidx($)	  { return field($_[0], 'exptidx'); }
sub lanid($)	  { return field($_[0], 'lanid'); }
sub vname($)	  { return field($_[0], 'vname'); }
sub vidx($)	  { return field($_[0], 'vidx'); }
sub ready($)	  { return field($_[0], 'ready'); }
sub link($)	  { return field($_[0], 'link'); }
sub type($)	  { return field($_[0], 'type'); }
252
sub locked($)	  { return field($_[0], 'locked'); }
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
#
# Lookup an internal vlan (in the vlan-holding experiment).
#
sub LookupInternal($$)
{
    my ($class, $vname) = @_;

    require Experiment;
    my $experiment = Experiment->Lookup(VLAN_PID(), VLAN_EID());
    return undef
	if (!defined($experiment));

    return Lan->Lookup($experiment, $vname);
}

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
#
# Create a new (empty) lan. Ready bit is set to zero. 
#
sub Create($$$;$$$)
{
    my ($class, $experiment, $vname, $type, $id, $link) = @_;

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

    my $pid     = $experiment->pid();
    my $eid     = $experiment->eid();
    my $exptidx = $experiment->idx();
    my $safe_vname = DBQuoteSpecial($vname);
    my $linkid  = (defined($link) ? $link->lanid() : "NULL");
    my $vidx    = 0;

    # Allow for the caller to specify the ID, as when converting from
    # existing vlans table.
    $id = "NULL"
	if (!defined($id));

    # We need the idx from the virt_lan_lans table.
    my $query_result =
	DBQueryWarn("select idx from virt_lan_lans ".
		    "where exptidx=$exptidx and vname='$vname'");
    return undef
	if (!$query_result);
    ($vidx) = $query_result->fetchrow_array()
	if ($query_result->numrows);

    $query_result =
	DBQueryWarn("insert into lans set ".
		    "   lanid=$id, ".
		    "   exptidx='$exptidx', ".
		    "   pid='$pid', eid='$eid', ".
		    "   vname=$safe_vname, ".
		    "   type='$type', ".
		    "   vidx='$vidx', ".
308
		    "   link=$linkid, ".
309 310 311 312 313 314 315
		    "   ready=0");
    return undef
	if (!defined($query_result));

    # Need the newly minted ID
    my $lanid = $query_result->insertid();
    my $lan   = Lan->Lookup($lanid);
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
    print "Created lan: $lan\n"
	if ($debug && $lan);
    return $lan;
}

#
# Destroy a lan and its attributes. 
#
sub Destroy($)
{
    my ($self) = @_;

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

    my $lanid = $self->lanid();
    my $type  = $self->type();

    #
    # List of members to destroy.
    #
    my @members;
    if ($self->MemberList(\@members) != 0) {
	print STDERR "Destroy: Could not get member list\n";
	return -1;
    }
    foreach my $member (@members) {
	#
	# Delete all members and interfaces and attributes.
	#
	my $memberid = $member->memberid();

	return -1
	    if (!DBQueryWarn("delete from lan_member_attributes ".
			     "where lanid='$lanid' and memberid='$memberid'"));
	return -1
	    if (!DBQueryWarn("delete from ifaces ".
			     "where lanid='$lanid' and ifaceid='$memberid'"));
	return -1
	    if (!DBQueryWarn("delete from lan_members ".
			     "where lanid='$lanid' and memberid='$memberid'"));
    }

    # Must delete attributes after above vlan removal but before lan removal.
    return -1
	if (!DBQueryWarn("delete from lan_attributes ".
			 "where lanid='$lanid'"));

    return -1
	if (!DBQueryWarn("delete from lans ".
			 "where lanid='$lanid'"));

    # From the cache. 
    delete($lans{"$lanid"});
    
    return 0;
}

#
# Class method to destroy all lans for an experiment.
377
# XXX Purge flag is for protogeni tunnels.
378
#
379
sub DestroyExperimentLans($$$)
380
{
381
    my ($class, $experiment, $purge) = @_;
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396

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

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

    my $query_result =
	DBQueryWarn("select lanid from lans where exptidx='$exptidx'");
    return -1
	if (! $query_result);

    while (my ($lanid) = $query_result->fetchrow_array()) {
	my $lan = Lan->Lookup($lanid);
	return -1
	    if (!$lan);
397 398 399 400 401 402 403 404 405 406
	
	if (!$purge && $lan->type() eq "tunnel") {
	    #
	    # XXX Terrible hack; Skip protogeni tunnels unless purging.
	    #
	    my $protogeni_tunnel;
	    next 
		if ($lan->GetAttribute("protogeni_tunnel",
				       \$protogeni_tunnel) == 0);
	}
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	$lan->Destroy() == 0 or return -1;
    }
    return 0;
}

#
# Class method to backup all lans for an experiment.
#
sub BackupExperimentLans($$$)
{
    my ($class, $experiment, $pstatedir) = @_;
    my @lanids = ();

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

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

    my $query_result =
	DBQueryWarn("select lanid from lans where exptidx='$exptidx'");
    return -1
	if (! $query_result);
429 430
    return 0
	if (! $query_result->numrows);
431 432 433 434 435 436

    while (my ($lanid) = $query_result->fetchrow_array()) {
	push(@lanids, $lanid);
    }
    foreach my $table ("lans", "lan_attributes", "lan_members",
		       "lan_member_attributes", "ifaces") {
437 438 439 440 441 442
	# This ordering is for wrapper/mapper regression testing. 
	my $orderby = "";
	if (exists($LanTables{$table}) &&
	    defined($LanTables{$table})) {
	    $orderby = "order by " . join(",", @{$LanTables{$table}});
	}
443 444
	DBQueryWarn("select * from $table where ".
		      join(" or ", map("lanid='$_'", @lanids)) . " " .
445
		    "$orderby into outfile '$pstatedir/$table'")
446 447
	    or return -1;
    }
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    
    return 0;
}

#
# Class method to restore all lans for an experiment.
#
sub RestoreExperimentLans($$$)
{
    my ($class, $experiment, $pstatedir) = @_;

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

    foreach my $table ("lans", "lan_attributes", "lan_members",
463
		       "lan_member_attributes", "ifaces") {
464 465 466 467 468 469
	if (-e "$pstatedir/$table") {
	    DBQueryWarn("load data infile '$pstatedir/$table' ".
			"into table $table")
		or return -1;
	}
    }
470 471 472
    return 0;
}

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
#
# Compare current vlans with pre-modify vlans to see which ones changed.
# These are the ones we will delete from the switches. The ones that do not
# change can be left alone. In the common case, this should save on the
# amount of vlan churning we do for swapmod.
#
# We return two lists of vlan ids; ones that have changed and need to be
# deleted, and the rest.
#
sub CompareVlansWithSwitches($$$)
{
    my ($class, $experiment, $pdiff, $psame) = @_;

    my $exptidx = $experiment->idx();
    my @changed = ();
    my @same    = ();

    #
    # Grab the existing vlans from the vlans table (managed by snmpit).
    #
    my $query_result =
	DBQueryWarn("select id,virtual,members,tag from vlans ".
		    "where exptidx='$exptidx'");
    return -1
	if (!$query_result);
    
    while (my ($oldid,$vname,$oldmembers,$tag) =
	   $query_result->fetchrow_array()) {

	my $vlan = VLan->Lookup($experiment, $vname);
	if (!defined($vlan) || $vlan->type ne "vlan") {
504 505
	    print STDERR "$vname is not a vlan!\n"
		if (defined($vlan));
506 507 508 509 510
	    push(@changed, $oldid);
	    next;
	}
	my $newid = $vlan->lanid();

511
	#print STDERR "$newid, $vlan\n";
512

513 514 515 516 517 518 519 520 521
	#
	# Compare the members list.
	#
	my @oldportlist = split(/\s/, $oldmembers);
	my @newportlist;
	if ($vlan->PortList(\@newportlist) != 0) {
	    print STDERR "Could not get portlist for $vlan\n";
	    return -1;
	}
522 523
	#print "$oldmembers\n";
	#print join(" ", @newportlist) . "\n";
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
	if (scalar(@oldportlist) != scalar(@newportlist)) {
	    push(@changed, $oldid);
	    next;
	}
	my $diff = 0;
	foreach my $port (@oldportlist) {
	    if (! grep {$_ eq $port} @newportlist) {
		$diff++;
	    }
	}
	if ($diff) {
	    push(@changed, $oldid);
	    next;
	}
	push(@same, $oldid);

	#
	# Change the new lan (and its partner entries) to have the old id
	# number, so that it matches what is on the switch, as told by
	# the vlans table. 
	#
	# This is bad; if one of these updates fails, we are screwed.
	#
	foreach my $table ("lans", "lan_attributes", "lan_members",
548 549
			   "lan_member_attributes", "ifaces",
			   "reserved_vlantags") {
550 551 552 553 554 555 556 557 558 559
	    DBQueryWarn("update $table set lanid=$oldid ".
			"where lanid='$newid'")
		or return -1;
	}
    }
    @$pdiff = @changed;
    @$psame = @same;
    return 0;
}

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
#
# New version to coexist with syncVlansFromTables() in snmpit. Adding or
# subtracting ports to an existing vlan is not considered a change now,
# since syncVlansFromTables() can deal with that. The point of this function
# then is to compare the vlan names and update the lanids of the newly
# created lans.
# 
#
sub CompareVlansWithSwitches2($$)
{
    my ($class, $experiment) = @_;

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

    #
    # Grab the existing vlans from the vlans table (managed by snmpit).
    #
    my $query_result =
	DBQueryWarn("select id,virtual,members,tag from vlans ".
		    "where exptidx='$exptidx'");
    return -1
	if (!$query_result);
    
    while (my ($oldid,$vname,$oldmembers,$tag) =
	   $query_result->fetchrow_array()) {

	my $vlan = VLan->Lookup($experiment, $vname);
	if (!defined($vlan) || $vlan->type ne "vlan") {
	    #
	    # The vlan was deleted.
	    #
	    print STDERR "$vname is not a vlan!\n"
		if (defined($vlan));
	    next;
	}
	#
	# Old vlan exists by the same name in the new set. We can just
	# change the port membership on the switches.
	#
	my $newid = $vlan->lanid();

	#
	# Change the new lan (and its partner entries) to have the old id
	# number, so that it matches what is on the switch, as told by
	# the vlans table. 
	#
	# This is bad; if one of these updates fails, we are screwed.
	#
	foreach my $table ("lans", "lan_attributes", "lan_members",
609 610
			   "lan_member_attributes", "ifaces",
			   "reserved_vlantags") {
611 612 613 614
	    DBQueryWarn("update $table set lanid=$oldid ".
			"where lanid='$newid'")
		or return -1;
	}
615 616 617 618 619 620 621
	# From the cache. 
	delete($lans{"$newid"});
	delete($lans{"$oldid"});
    
	# XXX we should not use this slot anymore.
	$vlan = VLan->Lookup($oldid);
	$vlan->SetAttribute("vlantag", $tag);	
622 623 624 625
    }
    return 0;
}

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
#
# Class method to see if an experiment has any active trunks. If it does,
# do not optimize vlan setup/teardown (see above function) when doing a
# swapmod. Too difficult to deal with right now; the problem is that the
# trunked interface is potentially a shared resource for multiple vlans,
# and the bookkeeping does not support dealing with it.
#
sub GotTrunks($$)
{
    my ($class, $experiment) = @_;
    my $exptidx = $experiment->idx();

    my $query_result =
	DBQueryWarn("select distinct r.node_id,i.iface from reserved as r " .
		    "left join interfaces as i on i.node_id=r.node_id " .
Mike Hibler's avatar
Mike Hibler committed
641
		    "where r.exptidx='$exptidx' and i.trunk!=0");
642 643 644 645

    return $query_result->numrows;
}

Leigh Stoller's avatar
Leigh Stoller committed
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
#
# Get the set of lans that are linked to this lan. Optionally provide the
# type, say to look for just vlans.
#
sub GetLinkedTo($$;$)
{
    my ($class, $lan, $type) = @_;

    if (! ref($lan)) {
	$lan = Lan->Lookup($lan);
	return ()
	    if (!defined($lan));
    }
    my $exptidx = $lan->exptidx();
    my $lanid   = $lan->lanid();
    my @result  = ();

    my $query_result =
	DBQueryWarn("select lanid from lans ".
		    "where link='$lanid' ".
		    (defined($type) ? "and type='$type'" : ""));
    return ()
	if (!$query_result || !$query_result->numrows);

    while (my ($id) = $query_result->fetchrow_array()) {
	my $vlan = Lan->Lookup($id);
	return undef
	    if (!defined($vlan));
	push(@result, $vlan);
    }
    return @result;
}

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
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid   = $self->pid();
    my $eid   = $self->eid();
    my $vname = $self->vname();
    my $id    = $self->lanid();

    return "[Lan ${id}: $pid/$eid/$vname]";
}

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

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

704 705 706 707 708 709
    my $lanid = $self->lanid();

    # Delete from the cache to force lookup.
    delete($lans{"$lanid"});

    my $newref = Lan->Lookup($lanid);
710 711 712 713 714 715
    return -1
	if (!defined($newref));

    $self->{'LAN'}   = $newref->{'LAN'};
    $self->{"ATTRS"} = $newref->{'ATTRS'};

716 717 718
    # Add back to cache. 
    $lans{"$lanid"} = $self;

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
    return 0;
}

#
# Get value of an attribute.
#
sub GetAttribute($$$;$)
{
    my ($self, $key, $pvalue, $ptype) = @_;

    return -1
	if (!exists($self->{'ATTRS'}->{$key}));

    $$pvalue = $self->{'ATTRS'}->{$key}->{'attrvalue'};
    $$ptype  = $self->{'ATTRS'}->{$key}->{'attrtype'}
        if (defined($ptype));
    
    return 0;
}

#
# Set value of an attribute.
#
sub SetAttribute($$$;$)
{
    my ($self, $key, $value, $type) = @_;

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

    $type = "string"
	if (!defined($type));

    return -1
	if ($type ne "string" && $type ne "integer" &&
	    $type ne "float"  && $type ne "boolean");

    my $lanid = $self->lanid();
    my $safe_key = DBQuoteSpecial($key);
    my $safe_val = DBQuoteSpecial($value);

    return -1
	if (!DBQueryWarn("replace into lan_attributes set ".
			 "  lanid='$lanid', ".
			 "  attrkey=$safe_key, ".
			 "  attrvalue=$safe_val, ".
			 "  attrtype='$type'"));

    $self->{'ATTRS'}->{$key}->{'attrkey'}   = $key;
    $self->{'ATTRS'}->{$key}->{'attrvalue'} = $value;
    $self->{'ATTRS'}->{$key}->{'attrtype'}  = $type;
    
    return 0;
}

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
#
# Delete an attribute.
#
sub DelAttribute($$)
{
    my ($self, $key) = @_;

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

    if (exists($self->{'ATTRS'}->{$key})) {
	delete($self->{'ATTRS'}->{$key});
    }
    my $lanid    = $self->lanid();
    my $safe_key = DBQuoteSpecial($key);

    return -1
	if (!DBQueryWarn("delete from lan_attributes ".
			 "where lanid='$lanid' and attrkey=$safe_key"));

    return 0;
}

797 798 799 800 801 802 803 804 805 806 807 808
#
# Shorthand
#
sub SetRole($$)
{
    my ($self, $role) = @_;

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

    return $self->SetAttribute("role", $role);
}
809 810 811 812 813 814 815 816 817 818 819 820 821 822
sub GetRole($;$)
{
    my ($self, $prole) = @_;
    my $role;

    return -1
	if ($self->GetAttribute("role", \$role) != 0);

    if (defined($prole)) {
	$$prole = $role;
	return 0;
    }
    return $role;
}
823 824 825 826 827 828 829

#
# Get the experiment object for a lan.
#
sub GetExperiment($)
{
    my ($self) = @_;
830
    require Experiment;
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

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

    return $self->{"EXPT"}
        if (defined($self->{"EXPT"}));

    $self->{"EXPT"} = Experiment->Lookup($self->exptidx());
    return $self->{"EXPT"};
}

#
# Get the linked lan as a lan object.
#
sub GetLinkedLan($)
{
    my ($self) = @_;

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

    return Lan->Lookup($self->link());
}

#
# Add an Interface to a Lan. This interface always corresponds to a virtual
# interface on link or lan.
#
sub AddInterface($$$$;$$)
{
    my ($self, $node, $vnode, $vport, $iface, $member) = @_;

863 864 865 866 867
    if (!ref($node)) {
	$node = Node->Lookup($node);
	return undef
	    if (!defined($node));
    }
868 869 870 871 872 873
    my $interface = Lan::Interface->Create($self, $node,
					   $vnode, $vport, $member);
    return undef
	if (!defined($interface));

    #print "fee $interface\n";
874 875

    #
876
    # Set the attribute for the physical interface.
877 878 879 880 881 882 883 884 885 886 887 888 889 890
    # If a member was provided, then the physical interface
    # is already set. Do not overwrite it.
    #
    if (!defined($member)) {
	if (defined($iface) &&
	    $interface->SetAttribute("iface", $iface) != 0) {
	    $interface->Destroy();
	    return undef;
	}
	# And the node
	if ($interface->SetAttribute("node_id", $node->node_id()) != 0) {
	    $interface->Destroy();
	    return undef;
	}
891 892 893 894 895 896 897 898 899 900 901 902 903 904
    }
    return $interface;
}

#
# Add a member to a lan
#
sub AddMember($$;$)
{
    my ($self, $node, $iface) = @_;

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

905 906 907
    if (!ref($node)) {
	$node = Node->Lookup($node);
	if (!defined($node)) {
908 909
	    return undef;
	}
910
    }
911

912
    my $member = Lan::Member->Create($self, $node);
913

914 915 916 917 918 919 920 921 922 923 924
    # And the node attribute. 
    if ($member->SetAttribute("node_id", $node->node_id()) != 0) {
	$member->Destroy();
	return undef;
    }
    # Set the attribute for the physical interface.
    if (defined($iface) &&
	$member->SetAttribute("iface", $iface) != 0) {
	$member->Destroy();
	return undef;
    }
925 926 927
    return $member;
}

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
#
# Check membership.
#
sub IsMember($$$)
{
    my ($self, $node, $iface) = @_;

    if (!ref($node)) {
	$node = Node->Lookup($node);
	return 0
	    if (!defined($node));
    }
    my $nodeid = $node->node_id();
    my $lanid  = $self->lanid();

    my $query_result =
944 945 946 947 948 949 950 951 952 953
	DBQueryWarn("select lma1.memberid from lan_member_attributes as lma1 ".
		    "left join lan_member_attributes as lma2 on ".
		    "     lma1.lanid=lma2.lanid and ".
		    "     lma1.memberid=lma2.memberid ".
		    "where lma1.lanid='$lanid' and ".
		    "      ((lma1.attrkey='node_id' and ".
		    "        lma1.attrvalue='$nodeid') and ".
		    "      (lma2.attrkey='iface' and ".
		    "       lma2.attrvalue='$iface'))");

954
    return 0
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
	if (!$query_result || $query_result->numrows != 1);

    return 1;
}

#
# Check membership.
#
sub FindMember($$$)
{
    my ($self, $node, $iface) = @_;

    if (!ref($node)) {
	$node = Node->Lookup($node);
	return undef
	    if (!defined($node));
    }
    my $nodeid = $node->node_id();
    my $lanid  = $self->lanid();

    my $query_result =
	DBQueryWarn("select lma1.memberid from lan_member_attributes as lma1 ".
		    "left join lan_member_attributes as lma2 on ".
		    "     lma1.lanid=lma2.lanid and ".
		    "     lma1.memberid=lma2.memberid ".
		    "where lma1.lanid='$lanid' and ".
		    "      ((lma1.attrkey='node_id' and ".
		    "        lma1.attrvalue='$nodeid') and ".
		    "      (lma2.attrkey='iface' and ".
		    "       lma2.attrvalue='$iface'))");

    return undef
	if (!$query_result || $query_result->numrows != 1);
    
    my ($memberid) = $query_result->fetchrow_array();
990

991
    return Lan::Member->Lookup($self, $memberid);
992 993
}

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
#
# Remove a member from a lan.
#
sub DelMember($$)
{
    my ($self, $member) = @_;

    #
    # We do not cache the members, so just delete it.
    #
    return $member->Destroy();
}

#
# Return a list of members for a lan.
#
sub MemberList($$)
{
    my ($self, $plist) = @_;

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

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

    my $query_result =
	DBQueryWarn("select memberid from lan_members where lanid='$lanid'");
    return -1
	if (!defined($query_result));

    my @result = ();
    while (my ($memberid) = $query_result->fetchrow_array()) {
	my $member = Lan::Member->Lookup($self, $memberid);
	return -1
	    if (!defined($member));
	push(@result, $member);
    }
    @$plist = @result;
    return 0;
}

#
# List of all experiment lans. This is a class method.
#
sub ExperimentLans($$$)
{
    my ($class, $experiment, $plist) = @_;

    return -1
	if (! (ref($plist) && ref($experiment)));
    my $exptidx = $experiment->idx();

    my $query_result =
	DBQueryWarn("select l.lanid from lans as l ".
		    "where l.exptidx='$exptidx'");
    return -1
	if (!defined($query_result));

    my @result = ();
    while (my ($lanid) = $query_result->fetchrow_array()) {
	my $lan = Lan->Lookup($lanid);
	return -1
	    if (!defined($lan));
	push(@result, $lan);
    }
    @$plist = @result;
    return 0;
}

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
#
# Find a lan by looking an interface in the member list
#
sub FindLanByInterface($$$)
{
    my ($class, $experiment, $interface) = @_;
    my $exptidx = $experiment->idx();
    my $iface   = $interface->iface();
    my @lans   = ();

    #
    # We do not do this often, so worry about optimizing later.
    #
    return undef
	if (Lan->ExperimentLans($experiment, \@lans) != 0);

    foreach my $lan (@lans) {
	return $lan
	    if ($lan->IsMember($interface->node_id(), $interface->iface()));
    }
    return undef;
}

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
#
# Initialize from vlans table. Used when converting from old vlans table.
#
# XXX Need to deal with vlan encapsulation ...
#
sub Initialize($)
{
    my ($self)     = @_;
    my %delays     = ();
    my %elabinelab = ();
    my %vinterfaces= ();
1097
    require Experiment;
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

    # Prevent vlan insertion above.
    $initialize = 1;

    DBQueryFatal("delete from lans");
    DBQueryFatal("delete from lan_attributes");
    DBQueryFatal("delete from lan_members");
    DBQueryFatal("delete from lan_member_attributes");
    DBQueryFatal("delete from ifaces");

    my $query_result =
	DBQueryFatal("select node_id,iface0,iface1,vname from delays");
    while (my ($node_id,$iface0,$iface1,$vname) =
	   $query_result->fetchrow_array()) {
	$delays{"$node_id:$iface0"} = $vname;
	$delays{"$node_id:$iface1"} = $vname;

	print "$node_id:$iface0, $node_id:$iface1\n";
    }

    $query_result =
	DBQueryFatal("select exptidx,outer_id from elabinelab_vlans");
    while (my ($exptidx,$outer_id) = $query_result->fetchrow_array()) {
	$elabinelab{"$outer_id"} = $exptidx;

	print "$exptidx,$outer_id\n";
    }

    # vinterfaces
    $query_result =
	DBQueryFatal("select node_id,iface,vnode_id from vinterfaces ".
		     "where iface is not null and iface!=''");
    while (my ($node_id,$iface,$vnode_id) = $query_result->fetchrow_array()) {
	$vinterfaces{"$node_id:$iface"} = $vnode_id;

	print "veth: $node_id:$iface,$vnode_id\n";
    }

    $query_result =
	DBQueryWarn("select * from vlans");

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $exptidx    = $rowref->{'exptidx'};
	my $experiment = Experiment->Lookup($exptidx);
	if (!defined($experiment)) {
	    print STDERR "*** Initialize: No such experiment $exptidx\n";
	    return -1;
	}

	my $id      = $rowref->{'id'};
	my $tag     = $rowref->{'tag'};
	my $vname   = $rowref->{'virtual'};
	my $vlan    = VLan->Lookup($id);
	if ($vlan) {
	    print STDERR "*** Initialize: ".
		"Duplicate vlan $vname in $experiment\n";
	    return -1;
	}

	print "VLAN: $vname ($id) $experiment\n";

	# Create a new VLAN.
	$vlan = VLan->Create($experiment, $vname, $id);
	if (!defined($vlan)) {
	    print STDERR "*** Initialize: ".
		"Could not create vlan $vname ($id) in $experiment\n";
	    return -1;
	}
1166
	$vlan->ReserveVlanTag($tag);
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 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 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287

	#
	# Split apart the space-separated list of members
	#
	my @members = split /\s+/, $rowref->{'members'};

	#
	# See if this vlan is for a delay link or lan.
	#
	foreach my $member (@members) {
	    if (exists($delays{$member})) {
		if ($vlan->SetRole("delay") != 0) {
		    print STDERR "*** Initialize: ".
			"Could not set role to delay on $vlan\n";
		    return -1;
		}
		foreach my $memb (@members) {
		    my ($nodeid, $iface) = split /:/, $memb;
		    my $node = Node->Lookup($nodeid);
		    if (!$node) {
			print STDERR "*** Initialize: ".
			    "No such node $nodeid in $vlan in $experiment\n";
			return -1;
		    }
		    print "Delay: $memb\n";
	    
		    #
		    # Instead of interfaces, we just add members to the lan
		    # since they do not correspond to interfaces in the
		    # virtual topo.
		    #
		    $vlan->AddMember($node, $iface);
		}
		goto again;
	    }
	}

	#
	# Or for elabinelab.
	#
	if (exists($elabinelab{"$id"})) {
	    if ($vlan->SetRole("elabinelab") != 0) {
		print STDERR "*** Initialize: ".
		    "Could not set role to delay on $vlan\n";
		return -1;
	    }
	    #
	    # Instead of interfaces, we just add members to the lan since
	    # they do not correspond to interfaces in the virtual topo.
	    #
	    foreach my $member (@members) {
		my ($nodeid, $iface) = split /:/, $member;
		my $node = Node->Lookup($nodeid);
		if (!$node) {
		    print STDERR "*** Initialize: ".
			"No such node $nodeid in vlan $vname in $experiment\n";
		    return -1;
		}
		$vlan->AddMember($node, $iface);
	    }
	    next;
	}

	if ($vlan->SetRole("link/lan") != 0) {
	    print STDERR "*** Initialize: ".
		"Could not set role to link/lan on $vlan\n";
	    return -1;
	}
	foreach my $member (@members) {
	    my ($nodeid, $iface) = split /:/, $member;
	    my $node = Node->Lookup($nodeid);
	    if (!$node) {
		print STDERR "*** Initialize: ".
		    "No such node $nodeid in vlan $vname in $experiment\n";
		return -1;
	    }

	    # Look to see if its a multiplexed link (used by veths). If
	    # so do not create Interfaces, but just members.
	    if (exists($vinterfaces{"$nodeid:$iface"})) {
		my $memb = $vlan->AddMember($node, $iface);
		
		if (!defined($memb)) {
		    print STDERR "*** Initialize: ".
			"Cannot insert multiplexed $member into vlan ".
			"$vlan in $experiment\n";
		    return -1;
		}
		next;
	    }

	    # Correlate the interface with the virtual port.
	    my $iresult =
		DBQueryWarn("select vl.vnode,vl.vname,vl.vport,vl.ip ".
			    "  from virt_lans as vl ".
			    "left join interfaces as i on i.IP=vl.ip and ".
			    "     i.node_id='$nodeid' ".
			    "where exptidx='$exptidx' and i.iface='$iface'");
	    return -1
		if (!$iresult);
	    if ($iresult->numrows() != 1) {
		print STDERR "*** Initialize: ".
		    "Bad rows for $member in vlan $vlan\n";
		return -1;
	    }
	    my ($vnode,$check_vname,$vport) = $iresult->fetchrow_array();

	    #print "foo: $node, $vnode, $vname, $vport, $iface\n";

	    my $interface = $vlan->AddInterface($node, $vnode, $vport, $iface);
	    if (!defined($interface)) {
		print STDERR "*** Initialize: ".
		    "Cannot insert $member into vlan $vlan in $experiment\n";
		return -1;
	    }
	}
      again:
    }
    return 0;
}

1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
#
# Look for a shared vlan by token. Just return the row reference.
# Be fancy later if needed.
#
sub LookupSharedVLanByToken($$)
{
    my ($class, $token) = @_;

    my $query_result =
	DBQueryWarn("select * from shared_vlans ".
		    "where token='$token'");
    return undef
	if (!$query_result || !$query_result->numrows);

    return $query_result->fetchrow_hashref();
}

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
#
# Is this lan shared?
#
sub IsShared($)
{
    my ($self) = @_;
    my $lanid  = $self->lanid();
    
    my $query_result =
	DBQueryWarn("select * from shared_vlans ".
		    "where lanid='$lanid'");
    return undef
	if (!$query_result);

    return $query_result->numrows();
}

1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
#
# Try to lock this lan. Optional timeout in seconds. 
#
sub Lock($;$)
{
    my ($self, $timeout) = @_;
    my $lockmsg = 0;

    # Must be a real reference. 
    return -1
	if (! ref($self));

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

    if (!defined($timeout)) {
	$timeout = 0;
    }
    elsif ($timeout == 0) {
	$timeout = 999999; 
    }
    while ($timeout >= 0) {
	my $query_result =
	    DBQueryWarn("update lans set locked=now() ".
			"where lanid='$lanid' and locked is null");

	return -1
	    if (!$query_result);

	return 0
	    if ($query_result->numrows);

	$timeout -= 2;
	if (!$lockmsg && $timeout >= 0) {
	    print "$self is locked by another; ".
		"will keep trying for another $timeout seconds\n";
	    $lockmsg++;
	}
	sleep(2);
    }
    return -1;
}

sub Unlock($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

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

    my $query_result =
	DBQueryWarn("update lans set locked=NULL where lanid='$lanid'");

    if (! $query_result ||
	$query_result->numrows == 0) {
	return -1;
    }
    return 0;
}

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
############################################################################
#
# Lan::Member is just a set of attributes in the DB associated with an
# endpoint of a Lan. It may or may not map one-to-one with an Interface
# on an an actual node.
#
package Lan::Member;
use libdb;
use libtestbed;
use English;
use overload ('""' => 'Stringify');

# Cache of instances to avoid regenerating them.
my %members   = ();

#
# Lookup and create a class instance to return.
#
sub Lookup($$$)
{
    my ($class, $lan, $memberid) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
1405
    my $lanid = (ref($lan) ? $lan->lanid() : $lan);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

    return undef
	if (! ($memberid =~ /^\d*$/));

    # Look in cache first
    return $members{"${lanid}:${memberid}"}
        if (exists($members{"${lanid}:${memberid}"}));
    
    my $query_result =
	DBQueryWarn("select * from lan_members ".
		    "where lanid='$lanid' and memberid='$memberid'");

    return undef
	if (!$query_result || !$query_result->numrows);

    my $self             = {};
    $self->{'LAN'}       = $lan;
    $self->{'MEMBERID'}  = $memberid;
    $self->{"ATTRS"}     = {};

    #
    # Grab the attributes for this member.
    #
    $query_result =
	DBQueryWarn("select * from lan_member_attributes ".
		    "where lanid='$lanid' and memberid='$memberid'");
    return undef
	if (!$query_result);

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $key = $rowref->{'attrkey'};
	
	$self->{"ATTRS"}->{$key} = $rowref;
    }

    bless($self, $class);
    
    # Add to cache. 
    $members{"${lanid}:${memberid}"} = $self;
    
    return $self;
}

# accessors
sub pid($)	{ return $_[0]->GetLan()->pid(); }
sub eid($)	{ return $_[0]->GetLan()->eid(); }
sub exptidx($)	{ return $_[0]->GetLan()->exptidx(); }
sub lanid($)    { return $_[0]->GetLan()->lanid(); }
sub vname($)	{ return $_[0]->GetLan()->vname(); }
sub GetLan($)   { return $_[0]->{'LAN'}; }
sub memberid($) { return $_[0]->{'MEMBERID'}; }
1457
sub attributes($) { return $_[0]->{'ATTRS'}; }
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476

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

    return "[Lan::Member ${memberid}, Lan ${lanid}: $pid/$eid]";
}

#
# Create a new Lan::Member object (on a specific lan) and return it.
#
1477
sub Create($$$)
1478
{
1479 1480 1481 1482 1483 1484 1485 1486 1487
    my ($class, $lan, $node) = @_;

    if (!ref($node)) {
	$node = Node->Lookup($node);
	return 0
	    if (!defined($node));
    }
    my $nodeid = $node->node_id(); 
    my $lanid  = $lan->lanid();
1488 1489 1490

    my $query_result = 
	DBQueryWarn("insert into lan_members set ".
1491
		    "  lanid='$lanid', memberid=NULL, node_id='$nodeid'");
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
    return undef
	if (!$query_result);

    # Need the newly minted memberid.
    my $memberid = $query_result->insertid();

    return Lan::Member->Lookup($lan, $memberid);
}

#
# Destroy a lan member and its attributes.
#
sub Destroy($)
{
    my ($self) = @_;

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

    my $lanid    = $self->lanid();
    my $memberid = $self->memberid();

    # Must delete attributes first.
    return -1
	if (!DBQueryWarn("delete from lan_member_attributes ".
			 "where lanid='$lanid' and memberid='$memberid'"));
    
    return -1
	if (!DBQueryWarn("delete from lan_members ".
			 "where lanid='$lanid' and memberid='$memberid'"));

    # Delete from cache too.
    delete($members{"${lanid}:${memberid}"});

    return 0;
}

#
# Called directly to remove a member from its lan and then destroy itself.
#
sub Delete($)
{
    my ($self) = @_;

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

    return $self->GetLan()->DelMember($self);
}

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

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

    my $newref = Lan::Member->Lookup($self->lanid(), $self->memberid());
    return -1
	if (!defined($newref));

    $self->{"ATTRS"} = $newref->{'ATTRS'};

    return 0;
}

#
# Get value of an attribute.
#
sub GetAttribute($$$;$)
{
    my ($self, $key, $pvalue, $ptype) = @_;

    return -1
	if (!exists($self->{'ATTRS'}->{$key}));

    $$pvalue = $self->{'ATTRS'}->{$key}->{'attrvalue'};
    $$ptype  = $self->{'ATTRS'}->{$key}->{'attrtype'}
        if (defined($ptype));
    
    return 0;
}

#
# Set value of an attribute.
#
sub SetAttribute($$$;$)
{
    my ($self, $key, $value, $type) = @_;

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

    $type = "string"
	if (!defined($type));

    return -1
	if ($type ne "string" && $type ne "integer" &&
	    $type ne "float"  && $type ne "boolean");

    my $lanid    = $self->lanid();
    my $memberid = $self->memberid();
    my $safe_key = DBQuoteSpecial($key);
    my $safe_val = DBQuoteSpecial($value);

    return -1
	if (!DBQueryWarn("replace into lan_member_attributes set ".
			 "  lanid='$lanid', ".
			 "  memberid='$memberid', ".
			 "  attrkey=$safe_key, ".
			 "  attrvalue=$safe_val, ".
			 "  attrtype='$type'"));

    $self->{'ATTRS'}->{$key}->{'attrkey'}   = $key;
    $self->{'ATTRS'}->{$key}->{'attrvalue'} = $value;
    $self->{'ATTRS'}->{$key}->{'attrtype'}  = $type;
    
    return 0;
}

#
# Return node and iface for a member. Needed all over the place.
#
sub GetNodeIface($$$)
{
    my ($self, $pnode, $piface) = @_;
    
    return -1
	if (! (ref($self) && ref($pnode) && ref($piface)));

    my $nodeid;
    my $iface;

    return -1
	if ($self->GetAttribute("node_id", \$nodeid) != 0 ||
	    $self->GetAttribute("iface", \$iface) != 0);

    my $node = Node->Lookup($nodeid);
    return -1
	if (!defined($node));

    $$pnode  = $node;
    $$piface = $iface;
    return 0;
}

1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
#
# Get the Interface structure.
#
sub GetInterface($)
{
    my ($self) = @_;
    my $node;
    my $iface;

    require Interface;

Leigh Stoller's avatar
Leigh Stoller committed
1652
    return undef
1653 1654 1655 1656
	if ($self->GetNodeIface(\$node, \$iface));

    return Interface->LookupByIface($node, $iface);
}
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775

############################################################################
#
# Interfaces correspond one-to-one with the virtual ports (vports) of the
# virtual topology, but are really just lan members underneath. The interfaces
# table stores the mapping between them.
#
package Lan::Interface;
use libdb;
use libtestbed;
use English;
use overload ('""' => 'Stringify');

# Cache of instances to avoid regenerating them.
my %interfaces   = ();

# accessors
sub field($$)     { return ((! ref($_[0])) ? -1 : $_[0]->{'IFACE'}->{$_[1]}); }
sub pid($)	  { return field($_[0], 'pid'); }
sub eid($)	  { return field($_[0], 'eid'); }
sub exptidx($)	  { return field($_[0], 'exptidx'); }
sub node_id($)	  { return field($_[0], 'node_id'); }
sub ifaceid($)	  { return field($_[0], 'ifaceid'); }
sub vnode($)	  { return field($_[0], 'vnode'); }
sub vname($)	  { return field($_[0], 'vname'); }
sub vport($)	  { return field($_[0], 'vport'); }
sub GetLan($)     { return $_[0]->{'LAN'}; }
sub GetMember($)  { return $_[0]->{'MEMBER'}; }

#
# Lookup and create a class instance to return.
#
sub Lookup($$$;$)
{
    my ($class, $lan, $arg1, $arg2) = @_;
    my $ifaceid;

    return undef
	if (!ref($lan));
    my $lanid = $lan->lanid();

    #
    # A single arg is an ifaceid. Two args is vnode and vport.
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
	    $ifaceid = $1;
	}
	else {
	    return undef;
	}
    }
    elsif (! (($arg1 =~ /^[-\w]*$/) && ($arg2 =~ /^[-\w]*$/))) {
	return undef;
    }

    #
    # Two args means lookup by vnode,vport
    #
    if (defined($arg2)) {
	my $result =
	    DBQueryWarn("select ifaceid from ifaces ".
			"where lanid='$lanid' and vnode='$arg1' and ".
			"      vport='$arg2'");

	return undef
	    if (! $result || !$result->numrows);

	($ifaceid) = $result->fetchrow_array();
    }

    # Look in cache first
    return $interfaces{"$lanid:$ifaceid"}
        if (exists($interfaces{"$lanid:$ifaceid"}));
    
    my $query_result =
	DBQueryWarn("select * from ifaces ".
		    "where lanid='$lanid' and ifaceid='$ifaceid'");

    return undef
	if (!$query_result || !$query_result->numrows);

    my $self          = {};
    $self->{'IFACE'}  = $query_result->fetchrow_hashref();
    $self->{'LAN'}    = $lan;
    $self->{'MEMBER'} = Lan::Member->Lookup($lan, $ifaceid);

    return undef
	if (!defined($self->{'MEMBER'}));

    bless($self, $class);
    
    # Add to cache. 
    $interfaces{"$lanid:$ifaceid"} = $self;
    
    return $self;
}

#
# Create a new Interface object and return it
#
sub Create($$$$$;$)
{
    my ($class, $lan, $node, $vnode, $vport, $member) = @_;

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

    my $lanid   = $lan->lanid();
    my $vname   = $lan->vname();
    my $pid     = $lan->pid();
    my $eid     = $lan->eid();
    my $exptidx = $lan->exptidx();
    my $node_id = $node->node_id();

    # We need the idx from the virt_lan_lans table.
    my $query_result =
	DBQueryWarn("select idx from virt_lan_lans ".
		    "where exptidx=$exptidx and vname='$vname'");
1776
    return undef
1777 1778 1779 1780 1781 1782
	if (!$query_result || !$query_result->numrows);
    my ($vidx) = $query_result->fetchrow_array();

    # Use supplied member (which provides the ifaceid) or generate a
    # new one.
    if (!defined($member)) {
1783
	$member = Lan::Member->Create($lan, $node);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
	return undef
	    if (!defined($member));
    }
    my $ifaceid = $member->memberid();

    return undef
	if (!DBQueryWarn("insert into ifaces set ".
			 "   lanid='$lanid', ".
			 "   ifaceid='$ifaceid', ".
			 "   exptidx='$exptidx', ".
			 "   pid='$pid', ".
			 "   eid='$eid', ".
			 "   node_id='$node_id', ".
			 "   vnode='$vnode', ".
			 "   vname='$vname', ".
			 "   vidx='$vidx', ".
			 "   vport='$vport'"));

    return Lan::Interface->Lookup($lan, $ifaceid);
}

#
# Destroy an interface and the underlying lan_member.
#
sub Destroy($)
{
    my ($self) = @_;

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

    my $lanid   = $self->lanid();
    my $ifaceid = $self->ifaceid();
    
    # Delete the member first in case of failure.
    return -1
	if ($self->GetMember() && !$self->GetMember()->Destroy());

    $self->{'MEMBER'} = undef;

    return -1
	if (!DBQueryWarn("delete from ifaces ".
			 "where lanid='$lanid' and ifaceid='$ifaceid'"));

    # Remove from cache. 
    delete($interfaces{"$lanid:$ifaceid"});
    
    return 0;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid     = $self->pid();
    my $eid     = $self->eid();
    my $vnode   = $self->vnode();
    my $vname   = $self->vname();
    my $vport   = $self->vport();
    my $ifaceid = $self->ifaceid();
    my $lanid   = $self->GetLan()->lanid();

    return "[Interface ${ifaceid}, ".
	"Lan ${lanid}: $pid/$eid/$vnode/$vname/$vport]";
}

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

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

    my $newref = Interface->Lookup($self->GetLan(), $self->ifaceid());
    return -1
	if (!defined($newref));

    $self->{'IFACE'}  = $newref->{'IFACE'};
    $self->{'MEMBER'} = $newref->{'MEMBER'};

    return 0;
}

#
# Get value of an attribute.
#
sub GetAttribute($$$;$)
{
    my ($self, $key, $pvalue, $ptype) = @_;

    return $self->GetMember()->GetAttribute($key, $pvalue, $ptype);
}

#
# Set value of an attribute.
#
sub SetAttribute($$$;$)
{
    my ($self, $key, $value, $type) = @_;

    return $self->GetMember()->SetAttribute($key, $value, $type);
}

1893 1894 1895 1896 1897 1898 1899
sub memberid($)
{
    my ($self) = @_;

    return $self->GetMember()->memberid();
}

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
############################################################################
#
# A protolan is for creating a lan without sending it to the DB until
# later. Used from assign_wraper.
#
package ProtoLan;
use libdb;
use libtestbed;
use English;
use Lan;
use overload ('""' => 'Stringify');

# Keep track of protolans to prevent duplicates.
my %protolans = ();

sub Lookup($$$)
{
    my ($class, $experiment, $vname) = @_;
    
    return undef
	if (!ref($experiment));

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

    return undef
	if (! exists($protolans{"$exptidx:$vname"}));
    
    return $protolans{"$exptidx:$vname"};
}

#
# Create a new ProtoLan object and return it. 
#
1933
sub Create($$$$;$)
1934
{
1935
    my ($class, $experiment, $vname, $impotent, $link) = @_;
1936 1937 1938 1939 1940 1941 1942 1943 1944

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

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

    #
    # Make sure no existing lan ...
    #
1945
    if (!$impotent && Lan->Lookup($experiment, $vname)) {
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
	print STDERR "*** Protolan Create: ".
	    "Duplicate lan $vname in $experiment\n";
	return undef;
    }
    # Or protolan ...
    if (exists($protolans{"$exptidx:$vname"})) {
	print STDERR "*** Protolan Create: ".
	    "Duplicate protolan $vname in $experiment\n";
	return undef;
    }
	
    my $self              = {};
    $self->{"ATTRS"}      = {};
    $self->{"MEMBERS"}    = {};
    $self->{"IFACES"}     = {};
    $self->{"EXPT"}       = $experiment;
    $self->{"VNAME"}      = $vname;
    $self->{"LINK"}       = $link;
    $self->{"TYPE"}       = '';
    $self->{"ROLE"}       = '';
    $self->{"ENCAPSTYLE"} = '';
1967
    $self->{"IDX"}        = undef; # used in regression mode.
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
    $self->{"INSTANCE"}   = undef;

    bless($self, $class);
    
    # Add to cache. 
    $protolans{"$exptidx:$vname"} = $self;

    return $self;
}
sub vname($)		{ return $_[0]->{"VNAME"}; }
sub link($)		{ return $_[0]->{"LINK"}; }
sub type($)		{ return $_[0]->{"TYPE"}; }
sub role($)		{ return $_[0]->{"ROLE"}; }
sub encapstyle($)	{ return $_[0]->{"ENCAPSTYLE"}; }

#
# Destroy a protolan before it gets instantiated. 
#
sub Destroy($)
{
    my ($self) = @_;

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

    my $exptidx = $self->{"EXPT"}->idx();
    my $vname   = $self->{"VNAME"};

    # Remove from cache. 
    delete($protolans{"$exptidx:$vname"});
    return 0;
}

#
# Return the list of protolans.
#
sub ProtoLanList($)
{
    my ($class) = @_;

    return values(%protolans);
}

#
# Instantiate into the DB.
#
sub Instantiate($)
{
    my ($self) = @_;

    my $experiment = $self->{'EXPT'};
    my $vname      = $self->{'VNAME'};
    my $type       = $self->{'TYPE'};
2021
    my $idx        = $self->{'IDX'};  # defaults to undef when not regression.
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
    my $link       = undef;

    # Already created.
    return 0
	if (defined($self->{'INSTANCE'}));

    if (defined($self->{'LINK'})) {
	my $link_protolan = $self->{'LINK'};
	$link = $link_protolan->{'INSTANCE'};
	
	if (!defined($link)) {
	    $link_protolan->Instantiate();
	    $link = $link_protolan->{'INSTANCE'};
	}
    }

2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
    #
    # Check to see if there is an entry in reserved_vlantags table.
    # If so, use that lanid instead of generating a new one. This is
    # mostly for the benefit of ProtoGeni stitching, but is also handy
    # for swapmod so we can reuse existing vlan tags and lanids.
    #
    if (!defined($idx)) {
	my $exptidx = $experiment->idx();

	my $query_result =
	    DBQueryWarn("select lanid from reserved_vlantags ".
			"where exptidx='$exptidx' and vname='$vname'");

	return -1
	    if (!defined($query_result));

	if ($query_result->numrows) {
	    ($idx) = $query_result->fetchrow_array();
	}
    }

2059
    # The new lan has the 'ready' bit set to zero.
2060
    my $lan = Lan->Create($experiment, $vname, $type, $idx, $link);
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
    return -1
	if (!defined($lan));

    # Insert the attributes.
    foreach my $key (keys(%{ $self->{"ATTRS"} })) {
	my $pattr = $self->{"ATTRS"}->{$key};

	if ($lan->SetAttribute($pattr->{'attrkey'}, $pattr->{'attrvalue'},
			       $pattr->{'attrtype'}) != 0) {
	    $lan->Destroy();
	    return -1;
	}
    }
2074 2075 2076 2077 2078 2079
    #
    # These are always class=Experimental if not specified. Note that
    # we support experimental vlans on the control network via trunk
    # links. Thus the stack and the class can actually be different.
    #
    if (! exists($self->{"ATTRS"}->{'class'})) {
2080 2081 2082 2083 2084
	if ($lan->SetAttribute("class", "Experimental")) {
	    $lan->Destroy();
	    return -1;
	}
    }
2085 2086

    # Members ...
2087
    foreach my $key (sort(keys(%{ $self->{"MEMBERS"} }))) {
2088 2089 2090 2091 2092 2093 2094
	my $protomember = $self->{"MEMBERS"}->{$key};
	my $node        = $protomember->{'node'};
	my $iface       = $protomember->{'iface'};
	my $attributes  = $protomember->{'attrs'};
	my $member      = $lan->AddMember($node, $iface);
	
	if (!defined($member)) {
2095 2096 2097
	    $lan->Destroy();
	    return -1;
	}
2098 2099 2100 2101 2102 2103 2104 2105

	if (defined($attributes)) {
	    foreach my $attrkey (keys(%{$attributes})) {
		my $attrvalue = $attributes->{$attrkey};

		$member->SetAttribute($attrkey, $attrvalue);
	    }
	}
2106 2107 2108
    }

    # Interfaces ...
2109
    foreach my $key (sort(keys(%{ $self->{"IFACES"} }))) {
2110 2111 2112 2113 2114
	my $protomember = $self->{"IFACES"}->{$key};
	my $node        = $protomember->{'node'};
	my $vnode       = $protomember->{'vnode'};
	my $vport       = $protomember->{'vport'};
	my $iface       = $protomember->{'iface'};
2115
	my $pport       = $protomember->{'pport'};
2116
	my $attributes  = $protomember->{'attrs'};
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
	my $member;

	if (defined($pport)) {
	    $member = $lan->AddMember($node, $pport);
	    
	    if (!defined($member)) {
		$lan->Destroy();
		return -1;
	    }
	}
	my $interface =
	    $lan->AddInterface($node, $vnode, $vport, $iface, $member);
2129 2130
	
	if (!defined($interface)) {
2131 2132 2133
	    $lan->Destroy();
	    return -1;
	}
2134 2135 2136 2137 2138 2139 2140
	if (defined($attributes)) {
	    foreach my $attrkey (keys(%{$attributes})) {
		my $attrvalue = $attributes->{$attrkey};

		$interface->SetAttribute($attrkey, $attrvalue);
	    }
	}
2141 2142 2143 2144 2145 2146 2147 2148
    }
    $self->{'INSTANCE'} = $lan;
    return 0;
}

#
# Instantiate all protolans
#
2149
sub InstantiateAll($$)
2150
{
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
    my ($class, $regression) = @_;

    if ($regression) {
	#
	# Need to make sure the id numbers will compare exactly. At some
	# point a few years from now, this will fail.
	#
	my $idx = 999990000;
	
	foreach my $protolan (values(%protolans)) {
	    $protolan->{'IDX'} = $idx++;
	}
    }
2164 2165

    foreach my $protolan (values(%protolans)) {
2166 2167 2168 2169 2170
	if ($protolan->Instantiate() != 0) {
	    print STDERR "*** Could not instantiate protolan: " .
		$protolan->Dump() . "\n";
	    return -1;
	}
2171
    }
2172
    %protolans = ();
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
    return 0;
}

#
# Dump all protolans
#
sub DumpAll($)
{
    my ($class) = @_;

    foreach my $protolan (values(%protolans)) {
	print STDERR $protolan->Dump() . "\n";
    }
    return 0;
}

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

    my $vname      = $self->{'VNAME'};
    my $experiment = $self->{'EXPT'};

    return "[Protolan: $vname, $experiment]";
}

#
# Display for debug.
#
sub Dump($)
{
    my ($self) = @_;

    my $vname  = $self->{'VNAME'};
    my $type   = (defined($self->{'TYPE'}) ? "type:" . $self->{'TYPE'} : "");
    my $link   = (defined($self->{'LINK'}) ?
		  "(" . $self->{'LINK'}->vname() . ") " : "");
    my $string = "ProtoLan: $vname $type,$link";

    foreach my $key (keys(%{ $self->{"ATTRS"} })) {
	my $pattr = $self->{"ATTRS"}->{$key};
	my $val   = $pattr->{'attrvalue'};

	$string .= "$key:$val,";
    }
    $string .= ", ";

    foreach my $key (keys(%{ $self->{"MEMBERS"} })) {
	my $member = $self->{"MEMBERS"}->{$key};
	my $nodeid = $member->{'node'}->node_id();
	my $iface  = $member->{'iface'};

	$string .= "$nodeid:$iface, ";
    }

    foreach my $key (keys(%{ $self->{"IFACES"} })) {
	my $interface = $self->{"IFACES"}->{$key};
	my $nodeid = $interface->{'node'}->node_id();
	my $vnode  = $interface->{'vnode'};
	my $vport  = $interface->{'vport'};
	my $iface  = $interface->{'iface'};
2237
	my $pport  = $interface->{'pport'};
2238

2239 2240 2241 2242
	$string .= "$vnode:$vport:$nodeid:$iface";
	$string .= ":$pport"
	    if (defined($pport));
	$string .= ", ";
2243 2244 2245 2246 2247 2248 2249
    }
    return $string;
}

#
# Add an interface to a protolan.
#
2250
sub AddInterface($$$$$;$$)
2251
{
2252
    my ($self, $node, $vnode, $vport, $iface, $pport, $attributes) = @_;
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268

    if (!ref($node)) {
	$node = Node->Lookup($node);
	return -1
	    if (!defined($node));
    }

    if (exists($self->{'IFACES'}->{"$vnode:$vport"})) {
	print STDERR "*** Protolan AddInterface: ".
	    "Duplicate $vport ($iface) on $node ($self)\n";
	return -1;
    }

    $self->{'IFACES'}->{"$vnode:$vport"} = { "node"  => $node,
					     "vnode" => $vnode,
					     "vport" => $vport,
2269
					     "iface" => $iface,
2270
					     "pport" => $pport,
2271
					     "attrs" => $attributes,
2272 2273 2274 2275 2276 2277 2278
					    };
    return 0;
}

#
# Add a member to a vlan, as for delay node links and tagged vlans.
#
2279
sub AddMember($$$;$)
2280
{
2281
    my ($self, $node, $iface, $attributes) = @_;
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296

    if (!ref($node)) {
	$node = Node->Lookup($node);
	return -1
	    if (!defined($node));
    }
    my $nodeid = $node->node_id();

    if (exists($self->{'MEMBERS'}->{"$nodeid:$iface"})) {
	print STDERR "*** Protolan AddMember: ".
	    "Duplicate $iface on $node\n";
	return -1;
    }
    
    $self->{'MEMBERS'}->{"$nodeid:$iface"} = { "node"  => $node,
2297 2298
					       "iface" => $iface,
					       "attrs" => $attributes,
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
					     };
    return 0;
}

#
# Does member already exists in protolan.
#
sub IsMember($$$)
{
    my ($self, $node, $iface) = @_;

    if (!ref($node)) {
	$node = Node->Lookup($node);
	return 0
	    if (!defined($node));
    }
    my $nodeid = $node->node_id();

    return exists($self->{'MEMBERS'}->{"$nodeid:$iface"});
}

#
# Return the memberlist.
#
sub MemberList($)
{
    my ($self) = @_;

    return keys(%{ $self->{'MEMBERS'} });
}

2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
#
# Return member node.
#
sub MemberNode($$)
{
    my ($self, $member) = @_;
    
    return undef
	if (! exists($self->{'MEMBERS'}->{$member}));

    return $self->{'MEMBERS'}->{$member}->{'node'};
}

#
# Return the ifacelist
#
sub IfaceList($)
{
    my ($self) = @_;

    return keys(%{ $self->{'IFACES'} });
}

#
# Return member node.
#
sub IfaceNode($$)
{
    my ($self, $member) = @_;
    
    return undef
	if (! exists($self->{'IFACES'}->{$member}));

    return $self->{'IFACES'}->{$member}->{'node'};
}

2366
#
2367
# Set value of an attribute for a member;
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
#
sub SetAttribute($$$;$)
{
    my ($self, $key, $value, $type) = @_;

    $type = "string"
	if (!defined($type));

    $self->{"ATTRS"}->{$key} = {"attrkey"   => $key,
				"attrvalue" => $value,
				"attrtype"  => $type };

    return 0;
}
2382 2383 2384 2385 2386 2387 2388 2389 2390
sub GetAttribute($$)
{
    my ($self, $key) = @_;

    return undef
	if (!exists($self->{"ATTRS"}->{$key}));

    return $self->{"ATTRS"}->{$key}->{"attrvalue"};
}
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
sub SetRole($$)
{
    my ($self, $role) = @_;

    $self->{"ROLE"} = $role;
    
    return $self->SetAttribute("role", $role);
}
sub SetEncapStyle($$)
{
    my ($self, $style) = @_;

    $self->{"ENCAPSTYLE"} = $style;
    
    return $self->SetAttribute("encapstyle", $style);
}
sub SetType($$)
{
    my ($self, $type) = @_;

    $self->{"TYPE"} = $type;
    return 0;
}
sub SetLink($$)
{
    my ($self, $link) = @_;

    $self->{"LINK"} = $link;
    return 0;
}

############################################################################
#
# The most common kind of Lan is a Vlan, so lets create a package/object
# for it.
#
package VLan;
use libdb;
use libtestbed;
use English;
use Lan;
2432
use Interface;
2433 2434
use overload ('""' => 'Stringify');

2435 2436
my $SNMPIT = "$TB/bin/snmpit";

2437 2438 2439 2440 2441 2442 2443 2444 2445
# Cache of instances to avoid regenerating them.
my %vlans   = ();

#
# Lookup and create a class instance to return.
#
sub Lookup($$;$)
{
    my ($class, $arg1, $arg2) = @_;
2446
    my $lan;
2447

2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
    #
    # Lan->Lookup() does not do exactly what I want in two arg case.
    #
    if (!defined($arg2)) {
	$lan = Lan->Lookup($arg1);
    }
    elsif (!ref($arg1)) {
	# Two args means lookup by $experiment,$vname
	print STDERR "VLan->Lookup(): Bad first argument: $arg1\n";
	return undef;
    }
2459
    elsif (! ($arg2 =~ /^[-\w\/]*$/)) {
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
	print STDERR "VLan->Lookup(): Bad second argument: $arg2\n";
	return undef;
    }
    else {
	my $exptidx = $arg1->idx();
	my $result = 
	    DBQueryWarn("select lanid from lans ".
			"where exptidx='$exptidx' and vname='$arg2' and ".
			"      type='vlan'");
	return undef
	    if (!defined($result) || !$result->numrows);
	my ($lanid) = $result->fetchrow_array();
	$lan = Lan->Lookup($lanid);
    }
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
    return undef
	if (!defined($lan));

    my $lanid = $lan->lanid();

    # Look in cache first
    return $vlans{"$lanid"}
        if (exists($vlans{"$lanid"}));

    my $self        = {};
    $self->{'LAN'}  = $lan;

    bless($self, $class);
    
    # Add to cache. 
    $vlans{"$lanid"} = $self;
    
    return $self;
}

# accessors
sub pid($)	{ return $_[0]->GetLan()->pid(); }
sub eid($)	{ return $_[0]->GetLan()->eid(); }
sub exptidx($)	{ return $_[0]->GetLan()->exptidx(); }
sub lanid($)    { return $_[0]->GetLan()->lanid(); }
sub id($)       { return $_[0]->GetLan()->lanid(); }
sub vname($)	{ return $_[0]->GetLan()->vname(); }
sub ready($)	{ return $_[0]->GetLan()->ready(); }
sub type($)	{ return $_[0]->GetLan()->type(); }
Leigh Stoller's avatar
Leigh Stoller committed
2503
sub link($)	{ return $_[0]->GetLan()->link(); }
2504
sub GetLan($)   { return $_[0]->{'LAN'}; }
2505
sub GetExperiment($) { return $_[0]->GetLan()->GetExperiment(); }
2506
sub vlanid($)   { return $_[0]->lanid(); }
2507

2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
#
# Lookup a vlan in the internal holding experiment.
#
#
# Lookup an internal vlan (in the vlan-holding experiment).
#
sub LookupInternal($$)
{
    my ($class, $vname) = @_;

    require Experiment;
    my $experiment = Experiment->Lookup(VLAN_PID(), VLAN_EID());
    return undef
	if (!defined($experiment));

    my $lan = Lan->Lookup($experiment, $vname);
    return undef
	if (!defined($lan));

    return VLan->Lookup($lan->lanid());
}

2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
#
# Create a new VLan object and return it. No members yet ... which means
# it has to be locked so that snmpit does not try to do anything with it.
# For now lets use a 'ready' bit unless it becomes annoying.
#
sub Create($$$;$)
{
    my ($class, $experiment, $vname, $id) = @_;

    # The new lan has the 'ready' bit set to zero.
    my $lan = Lan->Create($experiment, $vname, "vlan", $id);
    return undef
	if (!defined($lan));

2544 2545 2546 2547
    my $vlan = VLan->Lookup($lan->lanid());
    return undef
	if (!defined($vlan));

2548
    $vlan->SetClass("Experimental") == 0
2549 2550 2551
	or return undef;

    return $vlan;
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
}

#
# Destroy.
#
sub Destroy($)
{
    my ($self) = @_;

    return $self->GetLan()->Destroy();
}

2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
#
# Equality
#
sub SameVlan($$)
{
    my ($self, $other) = @_;

    return $self->id() == $other->id();
}

2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
#
# Refresh underyling object.
#
sub Refresh($)
{
    my ($self) = @_;

    return $self->GetLan()->Refresh();
}

2584 2585 2586
#
# Stringify for output.
#
2587 2588 2589 2590 2591 2592
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
2593 2594 2595 2596 2597 2598 2599
    
    my $pid   = $self->pid();
    my $eid   = $self->eid();
    my $vname = $self->vname();
    my $id    = $self->lanid();
    my $tag   = $self->GetTag();
    $tag = (defined($tag) ? ":${tag}" : "");
2600

2601
    return "[VLan ${id}${tag}: $pid/$eid/$vname]";
2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
}

#
# Add an interface to a vlan. Hand this off to Lan->AddInterface().
# Local lans/links map to vlans directly. 
#
sub AddInterface($$$$$)
{
    my ($self, $node, $vnode, $vport, $iface) = @_;
    
    return $self->GetLan()->AddInterface($node, $vnode, $vport, $iface);
}

#
# Add a member to a vlan, as for delay node links and tagged vlans.
#
sub AddMember($;$$)
{
    my ($self, $node, $iface) = @_;
    
    return $self->GetLan()->AddMember($node, $iface);
}

#
# Remove a member from a vlan.
#
sub DelMember($$)
{
    my ($self, $member) = @_;
    
    return $self->GetLan()->DelMember($member);
}

2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
#
# Find a member
#
sub FindMember($$$)
{
    my ($self, $node, $iface) = @_;
    
    return $self->GetLan()->FindMember($node, $iface);
}

#
# Add a member in snmpit port form (node:card).
#
Weibin Sun's avatar
Weibin Sun committed
2648
sub AddPort_OLD($$)
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
{
    my ($self, $port) = @_;
    my ($node_id, $card) = split(":", $port);

    my $interface = Interface->Lookup($node_id, $card, 1);
    return undef
	if (!defined($interface));

    my $member = $self->FindMember($node_id, $interface->iface());
    return $member
	if (defined($member));
				   
    return $self->GetLan()->AddMember($node_id, $interface->iface());
}

Weibin Sun's avatar
Weibin Sun committed
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
#
# Use Port class
#
sub AddPort($$)
{
    my ($self, $port) = @_;
    if (!ref($port)) {
	    return $self->AddPort_OLD($port);
    }

    my $member = $self->FindMember($port->node_id(), $port->iface());
    return $member
	if (defined($member));
				   
    return $self->GetLan()->AddMember($port->node_id(), $port->iface());
}

2681 2682 2683
#
# Delete a member in snmpit port form (node:card).
#
2684
sub DelPort_OLD($$)
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
{
    my ($self, $port) = @_;
    my ($node_id, $card) = split(":", $port);

    my $interface = Interface->Lookup($node_id, $card, 1);
    return -1
	if (!defined($interface));

    my $member = $self->FindMember($node_id, $interface->iface());
    return 0
	if (!defined($member));
				   
    return $self->DelMember($member);
}

2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716
#
# Delete a member, use Port class
#
sub DelPort($$)
{
    my ($self, $port) = @_;
    if (!ref($port)) {
	    return $self->DelPort_OLD($port);
    }
    my $member = $self->FindMember($port->node_id(), $port->iface());
    return 0
	if (!defined($member));
				   
    return $self->DelMember($member);
}


2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
#
# Does member already exists in protolan.
#
sub IsMember($$$)
{
    my ($self, $node, $iface) = @_;

    return $self->GetLan()->IsMember($node, $iface);
}

2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
#
# Return a list of interfaces for a vlan.
#
sub InterfaceList($$)
{
    my ($self, $plist) = @_;

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

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

    my $query_result =
	DBQueryWarn("select ifaceid from ifaces where lanid='$lanid'");
    return -1
	if (!defined($query_result));

    my @result = ();
    while (my ($ifaceid) = $query_result->fetchrow_array()) {
	my $interface = Lan::Interface->Lookup($self->GetLan(), $ifaceid);
	return -1
	    if (!defined($interface));
	push(@result, $interface);
    }
    @$plist = @result;
    return 0;
}

#
# Return a list of members for a vlan.
#
sub MemberList($$)
{
    my ($self, $plist) = @_;

    return $self->GetLan()->MemberList($plist);
}

2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
sub PortList($$)
{
    my ($self, $pref) = @_;
    my @members;
    my @ports  = ();

    return -1
	if ($self->MemberList(\@members) != 0);

    foreach my $member (@members) {
	my $nodeid;
	my $iface;

	return -1
	    if ($member->GetAttribute("node_id", \$nodeid) != 0 ||
		$member->GetAttribute("iface", \$iface) != 0);
	
	push(@ports, "$nodeid:$iface");
    }
    @$pref = @ports;
    return 0;
}

2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
#
# Get value of an attribute.
#
sub GetAttribute($$$;$)
{
    my ($self, $key, $pvalue, $ptype) = @_;

    return $self->GetLan()->GetAttribute($key, $pvalue, $ptype);
}

#
# Set value of an attribute.
#
sub SetAttribute($$$;$)
{
    my ($self, $key, $value, $type) = @_;

    return $self->GetLan()->SetAttribute($key, $value, $type);
}
sub SetRole($$)
{
    my ($self, $role) = @_;

    return $self->GetLan()->SetRole($role);
}
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
sub GetRole($;$)
{
    my ($self, $prole) = @_;
    my $role;

    return -1
	if ($self->GetAttribute("role", \$role) != 0);

    if (defined($prole)) {
	$$prole = $role;
	return 0;
    }
    return $role;
}
2827 2828 2829
sub GetTag($$)
{
    my ($self, $ptag) = @_;
2830 2831 2832 2833 2834 2835 2836 2837
    my $lanid = $self->lanid();

    #
    # Go to vlans table for this, since that ensures that things are
    # consistent.
    #
    my $query_result =
	DBQueryWarn("select tag from vlans where id='$lanid'");
2838 2839

    return -1
2840 2841 2842
	if (! (defined($query_result) || $query_result->numrows));
    
    my ($tag) = $query_result->fetchrow_array();
2843 2844 2845 2846 2847 2848 2849 2850

    if (defined($ptag)) {
	$$ptag = $tag;
	return 0;
    }
    return $tag;
	
}
2851
sub SetClass($$)
2852
{
2853
    my ($self, $class) = @_;
2854