Commit 6d4ca49c authored by Leigh B. Stoller's avatar Leigh B. Stoller
Browse files

This file has moved to the db directory since its used by more then just

plab code.
parent e6d9909a
# -*- python -*-
#
# EMULAB-COPYRIGHT
# Copyright (c) 2000-2004 University of Utah and the Flux Group.
# All rights reserved.
#
#
# Database functions
#
import sys
sys.path.append("@prefix@/lib")
import os
import pwd
import MySQLdb
from libtestbed import *
#
# Debug vars.
#
verbose = 0;
debug = 0;
#
# DB variables.
#
__dbName = "@TBDBNAME@"
__dbQueryMaxtries = 1
__dbConnMaxtries = 5
__dbConnection = None
def TBDBConnect():
global __dbConnection
if __dbConnection:
return
# Create a DB username for accounting purposes
uid = os.getuid()
try:
name = pwd.getpwuid(uid)[0]
except KeyError:
name = "uid%d" % uid
dbuser = "%s:%s:%d" % (sys.argv[0], name, os.getpid())
if debug:
print "Connecting to db %s as %s" % (__dbName, dbuser)
# Connect, with retries
for tries in range(__dbConnMaxtries):
try:
__dbConnection = MySQLdb.connect(db = __dbName, user = dbuser)
except:
time.sleep(1)
else:
break
else:
raise RuntimeError, "Cannot connect to DB after several attempts!"
def DBQuery(queryPat, querySub = (), asDict = False):
TBDBConnect()
if asDict:
cursor = __dbConnection.cursor(MySQLdb.cursors.DictCursor)
else:
cursor = __dbConnection.cursor()
if debug:
print "Executing DB query %s" % queryPat
tries = __dbQueryMaxtries
while tries:
try:
cursor.execute(queryPat, querySub)
ret = cursor.fetchall()
if debug:
rs = `ret`
if len(rs) > 60:
rs = rs[:60] + "..."
print "Result: %s" % rs
pass
if ret == None:
return ()
return ret
except MySQLdb.MySQLError:
tries -= 1
if tries == 0:
break
else:
time.sleep(1)
try:
__dbConnection.ping()
except MySQLdb.MySQLError:
pass
tbmsg = queryPat % cursor.connection.literal(querySub)
tbmsg += "\n\n"
tbmsg += "".join(traceback.format_exception(*sys.exc_info()))
SENDMAIL(TBOPS, "DB query failed", "DB query failed:\n\n%s" % tbmsg, TBOPS)
return None
def DBQueryFatal(*args):
ret = DBQuery(*args)
if ret == None:
raise RuntimeError, "DBQueryFatal failed"
return ret
def TBSiteVarExists(name):
name = DBQuoteSpecial(name)
qres = DBQueryFatal("select name from sitevariables "
"where name=%s", (name,))
if len(qres) > 0:
return 1
else:
return 0
pass
def TBGetSiteVar(name):
name = DBQuoteSpecial(name)
qres = DBQueryFatal("select value, defaultvalue from sitevariables "
"where name=%s", (name,))
if len(qres) > 0:
value, defaultvalue = qres[0]
if value: return value
elif defaultvalue: return defaultvalue
pass
raise RuntimeException, \
"*** attempted to fetch unknown site variable name!"
def DBQuoteSpecial(str):
TBDBConnect()
return __dbConnection.escape_string(str)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment