Node.pm.in 31.9 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2005-2007 University of Utah and the Flux Group.
5 6 7
# All rights reserved.
#
package Node;
8 9 10

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

13
@ISA    = "Exporter";
14
@EXPORT = qw();
15

Leigh B. Stoller's avatar
Leigh B. Stoller committed
16 17 18 19 20 21 22
# Configure variables
my $TB		= "@prefix@";
my $BOSSNODE    = "@BOSSNODE@";
my $EVENTSYS    = @EVENTSYS@;
# XXX stinky hack detection
my $ISUTAH	= @TBMAINSITE@;

23 24 25
# Must come after package declaration!
use lib '@prefix@/lib';
use libdb;
26
use libtestbed;
27 28 29
require NodeType;
require Interface;
require Experiment;
30
require OSinfo;
31 32 33
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');
Leigh B. Stoller's avatar
Leigh B. Stoller committed
34 35 36 37
if ($EVENTSYS) {
    require event;
    import event;
}
38
use vars qw($NODEROLE_TESTNODE @EXPORT_OK);
39

40 41 42 43 44 45 46 47 48 49 50 51 52
# Exported defs
$NODEROLE_TESTNODE	= 'testnode';

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

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

53 54 55 56 57 58 59 60 61 62 63 64 65
# Cache of instances to avoid regenerating them.
my %nodes	= ();
my $debug	= 0;

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

    print STDERR "Running '$command'\n"
	if ($debug);
    return system($command);
}
66 67

#
68
# Lookup a (physical) node and create a class instance to return.
69
#
70 71
sub Lookup($$)
{
72 73
    my ($class, $nodeid) = @_;

74 75 76
    # Look in cache first
    return $nodes{$nodeid}
        if (exists($nodes{$nodeid}));
77

78
    return undef
Mike Hibler's avatar
Mike Hibler committed
79
	if (! ($nodeid =~ /^[-\w]+$/));
80

81
    my $query_result =
82 83
	DBQueryWarn("select * from nodes as n ".
		    "where n.node_id='$nodeid'");
84

85 86 87 88 89 90 91 92 93 94
    return undef
	if (!$query_result || !$query_result->numrows);

    my $self            = {};
    $self->{"DBROW"}    = $query_result->fetchrow_hashref();
    $self->{"RSRV"}     = undef;
    $self->{"TYPEINFO"} = undef;
    bless($self, $class);

    # Add to cache.
95 96 97
    $nodes{$nodeid} = $self;
    return $self;
}
98 99 100 101 102 103 104 105
# accessors
sub field($$)  { return ((! ref($_[0])) ? -1 : $_[0]->{'DBROW'}->{$_[1]}); }
sub node_id($)       { return field($_[0], 'node_id'); }
sub type($)          { return field($_[0], 'type'); }
sub eventstate($)    { return field($_[0], 'eventstate'); }
sub jailflag($)      { return field($_[0], 'jailflag'); }
sub phys_nodeid($)   { return field($_[0], 'phys_nodeid'); }
sub def_boot_osid($) { return field($_[0], 'def_boot_osid'); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
106
sub pxe_boot_path($) { return field($_[0], 'pxe_boot_path'); }
107

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
#
# Create a new node.
#
sub Create($$$$)
{
    my ($class, $node_id, $experiment, $argref) = @_;
    my ($control_iface,$virtnode_capacity,$adminmfs,$adminmfs_osid);
    my ($priority, $osid, $opmode, $state);

    my $type = $argref->{'type'};
    my $role = $argref->{'role'};

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

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

    if ($typeinfo->virtnode_capacity(\$virtnode_capacity)) {
	print STDERR "*** No virtnode_capacity for $type! Using zero.\n";
	$virtnode_capacity = 0;
    }
    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();
    $state  = $STATE_INITIAL;
    
    #
    # Make up a priority (just used for sorting)
    #
    if ($node_id =~ /^(.*\D)(\d+)$/) {
	$priority = $2;
    }
    else {
	$priority = 1;
    }
    # The list of table we have to clear if anything goes wrong.
    my @cleantables = ("nodes", "node_hostkeys", "node_status",
		       "node_activity", "node_utilization",
		       "node_auxtypes", "reserved");

    DBQueryWarn("insert into nodes set ".
		"  node_id='$node_id', type='$type', " .
		"  phys_nodeid='$node_id', role='$role', ".
		"  priority=$priority, " .
		"  eventstate='$state', op_mode='$opmode', " .
		"  def_boot_osid='$osid', " .
		"  inception=now(), ".
		"  state_timestamp=unix_timestamp(NOW()), " .
		"  op_mode_timestamp=unix_timestamp(NOW())")
	or goto bad;

    DBQueryWarn("insert into node_hostkeys (node_id) ".
		"values ('$node_id')")
	or goto bad;
	
    DBQueryWarn("insert into node_status ".
		"(node_id, status, status_timestamp) ".
		"values ('$node_id', 'down', now()) ")
	or goto bad;
    
    DBQueryWarn("insert into node_activity ".
		"(node_id) values ('$node_id')")
	or goto bad;
	
    DBQueryWarn("insert into node_utilization ".
		"(node_id) values ('$node_id')")
	or goto bad;

    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) {
	my $vtype = $type;
	if (!($vtype =~ s/pc/pcvm/)) {
	    $vtype = "$vtype-vm";
	}
	my $pcvmtype = ($isremote ? "pcvwa" : "pcvm");

	DBQueryWarn("insert into node_auxtypes set node_id='$node_id', " .
		    "type='$pcvmtype', count=$virtnode_capacity")
	    or goto bad;
	    
	DBQueryWarn("insert into node_auxtypes set node_id='$node_id', " .
		    "type='$vtype', count=$virtnode_capacity")
	    or goto bad;
    }
    return Node->Lookup($node_id);
    
  bad:
    foreach my $table (@cleantables) {
	DBQueryWarn("delete from $table where node_id='$node_id'");
    }
    return undef;
}

234
#
235
# Refresh a class instance by reloading from the DB.
236
#
237
sub Refresh($)
238
{
239 240 241 242
    my ($self) = @_;

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

244
    my $nodeid = $self->node_id();
245

246 247 248 249 250 251 252 253 254 255 256 257
    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;
    return 0;
258 259 260
}

#
261 262 263
# Stringify for output.
#
sub Stringify($)
264
{
265 266 267
    my ($self) = @_;
    
    my $nodeid = $self->node_id();
268

269
    return "[Node: $nodeid]";
270 271
}

272 273 274 275 276 277 278 279 280
#
# 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. 
281
    return 0
282 283
	if (! ref($self));

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    if ($access_type < TB_NODEACCESS_MIN ||
	$access_type > TB_NODEACCESS_MAX) {
	print "*** Invalid access type: $access_type!\n";
	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));
306

307 308 309 310 311 312 313 314 315 316 317 318 319 320
    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);
321 322
}

323
#
324 325 326
# Lazily load the reservation info.
#
sub IsReserved($)
327
{
328
    my ($self) = @_;
329

Leigh B. Stoller's avatar
Leigh B. Stoller committed
330
    return 0
331
	if (! ref($self));
332

333 334 335 336 337 338
    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
339
	return 0
340 341 342 343 344 345 346 347
	    if (!$query_result);
	return 0
	    if (!$query_result->numrows);

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
#
# 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.
    #
    my $query_result =
	DBQueryFatal("select distinct p.* from nodes as n ".
		     "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;
    }
    my ($ptype,$ppid) = $query_result->fetchrow_array();

    # No rows, or a pid match.
    if (!defined($ptype) || $ppid eq $pid) {
	return 1;
    }

    # Okay, must be rows in the permissions table. Check each pid for a match.
    while (my ($ptype,$ppid) = $query_result->fetchrow_array()) {
	if ($ppid eq $pid) {
	    return 1;
	}
    }
    return 0;
}

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

413 414 415 416 417 418 419
#
# Get the experiment this node is reserved too, or null.
#
sub Reservation($)
{
    my ($self) = @_;

420
    return undef
421 422
	if (! ref($self));

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    return Experiment->Lookup($self->{"RSRV"}->{'exptidx'});
}

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

    return Experiment->Lookup($pid, $eid);
}

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

    return -1
	if (! $self->IsReserved());
    
    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.
    if ($newpid eq OLDRESERVED_PID() && $neweid eq OLDRESERVED_EID()) {
        #
	# 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'};
    }
    
    DBQueryWarn("update reserved set " .
		" vname='$node_id', ".
		" exptidx=$newidx, ".
		" pid='$newpid', ".
		" eid='$neweid', ".
		" old_exptidx=$oldidx, ".
		" old_pid='$oldpid', ".
		" old_eid='$oldeid' ".
		"where node_id='$node_id'")
	or return -1;
    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();

    my $query = "update reserved set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where node_id='$node_id'";

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

    return 0;
}

#
# 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();
    
    return Experiment->Lookup($pid, $eid);
}

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.
#
sub TipServer($$;$)
{
    my ($self, $pserver, $ptipname) = @_;

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

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

    my $nodeid = $self->node_id();
	
    my $query_result =
	DBQueryWarn("select server,tipname from tiplines " .
		    "where node_id='$nodeid'");
    return -1
	if (!$query_result);
    
    return 0
	if (!$query_result->numrows);

    my ($server, $tipname) = $query_result->fetchrow_array();
    $$pserver  = $server;
    $$ptipname = $tipname
	if (defined($ptipname));

    return 0;
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
}

#
# 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
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
#
# Return a list of virtual nodes on the given physical node.
#
sub VirtualNodes($$)
{
    my ($self, $plist) = @_;

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

    my $reservation = $self->Reservation();
    my $node_id     = $self->node_id();
    my $exptidx     = $reservation->idx();
    my @result      = ();
    @$plist         = ();

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

684 685 686 687 688 689 690 691 692 693 694 695 696 697
# Need to create a set of access methods for the reservation.
sub vname($)
{
    my ($self) = @_;

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

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

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

698 699 700 701 702
#
# Return type info. We cache this in the instance since node_type stuff
# does not change much.
#
sub NodeTypeInfo($)
703
{
704
    my ($self) = @_;
705 706

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

709 710 711 712 713 714 715 716 717 718
    return $self->{"TYPEINFO"}
        if (defined($self->{"TYPEINFO"}));

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

721 722 723 724
#
# Lookup a specific attribute in the nodetype info. 
#
sub NodeTypeAttribute($$$;$)
725
{
726 727 728 729
    my ($self, $attrkey, $pattrvalue, $pattrtype) = @_;
    
    return -1
	if (!ref($self));
730

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

733 734
    return -1
	if (!defined($typeinfo));
735

736
    return $typeinfo->GetAttribute($attrkey, $pattrvalue, $pattrtype);
737 738
}

739 740 741 742 743 744 745 746 747 748 749 750 751
#
# 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(); }
752

753 754 755 756 757 758 759
#
# And these are the less common attributes, but still common enough to
# warrant shortcuts.
#
sub default_osid($;$) {
    return NodeTypeInfo($_[0])->default_osid($_[1]);
}
760 761 762
sub default_imageid($;$) {
    return NodeTypeInfo($_[0])->default_imageid($_[1]);
}
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
sub imageable($;$) {
    return NodeTypeInfo($_[0])->imageable($_[1]);
}
sub disksize($;$) {
    return NodeTypeInfo($_[0])->disksize($_[1]);
}
sub disktype($;$) {
    return NodeTypeInfo($_[0])->disktype($_[1]);
}
sub bootdisk_unit($;$) {
    return NodeTypeInfo($_[0])->bootdisk_unit($_[1]);
}
sub control_iface($;$) {
    return NodeTypeInfo($_[0])->control_iface($_[1]);
}
sub rebootable($;$) {
    return NodeTypeInfo($_[0])->rebootable($_[1]);
780 781
}

782 783 784 785 786 787 788 789 790 791 792 793
#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

    my $nodeid = $self->node_id();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
794
    my @sets   = ();
795

Leigh B. Stoller's avatar
Leigh B. Stoller committed
796 797 798 799 800 801
    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};

	# Treat NULL special.
	push (@sets, "${key}=" . ($val eq "NULL" ? "NULL" : "'$val'"));
    }
802

Leigh B. Stoller's avatar
Leigh B. Stoller committed
803 804
    my $query = "update nodes set " . join(",", @sets) .
	" where node_id='$nodeid'";
805 806 807 808 809 810 811

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

    return Refresh($self);
}

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
#
# 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;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
#
# Clear the experimental interfaces for a node.
#
#
# Insert a Log entry 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,".
		"       rtabid='0',vnode_id=NULL,current_speed='0' ".
		"where node_id='$node_id' and ".
		"  role='" . TBDB_IFACEROLE_EXPERIMENT() . "'")
	or return -1;

    return 0;
}

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 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 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
#
# Mark a node for an update.
#
sub MarkForUpdate($)
{
    my ($self) = @_;

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

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

    return -1
	if (! DBQueryWarn("update nodes set ".
			  "update_accounts=GREATEST(update_accounts,1) ".
			  "where node_id='$node_id'"));

    return Refresh($self);
}
# Class method!
sub CheckUpdateStatus($$$@)
{
    my ($class, $pdone, $pnotdone, @nodelist) = @_;
    my @done = ();
    my @notdone = ();

    my $where = join(" or ",
		     map("node_id='" . $_->node_id() . "'", @nodelist));

    my $query_result =
	DBQueryWarn("select node_id,update_accounts from nodes ".
		    "where ($where)");

    return -1
	if (! $query_result);

    while (my ($node_id,$update_accounts) = $query_result->fetchrow_array) {
	my $node = Node->Lookup($node_id);
	if (! $update_accounts) {
	    Refresh($node);
	    push(@done, $node);
	}
	else {
	    push(@notdone, $node);
	}
    }
    
    @$pdone = @done;
    @$pnotdone = @notdone;
    return 0;
}

#
# Clear the bootlog.
#
sub ClearBootLog($)
{
    my ($self) = @_;

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

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

    return -1
	if (! DBQueryWarn("delete from node_bootlogs ".
			  "where node_id='$node_id'"));
    return 0;
}

#
# Get the bootlog.
#
sub GetBootLog($$)
{
    my ($self, $pref) = @_;

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

    $$pref = undef;

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

    my $query_result =
	DBQueryWarn("select bootlog from node_bootlogs ".
		    "where node_id='$node_id'");
    return -1
	if (! $query_result);
    return 0
	if (! $query_result->numrows);

    my ($bootlog) = $query_result->fetchrow_array();
    $$pref = $bootlog;
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
#
# Set event state for a node.
#
sub SetEventState($$)
{
    my ($self, $state) = @_;

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

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

    #
    # If using the event system, we send out an event for the state daemon to
    # pick up. Otherwise, we just set the state in the database ourselves
    #
    if ($EVENTSYS) {
	return EventSendFatal(objtype   => TBDB_TBEVENT_NODESTATE,
			      objname   => $node_id,
			      eventtype => $state,
			      host      => $BOSSNODE);
    }
    return $self->Update({"eventstate"      => $state,
			  "state_timestamp" => time()});
}

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 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
#
# Create new vnodes. This routine obviously cannot be called on a specific
# instance since it does not exist! The argument is still a reference; to a
# a hash of options to be used when creating the new node(s). A list of the
# node names is returned.
#
sub CreateVnodes($$)
{
    my ($rptr, $options) = @_;
    my @created   = ();
    my @tocreate  = ();

    if (!defined($options->{'pid'})) {
	print STDERR "*** CreateVnodes: Must supply a pid!\n";
	return -1;
    }
    if (!defined($options->{'eid'})) {
	print STDERR "*** CreateVnodes: Must supply a eid!\n";
	return -1;
    }
    if (!defined($options->{'count'})) {
	print STDERR "*** CreateVnodes: Must supply a count!\n";
	return -1;
    }
    if (!defined($options->{'vtype'})) {
	print STDERR "*** CreateVnodes: Must supply a vtype!\n";
	return -1;
    }
    if (!defined($options->{'nodeid'})) {
	print STDERR "*** CreateVnodes: Must supply a pnode!\n";
	return -1;
    }
    
    my $debug   = defined($options->{'debug'}) && $options->{'debug'};
    my $impotent= defined($options->{'impotent'}) && $options->{'impotent'};
    my $verbose = defined($options->{'verbose'}) && $options->{'verbose'};
    my $pid     = $options->{'pid'};
    my $eid     = $options->{'eid'};
    my $count   = $options->{'count'};
    my $vtype   = $options->{'vtype'};
    my $pnode   = $options->{'nodeid'};

1033 1034 1035 1036 1037 1038
    my $exptidx;
    if (!TBExptIDX($pid, $eid, \$exptidx)) {
	print STDERR "*** CreateVnodes: No such experiment $pid/$eid!\n";
	return -1;
    }

1039 1040 1041
    #
    # Need the vtype node_type info. 
    #
1042 1043
    my $nodetype = NodeType->Lookup($vtype);
    if (! defined($nodetype)) {
1044 1045 1046
	print STDERR "*** CreateVnodes: No such node type '$vtype'\n";
	return -1;
    }
1047
    if (!$nodetype->isdynamic()) {
1048 1049 1050
	print STDERR "*** CreateVnodes: Not a dynamic node type: '$vtype'\n";
	return -1;
    }
1051 1052
    my $isremote = $nodetype->isremotenode();
    my $isjailed = $nodetype->isjailed();
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072

    #
    # Make up a priority (just used for sorting). We need the name prefix
    # as well for consing up the node name.
    #
    my $nodeprefix;
    my $nodenum;
    if ($pnode =~ /^(.*\D)(\d+)$/) {
	$nodeprefix = $1;
	$nodenum    = $2;
    }
    else {
	print STDERR "*** CreateVnodes: Unexpected nodeid '$pnode'\n";
	return -1;
    }

    #
    # Need the opmode, which comes from the OSID, which is in the node_types
    # table. 
    #
1073
    my $osid = $nodetype->default_osid();
1074
    
1075
    my $query_result =
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
	DBQueryWarn("select op_mode from os_info where osid='$osid'");
    return -1
	if (! $query_result);
    
    if (! $query_result->numrows) {
	print STDERR "*** CreateVnodes: No such OSID '$osid'\n";
	return -1;
    }
    my ($opmode) = $query_result->fetchrow_array();

    #
    # Need IP for jailed nodes.
    # 
    my $IPBASE = TBDB_JAILIPBASE();
1090 1091
    my $IPBASE1;
    my $IPBASE2;
1092
    if ($IPBASE =~ /^(\d+).(\d+).(\d+).(\d+)/) {
1093 1094
	$IPBASE1 = $1;
	$IPBASE2 = $2;
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    }
    else {
	print STDERR "*** CreateVnodes: Bad IPBASE '$IPBASE'\n";
	return -1;
    }

    #
    # Assign however many we are told to (typically by assign). Locally
    # this is not a problem since nodes are not shared; assign always
    # does the right thing and we do what it says. In the remote case,
    # nodes are shared and so it is harder to make sure that nodes are not
    # over committed. I am not going to worry about this right now though
    # cause it would be too hard. For RON nodes this is fine; we just
    # tell people to log in and use them. For plab nodes, this is more
    # of a problem, but I am going to ignore that for now too since we do
    # not ever allocate enough to worry; must revisit this at some point.
    # 
    # Look to see what nodes are already allocated on the node, and skip
    # those. Must do this with tables locked, of course.
    #
    DBQueryFatal("lock tables nodes write, reserved write, ".
		 "node_status write, node_hostkeys write");

    if (0 && !$isremote) {
	for (my $i = 1; $i <= $count; $i++) {
	    push(@tocreate, $i);
	}
    }
    else {
	my $n = 1;
	my $i = 0;

	while ($i < $count) {
	    my $vnodeid = $nodeprefix . "vm" . $nodenum . "-" . $n;
	    
	    $query_result =
		DBQueryWarn("select node_id from nodes ".
			     "where node_id='$vnodeid'");
	    goto bad
		if (!$query_result);

	    if (!$query_result->numrows) {
		push(@tocreate, $n);
		$i++;
	    }
	    $n++;
	}
    }

    # See below.
    my $eventstate = TBDB_NODESTATE_SHUTDOWN();
    my $allocstate = TBDB_ALLOCSTATE_FREE_CLEAN();

    #
    # Create a bunch.
    #
    foreach my $i (@tocreate) {
	my $vpriority = 10000000 + ($nodenum * 1000) + $i;
	my $vnodeid   = $nodeprefix . "vm" . $nodenum . "-" . $i;

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
	#
	# Construct the vnode IP.  The general form is:
	#	<IPBASE1>.<IPBASE2>.<pnode>.<vnode>
	# but if <pnode> is greater than 254 we have to increment
	# IPBASE2.
	#
	# XXX at Utah our second big cluster of nodes starts at
	# nodenum=201 and I would like our vnode IPs to align
	# at that boundary, so 254 becomes 200.
	#
	my $nodenumlimit = $ISUTAH ? 200 : 254;
	my $pnet = $IPBASE2;
1167
	my $pnode2 = int($nodenum);
1168 1169 1170 1171 1172 1173
	while ($pnode2 > $nodenumlimit) {
	    $pnet++;
	    $pnode2 -= $nodenumlimit;
	}
	my $jailip = "${IPBASE1}.${pnet}.${pnode2}.${i}";

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
	if ($verbose) {
	    if ($impotent) {
		print "Would allocate $vnodeid on $pnode ($vtype, $osid)\n";
	    }
	    else {
		print "Allocating $vnodeid on $pnode ($vtype, $osid)\n";
	    }
	}

	my $statement =
	         "insert into nodes set ".
		 "       node_id='$vnodeid', " .
		 "       type='$vtype', ".
		 "       phys_nodeid='$pnode', ".
		 "       role='virtnode', " .
		 "       priority='$vpriority', ".
		 "       op_mode='$opmode', " .
		 "       eventstate='$eventstate', " .
		 "       allocstate='$allocstate', ".
		 "       def_boot_osid='$osid', " .
		 "       update_accounts=1, ".
		 "       jailflag=$isjailed ".
1196
		 (($isjailed && !$isremote) ? ",jailip='$jailip'" : "");
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

	print STDERR "$statement\n"
	    if ($debug);

	if (!$impotent && !DBQueryWarn($statement)) {
	    print STDERR "*** CreateVnodes: Could not create nodes entry\n";
	    goto bad;
	}

	#
	# Also reserve the node!
	# 
	$statement =
	         "insert into reserved set ".
		 "       node_id='$vnodeid', " .
1212
		 "       exptidx=$exptidx, ".
1213 1214
		 "       pid='$pid', ".
		 "       eid='$eid', ".
1215
		 "       vname='$vnodeid', ".
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
		 "       old_pid='', ".
		 "       old_eid=''";

	print STDERR "$statement\n"
	    if ($debug);

	if (!$impotent && !DBQueryWarn($statement)) {
	    print STDERR "*** CreateVnodes: Could not create reserved entry\n";
	    goto bad;
	}

	$statement =
	         "insert into node_status set ".
		 "       node_id='$vnodeid', " .
		 "       status='up', ".
		 "       status_timestamp=now()";

	print STDERR "$statement\n"
	    if ($debug);

	if (!$impotent && !DBQueryWarn($statement)) {
	    print STDERR "*** CreateVnodes: Could not create status entry\n";
	    goto bad;
	}

	$statement =
	         "insert into node_hostkeys set ".
		 "       node_id='$vnodeid'";

	print STDERR "$statement\n"
	    if ($debug);

	if (!$impotent && !DBQueryWarn($statement)) {
	    print STDERR "*** CreateVnodes: Could not create hostkeys entry\n";
	    goto bad;
	}
	
	push(@created, $vnodeid);
    }
    DBQueryFatal("unlock tables");
    @$rptr = @created;
    return 0;

  bad:
    if (!$impotent) {
1261
	foreach my $vnodeid (@created) {
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
	    DBQueryWarn("delete from reserved where node_id='$vnodeid'");
	    DBQueryWarn("delete from nodes where node_id='$vnodeid'");
	    DBQueryWarn("delete from node_hostkeys where node_id='$vnodeid'");
	    DBQueryWarn("delete from node_status where node_id='$vnodeid'");
	}
    }
    DBQueryFatal("unlock tables");
    return -1;
}

#
# Delete vnodes created in above step.
# 
sub DeleteVnodes(@)
{
    my (@vnodes) = @_;

    DBQueryWarn("lock tables nodes write, reserved write");
    foreach my $vnodeid (@vnodes) {
	DBQueryWarn("delete from reserved where node_id='$vnodeid'");
	DBQueryWarn("delete from nodes where node_id='$vnodeid'");
    }
    DBQueryFatal("unlock tables");
    
    foreach my $vnodeid (@vnodes) {
	DBQueryWarn("delete from node_hostkeys where node_id='$vnodeid'");
	DBQueryWarn("delete from node_status where node_id='$vnodeid'");
	DBQueryWarn("delete from node_rusage where node_id='$vnodeid'");
    }

    return 0;
}

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
sub SetNodeHistory($$$$)
{
    my ($self, $op, $user, $experiment) = @_;

    my $exptidx = $experiment->idx();
    my $nodeid  = $self->node_id();
    my $now     = time();
    my $uid;
    my $uid_idx;

    if (!defined($user)) {
	# Should this be elabman instead?
	$uid = "root";
	$uid_idx = 0;
    }
    else {
	$uid = $user->uid();
	$uid_idx = $user->uid_idx();
    }
    if ($op eq TB_NODEHISTORY_OP_MOVE() || $op eq TB_NODEHISTORY_OP_FREE()) {
	# Summary info. We need the last entry made.
	my $query_result =
	    DBQueryWarn("select exptidx,stamp from node_history ".
			"where node_id='$nodeid' ".
			"order by stamp desc limit 1");

	if ($query_result && $query_result->numrows) {
	    my ($lastexptidx,$stamp) = $query_result->fetchrow_array();
	    my $checkexp;

	    if ($op eq TB_NODEHISTORY_OP_FREE()) {
		$checkexp = $experiment;
	    }
	    else {
		$checkexp = Experiment->Lookup($lastexptidx);
	    }
	    if (defined($checkexp)) {
		if ($checkexp->pid() eq NODEDEAD_PID() &&
		    $checkexp->eid() eq NODEDEAD_EID()) {
		    my $diff = $now - $stamp;

		    DBQueryWarn("update node_utilization set ".
				" down=down+$diff ".
				"where node_id='$nodeid'")
		    }
		else {
		    my $diff = $now - $stamp;

		    DBQueryWarn("update node_utilization set ".
				" allocated=allocated+$diff ".
				"where node_id='$nodeid'");
		}
	    }
	}
    }
    return DBQueryWarn("insert into node_history set ".
		       "  history_id=0, node_id='$nodeid', op='$op', ".
		       "  uid='$uid', uid_idx='$uid_idx', ".
		       "  stamp=$now, exptidx=$exptidx");
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
#
# Set the scheduled_reloads for a node. Type is optional and defaults to
# testbed default load type. See above.
#
sub SetSchedReload($$;$)
{
    my ($self, $image, $type) = @_;

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

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

    $type = TB_DEFAULT_RELOADTYPE
	if (!defined($type));

    return -1
	if (! DBQueryWarn("replace into scheduled_reloads ".
			  "(node_id, image_id, reload_type) values ".
			  "('$node_id', '$imageid', '$type')"));

    return 0;
}

1382 1383 1384
# _Always_ make sure that this 1 is at the end of the file...

1;