本文整理汇总了Python中six.moves.configparser.ConfigParser.add_section方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.add_section方法的具体用法?Python ConfigParser.add_section怎么用?Python ConfigParser.add_section使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.add_section方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _load_ec_as_default_policy
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def _load_ec_as_default_policy(proxy_conf_file, swift_conf_file, **kwargs):
"""
Override swift.conf [storage-policy:0] section to use a 2+1 EC policy.
:param proxy_conf_file: Source proxy conf filename
:param swift_conf_file: Source swift conf filename
:returns: Tuple of paths to the proxy conf file and swift conf file to use
"""
_debug('Setting configuration for default EC policy')
conf = ConfigParser()
conf.read(swift_conf_file)
# remove existing policy sections that came with swift.conf-sample
for section in list(conf.sections()):
if section.startswith('storage-policy'):
conf.remove_section(section)
# add new policy 0 section for an EC policy
conf.add_section('storage-policy:0')
ec_policy_spec = {
'name': 'ec-test',
'policy_type': 'erasure_coding',
'ec_type': 'liberasurecode_rs_vand',
'ec_num_data_fragments': 2,
'ec_num_parity_fragments': 1,
'ec_object_segment_size': 1048576,
'default': True
}
for k, v in ec_policy_spec.items():
conf.set('storage-policy:0', k, str(v))
with open(swift_conf_file, 'w') as fp:
conf.write(fp)
return proxy_conf_file, swift_conf_file
示例2: add_repo
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def add_repo(
self, name, uri, repo_type='rpm-md', prio=None, dist=None, components=None
):
"""
Add yum repository
:param string name: repository base file name
:param string uri: repository URI
:param repo_type: repostory type name
:param int prio: yum repostory priority
:param dist: unused
:param components: unused
"""
repo_file = self.shared_yum_dir['reposd-dir'] + '/' + name + '.repo'
self.repo_names.append(name + '.repo')
if os.path.exists(uri):
# yum requires local paths to take the file: type
uri = 'file://' + uri
repo_config = ConfigParser()
repo_config.add_section(name)
repo_config.set(
name, 'name', name
)
repo_config.set(
name, 'baseurl', uri
)
if prio:
repo_config.set(
name, 'priority', format(prio)
)
with open(repo_file, 'w') as repo:
repo_config.write(repo)
示例3: add_repo
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def add_repo(
self, name, uri, repo_type='rpm-md',
prio=None, dist=None, components=None,
user=None, secret=None, credentials_file=None,
repo_gpgcheck=None, pkg_gpgcheck=None
):
"""
Add yum repository
:param string name: repository base file name
:param string uri: repository URI
:param repo_type: repostory type name
:param int prio: yum repostory priority
:param dist: unused
:param components: unused
:param user: unused
:param secret: unused
:param credentials_file: unused
:param bool repo_gpgcheck: enable repository signature validation
:param bool pkg_gpgcheck: enable package signature validation
"""
repo_file = self.shared_yum_dir['reposd-dir'] + '/' + name + '.repo'
self.repo_names.append(name + '.repo')
if os.path.exists(uri):
# yum requires local paths to take the file: type
uri = 'file://' + uri
repo_config = ConfigParser()
repo_config.add_section(name)
repo_config.set(
name, 'name', name
)
repo_config.set(
name, 'baseurl', uri
)
repo_config.set(
name, 'enabled', '1'
)
if prio:
repo_config.set(
name, 'priority', format(prio)
)
if repo_gpgcheck is not None:
repo_config.set(
name, 'repo_gpgcheck', '1' if repo_gpgcheck else '0'
)
if pkg_gpgcheck is not None:
repo_config.set(
name, 'gpgcheck', '1' if pkg_gpgcheck else '0'
)
with open(repo_file, 'w') as repo:
repo_config.write(RepositoryYumSpaceRemover(repo))
示例4: test_get_user_list
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def test_get_user_list(self):
config = ConfigParser()
config.add_section('slapformat')
config.set('slapformat', 'partition_amount', '3')
config.set('slapformat', 'user_base_name', 'slapuser')
config.set('slapformat', 'partition_base_name', 'slappart')
config.add_section('slapos')
config.set('slapos', 'instance_root', self.instance_root)
user_dict = entity.get_user_list(config)
username_set = {'slapuser0', 'slapuser1', 'slapuser2'}
self.assertEqual(username_set, set(user_dict))
for name in username_set:
self.assertEqual(user_dict[name].name, name)
self.assertEqual(user_dict[name].snapshot_list, [])
expected_path = "%s/slappart%s" % (self.instance_root, name.strip("slapuser"))
self.assertEqual(user_dict[name].path, expected_path)
示例5: Namespaces
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
class Namespaces(object):
r"""Helper for namespaces.
The config file would look like:
```
[carbon-relay]
pattern = carbon\.relay\.*
[carbon-cache]
pattern = carbon\.agents\.*
[carbon-aggregator]
pattern = carbon\.aggregator\.*
[prometheus]
pattern = prometheus\.*
```
"""
def __init__(self, filename=None):
"""Initializer."""
self.config = ConfigParser({}, collections.OrderedDict)
self.patterns = collections.OrderedDict()
if not filename:
self.patterns[re.compile(".*")] = "total"
self.config.add_section("total")
return
self.config.read(filename)
for section in self.config.sections():
pattern = re.compile(self.config.get(section, "pattern"))
self.patterns[pattern] = section
def lookup(self, metric_name):
"""Return the namespace corresponding to the metric."""
for pattern, section in self.patterns.items():
if pattern.match(metric_name):
return section, self.config.items(section)
return "none", None
示例6: setUp
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.conffile = os.path.join(self.tmpdir, 'zeyple.conf')
self.homedir = os.path.join(self.tmpdir, 'gpg')
self.logfile = os.path.join(self.tmpdir, 'zeyple.log')
config = ConfigParser()
config.add_section('zeyple')
config.set('zeyple', 'log_file', self.logfile)
config.set('zeyple', 'add_header', 'true')
config.add_section('gpg')
config.set('gpg', 'home', self.homedir)
config.add_section('relay')
config.set('relay', 'host', 'example.net')
config.set('relay', 'port', '2525')
with open(self.conffile, 'w') as fp:
config.write(fp)
os.mkdir(self.homedir, 0o700)
subprocess.check_call(
['gpg', '--homedir', self.homedir, '--import', KEYS_FNAME],
stderr=open('/dev/null'),
)
self.zeyple = zeyple.Zeyple(self.conffile)
self.zeyple._send_message = Mock() # don't try to send emails
示例7: _install_desktop_file
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def _install_desktop_file(self, prefix, activity_path):
cp = ConfigParser()
section = 'Desktop Entry'
cp.add_section(section)
cp.optionxform = str # Allow CamelCase entries
# Get it from the activity.info for the non-translated version
info = ConfigParser()
info.read(os.path.join(activity_path, 'activity', 'activity.info'))
cp.set(section, 'Name', info.get('Activity', 'name'))
if info.has_option('Activity', 'summary'):
cp.set(section, 'Comment', info.get('Activity', 'summary'))
for path in sorted(glob(os.path.join(activity_path, 'locale',
'*', 'activity.linfo'))):
locale = path.split(os.path.sep)[-2]
info = ConfigParser()
info.read(path)
if info.has_option('Activity', 'name'):
cp.set(section, 'Name[{}]'.format(locale),
info.get('Activity', 'name'))
if info.has_option('Activity', 'summary'):
cp.set(section, 'Comment[{}]'.format(locale),
info.get('Activity', 'summary'))
cp.set(section, 'Terminal', 'false')
cp.set(section, 'Type', 'Application')
cp.set(section, 'Categories', 'Education;')
cp.set(section, 'Icon', os.path.join(
activity_path, 'activity', self.config.bundle.get_icon_filename()))
cp.set(section, 'Exec', self.config.bundle.get_command())
cp.set(section, 'Path', activity_path) # Path == CWD for running
name = '{}.activity.desktop'.format(self.config.bundle_id)
path = os.path.join(prefix, 'share', 'applications', name)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
with open(path, 'w') as f:
cp.write(f)
示例8: run
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def run(self, args, **kwargs):
if not args.password:
args.password = getpass.getpass()
instance = self.resource(ttl=args.ttl) if args.ttl else self.resource()
cli = BaseCLIApp()
# Determine path to config file
try:
config_file = cli._get_config_file_path(args)
except ValueError:
# config file not found in args or in env, defaulting
config_file = config_parser.ST2_CONFIG_PATH
# Retrieve token
manager = self.manager.create(instance, auth=(args.username, args.password), **kwargs)
cli._cache_auth_token(token_obj=manager)
# Update existing configuration with new credentials
config = ConfigParser()
config.read(config_file)
# Modify config (and optionally populate with password)
if not config.has_section('credentials'):
config.add_section('credentials')
config.set('credentials', 'username', args.username)
if args.write_password:
config.set('credentials', 'password', args.password)
else:
# Remove any existing password from config
config.remove_option('credentials', 'password')
with open(config_file, 'w') as cfg_file_out:
config.write(cfg_file_out)
return manager
示例9: _in_process_setup_ring
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def _in_process_setup_ring(swift_conf, conf_src_dir, testdir):
"""
If SWIFT_TEST_POLICY is set:
- look in swift.conf file for specified policy
- move this to be policy-0 but preserving its options
- copy its ring file to test dir, changing its devices to suit
in process testing, and renaming it to suit policy-0
Otherwise, create a default ring file.
"""
conf = ConfigParser()
conf.read(swift_conf)
sp_prefix = 'storage-policy:'
try:
# policy index 0 will be created if no policy exists in conf
policies = parse_storage_policies(conf)
except PolicyError as e:
raise InProcessException(e)
# clear all policies from test swift.conf before adding test policy back
for policy in policies:
conf.remove_section(sp_prefix + str(policy.idx))
if policy_specified:
policy_to_test = policies.get_by_name(policy_specified)
if policy_to_test is None:
raise InProcessException('Failed to find policy name "%s"'
% policy_specified)
_info('Using specified policy %s' % policy_to_test.name)
else:
policy_to_test = policies.default
_info('Defaulting to policy %s' % policy_to_test.name)
# make policy_to_test be policy index 0 and default for the test config
sp_zero_section = sp_prefix + '0'
conf.add_section(sp_zero_section)
for (k, v) in policy_to_test.get_info(config=True).items():
conf.set(sp_zero_section, k, str(v))
conf.set(sp_zero_section, 'default', 'True')
with open(swift_conf, 'w') as fp:
conf.write(fp)
# look for a source ring file
ring_file_src = ring_file_test = 'object.ring.gz'
if policy_to_test.idx:
ring_file_src = 'object-%s.ring.gz' % policy_to_test.idx
try:
ring_file_src = _in_process_find_conf_file(conf_src_dir, ring_file_src,
use_sample=False)
except InProcessException as e:
if policy_specified:
raise InProcessException('Failed to find ring file %s'
% ring_file_src)
ring_file_src = None
ring_file_test = os.path.join(testdir, ring_file_test)
if ring_file_src:
# copy source ring file to a policy-0 test ring file, re-homing servers
_info('Using source ring file %s' % ring_file_src)
ring_data = ring.RingData.load(ring_file_src)
obj_sockets = []
for dev in ring_data.devs:
device = 'sd%c1' % chr(len(obj_sockets) + ord('a'))
utils.mkdirs(os.path.join(_testdir, 'sda1'))
utils.mkdirs(os.path.join(_testdir, 'sda1', 'tmp'))
obj_socket = listen_zero()
obj_sockets.append(obj_socket)
dev['port'] = obj_socket.getsockname()[1]
dev['ip'] = '127.0.0.1'
dev['device'] = device
dev['replication_port'] = dev['port']
dev['replication_ip'] = dev['ip']
ring_data.save(ring_file_test)
else:
# make default test ring, 3 replicas, 4 partitions, 3 devices
# which will work for a replication policy or a 2+1 EC policy
_info('No source object ring file, creating 3rep/4part/3dev ring')
obj_sockets = [listen_zero() for _ in (0, 1, 2)]
replica2part2dev_id = [[0, 1, 2, 0],
[1, 2, 0, 1],
[2, 0, 1, 2]]
devs = [{'id': 0, 'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1',
'port': obj_sockets[0].getsockname()[1]},
{'id': 1, 'zone': 1, 'device': 'sdb1', 'ip': '127.0.0.1',
'port': obj_sockets[1].getsockname()[1]},
{'id': 2, 'zone': 2, 'device': 'sdc1', 'ip': '127.0.0.1',
'port': obj_sockets[2].getsockname()[1]}]
ring_data = ring.RingData(replica2part2dev_id, devs, 30)
with closing(GzipFile(ring_file_test, 'wb')) as f:
pickle.dump(ring_data, f)
for dev in ring_data.devs:
_debug('Ring file dev: %s' % dev)
return obj_sockets
示例10: makeconfigfile
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def makeconfigfile(fname,beamlist,radarname,simparams_orig):
"""This will make the config file based off of the desired input parmeters.
Inputs
fname - Name of the file as a string.
beamlist - A list of beams numbers used by the AMISRS
radarname - A string that is the name of the radar being simulated.
simparams_orig - A set of simulation parameters in a dictionary."""
fname = Path(fname).expanduser()
curpath = Path(__file__).resolve().parent
d_file = curpath/'default.ini'
fext = fname.suffix
# reduce the number of stuff needed to be saved and avoid problems with writing
keys2save = ['IPP', 'TimeLim', 'RangeLims', 'Pulselength', 't_s', 'Pulsetype',
'Tint', 'Fitinter', 'NNs', 'dtype', 'ambupsamp', 'species',
'numpoints', 'startfile', 'FitType','beamrate', 'outangles']
if not 'beamrate' in simparams_orig.keys():
simparams_orig['beamrate'] = 1
if not 'outangles' in simparams_orig.keys():
simparams_orig['outangles'] = beamlist
simparams = {i:simparams_orig[i] for i in keys2save}
if fext =='.pickle':
pickleFile = fname.open('wb')
pickle.dump([{'beamlist':beamlist,'radarname':radarname},simparams],pickleFile)
pickleFile.close()
elif fext=='.yml':
with fname.open('w') as f:
yaml.dump([{'beamlist':beamlist,'radarname':radarname},simparams], f)
elif fext =='.ini':
defaultparser = ConfigParser()
defaultparser.read(str(d_file))
# config = configparser()
# config.read(fname)
cfgfile = open(str(fname),'w')
config = ConfigParser(allow_no_value = True)
config.add_section('section 1')
beamstring = ""
for beam in beamlist:
beamstring += str(beam)
beamstring += " "
config.set('section 1','; beamlist must be list of ints')
config.set('section 1','beamlist',beamstring)
config.set('section 1','; radarname can be pfisr, risr, or sondastrom')
config.set('section 1','radarname',radarname)
config.add_section('simparams')
config.add_section('simparamsnames')
defitems = [i[0] for i in defaultparser.items('simparamsnotes')]
for param in simparams:
if param=='Beamlist':
continue
if param.lower() in defitems:
paramnote = defaultparser.get('simparamsnotes',param.lower())
else:
paramnote = 'Not in default parameters'
config.set('simparams','; '+param +' '+paramnote)
# for the output list of angles
if param.lower()=='outangles':
outstr = ''
beamlistlist = simparams[param]
if beamlistlist=='':
beamlistlist=beamlist
for ilist in beamlistlist:
if isinstance(ilist,list) or isinstance(ilist,sp.ndarray):
for inum in ilist:
outstr=outstr+str(inum)+' '
else:
outstr=outstr+str(ilist)
outstr=outstr+', '
outstr=outstr[:-2]
config.set('simparams',param,outstr)
elif isinstance(simparams[param],list):
data = ""
for a in simparams[param]:
data += str(a)
data += " "
config.set('simparams',param,str(data))
else: #TODO config.set() is obsolete, undefined behavior! use mapping protocol instead https://docs.python.org/3/library/configparser.html#mapping-protocol-access
config.set('simparams',param,str(simparams[param]))
config.set('simparamsnames',param,param)
config.write(cfgfile)
cfgfile.close()
else:
raise ValueError('fname needs to have an extension of .pickle or .ini')
示例11: Configuration
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
class Configuration(object):
defaults = {}
def __init__(self, filename=None):
self._config = ConfigParser()
self._set_defaults()
self._state_drivers = {}
if filename is not None:
self.load(filename)
def _set_defaults(self):
"""Set defaults for config
"""
self._config.add_section('main')
for key, value in six.iteritems(self.defaults):
if isinstance(value, dict):
self._config.add_section(key)
for subkey, subvalue in six.iteritems(value):
self._config.set(key, subkey, subvalue)
else:
self._config.set('main', key, value)
def load(self, filename):
"""Load the configuration by filename
"""
self._config.read(filename)
def save(self, filename):
"""Save the configuration to a file
"""
with open(filename, 'w') as handle:
self._config.write(handle)
@staticmethod
def sanitize(items):
options = {}
for key, value in items:
if key.endswith('[int]'):
options[key[:-5]] = int(value)
elif key.endswith('[bool]'):
value = value.lower()
if value in BOOL_MAP[True]:
value = True
elif value in BOOL_MAP[False]:
value = False
else:
raise ValueError('Expected boolean for {}'.format(key))
options[key[:-6]] = value
else:
options[key] = value
return options
def __getitem__(self, name):
if self._config.has_section(name):
return self.sanitize(self._config.items(name))
elif name == 'main':
raise ValueError('Missing main section of configuration')
return self['main'][name]
def state_driver(self, name='ai'):
"""Get an instance of the state driver
"""
from database import state
if name not in self._state_drivers:
extras = self[name]
driver = extras.pop('state-driver')
if driver == 'redis':
self._state_drivers[name] = state.RedisDriver(self, extras)
elif driver == 'dict':
self._state_drivers[name] = state.MemoryDriver(self, extras)
else:
raise ValueError('Unknown state driver')
return self._state_drivers[name]
示例12: RepositoryZypper
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
#.........这里部分代码省略.........
),
'solv-cache-dir': os.sep.join(
[manager_base, 'zypper/solv']
),
'raw-cache-dir': os.sep.join(
[manager_base, 'zypper/raw']
),
'cache-dir': os.sep.join(
[manager_base, 'zypper']
)
}
self.runtime_zypper_config_file = NamedTemporaryFile(
dir=self.root_dir
)
self.runtime_zypp_config_file = NamedTemporaryFile(
dir=self.root_dir
)
self.zypper_args = [
'--non-interactive',
'--pkg-cache-dir', self.shared_zypper_dir['pkg-cache-dir'],
'--reposd-dir', self.shared_zypper_dir['reposd-dir'],
'--solv-cache-dir', self.shared_zypper_dir['solv-cache-dir'],
'--cache-dir', self.shared_zypper_dir['cache-dir'],
'--raw-cache-dir', self.shared_zypper_dir['raw-cache-dir'],
'--config', self.runtime_zypper_config_file.name
] + self.custom_args
self.command_env = self._create_zypper_runtime_environment()
# config file parameters for zypper tool
self.runtime_zypper_config = ConfigParser()
self.runtime_zypper_config.add_section('main')
# config file parameters for libzypp library
self.runtime_zypp_config = ConfigParser()
self.runtime_zypp_config.add_section('main')
self.runtime_zypp_config.set(
'main', 'credentials.global.dir',
self.shared_zypper_dir['credentials-dir']
)
if self.exclude_docs:
self.runtime_zypp_config.set(
'main', 'rpm.install.excludedocs', 'yes'
)
if self.gpgcheck:
self.runtime_zypp_config.set(
'main', 'gpgcheck', '1'
)
else:
self.runtime_zypp_config.set(
'main', 'gpgcheck', '0'
)
self._write_runtime_config()
def use_default_location(self):
"""
Setup zypper repository operations to store all data
in the default places
"""
self.shared_zypper_dir['reposd-dir'] = \
self.root_dir + '/etc/zypp/repos.d'
self.shared_zypper_dir['credentials-dir'] = \
示例13: __spawn_instance
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
def __spawn_instance(self):
"""
Create and configure a new KRA instance using pkispawn.
Creates a configuration file with IPA-specific
parameters and passes it to the base class to call pkispawn
"""
# Create an empty and secured file
(cfg_fd, cfg_file) = tempfile.mkstemp()
os.close(cfg_fd)
pent = pwd.getpwnam(self.service_user)
os.chown(cfg_file, pent.pw_uid, pent.pw_gid)
# Create KRA configuration
config = ConfigParser()
config.optionxform = str
config.add_section("KRA")
# Security Domain Authentication
config.set("KRA", "pki_security_domain_https_port", "443")
config.set("KRA", "pki_security_domain_password", self.admin_password)
config.set("KRA", "pki_security_domain_user", self.admin_user)
# issuing ca
config.set("KRA", "pki_issuing_ca_uri", "https://%s" %
ipautil.format_netloc(self.fqdn, 443))
# Server
config.set("KRA", "pki_enable_proxy", "True")
config.set("KRA", "pki_restart_configured_instance", "False")
config.set("KRA", "pki_backup_keys", "True")
config.set("KRA", "pki_backup_password", self.admin_password)
# Client security database
config.set("KRA", "pki_client_database_dir", self.agent_db)
config.set("KRA", "pki_client_database_password", self.admin_password)
config.set("KRA", "pki_client_database_purge", "False")
config.set("KRA", "pki_client_pkcs12_password", self.admin_password)
# Administrator
config.set("KRA", "pki_admin_name", self.admin_user)
config.set("KRA", "pki_admin_uid", self.admin_user)
config.set("KRA", "pki_admin_email", "[email protected]")
config.set("KRA", "pki_admin_password", self.admin_password)
config.set("KRA", "pki_admin_nickname", "ipa-ca-agent")
config.set("KRA", "pki_admin_subject_dn",
str(DN(('cn', 'ipa-ca-agent'), self.subject_base)))
config.set("KRA", "pki_import_admin_cert", "True")
config.set("KRA", "pki_admin_cert_file", paths.ADMIN_CERT_PATH)
config.set("KRA", "pki_client_admin_cert_p12", paths.DOGTAG_ADMIN_P12)
# Directory server
config.set("KRA", "pki_ds_ldap_port", "389")
config.set("KRA", "pki_ds_password", self.dm_password)
config.set("KRA", "pki_ds_base_dn", self.basedn)
config.set("KRA", "pki_ds_database", "ipaca")
config.set("KRA", "pki_ds_create_new_db", "False")
self._use_ldaps_during_spawn(config)
# Certificate subject DNs
config.set("KRA", "pki_subsystem_subject_dn",
str(DN(('cn', 'CA Subsystem'), self.subject_base)))
config.set("KRA", "pki_ssl_server_subject_dn",
str(DN(('cn', self.fqdn), self.subject_base)))
config.set("KRA", "pki_audit_signing_subject_dn",
str(DN(('cn', 'KRA Audit'), self.subject_base)))
config.set(
"KRA", "pki_transport_subject_dn",
str(DN(('cn', 'KRA Transport Certificate'), self.subject_base)))
config.set(
"KRA", "pki_storage_subject_dn",
str(DN(('cn', 'KRA Storage Certificate'), self.subject_base)))
# Certificate nicknames
# Note that both the server certs and subsystem certs reuse
# the ca certs.
config.set("KRA", "pki_subsystem_nickname",
"subsystemCert cert-pki-ca")
config.set("KRA", "pki_ssl_server_nickname",
"Server-Cert cert-pki-ca")
config.set("KRA", "pki_audit_signing_nickname",
"auditSigningCert cert-pki-kra")
config.set("KRA", "pki_transport_nickname",
"transportCert cert-pki-kra")
config.set("KRA", "pki_storage_nickname",
"storageCert cert-pki-kra")
# Shared db settings
# Needed because CA and KRA share the same database
# We will use the dbuser created for the CA
config.set("KRA", "pki_share_db", "True")
config.set(
"KRA", "pki_share_dbuser_dn",
str(DN(('uid', 'pkidbuser'), ('ou', 'people'), ('o', 'ipaca'))))
_p12_tmpfile_handle, p12_tmpfile_name = tempfile.mkstemp(dir=paths.TMP)
if self.clone:
krafile = self.pkcs12_info[0]
#.........这里部分代码省略.........
示例14: RepositoryYum
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
class RepositoryYum(RepositoryBase):
"""
Implements repository handling for yum package manager
"""
def post_init(self, custom_args=None):
"""
Post initialization method
Store custom yum arguments and create runtime configuration
and environment
Attributes
* :attr:`shared_yum_dir`
shared directory between image root and build system root
* :attr:`runtime_yum_config_file`
yum runtime config file name
* :attr:`command_env`
customized os.environ for yum
* :attr:`runtime_yum_config`
Instance of ConfigParser
:param list custom_args: yum arguments
"""
self.custom_args = custom_args
if not custom_args:
self.custom_args = []
self.repo_names = []
# yum support is based on creating repo files which contains
# path names to the repo and its cache. In order to allow a
# persistent use of the files in and outside of a chroot call
# an active bind mount from RootBind::mount_shared_directory
# is expected and required
manager_base = self.shared_location + '/yum'
self.shared_yum_dir = {
'reposd-dir': manager_base + '/repos',
'cache-dir': manager_base + '/cache'
}
self.runtime_yum_config_file = NamedTemporaryFile(
dir=self.root_dir
)
self.yum_args = [
'-c', self.runtime_yum_config_file.name, '-y'
] + self.custom_args
self.command_env = self._create_yum_runtime_environment()
# config file parameters for yum tool
self._create_runtime_config_parser()
self._write_runtime_config()
def use_default_location(self):
"""
Setup yum repository operations to store all data
in the default places
"""
self.shared_yum_dir['reposd-dir'] = \
self.root_dir + '/etc/yum/repos.d'
self.shared_yum_dir['cache-dir'] = \
self.root_dir + '/var/cache/yum'
self._create_runtime_config_parser()
self._write_runtime_config()
def runtime_config(self):
"""
yum runtime configuration and environment
"""
return {
'yum_args': self.yum_args,
'command_env': self.command_env
}
def add_repo(
self, name, uri, repo_type='rpm-md', prio=None, dist=None, components=None
):
"""
Add yum repository
:param string name: repository base file name
:param string uri: repository URI
:param repo_type: repostory type name
:param int prio: yum repostory priority
:param dist: unused
:param components: unused
"""
repo_file = self.shared_yum_dir['reposd-dir'] + '/' + name + '.repo'
self.repo_names.append(name + '.repo')
if os.path.exists(uri):
# yum requires local paths to take the file: type
uri = 'file://' + uri
repo_config = ConfigParser()
repo_config.add_section(name)
#.........这里部分代码省略.........
示例15: RepositoryZypper
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import add_section [as 别名]
class RepositoryZypper(RepositoryBase):
"""
Implements repo handling for zypper package manager
"""
def post_init(self, custom_args=None):
"""
Post initialization method
Store custom zypper arguments and create runtime configuration
and environment
Attributes
* :attr:`shared_zypper_dir`
shared directory between image root and build system root
* :attr:`runtime_zypper_config_file`
zypper runtime config file name
* :attr:`runtime_zypp_config_file`
libzypp runtime config file name
* :attr:`zypper_args`
zypper caller args plus additional custom args
* :attr:`command_env`
customized os.environ for zypper
* :attr:`runtime_zypper_config`
Instance of ConfigParser
:param list custom_args: zypper arguments
"""
self.custom_args = custom_args
if not custom_args:
self.custom_args = []
self.repo_names = []
# zypper support by default point all actions into the root
# directory of the image system. This information is passed
# as arguments to zypper and adapted if the call runs as
# chrooted operation. Therefore the use of the shared location
# via RootBind::mount_shared_directory is optional but
# recommended to make use of the repo cache
manager_base = self.root_dir + self.shared_location
self.shared_zypper_dir = {
'pkg-cache-dir': manager_base + '/packages',
'reposd-dir': manager_base + '/zypper/repos',
'solv-cache-dir': manager_base + '/zypper/solv',
'raw-cache-dir': manager_base + '/zypper/raw',
'cache-dir': manager_base + '/zypper'
}
self.runtime_zypper_config_file = NamedTemporaryFile(
dir=self.root_dir
)
self.runtime_zypp_config_file = NamedTemporaryFile(
dir=self.root_dir
)
self.zypper_args = [
'--non-interactive', '--no-gpg-checks',
'--pkg-cache-dir', self.shared_zypper_dir['pkg-cache-dir'],
'--reposd-dir', self.shared_zypper_dir['reposd-dir'],
'--solv-cache-dir', self.shared_zypper_dir['solv-cache-dir'],
'--cache-dir', self.shared_zypper_dir['cache-dir'],
'--raw-cache-dir', self.shared_zypper_dir['raw-cache-dir'],
'--config', self.runtime_zypper_config_file.name
] + self.custom_args
self.command_env = self._create_zypper_runtime_environment()
# config file parameters for zypper tool
self.runtime_zypper_config = ConfigParser()
self.runtime_zypper_config.add_section('main')
# config file parameters for libzypp library
self.runtime_zypp_config = ConfigParser()
self.runtime_zypp_config.add_section('main')
self.runtime_zypp_config.set(
'main', 'cachedir', self.shared_zypper_dir['cache-dir']
)
self.runtime_zypp_config.set(
'main', 'metadatadir', self.shared_zypper_dir['raw-cache-dir']
)
self.runtime_zypp_config.set(
'main', 'solvfilesdir', self.shared_zypper_dir['solv-cache-dir']
)
self.runtime_zypp_config.set(
'main', 'packagesdir', self.shared_zypper_dir['pkg-cache-dir']
)
self._write_runtime_config()
def use_default_location(self):
"""
Setup zypper repository operations to store all data
in the default places
#.........这里部分代码省略.........