emutil.pm.in 26 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2019 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 28
#
# Utility routines for Emulab.
#
package emutil;
use strict;
use Exporter;
29
use SelfLoader;
30
use vars qw(@ISA @EXPORT);
31 32 33
@ISA = qw(Exporter SelfLoader);
@EXPORT = qw(TBDB_CHECKDBSLOT_NOFLAGS TBDB_CHECKDBSLOT_WARN
	     TBDB_CHECKDBSLOT_ERROR TBcheck_dbslot TBFieldErrorString
34
	     TBGetUniqueIndex ParRun VersionInfo UpdateVersionInfo
35
	     SpanningTree GenFakeMac BackTraceOnWarning PassWordHash
36 37
             SSHwithTimeout TBDateStringGMT TBDateStringLocal TBDateStringUTC
	     runBusyLoop
38
	     MapEventType MapEventObjectType MapEventTriggerType ValidUUID
39
);
40

41
use emdb;
42
use English;
43
use Carp;
44
use Date::Parse;
45
use Time::Local;
46
use Data::Dumper;
47
use POSIX qw(:signal_h);
48

49
# Configure variables.
50 51
my $TB           = "@prefix@";
my $OPSVM_ENABLE = @OPSVM_ENABLE@;
52
my $WITHZFS      = @WITHZFS@;
53
my $CHFLAGS      = "/bin/chflags";
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#
# Store up the list of caches to flush
#
my @ourcaches = ();

sub AddCache($)
{
    my ($ref) = @_;

    push(@ourcaches, $ref);
}
sub FlushCaches()
{
    foreach my $ref (@ourcaches) {
	%$ref = ();
    }
}
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
sub DumpCaches()
{
    require Devel::Size;

    my $total = 0;
    foreach my $cache (@ourcaches) {
	my $subtotal = 0;
	my @values = values(%{$cache});
	next
	    if (!@values);
	print STDERR "Dumping cache:\n";
	foreach my $ref (@values) {
	    my $size = Devel::Size::total_size($ref);
	    
	    print STDERR " $ref: $size\n";
	    $subtotal += $size;
	    $total += $size;
	}
	my $realsize = Devel::Size::total_size($cache);
	print STDERR "Cache total: $subtotal, $realsize\n";
    }
     if ($total) {
	my $realsize = Devel::Size::total_size(\@ourcaches);
	print STDERR "All caches total: $total, $realsize\n";
    }
}
98

99 100 101 102
#
# Support for checking field values against what is specified.
#
use vars qw(%DBFieldData $DBFieldErrstr);
103

104 105 106
%DBFieldData   = ();
$DBFieldErrstr = "";

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
#
# A helper function for checking lossrates. Bad place for this, I know.
# Needs to be before the __DATA__ cause we used defined() on it. Sigh.
#
sub _checklossrate($)
{
    my ($token) = @_;

    return 1
	if ("$token" eq "0");

    # floating point, no exponent. Stole this out of the perl tutorial.
    if (! ($token =~ /^[+-]?(\d+\.\d+|\d+\.|\.\d+)([eE][+-]?\d+)?$/)) {
	$DBFieldErrstr = "Improper floating number";
	return 0;
    }
    if ($token > 1.0) {
	$DBFieldErrstr = "Too big; must be < 1.0";
	return 0;
    }
    if ($token < 0.0) {
	$DBFieldErrstr = "Too small; must be > 0.0";
	return 0;
    }
    if ($token > 0.0 && $token < 0.000001) {
	$DBFieldErrstr = "Too small; must be >= 0.000001";
	return 0;
    }
    return 1;
}

138
1;
139
@SELFLOADER_DATA@
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

# Constants for checkslot code.
sub TBDB_CHECKDBSLOT_NOFLAGS()	{ 0x0; }
sub TBDB_CHECKDBSLOT_WARN()	{ 0x1; }
sub TBDB_CHECKDBSLOT_ERROR()	{ 0x2; }

sub TBFieldErrorString() { return $DBFieldErrstr; }

