Node.pm.in 71.4 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2005-2011 University of Utah and the Flux Group.
5 6 7
# All rights reserved.
#
package Node;
8 9
use strict;
use Exporter;
10 11 12
use SelfLoader ();
use vars qw(@ISA @EXPORT $AUTOLOAD @EXPORT_OK);
@ISA = qw(Exporter SelfLoader);
13
@EXPORT = qw();
14

Leigh B. Stoller's avatar
Leigh B. Stoller committed
15
# Configure variables
16
use vars qw($TB $BOSSNODE $WOL $OSSELECT $ISUTAH $CONTROL_NETMASK $TBOPS);
17 18
$TB	     = "@prefix@";
$BOSSNODE    = "@BOSSNODE@";
19
$TBOPS       = "@TBOPSEMAIL@";
20 21
$WOL         = "$TB/sbin/whol";
$OSSELECT    = "$TB/bin/os_select";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
22
# XXX stinky hack detection
23
$ISUTAH	     = @TBMAINSITE@;
24
# Need this for jail ip assignment.
25
$CONTROL_NETMASK = "@CONTROL_NETMASK@";
26

27
use libdb;
28
use libtestbed;
29
use event;
30
use English;
31
use Socket;
32 33
use Data::Dumper;
use overload ('""' => 'Stringify');
34 35

use vars qw($NODEROLE_TESTNODE $MFS_INITIAL $STATE_INITIAL
36
	    %nodes @cleantables %carped);
37

38 39 40 41 42 43
# Exported defs
$NODEROLE_TESTNODE	= 'testnode';

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

44
# Cache of instances to avoid regenerating them.
45
%nodes = ();
46

47 48 49 50 51 52 53 54 55 56 57 58
# Sorry, one carp per customer...
%carped = ();

#
# XXX debugging
# Find out where nulls at end of strings are coming from
#
sub checknodeid($$)
{
    my ($nid,$msg) = @_;

    if ($nid =~ /^(.*)\x0/) {
59
	my $onid = $nid;
60 61 62 63 64
	$nid = $1;
	if (!exists($carped{$nid}) && open(MAIL, "| /usr/sbin/sendmail -t")) {
	    $carped{$nid} = 1;
	    require Carp;
	    print MAIL "To: $TBOPS\n";
65
	    print MAIL "Subject: NUL in node_id '$nid' ('$onid')\n";
66 67 68 69 70 71 72 73 74 75
	    print MAIL "$msg\n";
	    print MAIL "\n";
	    print MAIL Carp::longmess();
	    print MAIL "\n";
	    close(MAIL);
	}
    }
    return $nid;
}

76 77 78 79 80 81
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
82
	if (0);
83 84
    return system($command);
}
85

86
# To avoid writing out all the methods.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
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");


127
#
128
# Lookup a (physical) node and create a class instance to return.
129
#
130 131
sub Lookup($$)
{
132 133 134
    my ($class, $token) = @_;
    my $nodeid;

135
    if ($token =~ /^\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12}$/) {
136 137 138 139 140 141 142 143 144 145 146 147 148 149
	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;
    }
150

151 152 153
    # XXX debug
    $nodeid = checknodeid($nodeid, "Argument");

154
    # Look in cache first
155 156 157 158 159 160 161 162
    if (exists($nodes{$nodeid})) {

	# XXX debug
	my $row = $nodes{$nodeid}->{"DBROW"};
	$row->{'node_id'} = checknodeid($row->{'node_id'}, "Cache");

	return $nodes{$nodeid};
    }
163 164

    my $query_result =
165 166
	DBQueryWarn("select * from nodes as n ".
		    "where n.node_id='$nodeid'");
167

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

171 172 173
    #
    # Make a copy of the array. Still fighting memory corruption error.
    #
174
    my $hash_orig = $query_result->fetchrow_hashref();
175 176 177 178 179 180
    my $hash_copy = {};
    foreach my $key (keys(%{ $hash_orig })) {
	my $val = $hash_orig->{$key};
	$hash_copy->{$key} = $val;
    }

181 182 183 184 185 186 187 188 189 190 191
    return LookupRow($class, $hash_copy);
}

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

192
    my $self            = {};
193
    $self->{"DBROW"}    = $hash_copy;
194 195
    $self->{"RSRV"}     = undef;
    $self->{"TYPEINFO"} = undef;
196
    $self->{"ATTRS"}    = undef;
197
    $self->{"IFACES"}   = undef;
198
    $self->{"WAROW"}    = undef;
199 200 201
    $self->{"HASH"}     = {};
    bless($self, $class);

202 203
    # XXX debug
    my $row = $self->{"DBROW"};
204
    my $nodeid = checknodeid($row->{'node_id'}, "From DB");
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    # Add to cache.
    $nodes{$nodeid} = $self;
    return $self;
}

# 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;
    $self->{"IFACES"}   = undef;
    $self->{"HASH"}     = undef;
221
    $self->{"WAROW"}    = undef;
222 223
}

224 225 226 227 228 229
sub node_id($)
{
    my $self = shift;
    return checknodeid($self->{"DBROW"}->{'node_id'}, "node_id method");
}

230 231 232 233 234 235
sub phys_nodeid($)
{
    my $self = shift;
    return $self->{"DBROW"}->{'phys_nodeid'};
}

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
#
# 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;
257
@SELFLOADER_DATA@
258

259 260 261 262 263 264 265 266 267 268 269 270 271
#
# 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;
    $self->{"IFACES"}   = undef;
272
    $self->{"WAROW"}    = undef;
273
    $self->{"HASH"}     = {};
274 275 276
    bless($self, $class);

    # Add to cache.
277 278 279
    $nodes{$nodeid} = $self;
    return $self;
}
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

#
# 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()) {
299
	my $nodeid = checknodeid($row->{'node_id'}, "BulkLookup method I");
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
	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;
317
	$node->{"IFACES"}   = undef;
Mike Hibler's avatar
Mike Hibler committed
318
	$node->{"WAROW"}    = undef;
319
	$node->{"HASH"}     = {};
320 321 322 323 324 325 326 327 328 329 330
	
	$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()) {
331
	my $nodeid = checknodeid($row->{'node_id'}, "BulkLookup method II");
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
	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()) {
348
	my $nodeid = checknodeid($row->{'node_id'}, "BulkLookup method III");
349 350 351 352 353 354 355 356 357 358 359 360
	my $key    = $row->{'attrkey'};
	my $node   = $nodelist{$nodeid};

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

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

362 363 364 365 366
sub Create($$$$)
{
    my ($class, $node_id, $experiment, $argref) = @_;
    my ($control_iface,$virtnode_capacity,$adminmfs,$adminmfs_osid);
    my ($priority, $osid, $opmode, $state);
367 368 369 370 371 372 373 374 375
    require OSinfo;
    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();
376 377 378

    my $type = $argref->{'type'};
    my $role = $argref->{'role'};
379 380 381 382 383 384 385 386 387 388 389 390 391
    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);
392 393 394 395 396 397 398

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

    my $isremote = $typeinfo->isremotenode();

399 400 401 402 403
    if ($role eq "testnode") {
	if ($typeinfo->virtnode_capacity(\$virtnode_capacity)) {
	    print STDERR "*** No virtnode_capacity for $type! Using zero.\n";
	    $virtnode_capacity = 0;
	}
404 405 406 407 408 409
	if ($typeinfo->isswitch()) {
	    $osid   = "NULL";
	    $opmode = "ALWAYSUP";
	}
	elsif ($isremote) {
	    $osid   = "NULL";
410 411 412 413 414 415 416 417 418 419 420 421 422 423
	    $opmode = "";

	    if (defined($typeinfo->default_osid())) {
		$osid = $typeinfo->default_osid();
		
		my $osinfo = OSinfo->Lookup($osid);
		if (!defined($osinfo)) {
		    print STDERR
			"*** Could not find OSinfo object for $osid!\n";
		    return undef;
		}
		$osid   = $osinfo->osid();
		$opmode = $osinfo->op_mode();
	    }
424 425
	}
	else {
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
	    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)) {
		$adminmfs = OSinfo->Lookup($adminmfs_osid);
	    }
	    else {
		$adminmfs = OSinfo->Lookup(TBOPSPID(), $MFS_INITIAL);
	    }
	    if (!defined($adminmfs)) {
		print STDERR
		    "*** Could not find OSinfo object for adminmfs!\n";
		return undef;
	    }
	    $osid   = $adminmfs->osid();
	    $opmode = $adminmfs->op_mode();
444
	}
