Node.pm.in 106 KB
Newer Older
1
#!/usr/bin/perl -wT
2
#
3
# Copyright (c) 2005-2017 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
#
package Node;
25 26
use strict;
use Exporter;
27 28 29
use SelfLoader ();
use vars qw(@ISA @EXPORT $AUTOLOAD @EXPORT_OK);
@ISA = qw(Exporter SelfLoader);
30
@EXPORT = qw();
31

Leigh Stoller's avatar
Leigh Stoller committed
32
# Configure variables
33
use vars qw($TB $BOSSNODE $WOL $OSSELECT $IPOD $ISUTAH $CONTROL_NETMASK
34
            $TBOPS $JAILIPMASK $TBBASE $TBADB);
35 36
$TB	     = "@prefix@";
$BOSSNODE    = "@BOSSNODE@";
37
$TBOPS       = "@TBOPSEMAIL@";
38 39
$WOL         = "$TB/sbin/whol";
$OSSELECT    = "$TB/bin/os_select";
40
$IPOD	     = "$TB/sbin/ipod";
41
$TBADB       = "$TB/bin/tbadb";
Leigh Stoller's avatar
Leigh Stoller committed
42
# XXX stinky hack detection
43
$ISUTAH	     = @TBMAINSITE@;
44
# Need this for jail ip assignment.
45
$CONTROL_NETMASK = "@CONTROL_NETMASK@";
46
$JAILIPMASK  = "@JAILIPMASK@";
47
$TBBASE      = "@TBBASE@";
48

49
use libdb;
50
use libtestbed;
51
use emutil;
52
use English;
53
use Socket;
54 55
use Data::Dumper;
use overload ('""' => 'Stringify');
56 57

use vars qw($NODEROLE_TESTNODE $MFS_INITIAL $STATE_INITIAL
58
	    %nodes @cleantables);
59

60 61 62 63 64 65
# Exported defs
$NODEROLE_TESTNODE	= 'testnode';

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

66
# Cache of instances to avoid regenerating them.
67
%nodes = ();
68
BEGIN { use emutil; emutil::AddCache(\%nodes); }
69 70 71 72 73 74 75

# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
76
	if (0);
77 78
    return system($command);
}
79

80
# To avoid writing out all the methods.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
AUTOLOAD {
#    print STDERR "$AUTOLOAD $_[0]\n";

    if (!ref($_[0])) {
	$SelfLoader::AUTOLOAD = $AUTOLOAD;
	return SelfLoader::AUTOLOAD(@_);
    }
    my $self  = $_[0];
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'DBROW'}->{$name})) {
	return $self->{'DBROW'}->{$name};
    }

    # The method is possibly for a SelfLoader method after __DATA__
    # Or it is for a local storage slot.
    if ($name =~ /^_.*$/) {
	if (scalar(@_) == 2) {
	    return $self->{'HASH'}->{$name} = $_[1];
	}
	elsif (exists($self->{'HASH'}->{$name})) {
	    return $self->{'HASH'}->{$name};
	}
    }
    $SelfLoader::AUTOLOAD = $AUTOLOAD;
    my $ref = \&SelfLoader::AUTOLOAD;
    goto &$ref;
}

#
# The list of table we have to clear if anything goes wrong when
# creating a new node.
# 
@cleantables = ("nodes", "node_hostkeys", "node_status",
		"node_activity", "node_utilization",
		"node_auxtypes", "reserved", "widearea_nodeinfo");


121
#
122
# Lookup a (physical) node and create a class instance to return.
123
#
124 125
sub Lookup($$)
{
126 127 128
    my ($class, $token) = @_;
    my $nodeid;

129
    if ($token =~ /^\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12}$/) {
130 131 132 133 134 135 136 137 138 139 140 141 142 143
	my $query_result =
	    DBQueryWarn("select node_id from nodes ".
			"where uuid='$token'");
	    return undef
		if (! $query_result || !$query_result->numrows);

	    ($nodeid) = $query_result->fetchrow_array();
    }
    elsif ($token =~ /^[-\w]+$/) {
	$nodeid = $token;
    }
    else {
	return undef;
    }
144

145
    # Look in cache first
146 147
    return $nodes{$nodeid}
        if (exists($nodes{$nodeid}));
148 149

    my $query_result =
150 151
	DBQueryWarn("select * from nodes as n ".
		    "where n.node_id='$nodeid'");
152

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

156
    return LookupRow($class, $query_result->fetchrow_hashref());
157 158 159 160 161 162 163 164
}

#
# Lookup a (physical) node based on an existing row from the database.
# Useful for bulk lookups.
#
sub LookupRow($$)
{
165
    my ($class, $row) = @_;
166

167
    my $self            = {};
168
    $self->{"DBROW"}    = $row;
169 170
    $self->{"RSRV"}     = undef;
    $self->{"TYPEINFO"} = undef;
171
    $self->{"ATTRS"}    = undef;
172
    $self->{"FEATURES"} = undef;
173
    $self->{"IFACES"}   = undef;
174
    $self->{"WAROW"}    = undef;
175 176 177
    $self->{"HASH"}     = {};
    bless($self, $class);

178
    $nodes{$row->{'node_id'}} = $self;
179 180 181
    return $self;
}

182 183 184 185 186 187 188 189 190 191 192 193 194
#
# Force a reload of the data.
#
sub LookupSync($$)
{
    my ($class, $nodeid) = @_;

    # delete from cache
    delete($nodes{$nodeid});

    return Lookup($class, $nodeid);
}

195 196 197 198 199 200 201 202
# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{"DBROW"}    = undef;
    $self->{"RSRV"}     = undef;
    $self->{"TYPEINFO"} = undef;
    $self->{"ATTRS"}    = undef;
203
    $self->{"FEATURES"} = undef;
204 205
    $self->{"IFACES"}   = undef;
    $self->{"HASH"}     = undef;
206
    $self->{"WAROW"}    = undef;
207 208
}

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $nodeid = $self->node_id();

    return "[Node: $nodeid]";
}

# Local lookup for an Experiment, to avoid dragging in the module.
sub LocalExpLookup(@)
{
    require Experiment;

    return Experiment->Lookup(@_);
}

1;
230
@SELFLOADER_DATA@
231

232 233 234 235 236 237 238 239 240 241 242 243
#
# Create a fake object, as for the mapper (assign_wrapper) during debugging.
#
sub MakeFake($$$$)
{
    my ($class, $nodeid, $dbrow, $rsrvrow) = @_;

    my $self            = {};
    $self->{"DBROW"}    = $dbrow;
    $self->{"RSRV"}     = $rsrvrow;
    $self->{"TYPEINFO"} = undef;
    $self->{"ATTRS"}    = undef;
244
    $self->{"FEATURES"} = undef;
245
    $self->{"IFACES"}   = undef;
246
    $self->{"WAROW"}    = undef;
247
    $self->{"HASH"}     = {};
248 249 250
    bless($self, $class);

    # Add to cache.
251 252 253
    $nodes{$nodeid} = $self;
    return $self;
}
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