#
# Download all data from the DB and store in hash for latter access.
#
sub TBGrabFieldData()
{
    %DBFieldData = ();

    my $query_result =
156
	emdb::DBQueryFatal("select * from table_regex");
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

    while (my %row = $query_result->fetchhash()) {
	my $table_name  = $row{"table_name"};
	my $column_name = $row{"column_name"};

	$DBFieldData{$table_name . ":" . $column_name} =
	    { "check"       => $row{"check"},
	      "check_type"  => $row{"check_type"},
	      "column_type" => $row{"column_type"},
	      "min"         => $row{"min"},
	      "max"         => $row{"max"}
	    };
    }
}

#
# Return the field data for a specific table/slot. If none, return the default
# entry.
#
# The top level entry defines some stuff that is not to be overidden by the
# redirected entries. For example, the top level entry is the only place we
# can specify a field is optional when inserting a record. We could do this
# with default entries in the DB table defintion, but I do not like that idea.
# The min/max lengths also override, unless they are both zero in which case
# let the first non-zero defs set them.
#
sub TBFieldData($$;$)
{
    my ($table, $column, $flag) = @_;
    my $toplevel;
    my $fielddata;

    if (! %DBFieldData) {
	TBGrabFieldData();
    }
    my $key = $table . ":" . $column;

    while (exists($DBFieldData{$key})) {
	$fielddata = $DBFieldData{$key};

	#
	# See if a redirect to another entry.
	#
	if ($fielddata->{"check_type"} eq "redirect") {
	    if (!defined($toplevel)) {
		$toplevel = $fielddata;
	    }

	    $key = $fielddata->{"check"};
#	    print STDERR "Redirecting to $key for $table/$column!\n";
	    next;
	}
	last;
    }
    # Resort to a default entry.
    if (!defined($fielddata)) {
	$DBFieldErrstr = "Error-checking pattern missing from the database";
	
	if (defined($flag)) {
	    if ($flag & TBDB_CHECKDBSLOT_WARN()) {
		print STDERR "*** $0:\n" .
		             "    WARNING: No slot data for $table/$column!\n";
	    }
	    return undef
		if ($flag & TBDB_CHECKDBSLOT_ERROR());
	}
	$fielddata = $DBFieldData{"default:default"};
    }
    # Return both entries.
    if (defined($toplevel) &&
	($toplevel->{"min"} || $toplevel->{"max"})) {
	return ($fielddata, $toplevel);
    }
    return ($fielddata);
}

