libdb.py.in 14.4 KB
Newer Older
1
# -*- python -*-
Kirk Webb's avatar
Kirk Webb committed
2
#
3
# Copyright (c) 2000-2015 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/>.
# 
# }}}
Kirk Webb's avatar
Kirk Webb committed
23
#
24 25 26 27 28 29

#
# Database functions
#

import sys
Timothy Stack's avatar
Timothy Stack committed
30
import os, os.path
31
import pwd
32 33 34
import string
import types
import traceback
35

Timothy Stack's avatar
Timothy Stack committed
36 37 38 39 40
TBPATH = os.path.join("@prefix@", "lib")
if TBPATH not in sys.path:
    sys.path.append(TBPATH)
    pass

41 42
import MySQLdb

43
from libtestbed import *
44

Kirk Webb's avatar
Kirk Webb committed
45 46 47
#
# Debug vars.
#
Kirk Webb's avatar
Kirk Webb committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
verbose = 0
debug = 0

# Constants
TBOPSPID               = "emulab-ops"
NODEDEAD_PID           = TBOPSPID
NODEDEAD_EID           = "hwdown"
TB_NODEHISTORY_OP_MOVE = "move"

# Node Log Types
TB_NODELOGTYPE_MISC    = "misc"
TB_NODELOGTYPES        = (TB_NODELOGTYPE_MISC, )
TB_DEFAULT_NODELOGTYPE = TB_NODELOGTYPE_MISC

# Node History Stuff.
TB_NODEHISTORY_OP_FREE  = "free"
TB_NODEHISTORY_OP_ALLOC	= "alloc"
TB_NODEHISTORY_OP_MOVE  = "move"
Kirk Webb's avatar
Kirk Webb committed
66 67 68 69

#
# DB variables.
#
70 71 72
__dbName = "@TBDBNAME@"
__dbQueryMaxtries = 1
__dbConnMaxtries = 5
73 74
__dbMailOnFail = True
__dbFailMailAddr = TBOPS
75

76 77 78 79 80
# Multiple connections via slots.
__DB = dict({})
# Keep connection info around for reconnects.  Except we don't save passwords!
# If a connection required a password, we throw a ManualReconnectRequiredError.
__DBConnectArgs = dict({})
81

82 83 84 85 86 87 88 89 90 91 92
class ManualReconnectRequiredError(StandardError):
    pass

def TBDBUnusedHandle():
    maxhandle = -1
    for k,v in __DB.iteritems():
        if (type(k) == types.IntType) and k > maxhandle:
            maxhandle = k
            pass
        pass
    return maxhandle+1
93

94 95 96 97 98 99 100 101 102 103 104 105
#
# By default, connect to the Emulab db.  Also supports connections to other
# dbs.  If you specify a dbnum of None, we pick the first unused one and
# return it.
#
def TBDBConnect(dbnum=0,db=None,user=None,host=None,passwd=None):
    global __DB
    global __DBConnectArgs

    if dbnum == None:
        dbnum = TBDBUnusedHandle()

David Johnson's avatar
David Johnson committed
106 107
    if __DB.has_key(dbnum) and __DB[dbnum] != None:
        return dbnum
108

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    cargs = {}
    dbname = db
    if db == None:
        dbname = __dbName
    cargs['db'] = dbname
    dbuser = user
    if user == None:
        # 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 (%d) as %s" % (dbname,dbnum,dbuser)
    cargs['user'] = dbuser
    if host != None:
        cargs['host'] = host
    if passwd != None:
        cargs['passwd'] = passwd
131

Kirk Webb's avatar
Kirk Webb committed
132
    if debug:
133 134
        print "About to try connect with args=%s" % str(cargs)
    
135 136 137
    # Connect, with retries
    for tries in range(__dbConnMaxtries):
        try:
138 139 140 141 142 143 144
            __DB[dbnum] = MySQLdb.connect(**cargs)
            # Delete the password if it exists, but make a record of it
            # so that we throw a "must manually reconnect" exception if
            # a reconnect happens.  Not ideal, but necessary.
            if cargs.has_key('passwd'):
                cargs['passwd'] = None
                pass
145 146 147
            # XXX we need this for mysql 5.5 and above to avoid metadata
            # lock hangs, even when using MyISAM tables.
            __DB[dbnum].autocommit(True)
