mainUtils.py 23.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Line too long - pylint: disable=C0301
# Invalid name  - pylint: disable=C0103

"""
mainUtils.py
------------

This file provides a rudimentary framework to support top-level option
parsing, initialization and cleanup logic common to multiple programs.

The primary interface function is 'simple_main'.  For an example of
how it is expected to be used, see gprecoverseg.

It is anticipated that the functionality of this file will grow as we
extend common functions of our gp utilities.  Please keep this in mind
and try to avoid placing logic for a specific utility here.
"""

T
Tyler Ramer 已提交
19
import errno, os, sys, shutil, yaml
20 21 22 23

gProgramName = os.path.split(sys.argv[0])[-1]
if sys.version_info < (2, 5, 0):
    sys.exit(
L
Larry Hamel 已提交
24 25
        '''Error: %s is supported on Python versions 2.5 or greater
        Please upgrade python installed on this machine.''' % gProgramName)
26 27 28 29 30

from gppylib import gplog
from gppylib.commands import gp, unix
from gppylib.commands.base import ExecutionError
from gppylib.system import configurationInterface, configurationImplGpdb, fileSystemInterface, \
L
Larry Hamel 已提交
31
    fileSystemImplOs, osInterface, osImplNative, faultProberInterface, faultProberImplGpdb
32 33 34 35 36 37 38 39 40 41 42
from optparse import OptionGroup, OptionParser, SUPPRESS_HELP


def getProgramName():
    """
    Return the name of the current top-level program from sys.argv[0]
    or the programNameOverride option passed to simple_main via mainOptions.
    """
    global gProgramName
    return gProgramName

T
Tyler Ramer 已提交
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 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 114 115 116 117 118 119 120 121 122
class PIDLockHeld(Exception):
    def __init__(self, message, path):
        self.message = message
        self.path = path

class PIDLockFile:
    """
    Create a lock, utilizing the atomic nature of mkdir on Unix
    Inside of this directory, a file named PID contains exactly the PID, with
    no newline or space, of the process which created the lock.

    The process which created the lock can release the lock. The lock will
    be released by the process which created it on object deletion
    """

    def __init__(self, path):
        self.path = path
        self.PIDfile = os.path.join(path, "PID")
        self.PID = os.getpid()

    def acquire(self):
        try:
            os.makedirs(self.path)
            with open(self.PIDfile, mode='w') as p:
                p.write(str(self.PID))
        except EnvironmentError as e:
            if e.errno == errno.EEXIST:
                raise PIDLockHeld("PIDLock already held at %s" % self.path, self.path)
            else:
                raise
        except:
            raise

    def release(self):
        """
        If the PIDfile or directory have been removed, the lock no longer
        exists, so pass
        """
        try:
            # only delete the lock if we created the lock
            if self.PID == self.read_pid():
                # remove the dir and PID file inside of it
                shutil.rmtree(self.path)
        except EnvironmentError as e:
            if e.errno == errno.ENOENT:
                pass
            else:
                raise
        except:
            raise

    def read_pid(self):
        """
        Return the PID of the process owning the lock as an int
        Return None if there is no lock
        """
        owner = ""
        try:
            with open(self.PIDfile) as p:
                owner = int(p.read())
        except EnvironmentError as e:
            if e.errno == errno.ENOENT:
                return None
            else:
                raise
        except:
            raise
        return owner

    def __enter__(self):
        self.acquire()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.release()
        return None

    def __del__(self):
        self.release()

123 124 125 126 127 128 129 130 131 132 133 134 135

class SimpleMainLock:
    """
    Tools like gprecoverseg prohibit running multiple instances at the same time
    via a simple lock file created in the MASTER_DATA_DIRECTORY.  This class takes
    care of the work to manage this lock as appropriate based on the mainOptions
    specified.

    Note that in some cases, the utility may want to recursively invoke
    itself (e.g. gprecoverseg -r).  To handle this, the caller may specify
    the name of an environment variable holding the pid already acquired by
    the parent process.
    """
L
Larry Hamel 已提交
136

137
    def __init__(self, mainOptions):
T
Tyler Ramer 已提交
138
        self.pidlockpath = mainOptions.get('pidlockpath', None)  # the directory we're using for locking
L
Larry Hamel 已提交
139 140 141 142 143 144
        self.parentpidvar = mainOptions.get('parentpidvar', None)  # environment variable holding parent pid
        self.parentpid = None  # parent pid which already has the lock
        self.ppath = None  # complete path to the lock file
        self.pidlockfile = None  # PIDLockFile object
        self.pidfilepid = None  # pid of the process which has the lock
        self.locktorelease = None  # PIDLockFile object we should release when done
145 146 147 148

        if self.parentpidvar is not None and self.parentpidvar in os.environ:
            self.parentpid = int(os.environ[self.parentpidvar])

T
Tyler Ramer 已提交
149 150
        if self.pidlockpath is not None:
            self.ppath = os.path.join(gp.get_masterdatadir(), self.pidlockpath)
L
Larry Hamel 已提交
151
            self.pidlockfile = PIDLockFile(self.ppath)
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

    def acquire(self):
        """
        Attempts to acquire the lock this process needs to proceed.

        Returns None on successful acquisition of the lock or 
          the pid of the other process which already has the lock.
        """
        # nothing to do if utiliity requires no locking
        if self.pidlockfile is None:
            return None

        # look for a lock file
        self.pidfilepid = self.pidlockfile.read_pid()
        if self.pidfilepid is not None:

            # we found a lock file
            # allow the process to proceed if the locker was our parent
            if self.pidfilepid == self.parentpid:
                return None

        # try and acquire the lock
        try:
T
Tyler Ramer 已提交
175
            self.pidlockfile.acquire()
176

T
Tyler Ramer 已提交
177
        except PIDLockHeld:
178 179 180 181 182 183 184
            self.pidfilepid = self.pidlockfile.read_pid()
            return self.pidfilepid

        # we have the lock
        # prepare for a later call to release() and take good
        # care of the process environment for the sake of our children
        self.locktorelease = self.pidlockfile
L
Larry Hamel 已提交
185
        self.pidfilepid = self.pidlockfile.read_pid()
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        if self.parentpidvar is not None:
            os.environ[self.parentpidvar] = str(self.pidfilepid)

        return None

    def release(self):
        """
        Releases the lock this process acquired.
        """
        if self.locktorelease is not None:
            self.locktorelease.release()
            self.locktorelease = None


#
# exceptions we handle specially by the simple_main framework.
#

class ProgramArgumentValidationException(Exception):
    """
    Throw this out to main to have the message possibly
    printed with a help suggestion.
    """
L
Larry Hamel 已提交
209

210 211
    def __init__(self, msg, shouldPrintHelp=False):
        "init"
212
        Exception.__init__(self, msg)
213 214 215
        self.__shouldPrintHelp = shouldPrintHelp
        self.__msg = msg

L
Larry Hamel 已提交
216
    def shouldPrintHelp(self):
217 218 219
        "shouldPrintHelp"
        return self.__shouldPrintHelp

L
Larry Hamel 已提交
220
    def getMessage(self):
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        "getMessage"
        return self.__msg


class ExceptionNoStackTraceNeeded(Exception):
    """
    Our code throws this exception when we encounter a condition
    we know can arise which demands immediate termination.
    """
    pass


class UserAbortedException(Exception):
    """
    UserAbortedException should be thrown when a user decides to stop the 
    program (at a y/n prompt, for example).
    """
    pass


L
Larry Hamel 已提交
241
def simple_main(createOptionParserFn, createCommandFn, mainOptions=None):
242 243
    """
     createOptionParserFn : a function that takes no arguments and returns an OptParser
Y
yanchaozhong 已提交
244
     createCommandFn : a function that takes two arguments (the options and the args (those that are not processed into
245 246 247 248 249 250 251 252 253
                       options) and returns an object that has "run" and "cleanup" functions.  Its "run" function must
                       run and return an exit code.  "cleanup" will be called to clean up before the program exits;
                       this can be used to clean up, for example, to clean up a worker pool

     mainOptions can include: forceQuietOutput (map to bool),
                              programNameOverride (map to string)
                              suppressStartupLogMessage (map to bool)
                              useHelperToolLogging (map to bool)
                              setNonuserOnToolLogger (map to bool, defaults to false)
T
Tyler Ramer 已提交
254
                              pidlockpath (string)
255 256 257
                              parentpidvar (string)

    """
M
Marbin Tan 已提交
258
    simple_main_internal(createOptionParserFn, createCommandFn, mainOptions)
259 260 261 262


def simple_main_internal(createOptionParserFn, createCommandFn, mainOptions):
    """
T
Tyler Ramer 已提交
263
    If caller specifies 'pidlockpath' in mainOptions then we manage the
264 265 266 267 268
    specified pid file within the MASTER_DATA_DIRECTORY before proceeding
    to execute the specified program and we clean up the pid file when
    we're done.
    """
    sml = None
T
Tyler Ramer 已提交
269
    if mainOptions is not None and 'pidlockpath' in mainOptions:
L
Larry Hamel 已提交
270
        sml = SimpleMainLock(mainOptions)
271 272 273
        otherpid = sml.acquire()
        if otherpid is not None:
            logger = gplog.get_default_logger()
T
Tyler Ramer 已提交
274 275
            logger.error("Lockfile %s indicates that an instance of %s is already running with PID %s" % (sml.ppath, getProgramName(), otherpid))
            logger.error("If this is not the case, remove the lockfile directory at %s" % (sml.ppath))
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
            return

    # at this point we have whatever lock we require
    try:
        simple_main_locked(createOptionParserFn, createCommandFn, mainOptions)
    finally:
        if sml is not None:
            sml.release()


def simple_main_locked(createOptionParserFn, createCommandFn, mainOptions):
    """
    Not to be called externally -- use simple_main instead
    """
    logger = gplog.get_default_logger()

L
Larry Hamel 已提交
292 293 294 295 296
    configurationInterface.registerConfigurationProvider(
        configurationImplGpdb.GpConfigurationProviderUsingGpdbCatalog())
    fileSystemInterface.registerFileSystemProvider(fileSystemImplOs.GpFileSystemProviderUsingOs())
    osInterface.registerOsProvider(osImplNative.GpOsProviderUsingNative())
    faultProberInterface.registerFaultProber(faultProberImplGpdb.GpFaultProberImplGpdb())
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311

    commandObject = None
    parser = None

    forceQuiet = mainOptions is not None and mainOptions.get("forceQuietOutput")
    options = None

    if mainOptions is not None and mainOptions.get("programNameOverride"):
        global gProgramName
        gProgramName = mainOptions.get("programNameOverride")
    suppressStartupLogMessage = mainOptions is not None and mainOptions.get("suppressStartupLogMessage")

    useHelperToolLogging = mainOptions is not None and mainOptions.get("useHelperToolLogging")
    nonuser = True if mainOptions is not None and mainOptions.get("setNonuserOnToolLogger") else False
    exit_status = 1
L
Larry Hamel 已提交
312

313 314 315 316 317 318 319 320 321 322 323 324
    try:
        execname = getProgramName()
        hostname = unix.getLocalHostname()
        username = unix.getUserName()

        parser = createOptionParserFn()
        (options, args) = parser.parse_args()

        if useHelperToolLogging:
            gplog.setup_helper_tool_logging(execname, hostname, username)
        else:
            gplog.setup_tool_logging(execname, hostname, username,
L
Larry Hamel 已提交
325
                                     logdir=options.ensure_value("logfileDirectory", None), nonuser=nonuser)
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

        if forceQuiet:
            gplog.quiet_stdout_logging()
        else:
            if options.ensure_value("verbose", False):
                gplog.enable_verbose_logging()
            if options.ensure_value("quiet", False):
                gplog.quiet_stdout_logging()

        if options.ensure_value("masterDataDirectory", None) is not None:
            options.master_data_directory = os.path.abspath(options.masterDataDirectory)

        if not suppressStartupLogMessage:
            logger.info("Starting %s with args: %s" % (gProgramName, ' '.join(sys.argv[1:])))

        commandObject = createCommandFn(options, args)
        exitCode = commandObject.run()
        exit_status = exitCode

    except ProgramArgumentValidationException, e:
        if e.shouldPrintHelp():
            parser.print_help()
L
Larry Hamel 已提交
348
        logger.error("%s: error: %s" % (gProgramName, e.getMessage()))
349 350
        exit_status = 2
    except ExceptionNoStackTraceNeeded, e:
L
Larry Hamel 已提交
351
        logger.error("%s error: %s" % (gProgramName, e))
352 353 354 355 356 357
        exit_status = 2
    except UserAbortedException, e:
        logger.info("User abort requested, Exiting...")
        exit_status = 4
    except ExecutionError, e:
        logger.fatal("Error occurred: %s\n Command was: '%s'\n"
L
Larry Hamel 已提交
358 359 360
                     "rc=%d, stdout='%s', stderr='%s'" % \
                     (e.summary, e.cmd.cmdStr, e.cmd.results.rc, e.cmd.results.stdout,
                      e.cmd.results.stderr))
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
        exit_status = 2
    except Exception, e:
        if options is None:
            logger.exception("%s failed.  exiting...", gProgramName)
        else:
            if options.ensure_value("verbose", False):
                logger.exception("%s failed.  exiting...", gProgramName)
            else:
                logger.fatal("%s failed. (Reason='%s') exiting..." % (gProgramName, e))
        exit_status = 2
    except KeyboardInterrupt:
        exit_status = 2
    finally:
        if commandObject:
            commandObject.cleanup()
    sys.exit(exit_status)


def addStandardLoggingAndHelpOptions(parser, includeNonInteractiveOption, includeUsageOption=False):
    """
    Add the standard options for help and logging
382 383
    to the specified parser object. Returns the logging OptionGroup so that
    callers may modify as needed.
384 385 386 387 388 389
    """
    parser.set_usage('%prog [--help] [options] ')
    parser.remove_option('-h')

    addTo = parser
    addTo.add_option('-h', '-?', '--help', action='help',
L
Larry Hamel 已提交
390
                     help='show this help message and exit')
391 392 393 394 395
    if includeUsageOption:
        parser.add_option('--usage', action="briefhelp")

    addTo = OptionGroup(parser, "Logging Options")
    parser.add_option_group(addTo)
L
Larry Hamel 已提交
396 397
    addTo.add_option('-v', '--verbose', action='store_true',
                     help='debug output.')
398
    addTo.add_option('-q', '--quiet', action='store_true',
L
Larry Hamel 已提交
399
                     help='suppress status messages')
400
    addTo.add_option("-l", None, dest="logfileDirectory", metavar="<directory>", type="string",
L
Larry Hamel 已提交
401
                     help="Logfile directory")
402 403

    if includeNonInteractiveOption:
L
Larry Hamel 已提交
404 405
        addTo.add_option('-a', dest="interactive", action='store_false', default=True,
                         help="quiet mode, do not require user input for confirmations")
406
    return addTo
407 408 409 410 411 412 413 414 415 416 417


def addMasterDirectoryOptionForSingleClusterProgram(addTo):
    """
    Add the -d master directory option to the specified parser object
    which is intended to provide the value of the master data directory.

    For programs that operate on multiple clusters at once, this function/option
    is not appropriate.
    """
    addTo.add_option('-d', '--master_data_directory', type='string',
L
Larry Hamel 已提交
418 419 420 421
                     dest="masterDataDirectory",
                     metavar="<master data directory>",
                     help="Optional. The master host data directory. If not specified, the value set" \
                          "for $MASTER_DATA_DIRECTORY will be used.")
422 423 424 425


#
# YamlMain
L
Larry Hamel 已提交
426
#
427 428 429 430 431 432 433 434 435 436 437 438

def get_yaml(targetclass):
    "get_yaml"

    # doc    - class's doc string
    # pos    - where YAML starts in doc
    # ystr   - YAML string extracted from doc

    if not hasattr(targetclass, '_yaml') or targetclass._yaml is None:
        doc = targetclass.__doc__
        pos = doc.find('%YAML')
        assert pos >= 0, "targetclass doc string is missing %YAML plan"
L
Larry Hamel 已提交
439
        ystr = doc[pos:].replace('\n    ', '\n')
440 441 442 443 444 445 446 447 448
        targetclass._yaml = yaml.load(ystr)
    return targetclass._yaml


class YamlMain:
    "YamlMain"

    def __init__(self):
        "Parse arguments based on yaml docstring"
L
Larry Hamel 已提交
449 450
        self.current = None
        self.plan = None
451
        self.scenario_name = None
L
Larry Hamel 已提交
452 453 454
        self.logger = None
        self.logfilename = None
        self.errmsg = None
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

        self.parser = YamlOptions(self).parser
        self.options, self.args = self.parser.parse_args()
        self.options.quiet = self.options.q
        self.options.verbose = self.options.v

    #
    # simple_main interface
    #
    def __call__(self, *args):
        "Allows us to use self as the create_parser and create_program functions in call to simple_main"
        return self

    def parse_args(self):
        "Called by simple_main to obtain results from parser returned by create_parser"
        return self.options, self.args

    def run(self):
        "Called by simple_main to execute the program returned by create_program"
        self.plan = Plan(self)
        self.scenario_name = self.plan.name
L
Larry Hamel 已提交
476 477 478 479
        self.logger = self.plan.logger
        self.logfilename = self.plan.logfilename
        self.errmsg = self.plan.errmsg
        self.current = []
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
        self.plan.run()

    def cleanup(self):
        "Called by simple_main to cleanup after program returned by create_program finishes"
        pass

    def simple(self):
        "Delegates setup and control to mainUtils.simple_main"
        simple_main(self, self)


#
# option parsing
#

class YamlOptions:
    "YamlOptions"

    def __init__(self, target):
        """
        Scan the class doc string of the given object, looking for the %YAML
        containing the option specification.  Parse the YAML and setup the
        corresponding OptionParser object.
        """
        # target - options object (input)
        # gname  - option group name

L
Larry Hamel 已提交
507 508
        self.y = get_yaml(target.__class__)
        self.parser = OptionParser(description=self.y['Description'], version='%prog version $Revision$')
509 510
        self.parser.remove_option('-h')
        self.parser.set_usage(self.y['Usage'])
L
Larry Hamel 已提交
511
        self.opty = self.y['Options']
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        for gname in self.opty.get('Groups', []):
            self._register_group(gname)

    def _register_group(self, gname):
        """
        Register options for the specified option group name to the OptionParser
        using an OptionGroup unless the group name starts with 'Help' in which
        case we just register the options with the top level OptionParser object.
        """
        # gname    - option group name (input)
        # gy       - option group YAML object
        # grp      - option group object
        # tgt      - where to add options (parser or option group)
        # optkey   - comma separated list of option flags
        # optval   - help string or dict with detailed option settings
        # listargs - list of option flags (e.g. ['-h', '--help'])
        # dictargs - key/value arguments to add_option

        gy = self.opty.get(gname, None)
L
Larry Hamel 已提交
531
        if gname.startswith('Help'):
532 533 534 535 536 537 538 539 540 541 542 543
            grp = None
            tgt = self.parser
        else:
            grp = OptionGroup(self.parser, gname)
            tgt = grp

        for optkey, optval in gy.items():
            listargs = optkey.split(',')
            if type(optval) == type(''):
                # short form: optval is just a help string
                dictargs = {
                    'action': 'store_true',
L
Larry Hamel 已提交
544
                    'help': optval
545 546 547 548 549 550
                }
            else:
                # optval is the complete option specification
                dictargs = optval

            # hide hidden options
L
Larry Hamel 已提交
551
            if dictargs.get('help', '').startswith('hidden'):
552 553
                dictargs['help'] = SUPPRESS_HELP

L
Larry Hamel 已提交
554
            # print 'adding', listargs, dictargs
555 556 557 558 559 560 561 562 563 564 565 566 567 568
            tgt.add_option(*listargs, **dictargs)

        if grp is not None:
            self.parser.add_option_group(grp)


#
# plan execution
#

class Task:
    "Task"

    def __init__(self, key, name, subtasks=None):
L
Larry Hamel 已提交
569 570 571 572
        self.Key = key  # task key
        self.Name = name  # task name
        self.SubTasks = subtasks  # subtasks, if any
        self.Func = None  # task function, set by _task
573 574 575 576 577 578 579 580 581 582 583

    def _print(self, main, prefix):
        print '%s %s %s:' % (prefix, self.Key, self.Name)

    def _debug(self, main, prefix):
        main.logger.debug('Execution Plan:%s %s %s%s' % (prefix, self.Key, self.Name, ':' if self.SubTasks else ''))

    def _run(self, main, prefix):
        main.logger.debug(' Now Executing:%s %s %s' % (prefix, self.Key, self.Name))
        if self.Func:
            self.Func()