#
# Bulk lookup of nodes reserved to an experiment. More efficient.
#
sub BulkLookup($$$)
{
    my ($class, $experiment, $pref) = @_;
    my %nodelist = ();
    my $exptidx  = $experiment->idx();

    my $query_result =
	DBQueryWarn("select n.* from reserved as r ".
		    "left join nodes as n on n.node_id=r.node_id ".
		    "where r.exptidx=$exptidx");

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

    while (my $row = $query_result->fetchrow_hashref()) {
273
	my $nodeid = $row->{'node_id'};
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
	my $node;

	if (exists($nodes{$nodeid})) {
	    $node = $nodes{$nodeid};
	    $node->{"DBROW"} = $row;
	}
	else {
	    $node               = {};
	    $node->{"DBROW"}    = $row;
	    bless($node, $class);

	    # Add to cache.
	    $nodes{$nodeid} = $node;
	}
	$node->{"RSRV"}     = undef;
	$node->{"TYPEINFO"} = undef;
	$node->{"ATTRS"}    = undef;
291
	$node->{"FEATURES"} = undef;
292
	$node->{"IFACES"}   = undef;
Mike Hibler's avatar
Mike Hibler committed
293
	$node->{"WAROW"}    = undef;
294
	$node->{"HASH"}     = {};
295 296 297 298 299 300 301 302 303 304 305
	
	$nodelist{$nodeid} = $node;
    }

    $query_result =
	DBQueryWarn("select r.* from reserved as r ".
		    "where r.exptidx=$exptidx");
    return -1
	if (!defined($query_result));
    
    while (my $row = $query_result->fetchrow_hashref()) {
306
	my $nodeid = $row->{'node_id'};
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
	my $node   = $nodelist{$nodeid};

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

	$node->{"RSRV"} = $row;
    }

    $query_result =
	DBQueryWarn("select a.* from reserved as r ".
		    "left join node_attributes as a on a.node_id=r.node_id ".
		    "where r.exptidx=$exptidx and a.node_id is not null");
    return -1
	if (!defined($query_result));
    
    while (my $row = $query_result->fetchrow_hashref()) {
323
	my $nodeid = $row->{'node_id'};
324 325 326 327 328 329 330 331 332 333 334 335
	my $key    = $row->{'attrkey'};
	my $node   = $nodelist{$nodeid};

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

	$node->{"ATTRS"}->{$key} = $row;
    }
	
    @$pref = values(%nodelist);
    return 0;
}
336

Leigh Stoller's avatar
Leigh Stoller committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
#
# Lookup all nodes of a type
#
sub LookupByType($$)
{
    my ($class, $type) = @_;
    my @result = ();

    my $query_result =
	DBQueryWarn("select node_id from nodes as n where n.type='$type'");
    return ()
	if (!$query_result);

    while (my ($node_id) = $query_result->fetchrow_array()) {
	my $node = Node->Lookup($node_id);
	if (!defined($node)) {
	    print STDERR "No such node $node_id\n";
	    next;
	}
	push(@result, $node);
    }
    return @result;
}

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
#
# Do we have regular nodes? Class method.
#
sub HaveExperimentNodes()
{
    my $query_result =
	DBQueryWarn("select count(node_id) from nodes as n ".
		    "left join node_types as t on t.type=n.type ".
		    "where t.class='pc'");
    return 0
	if (!$query_result);
    
    my ($count) = $query_result->fetchrow_array();
    return $count;
}

377 378 379 380
sub Create($$$$)
{
    my ($class, $node_id, $experiment, $argref) = @_;
    my ($control_iface,$virtnode_capacity,$adminmfs,$adminmfs_osid);
381
    my ($priority, $osid, $osid_vers, $opmode, $state);
382
    require OSImage;
383 384 385 386 387 388 389 390
    require NodeType;

    # Defaults. Leave these here to avoid startup costs of libdb.
    #
    # MFS to boot the nodes into initially
    my $MFS_INITIAL   = TB_OSID_FREEBSD_MFS();
    # Initial event system state to put the nodes into
    my $STATE_INITIAL = TBDB_NODESTATE_SHUTDOWN();
391 392 393

    my $type = $argref->{'type'};
    my $role = $argref->{'role'};
394 395 396 397 398 399 400 401 402 403 404 405 406
    my $uuid;

    if (exists($argref->{'uuid'})) {
	$uuid = $argref->{'uuid'};
    }
    else {
	$uuid = NewUUID();
	if (!defined($uuid)) {
	    print STDERR "Could not generate a UUID!\n";
	    return undef;
	}
    }
    $uuid = DBQuoteSpecial($uuid);
407 408 409 410 411 412

    my $typeinfo = NodeType->Lookup($type);
    return undef
	if (!defined($typeinfo));

    my $isremote = $typeinfo->isremotenode();
413
    $osid_vers   = 0;
414

415 416 417 418 419
    if ($role eq "testnode") {
	if ($typeinfo->virtnode_capacity(\$virtnode_capacity)) {
	    print STDERR "*** No virtnode_capacity for $type! Using zero.\n";
	    $virtnode_capacity = 0;
	}
420 421 422 423
	if ($typeinfo->isswitch()) {
	    $osid   = "NULL";
	    $opmode = "ALWAYSUP";
	}
424
	elsif ($isremote || $typeinfo->isfakenode()) {
425
	    $osid   = "NULL";
426 427 428 429 430
	    $opmode = "";

	    if (defined($typeinfo->default_osid())) {
		$osid = $typeinfo->default_osid();
		
431 432
		my $osimage = OSImage->Lookup($osid);
		if (!defined($osimage)) {
433
		    print STDERR
434
			"*** Could not find OSImage object for $osid!\n";
435 436
		    return undef;
		}
437 438 439
		$osid      = $osimage->osid();
		$osid_vers = $osimage->version();
		$opmode    = $osimage->op_mode();
440
	    }
441 442
	}
	else {
443 444 445 446 447 448
	    if ($typeinfo->adminmfs_osid(\$adminmfs_osid)) {
		print STDERR "*** No adminmfs osid for $type!\n";
		return undef;
	    }
	    # Find object for the adminfs.
	    if (defined($adminmfs_osid)) {
449
		$adminmfs = OSImage->Lookup($adminmfs_osid);
450 451
	    }
	    else {
452
		$adminmfs = OSImage->Lookup(TBOPSPID(), $MFS_INITIAL);
453 454 455
	    }
	    if (!defined($adminmfs)) {
		print STDERR
456
		    "*** Could not find OSImage object for adminmfs!\n";
457 458
		return undef;
	    }
459
	    $osid      = $adminmfs->osid();
460
	    $osid_vers = $adminmfs->version();
461
	    $opmode    = $adminmfs->op_mode();
462
	}
463 464
    }
    else {
465
	$osid   = "NULL";
466
	$opmode = "";
467
    }
Leigh Stoller's avatar
Leigh Stoller committed
468 469
    if (exists($argref->{'initial_eventstate'})) {
	$state = $argref->{'initial_eventstate'};
470 471 472 473
    }
    else {
	$state  = $STATE_INITIAL;
    }
474 475 476 477

    #
    # Lock the tables to prevent concurrent creation
    #
478 479 480 481 482
    DBQueryWarn("lock tables nodes write, widearea_nodeinfo write, ".
		"node_hostkeys write, node_status write, ".
		"node_utilization write, ".
		"node_activity write, reserved write, node_auxtypes write")
	or return undef;
483

484 485 486 487 488 489 490 491 492
    #
    # Make up a priority (just used for sorting)
    #
    if ($node_id =~ /^(.*\D)(\d+)$/) {
	$priority = $2;
    }
    else {
	$priority = 1;
    }
493

494 495 496 497 498 499 500 501 502 503 504
    #
    # See if we have a record; if we do, we can stop now and get the
    # existing record.
    #
    my $query_result =
	DBQueryWarn("select node_id from nodes where node_id='$node_id'");
    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
	return Node->Lookup($node_id);
    }