#
# Generic wrapper to check a slot.
#
sub TBcheck_dbslot($$$;$)
{
    my ($token, $table, $column, $flag) = @_;
    
    $DBFieldErrstr = "Unknown Error";

    my ($fielddata,$toplevel) = TBFieldData($table, $column, $flag);

    return 0
	if (!defined($fielddata));

    my $check       = $fielddata->{"check"};
    my $check_type  = $fielddata->{"check_type"};
    my $column_type = $fielddata->{"column_type"};
    my $min         = (defined($toplevel) ?
		       $toplevel->{"min"} : $fielddata->{"min"});
    my $max         = (defined($toplevel) ?
		       $toplevel->{"max"} : $fielddata->{"max"});

#    print STDERR "Using $check/$check_type/$column_type/$min/$max for ".
#	"$table/$column\n";

    #
259
    # Functional checks partly implemented. Needs work.
260 261
    #
    if ($check_type eq "function") {
262 263 264 265 266 267
	if (defined(&$check)) {
	    my $func = \&$check;
	    return &$func($token);   
	}
	else {
	    die("*** $0:\n" .
268 269
		"    Functional DB check not implemented: ".
		"$table/$column/$check\n");
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
    }

    # Make sure the regex is anchored. Its a mistake not to be!
    $check = "^" . $check
	if (! ($check =~ /^\^/));

    $check = $check . "\$"
	if (! ($check =~ /\Q$/));

    # Check regex.
    if (! ("$token" =~ /$check/)) {
	$DBFieldErrstr = "Illegal Characters";
	return 0;
    }

    # Check min/max.
    if ($column_type eq "text") {
	my $len = length($token);

	# Any length is okay if no min or max. 
	return 1
	    if ((!($min || $max)) ||
		($len >= $min && $len <= $max));
	$DBFieldErrstr = "Too Short"
	    if ($min && $len < $min);
	$DBFieldErrstr = "Too Long"
	    if ($max && $len > $max);
    }
    elsif ($column_type eq "int" ||
	   $column_type eq "float") {
	# If both min/max are zero, then skip check; allow anything.
	return 1
	    if ((!($min || $max)) || ($token >= $min && $token <= $max));
	$DBFieldErrstr = "Too Small"
	    if ($min && $token < $min);
	$DBFieldErrstr = "Too Big"
	    if ($max && $token > $max);
    }
    else {
	die("*** $0:\n" .
	    "    Unrecognized column_type $column_type\n");
    }
    return 0;
}

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
#
# Return a unique index from emulab_indicies for the indicated name.
# Updates the index to be, well, unique.
# Eats flaming death on error.
#
# WARNING: this will unlock all locked tables, be careful where you call it!
#
sub TBGetUniqueIndex($;$$)
{
    my ($name, $initval, $nolock) = @_;

    #
    # Lock the table to avoid conflict, but not if the caller already did it.
    #
    $nolock = 0
	if (!defined($nolock));
    
    DBQueryFatal("lock tables emulab_indicies write")
	if (!$nolock);

    my $query_result =
	DBQueryFatal("select idx from emulab_indicies ".
		     "where name='$name'");
    my ($curidx) = $query_result->fetchrow_array();
    if (!defined($curidx)) {
	$curidx = (defined($initval) ? $initval : 1);
    }
    my $nextidx = $curidx + 1;

    DBQueryFatal("replace into emulab_indicies (name, idx) ".
		 "values ('$name', $nextidx)");
    DBQueryFatal("unlock tables")
	if (!$nolock);

    return $curidx;
}

353 354 355 356 357 358 359 360 361 362 363 364 365
#
# A utility function for forking off a bunch of children and
# waiting for them.
#
# TODO: A fatal error will leave children. Need to catch that.
#
sub ParRun($$$@)
{
    my ($options, $pref, $function, @objects) = @_;
    my %children = ();
    my @results  = ();
    my $counter  = 0;
    my $signaled = 0;
366
    my $nosighup = 0;
367 368
    # We need this below.
    require event;
369 370 371 372 373 374 375 376 377 378

    # options.
    my $maxchildren = 10;
    my $maxwaittime = 200;

    if (defined($options)) {
	$maxchildren = $options->{'maxchildren'}
	    if (exists($options->{'maxchildren'}));
	$maxwaittime = $options->{'maxwaittime'}
	    if (exists($options->{'maxwaittime'}));
379 380
	$nosighup = $options->{'nosighup'}
	    if (exists($options->{'nosighup'}));
381 382 383 384 385 386 387 388
    }

    #
    # Set up a signal handler in the parent to handle termination.
    #
    my $coderef = sub {
	my ($signame) = @_;

389
	print STDERR "Caught SIG${signame} in $$! Killing parrun ...\n";
390 391 392 393 394

	$SIG{TERM} = 'IGNORE';
	$signaled = 1;

	foreach my $pid (keys(%children)) {
395 396
	    print STDERR "Sending HUP signal to $pid ...\n";
	    kill('HUP', $pid);
397 398 399 400 401
	}
	sleep(1);
    };
    local $SIG{QUIT} = $coderef;
    local $SIG{TERM} = $coderef;
402
    local $SIG{INT}  = $coderef;
403
    local $SIG{HUP}  = $coderef if (!$nosighup);
404 405 406 407 408 409 410 411

    #
    # Initialize return.
    #
    for (my $i = 0; $i < scalar(@objects); $i++) {
	$results[$i] = -1;
    }

412
    while ((@objects && !$signaled) || keys(%children)) {
413 414 415 416 417 418 419
	#
	# Something to do and still have free slots.
	#
	if (@objects && keys(%children) < $maxchildren && !$signaled) {
	    # Space out the invocation of child processes a little.
	    sleep(1);

420 421 422 423 424 425 426
	    my $newsigset = POSIX::SigSet->new(SIGQUIT,SIGINT,SIGTERM,SIGHUP);
	    my $oldsigset = POSIX::SigSet->new;
	    if (! defined(sigprocmask(SIG_BLOCK, $newsigset, $oldsigset))) {
		print STDERR "sigprocmask (BLOCK) failed!\n";
		return -1;
	    }
	    if (!$signaled) {
427
		#
428 429 430
		# Run command in a child process, protected by an alarm to
		# ensure that whatever happens is not hung up forever in
		# some funky state.
431
		#
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
		my $object = shift(@objects);
		my $syspid = fork();

		if ($syspid) {
		    #
		    # Just keep track of it, we'll wait for it finish down below
		    #
		    $children{$syspid} = [$object, $counter, time()];
		    $counter++;
		}
		else {
		    $SIG{TERM} = 'DEFAULT';
		    $SIG{QUIT} = 'DEFAULT';
		    $SIG{HUP}  = 'DEFAULT';
		    $SIG{INT}  = 'IGNORE';

		    # Unblock in child after resetting the handlers.
		    if (! defined(sigprocmask(SIG_SETMASK, $oldsigset))) {
			print STDERR "sigprocmask (UNBLOCK) failed!\n";
		    }
452
		
453 454 455 456 457 458 459 460 461 462 463 464
		    # So randomness is not the same in different children
		    srand();
		
		    # So we get the event system fork too ...
		    event::EventFork();
		    exit(&$function($object));
		}
	    }
	    # Unblock after critical section.
	    if (! defined(sigprocmask(SIG_SETMASK, $oldsigset))) {
		print STDERR "sigprocmask (UNBLOCK) failed!\n";
		return -1;
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
	    }
	}
	elsif ($signaled) {
	    my $childpid   = wait();
	    my $exitstatus = $?;

	    if (exists($children{$childpid})) {
		delete($children{$childpid});
	    }
	}
	else {
	    #
	    # We have too many of the little rugrats, wait for one to die
	    #
	    #
	    # Set up a timer - we want to kill processes after they
	    # hit timeout, so we find the first one marked for death.
	    #
	    my $oldest;
	    my $oldestpid = 0;
	    my $oldestobj;
	    
	    while (my ($pid, $aref) = each %children) {
		my ($object, $which, $birthtime) = @$aref;

		if ((!$oldestpid) || ($birthtime < $oldest)) {
		    $oldest    = $birthtime;
		    $oldestpid = $pid;
		    $oldestobj = $object;
		}
	    }

	    #
	    # Sanity check
	    #
	    if (!$oldest) {
		print STDERR 
		    "*** ParRun: ".
		    "Uh oh, I have no children left, something is wrong!\n";
	    }

	    #
	    # If the oldest has already expired, just kill it off
	    # right now, and go back around the loop
	    #
	    my $now = time();
	    my $waittime = ($oldest + $maxwaittime) - time();

	    #
	    # Kill off the oldest if it gets too old while we are waiting.
	    #
	    my $childpid = -1;
	    my $exitstatus = -1;

	    eval {
		local $SIG{ALRM} = sub { die "alarm clock" };

		if ($waittime <= 0) {
		    print STDERR
			"*** ParRun: timeout waiting for child: $oldestpid\n";
		    kill("TERM", $oldestpid);
		}
		else {
		    alarm($waittime);
		}
		$childpid = wait();
		alarm 0;
		$exitstatus = $?;
	    };
	    if ($@) {
		die unless $@ =~ /alarm clock/;
		next;
	    }

	    #
	    # Another sanity check
	    #
	    if ($childpid < 0) {
		print STDERR
		    "*** ParRun:\n".
		    "wait() returned <0, something is wrong!\n";
		next;
	    }

	    #
	    # Look up to see what object this was associated with - if we
	    # do not know about this child, ignore it
	    #
	    my $aref = $children{$childpid};
	    next unless @$aref;	
	    my ($object, $which, $birthtime) = @$aref;
	    delete($children{$childpid});
	    $results[$which] = $exitstatus;
	}
    }
    @$pref = @results
	if (defined($pref));
    return -1
	if ($signaled);
    return 0;
}

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
#
# Version Info
#
sub VersionInfo($)
{
    my ($name) = @_;

    my $query_result = 
	DBQueryWarn("select value from version_info ".
		    "where name='$name'");

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

    my ($value) = $query_result->fetchrow_array();
    return $value;
}

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
#
# Version Info
#
sub UpdateVersionInfo($$)
{
    my ($name, $value) = @_;
    my $safe_name  = DBQuoteSpecial($name);
    my $safe_value = DBQuoteSpecial($value);

    return -1
	if (!DBQueryWarn("replace into version_info set ".
			 "  name=$safe_name, value=$safe_value"));
    return 0;
}

600 601 602 603 604 605 606 607 608 609 610
#
# Run a command, being sure to capture all output. 
#
sub ExecQuiet($)
{
    #
    # Use a pipe read, so that we save away the output
    #
    my ($command) = @_;
    my $output    = "";
    
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    #
    # This open implicitly forks a child, which goes on to execute the
    # command. The parent is going to sit in this loop and capture the
    # output of the child. We do this so that we have better control
    # over the descriptors.
    #
    my $pid = open(PIPE, "-|");
    if (!defined($pid)) {
	print STDERR "ExecQuiet Failure; popen failed!\n";
	return -1;
    }
    
    if ($pid) {
	while (<PIPE>) {
	    $output .= $_;
	}
	close(PIPE);
    }
    else {
	open(STDERR, ">&STDOUT");
	exec($command);
632 633 634 635
    }
    return $output;
}

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
sub PipeCommand($$$)
{
    my ($command, $input, $pmsg) = @_;

    require Socket;
    import Socket qw(:DEFAULT);
    require IO::Handle;     # thousands of lines just for autoflush :-(
    
    if (! socketpair(CHILD, PARENT, AF_UNIX(), SOCK_STREAM(), PF_UNSPEC())) {
	print STDERR "*** PipeTo: Could not create socketpair\n";
	return undef;
    }
    CHILD->autoflush(1);
    PARENT->autoflush(1);

    my $childpid = fork();
    if (! $childpid) {
	close CHILD;

	#
	# Dup our descriptors to the parent, and exec the program.
	# The parent then talks to it read/write.
	#
	open(STDIN,  "<&PARENT") || die "Cannot redirect stdin";
	open(STDOUT, ">&PARENT") || die "Cannot redirect stdout";
	open(STDERR, ">&PARENT") || die "Cannot redirect stderr";

	exec($command);
	die("*** $0:\n".
665
	    "    exec '$command' failed: $!\n");
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
    }
    close PARENT;

    # Write input to the child.
    print CHILD $input;
    # Tell the process we are done writing. ie: Send it an EOF.
    shutdown(CHILD,1);
    
    my $output = "";
    while (<CHILD>) {
	$output .= $_;
    }
    close(CHILD);
    waitpid($childpid, 0);
    if ($?) {
	$$pmsg = "PipeCommand failed: '$command'";
	if ($output ne "") {
	    $$pmsg .= "\n" . $output;
	}
	return undef;
    }
    return $output;
}

690 691 692 693 694 695 696 697 698
#
# Given a set of edges: [[cisco1, cisco3], [cisco3, cisco4]].
# Return a spanning tree. Deadly simple algorithm. 
#
sub SpanningTree($)
{
    my ($edges)  = @_;
    my %vertices = ();
    my %edges    = ();
699
    my $maxloops = 1000;
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

    #
    # Get the unique set of vertices. Also form a hash of edges we can mark.
    #
    foreach my $edge (@$edges) {
	my ($a, $b) = @$edge;
	$vertices{$a} = 0
	    if (!exists($vertices{$a}));
	$vertices{$b} = 0
	    if (!exists($vertices{$b}));
	$edges{"$a:$b"} = 0;
    }
    #print Dumper(\%vertices);
    #print Dumper(\%edges);
    
    #
    # Pick the first vertex and mark it.
    #
    $vertices{(keys(%vertices))[0]} = 1;

    #
    # Loop according to Prims algorithm.
    #
723 724
    while ($maxloops) {
	$maxloops--;
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
	#
	# Get the set of marked vertices;
	#
	my %marked = ();
	foreach my $vertex (keys(%vertices)) {
	    $marked{$vertex} = 1
		if ($vertices{$vertex});
	}
	# Done if all vertices are marked.
	last
	    if (scalar(keys(%marked)) == scalar(keys(%vertices)));

	#
	# Find the first unmarked vertex that connects to any of the
	# marked ones. Mark that edge; that is an edge we want in the
	# final set.
	#
	foreach my $vertex (keys(%vertices)) {
	    next
		if ($marked{$vertex});

	    foreach my $marked (keys(%marked)) {
		if (exists($edges{"$vertex:$marked"})) {
		    $edges{"$vertex:$marked"} = 1;
		    $vertices{$vertex} = 1;
		    goto loop;
		}
		elsif (exists($edges{"$marked:$vertex"})) {
		    $edges{"$marked:$vertex"} = 1;
		    $vertices{$vertex} = 1;
		    goto loop;
		}
	    }
	}
      loop:
	#print Dumper(\%edges);
	#sleep(1);
    }
763 764 765
    if ($maxloops <= 0) {
	print STDERR "*** SpanningTree: aborting infinite loop!\n";
    }
766 767 768 769 770 771 772 773 774 775 776 777 778 779
    #
    # Return a new set of *marked* edges.
    #
    my @newedges = ();
    foreach my $edge (keys(%edges)) {
	next
	    if (!$edges{$edge});
	
	my ($a, $b) = split(":", $edge);
	push(@newedges, [$a, $b]);
    }
    return @newedges;
}

780 781 782 783 784 785 786 787 788
#
# Toggle backtrace on warning.
#
sub BackTraceOnWarning($)
{
    my ($enable) = @_;

    if ($enable) {
	$SIG{__WARN__} = sub { Carp::cluck(@_); };
789
	$SIG{__DIE__}  = sub { Carp::confess(@_) };
790 791 792
    }
    else {
	$SIG{__WARN__} = 'DEFAULT';
793
	$SIG{__DIE__}  = 'DEFAULT';
794 795 796
    }
}

797 798 799 800 801 802
#
# Convert to an encrypted hash.
#
sub PassWordHash($)
{
    my ($password) = @_;
803 804 805 806 807 808 809 810 811 812 813 814 815
    # Leave these here cause of SELFLOADER_DATA;
    my $MAINSITE   = @TBMAINSITE@;
    my $ELABINELAB = @ELABINELAB@;
    my $salt;
    require libtestbed;

    if ($MAINSITE || $ELABINELAB) {
	$salt = "\$5\$" . substr(libtestbed::TBGenSecretKey(), 0, 16) . "\$";
    }
    else {
	$salt = "\$1\$" . substr(libtestbed::TBGenSecretKey(), 0, 8) . "\$";
    }
    my $passhash = crypt($password, $salt);
816 817 818 819

    return $passhash;
}

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
#
# Generate a hopefully unique mac address that is suitable for use
# on a shared node where uniqueness matters.
#
sub GenFakeMac()
{
    my $mac;
    
    #
    # Random number for lower 4 octets.
    # 
    my $ran=`/bin/dd if=/dev/urandom count=32 bs=1 2>/dev/null | /sbin/md5`;
    return undef
	if ($?);
    
    if ($ran =~ /^\w\w\w(\w\w\w\w\w\w\w\w\w\w)/)  {
	$mac = $1;
    }

    #
    # Set the "locally administered" bit, good practice.
    #
    return "02" . $mac;
}

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
#
# SSH with timeout. 
#
sub SSHwithTimeout($$$$)
{
    my ($host, $cmd, $timeout, $debug) = @_;
    my $childpid;
    my $timedout = 0;
    my $SSHTB    = "@prefix@/bin/sshtb";

    $cmd = "$SSHTB -host $host $cmd";
    print "SSHwithTimeout($timeout): $cmd\n"
	if ($debug);

    if ($timeout) {
	$childpid = fork();

	if ($childpid) {
	    local $SIG{ALRM} = sub { kill("TERM", $childpid); $timedout = 1; };
	    alarm $timeout;
	    waitpid($childpid, 0);
	    my $exitstatus = $?;
	    alarm 0;

	    if ($timedout) {
		print STDERR "*** ssh timed out.\n";
		return -1;
	    }
	    return $exitstatus;
	}
	exec($cmd);
	die("Could not exec '$cmd'");
    }
    else {
	return system($cmd);
    }
}

883 884 885 886 887 888 889 890 891
sub GenHash()
{
    my $hash =`/bin/dd if=/dev/urandom count=128 bs=1 2> /dev/null | /sbin/md5`;
    return undef
	if ($?);
    chomp($hash);
    return $hash;
}

892 893 894 895 896 897 898 899
# Convert date to GMT
sub TBDateStringGMT($)
{
    my ($date) = @_;

    return ""
	if (!defined($date) || "$date" eq "");

900
    if ($date !~ /^\d+$/) {
901 902 903 904 905 906 907 908 909 910 911 912
	$date = str2time($date);
    }
    return POSIX::strftime("20%y-%m-%dT%H:%M:%SZ", gmtime($date));
}
# Convert date to Local
sub TBDateStringLocal($)
{
    my ($date) = @_;

    return ""
	if (!defined($date) || "$date" eq "");

913
    if ($date !~ /^\d+$/) {
Leigh Stoller's avatar
Leigh Stoller committed
914
	$date = str2time($date);
915 916 917
    }
    return POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime($date));
}
918 919 920 921 922 923 924 925 926 927 928 929 930
# Convert date to readable UTC
sub TBDateStringUTC($)
{
    my ($date) = @_;

    return ""
	if (!defined($date) || "$date" eq "");

    if ($date !~ /^\d+$/) {
	$date = str2time($date);
    }
    return POSIX::strftime("20%y-%m-%d %H:%M UTC", gmtime($date));
}
931

