libadminctrl.pm.in 36.9 KB
Newer Older
1 2 3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2006 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134
# All rights reserved.
#
#
# Admission control policies. These are the ones I could think of, although
# not all of these are implemented.
#
#  * Number of experiments per type/class (only one expt using robots).
#
#  * Number of experiments per project
#  * Number of experiments per subgroup
#  * Number of experiments per user
#
#  * Number of nodes per project      (nodes really means pc testnodes)
#  * Number of nodes per subgroup
#  * Number of nodes per user
#
#  * Number of nodes of a class per project
#  * Number of nodes of a class per group
#  * Number of nodes of a class per user
#
#  * Number of nodes of a type per project
#  * Number of nodes of a type per group
#  * Number of nodes of a type per user
#
#  * Number of nodes with attribute(s) per project
#  * Number of nodes with attribute(s) per group
#  * Number of nodes with attribute(s) per user
#
# So we have group (pid/gid) policies and user policies. These are stored
# into two different tables, group_policies and user_policies, indexed in
# the obvious manner. Each row of the table defines a count (experiments,
# nodes, etc) and a type of thing being counted (experiments, nodes, types,
# classes, etc). When we test for admission, we look for each matching row
# and test each condition. All conditions must pass. No conditions means a
# pass. There is also some "auxdata" which holds extra information needed
# for the policy (say, the type of node being restricted). 
#
#      uid:     a uid
#   policy:     'experiments', 'nodes', 'type', 'class', 'attribute'
#    count:     a number
#  auxdata:     a string (optional)
#
# Example: A user policy of ('mike', 'nodes', 10) says that poor mike is
# not allowed to have more 10 nodes at a time, while ('mike', 'type',
# '10', 'pc850') says that mike cannot allocate more than 10 pc850s.
#
# The group_policies table:
#
#      pid:     a pid
#      gid:     a gid
#   policy:     'experiments', 'nodes', 'type', 'class', 'attribute'
#    count:     a number
#  auxdata:     a string (optional)
#
# Example: A project policy of ('testbed', 'testbed', 'experiments', 10)
# says that the testbed project may not have more then 10 experiments
# swapped in at a time, while ('testbed', 'TG1', 'nodes', 10) says that the
# TG1 subgroup of the testbed project may not use more than 10 nodes at time.
#
# In addition to group and user policies (which are policies that apply to
# specific users/projects/subgroups), we also need policies that apply to
# all users/projects/subgroups (ie: do not want to specify a particular
# restriction for every user!). To indicate such a policy, we use a special
# tag in the tables (for the user or pid/gid):
#
#      '+'  -  The policy applies to all users (or project/groups).
#
# Example: ('+','experiments',10) says that no user may have more then 10
# experiments swapped in at a time. The rule overrides anything more
# specific (say a particular user is restricted to 20 experiments; the above
# rule overrides that and the user (all users) is restricted to 10.
#
# Sometimes, you want one of these special rules to apply to everyone, but
# *allow* it to be overridden by a more specific rule. For that we use:
#
#      '-'  -  The policy applies to all users (or project/groups),
#              but can be overridden by a more specific rule.
#
# Example: The rules:
#
#	('-','type',0, 'garcia')
#       ('testbed', 'testbed', 'type', 10, 'garcia')
#
# says that no one is allowed to allocate garcias, unless there is specific
# rule that allows it; in this case the testbed project can allocate them.
#
# There are other global policies we would like to enforce. For example,
# "only one experiment can be using the robot testbed." Encoding this kind
# of policy is harder, and leads down a path that can get arbitrarily
# complex. Tha path leads to ruination, and so we want to avoid it at
# all costs.
#
# Instead we define a simple global policies table that applies to all
# experiments currently active on the testbed:
#
#   policy:     'nodes', 'type', 'class', 'attribute'
#     test:     'max', others I cannot think of right now ...
#    count:     a number
#  auxdata:     a string
#
# Example: A global policy of ('nodes', 'max', 10, '') say that the maximum
# number of nodes that may be allocated across the testbed is 10. Thats not
# a very realistic policy of course, but ('type', 'max', 1, 'garcia') says
# that a max of one garcia can be allocated across the testbed, which
# effectively means only one experiment will be able to use them at once.
# This is of course very weak, but I want to step back and give it some
# more thought before I redo this part. 
#
# Is that clear? Hope so, cause it gets more complicated. Some admission
# control tests can be done early in the swap phase, before we really do
# anything (before assign_wrapper). Others (type and class) tests cannot
# be done here; only assign can figure out how an experiment is going to map
# to physical nodes (remember virtual types too), and in that case we need
# to tell assign what the "constraints" are and let it figure out what is
# possible.
#
# So, in addition to the simple checks we can do, we also generate an array
# to return to assign_wrapper with the maximum counts of each node type and
# class that is limited by the policies. assign_wrapper will dump those
# values into the ptop file so that assign can enforce those maximum values
# regardless of what hardware is actually available to use. As per discussion
# with Rob, that will look like:
#
#	set-type-limit <type> <limit>
#
# and assign will spit out a new type of violation that assign_wrapper will
# parse. 
#
# NOTES:
#
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
#  * The system is not hierarchical; it is flat. That is, user rules do not
#    override group rules and group rules do not override project rules, etc.
#  * Admission control is skipped in admin mode; returns okay.
#  * Admission control is skipped when the pid is emulab-ops; returns okay.
#  * When calculating current usage, nodes reserved to emulab-ops are
#    ignored.
#  * The sitevar "swap/use_admission_control" controls the use of admission
#    control; defaults to 1 (on).
#  * The current policies can be viewed in the web interface. See
#    https://www.emulab.net/showpolicies.php3
#  * The global policy stuff is weak. I plan to step back and think about it
#    some more before redoing it, but it will tide us over for now.
#
#####
# Regarding the nodetypeXpid_permissions table ...
#
# My original thought when I started this was that I would be able to replace
# the existing nodetypeXpid_permissions table with this new stuff. Well, it
# turns out that this was not a good thing to do, for a couple of reasons:
#
#  * Engineering: We access the nodetypeXpid_permissions table from three
#    different languages, and no way I wanted to rewrite this library in
#    in python and php!
#
#  * Performance: We access the nodetypeXpid_permissions from the web
#    interface, on every single page load. In fact, we access it twice if
#    if you count the FreePCs() count that we put at the top of the menu.
#    Going through this library on each page load would be a serious drag.
#
# So, rather then actually get rid of the nodetypeXpid_permissions table, I
# decided to keep it as a "cache" of permissions stored in the group
# policies table. Each time you update the policy tables, we need to run
# the update_permissions script which will call into this library (see the
# TBUpdateNodeTypeXpidPermissions() routine) to reconstruct the permissions
# table. I have whacked the grantnodetype script to do exactly that.
#
# Note that we could proably do the same thing for users by creating an
# equivalent nodetypeXuid_permissions table, mapping users to types they
# are allowed to use. That would be a lot rows, but the amount of data in
# the table is small. That would give us very fine grained control of what
# we show people in the web interface. Not sure it is worth it though.
#
# Bottom line: Do not update the nodetypeXpid_permissions table by hand
# anymore! Update the group_policies table and then run the script to
# update the permissions table (sbin/update_permissions). 
180 181 182 183 184 185 186 187
#

