libtestbed.py.in 17.7 KB
Newer Older
1
# -*- python -*-
Kirk Webb's avatar
Kirk Webb committed
2 3 4 5 6
#
# EMULAB-COPYRIGHT
# Copyright (c) 2000-2003 University of Utah and the Flux Group.
# All rights reserved.
#
7 8 9 10 11

import sys
import os
import time
import signal
Kirk Webb's avatar
Kirk Webb committed
12
import syslog
Kirk Webb's avatar
Kirk Webb committed
13
import socket
14
import traceback
15 16
import xmlrpclib

Kirk Webb's avatar
Kirk Webb committed
17
from optparse import OptionParser
Kirk Webb's avatar
Kirk Webb committed
18 19
from warnings import warn

20 21 22 23 24 25 26 27
#
# Constants
#
TBOPS             = "@TBOPSEMAIL@".replace("\\","")
MAILTAG           = "@THISHOMEBASE@"
SCRIPTNAME        = sys.argv[0][sys.argv[0].rfind("/")+1:]
DEFAULT_DATA_PATH = "@prefix@/etc/plab/" # ensure this ends in a slash

28 29 30 31 32 33 34 35
#
# Time constants (time lengths in seconds)
#
HOUR  = 60*60
DAY   = 24*HOUR
WEEK  = 7*DAY
MONTH = 30*DAY

36 37 38 39 40 41 42 43
#
# How many seconds to sleep between failures and how many times to try
# commands to both the dslice agent, and individual node managers.
#
DEF_SLEEPINT = 5
DEF_TRIES    = 3
DEF_TIMEOUT  = 1*60     # default timeout interval

Kirk Webb's avatar
Kirk Webb committed
44 45
MAXCONSECEXC = 3

46
#
Kirk Webb's avatar
Kirk Webb committed
47
# Output control variables.
48
#
Kirk Webb's avatar
Kirk Webb committed
49 50 51 52
verbose = 0
debug = 0

class TBParser (OptionParser):
53
    """
Kirk Webb's avatar
Kirk Webb committed
54 55
    Slightly modified OptionParser that simply adds some universally
    useful options.  May want to extend to have different error behavior.
56
    """
57 58
    def __init__(self, *args):
        OptionParser.__init__(self, *args)
Kirk Webb's avatar
Kirk Webb committed
59 60 61 62 63 64 65
        self.add_option("-v", "--verbose", dest="verbose", default=False,
                        action="store_true", help="Say more about internal stuff")
        self.add_option("-d", "--debug", dest="debug", default=False,
                        action="store_true", help="Say A LOT about internal stuff")
        return

    pass
66

Kirk Webb's avatar
Kirk Webb committed
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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
def SENDMAIL(To, Subj, Msg, From = None, Headers = None, Files = ()):
    """
    Sends email to someone about something :)

    This function is similar to its perl library counterpart.

    ARGS:

     To:      <string> Email address of recipient.
     Subj:    <string> Subject of email.
     Msg:     <string> Message text.
     From:    <string> Email address of sender (optional).
     Headers: <string> Extra header strings (must newline terminate all but
                       the last one) (optional).
     Files:   <tuple>  List of files to append to message body (optional).
     
    RETURNS:
     Always returns 1

    SIDE EFFECTS:
     Can raise exceptions via called methods/functions.
    """
    Tag = MAILTAG.upper()
    # damn, no good way to tell if this fails
    sm = os.popen("/usr/sbin/sendmail -t", "w")
    
    #
    # Sendmail will figure this out if not given.
    # 
    if From:
	sm.write("From: %s\n" % From)
        
    if Headers:
	sm.write("%s\n" % Headers)
        
    sm.write("X-NetBed: %s\n" % SCRIPTNAME)
    sm.write("To: %s\n" % To)
    sm.write("Subject: %s: %s\n" % (Tag, Subj))
    sm.write("\n")
    sm.write("%s\n" % Msg)
    sm.write("\n")

    if len(Files):
        for fname in Files:
            try:
                infile = open(fname)
114 115 116 117 118 119 120 121 122 123 124 125
                sm.write("\n--------- %s --------\n" % fname)

                for line in infile.readlines():
                    sm.write(line)
                    pass

                infile.close()
                pass
            except:
                pass
            pass
        pass
126 127 128 129 130
    
    sm.write("\n")
    sm.close()
    
    return 1
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
#
# General library functions
#

#
# Print out a timestamp with optional message
#
def TIMESTAMP(msgstr = ""):
    mytime = time.strftime("%H:%M:%S")
    print "TIMESTAMP: %s %s" % (mytime, msgstr)
    
