opsdb_control.proxy.in 15.7 KB
Newer Older
1 2 3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2005, 2006, 2007 University of Utah and the Flux Group.
5 6 7 8 9
# All rights reserved.
#
use English;
use Getopt::Std;
use Errno;
10
use File::Basename;
11
use strict;
12
use GD::Graph::lines;
13

14 15 16 17 18
#
# A wrapper for messing with the OPS DB from boss.
#
sub usage()
{
19
    print "Usage: opsdb_control.proxy adduser [-m] <uid> or\n";
20 21 22 23 24 25 26 27 28 29 30 31
    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";
32
my $MYSQLDUMP= "/usr/local/bin/mysqldump";
33
my $MYSQL    = "/usr/local/bin/mysql";
34
my $GZIP     = "/usr/bin/gzip";
35
my $TRACESCHEMA = "/usr/local/share/examples/snort/create_mysql";
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

#
# 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(@);
75
sub DumpDB(@);
76
sub LoadDB(@);
77
sub GraphDB(@);
78
sub CleanDB(@);
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
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));
}
129 130 131
elsif ($action eq "dumpdb") {
    exit(DumpDB(@ARGV));
}
132 133 134
elsif ($action eq "loaddb") {
    exit(LoadDB(@ARGV));
}
135 136 137
elsif ($action eq "graphdb") {
    exit(GraphDB(@ARGV));
}
138 139 140
elsif ($action eq "cleandb") {
    exit(CleanDB(@ARGV));
}
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 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
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
#
246 247 248
# The withtrace argument is a temp hack; need to figure out a better way
# to do this.
#
249 250
sub AddDB(@)
{
251 252 253
    my ($dbname, $option) = @_;
    my $withtrace = 0;
    my $temporary = 0;
254 255

    usage()
256
	if (@_ < 1 || @_ > 2);
257 258 259 260 261 262 263 264

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

265 266 267 268 269 270 271 272
    # XXX use getopt ...
    if (defined($option)) {
	$withtrace = 1
	    if ($option eq "-s");
	$temporary = 1
	    if ($option eq "-t");
    }

273 274 275 276 277 278 279 280 281 282 283 284 285 286
    #
    # 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.
287 288
    DBQueryFatal("replace into emulab_dbs (dbname, date_created, temporary) ".
		 "  values ('$dbname', now(), $temporary)")
289
	or return -1;
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

    #
    # 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");
    }
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
    
    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;
}

#
359
# Set DBs for a list of users.
360 361 362
#
sub SetDBs(@)
{
363
    my @input    = ();
364 365

    usage()
366
	if (@_ != 0);
367

368 369 370 371 372
    #
    # Grab all the input.
    #
    while (<STDIN>) {
	push(@input, $_);
373 374
    }

375 376 377 378 379
    foreach my $line (@input) {
	my @tokens   = split(/\s/, $line);
	my $uid      = shift(@tokens);
	my %newglist = ();
	my %oldglist = ();
380

381 382
	print "Setting dbs for $uid to @tokens\n"
	    if ($debug);
383

384 385 386 387 388 389 390
	# 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'");
391
	return -1
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	    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;
	}
421

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
	# 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;
	}
441
    }
442 443
    DBQueryFatal("flush privileges")
	or return -1;
444 445 446 447

    return 0;
}

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
#
# 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;
    }

470 471 472 473 474 475 476 477
    #
    # 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");
    }

478 479 480 481 482 483 484
    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");

485 486 487
    unlink("${filename}.old")
	if (-e "${filename}.old");

488 489 490
    return 0;
}

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
#
# 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;
}

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 574 575 576 577
#
# 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;
}

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
#
# 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()
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 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
	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();
	}
    }
656 657 658 659 660 661 662 663 664 665 666 667

    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;
    }
668
    my $gd = new GD::Graph::lines(500,325);
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 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    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;
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
	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 ";
	}
746 747 748 749

	if ($which eq "pps") {
	    $query_result =
		DBQueryFatal("select UNIX_TIMESTAMP(timestamp),count(*) ".
750 751 752 753
			     "  from event as e ".
			     "left join iphdr as i on ".
			     "     i.sid=e.sid and i.cid=e.cid ".
			     $whereclause . " " .
754 755 756 757 758 759 760 761
			     "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 ".
762
			     $whereclause . " " .
763 764
			     "group by timestamp order by timestamp");
	}
765 766 767
	return 0
	    if (! $query_result->numrows);
	
768 769 770 771 772
	my ($tstart,$first) = $query_result->fetchrow_array();

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
773 774
	my $last = 0;

775
	while (my ($timestamp, $count) = $query_result->fetchrow_array()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
776 777 778 779 780 781 782 783 784 785 786 787
	    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);
788
	    push(@y_data, $count);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
789
	    $last = $now;
790 791 792 793 794 795 796 797 798
	}
    }
    
    my @data = ( \@x_data , \@y_data );
    $gd->plot(\@data);
    SaveGraph($gd, $filename);
    return 0;
}

799 800 801 802 803 804 805
sub fatal($)
{
    my($mesg) = $_[0];

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