Project.pm.in 29.2 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2005-2018 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27
#
package Project;

use strict;
use Exporter;
28
use vars qw(@ISA @EXPORT @PROJDIRECTORIES @GROUPDIRECTORIES);
29 30

@ISA    = "Exporter";
31
@EXPORT = qw ();
32 33 34

use libdb;
use libtestbed;
35
use Brand;
36
use libEmulab;
37
use User;
38
use Group;
39 40 41 42 43 44 45 46 47
use English;
use Data::Dumper;
use File::Basename;
use overload ('""' => 'Stringify');

# Configure variables
my $TB		= "@prefix@";
my $BOSSNODE    = "@BOSSNODE@";
my $CONTROL	= "@USERNODE@";
48 49 50 51 52
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAPPROVAL  = "@TBAPPROVALEMAIL@";
my $TBAUDIT	= "@TBAUDITEMAIL@";
my $TBBASE      = "@TBBASE@";
my $TBWWW       = "@TBWWW@";
53 54
my $OURDOMAIN   = "@OURDOMAIN@";
my $PGENISUPPORT= @PROTOGENI_SUPPORT@;
55
my $WIKISUPPORT = @WIKISUPPORT@;
56 57 58
my $WITHZFS     = @WITHZFS@;
my $WITHAMD     = @WITHAMD@;
my $ZFS_NOEXPORT= @ZFS_NOEXPORT@;
59 60
my $MAILMANSUPPORT = @MAILMANSUPPORT@;
my $ADDPROJADMINLIST = "$TB/sbin/addprojadminlist";
61
my $EXPORTS_SETUP    = "$TB/sbin/exports_setup";
62

63 64 65 66 67
# These are duplicated in account/accountsetup.in ...
@PROJDIRECTORIES  = ("exp", "images", "logs", "deltas", "tarfiles", "rpms",
		     "groups", "tiplogs", "images/sigs", "templates");
@GROUPDIRECTORIES = ("exp", "images", "logs", "tarfiles", "rpms", "tiplogs");

68 69
# Cache of instances to avoid regenerating them.
my %projects   = ();
70 71
BEGIN { use emutil; emutil::AddCache(\%projects); }

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
my $debug      = 0;

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

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

