emdbi.pm.in 11.1 KB
Newer Older
1 2 3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2008, 2009 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13
# All rights reserved.
#
package emdbi;
use strict;
use File::Basename;
use Mysql;
use English;
use Exporter;
use vars qw(@ISA @EXPORT);
14
@ISA = "Exporter";
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 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 75 76 77 78 79 80 81 82 83 84

# Configure variables
my $TB		= "@prefix@";
my $SCRIPTNAME  = "Unknown";
my $TBOPS       = "@TBOPSEMAIL@";

# Locals
my $DBErrorString = "";		# Record last DB error string.

# Remember the DBname for subsequent reconnects.
my @DBNAMES       = ();

# Untainted scriptname for below.
if ($PROGRAM_NAME =~ /^([-\w\.\/]+)$/) {
    $SCRIPTNAME = basename($1);
}
else {
    $SCRIPTNAME = "Tainted";
}

{
    #
    # Create a special class for keeping track of the process the
    # database handle was created.  This is needed so that the child
    # process after a fork() 1) set's InactiveDestroy to avoid sending
    # a disconnect message since it will also close the parent's
    # database handle 2) reconnects since two separate processes
    # shouldn't share the same handle.  (1) is handled via overridding
    # the database handle DESTROY method, (2) is handled in the
    # DBQueryN function.
    #
    package TestbedDBHandle;
    use vars '@ISA';
    @ISA = ('Mysql');
    @TestbedDBHandle::Statement::ISA = ('Mysql::Statement');
    my %DB_PID; # hash based on db handle
    sub obj_hash( $ ) {
	# Return a hex string of the location of the object in memory.
	# This is slightly better than just converting it to a scalar
	# as two objects as the scalar also included the class name
	# the object is "blessed" into which might change over time
	sprintf("0x%x", $_[0]); 
    }
    sub MakeA ( $ ) {
	my ($obj) = @_;
	return unless defined $obj;
	bless ($obj);
	$DB_PID{obj_hash($obj)} = $$;
    }
    sub db_pid () {
	my ($self) = @_;
	return $DB_PID{obj_hash($self)};
    }
    sub DESTROY {
	my ($self) = @_;
	if ($self->db_pid() != $$) {
	    $self->setInactiveDestroy(1);
	}
	delete $DB_PID{obj_hash($self)};
	$self->SUPER::DESTROY() if $self->can("SUPER::DESTROY");
    }
}

#
# Set up for querying the database. Note that fork causes a reconnect
# to the DB in the child.
#
my @DB;

use vars qw($DBQUERY_MAXTRIES $DBCONN_MAXTRIES
85
	    $DBCONN_EXITONERR $DBQUERY_RECONNECT $DBQUERY_DEBUG);
86 87 88 89 90
$DBQUERY_MAXTRIES  = 1;
$DBQUERY_RECONNECT = 1;
$DBCONN_MAXTRIES   = 5;
$DBCONN_EXITONERR  = 1;
$DBQUERY_DEBUG     = 0;
91
@EXPORT            = qw($DBQUERY_MAXTRIES $DBQUERY_RECONNECT
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 129 130 131 132 133 134 135 136 137 138 139 140 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 246 247 248 249 250 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 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
			$DBCONN_EXITONERR $DBCONN_MAXTRIES $DBQUERY_DEBUG);

sub TBDBConnect($$)
{
    my ($dbnum, $dbname) = @_;
    my $maxtries = $DBCONN_MAXTRIES;

    if (!defined($dbname)) {
	    print STDERR "What DBNAME should I use?\n";
	    return -1
		if (! $DBCONN_EXITONERR);
	    exit(-1);
    }
    
    #
    # Do nothing if this DB handle is already connected to DB.
    #
    if (defined($DB[$dbnum])) {
	return 0
	    if ($DBNAMES[$dbnum] eq $dbname);
	
	print STDERR "DBnum $dbnum already connected to another DB: ".
	    $DBNAMES[$dbnum] . "!\n";
	return -1
	    if (! $DBCONN_EXITONERR);
	exit(-1);
    }
    $DBNAMES[$dbnum] = $dbname;

    #
    # Construct a 'username' from the name of this script and the user who
    # ran it. This is for accounting purposes.
    #
    my $name = getpwuid($UID);
    if (!$name) {
	$name = "uid$UID";
    }
    my $dbuser = "$SCRIPTNAME:$name:$PID";

    while ($maxtries) {
	if ($DBQUERY_DEBUG) {
	    print STDERR "DBConnect:$dbnum $dbname\n";
	}
	
	$DB[$dbnum] = Mysql->connect("localhost", $dbname, $dbuser, "none");
        TestbedDBHandle::MakeA($DB[$dbnum]);
	if (defined($DB[$dbnum])) {
	    last;
	}
	$maxtries--;
	if ($maxtries) {
	    print STDERR "Cannot connect to DB; trying again in 5 seconds!\n";
	    sleep(5);
	}
    }
    if (!defined($DB[$dbnum])) {
	print STDERR
	    "Cannot connect to DB after $DBQUERY_MAXTRIES attempts!\n";
	return -1
	    if (! $DBCONN_EXITONERR);
	exit(-1);
    }
    $DB[$dbnum]->{'dbh'}->{'PrintError'} = 0;
    $Mysql::QUIET = 1;
    return 0;
}