445 446
    }
    else {
447
	$osid   = "NULL";
448
	$opmode = "";
449 450
    }
    $state  = $STATE_INITIAL;
451 452 453 454

    #
    # Lock the tables to prevent concurrent creation
    #
455 456 457 458 459
    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;
460

461 462 463 464 465 466 467 468 469
    #
    # Make up a priority (just used for sorting)
    #
    if ($node_id =~ /^(.*\D)(\d+)$/) {
	$priority = $2;
    }
    else {
	$priority = 1;
    }
470

471 472 473 474 475 476 477 478 479 480 481
    #
    # 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);
    }

482 483 484 485 486
    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', " .
487
		     "  def_boot_osid=$osid, " .
488 489 490 491 492 493 494 495 496 497
		     "  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'};
498 499 500 501 502 503 504 505 506 507

	# 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 ".
508 509 510 511 512 513 514 515 516
			 " (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;
	}
    }
517

518 519 520 521
    if ($role eq "testnode") {
	DBQueryWarn("insert into node_hostkeys (node_id) ".
		    "values ('$node_id')")
	    or goto bad;
522
	
523 524 525 526
	DBQueryWarn("insert into node_status ".
		    "(node_id, status, status_timestamp) ".
		    "values ('$node_id', 'down', now()) ")
	    or goto bad;
527
    
528 529 530
	DBQueryWarn("insert into node_activity ".
		    "(node_id) values ('$node_id')")
	    or goto bad;
531
	
532 533 534 535
	DBQueryWarn("insert into node_utilization ".
		    "(node_id) values ('$node_id')")
	    or goto bad;
    }
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556

    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) {
557 558 559 560
	my $vtype;
	
	if (exists($argref->{'vtype'})) {
	    $vtype = $argref->{'vtype'};
561
	}
562 563 564 565 566 567 568
	else  {
	    $vtype = $type;
	    if (!($vtype =~ s/pc/pcvm/)) {
		$vtype = "$vtype-vm";
	    }
	}
	
569 570 571 572
	DBQueryWarn("insert into node_auxtypes set node_id='$node_id', " .
		    "type='$vtype', count=$virtnode_capacity")
	    or goto bad;
    }
573
    DBQueryWarn("unlock tables");
574 575 576 577 578 579
    return Node->Lookup($node_id);
    
  bad:
    foreach my $table (@cleantables) {
	DBQueryWarn("delete from $table where node_id='$node_id'");
    }
580
    DBQueryWarn("unlock tables");
581 582 583
    return undef;
}

584 585 586 587 588 589 590 591 592 593 594 595 596 597
#
# 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;
}

598
#
599
# Refresh a class instance by reloading from the DB.
600
#
601
sub Refresh($)
602
{
603 604 605 606
    my ($self) = @_;

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

608
    my $nodeid = $self->node_id();
609

610 611 612 613 614 615 616 617
    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();
618 619 620 621 622

    # XXX debug
    my $row = $nodes{$nodeid}->{"DBROW"};
    $row->{'node_id'} = checknodeid($row->{'node_id'}, "Refresh");

623 624 625
    # Force reload
    $self->{"RSRV"}     = undef;
    $self->{"TYPEINFO"} = undef;
626
    $self->{"ATTRS"}    = undef;
627
    $self->{"IFACES"}   = undef;
628
    $self->{"WAROW"}    = undef;
629
    return 0;
630 631
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

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

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
#
# 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};
}

