repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
juju/charm-helpers | charmhelpers/contrib/templating/contexts.py | dict_keys_without_hyphens | def dict_keys_without_hyphens(a_dict):
"""Return the a new dict with underscores instead of hyphens in keys."""
return dict(
(key.replace('-', '_'), val) for key, val in a_dict.items()) | python | def dict_keys_without_hyphens(a_dict):
"""Return the a new dict with underscores instead of hyphens in keys."""
return dict(
(key.replace('-', '_'), val) for key, val in a_dict.items()) | [
"def",
"dict_keys_without_hyphens",
"(",
"a_dict",
")",
":",
"return",
"dict",
"(",
"(",
"key",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"a_dict",
".",
"items",
"(",
")",
")"
] | Return the a new dict with underscores instead of hyphens in keys. | [
"Return",
"the",
"a",
"new",
"dict",
"with",
"underscores",
"instead",
"of",
"hyphens",
"in",
"keys",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/templating/contexts.py#L31-L34 | train |
juju/charm-helpers | charmhelpers/contrib/templating/contexts.py | update_relations | def update_relations(context, namespace_separator=':'):
"""Update the context with the relation data."""
# Add any relation data prefixed with the relation type.
relation_type = charmhelpers.core.hookenv.relation_type()
relations = []
context['current_relation'] = {}
if relation_type is not None:
relation_data = charmhelpers.core.hookenv.relation_get()
context['current_relation'] = relation_data
# Deprecated: the following use of relation data as keys
# directly in the context will be removed.
relation_data = dict(
("{relation_type}{namespace_separator}{key}".format(
relation_type=relation_type,
key=key,
namespace_separator=namespace_separator), val)
for key, val in relation_data.items())
relation_data = dict_keys_without_hyphens(relation_data)
context.update(relation_data)
relations = charmhelpers.core.hookenv.relations_of_type(relation_type)
relations = [dict_keys_without_hyphens(rel) for rel in relations]
context['relations_full'] = charmhelpers.core.hookenv.relations()
# the hookenv.relations() data structure is effectively unusable in
# templates and other contexts when trying to access relation data other
# than the current relation. So provide a more useful structure that works
# with any hook.
local_unit = charmhelpers.core.hookenv.local_unit()
relations = {}
for rname, rids in context['relations_full'].items():
relations[rname] = []
for rid, rdata in rids.items():
data = rdata.copy()
if local_unit in rdata:
data.pop(local_unit)
for unit_name, rel_data in data.items():
new_data = {'__relid__': rid, '__unit__': unit_name}
new_data.update(rel_data)
relations[rname].append(new_data)
context['relations'] = relations | python | def update_relations(context, namespace_separator=':'):
"""Update the context with the relation data."""
# Add any relation data prefixed with the relation type.
relation_type = charmhelpers.core.hookenv.relation_type()
relations = []
context['current_relation'] = {}
if relation_type is not None:
relation_data = charmhelpers.core.hookenv.relation_get()
context['current_relation'] = relation_data
# Deprecated: the following use of relation data as keys
# directly in the context will be removed.
relation_data = dict(
("{relation_type}{namespace_separator}{key}".format(
relation_type=relation_type,
key=key,
namespace_separator=namespace_separator), val)
for key, val in relation_data.items())
relation_data = dict_keys_without_hyphens(relation_data)
context.update(relation_data)
relations = charmhelpers.core.hookenv.relations_of_type(relation_type)
relations = [dict_keys_without_hyphens(rel) for rel in relations]
context['relations_full'] = charmhelpers.core.hookenv.relations()
# the hookenv.relations() data structure is effectively unusable in
# templates and other contexts when trying to access relation data other
# than the current relation. So provide a more useful structure that works
# with any hook.
local_unit = charmhelpers.core.hookenv.local_unit()
relations = {}
for rname, rids in context['relations_full'].items():
relations[rname] = []
for rid, rdata in rids.items():
data = rdata.copy()
if local_unit in rdata:
data.pop(local_unit)
for unit_name, rel_data in data.items():
new_data = {'__relid__': rid, '__unit__': unit_name}
new_data.update(rel_data)
relations[rname].append(new_data)
context['relations'] = relations | [
"def",
"update_relations",
"(",
"context",
",",
"namespace_separator",
"=",
"':'",
")",
":",
"# Add any relation data prefixed with the relation type.",
"relation_type",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"relation_type",
"(",
")",
"relations",
"=",
"[",
"]",
"context",
"[",
"'current_relation'",
"]",
"=",
"{",
"}",
"if",
"relation_type",
"is",
"not",
"None",
":",
"relation_data",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"relation_get",
"(",
")",
"context",
"[",
"'current_relation'",
"]",
"=",
"relation_data",
"# Deprecated: the following use of relation data as keys",
"# directly in the context will be removed.",
"relation_data",
"=",
"dict",
"(",
"(",
"\"{relation_type}{namespace_separator}{key}\"",
".",
"format",
"(",
"relation_type",
"=",
"relation_type",
",",
"key",
"=",
"key",
",",
"namespace_separator",
"=",
"namespace_separator",
")",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"relation_data",
".",
"items",
"(",
")",
")",
"relation_data",
"=",
"dict_keys_without_hyphens",
"(",
"relation_data",
")",
"context",
".",
"update",
"(",
"relation_data",
")",
"relations",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"relations_of_type",
"(",
"relation_type",
")",
"relations",
"=",
"[",
"dict_keys_without_hyphens",
"(",
"rel",
")",
"for",
"rel",
"in",
"relations",
"]",
"context",
"[",
"'relations_full'",
"]",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"relations",
"(",
")",
"# the hookenv.relations() data structure is effectively unusable in",
"# templates and other contexts when trying to access relation data other",
"# than the current relation. So provide a more useful structure that works",
"# with any hook.",
"local_unit",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"local_unit",
"(",
")",
"relations",
"=",
"{",
"}",
"for",
"rname",
",",
"rids",
"in",
"context",
"[",
"'relations_full'",
"]",
".",
"items",
"(",
")",
":",
"relations",
"[",
"rname",
"]",
"=",
"[",
"]",
"for",
"rid",
",",
"rdata",
"in",
"rids",
".",
"items",
"(",
")",
":",
"data",
"=",
"rdata",
".",
"copy",
"(",
")",
"if",
"local_unit",
"in",
"rdata",
":",
"data",
".",
"pop",
"(",
"local_unit",
")",
"for",
"unit_name",
",",
"rel_data",
"in",
"data",
".",
"items",
"(",
")",
":",
"new_data",
"=",
"{",
"'__relid__'",
":",
"rid",
",",
"'__unit__'",
":",
"unit_name",
"}",
"new_data",
".",
"update",
"(",
"rel_data",
")",
"relations",
"[",
"rname",
"]",
".",
"append",
"(",
"new_data",
")",
"context",
"[",
"'relations'",
"]",
"=",
"relations"
] | Update the context with the relation data. | [
"Update",
"the",
"context",
"with",
"the",
"relation",
"data",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/templating/contexts.py#L37-L77 | train |
juju/charm-helpers | charmhelpers/contrib/templating/contexts.py | juju_state_to_yaml | def juju_state_to_yaml(yaml_path, namespace_separator=':',
allow_hyphens_in_keys=True, mode=None):
"""Update the juju config and state in a yaml file.
This includes any current relation-get data, and the charm
directory.
This function was created for the ansible and saltstack
support, as those libraries can use a yaml file to supply
context to templates, but it may be useful generally to
create and update an on-disk cache of all the config, including
previous relation data.
By default, hyphens are allowed in keys as this is supported
by yaml, but for tools like ansible, hyphens are not valid [1].
[1] http://www.ansibleworks.com/docs/playbooks_variables.html#what-makes-a-valid-variable-name
"""
config = charmhelpers.core.hookenv.config()
# Add the charm_dir which we will need to refer to charm
# file resources etc.
config['charm_dir'] = charm_dir
config['local_unit'] = charmhelpers.core.hookenv.local_unit()
config['unit_private_address'] = charmhelpers.core.hookenv.unit_private_ip()
config['unit_public_address'] = charmhelpers.core.hookenv.unit_get(
'public-address'
)
# Don't use non-standard tags for unicode which will not
# work when salt uses yaml.load_safe.
yaml.add_representer(six.text_type,
lambda dumper, value: dumper.represent_scalar(
six.u('tag:yaml.org,2002:str'), value))
yaml_dir = os.path.dirname(yaml_path)
if not os.path.exists(yaml_dir):
os.makedirs(yaml_dir)
if os.path.exists(yaml_path):
with open(yaml_path, "r") as existing_vars_file:
existing_vars = yaml.load(existing_vars_file.read())
else:
with open(yaml_path, "w+"):
pass
existing_vars = {}
if mode is not None:
os.chmod(yaml_path, mode)
if not allow_hyphens_in_keys:
config = dict_keys_without_hyphens(config)
existing_vars.update(config)
update_relations(existing_vars, namespace_separator)
with open(yaml_path, "w+") as fp:
fp.write(yaml.dump(existing_vars, default_flow_style=False)) | python | def juju_state_to_yaml(yaml_path, namespace_separator=':',
allow_hyphens_in_keys=True, mode=None):
"""Update the juju config and state in a yaml file.
This includes any current relation-get data, and the charm
directory.
This function was created for the ansible and saltstack
support, as those libraries can use a yaml file to supply
context to templates, but it may be useful generally to
create and update an on-disk cache of all the config, including
previous relation data.
By default, hyphens are allowed in keys as this is supported
by yaml, but for tools like ansible, hyphens are not valid [1].
[1] http://www.ansibleworks.com/docs/playbooks_variables.html#what-makes-a-valid-variable-name
"""
config = charmhelpers.core.hookenv.config()
# Add the charm_dir which we will need to refer to charm
# file resources etc.
config['charm_dir'] = charm_dir
config['local_unit'] = charmhelpers.core.hookenv.local_unit()
config['unit_private_address'] = charmhelpers.core.hookenv.unit_private_ip()
config['unit_public_address'] = charmhelpers.core.hookenv.unit_get(
'public-address'
)
# Don't use non-standard tags for unicode which will not
# work when salt uses yaml.load_safe.
yaml.add_representer(six.text_type,
lambda dumper, value: dumper.represent_scalar(
six.u('tag:yaml.org,2002:str'), value))
yaml_dir = os.path.dirname(yaml_path)
if not os.path.exists(yaml_dir):
os.makedirs(yaml_dir)
if os.path.exists(yaml_path):
with open(yaml_path, "r") as existing_vars_file:
existing_vars = yaml.load(existing_vars_file.read())
else:
with open(yaml_path, "w+"):
pass
existing_vars = {}
if mode is not None:
os.chmod(yaml_path, mode)
if not allow_hyphens_in_keys:
config = dict_keys_without_hyphens(config)
existing_vars.update(config)
update_relations(existing_vars, namespace_separator)
with open(yaml_path, "w+") as fp:
fp.write(yaml.dump(existing_vars, default_flow_style=False)) | [
"def",
"juju_state_to_yaml",
"(",
"yaml_path",
",",
"namespace_separator",
"=",
"':'",
",",
"allow_hyphens_in_keys",
"=",
"True",
",",
"mode",
"=",
"None",
")",
":",
"config",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"config",
"(",
")",
"# Add the charm_dir which we will need to refer to charm",
"# file resources etc.",
"config",
"[",
"'charm_dir'",
"]",
"=",
"charm_dir",
"config",
"[",
"'local_unit'",
"]",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"local_unit",
"(",
")",
"config",
"[",
"'unit_private_address'",
"]",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"unit_private_ip",
"(",
")",
"config",
"[",
"'unit_public_address'",
"]",
"=",
"charmhelpers",
".",
"core",
".",
"hookenv",
".",
"unit_get",
"(",
"'public-address'",
")",
"# Don't use non-standard tags for unicode which will not",
"# work when salt uses yaml.load_safe.",
"yaml",
".",
"add_representer",
"(",
"six",
".",
"text_type",
",",
"lambda",
"dumper",
",",
"value",
":",
"dumper",
".",
"represent_scalar",
"(",
"six",
".",
"u",
"(",
"'tag:yaml.org,2002:str'",
")",
",",
"value",
")",
")",
"yaml_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"yaml_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"yaml_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"yaml_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"yaml_path",
")",
":",
"with",
"open",
"(",
"yaml_path",
",",
"\"r\"",
")",
"as",
"existing_vars_file",
":",
"existing_vars",
"=",
"yaml",
".",
"load",
"(",
"existing_vars_file",
".",
"read",
"(",
")",
")",
"else",
":",
"with",
"open",
"(",
"yaml_path",
",",
"\"w+\"",
")",
":",
"pass",
"existing_vars",
"=",
"{",
"}",
"if",
"mode",
"is",
"not",
"None",
":",
"os",
".",
"chmod",
"(",
"yaml_path",
",",
"mode",
")",
"if",
"not",
"allow_hyphens_in_keys",
":",
"config",
"=",
"dict_keys_without_hyphens",
"(",
"config",
")",
"existing_vars",
".",
"update",
"(",
"config",
")",
"update_relations",
"(",
"existing_vars",
",",
"namespace_separator",
")",
"with",
"open",
"(",
"yaml_path",
",",
"\"w+\"",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"yaml",
".",
"dump",
"(",
"existing_vars",
",",
"default_flow_style",
"=",
"False",
")",
")"
] | Update the juju config and state in a yaml file.
This includes any current relation-get data, and the charm
directory.
This function was created for the ansible and saltstack
support, as those libraries can use a yaml file to supply
context to templates, but it may be useful generally to
create and update an on-disk cache of all the config, including
previous relation data.
By default, hyphens are allowed in keys as this is supported
by yaml, but for tools like ansible, hyphens are not valid [1].
[1] http://www.ansibleworks.com/docs/playbooks_variables.html#what-makes-a-valid-variable-name | [
"Update",
"the",
"juju",
"config",
"and",
"state",
"in",
"a",
"yaml",
"file",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/templating/contexts.py#L80-L137 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/apache/checks/config.py | get_audits | def get_audits():
"""Get Apache hardening config audits.
:returns: dictionary of audits
"""
if subprocess.call(['which', 'apache2'], stdout=subprocess.PIPE) != 0:
log("Apache server does not appear to be installed on this node - "
"skipping apache hardening", level=INFO)
return []
context = ApacheConfContext()
settings = utils.get_settings('apache')
audits = [
FilePermissionAudit(paths=os.path.join(
settings['common']['apache_dir'], 'apache2.conf'),
user='root', group='root', mode=0o0640),
TemplatedFile(os.path.join(settings['common']['apache_dir'],
'mods-available/alias.conf'),
context,
TEMPLATES_DIR,
mode=0o0640,
user='root',
service_actions=[{'service': 'apache2',
'actions': ['restart']}]),
TemplatedFile(os.path.join(settings['common']['apache_dir'],
'conf-enabled/99-hardening.conf'),
context,
TEMPLATES_DIR,
mode=0o0640,
user='root',
service_actions=[{'service': 'apache2',
'actions': ['restart']}]),
DirectoryPermissionAudit(settings['common']['apache_dir'],
user='root',
group='root',
mode=0o0750),
DisabledModuleAudit(settings['hardening']['modules_to_disable']),
NoReadWriteForOther(settings['common']['apache_dir']),
DeletedFile(['/var/www/html/index.html'])
]
return audits | python | def get_audits():
"""Get Apache hardening config audits.
:returns: dictionary of audits
"""
if subprocess.call(['which', 'apache2'], stdout=subprocess.PIPE) != 0:
log("Apache server does not appear to be installed on this node - "
"skipping apache hardening", level=INFO)
return []
context = ApacheConfContext()
settings = utils.get_settings('apache')
audits = [
FilePermissionAudit(paths=os.path.join(
settings['common']['apache_dir'], 'apache2.conf'),
user='root', group='root', mode=0o0640),
TemplatedFile(os.path.join(settings['common']['apache_dir'],
'mods-available/alias.conf'),
context,
TEMPLATES_DIR,
mode=0o0640,
user='root',
service_actions=[{'service': 'apache2',
'actions': ['restart']}]),
TemplatedFile(os.path.join(settings['common']['apache_dir'],
'conf-enabled/99-hardening.conf'),
context,
TEMPLATES_DIR,
mode=0o0640,
user='root',
service_actions=[{'service': 'apache2',
'actions': ['restart']}]),
DirectoryPermissionAudit(settings['common']['apache_dir'],
user='root',
group='root',
mode=0o0750),
DisabledModuleAudit(settings['hardening']['modules_to_disable']),
NoReadWriteForOther(settings['common']['apache_dir']),
DeletedFile(['/var/www/html/index.html'])
]
return audits | [
"def",
"get_audits",
"(",
")",
":",
"if",
"subprocess",
".",
"call",
"(",
"[",
"'which'",
",",
"'apache2'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"!=",
"0",
":",
"log",
"(",
"\"Apache server does not appear to be installed on this node - \"",
"\"skipping apache hardening\"",
",",
"level",
"=",
"INFO",
")",
"return",
"[",
"]",
"context",
"=",
"ApacheConfContext",
"(",
")",
"settings",
"=",
"utils",
".",
"get_settings",
"(",
"'apache'",
")",
"audits",
"=",
"[",
"FilePermissionAudit",
"(",
"paths",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
"[",
"'common'",
"]",
"[",
"'apache_dir'",
"]",
",",
"'apache2.conf'",
")",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"mode",
"=",
"0o0640",
")",
",",
"TemplatedFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"settings",
"[",
"'common'",
"]",
"[",
"'apache_dir'",
"]",
",",
"'mods-available/alias.conf'",
")",
",",
"context",
",",
"TEMPLATES_DIR",
",",
"mode",
"=",
"0o0640",
",",
"user",
"=",
"'root'",
",",
"service_actions",
"=",
"[",
"{",
"'service'",
":",
"'apache2'",
",",
"'actions'",
":",
"[",
"'restart'",
"]",
"}",
"]",
")",
",",
"TemplatedFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"settings",
"[",
"'common'",
"]",
"[",
"'apache_dir'",
"]",
",",
"'conf-enabled/99-hardening.conf'",
")",
",",
"context",
",",
"TEMPLATES_DIR",
",",
"mode",
"=",
"0o0640",
",",
"user",
"=",
"'root'",
",",
"service_actions",
"=",
"[",
"{",
"'service'",
":",
"'apache2'",
",",
"'actions'",
":",
"[",
"'restart'",
"]",
"}",
"]",
")",
",",
"DirectoryPermissionAudit",
"(",
"settings",
"[",
"'common'",
"]",
"[",
"'apache_dir'",
"]",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"mode",
"=",
"0o0750",
")",
",",
"DisabledModuleAudit",
"(",
"settings",
"[",
"'hardening'",
"]",
"[",
"'modules_to_disable'",
"]",
")",
",",
"NoReadWriteForOther",
"(",
"settings",
"[",
"'common'",
"]",
"[",
"'apache_dir'",
"]",
")",
",",
"DeletedFile",
"(",
"[",
"'/var/www/html/index.html'",
"]",
")",
"]",
"return",
"audits"
] | Get Apache hardening config audits.
:returns: dictionary of audits | [
"Get",
"Apache",
"hardening",
"config",
"audits",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/apache/checks/config.py#L37-L84 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/host/checks/minimize_access.py | get_audits | def get_audits():
"""Get OS hardening access audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Remove write permissions from $PATH folders for all regular users.
# This prevents changing system-wide commands from normal users.
path_folders = {'/usr/local/sbin',
'/usr/local/bin',
'/usr/sbin',
'/usr/bin',
'/bin'}
extra_user_paths = settings['environment']['extra_user_paths']
path_folders.update(extra_user_paths)
audits.append(ReadOnly(path_folders))
# Only allow the root user to have access to the shadow file.
audits.append(FilePermissionAudit('/etc/shadow', 'root', 'root', 0o0600))
if 'change_user' not in settings['security']['users_allow']:
# su should only be accessible to user and group root, unless it is
# expressly defined to allow users to change to root via the
# security_users_allow config option.
audits.append(FilePermissionAudit('/bin/su', 'root', 'root', 0o750))
return audits | python | def get_audits():
"""Get OS hardening access audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Remove write permissions from $PATH folders for all regular users.
# This prevents changing system-wide commands from normal users.
path_folders = {'/usr/local/sbin',
'/usr/local/bin',
'/usr/sbin',
'/usr/bin',
'/bin'}
extra_user_paths = settings['environment']['extra_user_paths']
path_folders.update(extra_user_paths)
audits.append(ReadOnly(path_folders))
# Only allow the root user to have access to the shadow file.
audits.append(FilePermissionAudit('/etc/shadow', 'root', 'root', 0o0600))
if 'change_user' not in settings['security']['users_allow']:
# su should only be accessible to user and group root, unless it is
# expressly defined to allow users to change to root via the
# security_users_allow config option.
audits.append(FilePermissionAudit('/bin/su', 'root', 'root', 0o750))
return audits | [
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"]",
"settings",
"=",
"utils",
".",
"get_settings",
"(",
"'os'",
")",
"# Remove write permissions from $PATH folders for all regular users.",
"# This prevents changing system-wide commands from normal users.",
"path_folders",
"=",
"{",
"'/usr/local/sbin'",
",",
"'/usr/local/bin'",
",",
"'/usr/sbin'",
",",
"'/usr/bin'",
",",
"'/bin'",
"}",
"extra_user_paths",
"=",
"settings",
"[",
"'environment'",
"]",
"[",
"'extra_user_paths'",
"]",
"path_folders",
".",
"update",
"(",
"extra_user_paths",
")",
"audits",
".",
"append",
"(",
"ReadOnly",
"(",
"path_folders",
")",
")",
"# Only allow the root user to have access to the shadow file.",
"audits",
".",
"append",
"(",
"FilePermissionAudit",
"(",
"'/etc/shadow'",
",",
"'root'",
",",
"'root'",
",",
"0o0600",
")",
")",
"if",
"'change_user'",
"not",
"in",
"settings",
"[",
"'security'",
"]",
"[",
"'users_allow'",
"]",
":",
"# su should only be accessible to user and group root, unless it is",
"# expressly defined to allow users to change to root via the",
"# security_users_allow config option.",
"audits",
".",
"append",
"(",
"FilePermissionAudit",
"(",
"'/bin/su'",
",",
"'root'",
",",
"'root'",
",",
"0o750",
")",
")",
"return",
"audits"
] | Get OS hardening access audits.
:returns: dictionary of audits | [
"Get",
"OS",
"hardening",
"access",
"audits",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/minimize_access.py#L22-L50 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/harden.py | harden | def harden(overrides=None):
"""Hardening decorator.
This is the main entry point for running the hardening stack. In order to
run modules of the stack you must add this decorator to charm hook(s) and
ensure that your charm config.yaml contains the 'harden' option set to
one or more of the supported modules. Setting these will cause the
corresponding hardening code to be run when the hook fires.
This decorator can and should be applied to more than one hook or function
such that hardening modules are called multiple times. This is because
subsequent calls will perform auditing checks that will report any changes
to resources hardened by the first run (and possibly perform compliance
actions as a result of any detected infractions).
:param overrides: Optional list of stack modules used to override those
provided with 'harden' config.
:returns: Returns value returned by decorated function once executed.
"""
if overrides is None:
overrides = []
def _harden_inner1(f):
# As this has to be py2.7 compat, we can't use nonlocal. Use a trick
# to capture the dictionary that can then be updated.
_logged = {'done': False}
def _harden_inner2(*args, **kwargs):
# knock out hardening via a config var; normally it won't get
# disabled.
if _DISABLE_HARDENING_FOR_UNIT_TEST:
return f(*args, **kwargs)
if not _logged['done']:
log("Hardening function '%s'" % (f.__name__), level=DEBUG)
_logged['done'] = True
RUN_CATALOG = OrderedDict([('os', run_os_checks),
('ssh', run_ssh_checks),
('mysql', run_mysql_checks),
('apache', run_apache_checks)])
enabled = overrides[:] or (config("harden") or "").split()
if enabled:
modules_to_run = []
# modules will always be performed in the following order
for module, func in six.iteritems(RUN_CATALOG):
if module in enabled:
enabled.remove(module)
modules_to_run.append(func)
if enabled:
log("Unknown hardening modules '%s' - ignoring" %
(', '.join(enabled)), level=WARNING)
for hardener in modules_to_run:
log("Executing hardening module '%s'" %
(hardener.__name__), level=DEBUG)
hardener()
else:
log("No hardening applied to '%s'" % (f.__name__), level=DEBUG)
return f(*args, **kwargs)
return _harden_inner2
return _harden_inner1 | python | def harden(overrides=None):
"""Hardening decorator.
This is the main entry point for running the hardening stack. In order to
run modules of the stack you must add this decorator to charm hook(s) and
ensure that your charm config.yaml contains the 'harden' option set to
one or more of the supported modules. Setting these will cause the
corresponding hardening code to be run when the hook fires.
This decorator can and should be applied to more than one hook or function
such that hardening modules are called multiple times. This is because
subsequent calls will perform auditing checks that will report any changes
to resources hardened by the first run (and possibly perform compliance
actions as a result of any detected infractions).
:param overrides: Optional list of stack modules used to override those
provided with 'harden' config.
:returns: Returns value returned by decorated function once executed.
"""
if overrides is None:
overrides = []
def _harden_inner1(f):
# As this has to be py2.7 compat, we can't use nonlocal. Use a trick
# to capture the dictionary that can then be updated.
_logged = {'done': False}
def _harden_inner2(*args, **kwargs):
# knock out hardening via a config var; normally it won't get
# disabled.
if _DISABLE_HARDENING_FOR_UNIT_TEST:
return f(*args, **kwargs)
if not _logged['done']:
log("Hardening function '%s'" % (f.__name__), level=DEBUG)
_logged['done'] = True
RUN_CATALOG = OrderedDict([('os', run_os_checks),
('ssh', run_ssh_checks),
('mysql', run_mysql_checks),
('apache', run_apache_checks)])
enabled = overrides[:] or (config("harden") or "").split()
if enabled:
modules_to_run = []
# modules will always be performed in the following order
for module, func in six.iteritems(RUN_CATALOG):
if module in enabled:
enabled.remove(module)
modules_to_run.append(func)
if enabled:
log("Unknown hardening modules '%s' - ignoring" %
(', '.join(enabled)), level=WARNING)
for hardener in modules_to_run:
log("Executing hardening module '%s'" %
(hardener.__name__), level=DEBUG)
hardener()
else:
log("No hardening applied to '%s'" % (f.__name__), level=DEBUG)
return f(*args, **kwargs)
return _harden_inner2
return _harden_inner1 | [
"def",
"harden",
"(",
"overrides",
"=",
"None",
")",
":",
"if",
"overrides",
"is",
"None",
":",
"overrides",
"=",
"[",
"]",
"def",
"_harden_inner1",
"(",
"f",
")",
":",
"# As this has to be py2.7 compat, we can't use nonlocal. Use a trick",
"# to capture the dictionary that can then be updated.",
"_logged",
"=",
"{",
"'done'",
":",
"False",
"}",
"def",
"_harden_inner2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# knock out hardening via a config var; normally it won't get",
"# disabled.",
"if",
"_DISABLE_HARDENING_FOR_UNIT_TEST",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"_logged",
"[",
"'done'",
"]",
":",
"log",
"(",
"\"Hardening function '%s'\"",
"%",
"(",
"f",
".",
"__name__",
")",
",",
"level",
"=",
"DEBUG",
")",
"_logged",
"[",
"'done'",
"]",
"=",
"True",
"RUN_CATALOG",
"=",
"OrderedDict",
"(",
"[",
"(",
"'os'",
",",
"run_os_checks",
")",
",",
"(",
"'ssh'",
",",
"run_ssh_checks",
")",
",",
"(",
"'mysql'",
",",
"run_mysql_checks",
")",
",",
"(",
"'apache'",
",",
"run_apache_checks",
")",
"]",
")",
"enabled",
"=",
"overrides",
"[",
":",
"]",
"or",
"(",
"config",
"(",
"\"harden\"",
")",
"or",
"\"\"",
")",
".",
"split",
"(",
")",
"if",
"enabled",
":",
"modules_to_run",
"=",
"[",
"]",
"# modules will always be performed in the following order",
"for",
"module",
",",
"func",
"in",
"six",
".",
"iteritems",
"(",
"RUN_CATALOG",
")",
":",
"if",
"module",
"in",
"enabled",
":",
"enabled",
".",
"remove",
"(",
"module",
")",
"modules_to_run",
".",
"append",
"(",
"func",
")",
"if",
"enabled",
":",
"log",
"(",
"\"Unknown hardening modules '%s' - ignoring\"",
"%",
"(",
"', '",
".",
"join",
"(",
"enabled",
")",
")",
",",
"level",
"=",
"WARNING",
")",
"for",
"hardener",
"in",
"modules_to_run",
":",
"log",
"(",
"\"Executing hardening module '%s'\"",
"%",
"(",
"hardener",
".",
"__name__",
")",
",",
"level",
"=",
"DEBUG",
")",
"hardener",
"(",
")",
"else",
":",
"log",
"(",
"\"No hardening applied to '%s'\"",
"%",
"(",
"f",
".",
"__name__",
")",
",",
"level",
"=",
"DEBUG",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_harden_inner2",
"return",
"_harden_inner1"
] | Hardening decorator.
This is the main entry point for running the hardening stack. In order to
run modules of the stack you must add this decorator to charm hook(s) and
ensure that your charm config.yaml contains the 'harden' option set to
one or more of the supported modules. Setting these will cause the
corresponding hardening code to be run when the hook fires.
This decorator can and should be applied to more than one hook or function
such that hardening modules are called multiple times. This is because
subsequent calls will perform auditing checks that will report any changes
to resources hardened by the first run (and possibly perform compliance
actions as a result of any detected infractions).
:param overrides: Optional list of stack modules used to override those
provided with 'harden' config.
:returns: Returns value returned by decorated function once executed. | [
"Hardening",
"decorator",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/harden.py#L33-L96 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/neutron.py | parse_mappings | def parse_mappings(mappings, key_rvalue=False):
"""By default mappings are lvalue keyed.
If key_rvalue is True, the mapping will be reversed to allow multiple
configs for the same lvalue.
"""
parsed = {}
if mappings:
mappings = mappings.split()
for m in mappings:
p = m.partition(':')
if key_rvalue:
key_index = 2
val_index = 0
# if there is no rvalue skip to next
if not p[1]:
continue
else:
key_index = 0
val_index = 2
key = p[key_index].strip()
parsed[key] = p[val_index].strip()
return parsed | python | def parse_mappings(mappings, key_rvalue=False):
"""By default mappings are lvalue keyed.
If key_rvalue is True, the mapping will be reversed to allow multiple
configs for the same lvalue.
"""
parsed = {}
if mappings:
mappings = mappings.split()
for m in mappings:
p = m.partition(':')
if key_rvalue:
key_index = 2
val_index = 0
# if there is no rvalue skip to next
if not p[1]:
continue
else:
key_index = 0
val_index = 2
key = p[key_index].strip()
parsed[key] = p[val_index].strip()
return parsed | [
"def",
"parse_mappings",
"(",
"mappings",
",",
"key_rvalue",
"=",
"False",
")",
":",
"parsed",
"=",
"{",
"}",
"if",
"mappings",
":",
"mappings",
"=",
"mappings",
".",
"split",
"(",
")",
"for",
"m",
"in",
"mappings",
":",
"p",
"=",
"m",
".",
"partition",
"(",
"':'",
")",
"if",
"key_rvalue",
":",
"key_index",
"=",
"2",
"val_index",
"=",
"0",
"# if there is no rvalue skip to next",
"if",
"not",
"p",
"[",
"1",
"]",
":",
"continue",
"else",
":",
"key_index",
"=",
"0",
"val_index",
"=",
"2",
"key",
"=",
"p",
"[",
"key_index",
"]",
".",
"strip",
"(",
")",
"parsed",
"[",
"key",
"]",
"=",
"p",
"[",
"val_index",
"]",
".",
"strip",
"(",
")",
"return",
"parsed"
] | By default mappings are lvalue keyed.
If key_rvalue is True, the mapping will be reversed to allow multiple
configs for the same lvalue. | [
"By",
"default",
"mappings",
"are",
"lvalue",
"keyed",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/neutron.py#L270-L295 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/neutron.py | parse_data_port_mappings | def parse_data_port_mappings(mappings, default_bridge='br-data'):
"""Parse data port mappings.
Mappings must be a space-delimited list of bridge:port.
Returns dict of the form {port:bridge} where ports may be mac addresses or
interface names.
"""
# NOTE(dosaboy): we use rvalue for key to allow multiple values to be
# proposed for <port> since it may be a mac address which will differ
# across units this allowing first-known-good to be chosen.
_mappings = parse_mappings(mappings, key_rvalue=True)
if not _mappings or list(_mappings.values()) == ['']:
if not mappings:
return {}
# For backwards-compatibility we need to support port-only provided in
# config.
_mappings = {mappings.split()[0]: default_bridge}
ports = _mappings.keys()
if len(set(ports)) != len(ports):
raise Exception("It is not allowed to have the same port configured "
"on more than one bridge")
return _mappings | python | def parse_data_port_mappings(mappings, default_bridge='br-data'):
"""Parse data port mappings.
Mappings must be a space-delimited list of bridge:port.
Returns dict of the form {port:bridge} where ports may be mac addresses or
interface names.
"""
# NOTE(dosaboy): we use rvalue for key to allow multiple values to be
# proposed for <port> since it may be a mac address which will differ
# across units this allowing first-known-good to be chosen.
_mappings = parse_mappings(mappings, key_rvalue=True)
if not _mappings or list(_mappings.values()) == ['']:
if not mappings:
return {}
# For backwards-compatibility we need to support port-only provided in
# config.
_mappings = {mappings.split()[0]: default_bridge}
ports = _mappings.keys()
if len(set(ports)) != len(ports):
raise Exception("It is not allowed to have the same port configured "
"on more than one bridge")
return _mappings | [
"def",
"parse_data_port_mappings",
"(",
"mappings",
",",
"default_bridge",
"=",
"'br-data'",
")",
":",
"# NOTE(dosaboy): we use rvalue for key to allow multiple values to be",
"# proposed for <port> since it may be a mac address which will differ",
"# across units this allowing first-known-good to be chosen.",
"_mappings",
"=",
"parse_mappings",
"(",
"mappings",
",",
"key_rvalue",
"=",
"True",
")",
"if",
"not",
"_mappings",
"or",
"list",
"(",
"_mappings",
".",
"values",
"(",
")",
")",
"==",
"[",
"''",
"]",
":",
"if",
"not",
"mappings",
":",
"return",
"{",
"}",
"# For backwards-compatibility we need to support port-only provided in",
"# config.",
"_mappings",
"=",
"{",
"mappings",
".",
"split",
"(",
")",
"[",
"0",
"]",
":",
"default_bridge",
"}",
"ports",
"=",
"_mappings",
".",
"keys",
"(",
")",
"if",
"len",
"(",
"set",
"(",
"ports",
")",
")",
"!=",
"len",
"(",
"ports",
")",
":",
"raise",
"Exception",
"(",
"\"It is not allowed to have the same port configured \"",
"\"on more than one bridge\"",
")",
"return",
"_mappings"
] | Parse data port mappings.
Mappings must be a space-delimited list of bridge:port.
Returns dict of the form {port:bridge} where ports may be mac addresses or
interface names. | [
"Parse",
"data",
"port",
"mappings",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/neutron.py#L308-L334 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/neutron.py | parse_vlan_range_mappings | def parse_vlan_range_mappings(mappings):
"""Parse vlan range mappings.
Mappings must be a space-delimited list of provider:start:end mappings.
The start:end range is optional and may be omitted.
Returns dict of the form {provider: (start, end)}.
"""
_mappings = parse_mappings(mappings)
if not _mappings:
return {}
mappings = {}
for p, r in six.iteritems(_mappings):
mappings[p] = tuple(r.split(':'))
return mappings | python | def parse_vlan_range_mappings(mappings):
"""Parse vlan range mappings.
Mappings must be a space-delimited list of provider:start:end mappings.
The start:end range is optional and may be omitted.
Returns dict of the form {provider: (start, end)}.
"""
_mappings = parse_mappings(mappings)
if not _mappings:
return {}
mappings = {}
for p, r in six.iteritems(_mappings):
mappings[p] = tuple(r.split(':'))
return mappings | [
"def",
"parse_vlan_range_mappings",
"(",
"mappings",
")",
":",
"_mappings",
"=",
"parse_mappings",
"(",
"mappings",
")",
"if",
"not",
"_mappings",
":",
"return",
"{",
"}",
"mappings",
"=",
"{",
"}",
"for",
"p",
",",
"r",
"in",
"six",
".",
"iteritems",
"(",
"_mappings",
")",
":",
"mappings",
"[",
"p",
"]",
"=",
"tuple",
"(",
"r",
".",
"split",
"(",
"':'",
")",
")",
"return",
"mappings"
] | Parse vlan range mappings.
Mappings must be a space-delimited list of provider:start:end mappings.
The start:end range is optional and may be omitted.
Returns dict of the form {provider: (start, end)}. | [
"Parse",
"vlan",
"range",
"mappings",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/neutron.py#L337-L354 | train |
juju/charm-helpers | charmhelpers/payload/archive.py | extract_tarfile | def extract_tarfile(archive_name, destpath):
"Unpack a tar archive, optionally compressed"
archive = tarfile.open(archive_name)
archive.extractall(destpath) | python | def extract_tarfile(archive_name, destpath):
"Unpack a tar archive, optionally compressed"
archive = tarfile.open(archive_name)
archive.extractall(destpath) | [
"def",
"extract_tarfile",
"(",
"archive_name",
",",
"destpath",
")",
":",
"archive",
"=",
"tarfile",
".",
"open",
"(",
"archive_name",
")",
"archive",
".",
"extractall",
"(",
"destpath",
")"
] | Unpack a tar archive, optionally compressed | [
"Unpack",
"a",
"tar",
"archive",
"optionally",
"compressed"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/archive.py#L62-L65 | train |
juju/charm-helpers | charmhelpers/payload/archive.py | extract_zipfile | def extract_zipfile(archive_name, destpath):
"Unpack a zip file"
archive = zipfile.ZipFile(archive_name)
archive.extractall(destpath) | python | def extract_zipfile(archive_name, destpath):
"Unpack a zip file"
archive = zipfile.ZipFile(archive_name)
archive.extractall(destpath) | [
"def",
"extract_zipfile",
"(",
"archive_name",
",",
"destpath",
")",
":",
"archive",
"=",
"zipfile",
".",
"ZipFile",
"(",
"archive_name",
")",
"archive",
".",
"extractall",
"(",
"destpath",
")"
] | Unpack a zip file | [
"Unpack",
"a",
"zip",
"file"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/archive.py#L68-L71 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_address_in_network | def get_address_in_network(network, fallback=None, fatal=False):
"""Get an IPv4 or IPv6 address within the network from the host.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'. Supports multiple networks as a space-delimited list.
:param fallback (str): If no address is found, return fallback.
:param fatal (boolean): If no address is found, fallback is not
set and fatal is True then exit(1).
"""
if network is None:
if fallback is not None:
return fallback
if fatal:
no_ip_found_error_out(network)
else:
return None
networks = network.split() or [network]
for network in networks:
_validate_cidr(network)
network = netaddr.IPNetwork(network)
for iface in netifaces.interfaces():
try:
addresses = netifaces.ifaddresses(iface)
except ValueError:
# If an instance was deleted between
# netifaces.interfaces() run and now, its interfaces are gone
continue
if network.version == 4 and netifaces.AF_INET in addresses:
for addr in addresses[netifaces.AF_INET]:
cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'],
addr['netmask']))
if cidr in network:
return str(cidr.ip)
if network.version == 6 and netifaces.AF_INET6 in addresses:
for addr in addresses[netifaces.AF_INET6]:
cidr = _get_ipv6_network_from_address(addr)
if cidr and cidr in network:
return str(cidr.ip)
if fallback is not None:
return fallback
if fatal:
no_ip_found_error_out(network)
return None | python | def get_address_in_network(network, fallback=None, fatal=False):
"""Get an IPv4 or IPv6 address within the network from the host.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'. Supports multiple networks as a space-delimited list.
:param fallback (str): If no address is found, return fallback.
:param fatal (boolean): If no address is found, fallback is not
set and fatal is True then exit(1).
"""
if network is None:
if fallback is not None:
return fallback
if fatal:
no_ip_found_error_out(network)
else:
return None
networks = network.split() or [network]
for network in networks:
_validate_cidr(network)
network = netaddr.IPNetwork(network)
for iface in netifaces.interfaces():
try:
addresses = netifaces.ifaddresses(iface)
except ValueError:
# If an instance was deleted between
# netifaces.interfaces() run and now, its interfaces are gone
continue
if network.version == 4 and netifaces.AF_INET in addresses:
for addr in addresses[netifaces.AF_INET]:
cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'],
addr['netmask']))
if cidr in network:
return str(cidr.ip)
if network.version == 6 and netifaces.AF_INET6 in addresses:
for addr in addresses[netifaces.AF_INET6]:
cidr = _get_ipv6_network_from_address(addr)
if cidr and cidr in network:
return str(cidr.ip)
if fallback is not None:
return fallback
if fatal:
no_ip_found_error_out(network)
return None | [
"def",
"get_address_in_network",
"(",
"network",
",",
"fallback",
"=",
"None",
",",
"fatal",
"=",
"False",
")",
":",
"if",
"network",
"is",
"None",
":",
"if",
"fallback",
"is",
"not",
"None",
":",
"return",
"fallback",
"if",
"fatal",
":",
"no_ip_found_error_out",
"(",
"network",
")",
"else",
":",
"return",
"None",
"networks",
"=",
"network",
".",
"split",
"(",
")",
"or",
"[",
"network",
"]",
"for",
"network",
"in",
"networks",
":",
"_validate_cidr",
"(",
"network",
")",
"network",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"network",
")",
"for",
"iface",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
":",
"try",
":",
"addresses",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"iface",
")",
"except",
"ValueError",
":",
"# If an instance was deleted between",
"# netifaces.interfaces() run and now, its interfaces are gone",
"continue",
"if",
"network",
".",
"version",
"==",
"4",
"and",
"netifaces",
".",
"AF_INET",
"in",
"addresses",
":",
"for",
"addr",
"in",
"addresses",
"[",
"netifaces",
".",
"AF_INET",
"]",
":",
"cidr",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"\"%s/%s\"",
"%",
"(",
"addr",
"[",
"'addr'",
"]",
",",
"addr",
"[",
"'netmask'",
"]",
")",
")",
"if",
"cidr",
"in",
"network",
":",
"return",
"str",
"(",
"cidr",
".",
"ip",
")",
"if",
"network",
".",
"version",
"==",
"6",
"and",
"netifaces",
".",
"AF_INET6",
"in",
"addresses",
":",
"for",
"addr",
"in",
"addresses",
"[",
"netifaces",
".",
"AF_INET6",
"]",
":",
"cidr",
"=",
"_get_ipv6_network_from_address",
"(",
"addr",
")",
"if",
"cidr",
"and",
"cidr",
"in",
"network",
":",
"return",
"str",
"(",
"cidr",
".",
"ip",
")",
"if",
"fallback",
"is",
"not",
"None",
":",
"return",
"fallback",
"if",
"fatal",
":",
"no_ip_found_error_out",
"(",
"network",
")",
"return",
"None"
] | Get an IPv4 or IPv6 address within the network from the host.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'. Supports multiple networks as a space-delimited list.
:param fallback (str): If no address is found, return fallback.
:param fatal (boolean): If no address is found, fallback is not
set and fatal is True then exit(1). | [
"Get",
"an",
"IPv4",
"or",
"IPv6",
"address",
"within",
"the",
"network",
"from",
"the",
"host",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L90-L138 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | is_ipv6 | def is_ipv6(address):
"""Determine whether provided address is IPv6 or not."""
try:
address = netaddr.IPAddress(address)
except netaddr.AddrFormatError:
# probably a hostname - so not an address at all!
return False
return address.version == 6 | python | def is_ipv6(address):
"""Determine whether provided address is IPv6 or not."""
try:
address = netaddr.IPAddress(address)
except netaddr.AddrFormatError:
# probably a hostname - so not an address at all!
return False
return address.version == 6 | [
"def",
"is_ipv6",
"(",
"address",
")",
":",
"try",
":",
"address",
"=",
"netaddr",
".",
"IPAddress",
"(",
"address",
")",
"except",
"netaddr",
".",
"AddrFormatError",
":",
"# probably a hostname - so not an address at all!",
"return",
"False",
"return",
"address",
".",
"version",
"==",
"6"
] | Determine whether provided address is IPv6 or not. | [
"Determine",
"whether",
"provided",
"address",
"is",
"IPv6",
"or",
"not",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L141-L149 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | is_address_in_network | def is_address_in_network(network, address):
"""
Determine whether the provided address is within a network range.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'.
:param address: An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:returns boolean: Flag indicating whether address is in network.
"""
try:
network = netaddr.IPNetwork(network)
except (netaddr.core.AddrFormatError, ValueError):
raise ValueError("Network (%s) is not in CIDR presentation format" %
network)
try:
address = netaddr.IPAddress(address)
except (netaddr.core.AddrFormatError, ValueError):
raise ValueError("Address (%s) is not in correct presentation format" %
address)
if address in network:
return True
else:
return False | python | def is_address_in_network(network, address):
"""
Determine whether the provided address is within a network range.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'.
:param address: An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:returns boolean: Flag indicating whether address is in network.
"""
try:
network = netaddr.IPNetwork(network)
except (netaddr.core.AddrFormatError, ValueError):
raise ValueError("Network (%s) is not in CIDR presentation format" %
network)
try:
address = netaddr.IPAddress(address)
except (netaddr.core.AddrFormatError, ValueError):
raise ValueError("Address (%s) is not in correct presentation format" %
address)
if address in network:
return True
else:
return False | [
"def",
"is_address_in_network",
"(",
"network",
",",
"address",
")",
":",
"try",
":",
"network",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"network",
")",
"except",
"(",
"netaddr",
".",
"core",
".",
"AddrFormatError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"\"Network (%s) is not in CIDR presentation format\"",
"%",
"network",
")",
"try",
":",
"address",
"=",
"netaddr",
".",
"IPAddress",
"(",
"address",
")",
"except",
"(",
"netaddr",
".",
"core",
".",
"AddrFormatError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"\"Address (%s) is not in correct presentation format\"",
"%",
"address",
")",
"if",
"address",
"in",
"network",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Determine whether the provided address is within a network range.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'.
:param address: An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:returns boolean: Flag indicating whether address is in network. | [
"Determine",
"whether",
"the",
"provided",
"address",
"is",
"within",
"a",
"network",
"range",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L152-L177 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | _get_for_address | def _get_for_address(address, key):
"""Retrieve an attribute of or the physical interface that
the IP address provided could be bound to.
:param address (str): An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:param key: 'iface' for the physical interface name or an attribute
of the configured interface, for example 'netmask'.
:returns str: Requested attribute or None if address is not bindable.
"""
address = netaddr.IPAddress(address)
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
if address.version == 4 and netifaces.AF_INET in addresses:
addr = addresses[netifaces.AF_INET][0]['addr']
netmask = addresses[netifaces.AF_INET][0]['netmask']
network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
cidr = network.cidr
if address in cidr:
if key == 'iface':
return iface
else:
return addresses[netifaces.AF_INET][0][key]
if address.version == 6 and netifaces.AF_INET6 in addresses:
for addr in addresses[netifaces.AF_INET6]:
network = _get_ipv6_network_from_address(addr)
if not network:
continue
cidr = network.cidr
if address in cidr:
if key == 'iface':
return iface
elif key == 'netmask' and cidr:
return str(cidr).split('/')[1]
else:
return addr[key]
return None | python | def _get_for_address(address, key):
"""Retrieve an attribute of or the physical interface that
the IP address provided could be bound to.
:param address (str): An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:param key: 'iface' for the physical interface name or an attribute
of the configured interface, for example 'netmask'.
:returns str: Requested attribute or None if address is not bindable.
"""
address = netaddr.IPAddress(address)
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
if address.version == 4 and netifaces.AF_INET in addresses:
addr = addresses[netifaces.AF_INET][0]['addr']
netmask = addresses[netifaces.AF_INET][0]['netmask']
network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
cidr = network.cidr
if address in cidr:
if key == 'iface':
return iface
else:
return addresses[netifaces.AF_INET][0][key]
if address.version == 6 and netifaces.AF_INET6 in addresses:
for addr in addresses[netifaces.AF_INET6]:
network = _get_ipv6_network_from_address(addr)
if not network:
continue
cidr = network.cidr
if address in cidr:
if key == 'iface':
return iface
elif key == 'netmask' and cidr:
return str(cidr).split('/')[1]
else:
return addr[key]
return None | [
"def",
"_get_for_address",
"(",
"address",
",",
"key",
")",
":",
"address",
"=",
"netaddr",
".",
"IPAddress",
"(",
"address",
")",
"for",
"iface",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
":",
"addresses",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"iface",
")",
"if",
"address",
".",
"version",
"==",
"4",
"and",
"netifaces",
".",
"AF_INET",
"in",
"addresses",
":",
"addr",
"=",
"addresses",
"[",
"netifaces",
".",
"AF_INET",
"]",
"[",
"0",
"]",
"[",
"'addr'",
"]",
"netmask",
"=",
"addresses",
"[",
"netifaces",
".",
"AF_INET",
"]",
"[",
"0",
"]",
"[",
"'netmask'",
"]",
"network",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"\"%s/%s\"",
"%",
"(",
"addr",
",",
"netmask",
")",
")",
"cidr",
"=",
"network",
".",
"cidr",
"if",
"address",
"in",
"cidr",
":",
"if",
"key",
"==",
"'iface'",
":",
"return",
"iface",
"else",
":",
"return",
"addresses",
"[",
"netifaces",
".",
"AF_INET",
"]",
"[",
"0",
"]",
"[",
"key",
"]",
"if",
"address",
".",
"version",
"==",
"6",
"and",
"netifaces",
".",
"AF_INET6",
"in",
"addresses",
":",
"for",
"addr",
"in",
"addresses",
"[",
"netifaces",
".",
"AF_INET6",
"]",
":",
"network",
"=",
"_get_ipv6_network_from_address",
"(",
"addr",
")",
"if",
"not",
"network",
":",
"continue",
"cidr",
"=",
"network",
".",
"cidr",
"if",
"address",
"in",
"cidr",
":",
"if",
"key",
"==",
"'iface'",
":",
"return",
"iface",
"elif",
"key",
"==",
"'netmask'",
"and",
"cidr",
":",
"return",
"str",
"(",
"cidr",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"else",
":",
"return",
"addr",
"[",
"key",
"]",
"return",
"None"
] | Retrieve an attribute of or the physical interface that
the IP address provided could be bound to.
:param address (str): An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:param key: 'iface' for the physical interface name or an attribute
of the configured interface, for example 'netmask'.
:returns str: Requested attribute or None if address is not bindable. | [
"Retrieve",
"an",
"attribute",
"of",
"or",
"the",
"physical",
"interface",
"that",
"the",
"IP",
"address",
"provided",
"could",
"be",
"bound",
"to",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L180-L218 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | resolve_network_cidr | def resolve_network_cidr(ip_address):
'''
Resolves the full address cidr of an ip_address based on
configured network interfaces
'''
netmask = get_netmask_for_address(ip_address)
return str(netaddr.IPNetwork("%s/%s" % (ip_address, netmask)).cidr) | python | def resolve_network_cidr(ip_address):
'''
Resolves the full address cidr of an ip_address based on
configured network interfaces
'''
netmask = get_netmask_for_address(ip_address)
return str(netaddr.IPNetwork("%s/%s" % (ip_address, netmask)).cidr) | [
"def",
"resolve_network_cidr",
"(",
"ip_address",
")",
":",
"netmask",
"=",
"get_netmask_for_address",
"(",
"ip_address",
")",
"return",
"str",
"(",
"netaddr",
".",
"IPNetwork",
"(",
"\"%s/%s\"",
"%",
"(",
"ip_address",
",",
"netmask",
")",
")",
".",
"cidr",
")"
] | Resolves the full address cidr of an ip_address based on
configured network interfaces | [
"Resolves",
"the",
"full",
"address",
"cidr",
"of",
"an",
"ip_address",
"based",
"on",
"configured",
"network",
"interfaces"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L227-L233 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_iface_addr | def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
fatal=True, exc_list=None):
"""Return the assigned IP address for a given interface, if any.
:param iface: network interface on which address(es) are expected to
be found.
:param inet_type: inet address family
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:return: list of ip addresses
"""
# Extract nic if passed /dev/ethX
if '/' in iface:
iface = iface.split('/')[-1]
if not exc_list:
exc_list = []
try:
inet_num = getattr(netifaces, inet_type)
except AttributeError:
raise Exception("Unknown inet type '%s'" % str(inet_type))
interfaces = netifaces.interfaces()
if inc_aliases:
ifaces = []
for _iface in interfaces:
if iface == _iface or _iface.split(':')[0] == iface:
ifaces.append(_iface)
if fatal and not ifaces:
raise Exception("Invalid interface '%s'" % iface)
ifaces.sort()
else:
if iface not in interfaces:
if fatal:
raise Exception("Interface '%s' not found " % (iface))
else:
return []
else:
ifaces = [iface]
addresses = []
for netiface in ifaces:
net_info = netifaces.ifaddresses(netiface)
if inet_num in net_info:
for entry in net_info[inet_num]:
if 'addr' in entry and entry['addr'] not in exc_list:
addresses.append(entry['addr'])
if fatal and not addresses:
raise Exception("Interface '%s' doesn't have any %s addresses." %
(iface, inet_type))
return sorted(addresses) | python | def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
fatal=True, exc_list=None):
"""Return the assigned IP address for a given interface, if any.
:param iface: network interface on which address(es) are expected to
be found.
:param inet_type: inet address family
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:return: list of ip addresses
"""
# Extract nic if passed /dev/ethX
if '/' in iface:
iface = iface.split('/')[-1]
if not exc_list:
exc_list = []
try:
inet_num = getattr(netifaces, inet_type)
except AttributeError:
raise Exception("Unknown inet type '%s'" % str(inet_type))
interfaces = netifaces.interfaces()
if inc_aliases:
ifaces = []
for _iface in interfaces:
if iface == _iface or _iface.split(':')[0] == iface:
ifaces.append(_iface)
if fatal and not ifaces:
raise Exception("Invalid interface '%s'" % iface)
ifaces.sort()
else:
if iface not in interfaces:
if fatal:
raise Exception("Interface '%s' not found " % (iface))
else:
return []
else:
ifaces = [iface]
addresses = []
for netiface in ifaces:
net_info = netifaces.ifaddresses(netiface)
if inet_num in net_info:
for entry in net_info[inet_num]:
if 'addr' in entry and entry['addr'] not in exc_list:
addresses.append(entry['addr'])
if fatal and not addresses:
raise Exception("Interface '%s' doesn't have any %s addresses." %
(iface, inet_type))
return sorted(addresses) | [
"def",
"get_iface_addr",
"(",
"iface",
"=",
"'eth0'",
",",
"inet_type",
"=",
"'AF_INET'",
",",
"inc_aliases",
"=",
"False",
",",
"fatal",
"=",
"True",
",",
"exc_list",
"=",
"None",
")",
":",
"# Extract nic if passed /dev/ethX",
"if",
"'/'",
"in",
"iface",
":",
"iface",
"=",
"iface",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"if",
"not",
"exc_list",
":",
"exc_list",
"=",
"[",
"]",
"try",
":",
"inet_num",
"=",
"getattr",
"(",
"netifaces",
",",
"inet_type",
")",
"except",
"AttributeError",
":",
"raise",
"Exception",
"(",
"\"Unknown inet type '%s'\"",
"%",
"str",
"(",
"inet_type",
")",
")",
"interfaces",
"=",
"netifaces",
".",
"interfaces",
"(",
")",
"if",
"inc_aliases",
":",
"ifaces",
"=",
"[",
"]",
"for",
"_iface",
"in",
"interfaces",
":",
"if",
"iface",
"==",
"_iface",
"or",
"_iface",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"==",
"iface",
":",
"ifaces",
".",
"append",
"(",
"_iface",
")",
"if",
"fatal",
"and",
"not",
"ifaces",
":",
"raise",
"Exception",
"(",
"\"Invalid interface '%s'\"",
"%",
"iface",
")",
"ifaces",
".",
"sort",
"(",
")",
"else",
":",
"if",
"iface",
"not",
"in",
"interfaces",
":",
"if",
"fatal",
":",
"raise",
"Exception",
"(",
"\"Interface '%s' not found \"",
"%",
"(",
"iface",
")",
")",
"else",
":",
"return",
"[",
"]",
"else",
":",
"ifaces",
"=",
"[",
"iface",
"]",
"addresses",
"=",
"[",
"]",
"for",
"netiface",
"in",
"ifaces",
":",
"net_info",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"netiface",
")",
"if",
"inet_num",
"in",
"net_info",
":",
"for",
"entry",
"in",
"net_info",
"[",
"inet_num",
"]",
":",
"if",
"'addr'",
"in",
"entry",
"and",
"entry",
"[",
"'addr'",
"]",
"not",
"in",
"exc_list",
":",
"addresses",
".",
"append",
"(",
"entry",
"[",
"'addr'",
"]",
")",
"if",
"fatal",
"and",
"not",
"addresses",
":",
"raise",
"Exception",
"(",
"\"Interface '%s' doesn't have any %s addresses.\"",
"%",
"(",
"iface",
",",
"inet_type",
")",
")",
"return",
"sorted",
"(",
"addresses",
")"
] | Return the assigned IP address for a given interface, if any.
:param iface: network interface on which address(es) are expected to
be found.
:param inet_type: inet address family
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:return: list of ip addresses | [
"Return",
"the",
"assigned",
"IP",
"address",
"for",
"a",
"given",
"interface",
"if",
"any",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L260-L317 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_iface_from_addr | def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg) | python | def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg) | [
"def",
"get_iface_from_addr",
"(",
"addr",
")",
":",
"for",
"iface",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
":",
"addresses",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"iface",
")",
"for",
"inet_type",
"in",
"addresses",
":",
"for",
"_addr",
"in",
"addresses",
"[",
"inet_type",
"]",
":",
"_addr",
"=",
"_addr",
"[",
"'addr'",
"]",
"# link local",
"ll_key",
"=",
"re",
".",
"compile",
"(",
"\"(.+)%.*\"",
")",
"raw",
"=",
"re",
".",
"match",
"(",
"ll_key",
",",
"_addr",
")",
"if",
"raw",
":",
"_addr",
"=",
"raw",
".",
"group",
"(",
"1",
")",
"if",
"_addr",
"==",
"addr",
":",
"log",
"(",
"\"Address '%s' is configured on iface '%s'\"",
"%",
"(",
"addr",
",",
"iface",
")",
")",
"return",
"iface",
"msg",
"=",
"\"Unable to infer net iface on which '%s' is configured\"",
"%",
"(",
"addr",
")",
"raise",
"Exception",
"(",
"msg",
")"
] | Work out on which interface the provided address is configured. | [
"Work",
"out",
"on",
"which",
"interface",
"the",
"provided",
"address",
"is",
"configured",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L323-L342 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | sniff_iface | def sniff_iface(f):
"""Ensure decorated function is called with a value for iface.
If no iface provided, inject net iface inferred from unit private address.
"""
def iface_sniffer(*args, **kwargs):
if not kwargs.get('iface', None):
kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
return f(*args, **kwargs)
return iface_sniffer | python | def sniff_iface(f):
"""Ensure decorated function is called with a value for iface.
If no iface provided, inject net iface inferred from unit private address.
"""
def iface_sniffer(*args, **kwargs):
if not kwargs.get('iface', None):
kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
return f(*args, **kwargs)
return iface_sniffer | [
"def",
"sniff_iface",
"(",
"f",
")",
":",
"def",
"iface_sniffer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'iface'",
",",
"None",
")",
":",
"kwargs",
"[",
"'iface'",
"]",
"=",
"get_iface_from_addr",
"(",
"unit_get",
"(",
"'private-address'",
")",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"iface_sniffer"
] | Ensure decorated function is called with a value for iface.
If no iface provided, inject net iface inferred from unit private address. | [
"Ensure",
"decorated",
"function",
"is",
"called",
"with",
"a",
"value",
"for",
"iface",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L345-L356 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_ipv6_addr | def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
dynamic_only=True):
"""Get assigned IPv6 address for a given interface.
Returns list of addresses found. If no address found, returns empty list.
If iface is None, we infer the current primary interface by doing a reverse
lookup on the unit private-address.
We currently only support scope global IPv6 addresses i.e. non-temporary
addresses. If no global IPv6 address is found, return the first one found
in the ipv6 address list.
:param iface: network interface on which ipv6 address(es) are expected to
be found.
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:param dynamic_only: only recognise dynamic addresses
:return: list of ipv6 addresses
"""
addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
inc_aliases=inc_aliases, fatal=fatal,
exc_list=exc_list)
if addresses:
global_addrs = []
for addr in addresses:
key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
m = re.match(key_scope_link_local, addr)
if m:
eui_64_mac = m.group(1)
iface = m.group(2)
else:
global_addrs.append(addr)
if global_addrs:
# Make sure any found global addresses are not temporary
cmd = ['ip', 'addr', 'show', iface]
out = subprocess.check_output(cmd).decode('UTF-8')
if dynamic_only:
key = re.compile("inet6 (.+)/[0-9]+ scope global.* dynamic.*")
else:
key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
addrs = []
for line in out.split('\n'):
line = line.strip()
m = re.match(key, line)
if m and 'temporary' not in line:
# Return the first valid address we find
for addr in global_addrs:
if m.group(1) == addr:
if not dynamic_only or \
m.group(1).endswith(eui_64_mac):
addrs.append(addr)
if addrs:
return addrs
if fatal:
raise Exception("Interface '%s' does not have a scope global "
"non-temporary ipv6 address." % iface)
return [] | python | def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
dynamic_only=True):
"""Get assigned IPv6 address for a given interface.
Returns list of addresses found. If no address found, returns empty list.
If iface is None, we infer the current primary interface by doing a reverse
lookup on the unit private-address.
We currently only support scope global IPv6 addresses i.e. non-temporary
addresses. If no global IPv6 address is found, return the first one found
in the ipv6 address list.
:param iface: network interface on which ipv6 address(es) are expected to
be found.
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:param dynamic_only: only recognise dynamic addresses
:return: list of ipv6 addresses
"""
addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
inc_aliases=inc_aliases, fatal=fatal,
exc_list=exc_list)
if addresses:
global_addrs = []
for addr in addresses:
key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
m = re.match(key_scope_link_local, addr)
if m:
eui_64_mac = m.group(1)
iface = m.group(2)
else:
global_addrs.append(addr)
if global_addrs:
# Make sure any found global addresses are not temporary
cmd = ['ip', 'addr', 'show', iface]
out = subprocess.check_output(cmd).decode('UTF-8')
if dynamic_only:
key = re.compile("inet6 (.+)/[0-9]+ scope global.* dynamic.*")
else:
key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
addrs = []
for line in out.split('\n'):
line = line.strip()
m = re.match(key, line)
if m and 'temporary' not in line:
# Return the first valid address we find
for addr in global_addrs:
if m.group(1) == addr:
if not dynamic_only or \
m.group(1).endswith(eui_64_mac):
addrs.append(addr)
if addrs:
return addrs
if fatal:
raise Exception("Interface '%s' does not have a scope global "
"non-temporary ipv6 address." % iface)
return [] | [
"def",
"get_ipv6_addr",
"(",
"iface",
"=",
"None",
",",
"inc_aliases",
"=",
"False",
",",
"fatal",
"=",
"True",
",",
"exc_list",
"=",
"None",
",",
"dynamic_only",
"=",
"True",
")",
":",
"addresses",
"=",
"get_iface_addr",
"(",
"iface",
"=",
"iface",
",",
"inet_type",
"=",
"'AF_INET6'",
",",
"inc_aliases",
"=",
"inc_aliases",
",",
"fatal",
"=",
"fatal",
",",
"exc_list",
"=",
"exc_list",
")",
"if",
"addresses",
":",
"global_addrs",
"=",
"[",
"]",
"for",
"addr",
"in",
"addresses",
":",
"key_scope_link_local",
"=",
"re",
".",
"compile",
"(",
"\"^fe80::..(.+)%(.+)\"",
")",
"m",
"=",
"re",
".",
"match",
"(",
"key_scope_link_local",
",",
"addr",
")",
"if",
"m",
":",
"eui_64_mac",
"=",
"m",
".",
"group",
"(",
"1",
")",
"iface",
"=",
"m",
".",
"group",
"(",
"2",
")",
"else",
":",
"global_addrs",
".",
"append",
"(",
"addr",
")",
"if",
"global_addrs",
":",
"# Make sure any found global addresses are not temporary",
"cmd",
"=",
"[",
"'ip'",
",",
"'addr'",
",",
"'show'",
",",
"iface",
"]",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
"if",
"dynamic_only",
":",
"key",
"=",
"re",
".",
"compile",
"(",
"\"inet6 (.+)/[0-9]+ scope global.* dynamic.*\"",
")",
"else",
":",
"key",
"=",
"re",
".",
"compile",
"(",
"\"inet6 (.+)/[0-9]+ scope global.*\"",
")",
"addrs",
"=",
"[",
"]",
"for",
"line",
"in",
"out",
".",
"split",
"(",
"'\\n'",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"m",
"=",
"re",
".",
"match",
"(",
"key",
",",
"line",
")",
"if",
"m",
"and",
"'temporary'",
"not",
"in",
"line",
":",
"# Return the first valid address we find",
"for",
"addr",
"in",
"global_addrs",
":",
"if",
"m",
".",
"group",
"(",
"1",
")",
"==",
"addr",
":",
"if",
"not",
"dynamic_only",
"or",
"m",
".",
"group",
"(",
"1",
")",
".",
"endswith",
"(",
"eui_64_mac",
")",
":",
"addrs",
".",
"append",
"(",
"addr",
")",
"if",
"addrs",
":",
"return",
"addrs",
"if",
"fatal",
":",
"raise",
"Exception",
"(",
"\"Interface '%s' does not have a scope global \"",
"\"non-temporary ipv6 address.\"",
"%",
"iface",
")",
"return",
"[",
"]"
] | Get assigned IPv6 address for a given interface.
Returns list of addresses found. If no address found, returns empty list.
If iface is None, we infer the current primary interface by doing a reverse
lookup on the unit private-address.
We currently only support scope global IPv6 addresses i.e. non-temporary
addresses. If no global IPv6 address is found, return the first one found
in the ipv6 address list.
:param iface: network interface on which ipv6 address(es) are expected to
be found.
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:param dynamic_only: only recognise dynamic addresses
:return: list of ipv6 addresses | [
"Get",
"assigned",
"IPv6",
"address",
"for",
"a",
"given",
"interface",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L360-L424 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_bridges | def get_bridges(vnic_dir='/sys/devices/virtual/net'):
"""Return a list of bridges on the system."""
b_regex = "%s/*/bridge" % vnic_dir
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)] | python | def get_bridges(vnic_dir='/sys/devices/virtual/net'):
"""Return a list of bridges on the system."""
b_regex = "%s/*/bridge" % vnic_dir
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)] | [
"def",
"get_bridges",
"(",
"vnic_dir",
"=",
"'/sys/devices/virtual/net'",
")",
":",
"b_regex",
"=",
"\"%s/*/bridge\"",
"%",
"vnic_dir",
"return",
"[",
"x",
".",
"replace",
"(",
"vnic_dir",
",",
"''",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"for",
"x",
"in",
"glob",
".",
"glob",
"(",
"b_regex",
")",
"]"
] | Return a list of bridges on the system. | [
"Return",
"a",
"list",
"of",
"bridges",
"on",
"the",
"system",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L427-L430 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_bridge_nics | def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
"""Return a list of nics comprising a given bridge on the system."""
brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
return [x.split('/')[-1] for x in glob.glob(brif_regex)] | python | def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
"""Return a list of nics comprising a given bridge on the system."""
brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
return [x.split('/')[-1] for x in glob.glob(brif_regex)] | [
"def",
"get_bridge_nics",
"(",
"bridge",
",",
"vnic_dir",
"=",
"'/sys/devices/virtual/net'",
")",
":",
"brif_regex",
"=",
"\"%s/%s/brif/*\"",
"%",
"(",
"vnic_dir",
",",
"bridge",
")",
"return",
"[",
"x",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"for",
"x",
"in",
"glob",
".",
"glob",
"(",
"brif_regex",
")",
"]"
] | Return a list of nics comprising a given bridge on the system. | [
"Return",
"a",
"list",
"of",
"nics",
"comprising",
"a",
"given",
"bridge",
"on",
"the",
"system",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L433-L436 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | is_ip | def is_ip(address):
"""
Returns True if address is a valid IP address.
"""
try:
# Test to see if already an IPv4/IPv6 address
address = netaddr.IPAddress(address)
return True
except (netaddr.AddrFormatError, ValueError):
return False | python | def is_ip(address):
"""
Returns True if address is a valid IP address.
"""
try:
# Test to see if already an IPv4/IPv6 address
address = netaddr.IPAddress(address)
return True
except (netaddr.AddrFormatError, ValueError):
return False | [
"def",
"is_ip",
"(",
"address",
")",
":",
"try",
":",
"# Test to see if already an IPv4/IPv6 address",
"address",
"=",
"netaddr",
".",
"IPAddress",
"(",
"address",
")",
"return",
"True",
"except",
"(",
"netaddr",
".",
"AddrFormatError",
",",
"ValueError",
")",
":",
"return",
"False"
] | Returns True if address is a valid IP address. | [
"Returns",
"True",
"if",
"address",
"is",
"a",
"valid",
"IP",
"address",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L448-L457 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_host_ip | def get_host_ip(hostname, fallback=None):
"""
Resolves the IP for a given hostname, or returns
the input if it is already an IP.
"""
if is_ip(hostname):
return hostname
ip_addr = ns_query(hostname)
if not ip_addr:
try:
ip_addr = socket.gethostbyname(hostname)
except Exception:
log("Failed to resolve hostname '%s'" % (hostname),
level=WARNING)
return fallback
return ip_addr | python | def get_host_ip(hostname, fallback=None):
"""
Resolves the IP for a given hostname, or returns
the input if it is already an IP.
"""
if is_ip(hostname):
return hostname
ip_addr = ns_query(hostname)
if not ip_addr:
try:
ip_addr = socket.gethostbyname(hostname)
except Exception:
log("Failed to resolve hostname '%s'" % (hostname),
level=WARNING)
return fallback
return ip_addr | [
"def",
"get_host_ip",
"(",
"hostname",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"is_ip",
"(",
"hostname",
")",
":",
"return",
"hostname",
"ip_addr",
"=",
"ns_query",
"(",
"hostname",
")",
"if",
"not",
"ip_addr",
":",
"try",
":",
"ip_addr",
"=",
"socket",
".",
"gethostbyname",
"(",
"hostname",
")",
"except",
"Exception",
":",
"log",
"(",
"\"Failed to resolve hostname '%s'\"",
"%",
"(",
"hostname",
")",
",",
"level",
"=",
"WARNING",
")",
"return",
"fallback",
"return",
"ip_addr"
] | Resolves the IP for a given hostname, or returns
the input if it is already an IP. | [
"Resolves",
"the",
"IP",
"for",
"a",
"given",
"hostname",
"or",
"returns",
"the",
"input",
"if",
"it",
"is",
"already",
"an",
"IP",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L487-L503 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_hostname | def get_hostname(address, fqdn=True):
"""
Resolves hostname for given IP, or returns the input
if it is already a hostname.
"""
if is_ip(address):
try:
import dns.reversename
except ImportError:
if six.PY2:
apt_install("python-dnspython", fatal=True)
else:
apt_install("python3-dnspython", fatal=True)
import dns.reversename
rev = dns.reversename.from_address(address)
result = ns_query(rev)
if not result:
try:
result = socket.gethostbyaddr(address)[0]
except Exception:
return None
else:
result = address
if fqdn:
# strip trailing .
if result.endswith('.'):
return result[:-1]
else:
return result
else:
return result.split('.')[0] | python | def get_hostname(address, fqdn=True):
"""
Resolves hostname for given IP, or returns the input
if it is already a hostname.
"""
if is_ip(address):
try:
import dns.reversename
except ImportError:
if six.PY2:
apt_install("python-dnspython", fatal=True)
else:
apt_install("python3-dnspython", fatal=True)
import dns.reversename
rev = dns.reversename.from_address(address)
result = ns_query(rev)
if not result:
try:
result = socket.gethostbyaddr(address)[0]
except Exception:
return None
else:
result = address
if fqdn:
# strip trailing .
if result.endswith('.'):
return result[:-1]
else:
return result
else:
return result.split('.')[0] | [
"def",
"get_hostname",
"(",
"address",
",",
"fqdn",
"=",
"True",
")",
":",
"if",
"is_ip",
"(",
"address",
")",
":",
"try",
":",
"import",
"dns",
".",
"reversename",
"except",
"ImportError",
":",
"if",
"six",
".",
"PY2",
":",
"apt_install",
"(",
"\"python-dnspython\"",
",",
"fatal",
"=",
"True",
")",
"else",
":",
"apt_install",
"(",
"\"python3-dnspython\"",
",",
"fatal",
"=",
"True",
")",
"import",
"dns",
".",
"reversename",
"rev",
"=",
"dns",
".",
"reversename",
".",
"from_address",
"(",
"address",
")",
"result",
"=",
"ns_query",
"(",
"rev",
")",
"if",
"not",
"result",
":",
"try",
":",
"result",
"=",
"socket",
".",
"gethostbyaddr",
"(",
"address",
")",
"[",
"0",
"]",
"except",
"Exception",
":",
"return",
"None",
"else",
":",
"result",
"=",
"address",
"if",
"fqdn",
":",
"# strip trailing .",
"if",
"result",
".",
"endswith",
"(",
"'.'",
")",
":",
"return",
"result",
"[",
":",
"-",
"1",
"]",
"else",
":",
"return",
"result",
"else",
":",
"return",
"result",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]"
] | Resolves hostname for given IP, or returns the input
if it is already a hostname. | [
"Resolves",
"hostname",
"for",
"given",
"IP",
"or",
"returns",
"the",
"input",
"if",
"it",
"is",
"already",
"a",
"hostname",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L506-L539 | train |
juju/charm-helpers | charmhelpers/contrib/network/ip.py | get_relation_ip | def get_relation_ip(interface, cidr_network=None):
"""Return this unit's IP for the given interface.
Allow for an arbitrary interface to use with network-get to select an IP.
Handle all address selection options including passed cidr network and
IPv6.
Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8')
@param interface: string name of the relation.
@param cidr_network: string CIDR Network to select an address from.
@raises Exception if prefer-ipv6 is configured but IPv6 unsupported.
@returns IPv6 or IPv4 address
"""
# Select the interface address first
# For possible use as a fallback bellow with get_address_in_network
try:
# Get the interface specific IP
address = network_get_primary_address(interface)
except NotImplementedError:
# If network-get is not available
address = get_host_ip(unit_get('private-address'))
except NoNetworkBinding:
log("No network binding for {}".format(interface), WARNING)
address = get_host_ip(unit_get('private-address'))
if config('prefer-ipv6'):
# Currently IPv6 has priority, eventually we want IPv6 to just be
# another network space.
assert_charm_supports_ipv6()
return get_ipv6_addr()[0]
elif cidr_network:
# If a specific CIDR network is passed get the address from that
# network.
return get_address_in_network(cidr_network, address)
# Return the interface address
return address | python | def get_relation_ip(interface, cidr_network=None):
"""Return this unit's IP for the given interface.
Allow for an arbitrary interface to use with network-get to select an IP.
Handle all address selection options including passed cidr network and
IPv6.
Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8')
@param interface: string name of the relation.
@param cidr_network: string CIDR Network to select an address from.
@raises Exception if prefer-ipv6 is configured but IPv6 unsupported.
@returns IPv6 or IPv4 address
"""
# Select the interface address first
# For possible use as a fallback bellow with get_address_in_network
try:
# Get the interface specific IP
address = network_get_primary_address(interface)
except NotImplementedError:
# If network-get is not available
address = get_host_ip(unit_get('private-address'))
except NoNetworkBinding:
log("No network binding for {}".format(interface), WARNING)
address = get_host_ip(unit_get('private-address'))
if config('prefer-ipv6'):
# Currently IPv6 has priority, eventually we want IPv6 to just be
# another network space.
assert_charm_supports_ipv6()
return get_ipv6_addr()[0]
elif cidr_network:
# If a specific CIDR network is passed get the address from that
# network.
return get_address_in_network(cidr_network, address)
# Return the interface address
return address | [
"def",
"get_relation_ip",
"(",
"interface",
",",
"cidr_network",
"=",
"None",
")",
":",
"# Select the interface address first",
"# For possible use as a fallback bellow with get_address_in_network",
"try",
":",
"# Get the interface specific IP",
"address",
"=",
"network_get_primary_address",
"(",
"interface",
")",
"except",
"NotImplementedError",
":",
"# If network-get is not available",
"address",
"=",
"get_host_ip",
"(",
"unit_get",
"(",
"'private-address'",
")",
")",
"except",
"NoNetworkBinding",
":",
"log",
"(",
"\"No network binding for {}\"",
".",
"format",
"(",
"interface",
")",
",",
"WARNING",
")",
"address",
"=",
"get_host_ip",
"(",
"unit_get",
"(",
"'private-address'",
")",
")",
"if",
"config",
"(",
"'prefer-ipv6'",
")",
":",
"# Currently IPv6 has priority, eventually we want IPv6 to just be",
"# another network space.",
"assert_charm_supports_ipv6",
"(",
")",
"return",
"get_ipv6_addr",
"(",
")",
"[",
"0",
"]",
"elif",
"cidr_network",
":",
"# If a specific CIDR network is passed get the address from that",
"# network.",
"return",
"get_address_in_network",
"(",
"cidr_network",
",",
"address",
")",
"# Return the interface address",
"return",
"address"
] | Return this unit's IP for the given interface.
Allow for an arbitrary interface to use with network-get to select an IP.
Handle all address selection options including passed cidr network and
IPv6.
Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8')
@param interface: string name of the relation.
@param cidr_network: string CIDR Network to select an address from.
@raises Exception if prefer-ipv6 is configured but IPv6 unsupported.
@returns IPv6 or IPv4 address | [
"Return",
"this",
"unit",
"s",
"IP",
"for",
"the",
"given",
"interface",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L565-L602 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | BaseFileAudit.ensure_compliance | def ensure_compliance(self):
"""Ensure that the all registered files comply to registered criteria.
"""
for p in self.paths:
if os.path.exists(p):
if self.is_compliant(p):
continue
log('File %s is not in compliance.' % p, level=INFO)
else:
if not self.always_comply:
log("Non-existent path '%s' - skipping compliance check"
% (p), level=INFO)
continue
if self._take_action():
log("Applying compliance criteria to '%s'" % (p), level=INFO)
self.comply(p) | python | def ensure_compliance(self):
"""Ensure that the all registered files comply to registered criteria.
"""
for p in self.paths:
if os.path.exists(p):
if self.is_compliant(p):
continue
log('File %s is not in compliance.' % p, level=INFO)
else:
if not self.always_comply:
log("Non-existent path '%s' - skipping compliance check"
% (p), level=INFO)
continue
if self._take_action():
log("Applying compliance criteria to '%s'" % (p), level=INFO)
self.comply(p) | [
"def",
"ensure_compliance",
"(",
"self",
")",
":",
"for",
"p",
"in",
"self",
".",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
":",
"if",
"self",
".",
"is_compliant",
"(",
"p",
")",
":",
"continue",
"log",
"(",
"'File %s is not in compliance.'",
"%",
"p",
",",
"level",
"=",
"INFO",
")",
"else",
":",
"if",
"not",
"self",
".",
"always_comply",
":",
"log",
"(",
"\"Non-existent path '%s' - skipping compliance check\"",
"%",
"(",
"p",
")",
",",
"level",
"=",
"INFO",
")",
"continue",
"if",
"self",
".",
"_take_action",
"(",
")",
":",
"log",
"(",
"\"Applying compliance criteria to '%s'\"",
"%",
"(",
"p",
")",
",",
"level",
"=",
"INFO",
")",
"self",
".",
"comply",
"(",
"p",
")"
] | Ensure that the all registered files comply to registered criteria. | [
"Ensure",
"that",
"the",
"all",
"registered",
"files",
"comply",
"to",
"registered",
"criteria",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L71-L88 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | FilePermissionAudit.is_compliant | def is_compliant(self, path):
"""Checks if the path is in compliance.
Used to determine if the path specified meets the necessary
requirements to be in compliance with the check itself.
:param path: the file path to check
:returns: True if the path is compliant, False otherwise.
"""
stat = self._get_stat(path)
user = self.user
group = self.group
compliant = True
if stat.st_uid != user.pw_uid or stat.st_gid != group.gr_gid:
log('File %s is not owned by %s:%s.' % (path, user.pw_name,
group.gr_name),
level=INFO)
compliant = False
# POSIX refers to the st_mode bits as corresponding to both the
# file type and file permission bits, where the least significant 12
# bits (o7777) are the suid (11), sgid (10), sticky bits (9), and the
# file permission bits (8-0)
perms = stat.st_mode & 0o7777
if perms != self.mode:
log('File %s has incorrect permissions, currently set to %s' %
(path, oct(stat.st_mode & 0o7777)), level=INFO)
compliant = False
return compliant | python | def is_compliant(self, path):
"""Checks if the path is in compliance.
Used to determine if the path specified meets the necessary
requirements to be in compliance with the check itself.
:param path: the file path to check
:returns: True if the path is compliant, False otherwise.
"""
stat = self._get_stat(path)
user = self.user
group = self.group
compliant = True
if stat.st_uid != user.pw_uid or stat.st_gid != group.gr_gid:
log('File %s is not owned by %s:%s.' % (path, user.pw_name,
group.gr_name),
level=INFO)
compliant = False
# POSIX refers to the st_mode bits as corresponding to both the
# file type and file permission bits, where the least significant 12
# bits (o7777) are the suid (11), sgid (10), sticky bits (9), and the
# file permission bits (8-0)
perms = stat.st_mode & 0o7777
if perms != self.mode:
log('File %s has incorrect permissions, currently set to %s' %
(path, oct(stat.st_mode & 0o7777)), level=INFO)
compliant = False
return compliant | [
"def",
"is_compliant",
"(",
"self",
",",
"path",
")",
":",
"stat",
"=",
"self",
".",
"_get_stat",
"(",
"path",
")",
"user",
"=",
"self",
".",
"user",
"group",
"=",
"self",
".",
"group",
"compliant",
"=",
"True",
"if",
"stat",
".",
"st_uid",
"!=",
"user",
".",
"pw_uid",
"or",
"stat",
".",
"st_gid",
"!=",
"group",
".",
"gr_gid",
":",
"log",
"(",
"'File %s is not owned by %s:%s.'",
"%",
"(",
"path",
",",
"user",
".",
"pw_name",
",",
"group",
".",
"gr_name",
")",
",",
"level",
"=",
"INFO",
")",
"compliant",
"=",
"False",
"# POSIX refers to the st_mode bits as corresponding to both the",
"# file type and file permission bits, where the least significant 12",
"# bits (o7777) are the suid (11), sgid (10), sticky bits (9), and the",
"# file permission bits (8-0)",
"perms",
"=",
"stat",
".",
"st_mode",
"&",
"0o7777",
"if",
"perms",
"!=",
"self",
".",
"mode",
":",
"log",
"(",
"'File %s has incorrect permissions, currently set to %s'",
"%",
"(",
"path",
",",
"oct",
"(",
"stat",
".",
"st_mode",
"&",
"0o7777",
")",
")",
",",
"level",
"=",
"INFO",
")",
"compliant",
"=",
"False",
"return",
"compliant"
] | Checks if the path is in compliance.
Used to determine if the path specified meets the necessary
requirements to be in compliance with the check itself.
:param path: the file path to check
:returns: True if the path is compliant, False otherwise. | [
"Checks",
"if",
"the",
"path",
"is",
"in",
"compliance",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L158-L188 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | FilePermissionAudit.comply | def comply(self, path):
"""Issues a chown and chmod to the file paths specified."""
utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name,
self.mode) | python | def comply(self, path):
"""Issues a chown and chmod to the file paths specified."""
utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name,
self.mode) | [
"def",
"comply",
"(",
"self",
",",
"path",
")",
":",
"utils",
".",
"ensure_permissions",
"(",
"path",
",",
"self",
".",
"user",
".",
"pw_name",
",",
"self",
".",
"group",
".",
"gr_name",
",",
"self",
".",
"mode",
")"
] | Issues a chown and chmod to the file paths specified. | [
"Issues",
"a",
"chown",
"and",
"chmod",
"to",
"the",
"file",
"paths",
"specified",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L190-L193 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | DirectoryPermissionAudit.is_compliant | def is_compliant(self, path):
"""Checks if the directory is compliant.
Used to determine if the path specified and all of its children
directories are in compliance with the check itself.
:param path: the directory path to check
:returns: True if the directory tree is compliant, otherwise False.
"""
if not os.path.isdir(path):
log('Path specified %s is not a directory.' % path, level=ERROR)
raise ValueError("%s is not a directory." % path)
if not self.recursive:
return super(DirectoryPermissionAudit, self).is_compliant(path)
compliant = True
for root, dirs, _ in os.walk(path):
if len(dirs) > 0:
continue
if not super(DirectoryPermissionAudit, self).is_compliant(root):
compliant = False
continue
return compliant | python | def is_compliant(self, path):
"""Checks if the directory is compliant.
Used to determine if the path specified and all of its children
directories are in compliance with the check itself.
:param path: the directory path to check
:returns: True if the directory tree is compliant, otherwise False.
"""
if not os.path.isdir(path):
log('Path specified %s is not a directory.' % path, level=ERROR)
raise ValueError("%s is not a directory." % path)
if not self.recursive:
return super(DirectoryPermissionAudit, self).is_compliant(path)
compliant = True
for root, dirs, _ in os.walk(path):
if len(dirs) > 0:
continue
if not super(DirectoryPermissionAudit, self).is_compliant(root):
compliant = False
continue
return compliant | [
"def",
"is_compliant",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"log",
"(",
"'Path specified %s is not a directory.'",
"%",
"path",
",",
"level",
"=",
"ERROR",
")",
"raise",
"ValueError",
"(",
"\"%s is not a directory.\"",
"%",
"path",
")",
"if",
"not",
"self",
".",
"recursive",
":",
"return",
"super",
"(",
"DirectoryPermissionAudit",
",",
"self",
")",
".",
"is_compliant",
"(",
"path",
")",
"compliant",
"=",
"True",
"for",
"root",
",",
"dirs",
",",
"_",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"if",
"len",
"(",
"dirs",
")",
">",
"0",
":",
"continue",
"if",
"not",
"super",
"(",
"DirectoryPermissionAudit",
",",
"self",
")",
".",
"is_compliant",
"(",
"root",
")",
":",
"compliant",
"=",
"False",
"continue",
"return",
"compliant"
] | Checks if the directory is compliant.
Used to determine if the path specified and all of its children
directories are in compliance with the check itself.
:param path: the directory path to check
:returns: True if the directory tree is compliant, otherwise False. | [
"Checks",
"if",
"the",
"directory",
"is",
"compliant",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L205-L230 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | TemplatedFile.is_compliant | def is_compliant(self, path):
"""Determines if the templated file is compliant.
A templated file is only compliant if it has not changed (as
determined by its sha256 hashsum) AND its file permissions are set
appropriately.
:param path: the path to check compliance.
"""
same_templates = self.templates_match(path)
same_content = self.contents_match(path)
same_permissions = self.permissions_match(path)
if same_content and same_permissions and same_templates:
return True
return False | python | def is_compliant(self, path):
"""Determines if the templated file is compliant.
A templated file is only compliant if it has not changed (as
determined by its sha256 hashsum) AND its file permissions are set
appropriately.
:param path: the path to check compliance.
"""
same_templates = self.templates_match(path)
same_content = self.contents_match(path)
same_permissions = self.permissions_match(path)
if same_content and same_permissions and same_templates:
return True
return False | [
"def",
"is_compliant",
"(",
"self",
",",
"path",
")",
":",
"same_templates",
"=",
"self",
".",
"templates_match",
"(",
"path",
")",
"same_content",
"=",
"self",
".",
"contents_match",
"(",
"path",
")",
"same_permissions",
"=",
"self",
".",
"permissions_match",
"(",
"path",
")",
"if",
"same_content",
"and",
"same_permissions",
"and",
"same_templates",
":",
"return",
"True",
"return",
"False"
] | Determines if the templated file is compliant.
A templated file is only compliant if it has not changed (as
determined by its sha256 hashsum) AND its file permissions are set
appropriately.
:param path: the path to check compliance. | [
"Determines",
"if",
"the",
"templated",
"file",
"is",
"compliant",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L347-L363 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | TemplatedFile.run_service_actions | def run_service_actions(self):
"""Run any actions on services requested."""
if not self.service_actions:
return
for svc_action in self.service_actions:
name = svc_action['service']
actions = svc_action['actions']
log("Running service '%s' actions '%s'" % (name, actions),
level=DEBUG)
for action in actions:
cmd = ['service', name, action]
try:
check_call(cmd)
except CalledProcessError as exc:
log("Service name='%s' action='%s' failed - %s" %
(name, action, exc), level=WARNING) | python | def run_service_actions(self):
"""Run any actions on services requested."""
if not self.service_actions:
return
for svc_action in self.service_actions:
name = svc_action['service']
actions = svc_action['actions']
log("Running service '%s' actions '%s'" % (name, actions),
level=DEBUG)
for action in actions:
cmd = ['service', name, action]
try:
check_call(cmd)
except CalledProcessError as exc:
log("Service name='%s' action='%s' failed - %s" %
(name, action, exc), level=WARNING) | [
"def",
"run_service_actions",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"service_actions",
":",
"return",
"for",
"svc_action",
"in",
"self",
".",
"service_actions",
":",
"name",
"=",
"svc_action",
"[",
"'service'",
"]",
"actions",
"=",
"svc_action",
"[",
"'actions'",
"]",
"log",
"(",
"\"Running service '%s' actions '%s'\"",
"%",
"(",
"name",
",",
"actions",
")",
",",
"level",
"=",
"DEBUG",
")",
"for",
"action",
"in",
"actions",
":",
"cmd",
"=",
"[",
"'service'",
",",
"name",
",",
"action",
"]",
"try",
":",
"check_call",
"(",
"cmd",
")",
"except",
"CalledProcessError",
"as",
"exc",
":",
"log",
"(",
"\"Service name='%s' action='%s' failed - %s\"",
"%",
"(",
"name",
",",
"action",
",",
"exc",
")",
",",
"level",
"=",
"WARNING",
")"
] | Run any actions on services requested. | [
"Run",
"any",
"actions",
"on",
"services",
"requested",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L365-L381 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | TemplatedFile.comply | def comply(self, path):
"""Ensures the contents and the permissions of the file.
:param path: the path to correct
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
self.pre_write()
render_and_write(self.template_dir, path, self.context())
utils.ensure_permissions(path, self.user, self.group, self.mode)
self.run_service_actions()
self.save_checksum(path)
self.post_write() | python | def comply(self, path):
"""Ensures the contents and the permissions of the file.
:param path: the path to correct
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
self.pre_write()
render_and_write(self.template_dir, path, self.context())
utils.ensure_permissions(path, self.user, self.group, self.mode)
self.run_service_actions()
self.save_checksum(path)
self.post_write() | [
"def",
"comply",
"(",
"self",
",",
"path",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"self",
".",
"pre_write",
"(",
")",
"render_and_write",
"(",
"self",
".",
"template_dir",
",",
"path",
",",
"self",
".",
"context",
"(",
")",
")",
"utils",
".",
"ensure_permissions",
"(",
"path",
",",
"self",
".",
"user",
",",
"self",
".",
"group",
",",
"self",
".",
"mode",
")",
"self",
".",
"run_service_actions",
"(",
")",
"self",
".",
"save_checksum",
"(",
"path",
")",
"self",
".",
"post_write",
"(",
")"
] | Ensures the contents and the permissions of the file.
:param path: the path to correct | [
"Ensures",
"the",
"contents",
"and",
"the",
"permissions",
"of",
"the",
"file",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L383-L397 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | TemplatedFile.templates_match | def templates_match(self, path):
"""Determines if the template files are the same.
The template file equality is determined by the hashsum of the
template files themselves. If there is no hashsum, then the content
cannot be sure to be the same so treat it as if they changed.
Otherwise, return whether or not the hashsums are the same.
:param path: the path to check
:returns: boolean
"""
template_path = get_template_path(self.template_dir, path)
key = 'hardening:template:%s' % template_path
template_checksum = file_hash(template_path)
kv = unitdata.kv()
stored_tmplt_checksum = kv.get(key)
if not stored_tmplt_checksum:
kv.set(key, template_checksum)
kv.flush()
log('Saved template checksum for %s.' % template_path,
level=DEBUG)
# Since we don't have a template checksum, then assume it doesn't
# match and return that the template is different.
return False
elif stored_tmplt_checksum != template_checksum:
kv.set(key, template_checksum)
kv.flush()
log('Updated template checksum for %s.' % template_path,
level=DEBUG)
return False
# Here the template hasn't changed based upon the calculated
# checksum of the template and what was previously stored.
return True | python | def templates_match(self, path):
"""Determines if the template files are the same.
The template file equality is determined by the hashsum of the
template files themselves. If there is no hashsum, then the content
cannot be sure to be the same so treat it as if they changed.
Otherwise, return whether or not the hashsums are the same.
:param path: the path to check
:returns: boolean
"""
template_path = get_template_path(self.template_dir, path)
key = 'hardening:template:%s' % template_path
template_checksum = file_hash(template_path)
kv = unitdata.kv()
stored_tmplt_checksum = kv.get(key)
if not stored_tmplt_checksum:
kv.set(key, template_checksum)
kv.flush()
log('Saved template checksum for %s.' % template_path,
level=DEBUG)
# Since we don't have a template checksum, then assume it doesn't
# match and return that the template is different.
return False
elif stored_tmplt_checksum != template_checksum:
kv.set(key, template_checksum)
kv.flush()
log('Updated template checksum for %s.' % template_path,
level=DEBUG)
return False
# Here the template hasn't changed based upon the calculated
# checksum of the template and what was previously stored.
return True | [
"def",
"templates_match",
"(",
"self",
",",
"path",
")",
":",
"template_path",
"=",
"get_template_path",
"(",
"self",
".",
"template_dir",
",",
"path",
")",
"key",
"=",
"'hardening:template:%s'",
"%",
"template_path",
"template_checksum",
"=",
"file_hash",
"(",
"template_path",
")",
"kv",
"=",
"unitdata",
".",
"kv",
"(",
")",
"stored_tmplt_checksum",
"=",
"kv",
".",
"get",
"(",
"key",
")",
"if",
"not",
"stored_tmplt_checksum",
":",
"kv",
".",
"set",
"(",
"key",
",",
"template_checksum",
")",
"kv",
".",
"flush",
"(",
")",
"log",
"(",
"'Saved template checksum for %s.'",
"%",
"template_path",
",",
"level",
"=",
"DEBUG",
")",
"# Since we don't have a template checksum, then assume it doesn't",
"# match and return that the template is different.",
"return",
"False",
"elif",
"stored_tmplt_checksum",
"!=",
"template_checksum",
":",
"kv",
".",
"set",
"(",
"key",
",",
"template_checksum",
")",
"kv",
".",
"flush",
"(",
")",
"log",
"(",
"'Updated template checksum for %s.'",
"%",
"template_path",
",",
"level",
"=",
"DEBUG",
")",
"return",
"False",
"# Here the template hasn't changed based upon the calculated",
"# checksum of the template and what was previously stored.",
"return",
"True"
] | Determines if the template files are the same.
The template file equality is determined by the hashsum of the
template files themselves. If there is no hashsum, then the content
cannot be sure to be the same so treat it as if they changed.
Otherwise, return whether or not the hashsums are the same.
:param path: the path to check
:returns: boolean | [
"Determines",
"if",
"the",
"template",
"files",
"are",
"the",
"same",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L407-L440 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | TemplatedFile.contents_match | def contents_match(self, path):
"""Determines if the file content is the same.
This is determined by comparing hashsum of the file contents and
the saved hashsum. If there is no hashsum, then the content cannot
be sure to be the same so treat them as if they are not the same.
Otherwise, return True if the hashsums are the same, False if they
are not the same.
:param path: the file to check.
"""
checksum = file_hash(path)
kv = unitdata.kv()
stored_checksum = kv.get('hardening:%s' % path)
if not stored_checksum:
# If the checksum hasn't been generated, return False to ensure
# the file is written and the checksum stored.
log('Checksum for %s has not been calculated.' % path, level=DEBUG)
return False
elif stored_checksum != checksum:
log('Checksum mismatch for %s.' % path, level=DEBUG)
return False
return True | python | def contents_match(self, path):
"""Determines if the file content is the same.
This is determined by comparing hashsum of the file contents and
the saved hashsum. If there is no hashsum, then the content cannot
be sure to be the same so treat them as if they are not the same.
Otherwise, return True if the hashsums are the same, False if they
are not the same.
:param path: the file to check.
"""
checksum = file_hash(path)
kv = unitdata.kv()
stored_checksum = kv.get('hardening:%s' % path)
if not stored_checksum:
# If the checksum hasn't been generated, return False to ensure
# the file is written and the checksum stored.
log('Checksum for %s has not been calculated.' % path, level=DEBUG)
return False
elif stored_checksum != checksum:
log('Checksum mismatch for %s.' % path, level=DEBUG)
return False
return True | [
"def",
"contents_match",
"(",
"self",
",",
"path",
")",
":",
"checksum",
"=",
"file_hash",
"(",
"path",
")",
"kv",
"=",
"unitdata",
".",
"kv",
"(",
")",
"stored_checksum",
"=",
"kv",
".",
"get",
"(",
"'hardening:%s'",
"%",
"path",
")",
"if",
"not",
"stored_checksum",
":",
"# If the checksum hasn't been generated, return False to ensure",
"# the file is written and the checksum stored.",
"log",
"(",
"'Checksum for %s has not been calculated.'",
"%",
"path",
",",
"level",
"=",
"DEBUG",
")",
"return",
"False",
"elif",
"stored_checksum",
"!=",
"checksum",
":",
"log",
"(",
"'Checksum mismatch for %s.'",
"%",
"path",
",",
"level",
"=",
"DEBUG",
")",
"return",
"False",
"return",
"True"
] | Determines if the file content is the same.
This is determined by comparing hashsum of the file contents and
the saved hashsum. If there is no hashsum, then the content cannot
be sure to be the same so treat them as if they are not the same.
Otherwise, return True if the hashsums are the same, False if they
are not the same.
:param path: the file to check. | [
"Determines",
"if",
"the",
"file",
"content",
"is",
"the",
"same",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L442-L466 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | TemplatedFile.permissions_match | def permissions_match(self, path):
"""Determines if the file owner and permissions match.
:param path: the path to check.
"""
audit = FilePermissionAudit(path, self.user, self.group, self.mode)
return audit.is_compliant(path) | python | def permissions_match(self, path):
"""Determines if the file owner and permissions match.
:param path: the path to check.
"""
audit = FilePermissionAudit(path, self.user, self.group, self.mode)
return audit.is_compliant(path) | [
"def",
"permissions_match",
"(",
"self",
",",
"path",
")",
":",
"audit",
"=",
"FilePermissionAudit",
"(",
"path",
",",
"self",
".",
"user",
",",
"self",
".",
"group",
",",
"self",
".",
"mode",
")",
"return",
"audit",
".",
"is_compliant",
"(",
"path",
")"
] | Determines if the file owner and permissions match.
:param path: the path to check. | [
"Determines",
"if",
"the",
"file",
"owner",
"and",
"permissions",
"match",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L468-L474 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/audits/file.py | TemplatedFile.save_checksum | def save_checksum(self, path):
"""Calculates and saves the checksum for the path specified.
:param path: the path of the file to save the checksum.
"""
checksum = file_hash(path)
kv = unitdata.kv()
kv.set('hardening:%s' % path, checksum)
kv.flush() | python | def save_checksum(self, path):
"""Calculates and saves the checksum for the path specified.
:param path: the path of the file to save the checksum.
"""
checksum = file_hash(path)
kv = unitdata.kv()
kv.set('hardening:%s' % path, checksum)
kv.flush() | [
"def",
"save_checksum",
"(",
"self",
",",
"path",
")",
":",
"checksum",
"=",
"file_hash",
"(",
"path",
")",
"kv",
"=",
"unitdata",
".",
"kv",
"(",
")",
"kv",
".",
"set",
"(",
"'hardening:%s'",
"%",
"path",
",",
"checksum",
")",
"kv",
".",
"flush",
"(",
")"
] | Calculates and saves the checksum for the path specified.
:param path: the path of the file to save the checksum. | [
"Calculates",
"and",
"saves",
"the",
"checksum",
"for",
"the",
"path",
"specified",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L476-L484 | train |
juju/charm-helpers | charmhelpers/core/strutils.py | bool_from_string | def bool_from_string(value):
"""Interpret string value as boolean.
Returns True if value translates to True otherwise False.
"""
if isinstance(value, six.string_types):
value = six.text_type(value)
else:
msg = "Unable to interpret non-string value '%s' as boolean" % (value)
raise ValueError(msg)
value = value.strip().lower()
if value in ['y', 'yes', 'true', 't', 'on']:
return True
elif value in ['n', 'no', 'false', 'f', 'off']:
return False
msg = "Unable to interpret string value '%s' as boolean" % (value)
raise ValueError(msg) | python | def bool_from_string(value):
"""Interpret string value as boolean.
Returns True if value translates to True otherwise False.
"""
if isinstance(value, six.string_types):
value = six.text_type(value)
else:
msg = "Unable to interpret non-string value '%s' as boolean" % (value)
raise ValueError(msg)
value = value.strip().lower()
if value in ['y', 'yes', 'true', 't', 'on']:
return True
elif value in ['n', 'no', 'false', 'f', 'off']:
return False
msg = "Unable to interpret string value '%s' as boolean" % (value)
raise ValueError(msg) | [
"def",
"bool_from_string",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"else",
":",
"msg",
"=",
"\"Unable to interpret non-string value '%s' as boolean\"",
"%",
"(",
"value",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"value",
"=",
"value",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"value",
"in",
"[",
"'y'",
",",
"'yes'",
",",
"'true'",
",",
"'t'",
",",
"'on'",
"]",
":",
"return",
"True",
"elif",
"value",
"in",
"[",
"'n'",
",",
"'no'",
",",
"'false'",
",",
"'f'",
",",
"'off'",
"]",
":",
"return",
"False",
"msg",
"=",
"\"Unable to interpret string value '%s' as boolean\"",
"%",
"(",
"value",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | Interpret string value as boolean.
Returns True if value translates to True otherwise False. | [
"Interpret",
"string",
"value",
"as",
"boolean",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/strutils.py#L22-L41 | train |
juju/charm-helpers | charmhelpers/core/strutils.py | bytes_from_string | def bytes_from_string(value):
"""Interpret human readable string value as bytes.
Returns int
"""
BYTE_POWER = {
'K': 1,
'KB': 1,
'M': 2,
'MB': 2,
'G': 3,
'GB': 3,
'T': 4,
'TB': 4,
'P': 5,
'PB': 5,
}
if isinstance(value, six.string_types):
value = six.text_type(value)
else:
msg = "Unable to interpret non-string value '%s' as bytes" % (value)
raise ValueError(msg)
matches = re.match("([0-9]+)([a-zA-Z]+)", value)
if matches:
size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])
else:
# Assume that value passed in is bytes
try:
size = int(value)
except ValueError:
msg = "Unable to interpret string value '%s' as bytes" % (value)
raise ValueError(msg)
return size | python | def bytes_from_string(value):
"""Interpret human readable string value as bytes.
Returns int
"""
BYTE_POWER = {
'K': 1,
'KB': 1,
'M': 2,
'MB': 2,
'G': 3,
'GB': 3,
'T': 4,
'TB': 4,
'P': 5,
'PB': 5,
}
if isinstance(value, six.string_types):
value = six.text_type(value)
else:
msg = "Unable to interpret non-string value '%s' as bytes" % (value)
raise ValueError(msg)
matches = re.match("([0-9]+)([a-zA-Z]+)", value)
if matches:
size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])
else:
# Assume that value passed in is bytes
try:
size = int(value)
except ValueError:
msg = "Unable to interpret string value '%s' as bytes" % (value)
raise ValueError(msg)
return size | [
"def",
"bytes_from_string",
"(",
"value",
")",
":",
"BYTE_POWER",
"=",
"{",
"'K'",
":",
"1",
",",
"'KB'",
":",
"1",
",",
"'M'",
":",
"2",
",",
"'MB'",
":",
"2",
",",
"'G'",
":",
"3",
",",
"'GB'",
":",
"3",
",",
"'T'",
":",
"4",
",",
"'TB'",
":",
"4",
",",
"'P'",
":",
"5",
",",
"'PB'",
":",
"5",
",",
"}",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"else",
":",
"msg",
"=",
"\"Unable to interpret non-string value '%s' as bytes\"",
"%",
"(",
"value",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"matches",
"=",
"re",
".",
"match",
"(",
"\"([0-9]+)([a-zA-Z]+)\"",
",",
"value",
")",
"if",
"matches",
":",
"size",
"=",
"int",
"(",
"matches",
".",
"group",
"(",
"1",
")",
")",
"*",
"(",
"1024",
"**",
"BYTE_POWER",
"[",
"matches",
".",
"group",
"(",
"2",
")",
"]",
")",
"else",
":",
"# Assume that value passed in is bytes",
"try",
":",
"size",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"msg",
"=",
"\"Unable to interpret string value '%s' as bytes\"",
"%",
"(",
"value",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"size"
] | Interpret human readable string value as bytes.
Returns int | [
"Interpret",
"human",
"readable",
"string",
"value",
"as",
"bytes",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/strutils.py#L44-L76 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/__init__.py | audit | def audit(*args):
"""Decorator to register an audit.
These are used to generate audits that can be run on a
deployed system that matches the given configuration
:param args: List of functions to filter tests against
:type args: List[Callable[Dict]]
"""
def wrapper(f):
test_name = f.__name__
if _audits.get(test_name):
raise RuntimeError(
"Test name '{}' used more than once"
.format(test_name))
non_callables = [fn for fn in args if not callable(fn)]
if non_callables:
raise RuntimeError(
"Configuration includes non-callable filters: {}"
.format(non_callables))
_audits[test_name] = Audit(func=f, filters=args)
return f
return wrapper | python | def audit(*args):
"""Decorator to register an audit.
These are used to generate audits that can be run on a
deployed system that matches the given configuration
:param args: List of functions to filter tests against
:type args: List[Callable[Dict]]
"""
def wrapper(f):
test_name = f.__name__
if _audits.get(test_name):
raise RuntimeError(
"Test name '{}' used more than once"
.format(test_name))
non_callables = [fn for fn in args if not callable(fn)]
if non_callables:
raise RuntimeError(
"Configuration includes non-callable filters: {}"
.format(non_callables))
_audits[test_name] = Audit(func=f, filters=args)
return f
return wrapper | [
"def",
"audit",
"(",
"*",
"args",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"test_name",
"=",
"f",
".",
"__name__",
"if",
"_audits",
".",
"get",
"(",
"test_name",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Test name '{}' used more than once\"",
".",
"format",
"(",
"test_name",
")",
")",
"non_callables",
"=",
"[",
"fn",
"for",
"fn",
"in",
"args",
"if",
"not",
"callable",
"(",
"fn",
")",
"]",
"if",
"non_callables",
":",
"raise",
"RuntimeError",
"(",
"\"Configuration includes non-callable filters: {}\"",
".",
"format",
"(",
"non_callables",
")",
")",
"_audits",
"[",
"test_name",
"]",
"=",
"Audit",
"(",
"func",
"=",
"f",
",",
"filters",
"=",
"args",
")",
"return",
"f",
"return",
"wrapper"
] | Decorator to register an audit.
These are used to generate audits that can be run on a
deployed system that matches the given configuration
:param args: List of functions to filter tests against
:type args: List[Callable[Dict]] | [
"Decorator",
"to",
"register",
"an",
"audit",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L35-L57 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/__init__.py | is_audit_type | def is_audit_type(*args):
"""This audit is included in the specified kinds of audits.
:param *args: List of AuditTypes to include this audit in
:type args: List[AuditType]
:rtype: Callable[Dict]
"""
def _is_audit_type(audit_options):
if audit_options.get('audit_type') in args:
return True
else:
return False
return _is_audit_type | python | def is_audit_type(*args):
"""This audit is included in the specified kinds of audits.
:param *args: List of AuditTypes to include this audit in
:type args: List[AuditType]
:rtype: Callable[Dict]
"""
def _is_audit_type(audit_options):
if audit_options.get('audit_type') in args:
return True
else:
return False
return _is_audit_type | [
"def",
"is_audit_type",
"(",
"*",
"args",
")",
":",
"def",
"_is_audit_type",
"(",
"audit_options",
")",
":",
"if",
"audit_options",
".",
"get",
"(",
"'audit_type'",
")",
"in",
"args",
":",
"return",
"True",
"else",
":",
"return",
"False",
"return",
"_is_audit_type"
] | This audit is included in the specified kinds of audits.
:param *args: List of AuditTypes to include this audit in
:type args: List[AuditType]
:rtype: Callable[Dict] | [
"This",
"audit",
"is",
"included",
"in",
"the",
"specified",
"kinds",
"of",
"audits",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L60-L72 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/__init__.py | run | def run(audit_options):
"""Run the configured audits with the specified audit_options.
:param audit_options: Configuration for the audit
:type audit_options: Config
:rtype: Dict[str, str]
"""
errors = {}
results = {}
for name, audit in sorted(_audits.items()):
result_name = name.replace('_', '-')
if result_name in audit_options.get('excludes', []):
print(
"Skipping {} because it is"
"excluded in audit config"
.format(result_name))
continue
if all(p(audit_options) for p in audit.filters):
try:
audit.func(audit_options)
print("{}: PASS".format(name))
results[result_name] = {
'success': True,
}
except AssertionError as e:
print("{}: FAIL ({})".format(name, e))
results[result_name] = {
'success': False,
'message': e,
}
except Exception as e:
print("{}: ERROR ({})".format(name, e))
errors[name] = e
results[result_name] = {
'success': False,
'message': e,
}
for name, error in errors.items():
print("=" * 20)
print("Error in {}: ".format(name))
traceback.print_tb(error.__traceback__)
print()
return results | python | def run(audit_options):
"""Run the configured audits with the specified audit_options.
:param audit_options: Configuration for the audit
:type audit_options: Config
:rtype: Dict[str, str]
"""
errors = {}
results = {}
for name, audit in sorted(_audits.items()):
result_name = name.replace('_', '-')
if result_name in audit_options.get('excludes', []):
print(
"Skipping {} because it is"
"excluded in audit config"
.format(result_name))
continue
if all(p(audit_options) for p in audit.filters):
try:
audit.func(audit_options)
print("{}: PASS".format(name))
results[result_name] = {
'success': True,
}
except AssertionError as e:
print("{}: FAIL ({})".format(name, e))
results[result_name] = {
'success': False,
'message': e,
}
except Exception as e:
print("{}: ERROR ({})".format(name, e))
errors[name] = e
results[result_name] = {
'success': False,
'message': e,
}
for name, error in errors.items():
print("=" * 20)
print("Error in {}: ".format(name))
traceback.print_tb(error.__traceback__)
print()
return results | [
"def",
"run",
"(",
"audit_options",
")",
":",
"errors",
"=",
"{",
"}",
"results",
"=",
"{",
"}",
"for",
"name",
",",
"audit",
"in",
"sorted",
"(",
"_audits",
".",
"items",
"(",
")",
")",
":",
"result_name",
"=",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"result_name",
"in",
"audit_options",
".",
"get",
"(",
"'excludes'",
",",
"[",
"]",
")",
":",
"print",
"(",
"\"Skipping {} because it is\"",
"\"excluded in audit config\"",
".",
"format",
"(",
"result_name",
")",
")",
"continue",
"if",
"all",
"(",
"p",
"(",
"audit_options",
")",
"for",
"p",
"in",
"audit",
".",
"filters",
")",
":",
"try",
":",
"audit",
".",
"func",
"(",
"audit_options",
")",
"print",
"(",
"\"{}: PASS\"",
".",
"format",
"(",
"name",
")",
")",
"results",
"[",
"result_name",
"]",
"=",
"{",
"'success'",
":",
"True",
",",
"}",
"except",
"AssertionError",
"as",
"e",
":",
"print",
"(",
"\"{}: FAIL ({})\"",
".",
"format",
"(",
"name",
",",
"e",
")",
")",
"results",
"[",
"result_name",
"]",
"=",
"{",
"'success'",
":",
"False",
",",
"'message'",
":",
"e",
",",
"}",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"{}: ERROR ({})\"",
".",
"format",
"(",
"name",
",",
"e",
")",
")",
"errors",
"[",
"name",
"]",
"=",
"e",
"results",
"[",
"result_name",
"]",
"=",
"{",
"'success'",
":",
"False",
",",
"'message'",
":",
"e",
",",
"}",
"for",
"name",
",",
"error",
"in",
"errors",
".",
"items",
"(",
")",
":",
"print",
"(",
"\"=\"",
"*",
"20",
")",
"print",
"(",
"\"Error in {}: \"",
".",
"format",
"(",
"name",
")",
")",
"traceback",
".",
"print_tb",
"(",
"error",
".",
"__traceback__",
")",
"print",
"(",
")",
"return",
"results"
] | Run the configured audits with the specified audit_options.
:param audit_options: Configuration for the audit
:type audit_options: Config
:rtype: Dict[str, str] | [
"Run",
"the",
"configured",
"audits",
"with",
"the",
"specified",
"audit_options",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L149-L192 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/__init__.py | action_parse_results | def action_parse_results(result):
"""Parse the result of `run` in the context of an action.
:param result: The result of running the security-checklist
action on a unit
:type result: Dict[str, Dict[str, str]]
:rtype: int
"""
passed = True
for test, result in result.items():
if result['success']:
hookenv.action_set({test: 'PASS'})
else:
hookenv.action_set({test: 'FAIL - {}'.format(result['message'])})
passed = False
if not passed:
hookenv.action_fail("One or more tests failed")
return 0 if passed else 1 | python | def action_parse_results(result):
"""Parse the result of `run` in the context of an action.
:param result: The result of running the security-checklist
action on a unit
:type result: Dict[str, Dict[str, str]]
:rtype: int
"""
passed = True
for test, result in result.items():
if result['success']:
hookenv.action_set({test: 'PASS'})
else:
hookenv.action_set({test: 'FAIL - {}'.format(result['message'])})
passed = False
if not passed:
hookenv.action_fail("One or more tests failed")
return 0 if passed else 1 | [
"def",
"action_parse_results",
"(",
"result",
")",
":",
"passed",
"=",
"True",
"for",
"test",
",",
"result",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"result",
"[",
"'success'",
"]",
":",
"hookenv",
".",
"action_set",
"(",
"{",
"test",
":",
"'PASS'",
"}",
")",
"else",
":",
"hookenv",
".",
"action_set",
"(",
"{",
"test",
":",
"'FAIL - {}'",
".",
"format",
"(",
"result",
"[",
"'message'",
"]",
")",
"}",
")",
"passed",
"=",
"False",
"if",
"not",
"passed",
":",
"hookenv",
".",
"action_fail",
"(",
"\"One or more tests failed\"",
")",
"return",
"0",
"if",
"passed",
"else",
"1"
] | Parse the result of `run` in the context of an action.
:param result: The result of running the security-checklist
action on a unit
:type result: Dict[str, Dict[str, str]]
:rtype: int | [
"Parse",
"the",
"result",
"of",
"run",
"in",
"the",
"context",
"of",
"an",
"action",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L195-L212 | train |
juju/charm-helpers | charmhelpers/contrib/ssl/__init__.py | generate_selfsigned | def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None):
"""Generate selfsigned SSL keypair
You must provide one of the 3 optional arguments:
config, subject or cn
If more than one is provided the leftmost will be used
Arguments:
keyfile -- (required) full path to the keyfile to be created
certfile -- (required) full path to the certfile to be created
keysize -- (optional) SSL key length
config -- (optional) openssl configuration file
subject -- (optional) dictionary with SSL subject variables
cn -- (optional) cerfificate common name
Required keys in subject dict:
cn -- Common name (eq. FQDN)
Optional keys in subject dict
country -- Country Name (2 letter code)
state -- State or Province Name (full name)
locality -- Locality Name (eg, city)
organization -- Organization Name (eg, company)
organizational_unit -- Organizational Unit Name (eg, section)
email -- Email Address
"""
cmd = []
if config:
cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
"rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
"-keyout", keyfile,
"-out", certfile, "-config", config]
elif subject:
ssl_subject = ""
if "country" in subject:
ssl_subject = ssl_subject + "/C={}".format(subject["country"])
if "state" in subject:
ssl_subject = ssl_subject + "/ST={}".format(subject["state"])
if "locality" in subject:
ssl_subject = ssl_subject + "/L={}".format(subject["locality"])
if "organization" in subject:
ssl_subject = ssl_subject + "/O={}".format(subject["organization"])
if "organizational_unit" in subject:
ssl_subject = ssl_subject + "/OU={}".format(subject["organizational_unit"])
if "cn" in subject:
ssl_subject = ssl_subject + "/CN={}".format(subject["cn"])
else:
hookenv.log("When using \"subject\" argument you must "
"provide \"cn\" field at very least")
return False
if "email" in subject:
ssl_subject = ssl_subject + "/emailAddress={}".format(subject["email"])
cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
"rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
"-keyout", keyfile,
"-out", certfile, "-subj", ssl_subject]
elif cn:
cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
"rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
"-keyout", keyfile,
"-out", certfile, "-subj", "/CN={}".format(cn)]
if not cmd:
hookenv.log("No config, subject or cn provided,"
"unable to generate self signed SSL certificates")
return False
try:
subprocess.check_call(cmd)
return True
except Exception as e:
print("Execution of openssl command failed:\n{}".format(e))
return False | python | def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None):
"""Generate selfsigned SSL keypair
You must provide one of the 3 optional arguments:
config, subject or cn
If more than one is provided the leftmost will be used
Arguments:
keyfile -- (required) full path to the keyfile to be created
certfile -- (required) full path to the certfile to be created
keysize -- (optional) SSL key length
config -- (optional) openssl configuration file
subject -- (optional) dictionary with SSL subject variables
cn -- (optional) cerfificate common name
Required keys in subject dict:
cn -- Common name (eq. FQDN)
Optional keys in subject dict
country -- Country Name (2 letter code)
state -- State or Province Name (full name)
locality -- Locality Name (eg, city)
organization -- Organization Name (eg, company)
organizational_unit -- Organizational Unit Name (eg, section)
email -- Email Address
"""
cmd = []
if config:
cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
"rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
"-keyout", keyfile,
"-out", certfile, "-config", config]
elif subject:
ssl_subject = ""
if "country" in subject:
ssl_subject = ssl_subject + "/C={}".format(subject["country"])
if "state" in subject:
ssl_subject = ssl_subject + "/ST={}".format(subject["state"])
if "locality" in subject:
ssl_subject = ssl_subject + "/L={}".format(subject["locality"])
if "organization" in subject:
ssl_subject = ssl_subject + "/O={}".format(subject["organization"])
if "organizational_unit" in subject:
ssl_subject = ssl_subject + "/OU={}".format(subject["organizational_unit"])
if "cn" in subject:
ssl_subject = ssl_subject + "/CN={}".format(subject["cn"])
else:
hookenv.log("When using \"subject\" argument you must "
"provide \"cn\" field at very least")
return False
if "email" in subject:
ssl_subject = ssl_subject + "/emailAddress={}".format(subject["email"])
cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
"rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
"-keyout", keyfile,
"-out", certfile, "-subj", ssl_subject]
elif cn:
cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
"rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
"-keyout", keyfile,
"-out", certfile, "-subj", "/CN={}".format(cn)]
if not cmd:
hookenv.log("No config, subject or cn provided,"
"unable to generate self signed SSL certificates")
return False
try:
subprocess.check_call(cmd)
return True
except Exception as e:
print("Execution of openssl command failed:\n{}".format(e))
return False | [
"def",
"generate_selfsigned",
"(",
"keyfile",
",",
"certfile",
",",
"keysize",
"=",
"\"1024\"",
",",
"config",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"cn",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"]",
"if",
"config",
":",
"cmd",
"=",
"[",
"\"/usr/bin/openssl\"",
",",
"\"req\"",
",",
"\"-new\"",
",",
"\"-newkey\"",
",",
"\"rsa:{}\"",
".",
"format",
"(",
"keysize",
")",
",",
"\"-days\"",
",",
"\"365\"",
",",
"\"-nodes\"",
",",
"\"-x509\"",
",",
"\"-keyout\"",
",",
"keyfile",
",",
"\"-out\"",
",",
"certfile",
",",
"\"-config\"",
",",
"config",
"]",
"elif",
"subject",
":",
"ssl_subject",
"=",
"\"\"",
"if",
"\"country\"",
"in",
"subject",
":",
"ssl_subject",
"=",
"ssl_subject",
"+",
"\"/C={}\"",
".",
"format",
"(",
"subject",
"[",
"\"country\"",
"]",
")",
"if",
"\"state\"",
"in",
"subject",
":",
"ssl_subject",
"=",
"ssl_subject",
"+",
"\"/ST={}\"",
".",
"format",
"(",
"subject",
"[",
"\"state\"",
"]",
")",
"if",
"\"locality\"",
"in",
"subject",
":",
"ssl_subject",
"=",
"ssl_subject",
"+",
"\"/L={}\"",
".",
"format",
"(",
"subject",
"[",
"\"locality\"",
"]",
")",
"if",
"\"organization\"",
"in",
"subject",
":",
"ssl_subject",
"=",
"ssl_subject",
"+",
"\"/O={}\"",
".",
"format",
"(",
"subject",
"[",
"\"organization\"",
"]",
")",
"if",
"\"organizational_unit\"",
"in",
"subject",
":",
"ssl_subject",
"=",
"ssl_subject",
"+",
"\"/OU={}\"",
".",
"format",
"(",
"subject",
"[",
"\"organizational_unit\"",
"]",
")",
"if",
"\"cn\"",
"in",
"subject",
":",
"ssl_subject",
"=",
"ssl_subject",
"+",
"\"/CN={}\"",
".",
"format",
"(",
"subject",
"[",
"\"cn\"",
"]",
")",
"else",
":",
"hookenv",
".",
"log",
"(",
"\"When using \\\"subject\\\" argument you must \"",
"\"provide \\\"cn\\\" field at very least\"",
")",
"return",
"False",
"if",
"\"email\"",
"in",
"subject",
":",
"ssl_subject",
"=",
"ssl_subject",
"+",
"\"/emailAddress={}\"",
".",
"format",
"(",
"subject",
"[",
"\"email\"",
"]",
")",
"cmd",
"=",
"[",
"\"/usr/bin/openssl\"",
",",
"\"req\"",
",",
"\"-new\"",
",",
"\"-newkey\"",
",",
"\"rsa:{}\"",
".",
"format",
"(",
"keysize",
")",
",",
"\"-days\"",
",",
"\"365\"",
",",
"\"-nodes\"",
",",
"\"-x509\"",
",",
"\"-keyout\"",
",",
"keyfile",
",",
"\"-out\"",
",",
"certfile",
",",
"\"-subj\"",
",",
"ssl_subject",
"]",
"elif",
"cn",
":",
"cmd",
"=",
"[",
"\"/usr/bin/openssl\"",
",",
"\"req\"",
",",
"\"-new\"",
",",
"\"-newkey\"",
",",
"\"rsa:{}\"",
".",
"format",
"(",
"keysize",
")",
",",
"\"-days\"",
",",
"\"365\"",
",",
"\"-nodes\"",
",",
"\"-x509\"",
",",
"\"-keyout\"",
",",
"keyfile",
",",
"\"-out\"",
",",
"certfile",
",",
"\"-subj\"",
",",
"\"/CN={}\"",
".",
"format",
"(",
"cn",
")",
"]",
"if",
"not",
"cmd",
":",
"hookenv",
".",
"log",
"(",
"\"No config, subject or cn provided,\"",
"\"unable to generate self signed SSL certificates\"",
")",
"return",
"False",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"cmd",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Execution of openssl command failed:\\n{}\"",
".",
"format",
"(",
"e",
")",
")",
"return",
"False"
] | Generate selfsigned SSL keypair
You must provide one of the 3 optional arguments:
config, subject or cn
If more than one is provided the leftmost will be used
Arguments:
keyfile -- (required) full path to the keyfile to be created
certfile -- (required) full path to the certfile to be created
keysize -- (optional) SSL key length
config -- (optional) openssl configuration file
subject -- (optional) dictionary with SSL subject variables
cn -- (optional) cerfificate common name
Required keys in subject dict:
cn -- Common name (eq. FQDN)
Optional keys in subject dict
country -- Country Name (2 letter code)
state -- State or Province Name (full name)
locality -- Locality Name (eg, city)
organization -- Organization Name (eg, company)
organizational_unit -- Organizational Unit Name (eg, section)
email -- Email Address | [
"Generate",
"selfsigned",
"SSL",
"keypair"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ssl/__init__.py#L19-L92 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | ssh_directory_for_unit | def ssh_directory_for_unit(application_name, user=None):
"""Return the directory used to store ssh assets for the application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Fully qualified directory path.
:rtype: str
"""
if user:
application_name = "{}_{}".format(application_name, user)
_dir = os.path.join(NOVA_SSH_DIR, application_name)
for d in [NOVA_SSH_DIR, _dir]:
if not os.path.isdir(d):
os.mkdir(d)
for f in ['authorized_keys', 'known_hosts']:
f = os.path.join(_dir, f)
if not os.path.isfile(f):
open(f, 'w').close()
return _dir | python | def ssh_directory_for_unit(application_name, user=None):
"""Return the directory used to store ssh assets for the application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Fully qualified directory path.
:rtype: str
"""
if user:
application_name = "{}_{}".format(application_name, user)
_dir = os.path.join(NOVA_SSH_DIR, application_name)
for d in [NOVA_SSH_DIR, _dir]:
if not os.path.isdir(d):
os.mkdir(d)
for f in ['authorized_keys', 'known_hosts']:
f = os.path.join(_dir, f)
if not os.path.isfile(f):
open(f, 'w').close()
return _dir | [
"def",
"ssh_directory_for_unit",
"(",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
":",
"application_name",
"=",
"\"{}_{}\"",
".",
"format",
"(",
"application_name",
",",
"user",
")",
"_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"NOVA_SSH_DIR",
",",
"application_name",
")",
"for",
"d",
"in",
"[",
"NOVA_SSH_DIR",
",",
"_dir",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"d",
")",
":",
"os",
".",
"mkdir",
"(",
"d",
")",
"for",
"f",
"in",
"[",
"'authorized_keys'",
",",
"'known_hosts'",
"]",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_dir",
",",
"f",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
":",
"open",
"(",
"f",
",",
"'w'",
")",
".",
"close",
"(",
")",
"return",
"_dir"
] | Return the directory used to store ssh assets for the application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Fully qualified directory path.
:rtype: str | [
"Return",
"the",
"directory",
"used",
"to",
"store",
"ssh",
"assets",
"for",
"the",
"application",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L36-L56 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | ssh_known_host_key | def ssh_known_host_key(host, application_name, user=None):
"""Return the first entry in known_hosts for host.
:param host: hostname to lookup in file.
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Host key
:rtype: str or None
"""
cmd = [
'ssh-keygen',
'-f', known_hosts(application_name, user),
'-H',
'-F',
host]
try:
# The first line of output is like '# Host xx found: line 1 type RSA',
# which should be excluded.
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
# RC of 1 seems to be legitimate for most ssh-keygen -F calls.
if e.returncode == 1:
output = e.output
else:
raise
output = output.strip()
if output:
# Bug #1500589 cmd has 0 rc on precise if entry not present
lines = output.split('\n')
if len(lines) >= 1:
return lines[0]
return None | python | def ssh_known_host_key(host, application_name, user=None):
"""Return the first entry in known_hosts for host.
:param host: hostname to lookup in file.
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Host key
:rtype: str or None
"""
cmd = [
'ssh-keygen',
'-f', known_hosts(application_name, user),
'-H',
'-F',
host]
try:
# The first line of output is like '# Host xx found: line 1 type RSA',
# which should be excluded.
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
# RC of 1 seems to be legitimate for most ssh-keygen -F calls.
if e.returncode == 1:
output = e.output
else:
raise
output = output.strip()
if output:
# Bug #1500589 cmd has 0 rc on precise if entry not present
lines = output.split('\n')
if len(lines) >= 1:
return lines[0]
return None | [
"def",
"ssh_known_host_key",
"(",
"host",
",",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'ssh-keygen'",
",",
"'-f'",
",",
"known_hosts",
"(",
"application_name",
",",
"user",
")",
",",
"'-H'",
",",
"'-F'",
",",
"host",
"]",
"try",
":",
"# The first line of output is like '# Host xx found: line 1 type RSA',",
"# which should be excluded.",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"# RC of 1 seems to be legitimate for most ssh-keygen -F calls.",
"if",
"e",
".",
"returncode",
"==",
"1",
":",
"output",
"=",
"e",
".",
"output",
"else",
":",
"raise",
"output",
"=",
"output",
".",
"strip",
"(",
")",
"if",
"output",
":",
"# Bug #1500589 cmd has 0 rc on precise if entry not present",
"lines",
"=",
"output",
".",
"split",
"(",
"'\\n'",
")",
"if",
"len",
"(",
"lines",
")",
">=",
"1",
":",
"return",
"lines",
"[",
"0",
"]",
"return",
"None"
] | Return the first entry in known_hosts for host.
:param host: hostname to lookup in file.
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Host key
:rtype: str or None | [
"Return",
"the",
"first",
"entry",
"in",
"known_hosts",
"for",
"host",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L89-L125 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | remove_known_host | def remove_known_host(host, application_name, user=None):
"""Remove the entry in known_hosts for host.
:param host: hostname to lookup in file.
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
log('Removing SSH known host entry for compute host at %s' % host)
cmd = ['ssh-keygen', '-f', known_hosts(application_name, user), '-R', host]
subprocess.check_call(cmd) | python | def remove_known_host(host, application_name, user=None):
"""Remove the entry in known_hosts for host.
:param host: hostname to lookup in file.
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
log('Removing SSH known host entry for compute host at %s' % host)
cmd = ['ssh-keygen', '-f', known_hosts(application_name, user), '-R', host]
subprocess.check_call(cmd) | [
"def",
"remove_known_host",
"(",
"host",
",",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"log",
"(",
"'Removing SSH known host entry for compute host at %s'",
"%",
"host",
")",
"cmd",
"=",
"[",
"'ssh-keygen'",
",",
"'-f'",
",",
"known_hosts",
"(",
"application_name",
",",
"user",
")",
",",
"'-R'",
",",
"host",
"]",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] | Remove the entry in known_hosts for host.
:param host: hostname to lookup in file.
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str | [
"Remove",
"the",
"entry",
"in",
"known_hosts",
"for",
"host",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L128-L140 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | is_same_key | def is_same_key(key_1, key_2):
"""Extract the key from two host entries and compare them.
:param key_1: Host key
:type key_1: str
:param key_2: Host key
:type key_2: str
"""
# The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp'
# 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAAB', we only need to compare
# the part start with 'ssh-rsa' followed with '= ', because the hash
# value in the beginning will change each time.
k_1 = key_1.split('= ')[1]
k_2 = key_2.split('= ')[1]
return k_1 == k_2 | python | def is_same_key(key_1, key_2):
"""Extract the key from two host entries and compare them.
:param key_1: Host key
:type key_1: str
:param key_2: Host key
:type key_2: str
"""
# The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp'
# 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAAB', we only need to compare
# the part start with 'ssh-rsa' followed with '= ', because the hash
# value in the beginning will change each time.
k_1 = key_1.split('= ')[1]
k_2 = key_2.split('= ')[1]
return k_1 == k_2 | [
"def",
"is_same_key",
"(",
"key_1",
",",
"key_2",
")",
":",
"# The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp'",
"# 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAAB', we only need to compare",
"# the part start with 'ssh-rsa' followed with '= ', because the hash",
"# value in the beginning will change each time.",
"k_1",
"=",
"key_1",
".",
"split",
"(",
"'= '",
")",
"[",
"1",
"]",
"k_2",
"=",
"key_2",
".",
"split",
"(",
"'= '",
")",
"[",
"1",
"]",
"return",
"k_1",
"==",
"k_2"
] | Extract the key from two host entries and compare them.
:param key_1: Host key
:type key_1: str
:param key_2: Host key
:type key_2: str | [
"Extract",
"the",
"key",
"from",
"two",
"host",
"entries",
"and",
"compare",
"them",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L143-L157 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | add_known_host | def add_known_host(host, application_name, user=None):
"""Add the given host key to the known hosts file.
:param host: host name
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
cmd = ['ssh-keyscan', '-H', '-t', 'rsa', host]
try:
remote_key = subprocess.check_output(cmd).strip()
except Exception as e:
log('Could not obtain SSH host key from %s' % host, level=ERROR)
raise e
current_key = ssh_known_host_key(host, application_name, user)
if current_key and remote_key:
if is_same_key(remote_key, current_key):
log('Known host key for compute host %s up to date.' % host)
return
else:
remove_known_host(host, application_name, user)
log('Adding SSH host key to known hosts for compute node at %s.' % host)
with open(known_hosts(application_name, user), 'a') as out:
out.write("{}\n".format(remote_key)) | python | def add_known_host(host, application_name, user=None):
"""Add the given host key to the known hosts file.
:param host: host name
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
cmd = ['ssh-keyscan', '-H', '-t', 'rsa', host]
try:
remote_key = subprocess.check_output(cmd).strip()
except Exception as e:
log('Could not obtain SSH host key from %s' % host, level=ERROR)
raise e
current_key = ssh_known_host_key(host, application_name, user)
if current_key and remote_key:
if is_same_key(remote_key, current_key):
log('Known host key for compute host %s up to date.' % host)
return
else:
remove_known_host(host, application_name, user)
log('Adding SSH host key to known hosts for compute node at %s.' % host)
with open(known_hosts(application_name, user), 'a') as out:
out.write("{}\n".format(remote_key)) | [
"def",
"add_known_host",
"(",
"host",
",",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'ssh-keyscan'",
",",
"'-H'",
",",
"'-t'",
",",
"'rsa'",
",",
"host",
"]",
"try",
":",
"remote_key",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
".",
"strip",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
"(",
"'Could not obtain SSH host key from %s'",
"%",
"host",
",",
"level",
"=",
"ERROR",
")",
"raise",
"e",
"current_key",
"=",
"ssh_known_host_key",
"(",
"host",
",",
"application_name",
",",
"user",
")",
"if",
"current_key",
"and",
"remote_key",
":",
"if",
"is_same_key",
"(",
"remote_key",
",",
"current_key",
")",
":",
"log",
"(",
"'Known host key for compute host %s up to date.'",
"%",
"host",
")",
"return",
"else",
":",
"remove_known_host",
"(",
"host",
",",
"application_name",
",",
"user",
")",
"log",
"(",
"'Adding SSH host key to known hosts for compute node at %s.'",
"%",
"host",
")",
"with",
"open",
"(",
"known_hosts",
"(",
"application_name",
",",
"user",
")",
",",
"'a'",
")",
"as",
"out",
":",
"out",
".",
"write",
"(",
"\"{}\\n\"",
".",
"format",
"(",
"remote_key",
")",
")"
] | Add the given host key to the known hosts file.
:param host: host name
:type host: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str | [
"Add",
"the",
"given",
"host",
"key",
"to",
"the",
"known",
"hosts",
"file",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L160-L187 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | ssh_authorized_key_exists | def ssh_authorized_key_exists(public_key, application_name, user=None):
"""Check if given key is in the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Whether given key is in the authorized_key file.
:rtype: boolean
"""
with open(authorized_keys(application_name, user)) as keys:
return ('%s' % public_key) in keys.read() | python | def ssh_authorized_key_exists(public_key, application_name, user=None):
"""Check if given key is in the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Whether given key is in the authorized_key file.
:rtype: boolean
"""
with open(authorized_keys(application_name, user)) as keys:
return ('%s' % public_key) in keys.read() | [
"def",
"ssh_authorized_key_exists",
"(",
"public_key",
",",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"with",
"open",
"(",
"authorized_keys",
"(",
"application_name",
",",
"user",
")",
")",
"as",
"keys",
":",
"return",
"(",
"'%s'",
"%",
"public_key",
")",
"in",
"keys",
".",
"read",
"(",
")"
] | Check if given key is in the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Whether given key is in the authorized_key file.
:rtype: boolean | [
"Check",
"if",
"given",
"key",
"is",
"in",
"the",
"authorized_key",
"file",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L190-L203 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | add_authorized_key | def add_authorized_key(public_key, application_name, user=None):
"""Add given key to the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
with open(authorized_keys(application_name, user), 'a') as keys:
keys.write("{}\n".format(public_key)) | python | def add_authorized_key(public_key, application_name, user=None):
"""Add given key to the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
with open(authorized_keys(application_name, user), 'a') as keys:
keys.write("{}\n".format(public_key)) | [
"def",
"add_authorized_key",
"(",
"public_key",
",",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"with",
"open",
"(",
"authorized_keys",
"(",
"application_name",
",",
"user",
")",
",",
"'a'",
")",
"as",
"keys",
":",
"keys",
".",
"write",
"(",
"\"{}\\n\"",
".",
"format",
"(",
"public_key",
")",
")"
] | Add given key to the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str | [
"Add",
"given",
"key",
"to",
"the",
"authorized_key",
"file",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L206-L217 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | ssh_known_hosts_lines | def ssh_known_hosts_lines(application_name, user=None):
"""Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
known_hosts_list = []
with open(known_hosts(application_name, user)) as hosts:
for hosts_line in hosts:
if hosts_line.rstrip():
known_hosts_list.append(hosts_line.rstrip())
return(known_hosts_list) | python | def ssh_known_hosts_lines(application_name, user=None):
"""Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
known_hosts_list = []
with open(known_hosts(application_name, user)) as hosts:
for hosts_line in hosts:
if hosts_line.rstrip():
known_hosts_list.append(hosts_line.rstrip())
return(known_hosts_list) | [
"def",
"ssh_known_hosts_lines",
"(",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"known_hosts_list",
"=",
"[",
"]",
"with",
"open",
"(",
"known_hosts",
"(",
"application_name",
",",
"user",
")",
")",
"as",
"hosts",
":",
"for",
"hosts_line",
"in",
"hosts",
":",
"if",
"hosts_line",
".",
"rstrip",
"(",
")",
":",
"known_hosts_list",
".",
"append",
"(",
"hosts_line",
".",
"rstrip",
"(",
")",
")",
"return",
"(",
"known_hosts_list",
")"
] | Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str | [
"Return",
"contents",
"of",
"known_hosts",
"file",
"for",
"given",
"application",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L300-L313 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | ssh_authorized_keys_lines | def ssh_authorized_keys_lines(application_name, user=None):
"""Return contents of authorized_keys file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
authorized_keys_list = []
with open(authorized_keys(application_name, user)) as keys:
for authkey_line in keys:
if authkey_line.rstrip():
authorized_keys_list.append(authkey_line.rstrip())
return(authorized_keys_list) | python | def ssh_authorized_keys_lines(application_name, user=None):
"""Return contents of authorized_keys file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
authorized_keys_list = []
with open(authorized_keys(application_name, user)) as keys:
for authkey_line in keys:
if authkey_line.rstrip():
authorized_keys_list.append(authkey_line.rstrip())
return(authorized_keys_list) | [
"def",
"ssh_authorized_keys_lines",
"(",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"authorized_keys_list",
"=",
"[",
"]",
"with",
"open",
"(",
"authorized_keys",
"(",
"application_name",
",",
"user",
")",
")",
"as",
"keys",
":",
"for",
"authkey_line",
"in",
"keys",
":",
"if",
"authkey_line",
".",
"rstrip",
"(",
")",
":",
"authorized_keys_list",
".",
"append",
"(",
"authkey_line",
".",
"rstrip",
"(",
")",
")",
"return",
"(",
"authorized_keys_list",
")"
] | Return contents of authorized_keys file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str | [
"Return",
"contents",
"of",
"authorized_keys",
"file",
"for",
"given",
"application",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L316-L330 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ssh_migrations.py | ssh_compute_remove | def ssh_compute_remove(public_key, application_name, user=None):
"""Remove given public key from authorized_keys file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
if not (os.path.isfile(authorized_keys(application_name, user)) or
os.path.isfile(known_hosts(application_name, user))):
return
keys = ssh_authorized_keys_lines(application_name, user=None)
keys = [k.strip() for k in keys]
if public_key not in keys:
return
[keys.remove(key) for key in keys if key == public_key]
with open(authorized_keys(application_name, user), 'w') as _keys:
keys = '\n'.join(keys)
if not keys.endswith('\n'):
keys += '\n'
_keys.write(keys) | python | def ssh_compute_remove(public_key, application_name, user=None):
"""Remove given public key from authorized_keys file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
if not (os.path.isfile(authorized_keys(application_name, user)) or
os.path.isfile(known_hosts(application_name, user))):
return
keys = ssh_authorized_keys_lines(application_name, user=None)
keys = [k.strip() for k in keys]
if public_key not in keys:
return
[keys.remove(key) for key in keys if key == public_key]
with open(authorized_keys(application_name, user), 'w') as _keys:
keys = '\n'.join(keys)
if not keys.endswith('\n'):
keys += '\n'
_keys.write(keys) | [
"def",
"ssh_compute_remove",
"(",
"public_key",
",",
"application_name",
",",
"user",
"=",
"None",
")",
":",
"if",
"not",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"authorized_keys",
"(",
"application_name",
",",
"user",
")",
")",
"or",
"os",
".",
"path",
".",
"isfile",
"(",
"known_hosts",
"(",
"application_name",
",",
"user",
")",
")",
")",
":",
"return",
"keys",
"=",
"ssh_authorized_keys_lines",
"(",
"application_name",
",",
"user",
"=",
"None",
")",
"keys",
"=",
"[",
"k",
".",
"strip",
"(",
")",
"for",
"k",
"in",
"keys",
"]",
"if",
"public_key",
"not",
"in",
"keys",
":",
"return",
"[",
"keys",
".",
"remove",
"(",
"key",
")",
"for",
"key",
"in",
"keys",
"if",
"key",
"==",
"public_key",
"]",
"with",
"open",
"(",
"authorized_keys",
"(",
"application_name",
",",
"user",
")",
",",
"'w'",
")",
"as",
"_keys",
":",
"keys",
"=",
"'\\n'",
".",
"join",
"(",
"keys",
")",
"if",
"not",
"keys",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"keys",
"+=",
"'\\n'",
"_keys",
".",
"write",
"(",
"keys",
")"
] | Remove given public key from authorized_keys file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str | [
"Remove",
"given",
"public",
"key",
"from",
"authorized_keys",
"file",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L333-L359 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | apt_cache | def apt_cache(in_memory=True, progress=None):
"""Build and return an apt cache."""
from apt import apt_pkg
apt_pkg.init()
if in_memory:
apt_pkg.config.set("Dir::Cache::pkgcache", "")
apt_pkg.config.set("Dir::Cache::srcpkgcache", "")
return apt_pkg.Cache(progress) | python | def apt_cache(in_memory=True, progress=None):
"""Build and return an apt cache."""
from apt import apt_pkg
apt_pkg.init()
if in_memory:
apt_pkg.config.set("Dir::Cache::pkgcache", "")
apt_pkg.config.set("Dir::Cache::srcpkgcache", "")
return apt_pkg.Cache(progress) | [
"def",
"apt_cache",
"(",
"in_memory",
"=",
"True",
",",
"progress",
"=",
"None",
")",
":",
"from",
"apt",
"import",
"apt_pkg",
"apt_pkg",
".",
"init",
"(",
")",
"if",
"in_memory",
":",
"apt_pkg",
".",
"config",
".",
"set",
"(",
"\"Dir::Cache::pkgcache\"",
",",
"\"\"",
")",
"apt_pkg",
".",
"config",
".",
"set",
"(",
"\"Dir::Cache::srcpkgcache\"",
",",
"\"\"",
")",
"return",
"apt_pkg",
".",
"Cache",
"(",
"progress",
")"
] | Build and return an apt cache. | [
"Build",
"and",
"return",
"an",
"apt",
"cache",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L211-L218 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | apt_mark | def apt_mark(packages, mark, fatal=False):
"""Flag one or more packages using apt-mark."""
log("Marking {} as {}".format(packages, mark))
cmd = ['apt-mark', mark]
if isinstance(packages, six.string_types):
cmd.append(packages)
else:
cmd.extend(packages)
if fatal:
subprocess.check_call(cmd, universal_newlines=True)
else:
subprocess.call(cmd, universal_newlines=True) | python | def apt_mark(packages, mark, fatal=False):
"""Flag one or more packages using apt-mark."""
log("Marking {} as {}".format(packages, mark))
cmd = ['apt-mark', mark]
if isinstance(packages, six.string_types):
cmd.append(packages)
else:
cmd.extend(packages)
if fatal:
subprocess.check_call(cmd, universal_newlines=True)
else:
subprocess.call(cmd, universal_newlines=True) | [
"def",
"apt_mark",
"(",
"packages",
",",
"mark",
",",
"fatal",
"=",
"False",
")",
":",
"log",
"(",
"\"Marking {} as {}\"",
".",
"format",
"(",
"packages",
",",
"mark",
")",
")",
"cmd",
"=",
"[",
"'apt-mark'",
",",
"mark",
"]",
"if",
"isinstance",
"(",
"packages",
",",
"six",
".",
"string_types",
")",
":",
"cmd",
".",
"append",
"(",
"packages",
")",
"else",
":",
"cmd",
".",
"extend",
"(",
"packages",
")",
"if",
"fatal",
":",
"subprocess",
".",
"check_call",
"(",
"cmd",
",",
"universal_newlines",
"=",
"True",
")",
"else",
":",
"subprocess",
".",
"call",
"(",
"cmd",
",",
"universal_newlines",
"=",
"True",
")"
] | Flag one or more packages using apt-mark. | [
"Flag",
"one",
"or",
"more",
"packages",
"using",
"apt",
"-",
"mark",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L278-L290 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | import_key | def import_key(key):
"""Import an ASCII Armor key.
A Radix64 format keyid is also supported for backwards
compatibility. In this case Ubuntu keyserver will be
queried for a key via HTTPS by its keyid. This method
is less preferrable because https proxy servers may
require traffic decryption which is equivalent to a
man-in-the-middle attack (a proxy server impersonates
keyserver TLS certificates and has to be explicitly
trusted by the system).
:param key: A GPG key in ASCII armor format,
including BEGIN and END markers or a keyid.
:type key: (bytes, str)
:raises: GPGKeyError if the key could not be imported
"""
key = key.strip()
if '-' in key or '\n' in key:
# Send everything not obviously a keyid to GPG to import, as
# we trust its validation better than our own. eg. handling
# comments before the key.
log("PGP key found (looks like ASCII Armor format)", level=DEBUG)
if ('-----BEGIN PGP PUBLIC KEY BLOCK-----' in key and
'-----END PGP PUBLIC KEY BLOCK-----' in key):
log("Writing provided PGP key in the binary format", level=DEBUG)
if six.PY3:
key_bytes = key.encode('utf-8')
else:
key_bytes = key
key_name = _get_keyid_by_gpg_key(key_bytes)
key_gpg = _dearmor_gpg_key(key_bytes)
_write_apt_gpg_keyfile(key_name=key_name, key_material=key_gpg)
else:
raise GPGKeyError("ASCII armor markers missing from GPG key")
else:
log("PGP key found (looks like Radix64 format)", level=WARNING)
log("SECURELY importing PGP key from keyserver; "
"full key not provided.", level=WARNING)
# as of bionic add-apt-repository uses curl with an HTTPS keyserver URL
# to retrieve GPG keys. `apt-key adv` command is deprecated as is
# apt-key in general as noted in its manpage. See lp:1433761 for more
# history. Instead, /etc/apt/trusted.gpg.d is used directly to drop
# gpg
key_asc = _get_key_by_keyid(key)
# write the key in GPG format so that apt-key list shows it
key_gpg = _dearmor_gpg_key(key_asc)
_write_apt_gpg_keyfile(key_name=key, key_material=key_gpg) | python | def import_key(key):
"""Import an ASCII Armor key.
A Radix64 format keyid is also supported for backwards
compatibility. In this case Ubuntu keyserver will be
queried for a key via HTTPS by its keyid. This method
is less preferrable because https proxy servers may
require traffic decryption which is equivalent to a
man-in-the-middle attack (a proxy server impersonates
keyserver TLS certificates and has to be explicitly
trusted by the system).
:param key: A GPG key in ASCII armor format,
including BEGIN and END markers or a keyid.
:type key: (bytes, str)
:raises: GPGKeyError if the key could not be imported
"""
key = key.strip()
if '-' in key or '\n' in key:
# Send everything not obviously a keyid to GPG to import, as
# we trust its validation better than our own. eg. handling
# comments before the key.
log("PGP key found (looks like ASCII Armor format)", level=DEBUG)
if ('-----BEGIN PGP PUBLIC KEY BLOCK-----' in key and
'-----END PGP PUBLIC KEY BLOCK-----' in key):
log("Writing provided PGP key in the binary format", level=DEBUG)
if six.PY3:
key_bytes = key.encode('utf-8')
else:
key_bytes = key
key_name = _get_keyid_by_gpg_key(key_bytes)
key_gpg = _dearmor_gpg_key(key_bytes)
_write_apt_gpg_keyfile(key_name=key_name, key_material=key_gpg)
else:
raise GPGKeyError("ASCII armor markers missing from GPG key")
else:
log("PGP key found (looks like Radix64 format)", level=WARNING)
log("SECURELY importing PGP key from keyserver; "
"full key not provided.", level=WARNING)
# as of bionic add-apt-repository uses curl with an HTTPS keyserver URL
# to retrieve GPG keys. `apt-key adv` command is deprecated as is
# apt-key in general as noted in its manpage. See lp:1433761 for more
# history. Instead, /etc/apt/trusted.gpg.d is used directly to drop
# gpg
key_asc = _get_key_by_keyid(key)
# write the key in GPG format so that apt-key list shows it
key_gpg = _dearmor_gpg_key(key_asc)
_write_apt_gpg_keyfile(key_name=key, key_material=key_gpg) | [
"def",
"import_key",
"(",
"key",
")",
":",
"key",
"=",
"key",
".",
"strip",
"(",
")",
"if",
"'-'",
"in",
"key",
"or",
"'\\n'",
"in",
"key",
":",
"# Send everything not obviously a keyid to GPG to import, as",
"# we trust its validation better than our own. eg. handling",
"# comments before the key.",
"log",
"(",
"\"PGP key found (looks like ASCII Armor format)\"",
",",
"level",
"=",
"DEBUG",
")",
"if",
"(",
"'-----BEGIN PGP PUBLIC KEY BLOCK-----'",
"in",
"key",
"and",
"'-----END PGP PUBLIC KEY BLOCK-----'",
"in",
"key",
")",
":",
"log",
"(",
"\"Writing provided PGP key in the binary format\"",
",",
"level",
"=",
"DEBUG",
")",
"if",
"six",
".",
"PY3",
":",
"key_bytes",
"=",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"key_bytes",
"=",
"key",
"key_name",
"=",
"_get_keyid_by_gpg_key",
"(",
"key_bytes",
")",
"key_gpg",
"=",
"_dearmor_gpg_key",
"(",
"key_bytes",
")",
"_write_apt_gpg_keyfile",
"(",
"key_name",
"=",
"key_name",
",",
"key_material",
"=",
"key_gpg",
")",
"else",
":",
"raise",
"GPGKeyError",
"(",
"\"ASCII armor markers missing from GPG key\"",
")",
"else",
":",
"log",
"(",
"\"PGP key found (looks like Radix64 format)\"",
",",
"level",
"=",
"WARNING",
")",
"log",
"(",
"\"SECURELY importing PGP key from keyserver; \"",
"\"full key not provided.\"",
",",
"level",
"=",
"WARNING",
")",
"# as of bionic add-apt-repository uses curl with an HTTPS keyserver URL",
"# to retrieve GPG keys. `apt-key adv` command is deprecated as is",
"# apt-key in general as noted in its manpage. See lp:1433761 for more",
"# history. Instead, /etc/apt/trusted.gpg.d is used directly to drop",
"# gpg",
"key_asc",
"=",
"_get_key_by_keyid",
"(",
"key",
")",
"# write the key in GPG format so that apt-key list shows it",
"key_gpg",
"=",
"_dearmor_gpg_key",
"(",
"key_asc",
")",
"_write_apt_gpg_keyfile",
"(",
"key_name",
"=",
"key",
",",
"key_material",
"=",
"key_gpg",
")"
] | Import an ASCII Armor key.
A Radix64 format keyid is also supported for backwards
compatibility. In this case Ubuntu keyserver will be
queried for a key via HTTPS by its keyid. This method
is less preferrable because https proxy servers may
require traffic decryption which is equivalent to a
man-in-the-middle attack (a proxy server impersonates
keyserver TLS certificates and has to be explicitly
trusted by the system).
:param key: A GPG key in ASCII armor format,
including BEGIN and END markers or a keyid.
:type key: (bytes, str)
:raises: GPGKeyError if the key could not be imported | [
"Import",
"an",
"ASCII",
"Armor",
"key",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L301-L348 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | _dearmor_gpg_key | def _dearmor_gpg_key(key_asc):
"""Converts a GPG key in the ASCII armor format to the binary format.
:param key_asc: A GPG key in ASCII armor format.
:type key_asc: (str, bytes)
:returns: A GPG key in binary format
:rtype: (str, bytes)
:raises: GPGKeyError
"""
ps = subprocess.Popen(['gpg', '--dearmor'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
out, err = ps.communicate(input=key_asc)
# no need to decode output as it is binary (invalid utf-8), only error
if six.PY3:
err = err.decode('utf-8')
if 'gpg: no valid OpenPGP data found.' in err:
raise GPGKeyError('Invalid GPG key material. Check your network setup'
' (MTU, routing, DNS) and/or proxy server settings'
' as well as destination keyserver status.')
else:
return out | python | def _dearmor_gpg_key(key_asc):
"""Converts a GPG key in the ASCII armor format to the binary format.
:param key_asc: A GPG key in ASCII armor format.
:type key_asc: (str, bytes)
:returns: A GPG key in binary format
:rtype: (str, bytes)
:raises: GPGKeyError
"""
ps = subprocess.Popen(['gpg', '--dearmor'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
out, err = ps.communicate(input=key_asc)
# no need to decode output as it is binary (invalid utf-8), only error
if six.PY3:
err = err.decode('utf-8')
if 'gpg: no valid OpenPGP data found.' in err:
raise GPGKeyError('Invalid GPG key material. Check your network setup'
' (MTU, routing, DNS) and/or proxy server settings'
' as well as destination keyserver status.')
else:
return out | [
"def",
"_dearmor_gpg_key",
"(",
"key_asc",
")",
":",
"ps",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'gpg'",
",",
"'--dearmor'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"ps",
".",
"communicate",
"(",
"input",
"=",
"key_asc",
")",
"# no need to decode output as it is binary (invalid utf-8), only error",
"if",
"six",
".",
"PY3",
":",
"err",
"=",
"err",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"'gpg: no valid OpenPGP data found.'",
"in",
"err",
":",
"raise",
"GPGKeyError",
"(",
"'Invalid GPG key material. Check your network setup'",
"' (MTU, routing, DNS) and/or proxy server settings'",
"' as well as destination keyserver status.'",
")",
"else",
":",
"return",
"out"
] | Converts a GPG key in the ASCII armor format to the binary format.
:param key_asc: A GPG key in ASCII armor format.
:type key_asc: (str, bytes)
:returns: A GPG key in binary format
:rtype: (str, bytes)
:raises: GPGKeyError | [
"Converts",
"a",
"GPG",
"key",
"in",
"the",
"ASCII",
"armor",
"format",
"to",
"the",
"binary",
"format",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L415-L437 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | _write_apt_gpg_keyfile | def _write_apt_gpg_keyfile(key_name, key_material):
"""Writes GPG key material into a file at a provided path.
:param key_name: A key name to use for a key file (could be a fingerprint)
:type key_name: str
:param key_material: A GPG key material (binary)
:type key_material: (str, bytes)
"""
with open('/etc/apt/trusted.gpg.d/{}.gpg'.format(key_name),
'wb') as keyf:
keyf.write(key_material) | python | def _write_apt_gpg_keyfile(key_name, key_material):
"""Writes GPG key material into a file at a provided path.
:param key_name: A key name to use for a key file (could be a fingerprint)
:type key_name: str
:param key_material: A GPG key material (binary)
:type key_material: (str, bytes)
"""
with open('/etc/apt/trusted.gpg.d/{}.gpg'.format(key_name),
'wb') as keyf:
keyf.write(key_material) | [
"def",
"_write_apt_gpg_keyfile",
"(",
"key_name",
",",
"key_material",
")",
":",
"with",
"open",
"(",
"'/etc/apt/trusted.gpg.d/{}.gpg'",
".",
"format",
"(",
"key_name",
")",
",",
"'wb'",
")",
"as",
"keyf",
":",
"keyf",
".",
"write",
"(",
"key_material",
")"
] | Writes GPG key material into a file at a provided path.
:param key_name: A key name to use for a key file (could be a fingerprint)
:type key_name: str
:param key_material: A GPG key material (binary)
:type key_material: (str, bytes) | [
"Writes",
"GPG",
"key",
"material",
"into",
"a",
"file",
"at",
"a",
"provided",
"path",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L440-L450 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | _add_apt_repository | def _add_apt_repository(spec):
"""Add the spec using add_apt_repository
:param spec: the parameter to pass to add_apt_repository
:type spec: str
"""
if '{series}' in spec:
series = get_distrib_codename()
spec = spec.replace('{series}', series)
# software-properties package for bionic properly reacts to proxy settings
# passed as environment variables (See lp:1433761). This is not the case
# LTS and non-LTS releases below bionic.
_run_with_retries(['add-apt-repository', '--yes', spec],
cmd_env=env_proxy_settings(['https'])) | python | def _add_apt_repository(spec):
"""Add the spec using add_apt_repository
:param spec: the parameter to pass to add_apt_repository
:type spec: str
"""
if '{series}' in spec:
series = get_distrib_codename()
spec = spec.replace('{series}', series)
# software-properties package for bionic properly reacts to proxy settings
# passed as environment variables (See lp:1433761). This is not the case
# LTS and non-LTS releases below bionic.
_run_with_retries(['add-apt-repository', '--yes', spec],
cmd_env=env_proxy_settings(['https'])) | [
"def",
"_add_apt_repository",
"(",
"spec",
")",
":",
"if",
"'{series}'",
"in",
"spec",
":",
"series",
"=",
"get_distrib_codename",
"(",
")",
"spec",
"=",
"spec",
".",
"replace",
"(",
"'{series}'",
",",
"series",
")",
"# software-properties package for bionic properly reacts to proxy settings",
"# passed as environment variables (See lp:1433761). This is not the case",
"# LTS and non-LTS releases below bionic.",
"_run_with_retries",
"(",
"[",
"'add-apt-repository'",
",",
"'--yes'",
",",
"spec",
"]",
",",
"cmd_env",
"=",
"env_proxy_settings",
"(",
"[",
"'https'",
"]",
")",
")"
] | Add the spec using add_apt_repository
:param spec: the parameter to pass to add_apt_repository
:type spec: str | [
"Add",
"the",
"spec",
"using",
"add_apt_repository"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L560-L573 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | _add_cloud_distro_check | def _add_cloud_distro_check(cloud_archive_release, openstack_release):
"""Add the cloud pocket, but also check the cloud_archive_release against
the current distro, and use the openstack_release as the full lookup.
This just calls _add_cloud_pocket() with the openstack_release as pocket
to get the correct cloud-archive.list for dpkg to work with.
:param cloud_archive_release:String, codename for the distro release.
:param openstack_release: String, spec for the release to look up in the
CLOUD_ARCHIVE_POCKETS
:raises: SourceConfigError if this is the wrong distro, or the pocket spec
doesn't exist.
"""
_verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
_add_cloud_pocket("{}-{}".format(cloud_archive_release, openstack_release)) | python | def _add_cloud_distro_check(cloud_archive_release, openstack_release):
"""Add the cloud pocket, but also check the cloud_archive_release against
the current distro, and use the openstack_release as the full lookup.
This just calls _add_cloud_pocket() with the openstack_release as pocket
to get the correct cloud-archive.list for dpkg to work with.
:param cloud_archive_release:String, codename for the distro release.
:param openstack_release: String, spec for the release to look up in the
CLOUD_ARCHIVE_POCKETS
:raises: SourceConfigError if this is the wrong distro, or the pocket spec
doesn't exist.
"""
_verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
_add_cloud_pocket("{}-{}".format(cloud_archive_release, openstack_release)) | [
"def",
"_add_cloud_distro_check",
"(",
"cloud_archive_release",
",",
"openstack_release",
")",
":",
"_verify_is_ubuntu_rel",
"(",
"cloud_archive_release",
",",
"openstack_release",
")",
"_add_cloud_pocket",
"(",
"\"{}-{}\"",
".",
"format",
"(",
"cloud_archive_release",
",",
"openstack_release",
")",
")"
] | Add the cloud pocket, but also check the cloud_archive_release against
the current distro, and use the openstack_release as the full lookup.
This just calls _add_cloud_pocket() with the openstack_release as pocket
to get the correct cloud-archive.list for dpkg to work with.
:param cloud_archive_release:String, codename for the distro release.
:param openstack_release: String, spec for the release to look up in the
CLOUD_ARCHIVE_POCKETS
:raises: SourceConfigError if this is the wrong distro, or the pocket spec
doesn't exist. | [
"Add",
"the",
"cloud",
"pocket",
"but",
"also",
"check",
"the",
"cloud_archive_release",
"against",
"the",
"current",
"distro",
"and",
"use",
"the",
"openstack_release",
"as",
"the",
"full",
"lookup",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L617-L631 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | _verify_is_ubuntu_rel | def _verify_is_ubuntu_rel(release, os_release):
"""Verify that the release is in the same as the current ubuntu release.
:param release: String, lowercase for the release.
:param os_release: String, the os_release being asked for
:raises: SourceConfigError if the release is not the same as the ubuntu
release.
"""
ubuntu_rel = get_distrib_codename()
if release != ubuntu_rel:
raise SourceConfigError(
'Invalid Cloud Archive release specified: {}-{} on this Ubuntu'
'version ({})'.format(release, os_release, ubuntu_rel)) | python | def _verify_is_ubuntu_rel(release, os_release):
"""Verify that the release is in the same as the current ubuntu release.
:param release: String, lowercase for the release.
:param os_release: String, the os_release being asked for
:raises: SourceConfigError if the release is not the same as the ubuntu
release.
"""
ubuntu_rel = get_distrib_codename()
if release != ubuntu_rel:
raise SourceConfigError(
'Invalid Cloud Archive release specified: {}-{} on this Ubuntu'
'version ({})'.format(release, os_release, ubuntu_rel)) | [
"def",
"_verify_is_ubuntu_rel",
"(",
"release",
",",
"os_release",
")",
":",
"ubuntu_rel",
"=",
"get_distrib_codename",
"(",
")",
"if",
"release",
"!=",
"ubuntu_rel",
":",
"raise",
"SourceConfigError",
"(",
"'Invalid Cloud Archive release specified: {}-{} on this Ubuntu'",
"'version ({})'",
".",
"format",
"(",
"release",
",",
"os_release",
",",
"ubuntu_rel",
")",
")"
] | Verify that the release is in the same as the current ubuntu release.
:param release: String, lowercase for the release.
:param os_release: String, the os_release being asked for
:raises: SourceConfigError if the release is not the same as the ubuntu
release. | [
"Verify",
"that",
"the",
"release",
"is",
"in",
"the",
"same",
"as",
"the",
"current",
"ubuntu",
"release",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L634-L646 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | _run_with_retries | def _run_with_retries(cmd, max_retries=CMD_RETRY_COUNT, retry_exitcodes=(1,),
retry_message="", cmd_env=None):
"""Run a command and retry until success or max_retries is reached.
:param: cmd: str: The apt command to run.
:param: max_retries: int: The number of retries to attempt on a fatal
command. Defaults to CMD_RETRY_COUNT.
:param: retry_exitcodes: tuple: Optional additional exit codes to retry.
Defaults to retry on exit code 1.
:param: retry_message: str: Optional log prefix emitted during retries.
:param: cmd_env: dict: Environment variables to add to the command run.
"""
env = None
kwargs = {}
if cmd_env:
env = os.environ.copy()
env.update(cmd_env)
kwargs['env'] = env
if not retry_message:
retry_message = "Failed executing '{}'".format(" ".join(cmd))
retry_message += ". Will retry in {} seconds".format(CMD_RETRY_DELAY)
retry_count = 0
result = None
retry_results = (None,) + retry_exitcodes
while result in retry_results:
try:
# result = subprocess.check_call(cmd, env=env)
result = subprocess.check_call(cmd, **kwargs)
except subprocess.CalledProcessError as e:
retry_count = retry_count + 1
if retry_count > max_retries:
raise
result = e.returncode
log(retry_message)
time.sleep(CMD_RETRY_DELAY) | python | def _run_with_retries(cmd, max_retries=CMD_RETRY_COUNT, retry_exitcodes=(1,),
retry_message="", cmd_env=None):
"""Run a command and retry until success or max_retries is reached.
:param: cmd: str: The apt command to run.
:param: max_retries: int: The number of retries to attempt on a fatal
command. Defaults to CMD_RETRY_COUNT.
:param: retry_exitcodes: tuple: Optional additional exit codes to retry.
Defaults to retry on exit code 1.
:param: retry_message: str: Optional log prefix emitted during retries.
:param: cmd_env: dict: Environment variables to add to the command run.
"""
env = None
kwargs = {}
if cmd_env:
env = os.environ.copy()
env.update(cmd_env)
kwargs['env'] = env
if not retry_message:
retry_message = "Failed executing '{}'".format(" ".join(cmd))
retry_message += ". Will retry in {} seconds".format(CMD_RETRY_DELAY)
retry_count = 0
result = None
retry_results = (None,) + retry_exitcodes
while result in retry_results:
try:
# result = subprocess.check_call(cmd, env=env)
result = subprocess.check_call(cmd, **kwargs)
except subprocess.CalledProcessError as e:
retry_count = retry_count + 1
if retry_count > max_retries:
raise
result = e.returncode
log(retry_message)
time.sleep(CMD_RETRY_DELAY) | [
"def",
"_run_with_retries",
"(",
"cmd",
",",
"max_retries",
"=",
"CMD_RETRY_COUNT",
",",
"retry_exitcodes",
"=",
"(",
"1",
",",
")",
",",
"retry_message",
"=",
"\"\"",
",",
"cmd_env",
"=",
"None",
")",
":",
"env",
"=",
"None",
"kwargs",
"=",
"{",
"}",
"if",
"cmd_env",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"cmd_env",
")",
"kwargs",
"[",
"'env'",
"]",
"=",
"env",
"if",
"not",
"retry_message",
":",
"retry_message",
"=",
"\"Failed executing '{}'\"",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"cmd",
")",
")",
"retry_message",
"+=",
"\". Will retry in {} seconds\"",
".",
"format",
"(",
"CMD_RETRY_DELAY",
")",
"retry_count",
"=",
"0",
"result",
"=",
"None",
"retry_results",
"=",
"(",
"None",
",",
")",
"+",
"retry_exitcodes",
"while",
"result",
"in",
"retry_results",
":",
"try",
":",
"# result = subprocess.check_call(cmd, env=env)",
"result",
"=",
"subprocess",
".",
"check_call",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"retry_count",
"=",
"retry_count",
"+",
"1",
"if",
"retry_count",
">",
"max_retries",
":",
"raise",
"result",
"=",
"e",
".",
"returncode",
"log",
"(",
"retry_message",
")",
"time",
".",
"sleep",
"(",
"CMD_RETRY_DELAY",
")"
] | Run a command and retry until success or max_retries is reached.
:param: cmd: str: The apt command to run.
:param: max_retries: int: The number of retries to attempt on a fatal
command. Defaults to CMD_RETRY_COUNT.
:param: retry_exitcodes: tuple: Optional additional exit codes to retry.
Defaults to retry on exit code 1.
:param: retry_message: str: Optional log prefix emitted during retries.
:param: cmd_env: dict: Environment variables to add to the command run. | [
"Run",
"a",
"command",
"and",
"retry",
"until",
"success",
"or",
"max_retries",
"is",
"reached",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L649-L687 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | _run_apt_command | def _run_apt_command(cmd, fatal=False):
"""Run an apt command with optional retries.
:param: cmd: str: The apt command to run.
:param: fatal: bool: Whether the command's output should be checked and
retried.
"""
# Provide DEBIAN_FRONTEND=noninteractive if not present in the environment.
cmd_env = {
'DEBIAN_FRONTEND': os.environ.get('DEBIAN_FRONTEND', 'noninteractive')}
if fatal:
_run_with_retries(
cmd, cmd_env=cmd_env, retry_exitcodes=(1, APT_NO_LOCK,),
retry_message="Couldn't acquire DPKG lock")
else:
env = os.environ.copy()
env.update(cmd_env)
subprocess.call(cmd, env=env) | python | def _run_apt_command(cmd, fatal=False):
"""Run an apt command with optional retries.
:param: cmd: str: The apt command to run.
:param: fatal: bool: Whether the command's output should be checked and
retried.
"""
# Provide DEBIAN_FRONTEND=noninteractive if not present in the environment.
cmd_env = {
'DEBIAN_FRONTEND': os.environ.get('DEBIAN_FRONTEND', 'noninteractive')}
if fatal:
_run_with_retries(
cmd, cmd_env=cmd_env, retry_exitcodes=(1, APT_NO_LOCK,),
retry_message="Couldn't acquire DPKG lock")
else:
env = os.environ.copy()
env.update(cmd_env)
subprocess.call(cmd, env=env) | [
"def",
"_run_apt_command",
"(",
"cmd",
",",
"fatal",
"=",
"False",
")",
":",
"# Provide DEBIAN_FRONTEND=noninteractive if not present in the environment.",
"cmd_env",
"=",
"{",
"'DEBIAN_FRONTEND'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'DEBIAN_FRONTEND'",
",",
"'noninteractive'",
")",
"}",
"if",
"fatal",
":",
"_run_with_retries",
"(",
"cmd",
",",
"cmd_env",
"=",
"cmd_env",
",",
"retry_exitcodes",
"=",
"(",
"1",
",",
"APT_NO_LOCK",
",",
")",
",",
"retry_message",
"=",
"\"Couldn't acquire DPKG lock\"",
")",
"else",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"cmd_env",
")",
"subprocess",
".",
"call",
"(",
"cmd",
",",
"env",
"=",
"env",
")"
] | Run an apt command with optional retries.
:param: cmd: str: The apt command to run.
:param: fatal: bool: Whether the command's output should be checked and
retried. | [
"Run",
"an",
"apt",
"command",
"with",
"optional",
"retries",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L690-L708 | train |
juju/charm-helpers | charmhelpers/fetch/ubuntu.py | get_upstream_version | def get_upstream_version(package):
"""Determine upstream version based on installed package
@returns None (if not installed) or the upstream version
"""
import apt_pkg
cache = apt_cache()
try:
pkg = cache[package]
except Exception:
# the package is unknown to the current apt cache.
return None
if not pkg.current_ver:
# package is known, but no version is currently installed.
return None
return apt_pkg.upstream_version(pkg.current_ver.ver_str) | python | def get_upstream_version(package):
"""Determine upstream version based on installed package
@returns None (if not installed) or the upstream version
"""
import apt_pkg
cache = apt_cache()
try:
pkg = cache[package]
except Exception:
# the package is unknown to the current apt cache.
return None
if not pkg.current_ver:
# package is known, but no version is currently installed.
return None
return apt_pkg.upstream_version(pkg.current_ver.ver_str) | [
"def",
"get_upstream_version",
"(",
"package",
")",
":",
"import",
"apt_pkg",
"cache",
"=",
"apt_cache",
"(",
")",
"try",
":",
"pkg",
"=",
"cache",
"[",
"package",
"]",
"except",
"Exception",
":",
"# the package is unknown to the current apt cache.",
"return",
"None",
"if",
"not",
"pkg",
".",
"current_ver",
":",
"# package is known, but no version is currently installed.",
"return",
"None",
"return",
"apt_pkg",
".",
"upstream_version",
"(",
"pkg",
".",
"current_ver",
".",
"ver_str",
")"
] | Determine upstream version based on installed package
@returns None (if not installed) or the upstream version | [
"Determine",
"upstream",
"version",
"based",
"on",
"installed",
"package"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L711-L728 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/bcache.py | get_bcache_fs | def get_bcache_fs():
"""Return all cache sets
"""
cachesetroot = "{}/fs/bcache".format(SYSFS)
try:
dirs = os.listdir(cachesetroot)
except OSError:
log("No bcache fs found")
return []
cacheset = set([Bcache('{}/{}'.format(cachesetroot, d)) for d in dirs if not d.startswith('register')])
return cacheset | python | def get_bcache_fs():
"""Return all cache sets
"""
cachesetroot = "{}/fs/bcache".format(SYSFS)
try:
dirs = os.listdir(cachesetroot)
except OSError:
log("No bcache fs found")
return []
cacheset = set([Bcache('{}/{}'.format(cachesetroot, d)) for d in dirs if not d.startswith('register')])
return cacheset | [
"def",
"get_bcache_fs",
"(",
")",
":",
"cachesetroot",
"=",
"\"{}/fs/bcache\"",
".",
"format",
"(",
"SYSFS",
")",
"try",
":",
"dirs",
"=",
"os",
".",
"listdir",
"(",
"cachesetroot",
")",
"except",
"OSError",
":",
"log",
"(",
"\"No bcache fs found\"",
")",
"return",
"[",
"]",
"cacheset",
"=",
"set",
"(",
"[",
"Bcache",
"(",
"'{}/{}'",
".",
"format",
"(",
"cachesetroot",
",",
"d",
")",
")",
"for",
"d",
"in",
"dirs",
"if",
"not",
"d",
".",
"startswith",
"(",
"'register'",
")",
"]",
")",
"return",
"cacheset"
] | Return all cache sets | [
"Return",
"all",
"cache",
"sets"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/bcache.py#L50-L60 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/bcache.py | get_stats_action | def get_stats_action(cachespec, interval):
"""Action for getting bcache statistics for a given cachespec.
Cachespec can either be a device name, eg. 'sdb', which will retrieve
cache stats for the given device, or 'global', which will retrieve stats
for all cachesets
"""
if cachespec == 'global':
caches = get_bcache_fs()
else:
caches = [Bcache.fromdevice(cachespec)]
res = dict((c.cachepath, c.get_stats(interval)) for c in caches)
return json.dumps(res, indent=4, separators=(',', ': ')) | python | def get_stats_action(cachespec, interval):
"""Action for getting bcache statistics for a given cachespec.
Cachespec can either be a device name, eg. 'sdb', which will retrieve
cache stats for the given device, or 'global', which will retrieve stats
for all cachesets
"""
if cachespec == 'global':
caches = get_bcache_fs()
else:
caches = [Bcache.fromdevice(cachespec)]
res = dict((c.cachepath, c.get_stats(interval)) for c in caches)
return json.dumps(res, indent=4, separators=(',', ': ')) | [
"def",
"get_stats_action",
"(",
"cachespec",
",",
"interval",
")",
":",
"if",
"cachespec",
"==",
"'global'",
":",
"caches",
"=",
"get_bcache_fs",
"(",
")",
"else",
":",
"caches",
"=",
"[",
"Bcache",
".",
"fromdevice",
"(",
"cachespec",
")",
"]",
"res",
"=",
"dict",
"(",
"(",
"c",
".",
"cachepath",
",",
"c",
".",
"get_stats",
"(",
"interval",
")",
")",
"for",
"c",
"in",
"caches",
")",
"return",
"json",
".",
"dumps",
"(",
"res",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")"
] | Action for getting bcache statistics for a given cachespec.
Cachespec can either be a device name, eg. 'sdb', which will retrieve
cache stats for the given device, or 'global', which will retrieve stats
for all cachesets | [
"Action",
"for",
"getting",
"bcache",
"statistics",
"for",
"a",
"given",
"cachespec",
".",
"Cachespec",
"can",
"either",
"be",
"a",
"device",
"name",
"eg",
".",
"sdb",
"which",
"will",
"retrieve",
"cache",
"stats",
"for",
"the",
"given",
"device",
"or",
"global",
"which",
"will",
"retrieve",
"stats",
"for",
"all",
"cachesets"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/bcache.py#L63-L74 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/bcache.py | Bcache.get_stats | def get_stats(self, interval):
"""Get cache stats
"""
intervaldir = 'stats_{}'.format(interval)
path = "{}/{}".format(self.cachepath, intervaldir)
out = dict()
for elem in os.listdir(path):
out[elem] = open('{}/{}'.format(path, elem)).read().strip()
return out | python | def get_stats(self, interval):
"""Get cache stats
"""
intervaldir = 'stats_{}'.format(interval)
path = "{}/{}".format(self.cachepath, intervaldir)
out = dict()
for elem in os.listdir(path):
out[elem] = open('{}/{}'.format(path, elem)).read().strip()
return out | [
"def",
"get_stats",
"(",
"self",
",",
"interval",
")",
":",
"intervaldir",
"=",
"'stats_{}'",
".",
"format",
"(",
"interval",
")",
"path",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"self",
".",
"cachepath",
",",
"intervaldir",
")",
"out",
"=",
"dict",
"(",
")",
"for",
"elem",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"out",
"[",
"elem",
"]",
"=",
"open",
"(",
"'{}/{}'",
".",
"format",
"(",
"path",
",",
"elem",
")",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"return",
"out"
] | Get cache stats | [
"Get",
"cache",
"stats"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/bcache.py#L39-L47 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ha/utils.py | update_dns_ha_resource_params | def update_dns_ha_resource_params(resources, resource_params,
relation_id=None,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration and
update resource dictionaries for the HA relation.
@param resources: Pointer to dictionary of resources.
Usually instantiated in ha_joined().
@param resource_params: Pointer to dictionary of resource parameters.
Usually instantiated in ha_joined()
@param relation_id: Relation ID of the ha relation
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
_relation_data = {'resources': {}, 'resource_params': {}}
update_hacluster_dns_ha(charm_name(),
_relation_data,
crm_ocf)
resources.update(_relation_data['resources'])
resource_params.update(_relation_data['resource_params'])
relation_set(relation_id=relation_id, groups=_relation_data['groups']) | python | def update_dns_ha_resource_params(resources, resource_params,
relation_id=None,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration and
update resource dictionaries for the HA relation.
@param resources: Pointer to dictionary of resources.
Usually instantiated in ha_joined().
@param resource_params: Pointer to dictionary of resource parameters.
Usually instantiated in ha_joined()
@param relation_id: Relation ID of the ha relation
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
_relation_data = {'resources': {}, 'resource_params': {}}
update_hacluster_dns_ha(charm_name(),
_relation_data,
crm_ocf)
resources.update(_relation_data['resources'])
resource_params.update(_relation_data['resource_params'])
relation_set(relation_id=relation_id, groups=_relation_data['groups']) | [
"def",
"update_dns_ha_resource_params",
"(",
"resources",
",",
"resource_params",
",",
"relation_id",
"=",
"None",
",",
"crm_ocf",
"=",
"'ocf:maas:dns'",
")",
":",
"_relation_data",
"=",
"{",
"'resources'",
":",
"{",
"}",
",",
"'resource_params'",
":",
"{",
"}",
"}",
"update_hacluster_dns_ha",
"(",
"charm_name",
"(",
")",
",",
"_relation_data",
",",
"crm_ocf",
")",
"resources",
".",
"update",
"(",
"_relation_data",
"[",
"'resources'",
"]",
")",
"resource_params",
".",
"update",
"(",
"_relation_data",
"[",
"'resource_params'",
"]",
")",
"relation_set",
"(",
"relation_id",
"=",
"relation_id",
",",
"groups",
"=",
"_relation_data",
"[",
"'groups'",
"]",
")"
] | Configure DNS-HA resources based on provided configuration and
update resource dictionaries for the HA relation.
@param resources: Pointer to dictionary of resources.
Usually instantiated in ha_joined().
@param resource_params: Pointer to dictionary of resource parameters.
Usually instantiated in ha_joined()
@param relation_id: Relation ID of the ha relation
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA | [
"Configure",
"DNS",
"-",
"HA",
"resources",
"based",
"on",
"provided",
"configuration",
"and",
"update",
"resource",
"dictionaries",
"for",
"the",
"HA",
"relation",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L77-L97 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ha/utils.py | expect_ha | def expect_ha():
""" Determine if the unit expects to be in HA
Check juju goal-state if ha relation is expected, check for VIP or dns-ha
settings which indicate the unit should expect to be related to hacluster.
@returns boolean
"""
ha_related_units = []
try:
ha_related_units = list(expected_related_units(reltype='ha'))
except (NotImplementedError, KeyError):
pass
return len(ha_related_units) > 0 or config('vip') or config('dns-ha') | python | def expect_ha():
""" Determine if the unit expects to be in HA
Check juju goal-state if ha relation is expected, check for VIP or dns-ha
settings which indicate the unit should expect to be related to hacluster.
@returns boolean
"""
ha_related_units = []
try:
ha_related_units = list(expected_related_units(reltype='ha'))
except (NotImplementedError, KeyError):
pass
return len(ha_related_units) > 0 or config('vip') or config('dns-ha') | [
"def",
"expect_ha",
"(",
")",
":",
"ha_related_units",
"=",
"[",
"]",
"try",
":",
"ha_related_units",
"=",
"list",
"(",
"expected_related_units",
"(",
"reltype",
"=",
"'ha'",
")",
")",
"except",
"(",
"NotImplementedError",
",",
"KeyError",
")",
":",
"pass",
"return",
"len",
"(",
"ha_related_units",
")",
">",
"0",
"or",
"config",
"(",
"'vip'",
")",
"or",
"config",
"(",
"'dns-ha'",
")"
] | Determine if the unit expects to be in HA
Check juju goal-state if ha relation is expected, check for VIP or dns-ha
settings which indicate the unit should expect to be related to hacluster.
@returns boolean | [
"Determine",
"if",
"the",
"unit",
"expects",
"to",
"be",
"in",
"HA"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L114-L127 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ha/utils.py | generate_ha_relation_data | def generate_ha_relation_data(service, extra_settings=None):
""" Generate relation data for ha relation
Based on configuration options and unit interfaces, generate a json
encoded dict of relation data items for the hacluster relation,
providing configuration for DNS HA or VIP's + haproxy clone sets.
Example of supplying additional settings::
COLO_CONSOLEAUTH = 'inf: res_nova_consoleauth grp_nova_vips'
AGENT_CONSOLEAUTH = 'ocf:openstack:nova-consoleauth'
AGENT_CA_PARAMS = 'op monitor interval="5s"'
ha_console_settings = {
'colocations': {'vip_consoleauth': COLO_CONSOLEAUTH},
'init_services': {'res_nova_consoleauth': 'nova-consoleauth'},
'resources': {'res_nova_consoleauth': AGENT_CONSOLEAUTH},
'resource_params': {'res_nova_consoleauth': AGENT_CA_PARAMS})
generate_ha_relation_data('nova', extra_settings=ha_console_settings)
@param service: Name of the service being configured
@param extra_settings: Dict of additional resource data
@returns dict: json encoded data for use with relation_set
"""
_haproxy_res = 'res_{}_haproxy'.format(service)
_relation_data = {
'resources': {
_haproxy_res: 'lsb:haproxy',
},
'resource_params': {
_haproxy_res: 'op monitor interval="5s"'
},
'init_services': {
_haproxy_res: 'haproxy'
},
'clones': {
'cl_{}_haproxy'.format(service): _haproxy_res
},
}
if extra_settings:
for k, v in extra_settings.items():
if _relation_data.get(k):
_relation_data[k].update(v)
else:
_relation_data[k] = v
if config('dns-ha'):
update_hacluster_dns_ha(service, _relation_data)
else:
update_hacluster_vip(service, _relation_data)
return {
'json_{}'.format(k): json.dumps(v, **JSON_ENCODE_OPTIONS)
for k, v in _relation_data.items() if v
} | python | def generate_ha_relation_data(service, extra_settings=None):
""" Generate relation data for ha relation
Based on configuration options and unit interfaces, generate a json
encoded dict of relation data items for the hacluster relation,
providing configuration for DNS HA or VIP's + haproxy clone sets.
Example of supplying additional settings::
COLO_CONSOLEAUTH = 'inf: res_nova_consoleauth grp_nova_vips'
AGENT_CONSOLEAUTH = 'ocf:openstack:nova-consoleauth'
AGENT_CA_PARAMS = 'op monitor interval="5s"'
ha_console_settings = {
'colocations': {'vip_consoleauth': COLO_CONSOLEAUTH},
'init_services': {'res_nova_consoleauth': 'nova-consoleauth'},
'resources': {'res_nova_consoleauth': AGENT_CONSOLEAUTH},
'resource_params': {'res_nova_consoleauth': AGENT_CA_PARAMS})
generate_ha_relation_data('nova', extra_settings=ha_console_settings)
@param service: Name of the service being configured
@param extra_settings: Dict of additional resource data
@returns dict: json encoded data for use with relation_set
"""
_haproxy_res = 'res_{}_haproxy'.format(service)
_relation_data = {
'resources': {
_haproxy_res: 'lsb:haproxy',
},
'resource_params': {
_haproxy_res: 'op monitor interval="5s"'
},
'init_services': {
_haproxy_res: 'haproxy'
},
'clones': {
'cl_{}_haproxy'.format(service): _haproxy_res
},
}
if extra_settings:
for k, v in extra_settings.items():
if _relation_data.get(k):
_relation_data[k].update(v)
else:
_relation_data[k] = v
if config('dns-ha'):
update_hacluster_dns_ha(service, _relation_data)
else:
update_hacluster_vip(service, _relation_data)
return {
'json_{}'.format(k): json.dumps(v, **JSON_ENCODE_OPTIONS)
for k, v in _relation_data.items() if v
} | [
"def",
"generate_ha_relation_data",
"(",
"service",
",",
"extra_settings",
"=",
"None",
")",
":",
"_haproxy_res",
"=",
"'res_{}_haproxy'",
".",
"format",
"(",
"service",
")",
"_relation_data",
"=",
"{",
"'resources'",
":",
"{",
"_haproxy_res",
":",
"'lsb:haproxy'",
",",
"}",
",",
"'resource_params'",
":",
"{",
"_haproxy_res",
":",
"'op monitor interval=\"5s\"'",
"}",
",",
"'init_services'",
":",
"{",
"_haproxy_res",
":",
"'haproxy'",
"}",
",",
"'clones'",
":",
"{",
"'cl_{}_haproxy'",
".",
"format",
"(",
"service",
")",
":",
"_haproxy_res",
"}",
",",
"}",
"if",
"extra_settings",
":",
"for",
"k",
",",
"v",
"in",
"extra_settings",
".",
"items",
"(",
")",
":",
"if",
"_relation_data",
".",
"get",
"(",
"k",
")",
":",
"_relation_data",
"[",
"k",
"]",
".",
"update",
"(",
"v",
")",
"else",
":",
"_relation_data",
"[",
"k",
"]",
"=",
"v",
"if",
"config",
"(",
"'dns-ha'",
")",
":",
"update_hacluster_dns_ha",
"(",
"service",
",",
"_relation_data",
")",
"else",
":",
"update_hacluster_vip",
"(",
"service",
",",
"_relation_data",
")",
"return",
"{",
"'json_{}'",
".",
"format",
"(",
"k",
")",
":",
"json",
".",
"dumps",
"(",
"v",
",",
"*",
"*",
"JSON_ENCODE_OPTIONS",
")",
"for",
"k",
",",
"v",
"in",
"_relation_data",
".",
"items",
"(",
")",
"if",
"v",
"}"
] | Generate relation data for ha relation
Based on configuration options and unit interfaces, generate a json
encoded dict of relation data items for the hacluster relation,
providing configuration for DNS HA or VIP's + haproxy clone sets.
Example of supplying additional settings::
COLO_CONSOLEAUTH = 'inf: res_nova_consoleauth grp_nova_vips'
AGENT_CONSOLEAUTH = 'ocf:openstack:nova-consoleauth'
AGENT_CA_PARAMS = 'op monitor interval="5s"'
ha_console_settings = {
'colocations': {'vip_consoleauth': COLO_CONSOLEAUTH},
'init_services': {'res_nova_consoleauth': 'nova-consoleauth'},
'resources': {'res_nova_consoleauth': AGENT_CONSOLEAUTH},
'resource_params': {'res_nova_consoleauth': AGENT_CA_PARAMS})
generate_ha_relation_data('nova', extra_settings=ha_console_settings)
@param service: Name of the service being configured
@param extra_settings: Dict of additional resource data
@returns dict: json encoded data for use with relation_set | [
"Generate",
"relation",
"data",
"for",
"ha",
"relation"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L130-L186 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ha/utils.py | update_hacluster_dns_ha | def update_hacluster_dns_ha(service, relation_data,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
# Validate the charm environment for DNS HA
assert_charm_supports_dns_ha()
settings = ['os-admin-hostname', 'os-internal-hostname',
'os-public-hostname', 'os-access-hostname']
# Check which DNS settings are set and update dictionaries
hostname_group = []
for setting in settings:
hostname = config(setting)
if hostname is None:
log('DNS HA: Hostname setting {} is None. Ignoring.'
''.format(setting),
DEBUG)
continue
m = re.search('os-(.+?)-hostname', setting)
if m:
endpoint_type = m.group(1)
# resolve_address's ADDRESS_MAP uses 'int' not 'internal'
if endpoint_type == 'internal':
endpoint_type = 'int'
else:
msg = ('Unexpected DNS hostname setting: {}. '
'Cannot determine endpoint_type name'
''.format(setting))
status_set('blocked', msg)
raise DNSHAException(msg)
hostname_key = 'res_{}_{}_hostname'.format(service, endpoint_type)
if hostname_key in hostname_group:
log('DNS HA: Resource {}: {} already exists in '
'hostname group - skipping'.format(hostname_key, hostname),
DEBUG)
continue
hostname_group.append(hostname_key)
relation_data['resources'][hostname_key] = crm_ocf
relation_data['resource_params'][hostname_key] = (
'params fqdn="{}" ip_address="{}"'
.format(hostname, resolve_address(endpoint_type=endpoint_type,
override=False)))
if len(hostname_group) >= 1:
log('DNS HA: Hostname group is set with {} as members. '
'Informing the ha relation'.format(' '.join(hostname_group)),
DEBUG)
relation_data['groups'] = {
DNSHA_GROUP_NAME.format(service=service): ' '.join(hostname_group)
}
else:
msg = 'DNS HA: Hostname group has no members.'
status_set('blocked', msg)
raise DNSHAException(msg) | python | def update_hacluster_dns_ha(service, relation_data,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
# Validate the charm environment for DNS HA
assert_charm_supports_dns_ha()
settings = ['os-admin-hostname', 'os-internal-hostname',
'os-public-hostname', 'os-access-hostname']
# Check which DNS settings are set and update dictionaries
hostname_group = []
for setting in settings:
hostname = config(setting)
if hostname is None:
log('DNS HA: Hostname setting {} is None. Ignoring.'
''.format(setting),
DEBUG)
continue
m = re.search('os-(.+?)-hostname', setting)
if m:
endpoint_type = m.group(1)
# resolve_address's ADDRESS_MAP uses 'int' not 'internal'
if endpoint_type == 'internal':
endpoint_type = 'int'
else:
msg = ('Unexpected DNS hostname setting: {}. '
'Cannot determine endpoint_type name'
''.format(setting))
status_set('blocked', msg)
raise DNSHAException(msg)
hostname_key = 'res_{}_{}_hostname'.format(service, endpoint_type)
if hostname_key in hostname_group:
log('DNS HA: Resource {}: {} already exists in '
'hostname group - skipping'.format(hostname_key, hostname),
DEBUG)
continue
hostname_group.append(hostname_key)
relation_data['resources'][hostname_key] = crm_ocf
relation_data['resource_params'][hostname_key] = (
'params fqdn="{}" ip_address="{}"'
.format(hostname, resolve_address(endpoint_type=endpoint_type,
override=False)))
if len(hostname_group) >= 1:
log('DNS HA: Hostname group is set with {} as members. '
'Informing the ha relation'.format(' '.join(hostname_group)),
DEBUG)
relation_data['groups'] = {
DNSHA_GROUP_NAME.format(service=service): ' '.join(hostname_group)
}
else:
msg = 'DNS HA: Hostname group has no members.'
status_set('blocked', msg)
raise DNSHAException(msg) | [
"def",
"update_hacluster_dns_ha",
"(",
"service",
",",
"relation_data",
",",
"crm_ocf",
"=",
"'ocf:maas:dns'",
")",
":",
"# Validate the charm environment for DNS HA",
"assert_charm_supports_dns_ha",
"(",
")",
"settings",
"=",
"[",
"'os-admin-hostname'",
",",
"'os-internal-hostname'",
",",
"'os-public-hostname'",
",",
"'os-access-hostname'",
"]",
"# Check which DNS settings are set and update dictionaries",
"hostname_group",
"=",
"[",
"]",
"for",
"setting",
"in",
"settings",
":",
"hostname",
"=",
"config",
"(",
"setting",
")",
"if",
"hostname",
"is",
"None",
":",
"log",
"(",
"'DNS HA: Hostname setting {} is None. Ignoring.'",
"''",
".",
"format",
"(",
"setting",
")",
",",
"DEBUG",
")",
"continue",
"m",
"=",
"re",
".",
"search",
"(",
"'os-(.+?)-hostname'",
",",
"setting",
")",
"if",
"m",
":",
"endpoint_type",
"=",
"m",
".",
"group",
"(",
"1",
")",
"# resolve_address's ADDRESS_MAP uses 'int' not 'internal'",
"if",
"endpoint_type",
"==",
"'internal'",
":",
"endpoint_type",
"=",
"'int'",
"else",
":",
"msg",
"=",
"(",
"'Unexpected DNS hostname setting: {}. '",
"'Cannot determine endpoint_type name'",
"''",
".",
"format",
"(",
"setting",
")",
")",
"status_set",
"(",
"'blocked'",
",",
"msg",
")",
"raise",
"DNSHAException",
"(",
"msg",
")",
"hostname_key",
"=",
"'res_{}_{}_hostname'",
".",
"format",
"(",
"service",
",",
"endpoint_type",
")",
"if",
"hostname_key",
"in",
"hostname_group",
":",
"log",
"(",
"'DNS HA: Resource {}: {} already exists in '",
"'hostname group - skipping'",
".",
"format",
"(",
"hostname_key",
",",
"hostname",
")",
",",
"DEBUG",
")",
"continue",
"hostname_group",
".",
"append",
"(",
"hostname_key",
")",
"relation_data",
"[",
"'resources'",
"]",
"[",
"hostname_key",
"]",
"=",
"crm_ocf",
"relation_data",
"[",
"'resource_params'",
"]",
"[",
"hostname_key",
"]",
"=",
"(",
"'params fqdn=\"{}\" ip_address=\"{}\"'",
".",
"format",
"(",
"hostname",
",",
"resolve_address",
"(",
"endpoint_type",
"=",
"endpoint_type",
",",
"override",
"=",
"False",
")",
")",
")",
"if",
"len",
"(",
"hostname_group",
")",
">=",
"1",
":",
"log",
"(",
"'DNS HA: Hostname group is set with {} as members. '",
"'Informing the ha relation'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"hostname_group",
")",
")",
",",
"DEBUG",
")",
"relation_data",
"[",
"'groups'",
"]",
"=",
"{",
"DNSHA_GROUP_NAME",
".",
"format",
"(",
"service",
"=",
"service",
")",
":",
"' '",
".",
"join",
"(",
"hostname_group",
")",
"}",
"else",
":",
"msg",
"=",
"'DNS HA: Hostname group has no members.'",
"status_set",
"(",
"'blocked'",
",",
"msg",
")",
"raise",
"DNSHAException",
"(",
"msg",
")"
] | Configure DNS-HA resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA | [
"Configure",
"DNS",
"-",
"HA",
"resources",
"based",
"on",
"provided",
"configuration"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L189-L250 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ha/utils.py | get_vip_settings | def get_vip_settings(vip):
"""Calculate which nic is on the correct network for the given vip.
If nic or netmask discovery fail then fallback to using charm supplied
config. If fallback is used this is indicated via the fallback variable.
@param vip: VIP to lookup nic and cidr for.
@returns (str, str, bool): eg (iface, netmask, fallback)
"""
iface = get_iface_for_address(vip)
netmask = get_netmask_for_address(vip)
fallback = False
if iface is None:
iface = config('vip_iface')
fallback = True
if netmask is None:
netmask = config('vip_cidr')
fallback = True
return iface, netmask, fallback | python | def get_vip_settings(vip):
"""Calculate which nic is on the correct network for the given vip.
If nic or netmask discovery fail then fallback to using charm supplied
config. If fallback is used this is indicated via the fallback variable.
@param vip: VIP to lookup nic and cidr for.
@returns (str, str, bool): eg (iface, netmask, fallback)
"""
iface = get_iface_for_address(vip)
netmask = get_netmask_for_address(vip)
fallback = False
if iface is None:
iface = config('vip_iface')
fallback = True
if netmask is None:
netmask = config('vip_cidr')
fallback = True
return iface, netmask, fallback | [
"def",
"get_vip_settings",
"(",
"vip",
")",
":",
"iface",
"=",
"get_iface_for_address",
"(",
"vip",
")",
"netmask",
"=",
"get_netmask_for_address",
"(",
"vip",
")",
"fallback",
"=",
"False",
"if",
"iface",
"is",
"None",
":",
"iface",
"=",
"config",
"(",
"'vip_iface'",
")",
"fallback",
"=",
"True",
"if",
"netmask",
"is",
"None",
":",
"netmask",
"=",
"config",
"(",
"'vip_cidr'",
")",
"fallback",
"=",
"True",
"return",
"iface",
",",
"netmask",
",",
"fallback"
] | Calculate which nic is on the correct network for the given vip.
If nic or netmask discovery fail then fallback to using charm supplied
config. If fallback is used this is indicated via the fallback variable.
@param vip: VIP to lookup nic and cidr for.
@returns (str, str, bool): eg (iface, netmask, fallback) | [
"Calculate",
"which",
"nic",
"is",
"on",
"the",
"correct",
"network",
"for",
"the",
"given",
"vip",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L253-L271 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/ha/utils.py | update_hacluster_vip | def update_hacluster_vip(service, relation_data):
""" Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
"""
cluster_config = get_hacluster_config()
vip_group = []
vips_to_delete = []
for vip in cluster_config['vip'].split():
if is_ipv6(vip):
res_vip = 'ocf:heartbeat:IPv6addr'
vip_params = 'ipv6addr'
else:
res_vip = 'ocf:heartbeat:IPaddr2'
vip_params = 'ip'
iface, netmask, fallback = get_vip_settings(vip)
vip_monitoring = 'op monitor depth="0" timeout="20s" interval="10s"'
if iface is not None:
# NOTE(jamespage): Delete old VIP resources
# Old style naming encoding iface in name
# does not work well in environments where
# interface/subnet wiring is not consistent
vip_key = 'res_{}_{}_vip'.format(service, iface)
if vip_key in vips_to_delete:
vip_key = '{}_{}'.format(vip_key, vip_params)
vips_to_delete.append(vip_key)
vip_key = 'res_{}_{}_vip'.format(
service,
hashlib.sha1(vip.encode('UTF-8')).hexdigest()[:7])
relation_data['resources'][vip_key] = res_vip
# NOTE(jamespage):
# Use option provided vip params if these where used
# instead of auto-detected values
if fallback:
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" cidr_netmask="{netmask}" '
'nic="{iface}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
iface=iface,
netmask=netmask,
vip_monitoring=vip_monitoring))
else:
# NOTE(jamespage):
# let heartbeat figure out which interface and
# netmask to configure, which works nicely
# when network interface naming is not
# consistent across units.
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
vip_monitoring=vip_monitoring))
vip_group.append(vip_key)
if vips_to_delete:
try:
relation_data['delete_resources'].extend(vips_to_delete)
except KeyError:
relation_data['delete_resources'] = vips_to_delete
if len(vip_group) >= 1:
key = VIP_GROUP_NAME.format(service=service)
try:
relation_data['groups'][key] = ' '.join(vip_group)
except KeyError:
relation_data['groups'] = {
key: ' '.join(vip_group)
} | python | def update_hacluster_vip(service, relation_data):
""" Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
"""
cluster_config = get_hacluster_config()
vip_group = []
vips_to_delete = []
for vip in cluster_config['vip'].split():
if is_ipv6(vip):
res_vip = 'ocf:heartbeat:IPv6addr'
vip_params = 'ipv6addr'
else:
res_vip = 'ocf:heartbeat:IPaddr2'
vip_params = 'ip'
iface, netmask, fallback = get_vip_settings(vip)
vip_monitoring = 'op monitor depth="0" timeout="20s" interval="10s"'
if iface is not None:
# NOTE(jamespage): Delete old VIP resources
# Old style naming encoding iface in name
# does not work well in environments where
# interface/subnet wiring is not consistent
vip_key = 'res_{}_{}_vip'.format(service, iface)
if vip_key in vips_to_delete:
vip_key = '{}_{}'.format(vip_key, vip_params)
vips_to_delete.append(vip_key)
vip_key = 'res_{}_{}_vip'.format(
service,
hashlib.sha1(vip.encode('UTF-8')).hexdigest()[:7])
relation_data['resources'][vip_key] = res_vip
# NOTE(jamespage):
# Use option provided vip params if these where used
# instead of auto-detected values
if fallback:
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" cidr_netmask="{netmask}" '
'nic="{iface}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
iface=iface,
netmask=netmask,
vip_monitoring=vip_monitoring))
else:
# NOTE(jamespage):
# let heartbeat figure out which interface and
# netmask to configure, which works nicely
# when network interface naming is not
# consistent across units.
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
vip_monitoring=vip_monitoring))
vip_group.append(vip_key)
if vips_to_delete:
try:
relation_data['delete_resources'].extend(vips_to_delete)
except KeyError:
relation_data['delete_resources'] = vips_to_delete
if len(vip_group) >= 1:
key = VIP_GROUP_NAME.format(service=service)
try:
relation_data['groups'][key] = ' '.join(vip_group)
except KeyError:
relation_data['groups'] = {
key: ' '.join(vip_group)
} | [
"def",
"update_hacluster_vip",
"(",
"service",
",",
"relation_data",
")",
":",
"cluster_config",
"=",
"get_hacluster_config",
"(",
")",
"vip_group",
"=",
"[",
"]",
"vips_to_delete",
"=",
"[",
"]",
"for",
"vip",
"in",
"cluster_config",
"[",
"'vip'",
"]",
".",
"split",
"(",
")",
":",
"if",
"is_ipv6",
"(",
"vip",
")",
":",
"res_vip",
"=",
"'ocf:heartbeat:IPv6addr'",
"vip_params",
"=",
"'ipv6addr'",
"else",
":",
"res_vip",
"=",
"'ocf:heartbeat:IPaddr2'",
"vip_params",
"=",
"'ip'",
"iface",
",",
"netmask",
",",
"fallback",
"=",
"get_vip_settings",
"(",
"vip",
")",
"vip_monitoring",
"=",
"'op monitor depth=\"0\" timeout=\"20s\" interval=\"10s\"'",
"if",
"iface",
"is",
"not",
"None",
":",
"# NOTE(jamespage): Delete old VIP resources",
"# Old style naming encoding iface in name",
"# does not work well in environments where",
"# interface/subnet wiring is not consistent",
"vip_key",
"=",
"'res_{}_{}_vip'",
".",
"format",
"(",
"service",
",",
"iface",
")",
"if",
"vip_key",
"in",
"vips_to_delete",
":",
"vip_key",
"=",
"'{}_{}'",
".",
"format",
"(",
"vip_key",
",",
"vip_params",
")",
"vips_to_delete",
".",
"append",
"(",
"vip_key",
")",
"vip_key",
"=",
"'res_{}_{}_vip'",
".",
"format",
"(",
"service",
",",
"hashlib",
".",
"sha1",
"(",
"vip",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
":",
"7",
"]",
")",
"relation_data",
"[",
"'resources'",
"]",
"[",
"vip_key",
"]",
"=",
"res_vip",
"# NOTE(jamespage):",
"# Use option provided vip params if these where used",
"# instead of auto-detected values",
"if",
"fallback",
":",
"relation_data",
"[",
"'resource_params'",
"]",
"[",
"vip_key",
"]",
"=",
"(",
"'params {ip}=\"{vip}\" cidr_netmask=\"{netmask}\" '",
"'nic=\"{iface}\" {vip_monitoring}'",
".",
"format",
"(",
"ip",
"=",
"vip_params",
",",
"vip",
"=",
"vip",
",",
"iface",
"=",
"iface",
",",
"netmask",
"=",
"netmask",
",",
"vip_monitoring",
"=",
"vip_monitoring",
")",
")",
"else",
":",
"# NOTE(jamespage):",
"# let heartbeat figure out which interface and",
"# netmask to configure, which works nicely",
"# when network interface naming is not",
"# consistent across units.",
"relation_data",
"[",
"'resource_params'",
"]",
"[",
"vip_key",
"]",
"=",
"(",
"'params {ip}=\"{vip}\" {vip_monitoring}'",
".",
"format",
"(",
"ip",
"=",
"vip_params",
",",
"vip",
"=",
"vip",
",",
"vip_monitoring",
"=",
"vip_monitoring",
")",
")",
"vip_group",
".",
"append",
"(",
"vip_key",
")",
"if",
"vips_to_delete",
":",
"try",
":",
"relation_data",
"[",
"'delete_resources'",
"]",
".",
"extend",
"(",
"vips_to_delete",
")",
"except",
"KeyError",
":",
"relation_data",
"[",
"'delete_resources'",
"]",
"=",
"vips_to_delete",
"if",
"len",
"(",
"vip_group",
")",
">=",
"1",
":",
"key",
"=",
"VIP_GROUP_NAME",
".",
"format",
"(",
"service",
"=",
"service",
")",
"try",
":",
"relation_data",
"[",
"'groups'",
"]",
"[",
"key",
"]",
"=",
"' '",
".",
"join",
"(",
"vip_group",
")",
"except",
"KeyError",
":",
"relation_data",
"[",
"'groups'",
"]",
"=",
"{",
"key",
":",
"' '",
".",
"join",
"(",
"vip_group",
")",
"}"
] | Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data. | [
"Configure",
"VIP",
"resources",
"based",
"on",
"provided",
"configuration"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L274-L348 | train |
juju/charm-helpers | charmhelpers/contrib/amulet/deployment.py | AmuletDeployment._add_services | def _add_services(self, this_service, other_services):
"""Add services.
Add services to the deployment where this_service is the local charm
that we're testing and other_services are the other services that
are being used in the local amulet tests.
"""
if this_service['name'] != os.path.basename(os.getcwd()):
s = this_service['name']
msg = "The charm's root directory name needs to be {}".format(s)
amulet.raise_status(amulet.FAIL, msg=msg)
if 'units' not in this_service:
this_service['units'] = 1
self.d.add(this_service['name'], units=this_service['units'],
constraints=this_service.get('constraints'),
storage=this_service.get('storage'))
for svc in other_services:
if 'location' in svc:
branch_location = svc['location']
elif self.series:
branch_location = 'cs:{}/{}'.format(self.series, svc['name']),
else:
branch_location = None
if 'units' not in svc:
svc['units'] = 1
self.d.add(svc['name'], charm=branch_location, units=svc['units'],
constraints=svc.get('constraints'),
storage=svc.get('storage')) | python | def _add_services(self, this_service, other_services):
"""Add services.
Add services to the deployment where this_service is the local charm
that we're testing and other_services are the other services that
are being used in the local amulet tests.
"""
if this_service['name'] != os.path.basename(os.getcwd()):
s = this_service['name']
msg = "The charm's root directory name needs to be {}".format(s)
amulet.raise_status(amulet.FAIL, msg=msg)
if 'units' not in this_service:
this_service['units'] = 1
self.d.add(this_service['name'], units=this_service['units'],
constraints=this_service.get('constraints'),
storage=this_service.get('storage'))
for svc in other_services:
if 'location' in svc:
branch_location = svc['location']
elif self.series:
branch_location = 'cs:{}/{}'.format(self.series, svc['name']),
else:
branch_location = None
if 'units' not in svc:
svc['units'] = 1
self.d.add(svc['name'], charm=branch_location, units=svc['units'],
constraints=svc.get('constraints'),
storage=svc.get('storage')) | [
"def",
"_add_services",
"(",
"self",
",",
"this_service",
",",
"other_services",
")",
":",
"if",
"this_service",
"[",
"'name'",
"]",
"!=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"s",
"=",
"this_service",
"[",
"'name'",
"]",
"msg",
"=",
"\"The charm's root directory name needs to be {}\"",
".",
"format",
"(",
"s",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"if",
"'units'",
"not",
"in",
"this_service",
":",
"this_service",
"[",
"'units'",
"]",
"=",
"1",
"self",
".",
"d",
".",
"add",
"(",
"this_service",
"[",
"'name'",
"]",
",",
"units",
"=",
"this_service",
"[",
"'units'",
"]",
",",
"constraints",
"=",
"this_service",
".",
"get",
"(",
"'constraints'",
")",
",",
"storage",
"=",
"this_service",
".",
"get",
"(",
"'storage'",
")",
")",
"for",
"svc",
"in",
"other_services",
":",
"if",
"'location'",
"in",
"svc",
":",
"branch_location",
"=",
"svc",
"[",
"'location'",
"]",
"elif",
"self",
".",
"series",
":",
"branch_location",
"=",
"'cs:{}/{}'",
".",
"format",
"(",
"self",
".",
"series",
",",
"svc",
"[",
"'name'",
"]",
")",
",",
"else",
":",
"branch_location",
"=",
"None",
"if",
"'units'",
"not",
"in",
"svc",
":",
"svc",
"[",
"'units'",
"]",
"=",
"1",
"self",
".",
"d",
".",
"add",
"(",
"svc",
"[",
"'name'",
"]",
",",
"charm",
"=",
"branch_location",
",",
"units",
"=",
"svc",
"[",
"'units'",
"]",
",",
"constraints",
"=",
"svc",
".",
"get",
"(",
"'constraints'",
")",
",",
"storage",
"=",
"svc",
".",
"get",
"(",
"'storage'",
")",
")"
] | Add services.
Add services to the deployment where this_service is the local charm
that we're testing and other_services are the other services that
are being used in the local amulet tests. | [
"Add",
"services",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L37-L69 | train |
juju/charm-helpers | charmhelpers/contrib/amulet/deployment.py | AmuletDeployment._add_relations | def _add_relations(self, relations):
"""Add all of the relations for the services."""
for k, v in six.iteritems(relations):
self.d.relate(k, v) | python | def _add_relations(self, relations):
"""Add all of the relations for the services."""
for k, v in six.iteritems(relations):
self.d.relate(k, v) | [
"def",
"_add_relations",
"(",
"self",
",",
"relations",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"relations",
")",
":",
"self",
".",
"d",
".",
"relate",
"(",
"k",
",",
"v",
")"
] | Add all of the relations for the services. | [
"Add",
"all",
"of",
"the",
"relations",
"for",
"the",
"services",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L71-L74 | train |
juju/charm-helpers | charmhelpers/contrib/amulet/deployment.py | AmuletDeployment._configure_services | def _configure_services(self, configs):
"""Configure all of the services."""
for service, config in six.iteritems(configs):
self.d.configure(service, config) | python | def _configure_services(self, configs):
"""Configure all of the services."""
for service, config in six.iteritems(configs):
self.d.configure(service, config) | [
"def",
"_configure_services",
"(",
"self",
",",
"configs",
")",
":",
"for",
"service",
",",
"config",
"in",
"six",
".",
"iteritems",
"(",
"configs",
")",
":",
"self",
".",
"d",
".",
"configure",
"(",
"service",
",",
"config",
")"
] | Configure all of the services. | [
"Configure",
"all",
"of",
"the",
"services",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L76-L79 | train |
juju/charm-helpers | charmhelpers/contrib/amulet/deployment.py | AmuletDeployment._deploy | def _deploy(self):
"""Deploy environment and wait for all hooks to finish executing."""
timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 900))
try:
self.d.setup(timeout=timeout)
self.d.sentry.wait(timeout=timeout)
except amulet.helpers.TimeoutError:
amulet.raise_status(
amulet.FAIL,
msg="Deployment timed out ({}s)".format(timeout)
)
except Exception:
raise | python | def _deploy(self):
"""Deploy environment and wait for all hooks to finish executing."""
timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 900))
try:
self.d.setup(timeout=timeout)
self.d.sentry.wait(timeout=timeout)
except amulet.helpers.TimeoutError:
amulet.raise_status(
amulet.FAIL,
msg="Deployment timed out ({}s)".format(timeout)
)
except Exception:
raise | [
"def",
"_deploy",
"(",
"self",
")",
":",
"timeout",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'AMULET_SETUP_TIMEOUT'",
",",
"900",
")",
")",
"try",
":",
"self",
".",
"d",
".",
"setup",
"(",
"timeout",
"=",
"timeout",
")",
"self",
".",
"d",
".",
"sentry",
".",
"wait",
"(",
"timeout",
"=",
"timeout",
")",
"except",
"amulet",
".",
"helpers",
".",
"TimeoutError",
":",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"\"Deployment timed out ({}s)\"",
".",
"format",
"(",
"timeout",
")",
")",
"except",
"Exception",
":",
"raise"
] | Deploy environment and wait for all hooks to finish executing. | [
"Deploy",
"environment",
"and",
"wait",
"for",
"all",
"hooks",
"to",
"finish",
"executing",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L81-L93 | train |
juju/charm-helpers | charmhelpers/contrib/ssl/service.py | ServiceCA._init_ca | def _init_ca(self):
"""Generate the root ca's cert and key.
"""
if not exists(path_join(self.ca_dir, 'ca.cnf')):
with open(path_join(self.ca_dir, 'ca.cnf'), 'w') as fh:
fh.write(
CA_CONF_TEMPLATE % (self.get_conf_variables()))
if not exists(path_join(self.ca_dir, 'signing.cnf')):
with open(path_join(self.ca_dir, 'signing.cnf'), 'w') as fh:
fh.write(
SIGNING_CONF_TEMPLATE % (self.get_conf_variables()))
if exists(self.ca_cert) or exists(self.ca_key):
raise RuntimeError("Initialized called when CA already exists")
cmd = ['openssl', 'req', '-config', self.ca_conf,
'-x509', '-nodes', '-newkey', 'rsa',
'-days', self.default_ca_expiry,
'-keyout', self.ca_key, '-out', self.ca_cert,
'-outform', 'PEM']
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
log("CA Init:\n %s" % output, level=DEBUG) | python | def _init_ca(self):
"""Generate the root ca's cert and key.
"""
if not exists(path_join(self.ca_dir, 'ca.cnf')):
with open(path_join(self.ca_dir, 'ca.cnf'), 'w') as fh:
fh.write(
CA_CONF_TEMPLATE % (self.get_conf_variables()))
if not exists(path_join(self.ca_dir, 'signing.cnf')):
with open(path_join(self.ca_dir, 'signing.cnf'), 'w') as fh:
fh.write(
SIGNING_CONF_TEMPLATE % (self.get_conf_variables()))
if exists(self.ca_cert) or exists(self.ca_key):
raise RuntimeError("Initialized called when CA already exists")
cmd = ['openssl', 'req', '-config', self.ca_conf,
'-x509', '-nodes', '-newkey', 'rsa',
'-days', self.default_ca_expiry,
'-keyout', self.ca_key, '-out', self.ca_cert,
'-outform', 'PEM']
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
log("CA Init:\n %s" % output, level=DEBUG) | [
"def",
"_init_ca",
"(",
"self",
")",
":",
"if",
"not",
"exists",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'ca.cnf'",
")",
")",
":",
"with",
"open",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'ca.cnf'",
")",
",",
"'w'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"CA_CONF_TEMPLATE",
"%",
"(",
"self",
".",
"get_conf_variables",
"(",
")",
")",
")",
"if",
"not",
"exists",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'signing.cnf'",
")",
")",
":",
"with",
"open",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'signing.cnf'",
")",
",",
"'w'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"SIGNING_CONF_TEMPLATE",
"%",
"(",
"self",
".",
"get_conf_variables",
"(",
")",
")",
")",
"if",
"exists",
"(",
"self",
".",
"ca_cert",
")",
"or",
"exists",
"(",
"self",
".",
"ca_key",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Initialized called when CA already exists\"",
")",
"cmd",
"=",
"[",
"'openssl'",
",",
"'req'",
",",
"'-config'",
",",
"self",
".",
"ca_conf",
",",
"'-x509'",
",",
"'-nodes'",
",",
"'-newkey'",
",",
"'rsa'",
",",
"'-days'",
",",
"self",
".",
"default_ca_expiry",
",",
"'-keyout'",
",",
"self",
".",
"ca_key",
",",
"'-out'",
",",
"self",
".",
"ca_cert",
",",
"'-outform'",
",",
"'PEM'",
"]",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"log",
"(",
"\"CA Init:\\n %s\"",
"%",
"output",
",",
"level",
"=",
"DEBUG",
")"
] | Generate the root ca's cert and key. | [
"Generate",
"the",
"root",
"ca",
"s",
"cert",
"and",
"key",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ssl/service.py#L95-L116 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/keystone.py | format_endpoint | def format_endpoint(schema, addr, port, api_version):
"""Return a formatted keystone endpoint
@param schema: http or https
@param addr: ipv4/ipv6 host of the keystone service
@param port: port of the keystone service
@param api_version: 2 or 3
@returns a fully formatted keystone endpoint
"""
return '{}://{}:{}/{}/'.format(schema, addr, port,
get_api_suffix(api_version)) | python | def format_endpoint(schema, addr, port, api_version):
"""Return a formatted keystone endpoint
@param schema: http or https
@param addr: ipv4/ipv6 host of the keystone service
@param port: port of the keystone service
@param api_version: 2 or 3
@returns a fully formatted keystone endpoint
"""
return '{}://{}:{}/{}/'.format(schema, addr, port,
get_api_suffix(api_version)) | [
"def",
"format_endpoint",
"(",
"schema",
",",
"addr",
",",
"port",
",",
"api_version",
")",
":",
"return",
"'{}://{}:{}/{}/'",
".",
"format",
"(",
"schema",
",",
"addr",
",",
"port",
",",
"get_api_suffix",
"(",
"api_version",
")",
")"
] | Return a formatted keystone endpoint
@param schema: http or https
@param addr: ipv4/ipv6 host of the keystone service
@param port: port of the keystone service
@param api_version: 2 or 3
@returns a fully formatted keystone endpoint | [
"Return",
"a",
"formatted",
"keystone",
"endpoint"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L35-L44 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/keystone.py | get_keystone_manager | def get_keystone_manager(endpoint, api_version, **kwargs):
"""Return a keystonemanager for the correct API version
@param endpoint: the keystone endpoint to point client at
@param api_version: version of the keystone api the client should use
@param kwargs: token or username/tenant/password information
@returns keystonemanager class used for interrogating keystone
"""
if api_version == 2:
return KeystoneManager2(endpoint, **kwargs)
if api_version == 3:
return KeystoneManager3(endpoint, **kwargs)
raise ValueError('No manager found for api version {}'.format(api_version)) | python | def get_keystone_manager(endpoint, api_version, **kwargs):
"""Return a keystonemanager for the correct API version
@param endpoint: the keystone endpoint to point client at
@param api_version: version of the keystone api the client should use
@param kwargs: token or username/tenant/password information
@returns keystonemanager class used for interrogating keystone
"""
if api_version == 2:
return KeystoneManager2(endpoint, **kwargs)
if api_version == 3:
return KeystoneManager3(endpoint, **kwargs)
raise ValueError('No manager found for api version {}'.format(api_version)) | [
"def",
"get_keystone_manager",
"(",
"endpoint",
",",
"api_version",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"api_version",
"==",
"2",
":",
"return",
"KeystoneManager2",
"(",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
"if",
"api_version",
"==",
"3",
":",
"return",
"KeystoneManager3",
"(",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
"raise",
"ValueError",
"(",
"'No manager found for api version {}'",
".",
"format",
"(",
"api_version",
")",
")"
] | Return a keystonemanager for the correct API version
@param endpoint: the keystone endpoint to point client at
@param api_version: version of the keystone api the client should use
@param kwargs: token or username/tenant/password information
@returns keystonemanager class used for interrogating keystone | [
"Return",
"a",
"keystonemanager",
"for",
"the",
"correct",
"API",
"version"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L47-L59 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/keystone.py | get_keystone_manager_from_identity_service_context | def get_keystone_manager_from_identity_service_context():
"""Return a keystonmanager generated from a
instance of charmhelpers.contrib.openstack.context.IdentityServiceContext
@returns keystonamenager instance
"""
context = IdentityServiceContext()()
if not context:
msg = "Identity service context cannot be generated"
log(msg, level=ERROR)
raise ValueError(msg)
endpoint = format_endpoint(context['service_protocol'],
context['service_host'],
context['service_port'],
context['api_version'])
if context['api_version'] in (2, "2.0"):
api_version = 2
else:
api_version = 3
return get_keystone_manager(endpoint, api_version,
username=context['admin_user'],
password=context['admin_password'],
tenant_name=context['admin_tenant_name']) | python | def get_keystone_manager_from_identity_service_context():
"""Return a keystonmanager generated from a
instance of charmhelpers.contrib.openstack.context.IdentityServiceContext
@returns keystonamenager instance
"""
context = IdentityServiceContext()()
if not context:
msg = "Identity service context cannot be generated"
log(msg, level=ERROR)
raise ValueError(msg)
endpoint = format_endpoint(context['service_protocol'],
context['service_host'],
context['service_port'],
context['api_version'])
if context['api_version'] in (2, "2.0"):
api_version = 2
else:
api_version = 3
return get_keystone_manager(endpoint, api_version,
username=context['admin_user'],
password=context['admin_password'],
tenant_name=context['admin_tenant_name']) | [
"def",
"get_keystone_manager_from_identity_service_context",
"(",
")",
":",
"context",
"=",
"IdentityServiceContext",
"(",
")",
"(",
")",
"if",
"not",
"context",
":",
"msg",
"=",
"\"Identity service context cannot be generated\"",
"log",
"(",
"msg",
",",
"level",
"=",
"ERROR",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"endpoint",
"=",
"format_endpoint",
"(",
"context",
"[",
"'service_protocol'",
"]",
",",
"context",
"[",
"'service_host'",
"]",
",",
"context",
"[",
"'service_port'",
"]",
",",
"context",
"[",
"'api_version'",
"]",
")",
"if",
"context",
"[",
"'api_version'",
"]",
"in",
"(",
"2",
",",
"\"2.0\"",
")",
":",
"api_version",
"=",
"2",
"else",
":",
"api_version",
"=",
"3",
"return",
"get_keystone_manager",
"(",
"endpoint",
",",
"api_version",
",",
"username",
"=",
"context",
"[",
"'admin_user'",
"]",
",",
"password",
"=",
"context",
"[",
"'admin_password'",
"]",
",",
"tenant_name",
"=",
"context",
"[",
"'admin_tenant_name'",
"]",
")"
] | Return a keystonmanager generated from a
instance of charmhelpers.contrib.openstack.context.IdentityServiceContext
@returns keystonamenager instance | [
"Return",
"a",
"keystonmanager",
"generated",
"from",
"a",
"instance",
"of",
"charmhelpers",
".",
"contrib",
".",
"openstack",
".",
"context",
".",
"IdentityServiceContext"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L62-L86 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/keystone.py | KeystoneManager.resolve_service_id | def resolve_service_id(self, service_name=None, service_type=None):
"""Find the service_id of a given service"""
services = [s._info for s in self.api.services.list()]
service_name = service_name.lower()
for s in services:
name = s['name'].lower()
if service_type and service_name:
if (service_name == name and service_type == s['type']):
return s['id']
elif service_name and service_name == name:
return s['id']
elif service_type and service_type == s['type']:
return s['id']
return None | python | def resolve_service_id(self, service_name=None, service_type=None):
"""Find the service_id of a given service"""
services = [s._info for s in self.api.services.list()]
service_name = service_name.lower()
for s in services:
name = s['name'].lower()
if service_type and service_name:
if (service_name == name and service_type == s['type']):
return s['id']
elif service_name and service_name == name:
return s['id']
elif service_type and service_type == s['type']:
return s['id']
return None | [
"def",
"resolve_service_id",
"(",
"self",
",",
"service_name",
"=",
"None",
",",
"service_type",
"=",
"None",
")",
":",
"services",
"=",
"[",
"s",
".",
"_info",
"for",
"s",
"in",
"self",
".",
"api",
".",
"services",
".",
"list",
"(",
")",
"]",
"service_name",
"=",
"service_name",
".",
"lower",
"(",
")",
"for",
"s",
"in",
"services",
":",
"name",
"=",
"s",
"[",
"'name'",
"]",
".",
"lower",
"(",
")",
"if",
"service_type",
"and",
"service_name",
":",
"if",
"(",
"service_name",
"==",
"name",
"and",
"service_type",
"==",
"s",
"[",
"'type'",
"]",
")",
":",
"return",
"s",
"[",
"'id'",
"]",
"elif",
"service_name",
"and",
"service_name",
"==",
"name",
":",
"return",
"s",
"[",
"'id'",
"]",
"elif",
"service_type",
"and",
"service_type",
"==",
"s",
"[",
"'type'",
"]",
":",
"return",
"s",
"[",
"'id'",
"]",
"return",
"None"
] | Find the service_id of a given service | [
"Find",
"the",
"service_id",
"of",
"a",
"given",
"service"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L91-L105 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/lvm.py | deactivate_lvm_volume_group | def deactivate_lvm_volume_group(block_device):
'''
Deactivate any volume gruop associated with an LVM physical volume.
:param block_device: str: Full path to LVM physical volume
'''
vg = list_lvm_volume_group(block_device)
if vg:
cmd = ['vgchange', '-an', vg]
check_call(cmd) | python | def deactivate_lvm_volume_group(block_device):
'''
Deactivate any volume gruop associated with an LVM physical volume.
:param block_device: str: Full path to LVM physical volume
'''
vg = list_lvm_volume_group(block_device)
if vg:
cmd = ['vgchange', '-an', vg]
check_call(cmd) | [
"def",
"deactivate_lvm_volume_group",
"(",
"block_device",
")",
":",
"vg",
"=",
"list_lvm_volume_group",
"(",
"block_device",
")",
"if",
"vg",
":",
"cmd",
"=",
"[",
"'vgchange'",
",",
"'-an'",
",",
"vg",
"]",
"check_call",
"(",
"cmd",
")"
] | Deactivate any volume gruop associated with an LVM physical volume.
:param block_device: str: Full path to LVM physical volume | [
"Deactivate",
"any",
"volume",
"gruop",
"associated",
"with",
"an",
"LVM",
"physical",
"volume",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L28-L37 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/lvm.py | remove_lvm_physical_volume | def remove_lvm_physical_volume(block_device):
'''
Remove LVM PV signatures from a given block device.
:param block_device: str: Full path of block device to scrub.
'''
p = Popen(['pvremove', '-ff', block_device],
stdin=PIPE)
p.communicate(input='y\n') | python | def remove_lvm_physical_volume(block_device):
'''
Remove LVM PV signatures from a given block device.
:param block_device: str: Full path of block device to scrub.
'''
p = Popen(['pvremove', '-ff', block_device],
stdin=PIPE)
p.communicate(input='y\n') | [
"def",
"remove_lvm_physical_volume",
"(",
"block_device",
")",
":",
"p",
"=",
"Popen",
"(",
"[",
"'pvremove'",
",",
"'-ff'",
",",
"block_device",
"]",
",",
"stdin",
"=",
"PIPE",
")",
"p",
".",
"communicate",
"(",
"input",
"=",
"'y\\n'",
")"
] | Remove LVM PV signatures from a given block device.
:param block_device: str: Full path of block device to scrub. | [
"Remove",
"LVM",
"PV",
"signatures",
"from",
"a",
"given",
"block",
"device",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L55-L63 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/lvm.py | list_lvm_volume_group | def list_lvm_volume_group(block_device):
'''
List LVM volume group associated with a given block device.
Assumes block device is a valid LVM PV.
:param block_device: str: Full path of block device to inspect.
:returns: str: Name of volume group associated with block device or None
'''
vg = None
pvd = check_output(['pvdisplay', block_device]).splitlines()
for lvm in pvd:
lvm = lvm.decode('UTF-8')
if lvm.strip().startswith('VG Name'):
vg = ' '.join(lvm.strip().split()[2:])
return vg | python | def list_lvm_volume_group(block_device):
'''
List LVM volume group associated with a given block device.
Assumes block device is a valid LVM PV.
:param block_device: str: Full path of block device to inspect.
:returns: str: Name of volume group associated with block device or None
'''
vg = None
pvd = check_output(['pvdisplay', block_device]).splitlines()
for lvm in pvd:
lvm = lvm.decode('UTF-8')
if lvm.strip().startswith('VG Name'):
vg = ' '.join(lvm.strip().split()[2:])
return vg | [
"def",
"list_lvm_volume_group",
"(",
"block_device",
")",
":",
"vg",
"=",
"None",
"pvd",
"=",
"check_output",
"(",
"[",
"'pvdisplay'",
",",
"block_device",
"]",
")",
".",
"splitlines",
"(",
")",
"for",
"lvm",
"in",
"pvd",
":",
"lvm",
"=",
"lvm",
".",
"decode",
"(",
"'UTF-8'",
")",
"if",
"lvm",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'VG Name'",
")",
":",
"vg",
"=",
"' '",
".",
"join",
"(",
"lvm",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"[",
"2",
":",
"]",
")",
"return",
"vg"
] | List LVM volume group associated with a given block device.
Assumes block device is a valid LVM PV.
:param block_device: str: Full path of block device to inspect.
:returns: str: Name of volume group associated with block device or None | [
"List",
"LVM",
"volume",
"group",
"associated",
"with",
"a",
"given",
"block",
"device",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L66-L82 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/lvm.py | list_logical_volumes | def list_logical_volumes(select_criteria=None, path_mode=False):
'''
List logical volumes
:param select_criteria: str: Limit list to those volumes matching this
criteria (see 'lvs -S help' for more details)
:param path_mode: bool: return logical volume name in 'vg/lv' format, this
format is required for some commands like lvextend
:returns: [str]: List of logical volumes
'''
lv_diplay_attr = 'lv_name'
if path_mode:
# Parsing output logic relies on the column order
lv_diplay_attr = 'vg_name,' + lv_diplay_attr
cmd = ['lvs', '--options', lv_diplay_attr, '--noheadings']
if select_criteria:
cmd.extend(['--select', select_criteria])
lvs = []
for lv in check_output(cmd).decode('UTF-8').splitlines():
if not lv:
continue
if path_mode:
lvs.append('/'.join(lv.strip().split()))
else:
lvs.append(lv.strip())
return lvs | python | def list_logical_volumes(select_criteria=None, path_mode=False):
'''
List logical volumes
:param select_criteria: str: Limit list to those volumes matching this
criteria (see 'lvs -S help' for more details)
:param path_mode: bool: return logical volume name in 'vg/lv' format, this
format is required for some commands like lvextend
:returns: [str]: List of logical volumes
'''
lv_diplay_attr = 'lv_name'
if path_mode:
# Parsing output logic relies on the column order
lv_diplay_attr = 'vg_name,' + lv_diplay_attr
cmd = ['lvs', '--options', lv_diplay_attr, '--noheadings']
if select_criteria:
cmd.extend(['--select', select_criteria])
lvs = []
for lv in check_output(cmd).decode('UTF-8').splitlines():
if not lv:
continue
if path_mode:
lvs.append('/'.join(lv.strip().split()))
else:
lvs.append(lv.strip())
return lvs | [
"def",
"list_logical_volumes",
"(",
"select_criteria",
"=",
"None",
",",
"path_mode",
"=",
"False",
")",
":",
"lv_diplay_attr",
"=",
"'lv_name'",
"if",
"path_mode",
":",
"# Parsing output logic relies on the column order",
"lv_diplay_attr",
"=",
"'vg_name,'",
"+",
"lv_diplay_attr",
"cmd",
"=",
"[",
"'lvs'",
",",
"'--options'",
",",
"lv_diplay_attr",
",",
"'--noheadings'",
"]",
"if",
"select_criteria",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--select'",
",",
"select_criteria",
"]",
")",
"lvs",
"=",
"[",
"]",
"for",
"lv",
"in",
"check_output",
"(",
"cmd",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"lv",
":",
"continue",
"if",
"path_mode",
":",
"lvs",
".",
"append",
"(",
"'/'",
".",
"join",
"(",
"lv",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
")",
")",
"else",
":",
"lvs",
".",
"append",
"(",
"lv",
".",
"strip",
"(",
")",
")",
"return",
"lvs"
] | List logical volumes
:param select_criteria: str: Limit list to those volumes matching this
criteria (see 'lvs -S help' for more details)
:param path_mode: bool: return logical volume name in 'vg/lv' format, this
format is required for some commands like lvextend
:returns: [str]: List of logical volumes | [
"List",
"logical",
"volumes"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L107-L132 | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/lvm.py | create_logical_volume | def create_logical_volume(lv_name, volume_group, size=None):
'''
Create a new logical volume in an existing volume group
:param lv_name: str: name of logical volume to be created.
:param volume_group: str: Name of volume group to use for the new volume.
:param size: str: Size of logical volume to create (100% if not supplied)
:raises subprocess.CalledProcessError: in the event that the lvcreate fails.
'''
if size:
check_call([
'lvcreate',
'--yes',
'-L',
'{}'.format(size),
'-n', lv_name, volume_group
])
# create the lv with all the space available, this is needed because the
# system call is different for LVM
else:
check_call([
'lvcreate',
'--yes',
'-l',
'100%FREE',
'-n', lv_name, volume_group
]) | python | def create_logical_volume(lv_name, volume_group, size=None):
'''
Create a new logical volume in an existing volume group
:param lv_name: str: name of logical volume to be created.
:param volume_group: str: Name of volume group to use for the new volume.
:param size: str: Size of logical volume to create (100% if not supplied)
:raises subprocess.CalledProcessError: in the event that the lvcreate fails.
'''
if size:
check_call([
'lvcreate',
'--yes',
'-L',
'{}'.format(size),
'-n', lv_name, volume_group
])
# create the lv with all the space available, this is needed because the
# system call is different for LVM
else:
check_call([
'lvcreate',
'--yes',
'-l',
'100%FREE',
'-n', lv_name, volume_group
]) | [
"def",
"create_logical_volume",
"(",
"lv_name",
",",
"volume_group",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
":",
"check_call",
"(",
"[",
"'lvcreate'",
",",
"'--yes'",
",",
"'-L'",
",",
"'{}'",
".",
"format",
"(",
"size",
")",
",",
"'-n'",
",",
"lv_name",
",",
"volume_group",
"]",
")",
"# create the lv with all the space available, this is needed because the",
"# system call is different for LVM",
"else",
":",
"check_call",
"(",
"[",
"'lvcreate'",
",",
"'--yes'",
",",
"'-l'",
",",
"'100%FREE'",
",",
"'-n'",
",",
"lv_name",
",",
"volume_group",
"]",
")"
] | Create a new logical volume in an existing volume group
:param lv_name: str: name of logical volume to be created.
:param volume_group: str: Name of volume group to use for the new volume.
:param size: str: Size of logical volume to create (100% if not supplied)
:raises subprocess.CalledProcessError: in the event that the lvcreate fails. | [
"Create",
"a",
"new",
"logical",
"volume",
"in",
"an",
"existing",
"volume",
"group"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L156-L182 | train |
juju/charm-helpers | charmhelpers/core/templating.py | render | def render(source, target, context, owner='root', group='root',
perms=0o444, templates_dir=None, encoding='UTF-8',
template_loader=None, config_template=None):
"""
Render a template.
The `source` path, if not absolute, is relative to the `templates_dir`.
The `target` path should be absolute. It can also be `None`, in which
case no file will be written.
The context should be a dict containing the values to be replaced in the
template.
config_template may be provided to render from a provided template instead
of loading from a file.
The `owner`, `group`, and `perms` options will be passed to `write_file`.
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
The rendered template will be written to the file as well as being returned
as a string.
Note: Using this requires python-jinja2 or python3-jinja2; if it is not
installed, calling this will attempt to use charmhelpers.fetch.apt_install
to install it.
"""
try:
from jinja2 import FileSystemLoader, Environment, exceptions
except ImportError:
try:
from charmhelpers.fetch import apt_install
except ImportError:
hookenv.log('Could not import jinja2, and could not import '
'charmhelpers.fetch to install it',
level=hookenv.ERROR)
raise
if sys.version_info.major == 2:
apt_install('python-jinja2', fatal=True)
else:
apt_install('python3-jinja2', fatal=True)
from jinja2 import FileSystemLoader, Environment, exceptions
if template_loader:
template_env = Environment(loader=template_loader)
else:
if templates_dir is None:
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
template_env = Environment(loader=FileSystemLoader(templates_dir))
# load from a string if provided explicitly
if config_template is not None:
template = template_env.from_string(config_template)
else:
try:
source = source
template = template_env.get_template(source)
except exceptions.TemplateNotFound as e:
hookenv.log('Could not load template %s from %s.' %
(source, templates_dir),
level=hookenv.ERROR)
raise e
content = template.render(context)
if target is not None:
target_dir = os.path.dirname(target)
if not os.path.exists(target_dir):
# This is a terrible default directory permission, as the file
# or its siblings will often contain secrets.
host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
host.write_file(target, content.encode(encoding), owner, group, perms)
return content | python | def render(source, target, context, owner='root', group='root',
perms=0o444, templates_dir=None, encoding='UTF-8',
template_loader=None, config_template=None):
"""
Render a template.
The `source` path, if not absolute, is relative to the `templates_dir`.
The `target` path should be absolute. It can also be `None`, in which
case no file will be written.
The context should be a dict containing the values to be replaced in the
template.
config_template may be provided to render from a provided template instead
of loading from a file.
The `owner`, `group`, and `perms` options will be passed to `write_file`.
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
The rendered template will be written to the file as well as being returned
as a string.
Note: Using this requires python-jinja2 or python3-jinja2; if it is not
installed, calling this will attempt to use charmhelpers.fetch.apt_install
to install it.
"""
try:
from jinja2 import FileSystemLoader, Environment, exceptions
except ImportError:
try:
from charmhelpers.fetch import apt_install
except ImportError:
hookenv.log('Could not import jinja2, and could not import '
'charmhelpers.fetch to install it',
level=hookenv.ERROR)
raise
if sys.version_info.major == 2:
apt_install('python-jinja2', fatal=True)
else:
apt_install('python3-jinja2', fatal=True)
from jinja2 import FileSystemLoader, Environment, exceptions
if template_loader:
template_env = Environment(loader=template_loader)
else:
if templates_dir is None:
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
template_env = Environment(loader=FileSystemLoader(templates_dir))
# load from a string if provided explicitly
if config_template is not None:
template = template_env.from_string(config_template)
else:
try:
source = source
template = template_env.get_template(source)
except exceptions.TemplateNotFound as e:
hookenv.log('Could not load template %s from %s.' %
(source, templates_dir),
level=hookenv.ERROR)
raise e
content = template.render(context)
if target is not None:
target_dir = os.path.dirname(target)
if not os.path.exists(target_dir):
# This is a terrible default directory permission, as the file
# or its siblings will often contain secrets.
host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
host.write_file(target, content.encode(encoding), owner, group, perms)
return content | [
"def",
"render",
"(",
"source",
",",
"target",
",",
"context",
",",
"owner",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"perms",
"=",
"0o444",
",",
"templates_dir",
"=",
"None",
",",
"encoding",
"=",
"'UTF-8'",
",",
"template_loader",
"=",
"None",
",",
"config_template",
"=",
"None",
")",
":",
"try",
":",
"from",
"jinja2",
"import",
"FileSystemLoader",
",",
"Environment",
",",
"exceptions",
"except",
"ImportError",
":",
"try",
":",
"from",
"charmhelpers",
".",
"fetch",
"import",
"apt_install",
"except",
"ImportError",
":",
"hookenv",
".",
"log",
"(",
"'Could not import jinja2, and could not import '",
"'charmhelpers.fetch to install it'",
",",
"level",
"=",
"hookenv",
".",
"ERROR",
")",
"raise",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"2",
":",
"apt_install",
"(",
"'python-jinja2'",
",",
"fatal",
"=",
"True",
")",
"else",
":",
"apt_install",
"(",
"'python3-jinja2'",
",",
"fatal",
"=",
"True",
")",
"from",
"jinja2",
"import",
"FileSystemLoader",
",",
"Environment",
",",
"exceptions",
"if",
"template_loader",
":",
"template_env",
"=",
"Environment",
"(",
"loader",
"=",
"template_loader",
")",
"else",
":",
"if",
"templates_dir",
"is",
"None",
":",
"templates_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"hookenv",
".",
"charm_dir",
"(",
")",
",",
"'templates'",
")",
"template_env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"templates_dir",
")",
")",
"# load from a string if provided explicitly",
"if",
"config_template",
"is",
"not",
"None",
":",
"template",
"=",
"template_env",
".",
"from_string",
"(",
"config_template",
")",
"else",
":",
"try",
":",
"source",
"=",
"source",
"template",
"=",
"template_env",
".",
"get_template",
"(",
"source",
")",
"except",
"exceptions",
".",
"TemplateNotFound",
"as",
"e",
":",
"hookenv",
".",
"log",
"(",
"'Could not load template %s from %s.'",
"%",
"(",
"source",
",",
"templates_dir",
")",
",",
"level",
"=",
"hookenv",
".",
"ERROR",
")",
"raise",
"e",
"content",
"=",
"template",
".",
"render",
"(",
"context",
")",
"if",
"target",
"is",
"not",
"None",
":",
"target_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"target",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target_dir",
")",
":",
"# This is a terrible default directory permission, as the file",
"# or its siblings will often contain secrets.",
"host",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"target",
")",
",",
"owner",
",",
"group",
",",
"perms",
"=",
"0o755",
")",
"host",
".",
"write_file",
"(",
"target",
",",
"content",
".",
"encode",
"(",
"encoding",
")",
",",
"owner",
",",
"group",
",",
"perms",
")",
"return",
"content"
] | Render a template.
The `source` path, if not absolute, is relative to the `templates_dir`.
The `target` path should be absolute. It can also be `None`, in which
case no file will be written.
The context should be a dict containing the values to be replaced in the
template.
config_template may be provided to render from a provided template instead
of loading from a file.
The `owner`, `group`, and `perms` options will be passed to `write_file`.
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
The rendered template will be written to the file as well as being returned
as a string.
Note: Using this requires python-jinja2 or python3-jinja2; if it is not
installed, calling this will attempt to use charmhelpers.fetch.apt_install
to install it. | [
"Render",
"a",
"template",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/templating.py#L22-L93 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | cached | def cached(func):
"""Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls.
"""
@wraps(func)
def wrapper(*args, **kwargs):
global cache
key = json.dumps((func, args, kwargs), sort_keys=True, default=str)
try:
return cache[key]
except KeyError:
pass # Drop out of the exception handler scope.
res = func(*args, **kwargs)
cache[key] = res
return res
wrapper._wrapped = func
return wrapper | python | def cached(func):
"""Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls.
"""
@wraps(func)
def wrapper(*args, **kwargs):
global cache
key = json.dumps((func, args, kwargs), sort_keys=True, default=str)
try:
return cache[key]
except KeyError:
pass # Drop out of the exception handler scope.
res = func(*args, **kwargs)
cache[key] = res
return res
wrapper._wrapped = func
return wrapper | [
"def",
"cached",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"cache",
"key",
"=",
"json",
".",
"dumps",
"(",
"(",
"func",
",",
"args",
",",
"kwargs",
")",
",",
"sort_keys",
"=",
"True",
",",
"default",
"=",
"str",
")",
"try",
":",
"return",
"cache",
"[",
"key",
"]",
"except",
"KeyError",
":",
"pass",
"# Drop out of the exception handler scope.",
"res",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cache",
"[",
"key",
"]",
"=",
"res",
"return",
"res",
"wrapper",
".",
"_wrapped",
"=",
"func",
"return",
"wrapper"
] | Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls. | [
"Cache",
"return",
"values",
"for",
"multiple",
"executions",
"of",
"func",
"+",
"args"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L61-L86 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | flush | def flush(key):
"""Flushes any entries from function cache where the
key is found in the function+args """
flush_list = []
for item in cache:
if key in item:
flush_list.append(item)
for item in flush_list:
del cache[item] | python | def flush(key):
"""Flushes any entries from function cache where the
key is found in the function+args """
flush_list = []
for item in cache:
if key in item:
flush_list.append(item)
for item in flush_list:
del cache[item] | [
"def",
"flush",
"(",
"key",
")",
":",
"flush_list",
"=",
"[",
"]",
"for",
"item",
"in",
"cache",
":",
"if",
"key",
"in",
"item",
":",
"flush_list",
".",
"append",
"(",
"item",
")",
"for",
"item",
"in",
"flush_list",
":",
"del",
"cache",
"[",
"item",
"]"
] | Flushes any entries from function cache where the
key is found in the function+args | [
"Flushes",
"any",
"entries",
"from",
"function",
"cache",
"where",
"the",
"key",
"is",
"found",
"in",
"the",
"function",
"+",
"args"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L89-L97 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | log | def log(message, level=None):
"""Write a message to the juju log"""
command = ['juju-log']
if level:
command += ['-l', level]
if not isinstance(message, six.string_types):
message = repr(message)
command += [message[:SH_MAX_ARG]]
# Missing juju-log should not cause failures in unit tests
# Send log output to stderr
try:
subprocess.call(command)
except OSError as e:
if e.errno == errno.ENOENT:
if level:
message = "{}: {}".format(level, message)
message = "juju-log: {}".format(message)
print(message, file=sys.stderr)
else:
raise | python | def log(message, level=None):
"""Write a message to the juju log"""
command = ['juju-log']
if level:
command += ['-l', level]
if not isinstance(message, six.string_types):
message = repr(message)
command += [message[:SH_MAX_ARG]]
# Missing juju-log should not cause failures in unit tests
# Send log output to stderr
try:
subprocess.call(command)
except OSError as e:
if e.errno == errno.ENOENT:
if level:
message = "{}: {}".format(level, message)
message = "juju-log: {}".format(message)
print(message, file=sys.stderr)
else:
raise | [
"def",
"log",
"(",
"message",
",",
"level",
"=",
"None",
")",
":",
"command",
"=",
"[",
"'juju-log'",
"]",
"if",
"level",
":",
"command",
"+=",
"[",
"'-l'",
",",
"level",
"]",
"if",
"not",
"isinstance",
"(",
"message",
",",
"six",
".",
"string_types",
")",
":",
"message",
"=",
"repr",
"(",
"message",
")",
"command",
"+=",
"[",
"message",
"[",
":",
"SH_MAX_ARG",
"]",
"]",
"# Missing juju-log should not cause failures in unit tests",
"# Send log output to stderr",
"try",
":",
"subprocess",
".",
"call",
"(",
"command",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"if",
"level",
":",
"message",
"=",
"\"{}: {}\"",
".",
"format",
"(",
"level",
",",
"message",
")",
"message",
"=",
"\"juju-log: {}\"",
".",
"format",
"(",
"message",
")",
"print",
"(",
"message",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"else",
":",
"raise"
] | Write a message to the juju log | [
"Write",
"a",
"message",
"to",
"the",
"juju",
"log"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L100-L119 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | execution_environment | def execution_environment():
"""A convenient bundling of the current execution context"""
context = {}
context['conf'] = config()
if relation_id():
context['reltype'] = relation_type()
context['relid'] = relation_id()
context['rel'] = relation_get()
context['unit'] = local_unit()
context['rels'] = relations()
context['env'] = os.environ
return context | python | def execution_environment():
"""A convenient bundling of the current execution context"""
context = {}
context['conf'] = config()
if relation_id():
context['reltype'] = relation_type()
context['relid'] = relation_id()
context['rel'] = relation_get()
context['unit'] = local_unit()
context['rels'] = relations()
context['env'] = os.environ
return context | [
"def",
"execution_environment",
"(",
")",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'conf'",
"]",
"=",
"config",
"(",
")",
"if",
"relation_id",
"(",
")",
":",
"context",
"[",
"'reltype'",
"]",
"=",
"relation_type",
"(",
")",
"context",
"[",
"'relid'",
"]",
"=",
"relation_id",
"(",
")",
"context",
"[",
"'rel'",
"]",
"=",
"relation_get",
"(",
")",
"context",
"[",
"'unit'",
"]",
"=",
"local_unit",
"(",
")",
"context",
"[",
"'rels'",
"]",
"=",
"relations",
"(",
")",
"context",
"[",
"'env'",
"]",
"=",
"os",
".",
"environ",
"return",
"context"
] | A convenient bundling of the current execution context | [
"A",
"convenient",
"bundling",
"of",
"the",
"current",
"execution",
"context"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L161-L172 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relation_id | def relation_id(relation_name=None, service_or_unit=None):
"""The relation ID for the current or a specified relation"""
if not relation_name and not service_or_unit:
return os.environ.get('JUJU_RELATION_ID', None)
elif relation_name and service_or_unit:
service_name = service_or_unit.split('/')[0]
for relid in relation_ids(relation_name):
remote_service = remote_service_name(relid)
if remote_service == service_name:
return relid
else:
raise ValueError('Must specify neither or both of relation_name and service_or_unit') | python | def relation_id(relation_name=None, service_or_unit=None):
"""The relation ID for the current or a specified relation"""
if not relation_name and not service_or_unit:
return os.environ.get('JUJU_RELATION_ID', None)
elif relation_name and service_or_unit:
service_name = service_or_unit.split('/')[0]
for relid in relation_ids(relation_name):
remote_service = remote_service_name(relid)
if remote_service == service_name:
return relid
else:
raise ValueError('Must specify neither or both of relation_name and service_or_unit') | [
"def",
"relation_id",
"(",
"relation_name",
"=",
"None",
",",
"service_or_unit",
"=",
"None",
")",
":",
"if",
"not",
"relation_name",
"and",
"not",
"service_or_unit",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"'JUJU_RELATION_ID'",
",",
"None",
")",
"elif",
"relation_name",
"and",
"service_or_unit",
":",
"service_name",
"=",
"service_or_unit",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"for",
"relid",
"in",
"relation_ids",
"(",
"relation_name",
")",
":",
"remote_service",
"=",
"remote_service_name",
"(",
"relid",
")",
"if",
"remote_service",
"==",
"service_name",
":",
"return",
"relid",
"else",
":",
"raise",
"ValueError",
"(",
"'Must specify neither or both of relation_name and service_or_unit'",
")"
] | The relation ID for the current or a specified relation | [
"The",
"relation",
"ID",
"for",
"the",
"current",
"or",
"a",
"specified",
"relation"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L186-L197 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | principal_unit | def principal_unit():
"""Returns the principal unit of this unit, otherwise None"""
# Juju 2.2 and above provides JUJU_PRINCIPAL_UNIT
principal_unit = os.environ.get('JUJU_PRINCIPAL_UNIT', None)
# If it's empty, then this unit is the principal
if principal_unit == '':
return os.environ['JUJU_UNIT_NAME']
elif principal_unit is not None:
return principal_unit
# For Juju 2.1 and below, let's try work out the principle unit by
# the various charms' metadata.yaml.
for reltype in relation_types():
for rid in relation_ids(reltype):
for unit in related_units(rid):
md = _metadata_unit(unit)
if not md:
continue
subordinate = md.pop('subordinate', None)
if not subordinate:
return unit
return None | python | def principal_unit():
"""Returns the principal unit of this unit, otherwise None"""
# Juju 2.2 and above provides JUJU_PRINCIPAL_UNIT
principal_unit = os.environ.get('JUJU_PRINCIPAL_UNIT', None)
# If it's empty, then this unit is the principal
if principal_unit == '':
return os.environ['JUJU_UNIT_NAME']
elif principal_unit is not None:
return principal_unit
# For Juju 2.1 and below, let's try work out the principle unit by
# the various charms' metadata.yaml.
for reltype in relation_types():
for rid in relation_ids(reltype):
for unit in related_units(rid):
md = _metadata_unit(unit)
if not md:
continue
subordinate = md.pop('subordinate', None)
if not subordinate:
return unit
return None | [
"def",
"principal_unit",
"(",
")",
":",
"# Juju 2.2 and above provides JUJU_PRINCIPAL_UNIT",
"principal_unit",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'JUJU_PRINCIPAL_UNIT'",
",",
"None",
")",
"# If it's empty, then this unit is the principal",
"if",
"principal_unit",
"==",
"''",
":",
"return",
"os",
".",
"environ",
"[",
"'JUJU_UNIT_NAME'",
"]",
"elif",
"principal_unit",
"is",
"not",
"None",
":",
"return",
"principal_unit",
"# For Juju 2.1 and below, let's try work out the principle unit by",
"# the various charms' metadata.yaml.",
"for",
"reltype",
"in",
"relation_types",
"(",
")",
":",
"for",
"rid",
"in",
"relation_ids",
"(",
"reltype",
")",
":",
"for",
"unit",
"in",
"related_units",
"(",
"rid",
")",
":",
"md",
"=",
"_metadata_unit",
"(",
"unit",
")",
"if",
"not",
"md",
":",
"continue",
"subordinate",
"=",
"md",
".",
"pop",
"(",
"'subordinate'",
",",
"None",
")",
"if",
"not",
"subordinate",
":",
"return",
"unit",
"return",
"None"
] | Returns the principal unit of this unit, otherwise None | [
"Returns",
"the",
"principal",
"unit",
"of",
"this",
"unit",
"otherwise",
"None"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L239-L259 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relation_get | def relation_get(attribute=None, unit=None, rid=None):
"""Get relation information"""
_args = ['relation-get', '--format=json']
if rid:
_args.append('-r')
_args.append(rid)
_args.append(attribute or '-')
if unit:
_args.append(unit)
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
except CalledProcessError as e:
if e.returncode == 2:
return None
raise | python | def relation_get(attribute=None, unit=None, rid=None):
"""Get relation information"""
_args = ['relation-get', '--format=json']
if rid:
_args.append('-r')
_args.append(rid)
_args.append(attribute or '-')
if unit:
_args.append(unit)
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
except CalledProcessError as e:
if e.returncode == 2:
return None
raise | [
"def",
"relation_get",
"(",
"attribute",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"rid",
"=",
"None",
")",
":",
"_args",
"=",
"[",
"'relation-get'",
",",
"'--format=json'",
"]",
"if",
"rid",
":",
"_args",
".",
"append",
"(",
"'-r'",
")",
"_args",
".",
"append",
"(",
"rid",
")",
"_args",
".",
"append",
"(",
"attribute",
"or",
"'-'",
")",
"if",
"unit",
":",
"_args",
".",
"append",
"(",
"unit",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"_args",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"except",
"ValueError",
":",
"return",
"None",
"except",
"CalledProcessError",
"as",
"e",
":",
"if",
"e",
".",
"returncode",
"==",
"2",
":",
"return",
"None",
"raise"
] | Get relation information | [
"Get",
"relation",
"information"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L429-L445 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relation_set | def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit()) | python | def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit()) | [
"def",
"relation_set",
"(",
"relation_id",
"=",
"None",
",",
"relation_settings",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"relation_settings",
"=",
"relation_settings",
"if",
"relation_settings",
"else",
"{",
"}",
"relation_cmd_line",
"=",
"[",
"'relation-set'",
"]",
"accepts_file",
"=",
"\"--file\"",
"in",
"subprocess",
".",
"check_output",
"(",
"relation_cmd_line",
"+",
"[",
"\"--help\"",
"]",
",",
"universal_newlines",
"=",
"True",
")",
"if",
"relation_id",
"is",
"not",
"None",
":",
"relation_cmd_line",
".",
"extend",
"(",
"(",
"'-r'",
",",
"relation_id",
")",
")",
"settings",
"=",
"relation_settings",
".",
"copy",
"(",
")",
"settings",
".",
"update",
"(",
"kwargs",
")",
"for",
"key",
",",
"value",
"in",
"settings",
".",
"items",
"(",
")",
":",
"# Force value to be a string: it always should, but some call",
"# sites pass in things like dicts or numbers.",
"if",
"value",
"is",
"not",
"None",
":",
"settings",
"[",
"key",
"]",
"=",
"\"{}\"",
".",
"format",
"(",
"value",
")",
"if",
"accepts_file",
":",
"# --file was introduced in Juju 1.23.2. Use it by default if",
"# available, since otherwise we'll break if the relation data is",
"# too big. Ideally we should tell relation-set to read the data from",
"# stdin, but that feature is broken in 1.23.2: Bug #1454678.",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"as",
"settings_file",
":",
"settings_file",
".",
"write",
"(",
"yaml",
".",
"safe_dump",
"(",
"settings",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"subprocess",
".",
"check_call",
"(",
"relation_cmd_line",
"+",
"[",
"\"--file\"",
",",
"settings_file",
".",
"name",
"]",
")",
"os",
".",
"remove",
"(",
"settings_file",
".",
"name",
")",
"else",
":",
"for",
"key",
",",
"value",
"in",
"settings",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"relation_cmd_line",
".",
"append",
"(",
"'{}='",
".",
"format",
"(",
"key",
")",
")",
"else",
":",
"relation_cmd_line",
".",
"append",
"(",
"'{}={}'",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"subprocess",
".",
"check_call",
"(",
"relation_cmd_line",
")",
"# Flush cache of any relation-gets for local unit",
"flush",
"(",
"local_unit",
"(",
")",
")"
] | Set relation information for the current unit | [
"Set",
"relation",
"information",
"for",
"the",
"current",
"unit"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L448-L481 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relation_clear | def relation_clear(r_id=None):
''' Clears any relation data already set on relation r_id '''
settings = relation_get(rid=r_id,
unit=local_unit())
for setting in settings:
if setting not in ['public-address', 'private-address']:
settings[setting] = None
relation_set(relation_id=r_id,
**settings) | python | def relation_clear(r_id=None):
''' Clears any relation data already set on relation r_id '''
settings = relation_get(rid=r_id,
unit=local_unit())
for setting in settings:
if setting not in ['public-address', 'private-address']:
settings[setting] = None
relation_set(relation_id=r_id,
**settings) | [
"def",
"relation_clear",
"(",
"r_id",
"=",
"None",
")",
":",
"settings",
"=",
"relation_get",
"(",
"rid",
"=",
"r_id",
",",
"unit",
"=",
"local_unit",
"(",
")",
")",
"for",
"setting",
"in",
"settings",
":",
"if",
"setting",
"not",
"in",
"[",
"'public-address'",
",",
"'private-address'",
"]",
":",
"settings",
"[",
"setting",
"]",
"=",
"None",
"relation_set",
"(",
"relation_id",
"=",
"r_id",
",",
"*",
"*",
"settings",
")"
] | Clears any relation data already set on relation r_id | [
"Clears",
"any",
"relation",
"data",
"already",
"set",
"on",
"relation",
"r_id"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L484-L492 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relation_ids | def relation_ids(reltype=None):
"""A list of relation_ids"""
reltype = reltype or relation_type()
relid_cmd_line = ['relation-ids', '--format=json']
if reltype is not None:
relid_cmd_line.append(reltype)
return json.loads(
subprocess.check_output(relid_cmd_line).decode('UTF-8')) or []
return [] | python | def relation_ids(reltype=None):
"""A list of relation_ids"""
reltype = reltype or relation_type()
relid_cmd_line = ['relation-ids', '--format=json']
if reltype is not None:
relid_cmd_line.append(reltype)
return json.loads(
subprocess.check_output(relid_cmd_line).decode('UTF-8')) or []
return [] | [
"def",
"relation_ids",
"(",
"reltype",
"=",
"None",
")",
":",
"reltype",
"=",
"reltype",
"or",
"relation_type",
"(",
")",
"relid_cmd_line",
"=",
"[",
"'relation-ids'",
",",
"'--format=json'",
"]",
"if",
"reltype",
"is",
"not",
"None",
":",
"relid_cmd_line",
".",
"append",
"(",
"reltype",
")",
"return",
"json",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"relid_cmd_line",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"or",
"[",
"]",
"return",
"[",
"]"
] | A list of relation_ids | [
"A",
"list",
"of",
"relation_ids"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L496-L504 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | related_units | def related_units(relid=None):
"""A list of related units"""
relid = relid or relation_id()
units_cmd_line = ['relation-list', '--format=json']
if relid is not None:
units_cmd_line.extend(('-r', relid))
return json.loads(
subprocess.check_output(units_cmd_line).decode('UTF-8')) or [] | python | def related_units(relid=None):
"""A list of related units"""
relid = relid or relation_id()
units_cmd_line = ['relation-list', '--format=json']
if relid is not None:
units_cmd_line.extend(('-r', relid))
return json.loads(
subprocess.check_output(units_cmd_line).decode('UTF-8')) or [] | [
"def",
"related_units",
"(",
"relid",
"=",
"None",
")",
":",
"relid",
"=",
"relid",
"or",
"relation_id",
"(",
")",
"units_cmd_line",
"=",
"[",
"'relation-list'",
",",
"'--format=json'",
"]",
"if",
"relid",
"is",
"not",
"None",
":",
"units_cmd_line",
".",
"extend",
"(",
"(",
"'-r'",
",",
"relid",
")",
")",
"return",
"json",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"units_cmd_line",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"or",
"[",
"]"
] | A list of related units | [
"A",
"list",
"of",
"related",
"units"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L508-L515 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.