932 933 934 935
sub isMounted($)
{
    my ($dir) = @_;
    my $rval  = 0;
Leigh Stoller's avatar
Leigh Stoller committed
936 937 938
    my $MOUNT   = "/sbin/mount";
    my $WITHAMD = @WITHAMD@;
    my $AMDROOT = "@AMD_ROOT@";
939 940 941 942 943 944

    if ($OPSVM_ENABLE && $WITHZFS) {
	return 0
	    if (! -e $dir);
	return 1;
    }
Leigh Stoller's avatar
Leigh Stoller committed
945
    
946 947 948
    if ($WITHAMD) {
	$dir = "${AMDROOT}${dir}";
    }
949 950 951 952 953 954 955 956 957 958 959

    #
    # Grab the output of the mount command and parse.
    #
    if (! open(MOUNT, "$MOUNT|")) {
	print "Cannot run mount command\n";
	return 0;
    }
    while (<MOUNT>) {
	if ($_ =~ /^([-\w\.\/:\(\)]+) on ([-\w\.\/]+) \((.*)\)$/) {
	    # Search for nfs string in the option list.
960 961
	    # N.B. there may be a space after the comma in the list
	    foreach my $opt (split(/, ?/, $3)) {
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
		if ($opt eq "nfs" && $2 eq $dir) {
		    $rval = 1;
		}
	    }
	}
    }
    close(MOUNT);
    return $rval;
}