675 676 677 678 679 680 681 682 683
#
# 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. 
684
    return 0
685 686
	if (! ref($self));

687 688
    if ($access_type < TB_NODEACCESS_MIN ||
	$access_type > TB_NODEACCESS_MAX) {
689
	print STDERR "*** Invalid access type: $access_type!\n";
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
	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));
709

710 711 712 713 714 715 716 717 718 719 720 721 722 723
    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);
724 725
}

726
#
727 728 729
# Lazily load the reservation info.
#
sub IsReserved($)
730
{
731
    my ($self) = @_;
732

Leigh B. Stoller's avatar
Leigh B. Stoller committed
733
    return 0
734
	if (! ref($self));
735

736 737 738 739 740 741
    if (! defined($self->{"RSRV"})) {
	my $nodeid = $self->node_id();
	
	my $query_result =
	    DBQueryWarn("select * from reserved " .
			"where node_id='$nodeid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
742
	return 0
743 744 745 746 747 748 749 750
	    if (!$query_result);
	return 0
	    if (!$query_result->numrows);

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

753 754 755 756 757 758 759 760 761 762
#
# 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;
    }
}
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

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

803 804 805 806 807 808 809 810 811 812 813
#
# Flush the reserve info so it reloads.
#
sub FlushReserved($)
{
    my ($self) = @_;

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

814 815 816 817 818 819 820 821 822 823 824 825 826
#
# Is node up.
#
sub IsUp($)
{
    my ($self) = @_;

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

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
#
# 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.
847 848 849
    # 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 B. Stoller's avatar
Leigh B. Stoller committed
850 851
    #
    my $query_result =
852
	DBQueryFatal("select distinct p.type, p.pid_idx from nodes as n ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
853 854 855 856 857 858 859 860 861
		     "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;
    }
862
    my ($ptype,$pid_idx) = $query_result->fetchrow_array();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
863 864

    # No rows, or a pid match.
865
    if (!defined($ptype) || $pid_idx eq $pid->pid_idx()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
866 867 868 869
	return 1;
    }

    # Okay, must be rows in the permissions table. Check each pid for a match.
870 871
    while (my ($ptype,$pid_idx) = $query_result->fetchrow_array()) {
	if ($pid_idx eq $pid->pid_idx()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
872 873 874 875 876 877
	    return 1;
	}
    }
    return 0;
}

878 879 880 881 882 883 884 885
# Naming confusion.
sub AllocCheck($$)
{
    my ($self, $pid) = @_;

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
886 887 888 889 890 891 892 893 894 895 896 897
#
# 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();
898

Leigh B. Stoller's avatar
Leigh B. Stoller committed
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
    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;
}

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
#
# We do this cause we always want to go to the DB.
#
sub GetEventState($$)
{
    my ($self, $pstate) = @_;
    my $node_id = $self->node_id();

    my $query_result =
	DBQueryWarn("select eventstate from nodes where node_id='$node_id'");
    return -1
	if (!$query_result || !$query_result->numrows);

    my ($state) = $query_result->fetchrow_array();
    $state = TBDB_NODESTATE_UNKNOWN
	if (!defined($state));

944
    $self->{'DBROW'}->{'eventstate'} = $state
945 946 947 948 949
	if (defined($self->{'DBROW'}));
    $$pstate = $state;
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
#
# 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();
}

965 966 967 968 969 970 971
#
# Get the experiment this node is reserved too, or null.
#
sub Reservation($)
{
    my ($self) = @_;

972
    return undef
973 974
	if (! ref($self));

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

978
    return LocalExpLookup($self->{"RSRV"}->{'exptidx'});
Leigh B. Stoller's avatar
Leigh B. Stoller committed
979 980 981 982 983 984 985 986 987 988 989 990 991 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
}

#
# 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();

1019
    return LocalExpLookup($pid, $eid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
}

#
# 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.
1041
    if ($newpid eq OLDRESERVED_PID() && $neweid eq OLDRESERVED_EID()) {	
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
        #
	# 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'};
    }
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    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;
    }
1070 1071 1072

    # Force this to reload.
    $self->{"RSRV"} = undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    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();
1090 1091 1092
    my @sets    = ();
    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1093

1094 1095
	push(@sets, "$key=" . ("$val" eq "NULL" ? "NULL" : "'$val'"));
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1096

1097
    my $query = "update reserved set ".	join(",", @sets);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1098 1099 1100 1101 1102
    $query .= " where node_id='$node_id'";

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

1103 1104 1105 1106 1107 1108
    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};
	
	$self->{'DBROW'}->{$key} = $val;
    }
    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
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
}