# New version.
sub TBDBReconnect($)
{
    my ($retry) = @_;
    my ($exitonerr,$maxtries);
    
    if ($retry) {
	$exitonerr = $DBCONN_EXITONERR;
	$DBCONN_EXITONERR = 0;
	
	# And we want to keep trying for a long time!
	$maxtries = $DBCONN_MAXTRIES;
	$DBCONN_MAXTRIES  = 10000;
    }

    for (my $i = 0; $i < @DB; $i++) {
	next
	    if (!defined($DB[$i]));
	
	undef($DB[$i]);
	return -1
	    if (TBDBConnect($i, $DBNAMES[$i]) != 0);
    }

    if ($retry) {
	$DBCONN_EXITONERR = $exitonerr;
	$DBCONN_MAXTRIES  = $maxtries;
    }
    #print "Reconnected to DB in process $PID\n";
   
    return 0;
}

# To avoid keeping a mysql connection around.
sub TBDBDisconnect()
{
    for (my $i = 0; $i < @DB; $i++) {
	undef($DB[$i]);
    }
    select(undef, undef, undef, 0.2);
}

# Create a new DB handle and return the handle number
sub NewTBDBHandle($)
{
    my ($dbname) = @_;
    
    my $dbnum = @DB;
    # Avoid using the initial one here.
    $dbnum++
	if (!$dbnum);
    
    TBDBConnect($dbnum, $dbname);
    return $dbnum;
}

#
# Issue a DB query. Argument is a string. Returns the actual query object, so
# it is up to the caller to test it. I would not for one moment view this
# as encapsulation of the DB interface. I'm just tired of typing the same
# silly stuff over and over.
#
# usage: DBQuery(char *str)
#        returns the query object result.
#
# Sets $DBErrorString is case of error; saving the original query string and
# the error string from the DB module. Use DBFatal (below) to print/email
# that string, and then exit.
#
sub DBQueryN($$)
{
    my($dbnum, $query)   = @_;
    my $maxtries = $DBQUERY_MAXTRIES;
    my $result;

    # Not really forever :-)
    if (!$maxtries) {
	$maxtries = 100000;
    }

    # Reconnect to mysqld in child of fork.
    if ($DB[$dbnum]->db_pid() != $PID) {
	if (TBDBReconnect(1) != 0) {
	    $DBErrorString =
		"  Query: $query\n".
		"  Error: Could not reconnect to mysqld";
	    return undef;
	}
    }

    if ($DBQUERY_DEBUG) {
	print STDERR "Query: '$query'\n";
    }

    while ($maxtries) {
	# Get this each time through the loop since we try reconnect below.
	my $db = $DB[$dbnum];

	$result = $db->query($query);

	if (! defined($result)) {
	    my $err = $db->err;

	    $DBErrorString =
		"  Query: $query\n".
		"  Error: " . $db->errstr . " ($err)";
	}
	if (defined($result) ||
	    ($db->err != 2006) && ($db->err != 1053) && ($db->err != 2013) &&
	    ($db->err != 1046)) {
	    last;
	}

	#
	# If we lose the connection to mysqld; lets try to reconnect. 
	#
	if ($db->err == 2006 || $db->err == 2013) {
	    # This is just for the mysqld watchdog daemon.
	    return undef
		if (! $DBQUERY_RECONNECT);

	    if (TBDBReconnect(1) != 0) {
		$DBErrorString =
		    "  Query: $query\n".
		    "  Error: Could not reconnect to mysqld";

		return undef;
	    }
	    next;
	}

	$maxtries--;
	DBWarn("mysqld went away in process $PID. $maxtries tries left", 0);
	sleep(1);
    }
    return $result;
}
sub DBQuery($) {return DBQueryN(0,$_[0]);}

#
# Same as above, but die on error.
#
sub DBQueryFatalN($$)
{
    my($dbnum, $query) = @_;
    my($result);

    $result = DBQueryN($dbnum, $query);

    if (! $result) {
	DBFatal("DB Query failed");
    }
    return $result;
}
sub DBQueryFatal($) {return DBQueryFatalN(0,$_[0]);}

315
#
316 317 318
# Like DBQueryFatal but also fail if the query didn't return any
# results and returns the result as an array in list context or the
# first column of the result is scalar content.
319 320 321 322 323 324 325
#
sub DBQuerySingleFatalN($$)
{
    my ($dbnum, $query) = @_;
    my $query_result = DBQueryFatalN($dbnum, $query);
    DBFatal("DB Query \"$query\" didn't return any results") 
	unless $query_result->numrows > 0;
326 327
    DBFatal("DB Query \"$query\" returned more than one row")
	unless $query_result->numrows == 1;
328
    my @row = $query_result->fetchrow_array();
329
    return wantarray ? @row : $row[0];
330 331 332
}
sub DBQuerySingleFatal($) {return DBQuerySingleFatalN(0,$_[0]);}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
#
# Same as above, but just send email on error. This info is useful
# to the TB system, but the caller has to retain control.
#
sub DBQueryWarnN($$)
{
    my($dbnum, $query) = @_;
    my($result);

    $result = DBQueryN($dbnum, $query);

    if (! $result) {
	DBWarn("DB Query failed");
    }
    return $result;
}
sub DBQueryWarn($) {return DBQueryWarnN(0,$_[0]);}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
351 352 353 354 355 356
#
# Helper functions.
#
sub emdbi_die($)	{ die($_[0]); }
sub emdbi_warn($)	{ warn($_[0]); }

357 358 359 360 361 362 363 364 365 366
#
# Warn and send email after a failed DB query. First argument is the error
# message to display. The contents of $DBErrorString is also printed.
#
# usage: DBWarn(char *message)
#
sub DBWarn($;$)
{
    my($message, $nomail) = @_;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
367
    DBError(\&emdbi_warn, $message, $nomail);
368 369 370 371 372 373 374 375 376 377 378
}

#
# Same as above, but die after the warning.
#
# usage: DBFatal(char *message);
#
sub DBFatal($;$)
{
    my ($message,$nomail) = $_[0];
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
379
    DBError(\&emdbi_die, $message, $nomail);
380 381 382 383 384 385 386 387 388 389 390 391
}

#
# DBError, common parts of DBWarn and DBFatal
#
# usage: DBError(log function, message, nomail)
#
sub DBError($$;$) 
{
    my($f, $message, $nomail) = @_;
    
    if (! defined($nomail)) {
392 393 394
	if (open(MAIL, "| /usr/sbin/sendmail -t")) {
	    print MAIL "To: $TBOPS\n";
	    print MAIL "Subject: DBError\n";
395
	    print MAIL "\n";
396 397
	    print MAIL "In $SCRIPTNAME\n\n";
	    print MAIL "$message\n\n";
398 399 400
	    print MAIL "$DBErrorString\n\n";
	    close(MAIL);
	}
401 402 403 404 405 406 407 408 409 410 411 412
    }

    $f->("$message:\n$DBErrorString\n");
}

#
# Quote a string for DB insertion.
#
# usage: char *DBQuoteSpecial(char *string);
#
sub DBQuoteSpecial($)
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
413
    my ($string) = @_;
414 415 416 417 418 419

    return $DB[0]->quote($string);
}

sub DBQuoteSpecialN($$)
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
420
    my ($dbnum, $string) = @_;
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

    return $DB[$dbnum]->quote($string);
}

#
# Get the Error From the Last Database query
#
sub DBErrN($)
{
    return $DB[$_[0]]->err;
}
sub DBErr()
{
    return $DB[0]->err;
}

437 438 439 440 441 442 443 444
#
# Some utility routines for doing migration (DB upgrades).
#
sub DBTableExistsN($$)
{
    my($dbnum, $table) = @_;

    my $result =
445
	DBQueryFatalN($dbnum, "show tables like '$table'");
446 447 448 449 450 451 452 453 454 455

    return $result->numrows;
}
sub DBTableExists($) { return DBTableExistsN(0,$_[0]); }

sub DBSlotExistsN($$$)
{
    my($dbnum, $table, $slot) = @_;

    my $result =
456
	DBQueryFatalN($dbnum, "show columns from `$table` like '$slot'");
457 458 459 460 461

    return $result->numrows;
}
sub DBSlotExists($$) { return DBSlotExistsN(0,$_[0],$_[1]); }

462 463 464 465 466 467 468 469 470 471 472 473 474 475
sub DBSlotTypeN($$$)
{
    my($dbnum, $table, $slot) = @_;

    my $result =
	DBQueryFatalN($dbnum, "show columns from `$table` like '$slot'");

    return undef
	if (! $result->numrows);
    my $row = $result->fetchrow_hashref();
    return $row->{'Type'};
}
sub DBSlotType($$) { return DBSlotTypeN(0,$_[0],$_[1]); }

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
END {
    # Call it here otherwise may get:
    #   (in cleanup) Can't call method "FETCH" on an undefined value at 
    #   /usr/local/lib/perl5/site_perl/5.8.8/mach/Mysql.pm line 91 during 
    #   global destruction.
    # where line 91 is:
    #  	my $oldvalue = $self->{'dbh'}->{'InactiveDestroy'};
    # which is in setInactiveDestroy() which get called in libdb.pm in:
    #   if ($self->db_pid() != $$) {
    #       $self->setInactiveDestroy(1);
    #   }
    # which is in TestbedDBHandle::DESTROY (still in libdb.pm even
    # though it is a diffrent package)
    #
    # This error is probably due to some object being destroyed too
    # soon somewhere in the DBI/DBD modules.
    TBDBDisconnect();
}

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

1;