sub waitForMount($;$)
{
    my ($dir, $delay) = @_;
    $delay = 10 if (!defined($delay));

    for (my $i = 0; $i < $delay; $i++) {
	if (isMounted($dir)) {
	    return 0;
	}
	sleep(1);
	system("/bin/ls $dir >/dev/null 2>&1");
    }
    return -1;
}

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
#
# Run pw/chpass, checking for a locked passwd/group file. The pw routines
# exit with non specific error code 1 for everything, so there is no way
# to tell that its a busy file except by looking at the error message. Then
# wait for a bit and try again. Silly.
#
sub runBusyLoop($)
{
    my $command   = shift;
    my $maxtries  = 10;

    while ($maxtries--) {
	my $output    = "";
    
	#
	# This open implicitly forks a child, which goes on to execute the
	# command. The parent is going to sit in this loop and capture the
	# output of the child. We do this so that we have better control
	# over the descriptors.
	#
	my $pid = open(PIPE, "-|");
	if (!defined($pid)) {
	    print STDERR "runBusyLoop; popen failed!\n";
	    return -1;
	}
	if ($pid) {
	    while (<PIPE>) {
		$output .= $_;
	    }
	    close(PIPE);
	    print $output;
	    return 0
		if (!$?);
	    if ($output =~ /(group|db) file is busy/m) {
		print "runBusyLoop; waiting a few seconds before trying again\n";
		sleep(3);
	    }
	}
	else {
	    open(STDERR, ">&STDOUT");
	    exec($command);
	}
    }
    return -1;
}
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
#
# A couple of helpers to map agent strings to their numeric values.
# Making these numeric was my really dumb idea about 15 years ago.
#
sub MapEventType($)
{
    my ($arg) = @_;
    return undef
	if ($arg !~ /^[-\w]+$/);
    my $query_result =
	DBQueryWarn("select idx from event_eventtypes where type='$arg'");
    return undef
	if (!$query_result || !$query_result->numrows);
    my ($idx) = $query_result->fetchrow_array();
    return $idx;
}
sub MapEventObjectType($)
{
    my ($arg) = @_;
    return undef
	if ($arg !~ /^[-\w]+$/);
    my $query_result =
	DBQueryWarn("select idx from event_objecttypes where type='$arg'");
    return undef
	if (!$query_result || !$query_result->numrows);
    my ($idx) = $query_result->fetchrow_array();
    return $idx;
}
sub MapEventTriggerType($)
{
    my ($arg) = @_;
    return undef
	if ($arg !~ /^[-\w]+$/);
    my $query_result =
	DBQueryWarn("select idx from event_triggertypes where type='$arg'");
    return undef
	if (!$query_result || !$query_result->numrows);
    my ($idx) = $query_result->fetchrow_array();
    return $idx;
}

