Quota.pm 12.4 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2012-2016 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 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
# 
# {{{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/>.
# 
# }}}
#
package Quota;

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

@ISA    = "Exporter";
@EXPORT = qw ( );

use libdb;
use libtestbed;
use EmulabConstants;
use User;
use Group;
use Project;
use English;
use Date::Parse;
use Data::Dumper;
use overload ('""' => 'Stringify');

my @QUOTA_TYPES  = ("ltdataset",);
45
my $MAXQUOTASIZE = 1024 * 1024 * 1024; # 1 pebibyte
46
my $UNLIMITED    = -1;
47

48
# cache of instances to avoid regenerating them.
49
my %quotas	= ();
50
BEGIN { use emutil; emutil::AddCache(\%quotas); }
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
my $debug	= 0;

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

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

#
# Accessors
#
sub idx($)             {return $_[0]->{'DBROW'}->{'quota_idx'}; }
sub quota_idx($)       {return $_[0]->idx(); }
sub quota_id($)        {return $_[0]->{'DBROW'}->{'quota_id'}; }
sub pid($)             {return $_[0]->{'DBROW'}->{'pid'}; }
sub type($)            {return $_[0]->{'DBROW'}->{'type'}; }
sub size($)            {return $_[0]->{'DBROW'}->{'size'}; }
sub notes($)           {return $_[0]->{'DBROW'}->{'notes'}; }
sub last_update($)     {return str2time($_[0]->{'DBROW'}->{'last_update'}); }

#
# Lookup a quota in the DB and return an object representing it.
#
sub Lookup($$;$)
{
    my ($class, $pid, $quota_id) = @_;
    my ($wclause);

    # Determine how we were called.  If only a single parameter was passed
    # to the method, then it should be a quota index.  If both are passed in,
    # then they are what their variable names imply.
    if (!defined($quota_id)) {
	my $idx = $pid;
	if ($idx !~ /^\d+$/) {
	    print STDERR "Quota->Lookup: single parameter to call must be a numeric index.\n";
	    return undef;
	}
	# Look in cache first
	return $quotas{$idx}
	    if (exists($quotas{$idx}));

	$wclause = "quota_idx=$idx";
    } else {
	# Look in cache first
	return $quotas{"$pid:$quota_id"}
	    if (exists($quotas{"$pid:$quota_id"}));

	$wclause = "pid='$pid' and quota_id='$quota_id'";
    }

    my $self              = {};
106 107
    $self->{"LOCKED"}     = 0;
    $self->{"LOCKER_PID"} = 0;
108 109 110 111 112 113 114 115 116 117 118 119

    # Load quota from DB, if it exists. Otherwise, return undef.
    my $query_result =
	DBQueryWarn("select * from project_quotas where $wclause");

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

    $self->{'DBROW'} = $query_result->fetchrow_hashref();;
    bless($self, $class);

    # Add to cache (dual lookup).
120
    $quotas{$self->pid() .":". $self->quota_id()} = $self;
121 122 123 124 125 126 127 128 129
    $quotas{$self->idx()} = $self;
    return $self;
}

#
# Force a reload of the data.
#
sub LookupSync($$;$) {
    my ($class, $pid, $quota_id) = @_;
130
    my ($quota_idx, $qpid);
131 132 133 134

    if (!defined($quota_id)) {
	$quota_idx = $pid;
	if (exists($quotas{$quota_idx})) {
135
	    $qpid = 
136
		$quotas{$quota_idx}->pid() .":". 
137 138 139
		$quotas{$quota_idx}->quota_id();
	}
    } else {
140 141 142
	$qpid = "$pid:$quota_id";
	if (exists($quotas{$qpid})) {
	    $quota_idx = $quotas{$qpid}->idx();
143 144 145 146 147 148
	}
    }

    # delete from cache
    delete($quotas{$quota_idx})
        if (defined($quota_idx) && exists($quotas{$quota_idx}));
149 150
    delete($quotas{$qpid})
        if (defined($qpid) && exists($quotas{$qpid}));
151 152 153 154 155 156 157 158 159 160

    return Lookup($class, $quota_idx);
}

#
# explicit object destructor to ensure we get rid of circular refs.
#
sub DESTROY($) {
    my ($self) = @_;

161 162
    $self->{'LOCKED'} = undef;
    $self->{'LOCKER_PID'} = undef;
163 164 165 166 167 168
    $self->{'DBROW'} = undef;
}

#
# Create a new quota.
#
169 170
sub Create($$) {
    my ($class, $argref) = @_;
171 172 173 174 175 176 177 178 179 180 181 182

    my ($quota_id, $pid, $type, $size, $notes);

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

    $quota_id  = $argref->{'quota_id'};
    $pid       = $argref->{'pid'};
    $type      = $argref->{'type'};
    $size      = $argref->{'size'};
    $notes     = $argref->{'notes'} || "";
    
183
    if (!($quota_id && $pid && $type && defined($size))) {
184 185 186 187 188 189 190
	print STDERR "Quota->Create: Missing required parameters in argref\n";
	return undef;
    }

    # Sanity checks for incoming arguments
    if (!TBcheck_dbslot($quota_id, "project_quotas", "quota_id")) {
	print STDERR "Quota->Create: Bad data for quota id: ". 
191
	    TBFieldErrorString() ."\n";
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
	return undef;
    }

    if (ref($pid) ne "Project") {
	my $npid = Project->Lookup($pid);
	if (!defined($npid)) {
	    print STDERR "Quota->Create: Bad/Unknown project: $pid\n";
	    return undef;
	}
	$pid = $npid;
    }
    
    # If quota types ever grow to be many and complex, then this info will
    # have to come from a DB table instead of a static list in this module.
    if (!grep {/^$type$/} @QUOTA_TYPES) {
	print STDERR "Quota->Create: Unknown quota type: $type\n";
	return undef;
    }

    # XXX: quota size limits should be changeable via sitevar.
    if ($size !~ /^\d+$/) {
	print "Quota->Create: Invalid quota size: $size\n";
	return undef;
    }
216 217
    if ($size < 0 || $size > $MAXQUOTASIZE) {
	print STDERR "Quota->Create: Quota is either negative or too big ($MAXQUOTASIZE).\n";
218 219 220 221 222 223 224 225
	return undef;
    }

    # If present, make sure the note is not too outrageously long.
    my $safe_notes;
    if (defined($notes) && $notes) {
	if (!TBcheck_dbslot($notes, "project_quotas", "notes")) {
	    print STDERR "Quota->Create: Bad data in notes: ".
226
		TBFieldErrorString() ."\n";
227 228 229 230
	    return undef;
	}
	$safe_notes = DBQuoteSpecial($notes);	
    } else {
231
	$safe_notes = "NULL";
232 233 234 235 236 237 238 239 240 241 242
    }

    # Get a unique quota index and slam this stuff into the DB.
    my $quota_idx = TBGetUniqueIndex('next_quotaidx');

    DBQueryWarn("insert into project_quotas set ".
		"quota_idx=$quota_idx,".
		"quota_id='$quota_id',".
		"pid='". $pid->pid() ."',".
		"type='$type',".
		"size=$size,".
243
		"notes=$safe_notes")
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
	or return undef;

    return Lookup($class, $pid->pid(), $quota_id);
}

#
# Delete an existing quota.
#
sub Delete($) {
    my ($self) = @_;

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

    my $idx  = $self->idx();
259
    my $qpid = $self->pid() .":". $self->quota_id();
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 329 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 361 362 363 364 365 366

    DBQueryWarn("delete from project_quotas where quota_idx=$idx")
	or return -1;
    
    delete($quotas{$idx})
	if (exists($quotas{$idx}));
    delete($quotas{$qpid})
	if (exists($quotas{$qpid}));

    return 0
}

#
# Return a list of all quotas belonging to a particular project.
#
sub AllProjectQuotas($$)
{
    my ($class, $pid)  = @_;
    my @pquotas = ();
    
    return undef
	if !defined($pid);

    if (ref($pid) eq "Project") {
	$pid = $pid->pid();
    }
    
    my $query_result =
	DBQueryWarn("select quota_id from project_quotas where pid='$pid'");
    
    return ()
	if (!$query_result || !$query_result->numrows);

    while (my ($quota_id) = $query_result->fetchrow_array()) {
	my $quota = Lookup($class, $pid, $quota_id);

	# Something went wrong?
	return ()
	    if (!defined($quota));
	
	push(@pquotas, $quota);
    }
    return @pquotas;
}

#
# Update fields in the project_quotas table, as requested.
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

    my $idx = $self->idx();
    my @sets   = ();

    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};

	# Don't let caller update the quota's index - that would be bad.
	return -1
	    if ($key eq "quota_idx");

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

    my $query = "update project_quotas set " . join(",", @sets) .
	" where quota_idx='$idx'";

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

    return Refresh($self);
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

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

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

    my $query_result =
	DBQueryWarn("select * from project_quotas ".
		    " where quota_idx='$idx'");

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

    $self->{"DBROW"}    = $query_result->fetchrow_hashref();

    return 0;
}

#
# Update the notes for a quota entry.
#
367
sub SetNotes($$) {
368 369 370 371 372 373 374 375 376 377
    my ($self, $notes) = @_;

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

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

    if (!TBcheck_dbslot($notes, "project_quotas", "notes")) {
	print STDERR "Quota->UpdateNotes: Bad data in notes: ".
378
	    TBFieldErrorString() ."\n";
379 380 381 382 383
	return -1;
    }
    my $safe_notes = DBQuoteSpecial($notes);	

    my $idx = $self->idx();
384
    DBQueryWarn("update project_quotas set notes=$safe_notes ".
385 386 387
		"where quota_idx=$idx")
	or return -1;

388
    $self->Refresh();
389 390 391 392 393 394 395 396 397 398 399 400
    return 0;
}

#
# Add space to an existing quota
#
sub IncreaseSize($$) {
    my ($self, $incr) = @_;

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

401 402 403 404 405 406
    my $cursize = $self->size();
    if ($cursize == $UNLIMITED) {
	print STDERR "Quota->IncreaseSize: quota is currently unlimited.\n";
	return -1;
    }
    if ($incr < 0 || $cursize + $incr > $MAXQUOTASIZE) {
407
	print STDERR "Quota->IncreaseSize: Size increment is either negative or the new total is too big ($MAXQUOTASIZE).\n";
408 409 410 411
	return -1
    }

    my $idx = $self->idx();
412
    my $newsize = $cursize + $incr;
413 414 415
    DBQueryWarn("update project_quotas set size=$newsize where quota_idx=$idx")
	or return -1;

416
    $self->Refresh();
417 418 419
    return 0;
}

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
#
# Make checking/setting a quota for/to "unlimited" an explicit operation
# so that we can change how we implement this as necessary.
# Right now, a size of -1 means unlimited.
#
sub IsUnlimited($)
{
    my ($self) = @_;

    return 0
	if (!ref($self));
    return ($self->size == $UNLIMITED);
}

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

    return -1
	if (!ref($self));
    my $idx = $self->idx();
    my $size = $UNLIMITED;
    DBQueryWarn("update project_quotas set size=$size where quota_idx=$idx")
	or return -1;

    $self->Refresh();
    return 0;
}

449 450 451 452 453 454 455 456 457
#
# Set a specific quota size.
#
sub SetSize($$) {
    my ($self, $size) = @_;

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

458 459
    if ($size < 0 || $size > $MAXQUOTASIZE) {
	print STDERR "Quota->SetSize: Size is either negative or too big ($MAXQUOTASIZE).\n";
460 461 462 463 464 465 466
	return -1
    }

    my $idx = $self->idx();
    DBQueryWarn("update project_quotas set size=$size where quota_idx=$idx")
	or return -1;

467
    $self->Refresh();
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    return 0;
}

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

    return "[Quota: $pid/$quota_id/${size}MiB]";
}

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
#
# Lock and Unlock
#
sub Lock($)
{
    my ($self) = @_;

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

    # Already locked?
    if ($self->GotLock()) {
	return 0;
    }

    return -1
	if (!DBQueryWarn("lock tables project_quotas write"));

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

    my $query_result =
	DBQueryWarn("update project_quotas set locked=now(),locker_pid=$PID " .
		    "where quota_idx=$idx and locked is null");

    if (! $query_result ||
	$query_result->numrows == 0) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    DBQueryWarn("unlock tables");
    $self->{'LOCKED'} = time();
    $self->{'LOCKER_PID'} = $PID;
    return 0;
}

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

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

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

    return -1
	if (! DBQueryWarn("update project_quotas set locked=null,locker_pid=0 " .
			  "where quota_idx=$idx"));
    
    $self->{'LOCKED'} = 0;
    $self->{'LOCKER_PID'} = 0;
    return 0;
}

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

    return 1
	if ($self->{'LOCKED'} &&
	    $self->{'LOCKER_PID'} == $PID);
    
    return 0;
}

#
# Wait to get lock.
#
sub WaitLock($$)
{
    my ($self, $seconds) = @_;

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

    while ($seconds > 0) {
	return 0
	    if ($self->Lock() == 0);

	# Sleep and try again.
	sleep(5);
	$seconds -= 5;
    }
    # One last try.
    return $self->Lock();
}

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

1;