#
# Termination signals, and global var to track if we got one when
# they are disabled with disable_sigs
#
TERMSIGS = (signal.SIGTERM, signal.SIGHUP, signal.SIGINT)
gotsig = 0

class SignalInterrupt(Exception):
    def __init__(self, signum):
        self.signum = signum

#
# Keep track of last terminal signal received
#
def localSigHandler(signum, frame):
    """
    Keep track of received signals.
    """
    global gotsig
    gotsig = signum
    if verbose:
        print "Caught signal %s" % signum

def disable_sigs(sigs):
    """
    Put signal watcher into place.  I wish you could just temporarily
    block (but not ignore) signals in python - alas.
    """
    osigs = {}
    for sig in sigs:
        osigs[sig] = signal.signal(sig, localSigHandler)
    return osigs

def enable_sigs(osigs):
    """
    Reinstate old signal handlers and then raise an exception if
    one was caught while we had them disabled.
    """
    global gotsig
    
    for sig,handler in osigs.items():
        signal.signal(sig, handler)

    if gotsig:
        tmp = gotsig
        gotsig = 0
        raise SignalInterrupt(tmp)


#
# Local timeout error class and generic alarm handler
# Also listed are a couple of state saving vars for the alarm handler
# when the local one is installed.  The *_alarm calls are nestable
#
class TimeoutError: pass
def alrmhandler(signum, frame):
Kirk Webb's avatar
Kirk Webb committed
199
    if debug:
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
        print "Timeout! Raising TimeoutError."
    raise TimeoutError

oalrmhandlerstk = []  # alarm handler stack
oalrmtmostk = []      # alarm timeout stack

def enable_alarm():
    """
    Install a little local alarm handler, stash away old one, and
    it's pending alarm timeout (if set).
    """
    global oalrmhandlerstk, oalrmtmostk
    oalrmhandlerstk.append(signal.signal(signal.SIGALRM, alrmhandler))
    oalrmtmo = signal.alarm(0)
    if oalrmtmo:
        oalrmtmo += time.time()
    oalrmtmostk.append(oalrmtmo)

def disable_alarm():
    """
    Restore old handler and timeout.  If the old timeout has passed, warn,
    and send the alarm signal immediately.
    """
    signal.signal(signal.SIGALRM, oalrmhandlerstk.pop())
    oalrmtmo = oalrmtmostk.pop()
    if oalrmtmo:
        diff = oalrmtmo - time.time()
        if diff > 0:
            signal.alarm(diff)
        else:
            warn("missed a timeout deadline, sending SIGALRM immediately!")
            os.kill(os.getpid(), signal.SIGALRM)
    

def ForkCmd(cmd, args=(), timeout=DEF_TIMEOUT,
            disable_sigs_parent=(), disable_sigs_child=()):
    """
    Fork and run the given command, and optionally timeout in the parent.

    ARGS:
     cmd: <bound method | function> command to run.
     args: <tuple> arguments to the above command.
     timeout: <int> seconds to wait for child/command to complete
              before killing it off and returning
     disable_sigs_parent: <tuple of ints> signals to disable in parent
     disable_sigs_child:  <tuple of ints> signals to disable in child

    RETURNS:
     two element tuple.  The first element is a boolean, indicating whether
     or not an exception was caught while executing the command.  The second
     element is the return code from the command (which could be meaningless
     if an exception was caught).

    SIDE EFFECTS:
     Forks child process to run provided command.  Blocks signals
     if instructed to with disable_sigs() (does an enable_sigs() before
     returning).
    """
    osigs = None
    childpid = os.fork()

    # parent
    if childpid:
        gotexc = 0
        exval = 256
        if disable_sigs_parent:
            osigs = disable_sigs(disable_sigs_parent)
        enable_alarm()
        signal.alarm(timeout)
        while 1:
            try:
                exval = os.waitpid(childpid, 0)[1]
            except TimeoutError:
                print "Timeout waiting for command completion: %s" % \
                      cmd.func_name
                gotexc = 1
                break
            except OSError, e:
                # Interrupted syscall: just jump back on it.
                if e.errno == 4:
                    continue
                else:
                    gotexc = 1
                    break
            except:
                gotexc = 1
                break
            else:
                break

        signal.alarm(0)
        if gotexc:
            tb = "".join(traceback.format_exception_only(*sys.exc_info()[:2]))
            print "Exception caught while trying to " \
                  "run command %s\n%s" % (cmd.func_name, tb)
            try: os.kill(childpid, signal.SIGUSR1)
            except: pass
            try: exval = os.wait()[1]
            except: exval = 256
        else:
Kirk Webb's avatar
Kirk Webb committed
300
            if debug:
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
                if os.WIFEXITED(exval):
                    print "Process complete, exit value: %d" % \
                          os.WEXITSTATUS(exval)
                if os.WIFSIGNALED(exval):
                    print "Process signalled: %d" % \
                          os.WTERMSIG(exval)

        disable_alarm()
        if osigs:
            enable_sigs(osigs)
        return (gotexc, os.WEXITSTATUS(exval))

    # child
    else:
        def sigusrexit(signum, frame):
Kirk Webb's avatar
Kirk Webb committed
316
            if debug:
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
                print "Received SIGUSR1, bailing out"
            os._exit(1)

        retval = 1
        if disable_sigs_child:
            osigs = disable_sigs(disable_sigs_child)
        signal.signal(signal.SIGUSR1, sigusrexit)
        try:
            if type(args) == tuple:
                retval = cmd(*args)
            else:
                retval = cmd(args)
        except:
            traceback.print_exception(*sys.exc_info())
        os._exit(retval)


def tryXmlrpcCmd(cmd, args = (),
                 inittries = DEF_TRIES,
                 sleepint = DEF_SLEEPINT,
337
                 OKstrs=[], NOKstrs=[], callback=None,
338 339 340 341 342 343 344 345 346 347 348 349
                 raisefault = False):
    """
    This helper/wrapper function's job is to invoke the commands to the
    central agent, or local node manager, taking steps to retry and
    recover from failure.

    ARGS:
     cmd:        <bound method | function> command to try.
     args:       <tuple> arguments to pass to the above command.
     inittries:  <int> number of retries before the function gives up
                 and reraises the last caught exception.
     sleepint:   <int> how long to sleep (in seconds) between retries.
350 351 352 353 354 355 356
     OKstrs:     <list> success strings to check against any XMLRPC faults.
                 If one is seen, then return 'success' (0)
     NOKstrs:    <list> failure strings to check against any XMLRPC faults.
                 If one is seen, then return 'failure' (1)
     callback:   <func_ptr> pointer to a function to call when an XMLRPC
                 fault is encountered.  it should return and integer, where:
                 0 means success; 1 means fail; and -1 means keep trying.
357 358 359 360 361
     raisefault: <boolean> indicates whether or not to reraise an
                 xmlrpclib Fault exception when caught.  When true it
                 also adds a new 'triesleft' member to the Fault class
                 instance containing the number of attempts this
                 function had remaining when the Fault exception was
362
                 encountered. XXX: DEPRECATED!
363 364

    RETURNS:
365
     This function returns the result returned by the passed in RPC.
366 367 368 369

    SIDE EFFECTS:
     Invokes the passed in command with the passed in arguments.
     Catches protocol/socket exceptions for command retry.
370
     Catches xmlrpclib.Fault exceptions for potential command retry.
371 372 373 374 375 376 377
     Adds a 'triesleft' member to all exceptions reraised prior to tries=0.
     Understands TimeoutError exceptions, and will reraise them.
     
    """

    tries = inittries
    
Kirk Webb's avatar
Kirk Webb committed
378
    if debug:
379 380
        print "About to perform command %s with args:\n\t%s" % \
              (cmd, args)
381

382 383 384 385 386 387 388 389
    while 1:
        tries = tries - 1
        try:
            if args:
                # have to differentiate since the '*' operator wants
                # a tuple - throws an exception if its operand isn't
                if type(args) == tuple:
                    return cmd(*args)
390 391
                elif type(args) == dict:
                    return cmd(**args)
392 393 394 395
                else:
                    return cmd(args)
            else:
                return cmd()
396 397
            pass
        # RPC returned a fault - process it here.
398
        except xmlrpclib.Fault, e:
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

            # If a callback fault handler was passed, then call it to assess
            # the damage first.
            if callback:
                cres = callback(e.faultCode, e.faultString)
                if cres == 0:
                    return "Fault received, but operation succeeded."
                elif cres == 1:
                    raise
                pass

            # If any of these string appears in the fault, then the desired
            # outcome of the function has been met, so return success.
            for fstr in OKstrs:
                if e.faultString.find(fstr) != -1:
                    return fstr
                pass
            # If any of these strings are found, then the RPC failed, no
            # sense retrying.
            for fstr in NOKstrs:
                if e.faultString.find(fstr) != -1:
                    raise
                pass
            
423 424 425
            print "XML-RPC Fault happened while executing agent " \
                  "command: %s" % cmd.func_name
            print "\tCode: %s, Error: %s" % (e.faultCode, e.faultString)