1074 1075 1076 1077 1078 1079 1080 1081 1082
sub ValidUUID($)
{
    my ($uuid) = @_;
    if ($uuid =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	return 1;
    }
    return 0;
}

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
sub ReadFile($)
{
    my ($filename) = @_;
    my $contents   = "";
    
    open(L, $filename)
	or return undef;

    while (<L>) {
	$contents .= $_;
    }
    close(L);
    return $contents;
}

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
#
# Use chflags on certain directories to prevent users from deleting things.
# Just a bandaid on the real problem.
#
sub SetNoDelete($)
{
    my ($filename) = @_;
    my $useflags   = 0;

    #
    # We use flags to prevent deletion of certain dirs, on FreeBSD 10
    # or greater.  Note that when OPSVM_ENABLE=1, the file systems are
    # actually on boss, not on ops, so have to this here on boss instead.
    #
    if ($OPSVM_ENABLE) {
	if (`uname -r` =~ /^(\d+)\.(\d+)/) {
	    if ($1 >= 10) {
		$useflags = 1;
	    }
	}
    }
    return 0
	if (!$useflags);

    system("$CHFLAGS sunlink $filename");
    return ($? ? -1 : 0);
}
sub ClearNoDelete($)
{
    my ($filename) = @_;
    my $useflags   = 0;

    return 0
	if (! -e $filename);

    #
    # We use flags to prevent deletion of certain dirs, on FreeBSD 10
    # or greater.  Note that when OPSVM_ENABLE=1, the file systems are
    # actually on boss, not on ops, so have to this here on boss instead.
    #
    if ($OPSVM_ENABLE) {
	if (`uname -r` =~ /^(\d+)\.(\d+)/) {
	    if ($1 >= 10) {
		$useflags = 1;
	    }
	}
    }
    return 0
	if (!$useflags);

    # Do a recursive change here since we tend to do deletions on the
    # top level directories.
    system("$CHFLAGS -R nosunlink $filename");
    return ($? ? -1 : 0);
}

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
sub escapeshellarg($)
{
    my ($str)  = @_;
    my @chars  = split('', $str);
    my $result = "";

    foreach my $ch (@chars) {
        if ($ch eq '\'') {
            $result = $result . "\'\\\'";
	}
	$result = $result . "$ch";
    }
    return "'$result'";
}

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