505 506 507 508 509
    if (!DBQueryWarn("insert into nodes set ".
		     "  node_id='$node_id', type='$type', " .
		     "  phys_nodeid='$node_id', role='$role', ".
		     "  priority=$priority, " .
		     "  eventstate='$state', op_mode='$opmode', " .
Leigh Stoller's avatar
Leigh Stoller committed
510
		     "  def_boot_osid=$osid, def_boot_osid_vers='$osid_vers',".
511 512 513 514 515 516 517 518 519 520
		     "  inception=now(), uuid=$uuid, ".
		     "  state_timestamp=unix_timestamp(NOW()), " .
		     "  op_mode_timestamp=unix_timestamp(NOW())")) {
	DBQueryWarn("unlock tables");
	return undef;
    }
    if ($isremote) {
	my $hostname = $argref->{'hostname'};
	my $external = $argref->{'external_node_id'};
	my $IP       = $argref->{'IP'};
521 522 523 524 525 526 527 528 529 530

	# Hmm, wanodecreate already does this.
	my $wa_result =
	    DBQueryWarn("select node_id from widearea_nodeinfo ".
			"where node_id='$node_id'");
	goto bad
	    if (!$wa_result);
	
	if ($wa_result->numrows == 0 &&
	    !DBQueryWarn("replace into widearea_nodeinfo ".
531 532 533 534 535 536 537 538 539
			 " (node_id, contact_uid, contact_idx, hostname," .
			 "  external_node_id, IP) ".
			 " values ('$node_id', 'nobody', '0', ".
			 "         '$hostname', '$external', '$IP')")) {
	    DBQueryWarn("delete from nodes where node_id='$node_id'");
	    DBQueryWarn("unlock tables");
	    return undef;
	}
    }
540

541 542 543 544
    if ($role eq "testnode") {
	DBQueryWarn("insert into node_hostkeys (node_id) ".
		    "values ('$node_id')")
	    or goto bad;
545
	
546 547 548 549
	DBQueryWarn("insert into node_status ".
		    "(node_id, status, status_timestamp) ".
		    "values ('$node_id', 'down', now()) ")
	    or goto bad;
550
    
551 552 553
	DBQueryWarn("insert into node_activity ".
		    "(node_id) values ('$node_id')")
	    or goto bad;
554
	
555 556 557 558
	DBQueryWarn("insert into node_utilization ".
		    "(node_id) values ('$node_id')")
	    or goto bad;
    }
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

    if (defined($experiment)) {
	my $exptidx = $experiment->idx();
	my $pid     = $experiment->pid();
	my $eid     = $experiment->eid();

	# Reserve node to hold it from being messed with.
	print STDERR
	    "*** Reserving new node $node_id to $pid/$eid\n";

	DBQueryWarn("insert into reserved ".
		    "(node_id, exptidx, pid, eid, rsrv_time, vname) ".
		    "values ('$node_id', $exptidx, ".
		    "        '$pid', '$eid', now(), '$node_id')")
	    or goto bad;
    }

    #
    # Add vnode counts.
    #
    if ($role eq $Node::NODEROLE_TESTNODE && $virtnode_capacity) {
580 581 582 583
	my $vtype;
	
	if (exists($argref->{'vtype'})) {
	    $vtype = $argref->{'vtype'};
584
	}
585 586 587 588 589 590 591
	else  {
	    $vtype = $type;
	    if (!($vtype =~ s/pc/pcvm/)) {
		$vtype = "$vtype-vm";
	    }
	}
	
592 593 594 595
	DBQueryWarn("insert into node_auxtypes set node_id='$node_id', " .
		    "type='$vtype', count=$virtnode_capacity")
	    or goto bad;
    }
596
    DBQueryWarn("unlock tables");
597 598 599 600 601 602
    return Node->Lookup($node_id);
    
  bad:
    foreach my $table (@cleantables) {
	DBQueryWarn("delete from $table where node_id='$node_id'");
    }
603
    DBQueryWarn("unlock tables");
604 605 606
    return undef;
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620
#
# Only use this for Create() errors.
#
sub Delete($)
{
    my ($self)  = @_;
    my $node_id = $self->node_id();

    foreach my $table (@cleantables) {
	DBQueryWarn("delete from $table where node_id='$node_id'");
    }
    return 0;
}

621
#
622
# Refresh a class instance by reloading from the DB.
623
#
624
sub Refresh($)
625
{
626 627 628 629
    my ($self) = @_;

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

631
    my $nodeid = $self->node_id();
632

633 634 635 636 637 638 639 640 641 642 643
    my $query_result =
	DBQueryWarn("select * from nodes as n ".
		    "where n.node_id='$nodeid'");

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

    $self->{"DBROW"}  = $query_result->fetchrow_hashref();
    # Force reload
    $self->{"RSRV"}     = undef;
    $self->{"TYPEINFO"} = undef;
644
    $self->{"ATTRS"}    = undef;
645
    $self->{"FEATURES"} = undef;
646
    $self->{"IFACES"}   = undef;
647
    $self->{"WAROW"}    = undef;
648
    return 0;
649 650
}

Leigh Stoller's avatar
Leigh Stoller committed
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

    delete($nodes{$self->node_id()});
}
sub FlushAll($)
{
    my ($class) = @_;
    
    %nodes = ();
}

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
#
# Convenience access method for widearea info
#
sub WideAreaInfo($$)
{
    my ($self, $slot) = @_;
    my $node_id = $self->node_id();

    if (!defined($self->{'WAROW'})) {
	my $query_result =
	    DBQueryWarn("select * from widearea_nodeinfo ".
			"where node_id='$node_id'");

	if (!$query_result || !$query_result->numrows) {
	    print STDERR "*** $node_id is not a widearea node\n";
	    return undef;
	}
	$self->{'WAROW'} = $query_result->fetchrow_hashref();
    }
    if (!exists($self->{'WAROW'}->{$slot})) {
	print STDERR
	    "*** Nonexistent slot '$slot' request for widearea node $node_id\n";
	return undef;
    }
    return $self->{'WAROW'}->{$slot};
}

694 695 696 697 698 699 700 701 702
#
# Check permissions. Allow for either uid or a user ref until all code
# updated.
#
sub AccessCheck($$$)
{
    my ($self, $user, $access_type) = @_;

    # Must be a real reference. 
703
    return 0
704 705
	if (! ref($self));

706 707
    if ($access_type < TB_NODEACCESS_MIN ||
	$access_type > TB_NODEACCESS_MAX) {
708
	print STDERR "*** Invalid access type: $access_type!\n";
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
	return 0;
    }
    # Admins do whatever they want.
    return 1
	if ($user->IsAdmin());

    my $mintrust;

    if ($access_type == TB_NODEACCESS_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

    # Get the reservation for this node. Only admins can mess with free nodes.
    my $experiment = $self->Reservation();
    return 0
	if (!defined($experiment));
728

729 730 731 732 733 734 735 736 737 738 739 740 741 742
    my $group = $experiment->GetGroup();
    return 0
	if (!defined($group));
    my $project = $experiment->GetProject();
    return 0
	if (!defined($project));

    #
    # Either proper permission in the group, or group_root in the
    # project. This lets group_roots muck with other people's
    # nodes, including those in groups they do not belong to.
    #
    return TBMinTrust($group->Trust($user), $mintrust) ||
	TBMinTrust($project->Trust($user), PROJMEMBERTRUST_GROUPROOT);
743 744
}

745
#
746 747 748
# Lazily load the reservation info.
#
sub IsReserved($)
749
{
750
    my ($self) = @_;
751

Leigh Stoller's avatar
Leigh Stoller committed
752
    return 0
753
	if (! ref($self));
754

755 756 757 758 759 760
    if (! defined($self->{"RSRV"})) {
	my $nodeid = $self->node_id();
	
	my $query_result =
	    DBQueryWarn("select * from reserved " .
			"where node_id='$nodeid'");
Leigh Stoller's avatar
Leigh Stoller committed
761
	return 0
762 763 764 765 766 767 768 769
	    if (!$query_result);
	return 0
	    if (!$query_result->numrows);

	$self->{"RSRV"} = $query_result->fetchrow_hashref();
	return 1;
    }
    return 1;
770 771
}

772 773 774 775 776 777 778 779 780 781
#
# Set reserved member based on a database row. Useful for bulk lookups.
#
sub SetReservedRow($$)
{
    my ($self, $reserved) = @_;
    if ($reserved->{"node_id"} eq $self->node_id()) {
	$self->{"RSRV"} = $reserved;
    }
}
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821

sub GetSubboss($$)
{
    my ($self, $service, $subboss_id) = @_;

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

    my $ref;

    if (defined $self->{"SUBBOSSES"}) {
	my $ref = $self->{"SUBBOSSES"}->{$service};
    }

    if (!defined $ref) {
	my $nodeid = $self->node_id();

	my $query_result =
	    DBQueryWarn("select * from subbosses " .
			"where node_id='$nodeid' and " .
			"service = '$service'");

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

	if (!defined($self->{"SUBBOSSES"})) {
	    $self->{"SUBBOSSES"} = {};
	}

	$ref = $self->{"SUBBOSSES"}->{$service} =
	    $query_result->fetchrow_hashref();
    }

    $$subboss_id = $ref->{'subboss_id'};

    return 0;
}

822 823 824 825 826 827 828 829 830 831 832
#
# Flush the reserve info so it reloads.
#
sub FlushReserved($)
{
    my ($self) = @_;

    $self->{"RSRV"} = undef;
    return 0;
}

833 834 835 836 837 838 839 840 841 842 843 844 845
#
# Is node up.
#
sub IsUp($)
{
    my ($self) = @_;

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

    return $self->eventstate() eq TBDB_NODESTATE_ISUP;
}

Leigh Stoller's avatar
Leigh Stoller committed
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
#
# Determine if a node can be allocated to a project.
#
sub NodeAllocCheck($$)
{
    my ($self, $pid) = @_;

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

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

    #
    # Hmm. The point of this join is to find rows in the permissions table
    # with the corresponding type of the node. If no rows come back, its
    # a non-existent node! If the values are NULL, then there are no rows
    # with that type/class, and thus the type/class is free to be allocated
    # by anyone. Otherwise we get the list of projects that are allowed,
    # and so we have to look at those.
866 867 868
    # Note: nodetypeXpid_permissions has the pid_idx in addition to the pid -
    # presumably, the Right Thing would be to use that, but this function
    # is only passed the pid right now.
Leigh Stoller's avatar
Leigh Stoller committed
869 870
    #
    my $query_result =
871
	DBQueryFatal("select distinct p.type, p.pid_idx from nodes as n ".
Leigh Stoller's avatar
Leigh Stoller committed
872 873 874 875 876 877 878 879 880
		     "left join node_types as nt on n.type=nt.type ".
		     "left join nodetypeXpid_permissions as p on ".
		     "     (p.type=nt.type or p.type=nt.class) ".
		     "where node_id='$node_id'");

    if (!$query_result->numrows) {
	print STDERR "NodeAllocCheck: No such node $node_id!\n";
	return 0;
    }
881
    my ($ptype,$pid_idx) = $query_result->fetchrow_array();
Leigh Stoller's avatar
Leigh Stoller committed
882 883

    # No rows, or a pid match.
884
    if (!defined($ptype) || $pid_idx eq $pid->pid_idx()) {
Leigh Stoller's avatar
Leigh Stoller committed
885 886 887 888
	return 1;
    }

    # Okay, must be rows in the permissions table. Check each pid for a match.
889 890
    while (my ($ptype,$pid_idx) = $query_result->fetchrow_array()) {
	if ($pid_idx eq $pid->pid_idx()) {
Leigh Stoller's avatar
Leigh Stoller committed
891 892 893 894 895 896
	    return 1;
	}
    }
    return 0;
}

897 898 899 900 901 902 903 904
# Naming confusion.
sub AllocCheck($$)
{
    my ($self, $pid) = @_;

    return $self->NodeAllocCheck($pid);
}

Leigh Stoller's avatar
Leigh Stoller committed
905 906 907 908 909 910 911 912 913 914 915 916
#
# Set alloc state for a node.
#
sub SetAllocState($$)
{
    my ($self, $state) = @_;

    return -1
	if (! (ref($self)));
    
    my $now = time();
    my $node_id = $self->node_id();
917

Leigh Stoller's avatar
Leigh Stoller committed
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
    DBQueryWarn("update nodes set allocstate='$state', " .
		"    allocstate_timestamp=$now where node_id='$node_id'")
	or return -1;

    return Refresh($self);
}

#
# Get alloc state for a node.
#
sub GetAllocState($$)
{
    my ($self, $pref) = @_;

    return -1
	if (! (ref($self) && ref($pref)));
    
    my $allocstate = $self->allocstate();
    
    if (defined($allocstate)) {
	$$pref = $allocstate;
    }
    else {
	$$pref = TBDB_ALLOCSTATE_UNKNOWN;
    }
    return 0;
}

946 947 948
#
# We do this cause we always want to go to the DB.
#
949
sub GetEventState($;$$)
950
{
951
    my ($self, $pstate, $popmode) = @_;
952 953 954
    my $node_id = $self->node_id();

    my $query_result =
955 956
	DBQueryWarn("select eventstate,op_mode from nodes ".
		    "where node_id='$node_id'");
957 958 959
    return -1
	if (!$query_result || !$query_result->numrows);

960
    my ($state,$op_mode) = $query_result->fetchrow_array();
961 962
    $state = TBDB_NODESTATE_UNKNOWN
	if (!defined($state));
963 964
    $op_mode = TBDB_NODEOPMODE_UNKNOWN
	if (!defined($op_mode));
965

966
    $self->{'DBROW'}->{'eventstate'} = $state
967
	if (defined($self->{'DBROW'}));
968 969
    $$pstate = $state
     	if (defined($pstate));
970 971
    $$popmode= $op_mode
 	if (defined($popmode));
972 973 974
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
#
# Equality test for two experiments.
# Not strictly necessary in perl, but good form.
#
sub SameExperiment($$)
{
    my ($self, $other) = @_;

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

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

990 991 992 993 994 995 996
#
# Get the experiment this node is reserved too, or null.
#
sub Reservation($)
{
    my ($self) = @_;

997
    return undef
998 999
	if (! ref($self));

1000
    return undef
1001 1002
	if (! $self->IsReserved());

1003
    return LocalExpLookup($self->{"RSRV"}->{'exptidx'});
Leigh Stoller's avatar
Leigh Stoller committed
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
}

#
# Return just the ID of the reservation experiment. Avoids locking problems
# within nalloc and nfree. 
#
sub ReservationID($)
{
    my ($self) = @_;

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

    return undef
	if (! $self->IsReserved());

    return $self->{"RSRV"}->{'exptidx'};
}

#
# Get the NEXT experiment this node is reserved too, or null.
#
sub NextReservation($)
{
    my ($self) = @_;

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

    my $node_id = $self->node_id();
    
    my $query_result =
	DBQueryFatal("select pid,eid from next_reserve ".
		     "where node_id='$node_id'");

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

    my ($pid,$eid) = $query_result->fetchrow_array();

1044
    return LocalExpLookup($pid, $eid);
Leigh Stoller's avatar
Leigh Stoller committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
}

#
# Move a node from its experiment to another. Must treat oldreserved special.
#
sub MoveReservation($$)
{
    my ($self, $newexperiment) = @_;
    
    return -1
	if (! (ref($self) && ref($newexperiment)));

    my $node_id    = $self->node_id();
    my $newpid     = $newexperiment->pid();
    my $neweid     = $newexperiment->eid();
    my $newidx     = $newexperiment->idx();
    my $oldpid     = "";
    my $oldeid     = "";
    my $oldidx     = 0;
    
    # Must remember old reservation when moving to new oldreserved.
1066
    if ($newpid eq OLDRESERVED_PID() && $neweid eq OLDRESERVED_EID()) {	
Leigh Stoller's avatar
Leigh Stoller committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
        #
	# Cannot do an experiment Lookup cause reserved table may be locked.
	# IsReserved() will load the reserved table entry only.
	#
	return -1
	    if (!$self->IsReserved());
	
	$oldpid     = $self->{"RSRV"}->{'pid'};
	$oldeid     = $self->{"RSRV"}->{'eid'};
	$oldidx     = $self->{"RSRV"}->{'exptidx'};
    }
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    my $sets = "rsrv_time=now(), ".
	" vname='$node_id', ".
	" exptidx=$newidx, ".
	" pid='$newpid', ".
	" eid='$neweid', ".
	" old_exptidx=$oldidx, ".
	" old_pid='$oldpid', ".
	" old_eid='$oldeid' ";

    if ($self->IsReserved()) {
	DBQueryWarn("update reserved set $sets where node_id='$node_id'")
	    or return -1;
    }
    else {
	DBQueryWarn("insert into reserved set $sets, node_id='$node_id'")
	    or return -1;
    }
1095 1096 1097

    # Force this to reload.
    $self->{"RSRV"} = undef;
Leigh Stoller's avatar
Leigh Stoller committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    return 0;
}

#
# Change reservation table for a node.
#
sub ModifyReservation($$)
{
    my ($self, $argref) = @_;
    
    return -1
	if (! (ref($self) && ref($argref)));

    return -1
	if (! $self->IsReserved());
    
    my $node_id = $self->node_id();
1115 1116 1117
    my @sets    = ();
    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};
Leigh Stoller's avatar
Leigh Stoller committed
1118

1119 1120
	push(@sets, "$key=" . ("$val" eq "NULL" ? "NULL" : "'$val'"));
    }
Leigh Stoller's avatar
Leigh Stoller committed
1121

1122
    my $query = "update reserved set ".	join(",", @sets);
Leigh Stoller's avatar
Leigh Stoller committed
1123 1124 1125 1126 1127
    $query .= " where node_id='$node_id'";

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

1128 1129 1130 1131 1132 1133
    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};
	
	$self->{'DBROW'}->{$key} = $val;
    }
    return 0;
