libtestbed.py.in 18.4 KB
Newer Older
1
# -*- python -*-
Kirk Webb's avatar
Kirk Webb committed
2
#
3
# Copyright (c) 2000-2014 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

import sys
import os
import time
import signal
Kirk Webb's avatar
Kirk Webb committed
29
import syslog
Kirk Webb's avatar
Kirk Webb committed
30
import socket
31
import traceback
32 33
import xmlrpclib

Kirk Webb's avatar
Kirk Webb committed
34
from optparse import OptionParser
Kirk Webb's avatar
Kirk Webb committed
35 36
from warnings import warn

37 38 39 40 41 42 43 44
#
# 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

45 46 47 48 49 50 51 52
#
# Time constants (time lengths in seconds)
#
HOUR  = 60*60
DAY   = 24*HOUR
WEEK  = 7*DAY
MONTH = 30*DAY

53 54 55 56 57 58 59 60
#
# 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
61 62
MAXCONSECEXC = 3

63
#
Kirk Webb's avatar
Kirk Webb committed
64
# Output control variables.
65
#
Kirk Webb's avatar
Kirk Webb committed
66 67 68 69
verbose = 0
debug = 0

class TBParser (OptionParser):
70
    """
Kirk Webb's avatar
Kirk Webb committed
71 72
    Slightly modified OptionParser that simply adds some universally
    useful options.  May want to extend to have different error behavior.
73
    """
74 75
    def __init__(self, *args):
        OptionParser.__init__(self, *args)
Kirk Webb's avatar
Kirk Webb committed
76 77 78 79 80 81 82
        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
83

Kirk Webb's avatar
Kirk Webb committed
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
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
109
    sm = os.popen("/usr/sbin/sendmail -i -t", "w")
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    
    #
    # 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)
131 132 133 134 135 136 137 138 139 140 141 142
                sm.write("\n--------- %s --------\n" % fname)

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

                infile.close()
                pass
            except:
                pass
            pass
        pass
143 144 145 146 147
    
    sm.write("\n")
    sm.close()
    
    return 1
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
#
# 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
216
    if debug:
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 315 316
        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
317
            if debug:
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
                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
333
            if debug:
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
                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,
354
                 OKstrs=[], NOKstrs=[], callback=None,
355 356 357 358 359 360 361 362 363 364 365 366
                 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.
367 368 369 370 371 372 373
     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.
374 375 376 377 378
     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
379
                 encountered. XXX: DEPRECATED!
380 381

    RETURNS:
382
     This function returns the result returned by the passed in RPC.
383 384 385 386

    SIDE EFFECTS:
     Invokes the passed in command with the passed in arguments.
     Catches protocol/socket exceptions for command retry.
387
     Catches xmlrpclib.Fault exceptions for potential command retry.
388 389 390 391 392 393 394
     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
395
    if debug:
396 397
        print "About to perform command %s with args:\n\t%s" % \
              (cmd, args)
398

399 400 401 402 403 404 405 406
    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)
407 408
                elif type(args) == dict:
                    return cmd(**args)
409 410 411 412
                else:
                    return cmd(args)
            else:
                return cmd()
413 414
            pass
        # RPC returned a fault - process it here.
415
        except xmlrpclib.Fault, e:
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439

            # 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
            
440 441 442
            print "XML-RPC Fault happened while executing agent " \
                  "command: %s" % cmd.func_name
            print "\tCode: %s, Error: %s" % (e.faultCode, e.faultString)
443 444 445 446
            # 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.
447 448 449
            if raisefault:
                e.triesleft = tries
                raise xmlrpclib.Fault, e
450 451 452
            pass

        # Jump out if we receive a timeout exception.
453
        except TimeoutError, e:
Kirk Webb's avatar
Kirk Webb committed
454
            if debug:
455 456 457
                print "Caught a timeout error, setting triesleft and raising."
            e.triesleft = tries
            raise TimeoutError, e
458 459 460

        # Communications errors are non-fatal unless they occur
        # several times in a row.
461 462 463
        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
464
            if debug:
465
                print "Exception is of type: %s" % e
466 467
                pass
            pass
468 469 470 471 472

        if tries > 0:
            print "Sleeping for %s seconds, then retrying %s command" % \
                  (sleepint, cmd.func_name)
            time.sleep(sleepint)
473 474
            pass
        
475 476 477 478 479
        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
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 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614


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