#
# Lookup by idx.
#
sub Lookup($$)
{
Leigh Stoller's avatar
Leigh Stoller committed
89 90
    my ($class, $token) = @_;
    my $query_result;
91 92

    # Look in cache first
Leigh Stoller's avatar
Leigh Stoller committed
93 94 95 96 97 98 99 100 101 102 103
    return $projects{"$token"}
        if (exists($projects{"$token"}));

    #
    # For backwards compatability, look to see if the token is numeric
    # or alphanumeric. If numeric, assumes its an idx, otherwise a name.
    #
    if ($token =~ /^\d*$/) {
	$query_result =
	    DBQueryWarn("select * from projects where pid_idx='$token'");
    }
104
    elsif ($token =~ /^[-\w]*$/) {
Leigh Stoller's avatar
Leigh Stoller committed
105 106 107 108 109 110
	$query_result =
	    DBQueryWarn("select * from projects where pid='$token'");
    }
    else {
	return undef;
    }
111 112 113 114 115 116
    
    return undef
	if (!$query_result || !$query_result->numrows);

    my $self           = {};
    $self->{'PROJECT'} = $query_result->fetchrow_hashref();
Leigh Stoller's avatar
Leigh Stoller committed
117 118 119 120
    $self->{'GROUP'}   = Group->Lookup($self->{'PROJECT'}->{'pid_idx'});

    return undef
	if (!defined($self->{'GROUP'}));
121 122

    bless($self, $class);
123
    $self->{'BRAND'}   = Brand->Create($self->portal());
124 125
    
    # Add to cache. 
Leigh Stoller's avatar
Leigh Stoller committed
126
    $projects{$self->{'PROJECT'}->{'pid_idx'}} = $self;
127 128 129 130 131 132
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'PROJECT'}->{$_[1]}); }
sub pid($)	        { return field($_[0], "pid"); }
Leigh Stoller's avatar
Leigh Stoller committed
133
sub gid($)	        { return field($_[0], "pid"); }
134
sub pid_idx($)          { return field($_[0], "pid_idx"); }
Leigh Stoller's avatar
Leigh Stoller committed
135 136 137
sub gid_idx($)          { return field($_[0], "pid_idx"); }
sub head_uid($)         { return field($_[0], "head_uid"); }
sub head_idx($)         { return field($_[0], "head_idx"); }
138
sub created($)          { return field($_[0], "created"); }
139 140 141 142 143 144 145 146 147 148 149 150
sub description($)      { return field($_[0], "name"); }
sub why($)		{ return field($_[0], "why"); }
sub addr($)		{ return field($_[0], "addr"); }
sub URL($)		{ return field($_[0], "URL"); }
sub funders($)		{ return field($_[0], "funders"); }
sub num_members($)      { return field($_[0], "num_members"); }
sub num_pcs($)		{ return field($_[0], "num_pcs"); }
sub num_pcplab($)       { return field($_[0], "num_pcplab"); }
sub num_ron($)		{ return field($_[0], "num_ron"); }
sub public($)		{ return field($_[0], "public"); }
sub public_whynot($)    { return field($_[0], "public_whynot"); }
sub linked_to_us($)     { return field($_[0], "linked_to_us"); }
151 152
sub expt_count($)       { return field($_[0], "expt_count"); }
sub expt_last($)        { return field($_[0], "expt_last"); }
153
sub approved($)         { return field($_[0], "approved"); }
154 155
sub wikiname($)         { return field($_[0], "wikiname"); }
sub mailman_password($) { return field($_[0], "mailman_password"); }
156
sub allow_workbench($)  { return field($_[0], "allow_workbench"); }
157 158 159 160 161
sub hidden($)		{ return field($_[0], "hidden"); }
sub IsLocal($)		{ return (defined($_[0]->nonlocal_id()) ? 0 : 1); };
sub IsNonLocal($)	{ return (defined($_[0]->nonlocal_id()) ? 1 : 0); };
sub nonlocal_id($)	{ return field($_[0], "nonlocal_id"); }
sub nonlocal_type($)	{ return field($_[0], "nonlocal_type"); }
162
sub manager_urn($)	{ return field($_[0], "manager_urn"); }
163
sub portal($)		{ return field($_[0], "portal"); }
164 165 166
sub Brand($)		{ return $_[0]->{'BRAND'}; }
sub isAPT($)	        { return $_[0]->Brand()->isAPT() ? 1 : 0; }
sub isCloud($)	        { return $_[0]->Brand()->isCloud() ? 1 : 0; }
167
sub isPNet($)	        { return $_[0]->Brand()->isPNet() ? 1 : 0; }
168
sub isPowder($)	        { return $_[0]->Brand()->isPowder() ? 1 : 0; }
169
sub isEmulab($)         { return $_[0]->Brand()->isEmulab() ? 1 : 0; }
170

Leigh Stoller's avatar
Leigh Stoller committed
171 172 173 174
# These come from the group not the project.
sub unix_gid($)         { return $_[0]->{'GROUP'}->unix_gid(); }
sub unix_name($)        { return $_[0]->{'GROUP'}->unix_name(); }

175 176 177
# Branding.
sub ApprovalEmailAddress($)  { return $_[0]->Brand()->ApprovalEmailAddress(); }
sub OpsEmailAddress($)       { return $_[0]->Brand()->OpsEmailAddress(); }
178
sub LogsEmailAddress($)      { return $_[0]->Brand()->LogsEmailAddress(); }
179 180
sub EmailTag($)              { return $_[0]->Brand()->EmailTag(); }
sub wwwBase($)               { return $_[0]->Brand()->wwwBase(); }
181
sub SignupURL($)             { return $_[0]->Brand()->SignupURL($_[0]); }
182
# So we can localize MAILTAG variable.
183
sub SendEmail($$$$;$$)
184
{
185
    return $_[0]->Brand()->SendEmail($_[1],$_[2],$_[3],$_[4],$_[5]);
186
}
187
sub AnonSendEmail($$$$;$$)
188
{
189
    return $_[0]->Brand()->AnonSendEmail($_[1],$_[2],$_[3],$_[4],$_[5]);
190
}
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
#
# Lookup given pid For backwards compat.
#
sub LookupByPid($$)
{
    my ($class, $pid) = @_;

    my $query_result =
	DBQueryWarn("select pid_idx from projects where pid='$pid'");

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

    my ($pid_idx) = $query_result->fetchrow_array();

    return Project->Lookup($pid_idx);
}

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
#
# Lookup a nonlocal project.
#
sub LookupNonLocal($$)
{
    my ($class, $urn) = @_;
    my $safe_urn = DBQuoteSpecial($urn);

    my $query_result =
	DBQueryFatal("select pid_idx from projects ".
		     "where nonlocal_id=$safe_urn");

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

    my ($pid_idx) = $query_result->fetchrow_array();

    return Project->Lookup($pid_idx);
}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

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

    my $pid_idx = $self->pid_idx();
    
    my $query_result =
	DBQueryWarn("select * from projects where pid_idx=$pid_idx");

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

    $self->{'PROJECT'} = $query_result->fetchrow_hashref();