Leigh Stoller's avatar
Leigh Stoller committed
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
}

#
# Map nodeid to its pid/eid in the oldreserved holding reservation
#
sub OldReservation($)
{
    my ($self) = @_;

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

    my $nodeid          = $self->node_id();
    my $oldreserved_pid = OLDRESERVED_PID;
    my $oldreserved_eid = OLDRESERVED_EID;
    
    my $query_result =
	DBQueryWarn("select old_pid,old_eid from reserved ".
		    "where node_id='$nodeid' and pid='$oldreserved_pid' ".
		    "and eid='$oldreserved_eid'");

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

    my ($pid,$eid) = $query_result->fetchrow_array();
    
1160
    return LocalExpLookup($pid, $eid);
Leigh Stoller's avatar
Leigh Stoller committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
}

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

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

    my $nodeid          = $self->node_id();
    my $oldreserved_pid = OLDRESERVED_PID;
    my $oldreserved_eid = OLDRESERVED_EID;
    
    my $query_result =
	DBQueryWarn("select old_exptidx from reserved ".
		    "where node_id='$nodeid' and pid='$oldreserved_pid' ".
		    "and eid='$oldreserved_eid'");

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

    my ($idx) = $query_result->fetchrow_array();
    
    return $idx;
}

#
# Return the tip server (and tipname) for a node.
#
1190
sub TipServer($$;$$$)
Leigh Stoller's avatar
Leigh Stoller committed
1191
{
1192
    my ($self, $pserver, $ptipname, $pportnum, $pkeydata) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203

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

    $$pserver  = undef;
    $$ptipname = undef
	if (defined($ptipname));

    my $nodeid = $self->node_id();
	
    my $query_result =
1204
	DBQueryWarn("select server,tipname,portnum,keydata from tiplines " .
Leigh Stoller's avatar
Leigh Stoller committed
1205 1206 1207 1208 1209 1210 1211
		    "where node_id='$nodeid'");
    return -1
	if (!$query_result);
    
    return 0
	if (!$query_result->numrows);

1212
    my ($server,$tipname,$portnum,$keydata) = $query_result->fetchrow_array();
Leigh Stoller's avatar
Leigh Stoller committed
1213 1214 1215
    $$pserver  = $server;
    $$ptipname = $tipname
	if (defined($ptipname));
1216 1217 1218 1219
    $$pkeydata = $keydata
	if (defined($pkeydata));
    $$pportnum = $portnum
	if (defined($pportnum));
Leigh Stoller's avatar
Leigh Stoller committed
1220 1221

    return 0;
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
}

#
# Get the raw reserved table info and return it, or null if no reservation
#
sub ReservedTableEntry($)
{
    my ($self) = @_;

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

    return undef
	if (! $self->IsReserved());

    return $self->{"RSRV"};
}