426 427 428 429
            # Raise xmlrpc exception, if requested.  Report tries left in
            # fault object.
            # XXX: this really should be removed once we've determined that
            #      no existing code uses this facility.
430 431 432
            if raisefault:
                e.triesleft = tries
                raise xmlrpclib.Fault, e
433 434 435
            pass

        # Jump out if we receive a timeout exception.
436
        except TimeoutError, e:
Kirk Webb's avatar
Kirk Webb committed
437
            if debug:
438 439 440
                print "Caught a timeout error, setting triesleft and raising."
            e.triesleft = tries
            raise TimeoutError, e
441 442 443

        # Communications errors are non-fatal unless they occur
        # several times in a row.
444 445 446
        except (socket.error, xmlrpclib.ProtocolError), e:
            print "Encountered problem communicating with agent " \
                  "while executing command: %s" % cmd.func_name
Kirk Webb's avatar
Kirk Webb committed
447
            if debug:
448
                print "Exception is of type: %s" % e
449 450
                pass
            pass
451 452 453 454 455

        if tries > 0:
            print "Sleeping for %s seconds, then retrying %s command" % \
                  (sleepint, cmd.func_name)
            time.sleep(sleepint)
456 457
            pass
        
458 459 460 461 462
        else:
            # XXX: perhaps this should raise its own, new type of
            # exception.
            print "Giving up after %s tries" % inittries
            raise
Kirk Webb's avatar
Kirk Webb committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 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 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 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 595 596 597


class logger:
    def __init__(self, logname):
        syslog.openlog(logname, syslog.LOG_PID, syslog.LOG_USER)
        self.buf = ""
        return

    def close(self):
        syslog.closelog()
        return

    def flush(self): pass
    
    def write(self, str):
        # Ugh
        self.buf += str
        while self.buf.find("\n") >= 0:
            pos = self.buf.find("\n")
            line = self.buf[:pos]
            self.buf = self.buf[pos+1:]
            syslog.syslog(line)
            pass
        return # XXX: need to return # bytes written?
    pass


class pydaemon:

    SYSLOG = "__SysLog__"
    
    def __init__(self, logname = ""):
        self.logname = logname
        return

    def daemonize(self):
        """
        Fork off into a daemon process, redirecting stdout and stderr to
        logfile.

        Based on code from the ASPN Python Cookbook.
        """
        # First fork
        if os.fork():
            sys.exit(0)
            pass
            
        # Decouple from parent environment.
        os.chdir("/") 
        os.umask(0) 
        os.setsid() 
        
        # Second fork
        if os.fork():
            sys.exit(0)
            pass

        # Redirect standard fd's
        si = open("/dev/null", 'r')
        so = open("/dev/null", 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(so.fileno(), sys.stderr.fileno())

        # Redirect output
        outfile = None
        if self.logname == self.SYSLOG:
            outfile = logger(SCRIPTNAME)
            pass
        elif self.logname:
            outfile = open(logname, "a+")
            pass
        else:
            return

        if outfile:
            sys.stdout = sys.stderr = outfile
            pass
        else:
            print "Couldn't open output log"
            pass

        return

    
    def daemonLoop(self, func, period, maxconsecexc = MAXCONSECEXC):
        """
        Forks off into a daemon process with output directed to logfile, and
        calls the given func every period seconds.
        """
        import time
        import traceback

        consecexc = maxconsecexc
        while True:
            start = time.clock()
            try:
                func()
                pass
            except SignalInterrupt, e:
                print "Received signal %s in daemon loop, exiting." % e.signum
                sys.exit(0)
                pass
            except KeyboardInterrupt:
                print "Received keyboard interrupt in daemon loop, exiting."
                sys.exit(1)
                pass
            except:
                print "Exception caught in plab daemon loop:"
                print "".join(traceback.format_exception(*sys.exc_info()))
                consecexc -= 1
                if consecexc > 0:
                    print "Going back to sleep until next scheduled run"
                else:
                    print "Too many consecutive exceptions seen, bailing out!"
                    SENDMAIL(TBOPS, "%s Exiting",
                             "The plab %s daemon has seen too many "
                             "consecutive exceptions and is bailing out."
                             "Someone needs to check the log!" %
                             (SCRIPTNAME, func.func_name), TBOPS)
                    raise
                pass
            else:
                consecexc = maxconsecexc
                pass
            
            end = time.clock()
            if end - start < period:
                wait = period - (end - start)
                print "Sleeping %g seconds" % wait
                time.sleep(wait)
                pass
            pass
        
        return # NOTREACHED