148
            __DBConnectArgs[dbnum] = cargs
149
        except:
150 151
            if debug:
                traceback.print_exc()
152
            time.sleep(5)
153 154 155
        else:
            break
    else:
156 157
        raise RuntimeError, "Cannot connect to DB %d after several " + \
              "attempts!" % dbnum
158

159 160 161 162
    return dbnum

def TBDBReconnect(retry = False,dbnum = 0,passwd=None):
    global __dbConnMaxtries, __DB
163 164 165 166 167 168 169 170 171
    
    if retry:
        tmpConnMaxtries = __dbConnMaxtries
        # "forever"
        __dbConnMaxtries = 10000
        pass

    # Force closed if not closed yet.
    try:
172
        __DB[dbnum].close()
173 174
    except:
        pass
175 176 177 178 179 180 181 182 183 184 185
    __DB[dbnum] = None

    tconnargs = __DBConnectArgs[dbnum].copy()
    if tconnargs.has_key('passwd') and tconnargs['passwd'] == None \
           and passwd == None:
        raise ManualReconnectRequiredError("This connection requires a passwd!")
    if passwd != None:
        tconnargs = __DBConnectArgs[dbnum].copy()
        tconnargs["passwd"] = passwd
        pass
    
186
    try:
187
        TBDBConnect(dbnum=dbnum,**tconnargs)
188 189 190 191 192 193
    except RuntimeError:
        # restore old value, even though the program will probably choose
        # to die if it can't reconnect...
        if retry:
            __dbConnMaxtries = tmpConnMaxtries
            pass
194 195
        raise RuntimeError, "Cannot reconnect to DB %d after %d attempts!" \
              % (dbnum,__dbConnMaxtries)
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

    if retry:
        __dbConnMaxtries = tmpConnMaxtries
        pass

    return

#
# XXX: Ugh.
# The reason for this hack is the limited functionality across fork supported
# by MySQLdb.  The desire is that child processes, on their first query
# post-fork, should notice if they inherited the parent's connection, stop
# using that connection, and let its resources be garbage-collected, BUT NOT
# send a disconnect to the server.  Unfortunately, since MySQLdb takes all its
# functionality from a C wrapper around the MySQL libs, there is no way to both
# garbage-collect the resources and not officially disconnect.  If you set the
# connection obj to None, you call the destructor and this disconnects from the
# server.  No way to both dealloc the C resources and not disconnect.  There's
# a simple one-line fix to allow for this in the C wrapper (and better multi-
# line fixes), but I don't want to hack this in right now.
#

#
# Thus, processes that os.fork off children should call TBDBPreFork() just
# before the actual fork syscall.  Note that this method does not perform the
# fork; it merely forces a disconnect from the server.  Both the parent and the
# child will reconnect transparently upon the first query.  At this point, this
# is the best transparent sol'n, even though it's terrible!
# Of course, if you're not planning to 1) touch the connection, or 2) close
# all open filehandles in the child, you don't need to call this.
# WARNING: do not call this function if you have any connection state (i.e.,
# are in the middle of a transaction)!
#
def TBDBPreFork():
230
    unclosed = []
David Johnson's avatar
David Johnson committed
231
    for dbno in __DB.keys():
232 233 234 235 236
        if not TBDBDisconnect(dbnum=dbno):
            unclosed.append(dbno)
            pass
        pass
    if len(unclosed) > 0:
237 238
        # don't just null out object; this could perhaps fail if there's an
        # uncommitted transaction or something...
239 240
        raise RuntimeError, "Could not close db connection(s) (%s) " + \
              "in prefork!" % (",".join(unclosed))
241 242 243
    
    return

244 245
def TBDBDisconnect(dbnum=0):
    global __DB
246

247
    if __DB[dbnum]:
248
        try:
249 250
            __DB[dbnum].close()
            __DB[dbnum] = None
251 252 253 254 255 256 257
        except:
            print "Could not close db connection!"
            return False
        pass
    
    return True

258 259
def DBQuery(queryPat, querySub = (), asDict = False, dbnum = 0):
    TBDBConnect(dbnum=dbnum)
260

Kirk Webb's avatar
Kirk Webb committed
261
    if debug:
262 263 264 265
        print "Executing DB query %s" % queryPat

    tries = __dbQueryMaxtries
    while tries:
266
        if asDict:
267
            cursor = __DB[dbnum].cursor(MySQLdb.cursors.DictCursor)
268
        else:
269
            cursor = __DB[dbnum].cursor()
270 271
            pass

272 273 274
        try:
            cursor.execute(queryPat, querySub)
            ret = cursor.fetchall()
Kirk Webb's avatar
Kirk Webb committed
275
            if debug:
276 277 278 279
                rs = `ret`
                if len(rs) > 60:
                    rs = rs[:60] + "..."
                print "Result: %s" % rs
280
                pass
281
            cursor.close()
282 283
            if ret == None:
                return ()
284
            return ret
Kirk Webb's avatar
Kirk Webb committed
285
        except MySQLdb.MySQLError, e:
286
            try:
287
                __DB[dbnum].ping()
288 289 290
            except MySQLdb.MySQLError:
                # Connection is dead; need a reconnect
                try:
291
                    TBDBReconnect(True,dbnum=dbnum)
292 293 294 295 296 297 298
                    continue
                except RuntimeError:
                    print "Error: could not reconnect to mysqld!"
                    time.sleep(1)
                    pass
                pass

299 300
            tries -= 1
            if tries == 0:
301
                break
302 303 304
            pass
        pass

305 306 307
    tbmsg  = queryPat % cursor.connection.literal(querySub)
    tbmsg += "\n\n"
    tbmsg += "".join(traceback.format_exception(*sys.exc_info()))
308 309 310
    if __dbMailOnFail:
        SENDMAIL(__dbFailMailAddr,"DB query failed", "DB query failed:\n\n%s" \
                 % tbmsg, __dbFailMailAddr)
311
    return None
312

313 314
def DBQueryFatal(*args,**kwargs):
    ret = DBQuery(*args,**kwargs)
Kirk Webb's avatar
Kirk Webb committed
315 316 317
    if ret == None:
        raise RuntimeError, "DBQueryFatal failed"
    return ret
Kirk Webb's avatar
Kirk Webb committed
318

319 320
def DBQueryWarn(*args,**kwargs):
    return DBQuery(*args,**kwargs)
Kirk Webb's avatar
Kirk Webb committed
321

322 323 324
def DBQuoteSpecial(str,dbnum=0):
    TBDBConnect(dbnum=dbnum)
    return __DB[dbnum].escape_string(str)
Kirk Webb's avatar
Kirk Webb committed
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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391


#
# Map UID to DB UID (login). Does a DB check to make sure user is known to
# the DB (user obviously has a regular account), and that account will
# always match what the DB says. Redundant, I know. But consider it a
# sanity (or consistency) check.
#
# usage: UNIX2DBUID(int uid)
#        returns username if the UID is okay.
#        raises a UserError exception if the UID is bogus.
#
class UserError(StandardError): pass # XXX: need better suite of exceptions
def UNIX2DBUID (unix_uid):
    qres = \
         DBQueryFatal("select uid from users where unix_uid=%s",
                      (unix_uid))
    if not len(qres):
	raise UserError, "*** %s not a valid Emulab user!" % uid
    pwname = pwd.getpwuid(unix_uid)[0]
    dbuser = qres[0][0]
    if dbuser != pwname:
	raise UserError, "*** %s (passwd file) does not match %s (db)" % \
              (pwname, dbuser)
    return dbuser

#
# Helper. Test if numeric. Convert to dbuid if numeric.
#
def MapNumericUID(uid):
    name = ""
    try:
        uid = int(uid)
	name = UNIX2DBUID(uid)
    except ValueError:
	name = uid
        pass
    return name


#
# Return the IDX for a current experiment. 
#
# usage: TBExptIDX(char $pid, char *gid, int \$idx)
#        returns 1 if okay.
#	 returns 0 if error.
#
class UnknownExptID(StandardError): pass # XXX: need better suite of exceptions
def TBExptIDX(pid,eid):
    qres = \
         DBQueryWarn("select idx from experiments "
                     "where pid=%s and eid=%s",
                     (pid, eid))

    if not len(qres):
	raise UnknownExptID, "Experiment %s/%s unknown!" % (pid,eid)
    
    idx = qres[0][0]
    return int(idx)

