def __init__(self, path, niclist): """Set the configurations. Required parameters: * path -- Path to bootstrap file * niclist -- list of possible nic names Raise InvalidConfig if there is a problem with parameters. """ if not path: raise InvalidConfig("No bootstrap path, illegal argument") name = "metadata server URL path" if not os.path.exists(path): msg = "%s '%s' does not exist on filesystem" % (name, path) raise InvalidConfig(msg) if not os.path.isabs(path): msg = "%s '%s' should be absolute path" % (name, path) raise InvalidConfig(msg) self.path = path if not isinstance(niclist, list): raise InvalidConfig("niclist must be a list") if len(niclist) == 0: raise InvalidConfig("niclist must not be empty") self.niclist = niclist
def getconfig(string=None, filepath=None): """Return SafeConfigParser instantiated from supplied config source. Keyword arguments: * string -- String containing the text of the config file (with newlines) * filepath -- Path to a config file One (and not both) of these keyword arguments must be supplied. Raise InvalidConfig if there is a problem. """ if not string and not filepath: raise InvalidConfig("neither string nor filepath was supplied " "to getconfig()") if string and filepath: raise InvalidConfig("both string and filepath were supplied " "to getconfig()") config = ConfigParser.SafeConfigParser() if string: config.readfp(FakeFile(string)) if filepath: config.read(filepath) return config
def getCommonConf(opts, config): """Return populated CommonConf object or raise InvalidConfig. Required parameters: * opts -- parsed optparse opts * config -- parsed ConfigParser """ if not opts: raise ProgrammingError("opts is None") if not config: raise ProgrammingError("config is None") polltime = POLL_DELAY_SECONDS_DEFAULT if opts.polltime: polltime = opts.polltime try: sshdkeypath = config.get("sshd", "generatedkey") hostbasedconfig = config.get("sshd", "hostbasedconfig") knownhostsconfig = config.get("sshd", "knownhostsconfig") scratchdir = config.get("ctxservice", "scratchspacedir") retr_template = config.get("ctxservice", "retr_template") retr_template2 = config.get("ctxservice", "retr_template2") err_template = config.get("ctxservice", "err_template") err_template2 = config.get("ctxservice", "err_template2") ok_template = config.get("ctxservice", "ok_template") ok_template2 = config.get("ctxservice", "ok_template2") ipandhostdir = config.get("taskpaths", "ipandhostdir") restartdir = config.get("taskpaths", "restartdir") thishostdir = config.get("taskpaths", "thishostdir") thishostfinalizedir = config.get("taskpaths", "thishostfinalizedir") logfilepath = config.get("ctxservice", "logfilepath") curl = config.get("systempaths", "curl") hostname = config.get("systempaths", "hostname") datadir = config.get("taskpaths", "datadir") etchosts_exe = config.get("taskpaths", "etchosts") except: exception_type = sys.exc_type try: exceptname = exception_type.__name__ except AttributeError: exceptname = exception_type msg = "%s: %s" % (str(exceptname), str(sys.exc_value)) raise InvalidConfig(msg) # no evaluate yet, pass False for now return CommonConf(opts.trace, False, ipandhostdir, restartdir, polltime, sshdkeypath, scratchdir, retr_template, retr_template2, err_template, err_template2, ok_template, ok_template2, hostbasedconfig, knownhostsconfig, thishostdir, thishostfinalizedir, logfilepath, curl, hostname, datadir, etchosts_exe)
def __init__(self, string): """Instantiate class with string. Required arguments: * string -- String to treat as file-like object, can contain newlines """ if string is None: raise InvalidConfig("config file (string) can not be None") self.lines = string.splitlines(True) self.gen = self.genline()
def getAmazonConf(opts, config): """Return populated AmazonConf object or raise InvalidConfig Required parameters: * opts -- parsed optparse opts * config -- parsed ConfigParser Raise InvalidConfig if there is a problem. """ if not opts: raise ProgrammingError("opts is None") if not config: raise ProgrammingError("config is None") try: localhostnameURL = config.get("ec2", "localhostnameURL") publichostnameURL = config.get("ec2", "publichostnameURL") localipURL = config.get("ec2", "localipURL") publicipURL = config.get("ec2", "publicipURL") publickeysURL = config.get("ec2", "publickeysURL") userdataURL = config.get("ec2", "userdataURL") except: exception_type = sys.exc_type try: exceptname = exception_type.__name__ except AttributeError: exceptname = exception_type msg = "%s: %s" % (str(exceptname), str(sys.exc_value)) raise InvalidConfig(msg) return AmazonConf(localhostnameURL, publichostnameURL, localipURL, publicipURL, publickeysURL, userdataURL)
def getReginstConf(opts, config): """Return populated reginstConf object or raise InvalidConfig Required parameters: * opts -- parsed optparse opts * config -- parsed ConfigParser Raise InvalidConfig if there is a problem. """ if not opts: raise ProgrammingError("opts is None") if not config: raise ProgrammingError("config is None") path = opts.bootstrap_path try: # commandline takes precendence if not path: path = config.get("reginst", "path") nicnames = config.get("reginst", "nicnames") niclist = map(string.strip, nicnames.split(",")) except: exception_type = sys.exc_type try: exceptname = exception_type.__name__ except AttributeError: exceptname = exception_type msg = "%s: %s" % (str(exceptname), str(sys.exc_value)) raise InvalidConfig(msg) return ReginstConf(path, niclist)
def mainrun(argv=None): """Consume inputs, configure logging, and launch the action. Keyword arguments: * argv -- Executable's arguments (default None) Return exit code: * 0 -- Success * 1 -- Input problem * 2 -- Configuration problem * 3 -- Problem with the local or remote system environment. * 4 -- Failure to carry out action. * 42 -- Programming error, please report if this is a non-modified release """ if os.name != 'posix': print >> sys.stderr, "Only runs on POSIX systems." return 3 starttimer() parser = parsersetup() if argv: (opts, args) = parser.parse_args(argv[1:]) else: (opts, args) = parser.parse_args() loglevel = None if opts.verbose or opts.trace: loglevel = logging.DEBUG elif opts.quiet: loglevel = logging.ERROR else: loglevel = logging.INFO log = configureLogging(loglevel, trace=opts.trace) try: validateargs(opts) #if opts.evaluate: # log.info("EVALUATE MODE ENABLED") if opts.configpath: config = getconfig(filepath=opts.configpath) else: config = getconfig(string=DEFAULTCONFIG) commonconf = getCommonConf(opts, config) if commonconf.logfilepath: addFileLogging(log, commonconf.logfilepath, None, loglevel, trace=opts.trace) setlogfilepath(commonconf.logfilepath) log.debug("[file logging enabled @ '%s'] " % commonconf.logfilepath) if opts.tryall: log.debug("action %s" % ARGS.TRYALL) elif opts.amazon: log.debug("action %s" % ARGS.AMAZON) elif opts.regular: log.debug("action %s" % ARGS.REGULAR) if opts.poweroff: log.info("OK to poweroff") try: problemscript = config.get("taskpaths", "problemscript") except: exception_type = sys.exc_type try: exceptname = exception_type.__name__ except AttributeError: exceptname = exception_type msg = "%s: %s" % (str(exceptname), str(sys.exc_value)) raise InvalidConfig(msg) setterminateok(problemscript) ####################################### ## I. Run one Instantiation action ## ####################################### # try-all could be replaced by supporting multiple action flags and # having an order (the order itself could be set via conf) iactionresult = None if not opts.tryall: if opts.regular: regconf = getReginstConf(opts, config) iaction = RegularInstantiation(commonconf, regconf) elif opts.amazon: ec2conf = getAmazonConf(opts, config) iaction = AmazonInstantiation(commonconf, ec2conf) log.info("Running instantiation action") iaction.run() iactionresult = iaction.result else: # embedded run order right now try: log.info("First running regular instantiation action") regconf = getReginstConf(opts, config) reg_iaction = RegularInstantiation(commonconf, regconf) reg_iaction.run() iactionresult = reg_iaction.result except: msg = "Problem with regular instantiation action: " exception_type = sys.exc_type try: exceptname = exception_type.__name__ except AttributeError: exceptname = exception_type msg += "%s: %s" % (str(exceptname), str(sys.exc_value)) log.error(msg) log.info("Second, running Amazon instantiation action") ec2conf = getAmazonConf(opts, config) ec2_iaction = AmazonInstantiation(commonconf, ec2conf) ec2_iaction.run() iactionresult = ec2_iaction.result # If there was an issue, exception should have been thrown: if iactionresult == None: raise ProgrammingError( "Instantiation action(s) ran to completion but no result?") ############################################################# ## II. Run one Retrieval action ## ## The Instantiation action throws an exception or ## ## places InstantiationResult in its "result" field. ## ############################################################# ractionresult = None # only one impl right now: raction = DefaultRetrieveAction(commonconf, iactionresult) log.info("Running retrieval action") raction.run() ractionresult = raction.result if ractionresult == None: raise ProgrammingError( "Retrieve Action ran to completion but no result?") ############################################################### ## III. Run one Consumption action ## ## The Retrieval action either throws an exception or ## ## places RetrieveResult object in its "result" field. ## ############################################################### # only one impl right now: caction = DefaultConsumeRetrieveResult(commonconf, ractionresult, iactionresult) log.info("Running consume action") caction.run() return 0 except InvalidInput, e: msg = "Problem with input: %s" % e.msg if log: log.critical(msg) else: print >> sys.stderr, msg return 1
def __init__(self, trace, evaluate, ipandhostdir, restartdir, polltime, sshdkeypath, scratchdir, retr_template, retr_template2, err_template, err_template2, ok_template, ok_template2, hostbasedconfig, knownhostsconfig, thishostdir, thishostfinalizedir, logfilepath, curlpath, hostnamepath, datadir, etchosts_exe): """Set the configurations. todo: many of these configs can be scoped out of common, the list has gotten long ... Required parameters: * trace -- Make extra log statements to DEBUG level (boolean). * evaluate -- "Dryrun" mode (boolean). * ipandhostdir -- The directory with role-specific task scripts that accept IP as arg1 and hostname as arg2 * restartdir -- The directory with role-specific task scripts that, if they exist, will be called after a role has received all new information (presumably to restart or start the service with its new config). * polltime -- Poll delay in seconds. * sshdkeypath -- Path to created sshd pubkey. * scratchdir -- Directory for writing temporary files to. * retr_template -- Template XML file for WS retrieval * retr_template2 -- Template XML file for WS retrieval * err_template -- Template XML file for WS error reporting * err_template2 -- Template XML file for WS error reporting * ok_template -- Template XML file for WS OK reporting * ok_template2 -- Template XML file for WS OK reporting * hostbasedconfig -- for adding hostnames to do host based authz * knownhostsconfig -- for adding pubkeys to do host based authz * thishostdir -- 'thishost' directory, see config file * thishostfinalizedir -- 'thishostfinalize' dir, see config file * logfilepath -- Path to write log file * curlpath -- relative or abs command for curl * hostnamepath -- relative or abs command for hostname * datadir -- Directory with data specific task scripts that will be called when a data field is present in the context information. * etchosts_exe -- path to send all identity info """ self.trace = trace self.evaluate = evaluate try: polltime = int(polltime) except: raise InvalidConfig( "polltime is required to be an integer (number of seconds)") self.polltime = polltime self.sshdkeypath = sshdkeypath self.scratchdir = scratchdir self.hostbasedconfig = hostbasedconfig self.knownhostsconfig = knownhostsconfig self.ipandhostdir = ipandhostdir self.restartdir = restartdir self.thishostdir = thishostdir self.thishostfinalizedir = thishostfinalizedir self.logfilepath = logfilepath self.curlpath = curlpath self.hostnamepath = hostnamepath self.datadir = datadir self.etchosts_exe = etchosts_exe # On the crazier side of things -- perhaps use ZSI but we also might # not use WS at all next round, so sticking with text-over-http hack # One important characteristic: a very low dependency situation (curl) self.retr_template = retr_template self.retr_template2 = retr_template2 self.err_template = err_template self.err_template2 = err_template2 self.ok_template = ok_template self.ok_template2 = ok_template2