250
    return $self->{'GROUP'}->Refresh();
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
}

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

    return "[Project: $pid, IDX: $pid_idx]";
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

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

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

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

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

    return Refresh($self);
}

290 291 292 293 294 295
#
# Class function to create new project and return object.
#
sub Create($$$$)
{
    my ($class, $pid, $leader, $argref) = @_;
296
    my $unix_gname = $pid;
297
    my $nonlocal   = (exists($argref->{'nonlocal_id'}) ? 1 : 0);
298 299 300 301 302 303 304 305 306
	
    #
    # The array of inserts is assumed to be safe already. Generate
    # a list of actual insert clauses to be joined below.
    #
    my @insert_data = (!defined($argref) ? () :
		       map("$_=" . DBQuoteSpecial($argref->{$_}),
			   keys(%{$argref})));

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    # Form a proper unix group name, which is limited to 16 chars.
    if (length($pid) > 16) {
	$unix_gname  = substr($pid, 0, 16);
	my $maxtries = 9;
	my $count    = 0;
	while ($count < $maxtries) {
	    my $query_result =
		DBQueryFatal("select gid from groups ".
			     "where unix_name='$unix_gname'");
	    last
		if (!$query_result->numrows);

	    $count++;
	    $unix_gname = substr($pid, 0, 15) . "$count";
	}
	if ($count == $maxtries) {
	    print STDERR "Project->Create: ".
		"Could not form a unique Unix group name!";
	    return undef;
	}
    }

329
    # First create the underlying default group for the project.
330 331
    my $newgroup =
	Group->Create(undef, $pid, $leader, 'Default Group', $unix_gname);
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    return undef
	if (!defined($newgroup));

    # Every project gets a new unique index, which comes from the group.
    my $pid_idx = $newgroup->gid_idx();

    # Now tack on other stuff we need.
    push(@insert_data, "pid='$pid'");
    push(@insert_data, "pid_idx='$pid_idx'");
    push(@insert_data, "head_uid='" . $leader->uid() . "'");
    push(@insert_data, "head_idx='" . $leader->uid_idx() . "'");
    push(@insert_data, "created=now()");

    # Insert into DB. 
    if (! DBQueryWarn("insert into projects set " . join(",", @insert_data))) {
	$newgroup->Delete();
	return undef;
    }

    if (! DBQueryWarn("insert into project_stats (pid, pid_idx) ".
		      "values ('$pid', $pid_idx)")) {
	$newgroup->Delete();
	DBQueryFatal("delete from projects where pid_idx='$pid_idx'");
	return undef;
    }
    my $newproject = Project->Lookup($pid_idx);
    return undef
	if (! $newproject);

    #
    # The creator of a group is not automatically added to the group,
    # but we do want that for a new project. 
    #
    if ($newgroup->AddMemberShip($leader) < 0) {
	$newgroup->Delete();
	DBQueryWarn("delete from project_stats where pid_idx=$pid_idx");
	DBQueryWarn("delete from projects where pid_idx=$pid_idx");
	return undef;
    }
371 372 373 374

    #
    # Now create the per-project Admin List
    #
375
    if (0 && $MAILMANSUPPORT && !$nonlocal) {
376 377 378 379 380 381 382
	my $res = system("$ADDPROJADMINLIST $pid");
	if ($res != 0) {
	    SENDMAIL($TBOPS, "Addprojadminlist failed!", 
		     "\"$ADDPROJADMINLIST $pid\" failed.\n".
		     "Details most likely in testbed-logs mail with \"suexec: webnewproj\"\n".
		     "in the subject.\n");
	}
383 384
    }

385 386 387
    return $newproject;
}

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
#
# Delete newly added project, as for errors.
#
sub Delete($)
{
    my ($self) = @_;
    my $pid_idx = $self->pid_idx();
    my $group   = $self->GetProjectGroup();

    $group->Delete()
	if (!defined($group));
    
    DBQueryWarn("delete from project_stats where pid_idx=$pid_idx")
	or return -1;
    DBQueryWarn("delete from projects where pid_idx=$pid_idx")
	or return -1;

    return 0;
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421
#
# Equality test for two projects. Not necessary in perl, but good form.
#
sub SameProject($$)
{
    my ($self, $other) = @_;

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

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

422 423 424 425 426 427 428 429
#
# The basis of access permissions; what is the users trust level in the project
#
sub Trust($$)
{
    my ($self, $user) = @_;

    # Must be a real reference. 
430
    return PROJMEMBERTRUST_NONE()
431 432 433 434
	if (! ref($self));

    my $group = $self->GetProjectGroup();
    # Should not happen!
435
    return PROJMEMBERTRUST_NONE()
436 437 438 439 440
	if (!defined($group));

    return $group->Trust($user);
}

441 442 443 444 445 446
#
# Check permissions.
#
sub AccessCheck($$$)
{
    my ($self, $user, $access_type) = @_;
447 448
    my $mintrust;
    
449
    # Must be a real reference. 
450
    return 0
451 452
	if (! ref($self));

453 454 455 456
    my $group = $self->GetProjectGroup();
    # Should not happen!
    return 0
	if (!defined($group));
457

458
    return $group->AccessCheck($user, $access_type);
459 460
}

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
#
# Send newproject email; separate function so email can be resent.
#
sub SendNewProjectEmail($;$)
{
    my ($self, $firstproject) = @_;

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

    $firstproject = 0
	if (!defined($firstproject));

    my $leader             = $self->GetLeader();
    my $usr_uid            = $leader->uid();
    my $usr_idx            = $leader->uid_idx();
478
    my $usr_title	   = $leader->title() || "";
479 480 481
    my $usr_name	   = $leader->name();
    my $usr_affil	   = $leader->affil();
    my $usr_email	   = $leader->email();
482
    my $usr_addr	   = $leader->addr() || "";
483 484 485
    my $usr_addr2	   = $leader->addr2();
    my $usr_city	   = $leader->city();
    my $usr_state	   = $leader->state();
486
    my $usr_zip	           = $leader->zip() || "";
487
    my $usr_country        = $leader->country();
488
    my $usr_phone	   = $leader->phone() || "";
489 490 491 492
    my $usr_URL            = $leader->URL();
    my $wikiname           = $leader->wikiname();
    my $returning          = $leader->status() ne $User::USERSTATUS_NEWUSER;
    my $usr_returning      = ($returning ? "Yes" : "No");
493 494
    my $wanted_sslcert     = (defined($leader->initial_passphrase()) ?
			      "Yes" : "No");
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    my $proj_desc	   = $self->description();
    my $proj_URL           = $self->URL();
    my $proj_funders       = $self->funders();
    my $proj_public        = ($self->public() ? "Yes" : "No");
    my $proj_linked        = ($self->linked_to_us() ? "Yes" : "No");
    my $proj_whynotpublic  = $self->public_whynot();
    my $proj_members       = $self->num_members();
    my $proj_pcs           = $self->num_pcs();
    my $proj_plabpcs       = $self->num_pcplab();
    my $proj_ronpcs        = $self->num_ron();
    my $proj_why	   = $self->why();
    my $unix_gid           = $self->unix_gid();
    my $unix_name          = $self->unix_name();
    my $pid                = $self->pid();
    my $pid_idx            = $self->pid_idx();
    my $gid                = $self->pid();

    $usr_addr2 = ""
	if (!defined($usr_addr2));
    $usr_URL = ""
	if (!defined($usr_URL));
Leigh Stoller's avatar
Leigh Stoller committed
516 517
    $proj_whynotpublic = ""
	if (!defined($proj_whynotpublic));
518 519

    if ($returning || $firstproject) {
520
	SendProjAdminMail
521
	    ($self, "$usr_name '$usr_uid' <$usr_email>", "ADMIN",
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
	     "New Project '$pid' ($usr_uid)",
	     "'$usr_name' wants to start project '$pid'.\n".
	     "\n".
	     "Name:            $usr_name ($usr_uid/$usr_idx)\n".
	     "Project IDX:     $pid_idx\n".
	     "Returning User?: $usr_returning\n".
	     "Email:           $usr_email\n".
	     "User URL:        $usr_URL\n".
	     "Description:     $proj_desc\n".
	     "Project URL:     $proj_URL\n".
	     "Public URL:      $proj_public\n".
	     "Why Not Public:  $proj_whynotpublic\n".
	     "Link to Us?:     $proj_linked\n".
	     "Funders:         $proj_funders\n".
	     "Job Title:       $usr_title\n".
	     "Affiliation:     $usr_affil\n".
	     "Address 1:       $usr_addr\n".
	     "Address 2:       $usr_addr2\n".
	     "City:            $usr_city\n".
	     "State:           $usr_state\n".
	     "ZIP/Postal Code: $usr_zip\n".
	     "Country:         $usr_country\n".
	     "Phone:           $usr_phone\n".
545
	     "SSL Cert:        $wanted_sslcert\n".
546 547 548 549 550 551 552 553 554
	     "Members:         $proj_members\n".
	     "PCs:             $proj_pcs\n".
	     "Planetlab PCs:   $proj_plabpcs\n".
	     "RON PCs:         $proj_ronpcs\n".
	     "Unix GID:        $unix_name ($unix_gid)\n".
	     "Reasons:\n$proj_why\n\n".
	     "Please review the application and when you have made a \n".
	     "decision, go to $TBWWW and\n".
	     "select the 'Project Approval' page.");
555 556
    }
    else {
557
	SendProjAdminMail
558
	    ($self, "$usr_name '$usr_uid' <$usr_email>", "ADMIN",
559 560 561 562 563 564 565 566 567 568
	     "New Project '$pid' ($usr_uid)",
	     "'$usr_name' wants to start project '$pid'.\n".
	     "\n".
	     "Name:            $usr_name ($usr_uid/$usr_idx)\n".
	     "Project IDX:     $pid_idx\n".
	     "Email:           $usr_email\n".
	     "Returning User?: No\n".
	     "\n".
	     "No action is necessary until the user has verified the ".
	     "account.\n");
569
    }
570
    
571 572 573
    return 0;
}

574 575 576 577 578 579 580 581
#
# Return user object for leader.
#
sub GetLeader($)
{
    my ($self) = @_;

    # Must be a real reference. 
582
    return undef
583 584 585 586 587
	if (! ref($self));

    return User->Lookup($self->head_idx());
}

588 589 590 591 592 593 594 595 596 597 598 599 600 601
#
# Is the user the project leader.
#
sub IsLeader($$)
{
    my ($self, $user) = @_;

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

    return $user->SameUser($self->GetLeader());
}

602 603 604 605 606 607 608 609 610 611 612 613 614 615
#
# Return project group.
#
sub GetProjectGroup($)
{
    my ($self) = @_;

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

    return $self->{'GROUP'};
}

616 617 618 619 620 621 622
#
# Generate a URN.
#
sub urn($)
{
    my ($self) = @_;
    my $pid  = $self->pid();
623

624 625 626 627 628
    return undef
	if (!$PGENISUPPORT);
    require GeniHRN;

    my $domain = "${OURDOMAIN}:${pid}";
629 630 631 632 633 634 635 636 637 638 639 640 641 642
    return GeniHRN->new(GeniHRN::Generate($domain, "project", $pid));
}
sub nonlocalurn($)
{
    my ($self) = @_;
    
    return undef
	if (!$PGENISUPPORT);
    require GeniHRN;

    if ($self->IsNonLocal()) {
	return GeniHRN->new($self->nonlocal_id());
    }
    return $self->urn();
643 644
}

645 646 647 648 649 650 651 652 653 654 655 656 657 658
#
# Return membership for user in the default group
#
sub LookupUser($$)
{
    my ($self, $user) = @_;

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

    return $self->{'GROUP'}->LookupUser($user);
}

659
#
660
# Change the leader for a project.
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
#
sub ChangeLeader($$)
{
    my ($self, $leader) = @_;

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

    # Default group fits.
    $self->{'GROUP'}->ChangeLeader($leader) == 0
	or return -1;

    # Then the project
    my %args = ();
    $args{'head_uid'} = $leader->uid();
    $args{'head_idx'} = $leader->uid_idx();
    return $self->Update(\%args);
}

#
# Set the approval bit,
#
sub SetApproved($$)
{
    my ($self, $approved) = @_;

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

    my %args = ("approved" => ($approved ? 1 : 0));
    return $self->Update(\%args);
}

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 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
#
# Delete a user from the project (and all subgroups of course). No checks
# are made; that should be done higher up. Optionally return list of groups
# from which the user was deleted.
#
sub DeleteUser($$;$)
{
    my ($self, $user, $plist) = @_;
    my @grouplist = ();

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

    my $uid_idx = $user->uid_idx();
    my $pid_idx = $self->pid_idx();
    my $gid_idx = $pid_idx;

    # Need a list of all groups for the user in this project.
    # Should probably use a "class" method in the Groups module.
    my $query_result =
	DBQueryWarn("select gid_idx from group_membership ".
		    "where pid_idx=$pid_idx and uid_idx=$uid_idx");
    return -1
	if (! $query_result);
    return 0
	if (! $query_result->numrows);

    while (my ($idx) = $query_result->fetchrow_array()) {
	# Do main group last.
	next
	    if ($idx == $gid_idx);

	my $group = Group->Lookup($idx);
	return -1
	    if (!defined($group));

	return -1
	    if ($group->DeleteMemberShip($user) < 0);

	push(@grouplist, $group);
    }

    my $group = Group->Lookup($gid_idx);
    return -1
	if (!defined($group));

    return -1
	if ($group->DeleteMemberShip($user) < 0);

    if (defined($plist)) {
	@$plist = (@grouplist, $group);
    }
    return 0;
}

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
#
# List of subgroups for a project member (not including default group).
#
sub GroupList($$)
{
    my ($self, $plist) = @_;
    my @grouplist = ();

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

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

    my $query_result =
	DBQueryWarn("select gid_idx from groups ".
		    "where pid_idx=$pid_idx and pid_idx!=gid_idx");
    return -1
	if (! $query_result);
    
    return 0
	if (! $query_result->numrows);

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $group = Group->Lookup($idx);
	return -1
	    if (!defined($group));

	push(@grouplist, $group);
    }
    @$plist = @grouplist;
    return 0;
}

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
#
# Find specific group in project.
#
sub LookupGroup($$)
{
    my ($self, $gid) = @_;
    my @grouplist = ();

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

    my $pid_idx = $self->pid_idx();
    my $clause;

    if ($gid =~ /^\d*$/) {
	$clause = "gid_idx='$gid'";
    }
    elsif ($gid =~ /^[-\w]*$/) {
	$clause = "gid='$gid'";
    }
    else {
	return undef;
    }

    my $query_result =
	DBQueryWarn("select gid_idx from groups ".
		    "where pid_idx=$pid_idx and $clause");
    return undef
	if (! $query_result);
    
    return undef
	if (! $query_result->numrows);

    my ($gid_idx) = $query_result->fetchrow_array();
    return Group->Lookup($gid_idx);
}

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
#
# Update the aggregate stats.
#
sub UpdateStats($$$$$)
{
    my ($self, $mode, $duration, $pnodes, $vnodes) = @_;
	
    # Must be a real reference. 
    return -1
	if (! ref($self));

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

    DBQueryWarn("update project_stats ".
		"set expt${mode}_count=expt${mode}_count+1, ".
		"    expt${mode}_last=now(), ".
		"    allexpt_duration=allexpt_duration+${duration}, ".
		"    allexpt_vnodes=allexpt_vnodes+${vnodes}, ".
		"    allexpt_pnodes=allexpt_pnodes+${pnodes}, ".
		"    allexpt_vnode_duration=".
		"        allexpt_vnode_duration+($vnodes * ${duration}), ".
		"    allexpt_pnode_duration=".
		"        allexpt_pnode_duration+($pnodes * ${duration}) ".
		"where pid_idx='$pid_idx'");

849
    if ($mode eq TBDB_STATS_SWAPIN() || $mode eq TBDB_STATS_START()) {
850 851 852 853 854 855 856 857 858 859
	DBQueryWarn("update projects set ".
		    " expt_last=now(),expt_count=expt_count+1 ".
		    "where pid_idx='$pid_idx'");
    }

    $self->Refresh();

    return 0;
}

860 861 862 863 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
#
# Return last activity as a unix timestamp.
#
sub GetActivity($)
{
    my ($self) = @_;
    my $stamp;

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

    my $pid_idx = $self->pid_idx();
    my $query_result =
	DBQueryWarn("select UNIX_TIMESTAMP(last_activity) from project_stats ".
		    "where pid_idx='$pid_idx'");
    if ($query_result->numrows) {
	($stamp) = $query_result->fetchrow_array();
    }

    return $stamp;
}

sub SetActivity($$)
{
    my ($self,$stamp) = @_;
	
    # Must be a real reference. 
    return -1
	if (! ref($self));

    if ($stamp !~ /^\d+$/ || $stamp < 0 || $stamp > time()) {
	return -1;
    }

    my $pid_idx = $self->pid_idx();
    DBQueryWarn("update project_stats set last_activity=FROM_UNIXTIME($stamp)".
		" where pid_idx='$pid_idx'");

    return 0;
}

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
#
# Bump last activity
#
sub BumpActivity($)
{
    my ($self) = @_;
	
    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $pid_idx = $self->pid_idx();
    
    DBQueryWarn("update project_stats set last_activity=now() ".
		"where pid_idx='$pid_idx'");

    return 0;
}

921 922 923 924 925 926 927 928 929 930 931 932
#
# Check to see if a pid is valid.
#
sub ValidPID($$)
{
    my ($class, $pid) = @_;

    return TBcheck_dbslot($pid, "projects", "newpid",
			  TBDB_CHECKDBSLOT_WARN()|
			  TBDB_CHECKDBSLOT_ERROR());
}

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
#
# Add a user to the Project
#
sub AddMemberShip($$;$)
{
    my ($self, $user, $trust) = @_;

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

    my $membership = $self->LookupUser($user);

    if (defined($membership)) {
	print "*** AddMemberShip: $user is already a member of $self!\n";
	return -1;
    }
    return $self->{'GROUP'}->AddMemberShip($user, $trust);    
}

#
# Return group_exports info, as a plain hash.
#
sub PeerExports($$)
{
    my ($self, $pref) = @_;

    return $self->{'GROUP'}->PeerExports($pref);
}

963 964 965 966 967 968 969 970 971 972 973
#
# Do an exports setup if needed (ZFS). See exports_setup, when ZFS is on
# we do not export all projects, only recently active ones. 
#
sub UpdateExports($)
{
    my ($self) = @_;
    my $pid_idx = $self->pid_idx();

    return 0
	if (! ($WITHZFS && ($ZFS_NOEXPORT || !$WITHAMD)));
974 975 976
    my $exports_limit = GetSiteVar("general/export_active");
    return 0
	if (!$exports_limit);
977 978 979 980 981 982 983 984 985 986

    my $query_result =
	DBQueryWarn("select UNIX_TIMESTAMP(last_activity) from project_stats ".
		    "where pid_idx='$pid_idx'");
    # Hmm.
    return 0
	if (!$query_result->numrows);

    my ($lastactivity) = $query_result->fetchrow_array();

987 988 989 990 991 992 993 994
    # Update last_activity first so exports_setup will do something
    # and to mark the project as active, to keep the mount active.
    DBQueryWarn("update project_stats set last_activity=now() ".
		"where pid_idx='$pid_idx'")
	or return -1;

    if (!defined($lastactivity) ||
	time() - $lastactivity > ((($exports_limit * 24) - 12) * 3600)) {
995 996 997 998 999 1000 1001 1002
	if ($ZFS_NOEXPORT) {
	    mysystem($EXPORTS_SETUP);
	}
	elsif (!$WITHAMD) {
	    mysystem($EXPORTS_SETUP . " -B");
	}

	# failed, reset the timestamp
1003 1004 1005 1006 1007
	if ($?) {
	    my $set = (defined($lastactivity) ?
		       "FROM_UNIXTIME($lastactivity)" : "null");
	    
	    DBQueryWarn("update project_stats set last_activity=$set ".
1008 1009 1010 1011 1012 1013 1014
			"where pid_idx='$pid_idx'");
	    return -1;
	}
    }
    return 0;
}

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
#
# Return usage records for experiments that have terminated (were running)
# between two dates.
#
sub Usage($$$)
{
    my ($self, $start, $end) = @_;
    my $pid_idx = $self->pid_idx();
    my @results = ();

    my $query_result =
1026
	DBQueryWarn("(select e.eid,s.rsrcidx,s.nonlocal_id,s.slice_uuid, ".
1027
		    "       s.nonlocal_user_id, ".
1028 1029
		    "       UNIX_TIMESTAMP(s.swapin_last),0,".
		    "       e.swapper_idx,n.type,count(n.type) ".
1030 1031 1032 1033 1034 1035
		    " from experiments as e ".
		    "left join experiment_stats as s on ".
		    "     s.exptidx=e.idx  ".
		    "left join reserved as r on r.exptidx=e.idx ".
		    "left join nodes as n on n.node_id=r.node_id ".
		    "where e.pid_idx='$pid_idx' and e.state='active' ".
1036
		    "      and UNIX_TIMESTAMP(s.swapin_last) < $end ".
1037
		    "group by e.eid,s.rsrcidx,s.nonlocal_id,s.slice_uuid, ".
1038
		    "         s.nonlocal_user_id, ".
1039 1040
		    "         UNIX_TIMESTAMP(s.swapin_last), ".
		    "         e.swapper_idx,n.type ".
Leigh Stoller's avatar
Leigh Stoller committed
1041
		    "order by s.swapin_last desc) ".
1042 1043
		    "union ".
		    "(select s.eid,r.idx,s.nonlocal_id,s.slice_uuid, ".
1044
		    "       s.nonlocal_user_id, ".
1045 1046
		    "       r.swapin_time,r.swapout_time, ".
		    "       h.uid_idx,n.type,count(n.type) ".
1047 1048 1049
		    "  from experiment_resources as r ".
		    "left join experiment_stats as s on ".
		    "     s.exptidx=r.exptidx  ".
Leigh Stoller's avatar
Leigh Stoller committed
1050 1051
		    "left join experiments as e on ".
		    "     e.idx=r.exptidx  ".
1052 1053 1054 1055 1056 1057 1058
		    "left join node_history as h on ".
		    "     h.exptidx=r.exptidx and h.op='alloc' and ".
		    "     h.stamp >= r.swapin_time - 120 and ".
		    "     (r.swapout_time=0 or ".
		    "      h.stamp < r.swapout_time) ".
		    "left join nodes as n on n.node_id=h.node_id ".
		    "where s.pid_idx='$pid_idx' and ".
Leigh Stoller's avatar
Leigh Stoller committed
1059
		    "     r.swapin_time!=0 and r.swapout_time!=0 and ".
1060 1061 1062
		    "    ((r.swapin_time >= $start and ".
		    "      r.swapin_time <= $end) or ".
		    "     (r.swapout_time > $start and ".
1063
		    "      r.swapout_time < $end)) ".
1064
		    "group by s.eid,r.idx,s.nonlocal_id,s.slice_uuid, ".
1065
		    "         s.nonlocal_user_id, ".
1066 1067
		    "         r.swapin_time,r.swapout_time, ".
		    "         h.uid_idx,n.type ".
1068 1069
		    "order by r.swapin_time desc) "
	);
1070 1071 1072 1073 1074 1075 1076

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

    my @summary = ();
    my $lastin  = 0;

1077
    while (my ($eid,$idx,$urn,$slice_uuid,$user_urn,
1078
	       $swapin_time,$swapout_time,$swapper_idx,$type,$count) =
1079
	   $query_result->fetchrow_array()) {
1080 1081 1082 1083
	# In the emulab-ops project, we nalloc nodes to experiments that
	# have never been swapped in (like hwdown).
	next
	    if (!defined($swapin_time));
1084 1085 1086
	# No phys nodes.
	next
	    if ($count == 0 || !defined($type));
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
	my ($swapper_urn, $swapper_uid, $user);
	#
	# A slice created by a local user uses the real local user identity,
	# but for a nonlocal user we have to find nonlocal identity.
	#
	if (defined($slice_uuid)) {
	    require GeniHRN;
	    my $hrn = GeniHRN->new($user_urn);
	    if ($hrn->domain() eq $OURDOMAIN) {
		$user = User->Lookup($hrn->id());
	    }
	    else {
		$user = User->LookupNonLocal($user_urn);
	    }
	}
	else {
	    $user = User->Lookup($swapper_idx);
	}
1106 1107 1108 1109
	if (defined($user)) {
	    $swapper_urn = $user->nonlocalurn()->asString();
	    $swapper_uid = $user->uid();
	}
1110
	
1111 1112 1113 1114
	# The order by clause is important.
	if ($swapin_time != $lastin) {
	    unshift(@summary, {"eid"    => $eid,
			       "urn"    => $urn || "",
1115
			       "slice_uuid" => $slice_uuid || "",
1116 1117
			       "start"  => $swapin_time,
			       "end"    => $swapout_time || "",
1118 1119
			       "user_uid" => $swapper_uid,
			       "user_urn" => $swapper_urn,
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
			       "types"  => {$type => {"count"  => $count}}});
	    $lastin = $swapin_time;
	    next;
	}
	my $blob = $summary[0];
	$blob->{"types"}->{$type} = {"count" => $count};
    }
    return \@summary;
}

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
#
# Return count of how many nodes of a type in use.
#
sub TypeInUseCount($$)
{
    my ($self, $type) = @_;
    my $pid = $self->pid();

    my $result =
	DBQueryWarn("select count(n.type) from reserved as r ".
		    "left join nodes as n on n.node_id=r.node_id ".
		    "where pid='$pid' and type='$type' ".
		    "group by type");
    return 0
	if (!defined($result) || !$result->numrows);

    my ($count) = $result->fetchrow_array();
    return $count;
}

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