本文整理汇总了Python中aquilon.config.Config.has_option方法的典型用法代码示例。如果您正苦于以下问题:Python Config.has_option方法的具体用法?Python Config.has_option怎么用?Python Config.has_option使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aquilon.config.Config
的用法示例。
在下文中一共展示了Config.has_option方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_git
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
def run_git(args, env=None, path=".",
logger=LOGGER, loglevel=logging.INFO, filterre=None):
config = Config()
if env:
git_env = env.copy()
else:
git_env = {}
env_path = git_env.get("PATH", os.environ.get("PATH", ""))
git_env["PATH"] = "%s:%s" % (config.get("broker", "git_path"), env_path)
for name in ["git_author_name", "git_author_email",
"git_committer_name", "git_committer_email"]:
if not config.has_option("broker", name):
continue
value = config.get("broker", name)
git_env[name.upper()] = value
if isinstance(args, list):
git_args = args[:]
if git_args[0] != "git":
git_args.insert(0, "git")
else:
git_args = ["git", args]
return run_command(git_args, env=git_env, path=path,
logger=logger, loglevel=loglevel, filterre=filterre)
示例2: onEnter
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
def onEnter(self, dbcluster):
dbdecommissioned = HostLifecycle.get_unique(object_session(dbcluster),
"decommissioned",
compel=True)
config = Config()
archetype = dbcluster.personality.archetype
section = "archetype_" + archetype.name
opt = "allow_cascaded_deco"
if dbcluster.hosts and (not config.has_option(section, opt) or
not config.getboolean(section, opt)):
raise ArgumentError("Cannot change state to {0}, as {1}'s "
"archetype is {2}."
.format(dbdecommissioned.name, dbcluster,
archetype.name))
if dbcluster.virtual_machines:
raise ArgumentError("Cannot change state to {0}, as {1} has "
"{2} VM(s)."
.format(dbdecommissioned.name, dbcluster,
len(dbcluster.virtual_machines)))
for dbhost in dbcluster.hosts:
dbhost.status.transition(dbhost, dbdecommissioned)
示例3: discover_network_types
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
def discover_network_types(dbapi_con, connection_record): # pylint: disable=W0613
config = Config()
if not config.has_option("broker", "default_network_type"): # pragma: no cover
raise InternalError("The default_network_type option is missing from "
"the [broker] section in the configuration.")
default_type = config.get("broker", "default_network_type")
default_section = "network_" + default_type
if not config.has_section(default_section): # pragma: no cover
raise InternalError("The default network type is %s, but there's no "
"section named [%s] in the configuration." %
(default_type, default_section))
nettypes = {}
# This function should be called only once, but you never know...
if Network.network_type_map:
return
for section in config.sections():
if not section.startswith("network_"):
continue
name = section[8:]
nettypes[name] = NetworkProperties(config, name)
LOGGER.info("Configured network type %s", name)
Network.network_type_map = nettypes
Network.default_network_props = nettypes[default_type]
示例4: teststart
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
def teststart(self):
# FIXME: Either remove any old pidfiles, or ignore it as a warning
# from stderr... or IMHO (daqscott) if pid files exist and are knc or
# python processes, kill -9 the pids and delete the files (with a
# warning message it tickles you)
config = Config()
twistd = os.path.join(config.get("broker", "srcdir"),
"lib", "python2.6", "aquilon", "unittest_patches.py")
pidfile = os.path.join(config.get("broker", "rundir"), "aqd.pid")
logfile = config.get("broker", "logfile")
# Specify twistd and options...
args = [sys.executable, twistd,
"--pidfile", pidfile, "--logfile", logfile]
if config.has_option("unittest", "profile"):
if config.getboolean("unittest", "profile"):
args.append("--profile")
args.append(os.path.join(config.get("broker", "logdir"),
"aqd.profile"))
args.append("--profiler=cProfile")
args.append("--savestats")
# And then aqd and options...
args.extend(["aqd", "--config", config.baseconfig])
if config.has_option("unittest", "coverage"):
if config.getboolean("unittest", "coverage"):
args.append("--coveragedir")
dir = os.path.join(config.get("broker", "logdir"), "coverage")
args.append(dir)
coveragerc = os.path.join(config.get("broker", "srcdir"),
"tests", "coverage.rc")
args.append("--coveragerc")
args.append(coveragerc)
p = Popen(args)
self.assertEqual(p.wait(), 0)
示例5: testclonetemplateking
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
def testclonetemplateking(self):
config = Config()
source = config.get("unittest", "template_base")
dest = config.get("broker", "kingdir")
p = Popen(("/bin/rm", "-rf", dest), stdout=1, stderr=2)
rc = p.wait()
self.assertEqual(rc, 0,
"Failed to clear old template-king directory '%s'" %
dest)
env = {}
env["PATH"] = "%s:%s" % (config.get("broker", "git_path"),
os.environ.get("PATH", ""))
p = Popen(("git", "clone", "--bare", source, dest),
env=env, stdout=PIPE, stderr=PIPE)
(out, err) = p.communicate()
# Ignore out/err unless we get a non-zero return code, then log it.
self.assertEqual(p.returncode, 0,
"Non-zero return code for clone of template-king, "
"STDOUT:\[email protected]@@\n'%s'\[email protected]@@\nSTDERR:\[email protected]@@\n'%s'\[email protected]@@\n"
% (out, err))
# This value can be used to test against a different branch/commit
# than the current 'prod'.
new_prod = None
if config.has_option("unittest", "template_alternate_prod"):
new_prod = config.get("unittest", "template_alternate_prod")
if new_prod:
for domain in ['prod', 'ny-prod']:
p = Popen(("git", "push", ".", '+%s:%s' % (new_prod, domain)),
env=env, cwd=dest, stdout=PIPE, stderr=PIPE)
(out, err) = p.communicate()
# Ignore out/err unless we get a non-zero return code, then log it.
self.assertEqual(p.returncode, 0,
"Non-zero return code while setting alternate "
"'%s' branch locally to '%s':"
"\nSTDOUT:\[email protected]@@\n'%s'\[email protected]@@\n"
"\nSTDERR:\[email protected]@@\n'%s'\[email protected]@@\n"
% (domain, new_prod, out, err))
# Set the default branch
p = Popen(("git", "symbolic-ref", "HEAD", "refs/heads/prod"),
env=env, cwd=dest, stdout=PIPE, stderr=PIPE)
(out, err) = p.communicate()
self.assertEqual(p.returncode, 0,
"Non-zero return code while setting HEAD "
"to refs/heads/prod:"
"\nSTDOUT:\[email protected]@@\n'%s'\[email protected]@@\n"
"\nSTDERR:\[email protected]@@\n'%s'\[email protected]@@\n"
% (out, err))
return
示例6: main
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
def main():
from aquilon.config import Config
config = Config()
if config.has_option("database", "module"):
ms.modulecmd.load(config.get("database", "module"))
db = DbFactory()
Base.metadata.bind = db.engine
session = db.Session()
add_interfaces(session)
add_addresses(session)
session.rollback()
raise Exception("Replace the rollback() in the code with commit() when "
"ready to go, and disable this exception")
示例7: and
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
if not os.path.exists(opts.config):
print >> sys.stderr, "configfile %s does not exist" % opts.config
sys.exit(1)
if os.environ.get("AQDCONF") and (os.path.realpath(opts.config)
!= os.path.realpath(os.environ["AQDCONF"])):
force_yes("""Will ignore AQDCONF variable value:
%s
and use
%s
instead.""" % (os.environ["AQDCONF"], opts.config))
config = Config(configfile=opts.config)
if not config.has_section("unittest"):
config.add_section("unittest")
if not config.has_option("unittest", "srcdir"):
config.set("unittest", "srcdir", SRCDIR)
if opts.coverage:
config.set("unittest", "coverage", "True")
if opts.profile:
config.set("unittest", "profile", "True")
hostname = config.get("unittest", "hostname")
if hostname.find(".") < 0:
print >> sys.stderr, """
Some regression tests depend on the config value for hostname to be
fully qualified. Please set the config value manually since the default
on this system (%s) is a short name.
""" % hostname
sys.exit(1)
示例8: makeService
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
def makeService(self, options):
# Start up coverage ASAP.
coverage_dir = options["coveragedir"]
if coverage_dir:
os.makedirs(coverage_dir, 0755)
if options["coveragerc"]:
coveragerc = options["coveragerc"]
else:
coveragerc = None
self.coverage = coverage.coverage(config_file=coveragerc)
self.coverage.erase()
self.coverage.start()
# Get the config object.
config = Config(configfile=options["config"])
# Helper for finishing off the coverage report.
def stop_coverage():
log.msg("Finishing coverage")
self.coverage.stop()
aquilon_srcdir = os.path.join(config.get("broker", "srcdir"),
"lib", "python2.6", "aquilon")
sourcefiles = []
for dirpath, dirnames, filenames in os.walk(aquilon_srcdir):
# FIXME: try to do this from the coverage config file
if dirpath.endswith("aquilon"):
dirnames.remove("client")
elif dirpath.endswith("aqdb"):
dirnames.remove("utils")
for filename in filenames:
if not filename.endswith('.py'):
continue
sourcefiles.append(os.path.join(dirpath, filename))
self.coverage.html_report(sourcefiles, directory=coverage_dir)
self.coverage.xml_report(sourcefiles,
outfile=os.path.join(coverage_dir, "aqd.xml"))
with open(os.path.join(coverage_dir, "aqd.coverage"), "w") as outfile:
self.coverage.report(sourcefiles, file=outfile)
# Make sure the coverage report gets generated.
if coverage_dir:
reactor.addSystemEventTrigger('after', 'shutdown', stop_coverage)
# Set up the environment...
m = Modulecmd()
log_module_load(m, config.get("broker", "CheckNet_module"))
if config.has_option("database", "module"):
log_module_load(m, config.get("database", "module"))
sys.path.append(config.get("protocols", "directory"))
# Set this up before the aqdb libs get imported...
integrate_logging(config)
progname = os.path.split(sys.argv[0])[1]
if progname == 'aqd':
if config.get('broker', 'mode') != 'readwrite':
log.msg("Broker started with aqd symlink, "
"setting config mode to readwrite")
config.set('broker', 'mode', 'readwrite')
if progname == 'aqd_readonly':
if config.get('broker', 'mode') != 'readonly':
log.msg("Broker started with aqd_readonly symlink, "
"setting config mode to readonly")
config.set('broker', 'mode', 'readonly')
log.msg("Loading broker in mode %s" % config.get('broker', 'mode'))
# Dynamic import means that we can parse config options before
# importing aqdb. This is a hack until aqdb can be imported without
# firing up database connections.
resources = __import__("aquilon.worker.resources", globals(), locals(),
["RestServer"], -1)
RestServer = getattr(resources, "RestServer")
restServer = RestServer(config)
openSite = AnonSite(restServer)
# twisted is nicely changing the umask for us when the process is
# set to daemonize. This sets it back.
restServer.set_umask()
reactor.addSystemEventTrigger('after', 'startup', restServer.set_umask)
reactor.addSystemEventTrigger('after', 'startup',
restServer.set_thread_pool_size)
sockdir = config.get("broker", "sockdir")
if not os.path.exists(sockdir):
os.makedirs(sockdir, 0700)
os.chmod(sockdir, 0700)
if options["usesock"]:
return strports.service("unix:%s/aqdsock" % sockdir, openSite)
openport = config.get("broker", "openport")
if config.has_option("broker", "bind_address"):
bind_address = config.get("broker", "bind_address").strip()
openaddr = "tcp:%s:interface=%s" % (openport, bind_address)
else: # pragma: no cover
bind_address = None
#.........这里部分代码省略.........
示例9: Column
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
xtn_id = Column(GUID(), ForeignKey(Xtn.xtn_id, name='xtn_dtl_xtn_fk'),
nullable=False)
name = Column(String(255), nullable=False)
value = Column(String(255), default='True', nullable=False)
__table_args__ = (PrimaryKeyConstraint(xtn_id, name, value,
name="xtn_detail_pk"),
Index('xtn_dtl_name_idx', name,
oracle_compress=True),
Index('xtn_dtl_value_idx', value, oracle_compress=True),
{'oracle_compress': 'OLTP'})
Xtn.args = relationship(XtnDetail, lazy="joined", order_by=[XtnDetail.name])
if config.has_option('database', 'audit_schema'): # pragma: no cover
schema = config.get('database', 'audit_schema')
Xtn.__table__.schema = schema
XtnEnd.__table__.schema = schema
XtnDetail.__table__.schema = schema
def start_xtn(session, xtn_id, username, command, is_readonly, details, ignore):
""" Wrapper to log the start of a transaction (or running command).
Takes a dictionary with the transaction parameters. The keys are
command, usename, readonly, and details. The details parameter
is itself a a dictionary of option names to option values provided
for the command.
The options_to_split is a list of any options that need to be
示例10: TestBrokerCommand
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
class TestBrokerCommand(unittest.TestCase):
def setUp(self):
self.config = Config()
self.net = DummyNetworks()
# Need to import protocol buffers after we have the config
# object all squared away and we can set the sys.path
# variable appropriately.
# It would be simpler just to change sys.path in runtests.py,
# but this allows for each test to be run individually (without
# the runtests.py wrapper).
protodir = self.config.get("protocols", "directory")
if protodir not in sys.path:
sys.path.append(protodir)
for m in ['aqdsystems_pb2', 'aqdnetworks_pb2', 'aqdservices_pb2',
'aqddnsdomains_pb2', 'aqdlocations_pb2', 'aqdaudit_pb2',
'aqdparamdefinitions_pb2', 'aqdparameters_pb2']:
globals()[m] = __import__(m)
self.user = self.config.get("broker", "user")
self.sandboxdir = os.path.join(self.config.get("broker",
"templatesdir"),
self.user)
self.template_extension = self.config.get("panc", "template_extension")
# This method is cumbersome. Should probably develop something
# like unittest.conf.defaults.
if self.config.has_option("unittest", "scratchdir"):
self.scratchdir = self.config.get("unittest", "scratchdir")
if not os.path.exists(self.scratchdir):
os.makedirs(self.scratchdir)
if self.config.has_option("unittest", "aurora_with_node"):
self.aurora_with_node = self.config.get("unittest",
"aurora_with_node")
else:
self.aurora_with_node = "oyidb1622"
if self.config.has_option("unittest", "aurora_without_node"):
self.aurora_without_node = self.config.get("unittest",
"aurora_without_node")
else:
self.aurora_without_node = "pissp1"
self.gzip_profiles = self.config.getboolean("panc", "gzip_output")
self.profile_suffix = ".xml.gz" if self.gzip_profiles else ".xml"
dsdb_coverage_dir = os.path.join(self.config.get("unittest", "scratchdir"),
"dsdb_coverage")
for name in [DSDB_EXPECT_SUCCESS_FILE, DSDB_EXPECT_FAILURE_FILE,
DSDB_ISSUED_CMDS_FILE, DSDB_EXPECT_FAILURE_ERROR]:
path = os.path.join(dsdb_coverage_dir, name)
try:
os.remove(path)
except OSError:
pass
def tearDown(self):
pass
def template_name(self, *template, **args):
if args.get("sandbox", None):
dir = os.path.join(self.sandboxdir, args.get("sandbox"))
elif args.get("domain", None):
dir = os.path.join(self.config.get("broker", "domainsdir"),
args.get("domain"))
else:
self.assert_(0, "template_name() called without domain or sandbox")
return os.path.join(dir, *template) + self.template_extension
def plenary_name(self, *template):
dir = self.config.get("broker", "plenarydir")
return os.path.join(dir, *template) + self.template_extension
def find_template(self, *template, **args):
""" Figure out the extension of an existing template """
if args.get("sandbox", None):
dir = os.path.join(self.sandboxdir, args.get("sandbox"))
elif args.get("domain", None):
dir = os.path.join(self.config.get("broker", "domainsdir"),
args.get("domain"))
else:
self.assert_(0, "find_template() called without domain or sandbox")
base = os.path.join(dir, *template)
for extension in [".tpl", ".pan"]:
if os.path.exists(base + extension):
return base + extension
self.assert_(0, "template %s does not exist with any extension" % base)
def build_profile_name(self, *template, **args):
base = os.path.join(self.config.get("broker", "builddir"),
"domains", args.get("domain"),
"profiles", *template)
return base + self.template_extension
msversion_dev_re = re.compile('WARNING:msversion:Loading \S* from dev\n')
def runcommand(self, command, auth=True, **kwargs):
aq = os.path.join(self.config.get("broker", "srcdir"), "bin", "aq.py")
if auth:
#.........这里部分代码省略.........
示例11: Config
# 需要导入模块: from aquilon.config import Config [as 别名]
# 或者: from aquilon.config.Config import has_option [as 别名]
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.exc import DBAPIError, DatabaseError as SaDBError
from sqlalchemy.schema import CreateIndex
from sqlalchemy.dialects.oracle.base import OracleDDLCompiler
import ms.modulecmd as modcmd
try:
config = Config()
except Exception, e:
print >> sys.stderr, 'failed to read configuration: %s' % e
sys.exit(os.EX_CONFIG)
assert config, 'No configuration in db_factory'
if config.has_option("database", "module"):
modcmd.load(config.get("database", "module"))
# Add support for Oracle-specific index extensions
@compiles(CreateIndex, 'oracle')
def visit_create_index(create, compiler, **kw):
index = create.element
compiler._verify_index_table(index)
preparer = compiler.preparer
text = "CREATE "
if index.unique:
text += "UNIQUE "
if index.kwargs.get("oracle_bitmap", False):
text += "BITMAP "