L
Larry Hamel 已提交
584

585 586 587 588

class Exit(Exception):
    def __init__(self, rc, code=None, call_support=False):
        Exception.__init__(self)
L
Larry Hamel 已提交
589 590 591
        self.code = code
        self.prm = sys._getframe(1).f_locals
        self.rc = rc
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        self.call_support = call_support


class Plan:
    "Plan"

    def __init__(self, main):
        """
        Create cached yaml from class doc string of the given object, 
        looking for the %YAML indicating the beginning of the object's YAML plan and parse it.
        Build the plan stages and tasks for the specified scenario.
        """
        # main - object with yaml scenarios (input)
        # sy   - Stage yaml

L
Larry Hamel 已提交
607
        self.logger = gplog.get_default_logger()
608 609
        self.logfilename = gplog.get_logfile()

L
Larry Hamel 已提交
610 611 612
        self.main = main
        self.y = get_yaml(main.__class__)
        self.name = main.options.scenario
613
        if not self.name:
L
Larry Hamel 已提交
614 615 616 617
            self.name = self.y['Default Scenario']
        self.scenario = self.y['Scenarios'][self.name]
        self.errors = self.y['Errors']
        self.Tasks = [self._task(ty) for ty in self.scenario]
618 619 620 621 622 623 624 625 626 627 628 629

    def _task(self, ty):
        "Invoked by __init__ to build a top-level task from the YAML"

        # ty   - Task yaml (input)
        # tyk  - Task yaml key
        # tyv  - Task yaml value
        # sty  - Sub Task yaml
        # t    - Task (returned)

        for tyk, tyv in ty.items():
            key, workers = tyk.split(None, 1)
L
Larry Hamel 已提交
630
            subtasks = [self._subtask(sty) for sty in tyv]
631 632 633 634 635 636 637 638 639 640 641
            t = Task(key, workers, subtasks)
            return t

    def _subtask(self, sty):
        "Invoked by _stage to build a task from the YAML"

        # sty  - Sub Task yaml (input)
        # st   - Sub Task (returned)

        key, rest = sty.split(None, 1)
        st = Task(key, rest)
L
Larry Hamel 已提交
642
        fn = st.Name.lower().replace(' ', '_')
643 644 645 646 647 648 649 650 651 652 653 654 655 656
        try:
            st.Func = getattr(self.main, fn)
        except AttributeError, e:
            raise Exception("Failed to lookup '%s' for sub task '%s': %s" % (fn, st.Name, str(e)))
        return st

    def _dotasks(self, subtasks, prefix, action):
        "Apply an action to each subtask recursively"

        # st   - Sub Task

        for st in subtasks or []:
            self.main.current.append(st)
            action(st, self.main, prefix)
L
Larry Hamel 已提交
657
            self._dotasks(st.SubTasks, '  ' + prefix, action)
658 659 660 661 662 663
            self.main.current.pop()

    def _print(self):
        "Print in YAML form."

        print '%s:' % self.name
L
Larry Hamel 已提交
664
        self._dotasks(self.Tasks, ' -', lambda t, m, p: t._print(m, p))
665 666 667 668 669

    def run(self):
        "Run the stages and tasks."

        self.logger.debug('Execution Plan: %s' % self.name)
L
Larry Hamel 已提交
670 671
        self._dotasks(self.Tasks, ' -', lambda t, m, p: t._debug(m, p))

672 673
        self.logger.debug(' Now Executing: %s' % self.name)
        try:
L
Larry Hamel 已提交
674
            self._dotasks(self.Tasks, ' -', lambda t, m, p: t._run(m, p))
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
        except Exit, e:
            self.exit(e.code, e.prm, e.rc, e.call_support)

    def errmsg(self, code, prm={}):
        "Return a formatted error message"
        return self.errors[code] % prm

    def exit(self, code=None, prm={}, rc=1, call_support=False):
        "Terminate the application"
        if code:
            msg = self.errmsg(code, prm)
            self.logger.error(msg)
        if call_support:
            self.logger.error('Please send %s to Greenplum support.' % self.logfilename)
        self.logger.debug('exiting with status %(rc)s' % locals())
        sys.exit(rc)