opsdb_control.proxy.in 16.4 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2005, 2006, 2007 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
#
use English;
use Getopt::Std;
use Errno;
27
use File::Basename;
28
use strict;
29
use GD::Graph::lines;
30

31 32 33 34 35
#
# A wrapper for messing with the OPS DB from boss.
#
sub usage()
{
36
    print "Usage: opsdb_control.proxy adduser [-m] <uid> or\n";
37 38 39 40 41 42 43 44 45 46 47 48
    exit(-1);
}
my $optlist = "d";
my $debug   = 0;

#
# Configure variables
#
my $TB       = "@prefix@";
my $TBOPS    = "@TBOPSEMAIL@";
my $OURDOMAIN= "@OURDOMAIN@";
my $DBCONF   = "/usr/testbed/etc/mysqld.pwd";
49
my $MYSQLDUMP= "/usr/local/bin/mysqldump";
50
my $MYSQL    = "/usr/local/bin/mysql";
51
my $GZIP     = "/usr/bin/gzip";
52
my $TRACESCHEMA = "/usr/local/share/examples/snort/create_mysql";
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

#
# Turn off line buffering on output
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Only real root, cause the script has to read/write a pid file that
# cannot be accessed by the user.
#
if ($UID != 0) {
    die("*** $0:\n".
	"    Must be root to run this script!\n");
}

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libtestbed;
use libtbdb;

# Locals
my $dbname = "mysql";
my $dbuser = "root";
my $dbpass;

# Protos
sub AddUser(@);
sub DelUser(@);
sub AddDB(@);
sub DelDB(@);
sub SetDBs(@);
92
sub DumpDB(@);
93
sub LoadDB(@);
94
sub GraphDB(@);
95
sub CleanDB(@);
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 135 136 137 138 139 140 141 142 143 144 145
sub fatal($);

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (! @ARGV) {
    usage();
}

#
# The DB passwd is stored in the config file, hopefully not world
# readable. Open and parse that file, then open a connection to the
# DB.
#
if (`cat $DBCONF` =~ /^([\w]*)$/) {
    $dbpass = $1;
}
else {
    fatal("Bad characters in password!");
}

if (TBDBConnect($dbname, $dbuser, $dbpass) < 0) {
    fatal("Could not connect to ops database!");
}

my $action = shift(@ARGV);

if ($action eq "adduser") {
    exit(AddUser(@ARGV));
}
elsif ($action eq "deluser") {
    exit(DelUser(@ARGV));
}
elsif ($action eq "adddb") {
    exit(AddDB(@ARGV));
}
elsif ($action eq "deldb") {
    exit(DelDB(@ARGV));
}
elsif ($action eq "setdbs") {
    exit(SetDBs(@ARGV));
}
146 147 148
elsif ($action eq "dumpdb") {
    exit(DumpDB(@ARGV));
}
149 150 151
elsif ($action eq "loaddb") {
    exit(LoadDB(@ARGV));
}
152 153 154
elsif ($action eq "graphdb") {
    exit(GraphDB(@ARGV));
}
155 156 157
elsif ($action eq "cleandb") {
    exit(CleanDB(@ARGV));
}
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 259 260 261 262
else {
    die("*** $0:\n".
	"    Do not know what to do with '$action'!\n");
}
exit(0);

#
# Utility function to see if a DB already exists.
#
sub DBExists($)
{
    my ($dbname) = @_;

    my $query_result =
	DBQueryWarn("show databases like '$dbname'");

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

#
# Utility function to see if a DB is an emulab DB
#
sub IsEmulabDB($)
{
    my ($dbname) = @_;

    my $query_result =
	DBQueryWarn("select * from emulab_dbs where dbname='$dbname'");

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

#
# Add user.
#
sub AddUser(@)
{
    my ($uid) = @_;
    my ($password);

    usage()
	if (@_ != 1);
    
    # Password comes in from STDIN.
    
    $_ = <STDIN>;
    usage()
	if (!defined($_));
	
    if ($_ =~ /^(.*)$/) {
	$password   = $1;
    }
    else {
	fatal("AddUser: Bad line in input: $_");
    }

    #
    # Default for users is no privs on anything. They get privs later
    # on a per-db basis.
    #
    DBQueryFatal("replace into user (Host, User, Password) ".
		 "values ('localhost','$uid', PASSWORD('$password'))")
	or return -1;

    # Eventually, we want to allow remote access.
    DBQueryFatal("replace into user (Host, User, Password) ".
		 "values ('%.${OURDOMAIN}','$uid', PASSWORD('$password'))")
	or return -1;

    DBQueryFatal("flush privileges")
	or return -1;

    return 0;
}

#
# Delete user.
#
sub DelUser(@)
{
    my ($uid) = @_;

    usage()
	if (@_ != 1);

    DBQueryFatal("delete from db where User='$uid'")
	or return -1;
    
    DBQueryFatal("delete from user where User='$uid'")
	or return -1;
    
    DBQueryFatal("flush privileges")
	or return -1;

    return 0;
}

#
# Add a DB
#
263 264 265
# The withtrace argument is a temp hack; need to figure out a better way
# to do this.
#
266 267
sub AddDB(@)
{
268 269 270
    my ($dbname, $option) = @_;
    my $withtrace = 0;
    my $temporary = 0;
271 272

    usage()
273
	if (@_ < 1 || @_ > 2);
274 275 276 277 278 279 280 281

    my $exists = DBExists($dbname);
    return -1
	if ($exists < 0);
    my $isemulab = IsEmulabDB($dbname);
    return -1
	if ($isemulab < 0);

282 283 284 285 286 287 288 289
    # XXX use getopt ...
    if (defined($option)) {
	$withtrace = 1
	    if ($option eq "-s");
	$temporary = 1
	    if ($option eq "-t");
    }

290 291 292 293 294 295 296 297 298 299 300 301 302 303
    #
    # We do not want to create a DB if there already is one of that
    # name, and its not in the emulab DB table. That means its a
    # pre-existing DB and we are screwed. 
    #
    if ($exists && !$isemulab) {
	print "DB '$dbname' already exists! Must be a conflict.\n";
	return -1;
    }

    DBQueryFatal("create database if not exists `$dbname`")
	or return -1;

    # This table tells us what belongs to Emulab.
304 305
    DBQueryFatal("replace into emulab_dbs (dbname, date_created, temporary) ".
		 "  values ('$dbname', now(), $temporary)")
306
	or return -1;
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

    #
    # If the DB is newly created and we are going to insert trace data,
    # run the schema file into it. Sorta silly, I know.
    #
    if ($withtrace && !$exists) {
	if (! open(INPUT, $TRACESCHEMA)) {
	    print "Could not open schema file: $!\n";
	    return -1;
	}
	open(SCHEMA, "| $MYSQL -u root -p $dbname >/dev/null") or
	    fatal("Could not start $MYSQL!");
	print SCHEMA "$dbpass\n";
	# So as not to lose input while mysql resets the tty.
	sleep(1);

	while (<INPUT>) {
	    print SCHEMA $_;
	}
	close(INPUT);
	close(SCHEMA) or
	    fatal($! ? "Error closing $MYSQL pipe: $!"
		     : "Exit status $? from $MYSQL");
    }
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 367 368 369 370 371 372 373 374 375
    
    return 0;
}

#
# Remove a DB. 
#
sub DelDB(@)
{
    my ($dbname) = @_;

    usage()
	if (@_ != 1);

    my $exists = DBExists($dbname);
    return -1
	if ($exists < 0);
    my $isemulab = IsEmulabDB($dbname);
    return -1
	if ($isemulab < 0);

    #
    # We do not want to remove a DB if there is no entry in the emulab_dbs
    # table; it belongs to someone else!
    #
    if ($exists && !$isemulab) {
	print "DB '$dbname' is not an Emulab DB! Not removing!\n";
	return -1;
    }

    DBQueryFatal("drop database if exists `$dbname`")
	or return -1;

    # Remove any dangling entries in the Db table ...
    DBQueryFatal("delete from db where Db='$dbname'")
	or return -1;

    # This table tells us what belongs to Emulab. Delete as last step.
    DBQueryFatal("delete from emulab_dbs where dbname='$dbname'")
	or return -1;

    return 0;
}

#
376
# Set DBs for a list of users.
377 378 379
#
sub SetDBs(@)
{
380
    my @input    = ();
381 382

    usage()
383
	if (@_ != 0);
384

385 386 387 388 389
    #
    # Grab all the input.
    #
    while (<STDIN>) {
	push(@input, $_);
390 391
    }

392 393 394 395 396
    foreach my $line (@input) {
	my @tokens   = split(/\s/, $line);
	my $uid      = shift(@tokens);
	my %newglist = ();
	my %oldglist = ();
397

398 399
	print "Setting dbs for $uid to @tokens\n"
	    if ($debug);
400

401 402 403 404 405 406 407
	# List of new DBs to grant access to.
	foreach my $db (@tokens) {
	    $newglist{$db} = $db;
	}
	
	my $query_result =
	    DBQueryFatal("select * from user where User='$uid'");
408
	return -1
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
	    if (!$query_result);

	if (!$query_result->numrows) {
	    print "User $uid does not exist in the user table!\n";
	    return 0;
	}

	# Generate existing DB access list.
	$query_result =
	    DBQueryFatal("select Db from db where User='$uid'");
	while (my ($db) = $query_result->fetchrow_array()) {
	    $oldglist{$db} = $db;
	}

	# First do deletions.
	foreach my $db (keys(%oldglist)) {
	    next
		if (exists($newglist{$db}));

	    # Do not delete user if not an Emulab created DB.
	    my $isemulab = IsEmulabDB($db);
	    return -1
		if ($isemulab < 0);
	    next
		if (!$isemulab);

	    DBQueryFatal("delete from db where User='$uid' and Db='$db'")
		or return -1;
	}
438

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
	# Then do additions.
	foreach my $db (keys(%newglist)) {
	    next
		if (exists($oldglist{$db}));

	    # Do not add user if not an Emulab created DB.
	    my $isemulab = IsEmulabDB($db);
	    return -1
		if ($isemulab < 0);
	    next
		if (!$isemulab);

	    DBQueryFatal("grant all on `${db}`.* to '$uid'\@'localhost'")
		or return -1;

	    # Eventually, we want to allow remote access.
	    DBQueryFatal("grant all on `${db}`.* to '$uid'\@'%.${OURDOMAIN}'")
		or return -1;
	}
458
    }
459 460
    DBQueryFatal("flush privileges")
	or return -1;
461 462 463 464

    return 0;
}

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
#
# Dump a DB to a file.
#
sub DumpDB(@)
{
    my ($dbname, $filename) = @_;

    usage()
	if (@_ != 2);

    my $exists = DBExists($dbname);
    return -1
	if ($exists < 0);
    my $isemulab = IsEmulabDB($dbname);
    return -1
	if ($isemulab < 0);

    if (!$exists) {
	print "DB '$dbname' does not exist!\n";
	return -1;
    }

487 488 489 490 491 492 493 494
    #
    # For NFS, lets not overwrite the samefile, but *create* a new one.
    #
    if (-e $filename) {
	system("/bin/mv $filename ${filename}.old") == 0 or
	    fatal("Could not mv $filename");
    }

495 496 497 498 499 500 501
    open(DUMP, "| $MYSQLDUMP -u root -p -a -e $dbname | $GZIP > $filename") or
	fatal("Could not start $MYSQLDUMP!");
    print DUMP "$dbpass\n";
    close(DUMP) or
	fatal($! ? "Error closing $MYSQLDUMP pipe: $!"
	         : "Exit status $? from $MYSQLDUMP");

502 503 504
    unlink("${filename}.old")
	if (-e "${filename}.old");

505 506 507
    return 0;
}

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
#
# Clean a DB.
#
sub CleanDB(@)
{
    my ($dbname) = @_;

    usage()
	if (@_ != 1);

    my $exists = DBExists($dbname);
    return -1
	if ($exists < 0);
    my $isemulab = IsEmulabDB($dbname);
    return -1
	if ($isemulab < 0);

    if (!$exists) {
	print "DB '$dbname' does not exist!\n";
	return -1;
    }

    # This is called as root, so just switch to the proper DB.
    if (TBDBConnect($dbname, $dbuser, $dbpass) < 0) {
	fatal("Could not connect to $dbname database!");
    }

    my $query_result =
	DBQueryFatal("show tables");

    while (my ($table) = $query_result->fetchrow_array()) {
	DBQueryFatal("delete from `$table`");
    }
    return 0;
}

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
#
# Load a DB from a file
#
sub LoadDB(@)
{
    my ($dbname, $filename) = @_;

    usage()
	if (@_ != 2);

    my $exists = DBExists($dbname);
    return -1
	if ($exists < 0);
    my $isemulab = IsEmulabDB($dbname);
    return -1
	if ($isemulab < 0);

    if (!$exists) {
	print "DB '$dbname' does not exist!\n";
	return -1;
    }

    # Check to see if the file is a .gz file.
    my $openwith = $filename;
    my (undef,undef,$suffix) = fileparse($filename, ".gz");

    if ($suffix eq ".gz") {
	$openwith = "zcat $filename |";
    }

    if (! open(INPUT, $openwith)) {
	print "Could not open '$openwith': $!\n";
	return -1;
    }
    open(SQL, "| $MYSQL -u root -p $dbname >/dev/null") or
	fatal("Could not start $MYSQL!");
    print SQL "$dbpass\n";
    # So as not to lose input while mysql resets the tty.
    sleep(1);

    while (<INPUT>) {
	print SQL $_;
    }
    close(INPUT);
    close(SQL) or
	fatal($! ? "Error closing $MYSQL pipe: $!"
	         : "Exit status $? from $MYSQL");

    return 0;
}

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
#
# Very hacky graphing support. Initially, I'm supporting a couple of
# different kinds of graphs just to get the ball rolling. I have no
# idea where this stuff is going to go.
#
sub SaveGraph($$)
{
    my ($gd, $filename) = @_;

    # Spew to stdout.
    if (!defined($filename)) {
	binmode STDOUT;
	print STDOUT $gd->gd->gif();
	return 0;
    }
    
    if (! open(OUT, ">$filename")) {
	print "Could not open $filename for writing!\n";
	return -1;
    }
    binmode OUT;
    print OUT $gd->gd->gif();
    close OUT;

    return 0;
}

sub GraphDB(@)
{
    usage()
625 626 627 628 629 630 631 632 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
	if (@_ < 2);

    my $dbname   = shift(@_);
    my $which    = shift(@_);
    my $filename;
    my $start;
    my $stop;
    my $srcip;
    my $dstip;

    # Parse the rest of the options.
    while (@_) {
	my $arg = shift(@_);

	if ($arg eq "-f") {
	    usage()
		if (@_ == 0);
	    $filename = shift(@_);
	}
	elsif ($arg eq "-r") {
	    usage()
		if (@_ == 0);

	    $arg = shift(@_);
	    if ($arg =~ /^(\d*):(\d*)$/) {
		$start = $1;
		if ($2) {
		    $stop = $2;
		}
	    }
	    else {
		usage();
	    }
	}
	elsif ($arg eq "-s") {
	    usage()
		if (@_ == 0);
	    $srcip = shift(@_);
	}
	elsif ($arg eq "-t") {
	    usage()
		if (@_ == 0);
	    $dstip = shift(@_);
	}
	else {
	    usage();
	}
    }
673 674 675 676 677 678 679 680 681 682 683 684

    my $exists = DBExists($dbname);
    return -1
	if ($exists < 0);
    my $isemulab = IsEmulabDB($dbname);
    return -1
	if ($isemulab < 0);

    if (!$exists) {
	print "DB '$dbname' does not exist!\n";
	return -1;
    }
685
    my $gd = new GD::Graph::lines(500,325);
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 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    if (!$gd) {
	print "Could not create a new graph object!\n";
	return -1;
    }
    # This is called as root, so just switch to the proper DB.
    if (TBDBConnect($dbname, $dbuser, $dbpass) < 0) {
	fatal("Could not connect to $dbname database!");
    }
    my $xlabel;
    my $ylabel;
    my $title;
    my @x_data = ();
    my @y_data = ();

    if ($which eq "pps") {
	$xlabel = "Seconds Since Time Start";
	$ylabel = "Packets per Second";
	$title  = "Aggregate Packets per Second";
    }
    elsif ($which eq "bps") {
	$xlabel = "Seconds Since Time Start";
	$ylabel = "Bytes per Second";
	$title  = "Aggregate Bytes per Second";
    }
    else {
	print "Do not know how to graph $which!\n";
	return -1;
    }
	
    $gd->set(x_label       => $xlabel,
	     y_label       => $ylabel,
	     title         => $title,
	     r_margin      => 30,
	     y_tick_number => 'auto',
	     x_tick_number => 'auto',
	     box_axis      => 0,
	     line_width    => 3,
	     transparent   => 0,
	     );

    if ($which eq "pps" || $which eq "bps") {
	my $query_result;
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
	my $timeclause;
	my $ipclause;
	my $whereclause = "";

	if (defined($start) && defined($stop)) {
	    $timeclause = "(timestamp >= FROM_UNIXTIME('$start') and ".
		"timestamp <= FROM_UNIXTIME('$stop')) ";
	}
	elsif (defined($start)) {
	    $timeclause = "(timestamp >= FROM_UNIXTIME('$start')) ";
	}
	elsif (defined($stop)) {
	    $timeclause = "(timestamp <= FROM_UNIXTIME('$stop')) ";
	}

	if (defined($srcip) && defined($dstip)) {
	    $ipclause = "(ip_src=INET_ATON('$srcip') ".
		"and ip_dst=INET_ATON('$dstip'))";
	}
	elsif (defined($srcip)) {
	    $ipclause = "(ip_src=INET_ATON('$srcip'))";
	}
	elsif (defined($dstip)) {
	    $ipclause = "(ip_dst=INET_ATON('$dstip'))";
	}

	if (defined($timeclause) && defined($ipclause)) {
	    $whereclause = "where $timeclause and $ipclause ";
	}
	elsif (defined($timeclause)) {
	    $whereclause = "where $timeclause ";
	}
	elsif (defined($ipclause)) {
	    $whereclause = "where $ipclause ";
	}
763 764 765 766

	if ($which eq "pps") {
	    $query_result =
		DBQueryFatal("select UNIX_TIMESTAMP(timestamp),count(*) ".
767 768 769 770
			     "  from event as e ".
			     "left join iphdr as i on ".
			     "     i.sid=e.sid and i.cid=e.cid ".
			     $whereclause . " " .
771 772 773 774 775 776 777 778
			     "group by timestamp order by timestamp");
	}
	else {
	    $query_result =
		DBQueryFatal("select UNIX_TIMESTAMP(timestamp),sum(ip_len) ".
			     "  from event as e ".
			     "left join iphdr as i on ".
			     "  i.sid=e.sid and i.cid=e.cid ".
779
			     $whereclause . " " .
780 781
			     "group by timestamp order by timestamp");
	}
782 783 784
	return 0
	    if (! $query_result->numrows);
	
785 786 787 788 789
	my ($tstart,$first) = $query_result->fetchrow_array();

	@x_data = (0);
	@y_data = ($first);

Leigh Stoller's avatar
Leigh Stoller committed
790 791
	my $last = 0;

792
	while (my ($timestamp, $count) = $query_result->fetchrow_array()) {
Leigh Stoller's avatar
Leigh Stoller committed
793 794 795 796 797 798 799 800 801 802 803 804
	    my $now = $timestamp - $tstart;

	    #
	    # Need to add explicit zero values for gaps.
	    #
	    $last++;
	    while ($last < $now) {
		push(@x_data, $last);
		push(@y_data, 0);
		$last++;
	    }
	    push(@x_data, $now);
805
	    push(@y_data, $count);
Leigh Stoller's avatar
Leigh Stoller committed
806
	    $last = $now;
807 808 809 810 811 812 813 814 815
	}
    }
    
    my @data = ( \@x_data , \@y_data );
    $gd->plot(\@data);
    SaveGraph($gd, $filename);
    return 0;
}

816 817 818 819 820 821 822
sub fatal($)
{
    my($mesg) = $_[0];

    die("*** $0:\n".
	"    $mesg\n");
}