#
# Insert a Log entry for a node.
#
# usage: TBSetNodeLogEntry(char *node, char *uid, char *type, char *message)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
392 393
def TBSetNodeLogEntry(node, dbuid, etype, message):
    if not TBValidNodeName(node) or not TBValidNodeLogType(etype):
Kirk Webb's avatar
Kirk Webb committed
394
	return 0
395
    idx = TBMapUIDtoIDX(dbuid)
David Johnson's avatar
David Johnson committed
396

397 398 399
    if type(idx) == tuple:
        idx = idx[0]
        pass
Kirk Webb's avatar
Kirk Webb committed
400 401
    return DBQueryWarn("insert into nodelog "
		       "values "
402
                       "(%s, NULL, %s, %s, %s, %s, now())",
403
                       (node, etype, dbuid, idx, message))
Kirk Webb's avatar
Kirk Webb committed
404 405 406 407 408 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 438 439 440

#
# Validate a node name.
#
# usage: TBValidNodeName(char *name)
#        Returns 1 if the node is valid.
#        Returns 0 if not.
#
def TBValidNodeName(node):
    qres = \
         DBQueryWarn("select node_id from nodes where node_id=%s",
                     (node))
    if len(qres) == 0:
	return 0
    return 1

#
# Validate a node log type.
#
# usage: TBValidNodeLogType(char *type)
#        Returns 1 if the type string is valid.
#        Returns 0 if not.
#
def TBValidNodeLogType(type):
    if type in TB_NODELOGTYPES:
        return 1
    return 0

#
# Mark a Phys node as down. Cannot use next reserve since the pnode is not
# going to go through the free path.
#
# usage: MarkPhysNodeDown(char *nodeid)
#
def MarkPhysNodeDown(pnode):
    pid = NODEDEAD_PID;
    eid = NODEDEAD_EID;
441 442 443 444 445 446 447 448
    exptidx = 0

    try:
        exptidx = TBExptIDX(pid, eid)
    except:
        print "*** WARNING: No such experiment %s/%s!" % (pid,eid)
	return

Kirk Webb's avatar
Kirk Webb committed
449 450
    DBQueryFatal("lock tables reserved write")
    DBQueryFatal("update reserved set "
451
		 "  exptidx=%s,pid=%s,eid=%s,rsrv_time=now() "
Kirk Webb's avatar
Kirk Webb committed
452
		 "where node_id=%s",
453
                 (exptidx,pid, eid, pnode))
Kirk Webb's avatar
Kirk Webb committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    DBQueryFatal("unlock tables")
    TBSetNodeHistory(pnode, TB_NODEHISTORY_OP_MOVE, os.getuid(), pid, eid)
    return


def TBSetNodeHistory(nodeid, op, uid, pid, eid):
    exptidx = 0

    try:
        exptidx = TBExptIDX(pid, eid)
    except:
        print "*** WARNING: No such experiment %s/%s!" % (pid,eid)
	return 0

    try:
        uid = int(uid)
        # val = <expr> ? TrueRet : FalseRet
        uid = uid == 0 and "root" or UNIX2DBUID(uid)
        pass
    except ValueError:
        pass
475 476

    idx = TBMapUIDtoIDX(uid)
Kirk Webb's avatar
Kirk Webb committed
477 478 479
    
    return DBQueryWarn("insert into node_history set "
		       "  history_id=0, node_id=%s, op=%s, "
480
		       "  uid=%s, uid_idx=%s, stamp=UNIX_TIMESTAMP(now()), "
Kirk Webb's avatar
Kirk Webb committed
481
		       "  exptidx=%s",
482
                       (nodeid,op,uid,idx,exptidx))
Kirk Webb's avatar
Kirk Webb committed
483

Kirk Webb's avatar
Kirk Webb committed
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

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!"
514 515 516 517 518

def TBMapUIDtoIDX(uid):
    uid = DBQuoteSpecial(uid)
    
    qres = DBQueryFatal("select uid_idx from users "
519 520
                        "where uid=%s and status!='archived' and status!='nonlocal'",
			(uid,))
521 522 523 524 525 526

    if len(qres) == 0:
        return 0

    return qres[0]