Leigh Stoller's avatar
Leigh Stoller committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
#
# Return a list of virtual nodes on the given physical node.
#
sub VirtualNodes($$)
{
    my ($self, $plist) = @_;

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

1250 1251
    @$plist         = ();

Leigh Stoller's avatar
Leigh Stoller committed
1252
    my $reservation = $self->Reservation();
1253 1254 1255
    return 0
	if (!defined($reservation));

Leigh Stoller's avatar
Leigh Stoller committed
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
    my $node_id     = $self->node_id();
    my $exptidx     = $reservation->idx();
    my @result      = ();

    my $query_result = 
	DBQueryWarn("select r.node_id from reserved as r ".
		    "left join nodes as n ".
		    "on r.node_id=n.node_id ".
		    "where n.phys_nodeid='$node_id' and ".
		    "      n.node_id!=n.phys_nodeid and exptidx='$exptidx'");

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

    while (my ($node_id) = $query_result->fetchrow_array()) {
	my $node = Node->Lookup($node_id);
	if (!defined($node)) {
	    print STDERR "*** VirtualNodes: no such virtual node $node_id!\n";
	    return -1;
	}
	push(@result, $node);
    }
    @$plist = @result;
    return 0;
}

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
#
# Does a node have any virtual nodes on it. Table might be locked.
#
sub HasVirtualNodes($)
{
    my ($self) = @_;

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

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

    my $query_result = 
1297 1298 1299 1300 1301
	DBQueryWarn("select nodes.node_id from nodes ".
		    "left join reserved on reserved.node_id=nodes.node_id ".
		    "where nodes.phys_nodeid='$node_id' and ".
		    "      nodes.node_id!=nodes.phys_nodeid and ".
		    "      reserved.node_id is not null");
1302 1303 1304 1305 1306 1307
    return -1
	if (!$query_result);
    
    return $query_result->numrows;
}

1308 1309 1310
#
# Access methods for the reservation.
#
1311
sub L__reservation($$)
1312
{
1313
    my ($self, $slotname) = @_;
1314 1315 1316 1317 1318

    return undef
	if (! ref($self));
    return undef
	if (! $self->IsReserved());
1319
    return undef
1320
	if (! exists($self->{"RSRV"}->{$slotname}));
1321

1322
    return $self->{"RSRV"}->{$slotname};
1323
}
1324 1325 1326
sub vname($)		{ return L__reservation($_[0], 'vname'); }
sub sharing_mode($)	{ return L__reservation($_[0], 'sharing_mode'); }
sub erole($)		{ return L__reservation($_[0], 'erole'); }
1327 1328
sub eid($)              { return L__reservation($_[0], 'eid'); }
sub pid($)              { return L__reservation($_[0], 'pid'); }
1329
sub exptidx($)          { return L__reservation($_[0], 'exptidx'); }
1330
sub genisliver_idx($)   { return L__reservation($_[0], 'genisliver_idx'); }
1331
sub external_resource_index($) {
1332
    return L__reservation($_[0], 'external_resource_index'); }
1333
sub external_resource_id($) {
1334
    return L__reservation($_[0], 'external_resource_id'); }
1335 1336
sub external_resource_key($) {
    return L__reservation($_[0], 'external_resource_key'); }
1337
sub inner_elab_role($) {
1338
    return L__reservation($_[0], 'inner_elab_role'); }
1339 1340
sub inner_elab_boot($) {
    return L__reservation($_[0], 'inner_elab_boot'); }
1341 1342 1343 1344 1345 1346 1347
sub OnSharedNode($) {
    my ($self) = @_;
    my $sharing_mode = $self->sharing_mode();
    return 1
	if (defined($sharing_mode) && $sharing_mode eq "using_shared_local");
    return 0;
}
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
#
# This function takes the user-provided values for root key distribution
# from virt_nodes and adjusts them according to system restrictions, putting
# the result into the reserved table. The Get/Set accessor functions below
# use the values from reserved.
#
# The current restrictions are that we do *not* distribute a root pubkey
# to tainted nodes (as it opens a path to root on a node where no one should
# be root) or any keys to firewall nodes, virtnode hosts, delay nodes,
# subbosses, storagehosts, etc. which are not really part of the user
# topology.
#
sub InitKeyDist($;$)
{
    my ($self,$experiment) = @_;
    my ($priv,$pub);

    return -1
	if (!ref($self) || !$self->IsReserved());

    if (!$experiment) {
	$experiment = $self->Reservation();
	return -1
	    if (!$experiment);
    }
    
    # XXX only PC class nodes for now, since we have to ssh to it
1376
    if ($self->class ne "pc" && $self->class ne "pcvm") {
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 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 1457 1458 1459 1460 1461 1462 1463
	$priv = $pub = 0;
	goto done;
    }

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

    # Get user-supplied values from virt_nodes
    my $result =
	DBQueryWarn("select v.rootkey_private,v.rootkey_public ".
		    " from virt_nodes as v, reserved as r ".
		    " where v.exptidx=r.exptidx and v.vname=r.vname ".
		    "  and r.node_id='$node_id'");

    if ($result && $result->numrows > 0) {
	($priv, $pub) = $result->fetchrow_array();
	my $fwnode;
	
	# tainted node: no pub key
	if ($self->IsTainted()) {
	    $pub = 0;
	}

	# special hosts: no keys at all
	elsif ($self->erole() ne TBDB_RSRVROLE_NODE()) {
	    $priv = $pub = 0;
	}

	# firewall node for an experiment: no keys at all
	elsif ($experiment->IsFirewalled(\$fwnode) && $fwnode eq $node_id) {
	    $priv = $pub = 0;
	}
    }

  done:
    return $self->SetKeyDist($priv, $pub);
}

sub GetKeyDist($$$)
{
    my ($self,$privref,$pubref) = @_;
    
    return -1
	if (!ref($self));
    return -1
	if (! $self->IsReserved());

    if ($privref) {
	$$privref = ($self->{"RSRV"}->{'rootkey_private'} ? 1 : 0);
    }
    if ($pubref) {
	$$pubref = ($self->{"RSRV"}->{'rootkey_public'} ? 1 : 0);
    }

    return 0;
}

sub SetKeyDist($$$)
{
    my ($self,$privval,$pubval) = @_;
    
    return -1
	if (!ref($self));
    return -1
	if (! $self->IsReserved());

    my $clause = "";
    if (defined($privval)) {
	$privval = 1
	    if ($privval != 0);
	$clause = "rootkey_private=$privval";
    }
    if (defined($pubval)) {
	$pubval = 1
	    if ($pubval != 0);
	$clause .= ","
	    if ($clause);
	$clause .= "rootkey_public=$pubval";
    }
    if ($clause) {
	my $node_id = $self->node_id();
	DBQueryWarn("update reserved set $clause where node_id='$node_id'")
	    or return -1;
	$self->FlushReserved();
    }
    return 0;
}

1464
#
1465
# Load all attributes from the node_attributes table, 
1466
#
1467
sub LoadNodeAttributes($)
1468
{
1469
    my ($self) = @_;
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    
    return -1
	if (!ref($self));

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

    if (!defined($self->{"ATTRS"})) {
	my $query_result =
	    DBQueryWarn("select * from node_attributes ".
			"where node_id='$node_id'");

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

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

	    $self->{"ATTRS"}->{$key} = $row;
	}
    }
1491 1492 1493 1494

    return 0;
}

1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
# Iterate through rows adding node attributes. Each row is a hashref.
sub PreloadNodeAttributes($$)
{
    my ($self, $rows) = @_;
    $self->{"ATTRS"} = {};
    foreach my $row (@{ $rows }) {
	my $key = $row->{'attrkey'};
	$self->{"ATTRS"}->{$key} = $row;
    }
}

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
#
# Lookup a specific attribute in the node_attributes table, 
#
sub NodeAttribute($$$;$)
{
    my ($self, $attrkey, $pattrvalue, $pattrtype) = @_;
    
    return -1
	if (!ref($self));

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

    if (!defined($self->{"ATTRS"})) {
	if ($self->LoadNodeAttributes()) {
	    return -1;
	}
    }
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    
    if (!exists($self->{"ATTRS"}->{$attrkey})) {
	$$pattrvalue = undef;
	return 0;
    }
    my $ref = $self->{"ATTRS"}->{$attrkey};

    $$pattrvalue = $ref->{'attrvalue'};
    $$pattrtype  = $ref->{'attrtype'}
        if (defined($pattrtype));

    return 0;
}

1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
#
# Return a hash of the node attributes for this node.
#
sub GetNodeAttributes($)
{
    my ($self) = @_;
    
    return undef
	if (!ref($self));

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

    if (!defined($self->{"ATTRS"})) {
	if ($self->LoadNodeAttributes()) {
	    return undef;
	}
    }

    return $self->{"ATTRS"};
}

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
#
# Set an attribute for a node, overwriting the same attribute if it
# already exists.
#
sub SetNodeAttribute($$$) {
    my ($self, $attrkey, $attrval) = @_;
    my $node_id = $self->node_id();

    return -1
	if (!$attrkey || !$attrval);

    $attrkey = DBQuoteSpecial($attrkey);
    $attrval = DBQuoteSpecial($attrval);

    return -1
	if (!DBQueryWarn("replace into node_attributes set".
			 "  node_id='$node_id',".
			 "  attrkey=$attrkey,".
			 "  attrvalue=$attrval"));

    if (!defined($self->{"ATTRS"})) {
	if ($self->LoadNodeAttributes()) {
	    return -1;
	}
    }
    $self->{"ATTRS"}->{$attrkey} = $attrval;

    return 0;
}

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
#
# Return a hash of the node features for this node.
#
sub GetNodeFeatures($)
{
    my ($self) = @_;
    
    return undef
	if (!ref($self));

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

    if (!defined($self->{"FEATURES"})) {
	my $query_result =
	    DBQueryWarn("select * from node_features ".
			"where node_id='$node_id'");

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

       	$self->{"FEATURES"} = {};
	while (my $row = $query_result->fetchrow_hashref()) {
	    my $feature = $row->{'feature'};
	    my $weight  = $row->{'weight'};

	    $self->{"FEATURES"}->{$feature} = $weight;
	}
    }
    return $self->{"FEATURES"};
}

1619 1620 1621 1622 1623
#
# Return type info. We cache this in the instance since node_type stuff
# does not change much.
#
sub NodeTypeInfo($)
1624
{
1625
    my ($self) = @_;
1626 1627
    require NodeType;
    
1628
    return undef
1629
	if (! ref($self));
1630

1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
    return $self->{"TYPEINFO"}
        if (defined($self->{"TYPEINFO"}));

    my $type = $self->type();
    my $nodetype = NodeType->Lookup($type);
    
    $self->{"TYPEINFO"} = $nodetype
	if (defined($nodetype));
    
    return $nodetype;
1641 1642
}

1643 1644 1645 1646 1647 1648 1649 1650
sub SetNodeTypeInfo($$)
{
    my ($self, $nodetype) = @_;
    if ($self->type() eq $nodetype->type()) {
	$self->{"TYPEINFO"} = $nodetype;
    }
}

1651 1652 1653 1654
#
# Lookup a specific attribute in the nodetype info. 
#
sub NodeTypeAttribute($$$;$)
1655
{
1656 1657 1658 1659
    my ($self, $attrkey, $pattrvalue, $pattrtype) = @_;
    
    return -1
	if (!ref($self));
1660

1661
    my $typeinfo = $self->NodeTypeInfo();
1662

1663 1664
    return -1
	if (!defined($typeinfo));
1665

1666
    return $typeinfo->GetAttribute($attrkey, $pattrvalue, $pattrtype);
1667 1668
}

1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
#
# Returns a hash of node type attributes in the nodetype info. 
#
sub GetNodeTypeAttributes($)
{
    my ($self) = @_;
    
    return undef
	if (!ref($self));

    my $typeinfo = $self->NodeTypeInfo();

    return undef
	if (!defined($typeinfo));

    return $typeinfo->GetAttributes();
}

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
#
# Shortcuts to "common" type information.
# Later these might be overriden by node attributes.
#
sub class($)          { return NodeTypeInfo($_[0])->class(); }
sub isvirtnode($)     { return NodeTypeInfo($_[0])->isvirtnode(); }
sub isjailed($)       { return NodeTypeInfo($_[0])->isjailed(); }
sub isdynamic($)      { return NodeTypeInfo($_[0])->isdynamic(); }
sub isremotenode($)   { return NodeTypeInfo($_[0])->isremotenode(); }
sub issubnode($)      { return NodeTypeInfo($_[0])->issubnode(); }
sub isplabdslice($)   { return NodeTypeInfo($_[0])->isplabdslice(); }
sub isplabphysnode($) { return NodeTypeInfo($_[0])->isplabphysnode(); }
sub issimnode($)      { return NodeTypeInfo($_[0])->issimnode(); }
1700
sub isgeninode($)     { return NodeTypeInfo($_[0])->isgeninode(); }
1701
sub isfednode($)      { return NodeTypeInfo($_[0])->isfednode(); }
1702
sub isdedicatedremote($) { return NodeTypeInfo($_[0])->isdedicatedremote(); }
1703
sub isswitch($)       { return NodeTypeInfo($_[0])->isswitch(); }
1704

1705
#
1706 1707 1708
# Later has arrived...
# Look for node_attributes settings first and if none, fall back on
# node_type_attributes info.
1709 1710
#
sub default_osid($;$) {
1711 1712 1713
    my ($self,$stuff) = @_;
    my $val = undef;

1714
    if (NodeAttribute($self, "default_osid", \$val) == 0 && defined($val)) {
1715 1716 1717
	return $val;
    }
    return NodeTypeInfo($self)->default_osid($stuff);
1718
}
1719

1720 1721 1722
sub adminmfs_osid($;$) {
    my ($self,$stuff) = @_;
    my $val = undef;
1723
    require OSImage;
1724 1725 1726 1727 1728 1729 1730 1731 1732

    if (NodeAttribute($self, "adminmfs_osid", \$val) == 0 &&
	defined($val)) {
	return $val;
    }
    if (NodeTypeAttribute($self, "adminmfs_osid", \$val) == 0 &&
	defined($val)) {
	return $val;
    }
1733
    return OSImage->Lookup(TBOPSPID(), TB_OSID_FREEBSD_MFS())->osid();
1734 1735 1736 1737 1738
}