#
# 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();
    
1135
    return LocalExpLookup($pid, $eid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
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
}

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.
#
1165
sub TipServer($$;$$$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1166
{
1167
    my ($self, $pserver, $ptipname, $pportnum, $pkeydata) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

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

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

    my $nodeid = $self->node_id();
	
    my $query_result =
1179
	DBQueryWarn("select server,tipname,portnum,keydata from tiplines " .
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1180 1181 1182 1183 1184 1185 1186
		    "where node_id='$nodeid'");
    return -1
	if (!$query_result);
    
    return 0
	if (!$query_result->numrows);

1187
    my ($server,$tipname,$portnum,$keydata) = $query_result->fetchrow_array();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1188 1189 1190
    $$pserver  = $server;
    $$ptipname = $tipname
	if (defined($ptipname));
1191 1192 1193 1194
    $$pkeydata = $keydata
	if (defined($pkeydata));
    $$pportnum = $portnum
	if (defined($pportnum));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1195 1196

    return 0;
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
}

#
# 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 B. Stoller's avatar
Leigh B. Stoller committed
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
#
# Return a list of virtual nodes on the given physical node.
#
sub VirtualNodes($$)
{
    my ($self, $plist) = @_;

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

1225 1226
    @$plist         = ();

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1227
    my $reservation = $self->Reservation();
1228 1229 1230
    return 0
	if (!defined($reservation));

Leigh B. Stoller's avatar
Leigh B. Stoller committed
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
    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;
}

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
#
# 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 = 
1272 1273 1274 1275 1276
	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");
1277 1278 1279 1280 1281 1282
    return -1
	if (!$query_result);
    
    return $query_result->numrows;
}

1283 1284 1285
#
# Access methods for the reservation.
#
1286
sub L__reservation($$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1287
{
1288
    my ($self, $slotname) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1289 1290 1291 1292 1293

    return undef
	if (! ref($self));
    return undef
	if (! $self->IsReserved());
1294
    return undef
1295
	if (! exists($self->{"RSRV"}->{$slotname}));
1296

1297
    return $self->{"RSRV"}->{$slotname};
1298
}
1299 1300 1301
sub vname($)		{ return L__reservation($_[0], 'vname'); }
sub sharing_mode($)	{ return L__reservation($_[0], 'sharing_mode'); }
sub erole($)		{ return L__reservation($_[0], 'erole'); }
1302 1303
sub eid($)              { return L__reservation($_[0], 'eid'); }
sub pid($)              { return L__reservation($_[0], 'pid'); }
1304
sub external_resource_index($) {
1305
    return L__reservation($_[0], 'external_resource_index'); }
1306
sub external_resource_id($) {
1307
    return L__reservation($_[0], 'external_resource_id'); }
1308 1309
sub external_resource_key($) {
    return L__reservation($_[0], 'external_resource_key'); }
1310
sub inner_elab_role($) {
1311
    return L__reservation($_[0], 'inner_elab_role'); }
1312

1313
#
1314
# Load all attributes from the node_attributes table, 
1315
#
1316
sub LoadNodeAttributes($)
1317
{
1318
    my ($self) = @_;
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    
    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;
	}
    }
1340 1341 1342 1343

    return 0;
}

1344 1345 1346 1347 1348 1349 1350 1351 1352