package libadminctrl;
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);
@ISA = "Exporter";
@EXPORT =
188
    qw ( TBAdmissionControlCheck TBUpdateNodeTypeXpidPermissions );
189 190 191 192 193 194

# Must come after package declaration!
use lib '@prefix@/lib';
use English;
use libdb;
use libtestbed;
195
use libtblog;
196
use Group;
197 198 199 200 201

# Configure variables
my $TB		= "@prefix@";

# Locals
202
my $debug         = 0;
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
my $expt_min;
my $expt_max;
my %virt_types    = ();  # Indexed by virt type, gives number desired
my %virt_classes  = ();  # Indexed by virt class, gives number desired
my %node_types    = ();	 # Indexed by type, gives class
my %node_classes  = ();	 # Indexed by class, gives class
my $assignflag    = 0;
my %assign_classes= ();  # For assign (wrapper).

# Constants.
sub TBADMINCTRL_TYPE_USER()		{ "user"; }
sub TBADMINCTRL_TYPE_PROJECT()		{ "project"; }
sub TBADMINCTRL_TYPE_GROUP()		{ "group"; }

sub TBADMINCTRL_POLICY_EXPT()		{ "experiments"; }
sub TBADMINCTRL_POLICY_NODES()		{ "nodes"; }
sub TBADMINCTRL_POLICY_TYPE()		{ "type"; }
sub TBADMINCTRL_POLICY_CLASS()		{ "class"; }
sub TBADMINCTRL_POLICY_ATTR()		{ "attribute"; }
222
sub TBADMINCTRL_POLICY_MEMBERSHIP()	{ "membership"; }
223

224 225 226
my $MINUS_GIDIDX	= 0;
my $PLUS_GIDIDX		= 999999;

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
#
# The current usage data structure, filled in below.
#
my %curusage =
    ("experiments"	=> {"user"    =>  0,
			    "project" =>  0,
			    "group"   =>  0},
     "nodes"    	=> {"user"    =>  0,
			    "project" =>  0,
			    "group"   =>  0},
     # Arrays of user/project/group counts, indexed by type and class. 
     "class"		=> {},
     "type"		=> {},
    );

# Output useful info.
sub Declare($)
{
    my ($msg) = @_;
    
247
    tberror({cause => 'user'}, "Admission Control: $msg\n");
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
}

# Debug stuff
sub Debug($)
{
    my ($msg) = @_;
    
    if ($debug) {
	print "*** - $msg\n";
    }
}

# Update assign number.
sub UpdateForAssign($$)
{
    my ($typeclass, $count) = @_;

    $count = 0
	if ($count < 0);

    $assign_classes{$typeclass} = 999999
	if (!defined($assign_classes{$typeclass}));
    
    # Max for assign is the global minus current number
    $assign_classes{$typeclass} = $count
	if ($count < $assign_classes{$typeclass});
}

#
# Test a user policy.
#
sub TestUserPolicy($$$$$)
{
    my ($uid, $policy, $count, $auxdata, $global) = @_;
    my $query_result;
    my $current = 0;
    my $gstring = ($global ? "global" : "user");

    if ($policy eq TBADMINCTRL_POLICY_EXPT()) {
	#
	# Simple check first.
	#
	if (!$count) {
	    Declare("$uid is not allowed to swap any experiments in!");
	    return 0;
	}
	$current = $curusage{"experiments"}->{'user'};

	Debug("$uid has $current active experiments; ".
	      "${gstring} limit is $count");
	
	if ($current >= $count) {
	    Declare("$uid has too many experiments swapped in!");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_NODES()) {
	#
	# Simple check first.
	#
	if (!$count) {
	    Declare("$uid is not allowed to allocate any nodes!");
	    return 0;
	}
	$current = $curusage{"nodes"}->{'user'};
	
	Debug("$uid has $current nodes allocated; ".
	      "${gstring} limit is $count");
	
	if ($current + $expt_min > $count) {
	    Declare("$uid has too many nodes allocated! ".
		    "Needs $expt_min more.");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_CLASS()) {
	$current = $curusage{"class"}->{$auxdata}->{'user'}
	    if (exists($curusage{"class"}->{$auxdata}));
	
	if ($assignflag) {
	    UpdateForAssign($auxdata, $count - $current);
329
	    return 1;
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
	}
	
	#
	# Check first to see if the experiment even wants this class.
	#
	return 1
	    if (! $virt_classes{$auxdata});

	#
	# If it does, then simple check first.
	# 
	if (!$count) {
	    Declare("$uid is not allowed to allocate any nodes of ".
		    "class $auxdata!");
	    return 0;
	}
	Debug("$uid has $current nodes of class $auxdata allocated; ".
	      "${gstring} limit is $count");
	
	if ($current + $virt_classes{$auxdata} > $count) {
	    Declare("$uid has too many nodes of class $auxdata allocated! ".
		    "Needs ". $virt_classes{$auxdata} ." more.");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_TYPE()) {
	$current = $curusage{"type"}->{$auxdata}->{'user'}
	    if (exists($curusage{"type"}->{$auxdata}));

	if ($assignflag) {
	    UpdateForAssign($auxdata, $count - $current);
361
	    return 1;
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 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
	}
	
	#
	# Check first to see if the experiment even wants this class.
	#
	return 1
	    if (! $virt_types{$auxdata});

	#
	# If it does, then simple check first.
	# 
	if (!$count) {
	    Declare("$uid is not allowed to allocate any nodes of ".
		    "type $auxdata!");
	    return 0;
	}
	
	Debug("$uid has $current nodes of type $auxdata allocated; ".
	      "${gstring} limit is $count");
	
	if ($current + $virt_types{$auxdata} > $count) {
	    Declare("$uid has too many nodes of type $auxdata allocated! ".
		    "Needs ". $virt_types{$auxdata} ." more.");
	    return 0;
	}
    }
    else {
	warn("*** WARNING: Unknown user policy '$policy'!\n");
    }

    return 1;
}

#
# Test a group policy.
#
sub TestGroupPolicy($$$$$$)
{
    my ($pid, $gid, $policy, $count, $auxdata, $global) = @_;
    my $query_result;
    my $current = 0;
    my $gstring = ($global ? "global" : "group");

    if ($policy eq TBADMINCTRL_POLICY_EXPT()) {
	#
	# Simple check first.
	#
	if (!$count) {
	    Declare("$pid/$gid is not allowed to swap any experiments in!");
	    return 0;
	}
	$current = ($pid eq $gid ?
		    $curusage{"experiments"}->{'project'} :
		    $curusage{"experiments"}->{'group'});

	Debug("$pid/$gid has $current active experiments; ".
	      "${gstring} limit is $count");
	
	if ($current >= $count) {
	    Declare("$pid/$gid has too many experiments swapped in!");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_NODES()) {
	#
	# Simple check first.
	#
	if (!$count) {
	    Declare("$pid/gid is not allowed to allocate any nodes!");
	    return 0;
	}
	$current = ($pid eq $gid ?
		    $curusage{"nodes"}->{'project'} :
		    $curusage{"nodes"}->{'group'});
	
	Debug("$pid/$gid has $current nodes allocated; ".
	      "${gstring} limit is $count");
	
	if ($current + $expt_min > $count) {
	    Declare("$pid/$gid has too many nodes allocated! ".
		    "Needs $expt_min more.");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_CLASS()) {
	$current = ($pid eq $gid ?
		    $curusage{"class"}->{$auxdata}->{'project'} :
		    $curusage{"class"}->{$auxdata}->{'group'})
	    if (exists($curusage{"class"}->{$auxdata}));
	
	if ($assignflag) {
	    UpdateForAssign($auxdata, $count - $current);
454
	    return 1;
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
	}
	
	#
	# Check first to see if the experiment even wants this class.
	#
	return 1
	    if (! $virt_classes{$auxdata});

	#
	# If it does, then simple check first.
	# 
	if (!$count) {
	    Declare("$pid/$gid is not allowed to allocate any nodes of ".
		    "class $auxdata!");
	    return 0;
	}
	
	Debug("$pid/$gid has $current nodes of class $auxdata allocated; ".
	      "${gstring} limit is $count");
	
	if ($current + $virt_classes{$auxdata} > $count) {
	    Declare("$pid/$gid has too many nodes of class $auxdata ".
		    "allocated! Needs ". $virt_classes{$auxdata} ." more.");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_TYPE()) {
	$current = ($pid eq $gid ?
		    $curusage{"type"}->{$auxdata}->{'project'} :
		    $curusage{"type"}->{$auxdata}->{'group'})
	    if (exists($curusage{"type"}->{$auxdata}));
	
	if ($assignflag) {
	    UpdateForAssign($auxdata, $count - $current);
489
	    return 1;
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
	}
	
	#
	# Check first to see if the experiment even wants this class.
	#
	return 1
	    if (! $virt_types{$auxdata});

	#
	# If it does, then simple check first.
	# 
	if (!$count) {
	    Declare("$pid/$gid is not allowed to allocate any nodes of ".
		    "type $auxdata!");
	    return 0;
	}
	Debug("$pid/$gid has $current nodes of type $auxdata allocated; ".
	      "${gstring} limit is $count");
	
	if ($current + $virt_types{$auxdata} > $count) {
	    Declare("$pid/$gid has too many nodes of type $auxdata ".
		    "allocated! Needs ". $virt_types{$auxdata} ." more.");
	    return 0;
	}
    }
    else {
	warn("*** WARNING: Unknown group policy '$policy'!\n");
    }

    return 1;
}

#
# Test a Global policy.
#
525
sub TestGlobalPolicy($$$$$)
526
{
527
    my ($policy, $test, $count, $auxdata, $uid) = @_;
528 529
    my $current = 0;

530 531 532 533 534 535 536 537
    if ($policy eq TBADMINCTRL_POLICY_MEMBERSHIP()) {
	#
	# HACK! $uid must be a member of the comma separated list of projects.
	#
	my @pidlist = split(",", $auxdata);

	my $query_result =
	    DBQueryWarn("select uid from group_membership ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
538
			"where uid='$uid' and trust!='none' and (".
539 540 541 542 543 544
			join(" or ", map("pid='$_'", @pidlist)) . ")");
	
	return -1
	    if (!$query_result);

	if (! $query_result->numrows) {
545 546
	    Declare("You are not a member of a project with permission to ".
		    "swapin experiments.");
547 548 549 550
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_EXPT()) {
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
	#
	# Simple check first.
	#
	if (!$count) {
	    Declare("No one is allowed to swap any experiments in!");
	    return 0;
	}

	#
	# Get number of current experiments.
	#
	my $query_result =
	    DBQueryWarn("select count(eid) from experiments ".
			"where (state='" . EXPTSTATE_ACTIVE() . "' or ".
			"       state='" . EXPTSTATE_ACTIVATING() . "') and ".
			"       pid!='" . TBOPSPID() . "'");

	return -1
	    if (!$query_result);
	
	$current = ($query_result->fetchrow_array())[0];

	Debug("There are $current active experiments; ".
	      "global limit is $count");
	
	if ($current >= $count) {
	    Declare("There are too many experiments swapped in!");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_NODES()) {
	#
	# Simple check first.
	#
	if (!$count) {
586
	    Declare("No one is allowed to allocate any more nodes!");
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 626 627 628 629 630 631
	    return 0;
	}

	my $query_result =
	    DBQueryFatal("select count(r.node_id) from reserved as r ".
		     "left join nodes as n on n.node_id=r.node_id ".
		     "left join node_types as nt on nt.type=n.type ".
		     "where r.pid!='" . TBOPSPID() . "' and ".
		     "      n.role='testnode'");
	
	return -1
	    if (!$query_result);
	
	$current = ($query_result->fetchrow_array())[0];
	
	Debug("The testbed has $current nodes allocated; ".
	      "global limit is $count");
	
	if ($current + $expt_min > $count) {
	    Declare("The testbed has too many nodes allocated! ".
		    "Needs $expt_min more.");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_CLASS()) {
	#
	# Get current count.
	#
	my $query_result =
	    DBQueryFatal("select count(r.node_id) from reserved as r ".
			 "left join nodes as n on n.node_id=r.node_id ".
			 "left join node_types as nt on nt.type=n.type ".
			 "where r.pid!='" . TBOPSPID() . "' and ".
			 "      nt.class='$auxdata' and ".
			 "      n.role='testnode'");
	
	return -1
	    if (!$query_result);
	$current = ($query_result->fetchrow_array())[0];

	Debug("The testbed has $current nodes of class $auxdata allocated; ".
	      "global limit is $count");
	
	if ($assignflag) {
	    UpdateForAssign($auxdata, $count - $current);
632
	    return 1;
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
	}
	
	#
	# Check to see if the experiment even wants this class.
	#
	return 1
	    if (! $virt_classes{$auxdata});

	#
	# If it does, then simple check first.
	# 
	if (!$count) {
	    Declare("No one is allowed to allocate any nodes of ".
		    "class $auxdata!");
	    return 0;
	}

	if ($current + $virt_classes{$auxdata} > $count) {
	    Declare("The testbed has too many nodes of class $auxdata ".
		    "allocated! Needs ". $virt_classes{$auxdata} ." more.");
	    return 0;
	}
    }
    elsif ($policy eq TBADMINCTRL_POLICY_TYPE()) {
	#
	# Get current count.
	#
	my $query_result =
	    DBQueryFatal("select count(r.node_id) from reserved as r ".
			 "left join nodes as n on n.node_id=r.node_id ".
			 "left join node_types as nt on nt.type=n.type ".
			 "where r.pid!='" . TBOPSPID() . "' and ".
			 "      nt.type='$auxdata' and ".
			 "      n.role='testnode'");
	
	return -1
	    if (!$query_result);
	$current = ($query_result->fetchrow_array())[0];

	Debug("The testbed has $current nodes of type $auxdata allocated; ".
	      "global limit is $count");
	
	if ($assignflag) {
	    UpdateForAssign($auxdata, $count - $current);
677
	    return 1;
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
	}
	
	#
	# Check first to see if the experiment even wants this class.
	#
	return 1
	    if (! $virt_types{$auxdata});

	#
	# If it does, then simple check first.
	# 
	if (!$count) {
	    Declare("No one is allowed to allocate any nodes of ".
		    "type $auxdata!");
	    return 0;
	}

	if ($current + $virt_types{$auxdata} > $count) {
	    Declare("The testbed has too many nodes of type $auxdata ".
		    "allocated! Needs ". $virt_types{$auxdata} ." more.");
	    return 0;
	}
    }
    else {
	warn("*** WARNING: Unknown global policy '$policy'!\n");
    }

    return 1;
}

#
# Test policies that apply.
#
711
sub TestPolicies($$$$)
712
{
713
    my ($uid, $pid, $eid, $gid) = @_;
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
    my $failcount       = 0;
    my %user_policies   = ();
    my %group_policies  = ();
    my %global_policies = ();

    #
    # Get the global policies. 
    #
    my $query_result =
	DBQueryWarn("select * from global_policies");

    return -1
	if (!$query_result);

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $policy  = $rowref->{'policy'};
	my $auxdata = $rowref->{'auxdata'};
	my $count   = $rowref->{'count'};
	my $test    = $rowref->{'test'};

	if ($debug) {
	    print "Global Policy: $policy, $test, $count, $auxdata\n";
	}

	$global_policies{"$policy:$test:$auxdata"} = $rowref;
    }

    #
    # Get user policies that apply. Ordering by uid will put the global
    # policies last, which makes it easier in the loop below.
    # 
    $query_result =
	DBQueryWarn("select * from user_policies ".
		    "where uid='$uid' or uid='+' or uid='-' ".
		    "order by uid desc");
    return -1
	if (!$query_result);

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $puid    = $rowref->{'uid'};
	my $policy  = $rowref->{'policy'};
	my $auxdata = $rowref->{'auxdata'};
	my $count   = $rowref->{'count'};

	if ($debug) {
	    print "User Policy: $puid, $policy, $count, $auxdata\n";
	}

	if ($puid eq "+") {
	    $user_policies{"$policy:$auxdata"} = $rowref;
	}
	elsif ($puid eq "-") {
	    # Allow existing user policy to override this.
	    $user_policies{"$policy:$auxdata"} = $rowref
		if (!exists($user_policies{"$policy:$auxdata"}));
	}
	else {
	    $user_policies{"$policy:$auxdata"} = $rowref;
	}
    }

    $query_result =
776 777
	DBQueryWarn("select distinct * from group_policies ".
		    "where (pid='$pid' and (pid=gid or gid='$gid')) or ".
778
		    "      pid='' or pid='-' ".
779 780 781 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
		    "order by pid,gid desc");
    return -1
	if (!$query_result);

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $ppid    = $rowref->{'pid'};
	my $policy  = $rowref->{'policy'};
	my $auxdata = $rowref->{'auxdata'};
	my $count   = $rowref->{'count'};

	if ($debug) {
	    print "Group Policy: $pid, $gid, $policy, $count, $auxdata\n";
	}
	
	if ($ppid eq "+") {
	    $group_policies{"$policy:$auxdata"} = $rowref;
	}
	elsif ($ppid eq "-") {
	    # Allow existing policy to override this.
	    $group_policies{"$policy:$auxdata"} = $rowref
		if (!exists($group_policies{"$policy:$auxdata"}));
	}
	else {
	    $group_policies{"$policy:$auxdata"} = $rowref;
	}
    }

    #
    # Now test the policies. Test them all so that we get feedback on
    # all policies that fail.
    #
    foreach my $key (keys(%global_policies)) {
	my $pref    = $global_policies{$key};
	my $test    = $pref->{'test'};
	my $policy  = $pref->{'policy'};
	my $count   = $pref->{'count'};
	my $auxdata = $pref->{'auxdata'};

817
	my $result = TestGlobalPolicy($policy, $test, $count, $auxdata, $uid);
818
	    
819 820 821
	$failcount++
	    if (!$result);
    }
822 823 824 825 826 827 828 829 830 831

    #
    # For node type permission checks, want to do project based checks
    # first so that user restrictions can override project based restrictions.
    # This is cause people can be in multiple projects and trying to get
    # permission checks in this case is totally bogus to begin with, but
    # we like to tell people how many nodes are available and they have
    # permission to use, across all projects they are members of, which is a
    # silly and meaningless number if you are in multiple projects.
    # 
832 833 834 835 836 837 838 839
    foreach my $key (keys(%group_policies)) {
	my $pref    = $group_policies{$key};
	my $ppid    = $pref->{'pid'};
	my $pgid    = $pref->{'gid'};
	my $policy  = $pref->{'policy'};
	my $count   = $pref->{'count'};
	my $auxdata = $pref->{'auxdata'};
	my $global  = ($ppid eq $pid ? 0 : 1);
840
	my $result;
841

842 843 844
	$result = TestGroupPolicy($pid, $gid,
				  $policy, $count, $auxdata, $global);
	
845 846 847 848 849 850 851 852 853 854 855
	$failcount++
	    if (!$result);
    }
    
    foreach my $key (keys(%user_policies)) {
	my $pref    = $user_policies{$key};
	my $puid    = $pref->{'uid'};
	my $policy  = $pref->{'policy'};
	my $count   = $pref->{'count'};
	my $auxdata = $pref->{'auxdata'};
	my $global  = ($puid eq $uid ? 0 : 1);
856
	my $result;
857

858 859
	$result = TestUserPolicy($uid, $policy,
				 $count, $auxdata, $global);
860 861 862 863

	$failcount++
	    if (!$result);
    }
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    # Skip Robot Lab checks if already failed.
    return 0
	if ($failcount);

    #
    # The Robot lab stuff is handled specially until I come up with a better
    # approach for global policies.
    #
    my $robotlab_isopen;
    return -1
	if (! TBGetSiteVar("robotlab/open", \$robotlab_isopen));

    if ($robotlab_isopen) {
	#
	# If the lab is open, then normal policies apply, except for
	# exclusive use of the lab.
	#
	my $robotlab_exclusive;
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
	return -1
	    if (! TBGetSiteVar("robotlab/exclusive", \$robotlab_exclusive));

	if ($robotlab_exclusive) {
	    # See who is using the Robot lab.
	    my ($rpid, $reid);

	    if (TBRobotLabExpt(\$rpid, \$reid) &&
		! ($pid eq $rpid && $eid eq $reid)) {
		#
		# Lab in use by another experiment.
		#
		foreach my $type (keys(%node_types)) {
		    my $class = $node_types{$type};

		    if ($class eq "robot") {
			if ($assignflag) {
			    UpdateForAssign($type, 0);
			}
			else {
			    #
			    # If user wants a robot type, then fail cause
			    # the lab is currently closed.
			    # 
			    if (exists($virt_types{$type}) ||
				exists($virt_classes{$class})) {
				Declare("The Robot Lab is already in use!");
				$failcount++;
			    }
			}
		    }
		}
	    }
	}
    }
    else {
	#
	# Lab is closed. Make sure assign gets zeros for the types, or if
	# doing the prepass, check for user defined usage. 
	#
	foreach my $type (keys(%node_types)) {
	    my $class = $node_types{$type};

	    if ($class eq "robot") {
		if ($assignflag) {
		    UpdateForAssign($type, 0);
		}
		else {
		    #
		    # If user wants a robot type, then fail cause the lab
		    # is currently closed.
		    # 
		    if (exists($virt_types{$type}) ||
			exists($virt_classes{$class})) {
			Declare("The Robot Lab is closed!");
			$failcount++;
		    }
		}
	    }
	}
    }
944 945 946 947 948
    return 0
	if ($failcount);
    return 1;
}

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
#
# Update nodetypeXpid_permissions table.
#
sub UpdateNodeTypeXpidPermissions()
{
    my %minus_policies  = ();
    my %plus_policies   = ();
    my %permissions     = ();

    #
    # Get global policies
    # 
    my $query_result =
	DBQueryWarn("select * from group_policies ".
		    "where pid='+' or pid='-' ".
		    "order by pid,gid desc");
    return -1
	if (!$query_result);

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $ppid    = $rowref->{'pid'};
	my $pgid    = $rowref->{'gid'};
	my $policy  = $rowref->{'policy'};
	my $auxdata = $rowref->{'auxdata'};
	my $count   = $rowref->{'count'};

	next
	    if (! ($policy eq TBADMINCTRL_POLICY_TYPE()));

	if ($debug) {
	    print "Type Perm: $ppid, $pgid, $count, $auxdata\n";
	}
	
	if ($ppid eq "+") {
	    $plus_policies{$auxdata} = $count;
	}
	elsif ($ppid eq "-") {
	    $minus_policies{$auxdata} = $count;
	}
    }

    #
    # Get all group specific policies. 
    #
    $query_result =
	DBQueryWarn("select * from group_policies ".
		    "where pid!='+' and pid!='-' ".
		    "order by pid,gid desc");
    return -1
	if (!$query_result);

    while (my $rowref = $query_result->fetchrow_hashref()) {
1001
	my $gid_idx = $rowref->{'gid_idx'};
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
	my $ppid    = $rowref->{'pid'};
	my $pgid    = $rowref->{'gid'};
	my $policy  = $rowref->{'policy'};
	my $auxdata = $rowref->{'auxdata'};
	my $count   = $rowref->{'count'};

	if ($debug) {
	    print "Type Perm: $ppid, $pgid, $count, $auxdata\n";
	}

	next
	    if ($count == 0);

1015 1016 1017 1018
	my $group = Group->Lookup($gid_idx);
	next
	    if (!defined($group) || !$group->IsProjectGroup());

1019 1020 1021 1022
	next
	    if (exists($plus_policies{$auxdata}) &&
		plus_policies{$auxdata} == 0);

1023 1024
	$permissions{"$gid_idx"} = {}
	    if (!exists($permissions{"$gid_idx"}));
1025
	
1026
	$permissions{"$gid_idx"}->{$auxdata} = 1;
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    }

    #
    # Generate the nodetypeXpid_permissions table (pid, type). We want to
    # do this atomically though, so create a temporary table and load that.
    # Then do a rename to swap the tables around.
    #
    return -1
	if (! (DBQueryWarn("select get_lock('libadminctrl', 999999)") &&
	       DBQueryWarn("drop table if exists libadminctrl_backup") &&
	       DBQueryWarn("drop table if exists libadminctrl_table")));

    $query_result = DBQueryWarn("show CREATE TABLE nodetypeXpid_permissions");
    return -1
	if (!$query_result);

    my $create_def = ($query_result->fetchrow_array())[1];
    $create_def =~ s/nodetypeXpid_permissions/libadminctrl_table/ig;

    return -1
	if (!DBQueryWarn($create_def));
    
1049 1050 1051 1052
    foreach my $gid_idx (keys(%permissions)) {
	my @typelist = keys(%{ $permissions{$gid_idx} });
	my $group    = Group->Lookup($gid_idx);
	my $pid      = $group->pid();
1053 1054 1055

	foreach my $type (@typelist) {
	    return -1
1056 1057 1058
		if (! DBQueryWarn("insert into libadminctrl_table ".
				  " (pid_idx, pid, type)".
				  "  values ($gid_idx, '$pid', '$type')"));
1059 1060 1061 1062 1063 1064 1065 1066
	}
    }
    $query_result = 
	DBQueryWarn("rename table ".
		    "  nodetypeXpid_permissions TO libadminctrl_backup, ".
		    "  libadminctrl_table TO nodetypeXpid_permissions ");

    DBQueryWarn("drop table if exists libadminctrl_table");
1067
    DBQueryWarn("drop table if exists libadminctrl_backup");
1068 1069 1070 1071 1072 1073 1074
    DBQueryWarn("select release_lock('libadminctrl')");
    return -1
	if (!$query_result);
    
    return 1;
}

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
#
# This is the primary interface to this library. Given a uid/pid/gid/eid,
# test all of the policies against the current experiment count, and the
# current node count plus the minimum number of nodes needed by the
# experiment.
# 
sub TBAdmissionControlCheck($$$$)
{
    my ($uid, $pid, $eid, $ptypearray) = @_;
    my $gid = ExpGroup($pid, $eid);

    $assignflag = 1
	if (defined($ptypearray));

    $uid = MapNumericUID($uid);
1090 1091 1092 1093 1094 1095

    #
    # Check to see if admin control is even on.
    #
    return 1
	if (! TBGetSiteVar("swap/use_admission_control"));
1096 1097 1098
    
    #
    # Admin people do not get checks (when in admin mode of course).
1099

1100 1101
    #
    return 1
1102
	if (TBAdmin($uid));
1103 1104 1105 1106 1107 1108 1109

    #
    # Nothing in emulab-ops should get admission control either.
    #
    return 1
	if ($pid eq TBOPSPID());

1110 1111 1112
    $debug = 1
	if (TBGetSiteVar("swap/admission_control_debug"));

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    #
    # Now we need the number of nodes needed by the experiment.
    #
    return -1
	if (!TBExptMinMaxNodes($pid, $eid, \$expt_min, \$expt_max));

    LoadNodeTypes();
    LoadVirtNodeTypes($pid, $eid);
    LoadCurrent($uid, $pid, $gid);

1123
    my $rval = TestPolicies($uid, $pid, $eid, $gid);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    
    if ($debug && $assignflag) {
	print "Assign type/class max counts:\n";
	foreach my $typeclass (keys(%assign_classes)) {
	    my $count = $assign_classes{$typeclass};

	    printf("%10s: %d\n", $typeclass, $count);
	}
    }
    %$ptypearray = %assign_classes
	if ($assignflag);

    return $rval;
}

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
#
# This is the secondary interface; this just gets a type restriction table.
# For each project the user is a member of, list the node types the user is
# not allowed to use. No mention in this table implies the user is allowed
# to use the type. No mention in a list for a specific project means the
# user is allowed to use the node type in that project (but might be
# restricted in another project). So silly. Once we figure out the project
# restrictions, apply the user restrictions to the table. 
# 
sub TBUpdateNodeTypeXpidPermissions()
{
1150 1151 1152
    $debug = 1
	if (TBGetSiteVar("swap/admission_control_debug"));

1153 1154 1155
    return UpdateNodeTypeXpidPermissions();
}
   
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 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
#
# Load the real types.
# 
sub LoadNodeTypes()
{
    my $query_result =
	DBQueryWarn("select type,class from node_types");

    return -1
	if (!$query_result);

    while (my ($type, $class) = $query_result->fetchrow_array()) {
	$node_types{$type}    = $class;
	$node_classes{$class} = $class;
    }
}
sub nodetypeistype($)   { return exists($node_types{$_[0]}); }
sub nodetypeclass($)	{ return $node_types{$_[0]}; }
sub nodeclassisclass($) { return exists($node_classes{$_[0]}); }

#
# Load the types this experiment wants, from the virt_nodes table.
# Might be a virtual type, which screws everything up!
#
sub LoadVirtNodeTypes($$)
{
    my ($pid, $eid) = @_;
    
    my $query_result =
	DBQueryWarn("select type from virt_nodes as vn ".
		    "where vn.pid='$pid' and vn.eid='$eid'");

    return -1
	if (!$query_result);

    # XXX Delay nodes!
    if ($expt_min > $query_result->numrows) {
	$virt_classes{"pc"} = $expt_min - $query_result->numrows;
    }

    while (my ($type) = $query_result->fetchrow_array()) {
	if (nodeclassisclass($type)) {
	    $virt_classes{$type} = 0
		if (!exists($virt_classes{$type}));
	    $virt_classes{$type} += 1;
	}
	else {
	    # Type counts.
	    $virt_types{$type} = 0
		if (!exists($virt_types{$type}));
	    $virt_types{$type} += 1;

	    # Class counts
	    if (nodetypeistype($type)) {
		my $class = nodetypeclass($type);

		$virt_classes{$class} = 0
		    if (!exists($virt_classes{$class}));
		$virt_classes{$class} += 1;
	    }
	}
    }
    if ($debug) {
	print "Experiment Desires:\n";
	print "  Classes:\n";
	foreach my $class (keys(%virt_classes)) {
	    my $count = $virt_classes{$class};
	    
	    print "    $class $count\n";
	}
	print "  Types:\n";
	foreach my $type (keys(%virt_types)) {
	    my $count = $virt_types{$type};
	    
	    print "    $type $count\n";
	}
    }
}

#
# Load Current physical usage. 
#
sub LoadCurrent($$$)
{
    my ($uid, $pid, $gid) = @_;

    #
    # Experiment counts,
    # 
    my $query_result =
	DBQueryWarn("select expt_swap_uid,pid,gid from experiments ".
		    "where (state='" . EXPTSTATE_ACTIVE() . "' or ".
		    "       state='" . EXPTSTATE_ACTIVATING() . "') and ".
		    "      (expt_swap_uid='$uid' or ".
		    "       pid='$pid' or gid='$gid')");

    return -1
	if (!$query_result);

    while (my ($c_uid,$c_pid,$c_gid) = $query_result->fetchrow_array()) {
	if ($c_uid eq $uid) {
	    $curusage{"experiments"}->{'user'} += 1;
	}
	if ($c_pid eq $pid) {
	    $curusage{"experiments"}->{'project'} += 1;
	}
	if ($c_gid eq $gid) {
	    $curusage{"experiments"}->{'group'} += 1;
	}
    }

    if ($debug) {
	printf("Experiment usage: user:%d, project:%d, group:%d\n",
	       $curusage{"experiments"}->{'user'},
	       $curusage{"experiments"}->{'project'},
	       $curusage{"experiments"}->{'group'});
    }

    #
    # Node stuff.
    #
    $query_result =
	DBQueryFatal("select e.expt_swap_uid,e.pid,e.gid,n.type,nt.class ".
		     "  from reserved as r ".
		     "left join nodes as n on n.node_id=r.node_id ".
		     "left join node_types as nt on nt.type=n.type ".
		     "left join experiments as e on ".
		     "     e.pid=r.pid and e.eid=r.eid ".
		     "where (e.expt_swap_uid='$uid' or ".
		     "       r.pid='$pid' and e.gid='$gid') and ".
		     "      r.pid!='" . TBOPSPID() . "' and ".
		     "      n.role='testnode'");
    return -1
	if (!$query_result);

    while (my ($c_uid,$c_pid,$c_gid,$c_type,$c_class) =
	   $query_result->fetchrow_array()) {
	if (!exists($curusage{"class"}->{$c_class})) {
	    $curusage{"class"}->{$c_class} = {"user"    =>  0,
					      "project" =>  0,
					      "group"   =>  0};
	}
	if (!exists($curusage{"type"}->{$c_type})) {
	    $curusage{"type"}->{$c_type} = {"user"    =>  0,
					    "project" =>  0,
					    "group"   =>  0};
	}
	if ($c_uid eq $uid) {
	    $curusage{"nodes"}->{'user'} += 1;
	    $curusage{"class"}->{$c_class}->{'user'} += 1;
	    $curusage{"type"}->{$c_type}->{'user'} += 1;
	}
	if ($c_pid eq $pid) {
	    $curusage{"nodes"}->{'project'} += 1;
	    $curusage{"class"}->{$c_class}->{'project'} += 1;
	    $curusage{"type"}->{$c_type}->{'project'} += 1;
	}
	if ($c_gid eq $gid) {
	    $curusage{"nodes"}->{'group'} += 1;
	    $curusage{"class"}->{$c_class}->{'group'} += 1;
	    $curusage{"type"}->{$c_type}->{'group'} += 1;
	}
    }
    if ($debug) {
	printf("Node usage: user:%d, project:%d, group:%d\n",
	       $curusage{"nodes"}->{'user'},
	       $curusage{"nodes"}->{'project'},
	       $curusage{"nodes"}->{'group'});
	foreach my $class (keys(%{$curusage{"class"}})) {
	    printf("Node class usage: $class user:%d, project:%d, group:%d\n",
		   $curusage{"class"}->{$class}->{'user'},
		   $curusage{"class"}->{$class}->{'project'},
		   $curusage{"class"}->{$class}->{'group'});
	}
	foreach my $type (keys(%{$curusage{"type"}})) {
	    printf("Node type usage: $type user:%d, project:%d, group:%d\n",
		   $curusage{"type"}->{$type}->{'user'},
		   $curusage{"type"}->{$type}->{'project'},
		   $curusage{"type"}->{$type}->{'group'});
	}
    }
    
    return 0;
}

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

1;