sub diskloadmfs_osid($;$) {
    my ($self,$stuff) = @_;
    my $val = undef;
1739
    require OSImage;
1740 1741 1742 1743 1744 1745 1746 1747 1748

    if (NodeAttribute($self, "diskloadmfs_osid", \$val) == 0 &&
	defined($val)) {
	return $val;
    }
    if (NodeTypeAttribute($self, "diskloadmfs_osid", \$val) == 0 &&
	defined($val)) {
	return $val;
    }
1749
    return OSImage->Lookup(TBOPSPID(), TB_OSID_FRISBEE_MFS())->osid();
1750 1751
}

1752
sub default_imageid($;$) {
1753 1754 1755
    my ($self,$stuff) = @_;
    my $val = undef;

1756
    if (NodeAttribute($self, "default_imageid", \$val) == 0 && defined($val)) {
1757 1758 1759
	return $val;
    }
    return NodeTypeInfo($self)->default_imageid($stuff);
1760
}
1761

1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
sub default_pxeboot($) {
    my ($self) = @_;
    my $val = undef;

    if (NodeAttribute($self, "pxe_boot_path", \$val) == 0 && defined($val)) {
	return $val;
    }

    return NodeTypeAttribute($self, "pxe_boot_path", undef);
}

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
sub boot_method($) {
    my ($self) = @_;
    my $val = undef;

    if (NodeAttribute($self, "boot_method", \$val) == 0 && defined($val)) {
	return $val;
    }
    $val = NodeTypeAttribute($self, "boot_method", undef);

    # XXX need a mechanism for setting default values for attributes
    $val = "pxeboot"
	if (!$val);

    return $val;
}

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
sub disksize($;$) {
    my ($self,$stuff) = @_;
    my $val = undef;

    if (NodeAttribute($self, "disksize", \$val) == 0 && defined($val)) {
	return $val;
    }
    return NodeTypeInfo($self)->disksize($stuff);
}

sub disktype($;$) {
    my ($self,$stuff) = @_;
    my $val = undef;

    if (NodeAttribute($self, "disktype", \$val) == 0 && defined($val)) {
	return $val;
    }
    return NodeTypeInfo($self)->disktype($stuff);
}

sub bootdisk_unit($;$) {
    my ($self,$stuff) = @_;
    my $val = undef;

    if (NodeAttribute($self, "bootdisk_unit", \$val) == 0 && defined($val)) {
	return $val;
    }
    return NodeTypeInfo($self)->bootdisk_unit($stuff);
}

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
sub cyclewhenoff($;$) {
    my ($self,$stuff) = @_;
    my $val = undef;

    if (NodeAttribute($self, "cyclewhenoff", \$val) == 0 && defined($val)) {
	return $val;
    }
    return NodeTypeInfo($self)->cyclewhenoff($stuff);
}

1829 1830 1831 1832 1833 1834 1835 1836
sub root_password($) {
    my ($self) = @_;
    my $val = undef;

    NodeAttribute($self, "root_password", \$val);
    return $val;
}

1837 1838 1839 1840
#
# And these are the less common attributes, but still common enough to
# warrant shortcuts.
#
1841 1842 1843 1844 1845 1846
sub delay_osid($;$) {
    return NodeTypeInfo($_[0])->delay_osid($_[1]);
}
sub jail_osid($;$) {
    return NodeTypeInfo($_[0])->jail_osid($_[1]);
}
1847 1848 1849 1850 1851 1852 1853 1854
sub imageable($;$) {
    return NodeTypeInfo($_[0])->imageable($_[1]);
}
sub control_iface($;$) {
    return NodeTypeInfo($_[0])->control_iface($_[1]);
}
sub rebootable($;$) {
    return NodeTypeInfo($_[0])->rebootable($_[1]);
1855
}
1856 1857 1858
sub isfakenode($;$) {
    return NodeTypeInfo($_[0])->isfakenode($_[1]);
}
1859 1860 1861
sub bios_waittime($;$) {
    return NodeTypeInfo($_[0])->bios_waittime($_[1]);
}
1862 1863 1864
sub memory($;$) {
    return NodeTypeInfo($_[0])->memory($_[1]);
}
1865

1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

    my $nodeid = $self->node_id();
Leigh Stoller's avatar
Leigh Stoller committed
1878
    my @sets   = ();
1879

Leigh Stoller's avatar
Leigh Stoller committed
1880 1881 1882 1883
    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};

	# Treat NULL special.
1884 1885
	push (@sets, "${key}=" . ($val eq "NULL" ?
				  "NULL" : DBQuoteSpecial($val)));
Leigh Stoller's avatar
Leigh Stoller committed
1886
    }
1887

Leigh Stoller's avatar
Leigh Stoller committed
1888 1889
    my $query = "update nodes set " . join(",", @sets) .
	" where node_id='$nodeid'";
1890 1891 1892 1893 1894 1895 1896

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

    return Refresh($self);
}

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
#
# Insert a Log entry for a node.
#
sub InsertNodeLogEntry($$$$)
{
    my ($self, $user, $type, $message) = @_;

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

    return -1
	if (! grep {$_ eq $type} TB_NODELOGTYPES());

    # XXX Eventually this should change, but it uses non-existent uids!
    my $dbid    = (defined($user) ? $user->uid_idx() : 0);
    my $dbuid   = (defined($user) ? $user->uid()     : "root");
    my $node_id = $self->node_id();
    $message    = DBQuoteSpecial($message);

    return -1
	if (! DBQueryWarn("insert into nodelog values ".
			  "('$node_id', NULL, '$type', '$dbuid', '$dbid', ".
			  " $message, now())"));
    return 0;
}

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
#
# Clear a bunch of stuff from the nodes tale entry so boot is clean.
#
sub ClearBootAttributes($)
{
    my ($self) = @_;
    my $node_id = (ref($self) ? $self->node_id() : $self);
    my $allocFreeState = TBDB_ALLOCSTATE_FREE_DIRTY();

    DBQueryWarn("update nodes set startupcmd='',rpms='',deltas='', ".
		"tarballs='',failureaction='fatal', routertype='none', ".
		"def_boot_cmd_line='',next_boot_cmd_line='', ".
		"temp_boot_osid=NULL,next_boot_osid=NULL, ".
1937
		"temp_boot_osid_vers=0,next_boot_osid_vers=0, ".
1938 1939 1940
		"update_accounts=0,ipport_next=ipport_low,rtabid=0, ".
		"sfshostid=NULL,allocstate='$allocFreeState',boot_errno=0, ".
		"destination_x=NULL,destination_y=NULL, ".
1941
		"destination_orientation=NULL,reserved_memory=0,".
1942
		"nonfsmounts=0,nfsmounts=NULL ".
1943 1944 1945
		"where node_id='$node_id'")
	or return -1;

1946 1947 1948
    my $node = (ref($self) ? $self : Node->Lookup($node_id));
    if ($node->boot_method() eq "pxelinux") {
	TBPxelinuxConfig($node);
1949 1950
    }

1951 1952 1953
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
#
# Clear the experimental interfaces for a node.
#
sub ClearInterfaces($)
{
    my ($self) = @_;

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

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

    DBQueryWarn("update interfaces set IP='',IPaliases=NULL,mask=NULL,".
1968
		"       rtabid='0',vnode_id=NULL,current_speed='0',trunk='0' ".
Leigh Stoller's avatar
Leigh Stoller committed
1969 1970 1971 1972
		"where node_id='$node_id' and ".
		"  role='" . TBDB_IFACEROLE_EXPERIMENT() . "'")
	or return -1;