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/core/hookenv.py | expected_peer_units | def expected_peer_units():
"""Get a generator for units we expect to join peer relation based on
goal-state.
The local unit is excluded from the result to make it easy to gauge
completion of all peers joining the relation with existing hook tools.
Example usage:
log('peer {} of {} joined peer relation'
.format(len(related_units()),
len(list(expected_peer_units()))))
This function will raise NotImplementedError if used with juju versions
without goal-state support.
:returns: iterator
:rtype: types.GeneratorType
:raises: NotImplementedError
"""
if not has_juju_version("2.4.0"):
# goal-state first appeared in 2.4.0.
raise NotImplementedError("goal-state")
_goal_state = goal_state()
return (key for key in _goal_state['units']
if '/' in key and key != local_unit()) | python | def expected_peer_units():
"""Get a generator for units we expect to join peer relation based on
goal-state.
The local unit is excluded from the result to make it easy to gauge
completion of all peers joining the relation with existing hook tools.
Example usage:
log('peer {} of {} joined peer relation'
.format(len(related_units()),
len(list(expected_peer_units()))))
This function will raise NotImplementedError if used with juju versions
without goal-state support.
:returns: iterator
:rtype: types.GeneratorType
:raises: NotImplementedError
"""
if not has_juju_version("2.4.0"):
# goal-state first appeared in 2.4.0.
raise NotImplementedError("goal-state")
_goal_state = goal_state()
return (key for key in _goal_state['units']
if '/' in key and key != local_unit()) | [
"def",
"expected_peer_units",
"(",
")",
":",
"if",
"not",
"has_juju_version",
"(",
"\"2.4.0\"",
")",
":",
"# goal-state first appeared in 2.4.0.",
"raise",
"NotImplementedError",
"(",
"\"goal-state\"",
")",
"_goal_state",
"=",
"goal_state",
"(",
")",
"return",
"(",
"key",
"for",
"key",
"in",
"_goal_state",
"[",
"'units'",
"]",
"if",
"'/'",
"in",
"key",
"and",
"key",
"!=",
"local_unit",
"(",
")",
")"
] | Get a generator for units we expect to join peer relation based on
goal-state.
The local unit is excluded from the result to make it easy to gauge
completion of all peers joining the relation with existing hook tools.
Example usage:
log('peer {} of {} joined peer relation'
.format(len(related_units()),
len(list(expected_peer_units()))))
This function will raise NotImplementedError if used with juju versions
without goal-state support.
:returns: iterator
:rtype: types.GeneratorType
:raises: NotImplementedError | [
"Get",
"a",
"generator",
"for",
"units",
"we",
"expect",
"to",
"join",
"peer",
"relation",
"based",
"on",
"goal",
"-",
"state",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L518-L542 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | expected_related_units | def expected_related_units(reltype=None):
"""Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
relation type for which juju goal-state does not have information. It will
raise NotImplementedError if used with juju versions without goal-state
support.
Example usage:
log('participant {} of {} joined relation {}'
.format(len(related_units()),
len(list(expected_related_units())),
relation_type()))
:param reltype: Relation type to list data for, default is to list data for
the realtion type we are currently executing a hook for.
:type reltype: str
:returns: iterator
:rtype: types.GeneratorType
:raises: KeyError, NotImplementedError
"""
if not has_juju_version("2.4.4"):
# goal-state existed in 2.4.0, but did not list individual units to
# join a relation in 2.4.1 through 2.4.3. (LP: #1794739)
raise NotImplementedError("goal-state relation unit count")
reltype = reltype or relation_type()
_goal_state = goal_state()
return (key for key in _goal_state['relations'][reltype] if '/' in key) | python | def expected_related_units(reltype=None):
"""Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
relation type for which juju goal-state does not have information. It will
raise NotImplementedError if used with juju versions without goal-state
support.
Example usage:
log('participant {} of {} joined relation {}'
.format(len(related_units()),
len(list(expected_related_units())),
relation_type()))
:param reltype: Relation type to list data for, default is to list data for
the realtion type we are currently executing a hook for.
:type reltype: str
:returns: iterator
:rtype: types.GeneratorType
:raises: KeyError, NotImplementedError
"""
if not has_juju_version("2.4.4"):
# goal-state existed in 2.4.0, but did not list individual units to
# join a relation in 2.4.1 through 2.4.3. (LP: #1794739)
raise NotImplementedError("goal-state relation unit count")
reltype = reltype or relation_type()
_goal_state = goal_state()
return (key for key in _goal_state['relations'][reltype] if '/' in key) | [
"def",
"expected_related_units",
"(",
"reltype",
"=",
"None",
")",
":",
"if",
"not",
"has_juju_version",
"(",
"\"2.4.4\"",
")",
":",
"# goal-state existed in 2.4.0, but did not list individual units to",
"# join a relation in 2.4.1 through 2.4.3. (LP: #1794739)",
"raise",
"NotImplementedError",
"(",
"\"goal-state relation unit count\"",
")",
"reltype",
"=",
"reltype",
"or",
"relation_type",
"(",
")",
"_goal_state",
"=",
"goal_state",
"(",
")",
"return",
"(",
"key",
"for",
"key",
"in",
"_goal_state",
"[",
"'relations'",
"]",
"[",
"reltype",
"]",
"if",
"'/'",
"in",
"key",
")"
] | Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
relation type for which juju goal-state does not have information. It will
raise NotImplementedError if used with juju versions without goal-state
support.
Example usage:
log('participant {} of {} joined relation {}'
.format(len(related_units()),
len(list(expected_related_units())),
relation_type()))
:param reltype: Relation type to list data for, default is to list data for
the realtion type we are currently executing a hook for.
:type reltype: str
:returns: iterator
:rtype: types.GeneratorType
:raises: KeyError, NotImplementedError | [
"Get",
"a",
"generator",
"for",
"units",
"we",
"expect",
"to",
"join",
"relation",
"based",
"on",
"goal",
"-",
"state",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L545-L576 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relation_for_unit | def relation_for_unit(unit=None, rid=None):
"""Get the json represenation of a unit's relation"""
unit = unit or remote_unit()
relation = relation_get(unit=unit, rid=rid)
for key in relation:
if key.endswith('-list'):
relation[key] = relation[key].split()
relation['__unit__'] = unit
return relation | python | def relation_for_unit(unit=None, rid=None):
"""Get the json represenation of a unit's relation"""
unit = unit or remote_unit()
relation = relation_get(unit=unit, rid=rid)
for key in relation:
if key.endswith('-list'):
relation[key] = relation[key].split()
relation['__unit__'] = unit
return relation | [
"def",
"relation_for_unit",
"(",
"unit",
"=",
"None",
",",
"rid",
"=",
"None",
")",
":",
"unit",
"=",
"unit",
"or",
"remote_unit",
"(",
")",
"relation",
"=",
"relation_get",
"(",
"unit",
"=",
"unit",
",",
"rid",
"=",
"rid",
")",
"for",
"key",
"in",
"relation",
":",
"if",
"key",
".",
"endswith",
"(",
"'-list'",
")",
":",
"relation",
"[",
"key",
"]",
"=",
"relation",
"[",
"key",
"]",
".",
"split",
"(",
")",
"relation",
"[",
"'__unit__'",
"]",
"=",
"unit",
"return",
"relation"
] | Get the json represenation of a unit's relation | [
"Get",
"the",
"json",
"represenation",
"of",
"a",
"unit",
"s",
"relation"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L580-L588 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relations_for_id | def relations_for_id(relid=None):
"""Get relations of a specific relation ID"""
relation_data = []
relid = relid or relation_ids()
for unit in related_units(relid):
unit_data = relation_for_unit(unit, relid)
unit_data['__relid__'] = relid
relation_data.append(unit_data)
return relation_data | python | def relations_for_id(relid=None):
"""Get relations of a specific relation ID"""
relation_data = []
relid = relid or relation_ids()
for unit in related_units(relid):
unit_data = relation_for_unit(unit, relid)
unit_data['__relid__'] = relid
relation_data.append(unit_data)
return relation_data | [
"def",
"relations_for_id",
"(",
"relid",
"=",
"None",
")",
":",
"relation_data",
"=",
"[",
"]",
"relid",
"=",
"relid",
"or",
"relation_ids",
"(",
")",
"for",
"unit",
"in",
"related_units",
"(",
"relid",
")",
":",
"unit_data",
"=",
"relation_for_unit",
"(",
"unit",
",",
"relid",
")",
"unit_data",
"[",
"'__relid__'",
"]",
"=",
"relid",
"relation_data",
".",
"append",
"(",
"unit_data",
")",
"return",
"relation_data"
] | Get relations of a specific relation ID | [
"Get",
"relations",
"of",
"a",
"specific",
"relation",
"ID"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L592-L600 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relations_of_type | def relations_of_type(reltype=None):
"""Get relations of a specific type"""
relation_data = []
reltype = reltype or relation_type()
for relid in relation_ids(reltype):
for relation in relations_for_id(relid):
relation['__relid__'] = relid
relation_data.append(relation)
return relation_data | python | def relations_of_type(reltype=None):
"""Get relations of a specific type"""
relation_data = []
reltype = reltype or relation_type()
for relid in relation_ids(reltype):
for relation in relations_for_id(relid):
relation['__relid__'] = relid
relation_data.append(relation)
return relation_data | [
"def",
"relations_of_type",
"(",
"reltype",
"=",
"None",
")",
":",
"relation_data",
"=",
"[",
"]",
"reltype",
"=",
"reltype",
"or",
"relation_type",
"(",
")",
"for",
"relid",
"in",
"relation_ids",
"(",
"reltype",
")",
":",
"for",
"relation",
"in",
"relations_for_id",
"(",
"relid",
")",
":",
"relation",
"[",
"'__relid__'",
"]",
"=",
"relid",
"relation_data",
".",
"append",
"(",
"relation",
")",
"return",
"relation_data"
] | Get relations of a specific type | [
"Get",
"relations",
"of",
"a",
"specific",
"type"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L604-L612 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | metadata | def metadata():
"""Get the current charm metadata.yaml contents as a python object"""
with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:
return yaml.safe_load(md) | python | def metadata():
"""Get the current charm metadata.yaml contents as a python object"""
with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:
return yaml.safe_load(md) | [
"def",
"metadata",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"charm_dir",
"(",
")",
",",
"'metadata.yaml'",
")",
")",
"as",
"md",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"md",
")"
] | Get the current charm metadata.yaml contents as a python object | [
"Get",
"the",
"current",
"charm",
"metadata",
".",
"yaml",
"contents",
"as",
"a",
"python",
"object"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L616-L619 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relation_types | def relation_types():
"""Get a list of relation types supported by this charm"""
rel_types = []
md = metadata()
for key in ('provides', 'requires', 'peers'):
section = md.get(key)
if section:
rel_types.extend(section.keys())
return rel_types | python | def relation_types():
"""Get a list of relation types supported by this charm"""
rel_types = []
md = metadata()
for key in ('provides', 'requires', 'peers'):
section = md.get(key)
if section:
rel_types.extend(section.keys())
return rel_types | [
"def",
"relation_types",
"(",
")",
":",
"rel_types",
"=",
"[",
"]",
"md",
"=",
"metadata",
"(",
")",
"for",
"key",
"in",
"(",
"'provides'",
",",
"'requires'",
",",
"'peers'",
")",
":",
"section",
"=",
"md",
".",
"get",
"(",
"key",
")",
"if",
"section",
":",
"rel_types",
".",
"extend",
"(",
"section",
".",
"keys",
"(",
")",
")",
"return",
"rel_types"
] | Get a list of relation types supported by this charm | [
"Get",
"a",
"list",
"of",
"relation",
"types",
"supported",
"by",
"this",
"charm"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L641-L649 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | peer_relation_id | def peer_relation_id():
'''Get the peers relation id if a peers relation has been joined, else None.'''
md = metadata()
section = md.get('peers')
if section:
for key in section:
relids = relation_ids(key)
if relids:
return relids[0]
return None | python | def peer_relation_id():
'''Get the peers relation id if a peers relation has been joined, else None.'''
md = metadata()
section = md.get('peers')
if section:
for key in section:
relids = relation_ids(key)
if relids:
return relids[0]
return None | [
"def",
"peer_relation_id",
"(",
")",
":",
"md",
"=",
"metadata",
"(",
")",
"section",
"=",
"md",
".",
"get",
"(",
"'peers'",
")",
"if",
"section",
":",
"for",
"key",
"in",
"section",
":",
"relids",
"=",
"relation_ids",
"(",
"key",
")",
"if",
"relids",
":",
"return",
"relids",
"[",
"0",
"]",
"return",
"None"
] | Get the peers relation id if a peers relation has been joined, else None. | [
"Get",
"the",
"peers",
"relation",
"id",
"if",
"a",
"peers",
"relation",
"has",
"been",
"joined",
"else",
"None",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L653-L662 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | interface_to_relations | def interface_to_relations(interface_name):
"""
Given an interface, return a list of relation names for the current
charm that use that interface.
:returns: A list of relation names.
"""
results = []
for role in ('provides', 'requires', 'peers'):
results.extend(role_and_interface_to_relations(role, interface_name))
return results | python | def interface_to_relations(interface_name):
"""
Given an interface, return a list of relation names for the current
charm that use that interface.
:returns: A list of relation names.
"""
results = []
for role in ('provides', 'requires', 'peers'):
results.extend(role_and_interface_to_relations(role, interface_name))
return results | [
"def",
"interface_to_relations",
"(",
"interface_name",
")",
":",
"results",
"=",
"[",
"]",
"for",
"role",
"in",
"(",
"'provides'",
",",
"'requires'",
",",
"'peers'",
")",
":",
"results",
".",
"extend",
"(",
"role_and_interface_to_relations",
"(",
"role",
",",
"interface_name",
")",
")",
"return",
"results"
] | Given an interface, return a list of relation names for the current
charm that use that interface.
:returns: A list of relation names. | [
"Given",
"an",
"interface",
"return",
"a",
"list",
"of",
"relation",
"names",
"for",
"the",
"current",
"charm",
"that",
"use",
"that",
"interface",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L709-L719 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | relations | def relations():
"""Get a nested dictionary of relation data for all related units"""
rels = {}
for reltype in relation_types():
relids = {}
for relid in relation_ids(reltype):
units = {local_unit(): relation_get(unit=local_unit(), rid=relid)}
for unit in related_units(relid):
reldata = relation_get(unit=unit, rid=relid)
units[unit] = reldata
relids[relid] = units
rels[reltype] = relids
return rels | python | def relations():
"""Get a nested dictionary of relation data for all related units"""
rels = {}
for reltype in relation_types():
relids = {}
for relid in relation_ids(reltype):
units = {local_unit(): relation_get(unit=local_unit(), rid=relid)}
for unit in related_units(relid):
reldata = relation_get(unit=unit, rid=relid)
units[unit] = reldata
relids[relid] = units
rels[reltype] = relids
return rels | [
"def",
"relations",
"(",
")",
":",
"rels",
"=",
"{",
"}",
"for",
"reltype",
"in",
"relation_types",
"(",
")",
":",
"relids",
"=",
"{",
"}",
"for",
"relid",
"in",
"relation_ids",
"(",
"reltype",
")",
":",
"units",
"=",
"{",
"local_unit",
"(",
")",
":",
"relation_get",
"(",
"unit",
"=",
"local_unit",
"(",
")",
",",
"rid",
"=",
"relid",
")",
"}",
"for",
"unit",
"in",
"related_units",
"(",
"relid",
")",
":",
"reldata",
"=",
"relation_get",
"(",
"unit",
"=",
"unit",
",",
"rid",
"=",
"relid",
")",
"units",
"[",
"unit",
"]",
"=",
"reldata",
"relids",
"[",
"relid",
"]",
"=",
"units",
"rels",
"[",
"reltype",
"]",
"=",
"relids",
"return",
"rels"
] | Get a nested dictionary of relation data for all related units | [
"Get",
"a",
"nested",
"dictionary",
"of",
"relation",
"data",
"for",
"all",
"related",
"units"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L729-L741 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | _port_op | def _port_op(op_name, port, protocol="TCP"):
"""Open or close a service network port"""
_args = [op_name]
icmp = protocol.upper() == "ICMP"
if icmp:
_args.append(protocol)
else:
_args.append('{}/{}'.format(port, protocol))
try:
subprocess.check_call(_args)
except subprocess.CalledProcessError:
# Older Juju pre 2.3 doesn't support ICMP
# so treat it as a no-op if it fails.
if not icmp:
raise | python | def _port_op(op_name, port, protocol="TCP"):
"""Open or close a service network port"""
_args = [op_name]
icmp = protocol.upper() == "ICMP"
if icmp:
_args.append(protocol)
else:
_args.append('{}/{}'.format(port, protocol))
try:
subprocess.check_call(_args)
except subprocess.CalledProcessError:
# Older Juju pre 2.3 doesn't support ICMP
# so treat it as a no-op if it fails.
if not icmp:
raise | [
"def",
"_port_op",
"(",
"op_name",
",",
"port",
",",
"protocol",
"=",
"\"TCP\"",
")",
":",
"_args",
"=",
"[",
"op_name",
"]",
"icmp",
"=",
"protocol",
".",
"upper",
"(",
")",
"==",
"\"ICMP\"",
"if",
"icmp",
":",
"_args",
".",
"append",
"(",
"protocol",
")",
"else",
":",
"_args",
".",
"append",
"(",
"'{}/{}'",
".",
"format",
"(",
"port",
",",
"protocol",
")",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"_args",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"# Older Juju pre 2.3 doesn't support ICMP",
"# so treat it as a no-op if it fails.",
"if",
"not",
"icmp",
":",
"raise"
] | Open or close a service network port | [
"Open",
"or",
"close",
"a",
"service",
"network",
"port"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L764-L778 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | open_ports | def open_ports(start, end, protocol="TCP"):
"""Opens a range of service network ports"""
_args = ['open-port']
_args.append('{}-{}/{}'.format(start, end, protocol))
subprocess.check_call(_args) | python | def open_ports(start, end, protocol="TCP"):
"""Opens a range of service network ports"""
_args = ['open-port']
_args.append('{}-{}/{}'.format(start, end, protocol))
subprocess.check_call(_args) | [
"def",
"open_ports",
"(",
"start",
",",
"end",
",",
"protocol",
"=",
"\"TCP\"",
")",
":",
"_args",
"=",
"[",
"'open-port'",
"]",
"_args",
".",
"append",
"(",
"'{}-{}/{}'",
".",
"format",
"(",
"start",
",",
"end",
",",
"protocol",
")",
")",
"subprocess",
".",
"check_call",
"(",
"_args",
")"
] | Opens a range of service network ports | [
"Opens",
"a",
"range",
"of",
"service",
"network",
"ports"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L791-L795 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | unit_get | def unit_get(attribute):
"""Get the unit ID for the remote unit"""
_args = ['unit-get', '--format=json', attribute]
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None | python | def unit_get(attribute):
"""Get the unit ID for the remote unit"""
_args = ['unit-get', '--format=json', attribute]
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None | [
"def",
"unit_get",
"(",
"attribute",
")",
":",
"_args",
"=",
"[",
"'unit-get'",
",",
"'--format=json'",
",",
"attribute",
"]",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"_args",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"except",
"ValueError",
":",
"return",
"None"
] | Get the unit ID for the remote unit | [
"Get",
"the",
"unit",
"ID",
"for",
"the",
"remote",
"unit"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L817-L823 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | storage_get | def storage_get(attribute=None, storage_id=None):
"""Get storage attributes"""
_args = ['storage-get', '--format=json']
if storage_id:
_args.extend(('-s', storage_id))
if attribute:
_args.append(attribute)
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None | python | def storage_get(attribute=None, storage_id=None):
"""Get storage attributes"""
_args = ['storage-get', '--format=json']
if storage_id:
_args.extend(('-s', storage_id))
if attribute:
_args.append(attribute)
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None | [
"def",
"storage_get",
"(",
"attribute",
"=",
"None",
",",
"storage_id",
"=",
"None",
")",
":",
"_args",
"=",
"[",
"'storage-get'",
",",
"'--format=json'",
"]",
"if",
"storage_id",
":",
"_args",
".",
"extend",
"(",
"(",
"'-s'",
",",
"storage_id",
")",
")",
"if",
"attribute",
":",
"_args",
".",
"append",
"(",
"attribute",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"_args",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"except",
"ValueError",
":",
"return",
"None"
] | Get storage attributes | [
"Get",
"storage",
"attributes"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L837-L847 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | storage_list | def storage_list(storage_name=None):
"""List the storage IDs for the unit"""
_args = ['storage-list', '--format=json']
if storage_name:
_args.append(storage_name)
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
except OSError as e:
import errno
if e.errno == errno.ENOENT:
# storage-list does not exist
return []
raise | python | def storage_list(storage_name=None):
"""List the storage IDs for the unit"""
_args = ['storage-list', '--format=json']
if storage_name:
_args.append(storage_name)
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
except OSError as e:
import errno
if e.errno == errno.ENOENT:
# storage-list does not exist
return []
raise | [
"def",
"storage_list",
"(",
"storage_name",
"=",
"None",
")",
":",
"_args",
"=",
"[",
"'storage-list'",
",",
"'--format=json'",
"]",
"if",
"storage_name",
":",
"_args",
".",
"append",
"(",
"storage_name",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"_args",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"except",
"ValueError",
":",
"return",
"None",
"except",
"OSError",
"as",
"e",
":",
"import",
"errno",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"# storage-list does not exist",
"return",
"[",
"]",
"raise"
] | List the storage IDs for the unit | [
"List",
"the",
"storage",
"IDs",
"for",
"the",
"unit"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L851-L865 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | charm_dir | def charm_dir():
"""Return the root directory of the current charm"""
d = os.environ.get('JUJU_CHARM_DIR')
if d is not None:
return d
return os.environ.get('CHARM_DIR') | python | def charm_dir():
"""Return the root directory of the current charm"""
d = os.environ.get('JUJU_CHARM_DIR')
if d is not None:
return d
return os.environ.get('CHARM_DIR') | [
"def",
"charm_dir",
"(",
")",
":",
"d",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'JUJU_CHARM_DIR'",
")",
"if",
"d",
"is",
"not",
"None",
":",
"return",
"d",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"'CHARM_DIR'",
")"
] | Return the root directory of the current charm | [
"Return",
"the",
"root",
"directory",
"of",
"the",
"current",
"charm"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L941-L946 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | action_set | def action_set(values):
"""Sets the values to be returned after the action finishes"""
cmd = ['action-set']
for k, v in list(values.items()):
cmd.append('{}={}'.format(k, v))
subprocess.check_call(cmd) | python | def action_set(values):
"""Sets the values to be returned after the action finishes"""
cmd = ['action-set']
for k, v in list(values.items()):
cmd.append('{}={}'.format(k, v))
subprocess.check_call(cmd) | [
"def",
"action_set",
"(",
"values",
")",
":",
"cmd",
"=",
"[",
"'action-set'",
"]",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"values",
".",
"items",
"(",
")",
")",
":",
"cmd",
".",
"append",
"(",
"'{}={}'",
".",
"format",
"(",
"k",
",",
"v",
")",
")",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] | Sets the values to be returned after the action finishes | [
"Sets",
"the",
"values",
"to",
"be",
"returned",
"after",
"the",
"action",
"finishes"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L960-L965 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | status_set | def status_set(workload_state, message):
"""Set the workload state with a message
Use status-set to set the workload state with a message which is visible
to the user via juju status. If the status-set command is not found then
assume this is juju < 1.23 and juju-log the message unstead.
workload_state -- valid juju workload state.
message -- status update message
"""
valid_states = ['maintenance', 'blocked', 'waiting', 'active']
if workload_state not in valid_states:
raise ValueError(
'{!r} is not a valid workload state'.format(workload_state)
)
cmd = ['status-set', workload_state, message]
try:
ret = subprocess.call(cmd)
if ret == 0:
return
except OSError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'status-set failed: {} {}'.format(workload_state,
message)
log(log_message, level='INFO') | python | def status_set(workload_state, message):
"""Set the workload state with a message
Use status-set to set the workload state with a message which is visible
to the user via juju status. If the status-set command is not found then
assume this is juju < 1.23 and juju-log the message unstead.
workload_state -- valid juju workload state.
message -- status update message
"""
valid_states = ['maintenance', 'blocked', 'waiting', 'active']
if workload_state not in valid_states:
raise ValueError(
'{!r} is not a valid workload state'.format(workload_state)
)
cmd = ['status-set', workload_state, message]
try:
ret = subprocess.call(cmd)
if ret == 0:
return
except OSError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'status-set failed: {} {}'.format(workload_state,
message)
log(log_message, level='INFO') | [
"def",
"status_set",
"(",
"workload_state",
",",
"message",
")",
":",
"valid_states",
"=",
"[",
"'maintenance'",
",",
"'blocked'",
",",
"'waiting'",
",",
"'active'",
"]",
"if",
"workload_state",
"not",
"in",
"valid_states",
":",
"raise",
"ValueError",
"(",
"'{!r} is not a valid workload state'",
".",
"format",
"(",
"workload_state",
")",
")",
"cmd",
"=",
"[",
"'status-set'",
",",
"workload_state",
",",
"message",
"]",
"try",
":",
"ret",
"=",
"subprocess",
".",
"call",
"(",
"cmd",
")",
"if",
"ret",
"==",
"0",
":",
"return",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"log_message",
"=",
"'status-set failed: {} {}'",
".",
"format",
"(",
"workload_state",
",",
"message",
")",
"log",
"(",
"log_message",
",",
"level",
"=",
"'INFO'",
")"
] | Set the workload state with a message
Use status-set to set the workload state with a message which is visible
to the user via juju status. If the status-set command is not found then
assume this is juju < 1.23 and juju-log the message unstead.
workload_state -- valid juju workload state.
message -- status update message | [
"Set",
"the",
"workload",
"state",
"with",
"a",
"message"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L990-L1015 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | status_get | def status_get():
"""Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', ""
"""
cmd = ['status-get', "--format=json", "--include-data"]
try:
raw_status = subprocess.check_output(cmd)
except OSError as e:
if e.errno == errno.ENOENT:
return ('unknown', "")
else:
raise
else:
status = json.loads(raw_status.decode("UTF-8"))
return (status["status"], status["message"]) | python | def status_get():
"""Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', ""
"""
cmd = ['status-get', "--format=json", "--include-data"]
try:
raw_status = subprocess.check_output(cmd)
except OSError as e:
if e.errno == errno.ENOENT:
return ('unknown', "")
else:
raise
else:
status = json.loads(raw_status.decode("UTF-8"))
return (status["status"], status["message"]) | [
"def",
"status_get",
"(",
")",
":",
"cmd",
"=",
"[",
"'status-get'",
",",
"\"--format=json\"",
",",
"\"--include-data\"",
"]",
"try",
":",
"raw_status",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"(",
"'unknown'",
",",
"\"\"",
")",
"else",
":",
"raise",
"else",
":",
"status",
"=",
"json",
".",
"loads",
"(",
"raw_status",
".",
"decode",
"(",
"\"UTF-8\"",
")",
")",
"return",
"(",
"status",
"[",
"\"status\"",
"]",
",",
"status",
"[",
"\"message\"",
"]",
")"
] | Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', "" | [
"Retrieve",
"the",
"previously",
"set",
"juju",
"workload",
"state",
"and",
"message"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1018-L1035 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | application_version_set | def application_version_set(version):
"""Charm authors may trigger this command from any hook to output what
version of the application is running. This could be a package version,
for instance postgres version 9.5. It could also be a build number or
version control revision identifier, for instance git sha 6fb7ba68. """
cmd = ['application-version-set']
cmd.append(version)
try:
subprocess.check_call(cmd)
except OSError:
log("Application Version: {}".format(version)) | python | def application_version_set(version):
"""Charm authors may trigger this command from any hook to output what
version of the application is running. This could be a package version,
for instance postgres version 9.5. It could also be a build number or
version control revision identifier, for instance git sha 6fb7ba68. """
cmd = ['application-version-set']
cmd.append(version)
try:
subprocess.check_call(cmd)
except OSError:
log("Application Version: {}".format(version)) | [
"def",
"application_version_set",
"(",
"version",
")",
":",
"cmd",
"=",
"[",
"'application-version-set'",
"]",
"cmd",
".",
"append",
"(",
"version",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"cmd",
")",
"except",
"OSError",
":",
"log",
"(",
"\"Application Version: {}\"",
".",
"format",
"(",
"version",
")",
")"
] | Charm authors may trigger this command from any hook to output what
version of the application is running. This could be a package version,
for instance postgres version 9.5. It could also be a build number or
version control revision identifier, for instance git sha 6fb7ba68. | [
"Charm",
"authors",
"may",
"trigger",
"this",
"command",
"from",
"any",
"hook",
"to",
"output",
"what",
"version",
"of",
"the",
"application",
"is",
"running",
".",
"This",
"could",
"be",
"a",
"package",
"version",
"for",
"instance",
"postgres",
"version",
"9",
".",
"5",
".",
"It",
"could",
"also",
"be",
"a",
"build",
"number",
"or",
"version",
"control",
"revision",
"identifier",
"for",
"instance",
"git",
"sha",
"6fb7ba68",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1052-L1063 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | payload_register | def payload_register(ptype, klass, pid):
""" is used while a hook is running to let Juju know that a
payload has been started."""
cmd = ['payload-register']
for x in [ptype, klass, pid]:
cmd.append(x)
subprocess.check_call(cmd) | python | def payload_register(ptype, klass, pid):
""" is used while a hook is running to let Juju know that a
payload has been started."""
cmd = ['payload-register']
for x in [ptype, klass, pid]:
cmd.append(x)
subprocess.check_call(cmd) | [
"def",
"payload_register",
"(",
"ptype",
",",
"klass",
",",
"pid",
")",
":",
"cmd",
"=",
"[",
"'payload-register'",
"]",
"for",
"x",
"in",
"[",
"ptype",
",",
"klass",
",",
"pid",
"]",
":",
"cmd",
".",
"append",
"(",
"x",
")",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] | is used while a hook is running to let Juju know that a
payload has been started. | [
"is",
"used",
"while",
"a",
"hook",
"is",
"running",
"to",
"let",
"Juju",
"know",
"that",
"a",
"payload",
"has",
"been",
"started",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1108-L1114 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | resource_get | def resource_get(name):
"""used to fetch the resource path of the given name.
<name> must match a name of defined resource in metadata.yaml
returns either a path or False if resource not available
"""
if not name:
return False
cmd = ['resource-get', name]
try:
return subprocess.check_output(cmd).decode('UTF-8')
except subprocess.CalledProcessError:
return False | python | def resource_get(name):
"""used to fetch the resource path of the given name.
<name> must match a name of defined resource in metadata.yaml
returns either a path or False if resource not available
"""
if not name:
return False
cmd = ['resource-get', name]
try:
return subprocess.check_output(cmd).decode('UTF-8')
except subprocess.CalledProcessError:
return False | [
"def",
"resource_get",
"(",
"name",
")",
":",
"if",
"not",
"name",
":",
"return",
"False",
"cmd",
"=",
"[",
"'resource-get'",
",",
"name",
"]",
"try",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"return",
"False"
] | used to fetch the resource path of the given name.
<name> must match a name of defined resource in metadata.yaml
returns either a path or False if resource not available | [
"used",
"to",
"fetch",
"the",
"resource",
"path",
"of",
"the",
"given",
"name",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1142-L1156 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | atstart | def atstart(callback, *args, **kwargs):
'''Schedule a callback to run before the main hook.
Callbacks are run in the order they were added.
This is useful for modules and classes to perform initialization
and inject behavior. In particular:
- Run common code before all of your hooks, such as logging
the hook name or interesting relation data.
- Defer object or module initialization that requires a hook
context until we know there actually is a hook context,
making testing easier.
- Rather than requiring charm authors to include boilerplate to
invoke your helper's behavior, have it run automatically if
your object is instantiated or module imported.
This is not at all useful after your hook framework as been launched.
'''
global _atstart
_atstart.append((callback, args, kwargs)) | python | def atstart(callback, *args, **kwargs):
'''Schedule a callback to run before the main hook.
Callbacks are run in the order they were added.
This is useful for modules and classes to perform initialization
and inject behavior. In particular:
- Run common code before all of your hooks, such as logging
the hook name or interesting relation data.
- Defer object or module initialization that requires a hook
context until we know there actually is a hook context,
making testing easier.
- Rather than requiring charm authors to include boilerplate to
invoke your helper's behavior, have it run automatically if
your object is instantiated or module imported.
This is not at all useful after your hook framework as been launched.
'''
global _atstart
_atstart.append((callback, args, kwargs)) | [
"def",
"atstart",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_atstart",
"_atstart",
".",
"append",
"(",
"(",
"callback",
",",
"args",
",",
"kwargs",
")",
")"
] | Schedule a callback to run before the main hook.
Callbacks are run in the order they were added.
This is useful for modules and classes to perform initialization
and inject behavior. In particular:
- Run common code before all of your hooks, such as logging
the hook name or interesting relation data.
- Defer object or module initialization that requires a hook
context until we know there actually is a hook context,
making testing easier.
- Rather than requiring charm authors to include boilerplate to
invoke your helper's behavior, have it run automatically if
your object is instantiated or module imported.
This is not at all useful after your hook framework as been launched. | [
"Schedule",
"a",
"callback",
"to",
"run",
"before",
"the",
"main",
"hook",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1177-L1197 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | _run_atstart | def _run_atstart():
'''Hook frameworks must invoke this before running the main hook body.'''
global _atstart
for callback, args, kwargs in _atstart:
callback(*args, **kwargs)
del _atstart[:] | python | def _run_atstart():
'''Hook frameworks must invoke this before running the main hook body.'''
global _atstart
for callback, args, kwargs in _atstart:
callback(*args, **kwargs)
del _atstart[:] | [
"def",
"_run_atstart",
"(",
")",
":",
"global",
"_atstart",
"for",
"callback",
",",
"args",
",",
"kwargs",
"in",
"_atstart",
":",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"del",
"_atstart",
"[",
":",
"]"
] | Hook frameworks must invoke this before running the main hook body. | [
"Hook",
"frameworks",
"must",
"invoke",
"this",
"before",
"running",
"the",
"main",
"hook",
"body",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1207-L1212 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | _run_atexit | def _run_atexit():
'''Hook frameworks must invoke this after the main hook body has
successfully completed. Do not invoke it if the hook fails.'''
global _atexit
for callback, args, kwargs in reversed(_atexit):
callback(*args, **kwargs)
del _atexit[:] | python | def _run_atexit():
'''Hook frameworks must invoke this after the main hook body has
successfully completed. Do not invoke it if the hook fails.'''
global _atexit
for callback, args, kwargs in reversed(_atexit):
callback(*args, **kwargs)
del _atexit[:] | [
"def",
"_run_atexit",
"(",
")",
":",
"global",
"_atexit",
"for",
"callback",
",",
"args",
",",
"kwargs",
"in",
"reversed",
"(",
"_atexit",
")",
":",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"del",
"_atexit",
"[",
":",
"]"
] | Hook frameworks must invoke this after the main hook body has
successfully completed. Do not invoke it if the hook fails. | [
"Hook",
"frameworks",
"must",
"invoke",
"this",
"after",
"the",
"main",
"hook",
"body",
"has",
"successfully",
"completed",
".",
"Do",
"not",
"invoke",
"it",
"if",
"the",
"hook",
"fails",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1215-L1221 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | network_get | def network_get(endpoint, relation_id=None):
"""
Retrieve the network details for a relation endpoint
:param endpoint: string. The name of a relation endpoint
:param relation_id: int. The ID of the relation for the current context.
:return: dict. The loaded YAML output of the network-get query.
:raise: NotImplementedError if request not supported by the Juju version.
"""
if not has_juju_version('2.2'):
raise NotImplementedError(juju_version()) # earlier versions require --primary-address
if relation_id and not has_juju_version('2.3'):
raise NotImplementedError # 2.3 added the -r option
cmd = ['network-get', endpoint, '--format', 'yaml']
if relation_id:
cmd.append('-r')
cmd.append(relation_id)
response = subprocess.check_output(
cmd,
stderr=subprocess.STDOUT).decode('UTF-8').strip()
return yaml.safe_load(response) | python | def network_get(endpoint, relation_id=None):
"""
Retrieve the network details for a relation endpoint
:param endpoint: string. The name of a relation endpoint
:param relation_id: int. The ID of the relation for the current context.
:return: dict. The loaded YAML output of the network-get query.
:raise: NotImplementedError if request not supported by the Juju version.
"""
if not has_juju_version('2.2'):
raise NotImplementedError(juju_version()) # earlier versions require --primary-address
if relation_id and not has_juju_version('2.3'):
raise NotImplementedError # 2.3 added the -r option
cmd = ['network-get', endpoint, '--format', 'yaml']
if relation_id:
cmd.append('-r')
cmd.append(relation_id)
response = subprocess.check_output(
cmd,
stderr=subprocess.STDOUT).decode('UTF-8').strip()
return yaml.safe_load(response) | [
"def",
"network_get",
"(",
"endpoint",
",",
"relation_id",
"=",
"None",
")",
":",
"if",
"not",
"has_juju_version",
"(",
"'2.2'",
")",
":",
"raise",
"NotImplementedError",
"(",
"juju_version",
"(",
")",
")",
"# earlier versions require --primary-address",
"if",
"relation_id",
"and",
"not",
"has_juju_version",
"(",
"'2.3'",
")",
":",
"raise",
"NotImplementedError",
"# 2.3 added the -r option",
"cmd",
"=",
"[",
"'network-get'",
",",
"endpoint",
",",
"'--format'",
",",
"'yaml'",
"]",
"if",
"relation_id",
":",
"cmd",
".",
"append",
"(",
"'-r'",
")",
"cmd",
".",
"append",
"(",
"relation_id",
")",
"response",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
".",
"strip",
"(",
")",
"return",
"yaml",
".",
"safe_load",
"(",
"response",
")"
] | Retrieve the network details for a relation endpoint
:param endpoint: string. The name of a relation endpoint
:param relation_id: int. The ID of the relation for the current context.
:return: dict. The loaded YAML output of the network-get query.
:raise: NotImplementedError if request not supported by the Juju version. | [
"Retrieve",
"the",
"network",
"details",
"for",
"a",
"relation",
"endpoint"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1249-L1270 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | add_metric | def add_metric(*args, **kwargs):
"""Add metric values. Values may be expressed with keyword arguments. For
metric names containing dashes, these may be expressed as one or more
'key=value' positional arguments. May only be called from the collect-metrics
hook."""
_args = ['add-metric']
_kvpairs = []
_kvpairs.extend(args)
_kvpairs.extend(['{}={}'.format(k, v) for k, v in kwargs.items()])
_args.extend(sorted(_kvpairs))
try:
subprocess.check_call(_args)
return
except EnvironmentError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'add-metric failed: {}'.format(' '.join(_kvpairs))
log(log_message, level='INFO') | python | def add_metric(*args, **kwargs):
"""Add metric values. Values may be expressed with keyword arguments. For
metric names containing dashes, these may be expressed as one or more
'key=value' positional arguments. May only be called from the collect-metrics
hook."""
_args = ['add-metric']
_kvpairs = []
_kvpairs.extend(args)
_kvpairs.extend(['{}={}'.format(k, v) for k, v in kwargs.items()])
_args.extend(sorted(_kvpairs))
try:
subprocess.check_call(_args)
return
except EnvironmentError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'add-metric failed: {}'.format(' '.join(_kvpairs))
log(log_message, level='INFO') | [
"def",
"add_metric",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_args",
"=",
"[",
"'add-metric'",
"]",
"_kvpairs",
"=",
"[",
"]",
"_kvpairs",
".",
"extend",
"(",
"args",
")",
"_kvpairs",
".",
"extend",
"(",
"[",
"'{}={}'",
".",
"format",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"]",
")",
"_args",
".",
"extend",
"(",
"sorted",
"(",
"_kvpairs",
")",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"_args",
")",
"return",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"log_message",
"=",
"'add-metric failed: {}'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"_kvpairs",
")",
")",
"log",
"(",
"log_message",
",",
"level",
"=",
"'INFO'",
")"
] | Add metric values. Values may be expressed with keyword arguments. For
metric names containing dashes, these may be expressed as one or more
'key=value' positional arguments. May only be called from the collect-metrics
hook. | [
"Add",
"metric",
"values",
".",
"Values",
"may",
"be",
"expressed",
"with",
"keyword",
"arguments",
".",
"For",
"metric",
"names",
"containing",
"dashes",
"these",
"may",
"be",
"expressed",
"as",
"one",
"or",
"more",
"key",
"=",
"value",
"positional",
"arguments",
".",
"May",
"only",
"be",
"called",
"from",
"the",
"collect",
"-",
"metrics",
"hook",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1273-L1290 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | iter_units_for_relation_name | def iter_units_for_relation_name(relation_name):
"""Iterate through all units in a relation
Generator that iterates through all the units in a relation and yields
a named tuple with rid and unit field names.
Usage:
data = [(u.rid, u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param relation_name: string relation name
:yield: Named Tuple with rid and unit field names
"""
RelatedUnit = namedtuple('RelatedUnit', 'rid, unit')
for rid in relation_ids(relation_name):
for unit in related_units(rid):
yield RelatedUnit(rid, unit) | python | def iter_units_for_relation_name(relation_name):
"""Iterate through all units in a relation
Generator that iterates through all the units in a relation and yields
a named tuple with rid and unit field names.
Usage:
data = [(u.rid, u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param relation_name: string relation name
:yield: Named Tuple with rid and unit field names
"""
RelatedUnit = namedtuple('RelatedUnit', 'rid, unit')
for rid in relation_ids(relation_name):
for unit in related_units(rid):
yield RelatedUnit(rid, unit) | [
"def",
"iter_units_for_relation_name",
"(",
"relation_name",
")",
":",
"RelatedUnit",
"=",
"namedtuple",
"(",
"'RelatedUnit'",
",",
"'rid, unit'",
")",
"for",
"rid",
"in",
"relation_ids",
"(",
"relation_name",
")",
":",
"for",
"unit",
"in",
"related_units",
"(",
"rid",
")",
":",
"yield",
"RelatedUnit",
"(",
"rid",
",",
"unit",
")"
] | Iterate through all units in a relation
Generator that iterates through all the units in a relation and yields
a named tuple with rid and unit field names.
Usage:
data = [(u.rid, u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param relation_name: string relation name
:yield: Named Tuple with rid and unit field names | [
"Iterate",
"through",
"all",
"units",
"in",
"a",
"relation"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1304-L1320 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | ingress_address | def ingress_address(rid=None, unit=None):
"""
Retrieve the ingress-address from a relation when available.
Otherwise, return the private-address.
When used on the consuming side of the relation (unit is a remote
unit), the ingress-address is the IP address that this unit needs
to use to reach the provided service on the remote unit.
When used on the providing side of the relation (unit == local_unit()),
the ingress-address is the IP address that is advertised to remote
units on this relation. Remote units need to use this address to
reach the local provided service on this unit.
Note that charms may document some other method to use in
preference to the ingress_address(), such as an address provided
on a different relation attribute or a service discovery mechanism.
This allows charms to redirect inbound connections to their peers
or different applications such as load balancers.
Usage:
addresses = [ingress_address(rid=u.rid, unit=u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: string IP address
"""
settings = relation_get(rid=rid, unit=unit)
return (settings.get('ingress-address') or
settings.get('private-address')) | python | def ingress_address(rid=None, unit=None):
"""
Retrieve the ingress-address from a relation when available.
Otherwise, return the private-address.
When used on the consuming side of the relation (unit is a remote
unit), the ingress-address is the IP address that this unit needs
to use to reach the provided service on the remote unit.
When used on the providing side of the relation (unit == local_unit()),
the ingress-address is the IP address that is advertised to remote
units on this relation. Remote units need to use this address to
reach the local provided service on this unit.
Note that charms may document some other method to use in
preference to the ingress_address(), such as an address provided
on a different relation attribute or a service discovery mechanism.
This allows charms to redirect inbound connections to their peers
or different applications such as load balancers.
Usage:
addresses = [ingress_address(rid=u.rid, unit=u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: string IP address
"""
settings = relation_get(rid=rid, unit=unit)
return (settings.get('ingress-address') or
settings.get('private-address')) | [
"def",
"ingress_address",
"(",
"rid",
"=",
"None",
",",
"unit",
"=",
"None",
")",
":",
"settings",
"=",
"relation_get",
"(",
"rid",
"=",
"rid",
",",
"unit",
"=",
"unit",
")",
"return",
"(",
"settings",
".",
"get",
"(",
"'ingress-address'",
")",
"or",
"settings",
".",
"get",
"(",
"'private-address'",
")",
")"
] | Retrieve the ingress-address from a relation when available.
Otherwise, return the private-address.
When used on the consuming side of the relation (unit is a remote
unit), the ingress-address is the IP address that this unit needs
to use to reach the provided service on the remote unit.
When used on the providing side of the relation (unit == local_unit()),
the ingress-address is the IP address that is advertised to remote
units on this relation. Remote units need to use this address to
reach the local provided service on this unit.
Note that charms may document some other method to use in
preference to the ingress_address(), such as an address provided
on a different relation attribute or a service discovery mechanism.
This allows charms to redirect inbound connections to their peers
or different applications such as load balancers.
Usage:
addresses = [ingress_address(rid=u.rid, unit=u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: string IP address | [
"Retrieve",
"the",
"ingress",
"-",
"address",
"from",
"a",
"relation",
"when",
"available",
".",
"Otherwise",
"return",
"the",
"private",
"-",
"address",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1323-L1354 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | egress_subnets | def egress_subnets(rid=None, unit=None):
"""
Retrieve the egress-subnets from a relation.
This function is to be used on the providing side of the
relation, and provides the ranges of addresses that client
connections may come from. The result is uninteresting on
the consuming side of a relation (unit == local_unit()).
Returns a stable list of subnets in CIDR format.
eg. ['192.168.1.0/24', '2001::F00F/128']
If egress-subnets is not available, falls back to using the published
ingress-address, or finally private-address.
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: list of subnets in CIDR format. eg. ['192.168.1.0/24', '2001::F00F/128']
"""
def _to_range(addr):
if re.search(r'^(?:\d{1,3}\.){3}\d{1,3}$', addr) is not None:
addr += '/32'
elif ':' in addr and '/' not in addr: # IPv6
addr += '/128'
return addr
settings = relation_get(rid=rid, unit=unit)
if 'egress-subnets' in settings:
return [n.strip() for n in settings['egress-subnets'].split(',') if n.strip()]
if 'ingress-address' in settings:
return [_to_range(settings['ingress-address'])]
if 'private-address' in settings:
return [_to_range(settings['private-address'])]
return [] | python | def egress_subnets(rid=None, unit=None):
"""
Retrieve the egress-subnets from a relation.
This function is to be used on the providing side of the
relation, and provides the ranges of addresses that client
connections may come from. The result is uninteresting on
the consuming side of a relation (unit == local_unit()).
Returns a stable list of subnets in CIDR format.
eg. ['192.168.1.0/24', '2001::F00F/128']
If egress-subnets is not available, falls back to using the published
ingress-address, or finally private-address.
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: list of subnets in CIDR format. eg. ['192.168.1.0/24', '2001::F00F/128']
"""
def _to_range(addr):
if re.search(r'^(?:\d{1,3}\.){3}\d{1,3}$', addr) is not None:
addr += '/32'
elif ':' in addr and '/' not in addr: # IPv6
addr += '/128'
return addr
settings = relation_get(rid=rid, unit=unit)
if 'egress-subnets' in settings:
return [n.strip() for n in settings['egress-subnets'].split(',') if n.strip()]
if 'ingress-address' in settings:
return [_to_range(settings['ingress-address'])]
if 'private-address' in settings:
return [_to_range(settings['private-address'])]
return [] | [
"def",
"egress_subnets",
"(",
"rid",
"=",
"None",
",",
"unit",
"=",
"None",
")",
":",
"def",
"_to_range",
"(",
"addr",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'^(?:\\d{1,3}\\.){3}\\d{1,3}$'",
",",
"addr",
")",
"is",
"not",
"None",
":",
"addr",
"+=",
"'/32'",
"elif",
"':'",
"in",
"addr",
"and",
"'/'",
"not",
"in",
"addr",
":",
"# IPv6",
"addr",
"+=",
"'/128'",
"return",
"addr",
"settings",
"=",
"relation_get",
"(",
"rid",
"=",
"rid",
",",
"unit",
"=",
"unit",
")",
"if",
"'egress-subnets'",
"in",
"settings",
":",
"return",
"[",
"n",
".",
"strip",
"(",
")",
"for",
"n",
"in",
"settings",
"[",
"'egress-subnets'",
"]",
".",
"split",
"(",
"','",
")",
"if",
"n",
".",
"strip",
"(",
")",
"]",
"if",
"'ingress-address'",
"in",
"settings",
":",
"return",
"[",
"_to_range",
"(",
"settings",
"[",
"'ingress-address'",
"]",
")",
"]",
"if",
"'private-address'",
"in",
"settings",
":",
"return",
"[",
"_to_range",
"(",
"settings",
"[",
"'private-address'",
"]",
")",
"]",
"return",
"[",
"]"
] | Retrieve the egress-subnets from a relation.
This function is to be used on the providing side of the
relation, and provides the ranges of addresses that client
connections may come from. The result is uninteresting on
the consuming side of a relation (unit == local_unit()).
Returns a stable list of subnets in CIDR format.
eg. ['192.168.1.0/24', '2001::F00F/128']
If egress-subnets is not available, falls back to using the published
ingress-address, or finally private-address.
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: list of subnets in CIDR format. eg. ['192.168.1.0/24', '2001::F00F/128'] | [
"Retrieve",
"the",
"egress",
"-",
"subnets",
"from",
"a",
"relation",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1357-L1391 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | unit_doomed | def unit_doomed(unit=None):
"""Determines if the unit is being removed from the model
Requires Juju 2.4.1.
:param unit: string unit name, defaults to local_unit
:side effect: calls goal_state
:side effect: calls local_unit
:side effect: calls has_juju_version
:return: True if the unit is being removed, already gone, or never existed
"""
if not has_juju_version("2.4.1"):
# We cannot risk blindly returning False for 'we don't know',
# because that could cause data loss; if call sites don't
# need an accurate answer, they likely don't need this helper
# at all.
# goal-state existed in 2.4.0, but did not handle removals
# correctly until 2.4.1.
raise NotImplementedError("is_doomed")
if unit is None:
unit = local_unit()
gs = goal_state()
units = gs.get('units', {})
if unit not in units:
return True
# I don't think 'dead' units ever show up in the goal-state, but
# check anyway in addition to 'dying'.
return units[unit]['status'] in ('dying', 'dead') | python | def unit_doomed(unit=None):
"""Determines if the unit is being removed from the model
Requires Juju 2.4.1.
:param unit: string unit name, defaults to local_unit
:side effect: calls goal_state
:side effect: calls local_unit
:side effect: calls has_juju_version
:return: True if the unit is being removed, already gone, or never existed
"""
if not has_juju_version("2.4.1"):
# We cannot risk blindly returning False for 'we don't know',
# because that could cause data loss; if call sites don't
# need an accurate answer, they likely don't need this helper
# at all.
# goal-state existed in 2.4.0, but did not handle removals
# correctly until 2.4.1.
raise NotImplementedError("is_doomed")
if unit is None:
unit = local_unit()
gs = goal_state()
units = gs.get('units', {})
if unit not in units:
return True
# I don't think 'dead' units ever show up in the goal-state, but
# check anyway in addition to 'dying'.
return units[unit]['status'] in ('dying', 'dead') | [
"def",
"unit_doomed",
"(",
"unit",
"=",
"None",
")",
":",
"if",
"not",
"has_juju_version",
"(",
"\"2.4.1\"",
")",
":",
"# We cannot risk blindly returning False for 'we don't know',",
"# because that could cause data loss; if call sites don't",
"# need an accurate answer, they likely don't need this helper",
"# at all.",
"# goal-state existed in 2.4.0, but did not handle removals",
"# correctly until 2.4.1.",
"raise",
"NotImplementedError",
"(",
"\"is_doomed\"",
")",
"if",
"unit",
"is",
"None",
":",
"unit",
"=",
"local_unit",
"(",
")",
"gs",
"=",
"goal_state",
"(",
")",
"units",
"=",
"gs",
".",
"get",
"(",
"'units'",
",",
"{",
"}",
")",
"if",
"unit",
"not",
"in",
"units",
":",
"return",
"True",
"# I don't think 'dead' units ever show up in the goal-state, but",
"# check anyway in addition to 'dying'.",
"return",
"units",
"[",
"unit",
"]",
"[",
"'status'",
"]",
"in",
"(",
"'dying'",
",",
"'dead'",
")"
] | Determines if the unit is being removed from the model
Requires Juju 2.4.1.
:param unit: string unit name, defaults to local_unit
:side effect: calls goal_state
:side effect: calls local_unit
:side effect: calls has_juju_version
:return: True if the unit is being removed, already gone, or never existed | [
"Determines",
"if",
"the",
"unit",
"is",
"being",
"removed",
"from",
"the",
"model"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1394-L1421 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | env_proxy_settings | def env_proxy_settings(selected_settings=None):
"""Get proxy settings from process environment variables.
Get charm proxy settings from environment variables that correspond to
juju-http-proxy, juju-https-proxy and juju-no-proxy (available as of 2.4.2,
see lp:1782236) in a format suitable for passing to an application that
reacts to proxy settings passed as environment variables. Some applications
support lowercase or uppercase notation (e.g. curl), some support only
lowercase (e.g. wget), there are also subjectively rare cases of only
uppercase notation support. no_proxy CIDR and wildcard support also varies
between runtimes and applications as there is no enforced standard.
Some applications may connect to multiple destinations and expose config
options that would affect only proxy settings for a specific destination
these should be handled in charms in an application-specific manner.
:param selected_settings: format only a subset of possible settings
:type selected_settings: list
:rtype: Option(None, dict[str, str])
"""
SUPPORTED_SETTINGS = {
'http': 'HTTP_PROXY',
'https': 'HTTPS_PROXY',
'no_proxy': 'NO_PROXY',
'ftp': 'FTP_PROXY'
}
if selected_settings is None:
selected_settings = SUPPORTED_SETTINGS
selected_vars = [v for k, v in SUPPORTED_SETTINGS.items()
if k in selected_settings]
proxy_settings = {}
for var in selected_vars:
var_val = os.getenv(var)
if var_val:
proxy_settings[var] = var_val
proxy_settings[var.lower()] = var_val
# Now handle juju-prefixed environment variables. The legacy vs new
# environment variable usage is mutually exclusive
charm_var_val = os.getenv('JUJU_CHARM_{}'.format(var))
if charm_var_val:
proxy_settings[var] = charm_var_val
proxy_settings[var.lower()] = charm_var_val
if 'no_proxy' in proxy_settings:
if _contains_range(proxy_settings['no_proxy']):
log(RANGE_WARNING, level=WARNING)
return proxy_settings if proxy_settings else None | python | def env_proxy_settings(selected_settings=None):
"""Get proxy settings from process environment variables.
Get charm proxy settings from environment variables that correspond to
juju-http-proxy, juju-https-proxy and juju-no-proxy (available as of 2.4.2,
see lp:1782236) in a format suitable for passing to an application that
reacts to proxy settings passed as environment variables. Some applications
support lowercase or uppercase notation (e.g. curl), some support only
lowercase (e.g. wget), there are also subjectively rare cases of only
uppercase notation support. no_proxy CIDR and wildcard support also varies
between runtimes and applications as there is no enforced standard.
Some applications may connect to multiple destinations and expose config
options that would affect only proxy settings for a specific destination
these should be handled in charms in an application-specific manner.
:param selected_settings: format only a subset of possible settings
:type selected_settings: list
:rtype: Option(None, dict[str, str])
"""
SUPPORTED_SETTINGS = {
'http': 'HTTP_PROXY',
'https': 'HTTPS_PROXY',
'no_proxy': 'NO_PROXY',
'ftp': 'FTP_PROXY'
}
if selected_settings is None:
selected_settings = SUPPORTED_SETTINGS
selected_vars = [v for k, v in SUPPORTED_SETTINGS.items()
if k in selected_settings]
proxy_settings = {}
for var in selected_vars:
var_val = os.getenv(var)
if var_val:
proxy_settings[var] = var_val
proxy_settings[var.lower()] = var_val
# Now handle juju-prefixed environment variables. The legacy vs new
# environment variable usage is mutually exclusive
charm_var_val = os.getenv('JUJU_CHARM_{}'.format(var))
if charm_var_val:
proxy_settings[var] = charm_var_val
proxy_settings[var.lower()] = charm_var_val
if 'no_proxy' in proxy_settings:
if _contains_range(proxy_settings['no_proxy']):
log(RANGE_WARNING, level=WARNING)
return proxy_settings if proxy_settings else None | [
"def",
"env_proxy_settings",
"(",
"selected_settings",
"=",
"None",
")",
":",
"SUPPORTED_SETTINGS",
"=",
"{",
"'http'",
":",
"'HTTP_PROXY'",
",",
"'https'",
":",
"'HTTPS_PROXY'",
",",
"'no_proxy'",
":",
"'NO_PROXY'",
",",
"'ftp'",
":",
"'FTP_PROXY'",
"}",
"if",
"selected_settings",
"is",
"None",
":",
"selected_settings",
"=",
"SUPPORTED_SETTINGS",
"selected_vars",
"=",
"[",
"v",
"for",
"k",
",",
"v",
"in",
"SUPPORTED_SETTINGS",
".",
"items",
"(",
")",
"if",
"k",
"in",
"selected_settings",
"]",
"proxy_settings",
"=",
"{",
"}",
"for",
"var",
"in",
"selected_vars",
":",
"var_val",
"=",
"os",
".",
"getenv",
"(",
"var",
")",
"if",
"var_val",
":",
"proxy_settings",
"[",
"var",
"]",
"=",
"var_val",
"proxy_settings",
"[",
"var",
".",
"lower",
"(",
")",
"]",
"=",
"var_val",
"# Now handle juju-prefixed environment variables. The legacy vs new",
"# environment variable usage is mutually exclusive",
"charm_var_val",
"=",
"os",
".",
"getenv",
"(",
"'JUJU_CHARM_{}'",
".",
"format",
"(",
"var",
")",
")",
"if",
"charm_var_val",
":",
"proxy_settings",
"[",
"var",
"]",
"=",
"charm_var_val",
"proxy_settings",
"[",
"var",
".",
"lower",
"(",
")",
"]",
"=",
"charm_var_val",
"if",
"'no_proxy'",
"in",
"proxy_settings",
":",
"if",
"_contains_range",
"(",
"proxy_settings",
"[",
"'no_proxy'",
"]",
")",
":",
"log",
"(",
"RANGE_WARNING",
",",
"level",
"=",
"WARNING",
")",
"return",
"proxy_settings",
"if",
"proxy_settings",
"else",
"None"
] | Get proxy settings from process environment variables.
Get charm proxy settings from environment variables that correspond to
juju-http-proxy, juju-https-proxy and juju-no-proxy (available as of 2.4.2,
see lp:1782236) in a format suitable for passing to an application that
reacts to proxy settings passed as environment variables. Some applications
support lowercase or uppercase notation (e.g. curl), some support only
lowercase (e.g. wget), there are also subjectively rare cases of only
uppercase notation support. no_proxy CIDR and wildcard support also varies
between runtimes and applications as there is no enforced standard.
Some applications may connect to multiple destinations and expose config
options that would affect only proxy settings for a specific destination
these should be handled in charms in an application-specific manner.
:param selected_settings: format only a subset of possible settings
:type selected_settings: list
:rtype: Option(None, dict[str, str]) | [
"Get",
"proxy",
"settings",
"from",
"process",
"environment",
"variables",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1424-L1470 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | Config.load_previous | def load_previous(self, path=None):
"""Load previous copy of config from disk.
In normal usage you don't need to call this method directly - it
is called automatically at object initialization.
:param path:
File path from which to load the previous config. If `None`,
config is loaded from the default location. If `path` is
specified, subsequent `save()` calls will write to the same
path.
"""
self.path = path or self.path
with open(self.path) as f:
try:
self._prev_dict = json.load(f)
except ValueError as e:
log('Unable to parse previous config data - {}'.format(str(e)),
level=ERROR)
for k, v in copy.deepcopy(self._prev_dict).items():
if k not in self:
self[k] = v | python | def load_previous(self, path=None):
"""Load previous copy of config from disk.
In normal usage you don't need to call this method directly - it
is called automatically at object initialization.
:param path:
File path from which to load the previous config. If `None`,
config is loaded from the default location. If `path` is
specified, subsequent `save()` calls will write to the same
path.
"""
self.path = path or self.path
with open(self.path) as f:
try:
self._prev_dict = json.load(f)
except ValueError as e:
log('Unable to parse previous config data - {}'.format(str(e)),
level=ERROR)
for k, v in copy.deepcopy(self._prev_dict).items():
if k not in self:
self[k] = v | [
"def",
"load_previous",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"self",
".",
"path",
"=",
"path",
"or",
"self",
".",
"path",
"with",
"open",
"(",
"self",
".",
"path",
")",
"as",
"f",
":",
"try",
":",
"self",
".",
"_prev_dict",
"=",
"json",
".",
"load",
"(",
"f",
")",
"except",
"ValueError",
"as",
"e",
":",
"log",
"(",
"'Unable to parse previous config data - {}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
",",
"level",
"=",
"ERROR",
")",
"for",
"k",
",",
"v",
"in",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_prev_dict",
")",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self",
":",
"self",
"[",
"k",
"]",
"=",
"v"
] | Load previous copy of config from disk.
In normal usage you don't need to call this method directly - it
is called automatically at object initialization.
:param path:
File path from which to load the previous config. If `None`,
config is loaded from the default location. If `path` is
specified, subsequent `save()` calls will write to the same
path. | [
"Load",
"previous",
"copy",
"of",
"config",
"from",
"disk",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L327-L350 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | Config.changed | def changed(self, key):
"""Return True if the current value for this key is different from
the previous value.
"""
if self._prev_dict is None:
return True
return self.previous(key) != self.get(key) | python | def changed(self, key):
"""Return True if the current value for this key is different from
the previous value.
"""
if self._prev_dict is None:
return True
return self.previous(key) != self.get(key) | [
"def",
"changed",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"_prev_dict",
"is",
"None",
":",
"return",
"True",
"return",
"self",
".",
"previous",
"(",
"key",
")",
"!=",
"self",
".",
"get",
"(",
"key",
")"
] | Return True if the current value for this key is different from
the previous value. | [
"Return",
"True",
"if",
"the",
"current",
"value",
"for",
"this",
"key",
"is",
"different",
"from",
"the",
"previous",
"value",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L352-L359 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | Config.save | def save(self):
"""Save this config to disk.
If the charm is using the :mod:`Services Framework <services.base>`
or :meth:'@hook <Hooks.hook>' decorator, this
is called automatically at the end of successful hook execution.
Otherwise, it should be called directly by user code.
To disable automatic saves, set ``implicit_save=False`` on this
instance.
"""
with open(self.path, 'w') as f:
os.fchmod(f.fileno(), 0o600)
json.dump(self, f) | python | def save(self):
"""Save this config to disk.
If the charm is using the :mod:`Services Framework <services.base>`
or :meth:'@hook <Hooks.hook>' decorator, this
is called automatically at the end of successful hook execution.
Otherwise, it should be called directly by user code.
To disable automatic saves, set ``implicit_save=False`` on this
instance.
"""
with open(self.path, 'w') as f:
os.fchmod(f.fileno(), 0o600)
json.dump(self, f) | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"os",
".",
"fchmod",
"(",
"f",
".",
"fileno",
"(",
")",
",",
"0o600",
")",
"json",
".",
"dump",
"(",
"self",
",",
"f",
")"
] | Save this config to disk.
If the charm is using the :mod:`Services Framework <services.base>`
or :meth:'@hook <Hooks.hook>' decorator, this
is called automatically at the end of successful hook execution.
Otherwise, it should be called directly by user code.
To disable automatic saves, set ``implicit_save=False`` on this
instance. | [
"Save",
"this",
"config",
"to",
"disk",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L370-L384 | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | Hooks.hook | def hook(self, *hook_names):
"""Decorator, registering them as hooks"""
def wrapper(decorated):
for hook_name in hook_names:
self.register(hook_name, decorated)
else:
self.register(decorated.__name__, decorated)
if '_' in decorated.__name__:
self.register(
decorated.__name__.replace('_', '-'), decorated)
return decorated
return wrapper | python | def hook(self, *hook_names):
"""Decorator, registering them as hooks"""
def wrapper(decorated):
for hook_name in hook_names:
self.register(hook_name, decorated)
else:
self.register(decorated.__name__, decorated)
if '_' in decorated.__name__:
self.register(
decorated.__name__.replace('_', '-'), decorated)
return decorated
return wrapper | [
"def",
"hook",
"(",
"self",
",",
"*",
"hook_names",
")",
":",
"def",
"wrapper",
"(",
"decorated",
")",
":",
"for",
"hook_name",
"in",
"hook_names",
":",
"self",
".",
"register",
"(",
"hook_name",
",",
"decorated",
")",
"else",
":",
"self",
".",
"register",
"(",
"decorated",
".",
"__name__",
",",
"decorated",
")",
"if",
"'_'",
"in",
"decorated",
".",
"__name__",
":",
"self",
".",
"register",
"(",
"decorated",
".",
"__name__",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
",",
"decorated",
")",
"return",
"decorated",
"return",
"wrapper"
] | Decorator, registering them as hooks | [
"Decorator",
"registering",
"them",
"as",
"hooks"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L923-L934 | train |
juju/charm-helpers | charmhelpers/fetch/python/rpdb.py | Rpdb.shutdown | def shutdown(self):
"""Revert stdin and stdout, close the socket."""
sys.stdout = self.old_stdout
sys.stdin = self.old_stdin
self.skt.close()
self.set_continue() | python | def shutdown(self):
"""Revert stdin and stdout, close the socket."""
sys.stdout = self.old_stdout
sys.stdin = self.old_stdin
self.skt.close()
self.set_continue() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"sys",
".",
"stdout",
"=",
"self",
".",
"old_stdout",
"sys",
".",
"stdin",
"=",
"self",
".",
"old_stdin",
"self",
".",
"skt",
".",
"close",
"(",
")",
"self",
".",
"set_continue",
"(",
")"
] | Revert stdin and stdout, close the socket. | [
"Revert",
"stdin",
"and",
"stdout",
"close",
"the",
"socket",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/rpdb.py#L44-L49 | train |
juju/charm-helpers | charmhelpers/contrib/benchmark/__init__.py | Benchmark.start | def start():
action_set('meta.start', time.strftime('%Y-%m-%dT%H:%M:%SZ'))
"""
If the collectd charm is also installed, tell it to send a snapshot
of the current profile data.
"""
COLLECT_PROFILE_DATA = '/usr/local/bin/collect-profile-data'
if os.path.exists(COLLECT_PROFILE_DATA):
subprocess.check_output([COLLECT_PROFILE_DATA]) | python | def start():
action_set('meta.start', time.strftime('%Y-%m-%dT%H:%M:%SZ'))
"""
If the collectd charm is also installed, tell it to send a snapshot
of the current profile data.
"""
COLLECT_PROFILE_DATA = '/usr/local/bin/collect-profile-data'
if os.path.exists(COLLECT_PROFILE_DATA):
subprocess.check_output([COLLECT_PROFILE_DATA]) | [
"def",
"start",
"(",
")",
":",
"action_set",
"(",
"'meta.start'",
",",
"time",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
")",
"COLLECT_PROFILE_DATA",
"=",
"'/usr/local/bin/collect-profile-data'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"COLLECT_PROFILE_DATA",
")",
":",
"subprocess",
".",
"check_output",
"(",
"[",
"COLLECT_PROFILE_DATA",
"]",
")"
] | If the collectd charm is also installed, tell it to send a snapshot
of the current profile data. | [
"If",
"the",
"collectd",
"charm",
"is",
"also",
"installed",
"tell",
"it",
"to",
"send",
"a",
"snapshot",
"of",
"the",
"current",
"profile",
"data",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/benchmark/__init__.py#L99-L108 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_os_codename_install_source | def get_os_codename_install_source(src):
'''Derive OpenStack release codename from a given installation source.'''
ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
rel = ''
if src is None:
return rel
if src in ['distro', 'distro-proposed', 'proposed']:
try:
rel = UBUNTU_OPENSTACK_RELEASE[ubuntu_rel]
except KeyError:
e = 'Could not derive openstack release for '\
'this Ubuntu release: %s' % ubuntu_rel
error_out(e)
return rel
if src.startswith('cloud:'):
ca_rel = src.split(':')[1]
ca_rel = ca_rel.split('-')[1].split('/')[0]
return ca_rel
# Best guess match based on deb string provided
if (src.startswith('deb') or
src.startswith('ppa') or
src.startswith('snap')):
for v in OPENSTACK_CODENAMES.values():
if v in src:
return v | python | def get_os_codename_install_source(src):
'''Derive OpenStack release codename from a given installation source.'''
ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
rel = ''
if src is None:
return rel
if src in ['distro', 'distro-proposed', 'proposed']:
try:
rel = UBUNTU_OPENSTACK_RELEASE[ubuntu_rel]
except KeyError:
e = 'Could not derive openstack release for '\
'this Ubuntu release: %s' % ubuntu_rel
error_out(e)
return rel
if src.startswith('cloud:'):
ca_rel = src.split(':')[1]
ca_rel = ca_rel.split('-')[1].split('/')[0]
return ca_rel
# Best guess match based on deb string provided
if (src.startswith('deb') or
src.startswith('ppa') or
src.startswith('snap')):
for v in OPENSTACK_CODENAMES.values():
if v in src:
return v | [
"def",
"get_os_codename_install_source",
"(",
"src",
")",
":",
"ubuntu_rel",
"=",
"lsb_release",
"(",
")",
"[",
"'DISTRIB_CODENAME'",
"]",
"rel",
"=",
"''",
"if",
"src",
"is",
"None",
":",
"return",
"rel",
"if",
"src",
"in",
"[",
"'distro'",
",",
"'distro-proposed'",
",",
"'proposed'",
"]",
":",
"try",
":",
"rel",
"=",
"UBUNTU_OPENSTACK_RELEASE",
"[",
"ubuntu_rel",
"]",
"except",
"KeyError",
":",
"e",
"=",
"'Could not derive openstack release for '",
"'this Ubuntu release: %s'",
"%",
"ubuntu_rel",
"error_out",
"(",
"e",
")",
"return",
"rel",
"if",
"src",
".",
"startswith",
"(",
"'cloud:'",
")",
":",
"ca_rel",
"=",
"src",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"ca_rel",
"=",
"ca_rel",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"return",
"ca_rel",
"# Best guess match based on deb string provided",
"if",
"(",
"src",
".",
"startswith",
"(",
"'deb'",
")",
"or",
"src",
".",
"startswith",
"(",
"'ppa'",
")",
"or",
"src",
".",
"startswith",
"(",
"'snap'",
")",
")",
":",
"for",
"v",
"in",
"OPENSTACK_CODENAMES",
".",
"values",
"(",
")",
":",
"if",
"v",
"in",
"src",
":",
"return",
"v"
] | Derive OpenStack release codename from a given installation source. | [
"Derive",
"OpenStack",
"release",
"codename",
"from",
"a",
"given",
"installation",
"source",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L322-L348 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_os_version_codename | def get_os_version_codename(codename, version_map=OPENSTACK_CODENAMES):
'''Determine OpenStack version number from codename.'''
for k, v in six.iteritems(version_map):
if v == codename:
return k
e = 'Could not derive OpenStack version for '\
'codename: %s' % codename
error_out(e) | python | def get_os_version_codename(codename, version_map=OPENSTACK_CODENAMES):
'''Determine OpenStack version number from codename.'''
for k, v in six.iteritems(version_map):
if v == codename:
return k
e = 'Could not derive OpenStack version for '\
'codename: %s' % codename
error_out(e) | [
"def",
"get_os_version_codename",
"(",
"codename",
",",
"version_map",
"=",
"OPENSTACK_CODENAMES",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"version_map",
")",
":",
"if",
"v",
"==",
"codename",
":",
"return",
"k",
"e",
"=",
"'Could not derive OpenStack version for '",
"'codename: %s'",
"%",
"codename",
"error_out",
"(",
"e",
")"
] | Determine OpenStack version number from codename. | [
"Determine",
"OpenStack",
"version",
"number",
"from",
"codename",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L365-L372 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_os_version_codename_swift | def get_os_version_codename_swift(codename):
'''Determine OpenStack version number of swift from codename.'''
for k, v in six.iteritems(SWIFT_CODENAMES):
if k == codename:
return v[-1]
e = 'Could not derive swift version for '\
'codename: %s' % codename
error_out(e) | python | def get_os_version_codename_swift(codename):
'''Determine OpenStack version number of swift from codename.'''
for k, v in six.iteritems(SWIFT_CODENAMES):
if k == codename:
return v[-1]
e = 'Could not derive swift version for '\
'codename: %s' % codename
error_out(e) | [
"def",
"get_os_version_codename_swift",
"(",
"codename",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"SWIFT_CODENAMES",
")",
":",
"if",
"k",
"==",
"codename",
":",
"return",
"v",
"[",
"-",
"1",
"]",
"e",
"=",
"'Could not derive swift version for '",
"'codename: %s'",
"%",
"codename",
"error_out",
"(",
"e",
")"
] | Determine OpenStack version number of swift from codename. | [
"Determine",
"OpenStack",
"version",
"number",
"of",
"swift",
"from",
"codename",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L375-L382 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_swift_codename | def get_swift_codename(version):
'''Determine OpenStack codename that corresponds to swift version.'''
codenames = [k for k, v in six.iteritems(SWIFT_CODENAMES) if version in v]
if len(codenames) > 1:
# If more than one release codename contains this version we determine
# the actual codename based on the highest available install source.
for codename in reversed(codenames):
releases = UBUNTU_OPENSTACK_RELEASE
release = [k for k, v in six.iteritems(releases) if codename in v]
ret = subprocess.check_output(['apt-cache', 'policy', 'swift'])
if six.PY3:
ret = ret.decode('UTF-8')
if codename in ret or release[0] in ret:
return codename
elif len(codenames) == 1:
return codenames[0]
# NOTE: fallback - attempt to match with just major.minor version
match = re.match(r'^(\d+)\.(\d+)', version)
if match:
major_minor_version = match.group(0)
for codename, versions in six.iteritems(SWIFT_CODENAMES):
for release_version in versions:
if release_version.startswith(major_minor_version):
return codename
return None | python | def get_swift_codename(version):
'''Determine OpenStack codename that corresponds to swift version.'''
codenames = [k for k, v in six.iteritems(SWIFT_CODENAMES) if version in v]
if len(codenames) > 1:
# If more than one release codename contains this version we determine
# the actual codename based on the highest available install source.
for codename in reversed(codenames):
releases = UBUNTU_OPENSTACK_RELEASE
release = [k for k, v in six.iteritems(releases) if codename in v]
ret = subprocess.check_output(['apt-cache', 'policy', 'swift'])
if six.PY3:
ret = ret.decode('UTF-8')
if codename in ret or release[0] in ret:
return codename
elif len(codenames) == 1:
return codenames[0]
# NOTE: fallback - attempt to match with just major.minor version
match = re.match(r'^(\d+)\.(\d+)', version)
if match:
major_minor_version = match.group(0)
for codename, versions in six.iteritems(SWIFT_CODENAMES):
for release_version in versions:
if release_version.startswith(major_minor_version):
return codename
return None | [
"def",
"get_swift_codename",
"(",
"version",
")",
":",
"codenames",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"SWIFT_CODENAMES",
")",
"if",
"version",
"in",
"v",
"]",
"if",
"len",
"(",
"codenames",
")",
">",
"1",
":",
"# If more than one release codename contains this version we determine",
"# the actual codename based on the highest available install source.",
"for",
"codename",
"in",
"reversed",
"(",
"codenames",
")",
":",
"releases",
"=",
"UBUNTU_OPENSTACK_RELEASE",
"release",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"releases",
")",
"if",
"codename",
"in",
"v",
"]",
"ret",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'apt-cache'",
",",
"'policy'",
",",
"'swift'",
"]",
")",
"if",
"six",
".",
"PY3",
":",
"ret",
"=",
"ret",
".",
"decode",
"(",
"'UTF-8'",
")",
"if",
"codename",
"in",
"ret",
"or",
"release",
"[",
"0",
"]",
"in",
"ret",
":",
"return",
"codename",
"elif",
"len",
"(",
"codenames",
")",
"==",
"1",
":",
"return",
"codenames",
"[",
"0",
"]",
"# NOTE: fallback - attempt to match with just major.minor version",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(\\d+)\\.(\\d+)'",
",",
"version",
")",
"if",
"match",
":",
"major_minor_version",
"=",
"match",
".",
"group",
"(",
"0",
")",
"for",
"codename",
",",
"versions",
"in",
"six",
".",
"iteritems",
"(",
"SWIFT_CODENAMES",
")",
":",
"for",
"release_version",
"in",
"versions",
":",
"if",
"release_version",
".",
"startswith",
"(",
"major_minor_version",
")",
":",
"return",
"codename",
"return",
"None"
] | Determine OpenStack codename that corresponds to swift version. | [
"Determine",
"OpenStack",
"codename",
"that",
"corresponds",
"to",
"swift",
"version",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L385-L412 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_os_codename_package | def get_os_codename_package(package, fatal=True):
'''Derive OpenStack release codename from an installed package.'''
if snap_install_requested():
cmd = ['snap', 'list', package]
try:
out = subprocess.check_output(cmd)
if six.PY3:
out = out.decode('UTF-8')
except subprocess.CalledProcessError:
return None
lines = out.split('\n')
for line in lines:
if package in line:
# Second item in list is Version
return line.split()[1]
import apt_pkg as apt
cache = apt_cache()
try:
pkg = cache[package]
except Exception:
if not fatal:
return None
# the package is unknown to the current apt cache.
e = 'Could not determine version of package with no installation '\
'candidate: %s' % package
error_out(e)
if not pkg.current_ver:
if not fatal:
return None
# package is known, but no version is currently installed.
e = 'Could not determine version of uninstalled package: %s' % package
error_out(e)
vers = apt.upstream_version(pkg.current_ver.ver_str)
if 'swift' in pkg.name:
# Fully x.y.z match for swift versions
match = re.match(r'^(\d+)\.(\d+)\.(\d+)', vers)
else:
# x.y match only for 20XX.X
# and ignore patch level for other packages
match = re.match(r'^(\d+)\.(\d+)', vers)
if match:
vers = match.group(0)
# Generate a major version number for newer semantic
# versions of openstack projects
major_vers = vers.split('.')[0]
# >= Liberty independent project versions
if (package in PACKAGE_CODENAMES and
major_vers in PACKAGE_CODENAMES[package]):
return PACKAGE_CODENAMES[package][major_vers]
else:
# < Liberty co-ordinated project versions
try:
if 'swift' in pkg.name:
return get_swift_codename(vers)
else:
return OPENSTACK_CODENAMES[vers]
except KeyError:
if not fatal:
return None
e = 'Could not determine OpenStack codename for version %s' % vers
error_out(e) | python | def get_os_codename_package(package, fatal=True):
'''Derive OpenStack release codename from an installed package.'''
if snap_install_requested():
cmd = ['snap', 'list', package]
try:
out = subprocess.check_output(cmd)
if six.PY3:
out = out.decode('UTF-8')
except subprocess.CalledProcessError:
return None
lines = out.split('\n')
for line in lines:
if package in line:
# Second item in list is Version
return line.split()[1]
import apt_pkg as apt
cache = apt_cache()
try:
pkg = cache[package]
except Exception:
if not fatal:
return None
# the package is unknown to the current apt cache.
e = 'Could not determine version of package with no installation '\
'candidate: %s' % package
error_out(e)
if not pkg.current_ver:
if not fatal:
return None
# package is known, but no version is currently installed.
e = 'Could not determine version of uninstalled package: %s' % package
error_out(e)
vers = apt.upstream_version(pkg.current_ver.ver_str)
if 'swift' in pkg.name:
# Fully x.y.z match for swift versions
match = re.match(r'^(\d+)\.(\d+)\.(\d+)', vers)
else:
# x.y match only for 20XX.X
# and ignore patch level for other packages
match = re.match(r'^(\d+)\.(\d+)', vers)
if match:
vers = match.group(0)
# Generate a major version number for newer semantic
# versions of openstack projects
major_vers = vers.split('.')[0]
# >= Liberty independent project versions
if (package in PACKAGE_CODENAMES and
major_vers in PACKAGE_CODENAMES[package]):
return PACKAGE_CODENAMES[package][major_vers]
else:
# < Liberty co-ordinated project versions
try:
if 'swift' in pkg.name:
return get_swift_codename(vers)
else:
return OPENSTACK_CODENAMES[vers]
except KeyError:
if not fatal:
return None
e = 'Could not determine OpenStack codename for version %s' % vers
error_out(e) | [
"def",
"get_os_codename_package",
"(",
"package",
",",
"fatal",
"=",
"True",
")",
":",
"if",
"snap_install_requested",
"(",
")",
":",
"cmd",
"=",
"[",
"'snap'",
",",
"'list'",
",",
"package",
"]",
"try",
":",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
"if",
"six",
".",
"PY3",
":",
"out",
"=",
"out",
".",
"decode",
"(",
"'UTF-8'",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"return",
"None",
"lines",
"=",
"out",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"package",
"in",
"line",
":",
"# Second item in list is Version",
"return",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
"import",
"apt_pkg",
"as",
"apt",
"cache",
"=",
"apt_cache",
"(",
")",
"try",
":",
"pkg",
"=",
"cache",
"[",
"package",
"]",
"except",
"Exception",
":",
"if",
"not",
"fatal",
":",
"return",
"None",
"# the package is unknown to the current apt cache.",
"e",
"=",
"'Could not determine version of package with no installation '",
"'candidate: %s'",
"%",
"package",
"error_out",
"(",
"e",
")",
"if",
"not",
"pkg",
".",
"current_ver",
":",
"if",
"not",
"fatal",
":",
"return",
"None",
"# package is known, but no version is currently installed.",
"e",
"=",
"'Could not determine version of uninstalled package: %s'",
"%",
"package",
"error_out",
"(",
"e",
")",
"vers",
"=",
"apt",
".",
"upstream_version",
"(",
"pkg",
".",
"current_ver",
".",
"ver_str",
")",
"if",
"'swift'",
"in",
"pkg",
".",
"name",
":",
"# Fully x.y.z match for swift versions",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(\\d+)\\.(\\d+)\\.(\\d+)'",
",",
"vers",
")",
"else",
":",
"# x.y match only for 20XX.X",
"# and ignore patch level for other packages",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(\\d+)\\.(\\d+)'",
",",
"vers",
")",
"if",
"match",
":",
"vers",
"=",
"match",
".",
"group",
"(",
"0",
")",
"# Generate a major version number for newer semantic",
"# versions of openstack projects",
"major_vers",
"=",
"vers",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"# >= Liberty independent project versions",
"if",
"(",
"package",
"in",
"PACKAGE_CODENAMES",
"and",
"major_vers",
"in",
"PACKAGE_CODENAMES",
"[",
"package",
"]",
")",
":",
"return",
"PACKAGE_CODENAMES",
"[",
"package",
"]",
"[",
"major_vers",
"]",
"else",
":",
"# < Liberty co-ordinated project versions",
"try",
":",
"if",
"'swift'",
"in",
"pkg",
".",
"name",
":",
"return",
"get_swift_codename",
"(",
"vers",
")",
"else",
":",
"return",
"OPENSTACK_CODENAMES",
"[",
"vers",
"]",
"except",
"KeyError",
":",
"if",
"not",
"fatal",
":",
"return",
"None",
"e",
"=",
"'Could not determine OpenStack codename for version %s'",
"%",
"vers",
"error_out",
"(",
"e",
")"
] | Derive OpenStack release codename from an installed package. | [
"Derive",
"OpenStack",
"release",
"codename",
"from",
"an",
"installed",
"package",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L415-L483 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_os_version_package | def get_os_version_package(pkg, fatal=True):
'''Derive OpenStack version number from an installed package.'''
codename = get_os_codename_package(pkg, fatal=fatal)
if not codename:
return None
if 'swift' in pkg:
vers_map = SWIFT_CODENAMES
for cname, version in six.iteritems(vers_map):
if cname == codename:
return version[-1]
else:
vers_map = OPENSTACK_CODENAMES
for version, cname in six.iteritems(vers_map):
if cname == codename:
return version | python | def get_os_version_package(pkg, fatal=True):
'''Derive OpenStack version number from an installed package.'''
codename = get_os_codename_package(pkg, fatal=fatal)
if not codename:
return None
if 'swift' in pkg:
vers_map = SWIFT_CODENAMES
for cname, version in six.iteritems(vers_map):
if cname == codename:
return version[-1]
else:
vers_map = OPENSTACK_CODENAMES
for version, cname in six.iteritems(vers_map):
if cname == codename:
return version | [
"def",
"get_os_version_package",
"(",
"pkg",
",",
"fatal",
"=",
"True",
")",
":",
"codename",
"=",
"get_os_codename_package",
"(",
"pkg",
",",
"fatal",
"=",
"fatal",
")",
"if",
"not",
"codename",
":",
"return",
"None",
"if",
"'swift'",
"in",
"pkg",
":",
"vers_map",
"=",
"SWIFT_CODENAMES",
"for",
"cname",
",",
"version",
"in",
"six",
".",
"iteritems",
"(",
"vers_map",
")",
":",
"if",
"cname",
"==",
"codename",
":",
"return",
"version",
"[",
"-",
"1",
"]",
"else",
":",
"vers_map",
"=",
"OPENSTACK_CODENAMES",
"for",
"version",
",",
"cname",
"in",
"six",
".",
"iteritems",
"(",
"vers_map",
")",
":",
"if",
"cname",
"==",
"codename",
":",
"return",
"version"
] | Derive OpenStack version number from an installed package. | [
"Derive",
"OpenStack",
"version",
"number",
"from",
"an",
"installed",
"package",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L486-L502 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | os_release | def os_release(package, base='essex', reset_cache=False):
'''
Returns OpenStack release codename from a cached global.
If reset_cache then unset the cached os_release version and return the
freshly determined version.
If the codename can not be determined from either an installed package or
the installation source, the earliest release supported by the charm should
be returned.
'''
global _os_rel
if reset_cache:
reset_os_release()
if _os_rel:
return _os_rel
_os_rel = (
get_os_codename_package(package, fatal=False) or
get_os_codename_install_source(config('openstack-origin')) or
base)
return _os_rel | python | def os_release(package, base='essex', reset_cache=False):
'''
Returns OpenStack release codename from a cached global.
If reset_cache then unset the cached os_release version and return the
freshly determined version.
If the codename can not be determined from either an installed package or
the installation source, the earliest release supported by the charm should
be returned.
'''
global _os_rel
if reset_cache:
reset_os_release()
if _os_rel:
return _os_rel
_os_rel = (
get_os_codename_package(package, fatal=False) or
get_os_codename_install_source(config('openstack-origin')) or
base)
return _os_rel | [
"def",
"os_release",
"(",
"package",
",",
"base",
"=",
"'essex'",
",",
"reset_cache",
"=",
"False",
")",
":",
"global",
"_os_rel",
"if",
"reset_cache",
":",
"reset_os_release",
"(",
")",
"if",
"_os_rel",
":",
"return",
"_os_rel",
"_os_rel",
"=",
"(",
"get_os_codename_package",
"(",
"package",
",",
"fatal",
"=",
"False",
")",
"or",
"get_os_codename_install_source",
"(",
"config",
"(",
"'openstack-origin'",
")",
")",
"or",
"base",
")",
"return",
"_os_rel"
] | Returns OpenStack release codename from a cached global.
If reset_cache then unset the cached os_release version and return the
freshly determined version.
If the codename can not be determined from either an installed package or
the installation source, the earliest release supported by the charm should
be returned. | [
"Returns",
"OpenStack",
"release",
"codename",
"from",
"a",
"cached",
"global",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L517-L537 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | import_key | def import_key(keyid):
"""Import a key, either ASCII armored, or a GPG key id.
@param keyid: the key in ASCII armor format, or a GPG key id.
@raises SystemExit() via sys.exit() on failure.
"""
try:
return fetch_import_key(keyid)
except GPGKeyError as e:
error_out("Could not import key: {}".format(str(e))) | python | def import_key(keyid):
"""Import a key, either ASCII armored, or a GPG key id.
@param keyid: the key in ASCII armor format, or a GPG key id.
@raises SystemExit() via sys.exit() on failure.
"""
try:
return fetch_import_key(keyid)
except GPGKeyError as e:
error_out("Could not import key: {}".format(str(e))) | [
"def",
"import_key",
"(",
"keyid",
")",
":",
"try",
":",
"return",
"fetch_import_key",
"(",
"keyid",
")",
"except",
"GPGKeyError",
"as",
"e",
":",
"error_out",
"(",
"\"Could not import key: {}\"",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")"
] | Import a key, either ASCII armored, or a GPG key id.
@param keyid: the key in ASCII armor format, or a GPG key id.
@raises SystemExit() via sys.exit() on failure. | [
"Import",
"a",
"key",
"either",
"ASCII",
"armored",
"or",
"a",
"GPG",
"key",
"id",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L541-L550 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_source_and_pgp_key | def get_source_and_pgp_key(source_and_key):
"""Look for a pgp key ID or ascii-armor key in the given input.
:param source_and_key: Sting, "source_spec|keyid" where '|keyid' is
optional.
:returns (source_spec, key_id OR None) as a tuple. Returns None for key_id
if there was no '|' in the source_and_key string.
"""
try:
source, key = source_and_key.split('|', 2)
return source, key or None
except ValueError:
return source_and_key, None | python | def get_source_and_pgp_key(source_and_key):
"""Look for a pgp key ID or ascii-armor key in the given input.
:param source_and_key: Sting, "source_spec|keyid" where '|keyid' is
optional.
:returns (source_spec, key_id OR None) as a tuple. Returns None for key_id
if there was no '|' in the source_and_key string.
"""
try:
source, key = source_and_key.split('|', 2)
return source, key or None
except ValueError:
return source_and_key, None | [
"def",
"get_source_and_pgp_key",
"(",
"source_and_key",
")",
":",
"try",
":",
"source",
",",
"key",
"=",
"source_and_key",
".",
"split",
"(",
"'|'",
",",
"2",
")",
"return",
"source",
",",
"key",
"or",
"None",
"except",
"ValueError",
":",
"return",
"source_and_key",
",",
"None"
] | Look for a pgp key ID or ascii-armor key in the given input.
:param source_and_key: Sting, "source_spec|keyid" where '|keyid' is
optional.
:returns (source_spec, key_id OR None) as a tuple. Returns None for key_id
if there was no '|' in the source_and_key string. | [
"Look",
"for",
"a",
"pgp",
"key",
"ID",
"or",
"ascii",
"-",
"armor",
"key",
"in",
"the",
"given",
"input",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L553-L565 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | configure_installation_source | def configure_installation_source(source_plus_key):
"""Configure an installation source.
The functionality is provided by charmhelpers.fetch.add_source()
The difference between the two functions is that add_source() signature
requires the key to be passed directly, whereas this function passes an
optional key by appending '|<key>' to the end of the source specificiation
'source'.
Another difference from add_source() is that the function calls sys.exit(1)
if the configuration fails, whereas add_source() raises
SourceConfigurationError(). Another difference, is that add_source()
silently fails (with a juju_log command) if there is no matching source to
configure, whereas this function fails with a sys.exit(1)
:param source: String_plus_key -- see above for details.
Note that the behaviour on error is to log the error to the juju log and
then call sys.exit(1).
"""
if source_plus_key.startswith('snap'):
# Do nothing for snap installs
return
# extract the key if there is one, denoted by a '|' in the rel
source, key = get_source_and_pgp_key(source_plus_key)
# handle the ordinary sources via add_source
try:
fetch_add_source(source, key, fail_invalid=True)
except SourceConfigError as se:
error_out(str(se)) | python | def configure_installation_source(source_plus_key):
"""Configure an installation source.
The functionality is provided by charmhelpers.fetch.add_source()
The difference between the two functions is that add_source() signature
requires the key to be passed directly, whereas this function passes an
optional key by appending '|<key>' to the end of the source specificiation
'source'.
Another difference from add_source() is that the function calls sys.exit(1)
if the configuration fails, whereas add_source() raises
SourceConfigurationError(). Another difference, is that add_source()
silently fails (with a juju_log command) if there is no matching source to
configure, whereas this function fails with a sys.exit(1)
:param source: String_plus_key -- see above for details.
Note that the behaviour on error is to log the error to the juju log and
then call sys.exit(1).
"""
if source_plus_key.startswith('snap'):
# Do nothing for snap installs
return
# extract the key if there is one, denoted by a '|' in the rel
source, key = get_source_and_pgp_key(source_plus_key)
# handle the ordinary sources via add_source
try:
fetch_add_source(source, key, fail_invalid=True)
except SourceConfigError as se:
error_out(str(se)) | [
"def",
"configure_installation_source",
"(",
"source_plus_key",
")",
":",
"if",
"source_plus_key",
".",
"startswith",
"(",
"'snap'",
")",
":",
"# Do nothing for snap installs",
"return",
"# extract the key if there is one, denoted by a '|' in the rel",
"source",
",",
"key",
"=",
"get_source_and_pgp_key",
"(",
"source_plus_key",
")",
"# handle the ordinary sources via add_source",
"try",
":",
"fetch_add_source",
"(",
"source",
",",
"key",
",",
"fail_invalid",
"=",
"True",
")",
"except",
"SourceConfigError",
"as",
"se",
":",
"error_out",
"(",
"str",
"(",
"se",
")",
")"
] | Configure an installation source.
The functionality is provided by charmhelpers.fetch.add_source()
The difference between the two functions is that add_source() signature
requires the key to be passed directly, whereas this function passes an
optional key by appending '|<key>' to the end of the source specificiation
'source'.
Another difference from add_source() is that the function calls sys.exit(1)
if the configuration fails, whereas add_source() raises
SourceConfigurationError(). Another difference, is that add_source()
silently fails (with a juju_log command) if there is no matching source to
configure, whereas this function fails with a sys.exit(1)
:param source: String_plus_key -- see above for details.
Note that the behaviour on error is to log the error to the juju log and
then call sys.exit(1). | [
"Configure",
"an",
"installation",
"source",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L570-L600 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | config_value_changed | def config_value_changed(option):
"""
Determine if config value changed since last call to this function.
"""
hook_data = unitdata.HookData()
with hook_data():
db = unitdata.kv()
current = config(option)
saved = db.get(option)
db.set(option, current)
if saved is None:
return False
return current != saved | python | def config_value_changed(option):
"""
Determine if config value changed since last call to this function.
"""
hook_data = unitdata.HookData()
with hook_data():
db = unitdata.kv()
current = config(option)
saved = db.get(option)
db.set(option, current)
if saved is None:
return False
return current != saved | [
"def",
"config_value_changed",
"(",
"option",
")",
":",
"hook_data",
"=",
"unitdata",
".",
"HookData",
"(",
")",
"with",
"hook_data",
"(",
")",
":",
"db",
"=",
"unitdata",
".",
"kv",
"(",
")",
"current",
"=",
"config",
"(",
"option",
")",
"saved",
"=",
"db",
".",
"get",
"(",
"option",
")",
"db",
".",
"set",
"(",
"option",
",",
"current",
")",
"if",
"saved",
"is",
"None",
":",
"return",
"False",
"return",
"current",
"!=",
"saved"
] | Determine if config value changed since last call to this function. | [
"Determine",
"if",
"config",
"value",
"changed",
"since",
"last",
"call",
"to",
"this",
"function",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L603-L615 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | save_script_rc | def save_script_rc(script_path="scripts/scriptrc", **env_vars):
"""
Write an rc file in the charm-delivered directory containing
exported environment variables provided by env_vars. Any charm scripts run
outside the juju hook environment can source this scriptrc to obtain
updated config information necessary to perform health checks or
service changes.
"""
juju_rc_path = "%s/%s" % (charm_dir(), script_path)
if not os.path.exists(os.path.dirname(juju_rc_path)):
os.mkdir(os.path.dirname(juju_rc_path))
with open(juju_rc_path, 'wt') as rc_script:
rc_script.write(
"#!/bin/bash\n")
[rc_script.write('export %s=%s\n' % (u, p))
for u, p in six.iteritems(env_vars) if u != "script_path"] | python | def save_script_rc(script_path="scripts/scriptrc", **env_vars):
"""
Write an rc file in the charm-delivered directory containing
exported environment variables provided by env_vars. Any charm scripts run
outside the juju hook environment can source this scriptrc to obtain
updated config information necessary to perform health checks or
service changes.
"""
juju_rc_path = "%s/%s" % (charm_dir(), script_path)
if not os.path.exists(os.path.dirname(juju_rc_path)):
os.mkdir(os.path.dirname(juju_rc_path))
with open(juju_rc_path, 'wt') as rc_script:
rc_script.write(
"#!/bin/bash\n")
[rc_script.write('export %s=%s\n' % (u, p))
for u, p in six.iteritems(env_vars) if u != "script_path"] | [
"def",
"save_script_rc",
"(",
"script_path",
"=",
"\"scripts/scriptrc\"",
",",
"*",
"*",
"env_vars",
")",
":",
"juju_rc_path",
"=",
"\"%s/%s\"",
"%",
"(",
"charm_dir",
"(",
")",
",",
"script_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"juju_rc_path",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"juju_rc_path",
")",
")",
"with",
"open",
"(",
"juju_rc_path",
",",
"'wt'",
")",
"as",
"rc_script",
":",
"rc_script",
".",
"write",
"(",
"\"#!/bin/bash\\n\"",
")",
"[",
"rc_script",
".",
"write",
"(",
"'export %s=%s\\n'",
"%",
"(",
"u",
",",
"p",
")",
")",
"for",
"u",
",",
"p",
"in",
"six",
".",
"iteritems",
"(",
"env_vars",
")",
"if",
"u",
"!=",
"\"script_path\"",
"]"
] | Write an rc file in the charm-delivered directory containing
exported environment variables provided by env_vars. Any charm scripts run
outside the juju hook environment can source this scriptrc to obtain
updated config information necessary to perform health checks or
service changes. | [
"Write",
"an",
"rc",
"file",
"in",
"the",
"charm",
"-",
"delivered",
"directory",
"containing",
"exported",
"environment",
"variables",
"provided",
"by",
"env_vars",
".",
"Any",
"charm",
"scripts",
"run",
"outside",
"the",
"juju",
"hook",
"environment",
"can",
"source",
"this",
"scriptrc",
"to",
"obtain",
"updated",
"config",
"information",
"necessary",
"to",
"perform",
"health",
"checks",
"or",
"service",
"changes",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L618-L633 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | openstack_upgrade_available | def openstack_upgrade_available(package):
"""
Determines if an OpenStack upgrade is available from installation
source, based on version of installed package.
:param package: str: Name of installed package.
:returns: bool: : Returns True if configured installation source offers
a newer version of package.
"""
import apt_pkg as apt
src = config('openstack-origin')
cur_vers = get_os_version_package(package)
if not cur_vers:
# The package has not been installed yet do not attempt upgrade
return False
if "swift" in package:
codename = get_os_codename_install_source(src)
avail_vers = get_os_version_codename_swift(codename)
else:
avail_vers = get_os_version_install_source(src)
apt.init()
return apt.version_compare(avail_vers, cur_vers) >= 1 | python | def openstack_upgrade_available(package):
"""
Determines if an OpenStack upgrade is available from installation
source, based on version of installed package.
:param package: str: Name of installed package.
:returns: bool: : Returns True if configured installation source offers
a newer version of package.
"""
import apt_pkg as apt
src = config('openstack-origin')
cur_vers = get_os_version_package(package)
if not cur_vers:
# The package has not been installed yet do not attempt upgrade
return False
if "swift" in package:
codename = get_os_codename_install_source(src)
avail_vers = get_os_version_codename_swift(codename)
else:
avail_vers = get_os_version_install_source(src)
apt.init()
return apt.version_compare(avail_vers, cur_vers) >= 1 | [
"def",
"openstack_upgrade_available",
"(",
"package",
")",
":",
"import",
"apt_pkg",
"as",
"apt",
"src",
"=",
"config",
"(",
"'openstack-origin'",
")",
"cur_vers",
"=",
"get_os_version_package",
"(",
"package",
")",
"if",
"not",
"cur_vers",
":",
"# The package has not been installed yet do not attempt upgrade",
"return",
"False",
"if",
"\"swift\"",
"in",
"package",
":",
"codename",
"=",
"get_os_codename_install_source",
"(",
"src",
")",
"avail_vers",
"=",
"get_os_version_codename_swift",
"(",
"codename",
")",
"else",
":",
"avail_vers",
"=",
"get_os_version_install_source",
"(",
"src",
")",
"apt",
".",
"init",
"(",
")",
"return",
"apt",
".",
"version_compare",
"(",
"avail_vers",
",",
"cur_vers",
")",
">=",
"1"
] | Determines if an OpenStack upgrade is available from installation
source, based on version of installed package.
:param package: str: Name of installed package.
:returns: bool: : Returns True if configured installation source offers
a newer version of package. | [
"Determines",
"if",
"an",
"OpenStack",
"upgrade",
"is",
"available",
"from",
"installation",
"source",
"based",
"on",
"version",
"of",
"installed",
"package",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L636-L659 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | ensure_block_device | def ensure_block_device(block_device):
'''
Confirm block_device, create as loopback if necessary.
:param block_device: str: Full path of block device to ensure.
:returns: str: Full path of ensured block device.
'''
_none = ['None', 'none', None]
if (block_device in _none):
error_out('prepare_storage(): Missing required input: block_device=%s.'
% block_device)
if block_device.startswith('/dev/'):
bdev = block_device
elif block_device.startswith('/'):
_bd = block_device.split('|')
if len(_bd) == 2:
bdev, size = _bd
else:
bdev = block_device
size = DEFAULT_LOOPBACK_SIZE
bdev = ensure_loopback_device(bdev, size)
else:
bdev = '/dev/%s' % block_device
if not is_block_device(bdev):
error_out('Failed to locate valid block device at %s' % bdev)
return bdev | python | def ensure_block_device(block_device):
'''
Confirm block_device, create as loopback if necessary.
:param block_device: str: Full path of block device to ensure.
:returns: str: Full path of ensured block device.
'''
_none = ['None', 'none', None]
if (block_device in _none):
error_out('prepare_storage(): Missing required input: block_device=%s.'
% block_device)
if block_device.startswith('/dev/'):
bdev = block_device
elif block_device.startswith('/'):
_bd = block_device.split('|')
if len(_bd) == 2:
bdev, size = _bd
else:
bdev = block_device
size = DEFAULT_LOOPBACK_SIZE
bdev = ensure_loopback_device(bdev, size)
else:
bdev = '/dev/%s' % block_device
if not is_block_device(bdev):
error_out('Failed to locate valid block device at %s' % bdev)
return bdev | [
"def",
"ensure_block_device",
"(",
"block_device",
")",
":",
"_none",
"=",
"[",
"'None'",
",",
"'none'",
",",
"None",
"]",
"if",
"(",
"block_device",
"in",
"_none",
")",
":",
"error_out",
"(",
"'prepare_storage(): Missing required input: block_device=%s.'",
"%",
"block_device",
")",
"if",
"block_device",
".",
"startswith",
"(",
"'/dev/'",
")",
":",
"bdev",
"=",
"block_device",
"elif",
"block_device",
".",
"startswith",
"(",
"'/'",
")",
":",
"_bd",
"=",
"block_device",
".",
"split",
"(",
"'|'",
")",
"if",
"len",
"(",
"_bd",
")",
"==",
"2",
":",
"bdev",
",",
"size",
"=",
"_bd",
"else",
":",
"bdev",
"=",
"block_device",
"size",
"=",
"DEFAULT_LOOPBACK_SIZE",
"bdev",
"=",
"ensure_loopback_device",
"(",
"bdev",
",",
"size",
")",
"else",
":",
"bdev",
"=",
"'/dev/%s'",
"%",
"block_device",
"if",
"not",
"is_block_device",
"(",
"bdev",
")",
":",
"error_out",
"(",
"'Failed to locate valid block device at %s'",
"%",
"bdev",
")",
"return",
"bdev"
] | Confirm block_device, create as loopback if necessary.
:param block_device: str: Full path of block device to ensure.
:returns: str: Full path of ensured block device. | [
"Confirm",
"block_device",
"create",
"as",
"loopback",
"if",
"necessary",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L662-L691 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | os_requires_version | def os_requires_version(ostack_release, pkg):
"""
Decorator for hook to specify minimum supported release
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args):
if os_release(pkg) < ostack_release:
raise Exception("This hook is not supported on releases"
" before %s" % ostack_release)
f(*args)
return wrapped_f
return wrap | python | def os_requires_version(ostack_release, pkg):
"""
Decorator for hook to specify minimum supported release
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args):
if os_release(pkg) < ostack_release:
raise Exception("This hook is not supported on releases"
" before %s" % ostack_release)
f(*args)
return wrapped_f
return wrap | [
"def",
"os_requires_version",
"(",
"ostack_release",
",",
"pkg",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
")",
":",
"if",
"os_release",
"(",
"pkg",
")",
"<",
"ostack_release",
":",
"raise",
"Exception",
"(",
"\"This hook is not supported on releases\"",
"\" before %s\"",
"%",
"ostack_release",
")",
"f",
"(",
"*",
"args",
")",
"return",
"wrapped_f",
"return",
"wrap"
] | Decorator for hook to specify minimum supported release | [
"Decorator",
"for",
"hook",
"to",
"specify",
"minimum",
"supported",
"release"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L754-L766 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | os_workload_status | def os_workload_status(configs, required_interfaces, charm_func=None):
"""
Decorator to set workload status based on complete contexts
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# Run the original function first
f(*args, **kwargs)
# Set workload status now that contexts have been
# acted on
set_os_workload_status(configs, required_interfaces, charm_func)
return wrapped_f
return wrap | python | def os_workload_status(configs, required_interfaces, charm_func=None):
"""
Decorator to set workload status based on complete contexts
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# Run the original function first
f(*args, **kwargs)
# Set workload status now that contexts have been
# acted on
set_os_workload_status(configs, required_interfaces, charm_func)
return wrapped_f
return wrap | [
"def",
"os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Run the original function first",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Set workload status now that contexts have been",
"# acted on",
"set_os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
")",
"return",
"wrapped_f",
"return",
"wrap"
] | Decorator to set workload status based on complete contexts | [
"Decorator",
"to",
"set",
"workload",
"status",
"based",
"on",
"complete",
"contexts"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L769-L782 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | set_os_workload_status | def set_os_workload_status(configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Set the state of the workload status for the charm.
This calls _determine_os_workload_status() to get the new state, message
and sets the status using status_set()
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _determine_os_workload_status(
configs, required_interfaces, charm_func, services, ports)
status_set(state, message) | python | def set_os_workload_status(configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Set the state of the workload status for the charm.
This calls _determine_os_workload_status() to get the new state, message
and sets the status using status_set()
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _determine_os_workload_status(
configs, required_interfaces, charm_func, services, ports)
status_set(state, message) | [
"def",
"set_os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
"=",
"None",
",",
"services",
"=",
"None",
",",
"ports",
"=",
"None",
")",
":",
"state",
",",
"message",
"=",
"_determine_os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
",",
"services",
",",
"ports",
")",
"status_set",
"(",
"state",
",",
"message",
")"
] | Set the state of the workload status for the charm.
This calls _determine_os_workload_status() to get the new state, message
and sets the status using status_set()
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message | [
"Set",
"the",
"state",
"of",
"the",
"workload",
"status",
"for",
"the",
"charm",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L785-L802 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | _determine_os_workload_status | def _determine_os_workload_status(
configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and whether the
services are actually running and any specified ports are open.
This checks:
1. if the unit should be paused, that it is actually paused. If so the
state is 'maintenance' + message, else 'broken'.
2. that the interfaces/relations are complete. If they are not then
it sets the state to either 'broken' or 'waiting' and an appropriate
message.
3. If all the relation data is set, then it checks that the actual
services really are running. If not it sets the state to 'broken'.
If everything is okay then the state returns 'active'.
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _ows_check_if_paused(services, ports)
if state is None:
state, message = _ows_check_generic_interfaces(
configs, required_interfaces)
if state != 'maintenance' and charm_func:
# _ows_check_charm_func() may modify the state, message
state, message = _ows_check_charm_func(
state, message, lambda: charm_func(configs))
if state is None:
state, message = _ows_check_services_running(services, ports)
if state is None:
state = 'active'
message = "Unit is ready"
juju_log(message, 'INFO')
return state, message | python | def _determine_os_workload_status(
configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and whether the
services are actually running and any specified ports are open.
This checks:
1. if the unit should be paused, that it is actually paused. If so the
state is 'maintenance' + message, else 'broken'.
2. that the interfaces/relations are complete. If they are not then
it sets the state to either 'broken' or 'waiting' and an appropriate
message.
3. If all the relation data is set, then it checks that the actual
services really are running. If not it sets the state to 'broken'.
If everything is okay then the state returns 'active'.
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _ows_check_if_paused(services, ports)
if state is None:
state, message = _ows_check_generic_interfaces(
configs, required_interfaces)
if state != 'maintenance' and charm_func:
# _ows_check_charm_func() may modify the state, message
state, message = _ows_check_charm_func(
state, message, lambda: charm_func(configs))
if state is None:
state, message = _ows_check_services_running(services, ports)
if state is None:
state = 'active'
message = "Unit is ready"
juju_log(message, 'INFO')
return state, message | [
"def",
"_determine_os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
"=",
"None",
",",
"services",
"=",
"None",
",",
"ports",
"=",
"None",
")",
":",
"state",
",",
"message",
"=",
"_ows_check_if_paused",
"(",
"services",
",",
"ports",
")",
"if",
"state",
"is",
"None",
":",
"state",
",",
"message",
"=",
"_ows_check_generic_interfaces",
"(",
"configs",
",",
"required_interfaces",
")",
"if",
"state",
"!=",
"'maintenance'",
"and",
"charm_func",
":",
"# _ows_check_charm_func() may modify the state, message",
"state",
",",
"message",
"=",
"_ows_check_charm_func",
"(",
"state",
",",
"message",
",",
"lambda",
":",
"charm_func",
"(",
"configs",
")",
")",
"if",
"state",
"is",
"None",
":",
"state",
",",
"message",
"=",
"_ows_check_services_running",
"(",
"services",
",",
"ports",
")",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"'active'",
"message",
"=",
"\"Unit is ready\"",
"juju_log",
"(",
"message",
",",
"'INFO'",
")",
"return",
"state",
",",
"message"
] | Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and whether the
services are actually running and any specified ports are open.
This checks:
1. if the unit should be paused, that it is actually paused. If so the
state is 'maintenance' + message, else 'broken'.
2. that the interfaces/relations are complete. If they are not then
it sets the state to either 'broken' or 'waiting' and an appropriate
message.
3. If all the relation data is set, then it checks that the actual
services really are running. If not it sets the state to 'broken'.
If everything is okay then the state returns 'active'.
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message | [
"Determine",
"the",
"state",
"of",
"the",
"workload",
"status",
"for",
"the",
"charm",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L805-L853 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | _ows_check_generic_interfaces | def _ows_check_generic_interfaces(configs, required_interfaces):
"""Check the complete contexts to determine the workload status.
- Checks for missing or incomplete contexts
- juju log details of missing required data.
- determines the correct workload status
- creates an appropriate message for status_set(...)
if there are no problems then the function returns None, None
@param configs: a templating.OSConfigRenderer() object
@params required_interfaces: {generic_interface: [specific_interface], }
@returns state, message or None, None
"""
incomplete_rel_data = incomplete_relation_data(configs,
required_interfaces)
state = None
message = None
missing_relations = set()
incomplete_relations = set()
for generic_interface, relations_states in incomplete_rel_data.items():
related_interface = None
missing_data = {}
# Related or not?
for interface, relation_state in relations_states.items():
if relation_state.get('related'):
related_interface = interface
missing_data = relation_state.get('missing_data')
break
# No relation ID for the generic_interface?
if not related_interface:
juju_log("{} relation is missing and must be related for "
"functionality. ".format(generic_interface), 'WARN')
state = 'blocked'
missing_relations.add(generic_interface)
else:
# Relation ID eists but no related unit
if not missing_data:
# Edge case - relation ID exists but departings
_hook_name = hook_name()
if (('departed' in _hook_name or 'broken' in _hook_name) and
related_interface in _hook_name):
state = 'blocked'
missing_relations.add(generic_interface)
juju_log("{} relation's interface, {}, "
"relationship is departed or broken "
"and is required for functionality."
"".format(generic_interface, related_interface),
"WARN")
# Normal case relation ID exists but no related unit
# (joining)
else:
juju_log("{} relations's interface, {}, is related but has"
" no units in the relation."
"".format(generic_interface, related_interface),
"INFO")
# Related unit exists and data missing on the relation
else:
juju_log("{} relation's interface, {}, is related awaiting "
"the following data from the relationship: {}. "
"".format(generic_interface, related_interface,
", ".join(missing_data)), "INFO")
if state != 'blocked':
state = 'waiting'
if generic_interface not in missing_relations:
incomplete_relations.add(generic_interface)
if missing_relations:
message = "Missing relations: {}".format(", ".join(missing_relations))
if incomplete_relations:
message += "; incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'blocked'
elif incomplete_relations:
message = "Incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'waiting'
return state, message | python | def _ows_check_generic_interfaces(configs, required_interfaces):
"""Check the complete contexts to determine the workload status.
- Checks for missing or incomplete contexts
- juju log details of missing required data.
- determines the correct workload status
- creates an appropriate message for status_set(...)
if there are no problems then the function returns None, None
@param configs: a templating.OSConfigRenderer() object
@params required_interfaces: {generic_interface: [specific_interface], }
@returns state, message or None, None
"""
incomplete_rel_data = incomplete_relation_data(configs,
required_interfaces)
state = None
message = None
missing_relations = set()
incomplete_relations = set()
for generic_interface, relations_states in incomplete_rel_data.items():
related_interface = None
missing_data = {}
# Related or not?
for interface, relation_state in relations_states.items():
if relation_state.get('related'):
related_interface = interface
missing_data = relation_state.get('missing_data')
break
# No relation ID for the generic_interface?
if not related_interface:
juju_log("{} relation is missing and must be related for "
"functionality. ".format(generic_interface), 'WARN')
state = 'blocked'
missing_relations.add(generic_interface)
else:
# Relation ID eists but no related unit
if not missing_data:
# Edge case - relation ID exists but departings
_hook_name = hook_name()
if (('departed' in _hook_name or 'broken' in _hook_name) and
related_interface in _hook_name):
state = 'blocked'
missing_relations.add(generic_interface)
juju_log("{} relation's interface, {}, "
"relationship is departed or broken "
"and is required for functionality."
"".format(generic_interface, related_interface),
"WARN")
# Normal case relation ID exists but no related unit
# (joining)
else:
juju_log("{} relations's interface, {}, is related but has"
" no units in the relation."
"".format(generic_interface, related_interface),
"INFO")
# Related unit exists and data missing on the relation
else:
juju_log("{} relation's interface, {}, is related awaiting "
"the following data from the relationship: {}. "
"".format(generic_interface, related_interface,
", ".join(missing_data)), "INFO")
if state != 'blocked':
state = 'waiting'
if generic_interface not in missing_relations:
incomplete_relations.add(generic_interface)
if missing_relations:
message = "Missing relations: {}".format(", ".join(missing_relations))
if incomplete_relations:
message += "; incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'blocked'
elif incomplete_relations:
message = "Incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'waiting'
return state, message | [
"def",
"_ows_check_generic_interfaces",
"(",
"configs",
",",
"required_interfaces",
")",
":",
"incomplete_rel_data",
"=",
"incomplete_relation_data",
"(",
"configs",
",",
"required_interfaces",
")",
"state",
"=",
"None",
"message",
"=",
"None",
"missing_relations",
"=",
"set",
"(",
")",
"incomplete_relations",
"=",
"set",
"(",
")",
"for",
"generic_interface",
",",
"relations_states",
"in",
"incomplete_rel_data",
".",
"items",
"(",
")",
":",
"related_interface",
"=",
"None",
"missing_data",
"=",
"{",
"}",
"# Related or not?",
"for",
"interface",
",",
"relation_state",
"in",
"relations_states",
".",
"items",
"(",
")",
":",
"if",
"relation_state",
".",
"get",
"(",
"'related'",
")",
":",
"related_interface",
"=",
"interface",
"missing_data",
"=",
"relation_state",
".",
"get",
"(",
"'missing_data'",
")",
"break",
"# No relation ID for the generic_interface?",
"if",
"not",
"related_interface",
":",
"juju_log",
"(",
"\"{} relation is missing and must be related for \"",
"\"functionality. \"",
".",
"format",
"(",
"generic_interface",
")",
",",
"'WARN'",
")",
"state",
"=",
"'blocked'",
"missing_relations",
".",
"add",
"(",
"generic_interface",
")",
"else",
":",
"# Relation ID eists but no related unit",
"if",
"not",
"missing_data",
":",
"# Edge case - relation ID exists but departings",
"_hook_name",
"=",
"hook_name",
"(",
")",
"if",
"(",
"(",
"'departed'",
"in",
"_hook_name",
"or",
"'broken'",
"in",
"_hook_name",
")",
"and",
"related_interface",
"in",
"_hook_name",
")",
":",
"state",
"=",
"'blocked'",
"missing_relations",
".",
"add",
"(",
"generic_interface",
")",
"juju_log",
"(",
"\"{} relation's interface, {}, \"",
"\"relationship is departed or broken \"",
"\"and is required for functionality.\"",
"\"\"",
".",
"format",
"(",
"generic_interface",
",",
"related_interface",
")",
",",
"\"WARN\"",
")",
"# Normal case relation ID exists but no related unit",
"# (joining)",
"else",
":",
"juju_log",
"(",
"\"{} relations's interface, {}, is related but has\"",
"\" no units in the relation.\"",
"\"\"",
".",
"format",
"(",
"generic_interface",
",",
"related_interface",
")",
",",
"\"INFO\"",
")",
"# Related unit exists and data missing on the relation",
"else",
":",
"juju_log",
"(",
"\"{} relation's interface, {}, is related awaiting \"",
"\"the following data from the relationship: {}. \"",
"\"\"",
".",
"format",
"(",
"generic_interface",
",",
"related_interface",
",",
"\", \"",
".",
"join",
"(",
"missing_data",
")",
")",
",",
"\"INFO\"",
")",
"if",
"state",
"!=",
"'blocked'",
":",
"state",
"=",
"'waiting'",
"if",
"generic_interface",
"not",
"in",
"missing_relations",
":",
"incomplete_relations",
".",
"add",
"(",
"generic_interface",
")",
"if",
"missing_relations",
":",
"message",
"=",
"\"Missing relations: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"missing_relations",
")",
")",
"if",
"incomplete_relations",
":",
"message",
"+=",
"\"; incomplete relations: {}\"",
"\"\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"incomplete_relations",
")",
")",
"state",
"=",
"'blocked'",
"elif",
"incomplete_relations",
":",
"message",
"=",
"\"Incomplete relations: {}\"",
"\"\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"incomplete_relations",
")",
")",
"state",
"=",
"'waiting'",
"return",
"state",
",",
"message"
] | Check the complete contexts to determine the workload status.
- Checks for missing or incomplete contexts
- juju log details of missing required data.
- determines the correct workload status
- creates an appropriate message for status_set(...)
if there are no problems then the function returns None, None
@param configs: a templating.OSConfigRenderer() object
@params required_interfaces: {generic_interface: [specific_interface], }
@returns state, message or None, None | [
"Check",
"the",
"complete",
"contexts",
"to",
"determine",
"the",
"workload",
"status",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L890-L969 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | _ows_check_services_running | def _ows_check_services_running(services, ports):
"""Check that the services that should be running are actually running
and that any ports specified are being listened to.
@param services: list of strings OR dictionary specifying services/ports
@param ports: list of ports
@returns state, message: strings or None, None
"""
messages = []
state = None
if services is not None:
services = _extract_services_list_helper(services)
services_running, running = _check_running_services(services)
if not all(running):
messages.append(
"Services not running that should be: {}"
.format(", ".join(_filter_tuples(services_running, False))))
state = 'blocked'
# also verify that the ports that should be open are open
# NB, that ServiceManager objects only OPTIONALLY have ports
map_not_open, ports_open = (
_check_listening_on_services_ports(services))
if not all(ports_open):
# find which service has missing ports. They are in service
# order which makes it a bit easier.
message_parts = {service: ", ".join([str(v) for v in open_ports])
for service, open_ports in map_not_open.items()}
message = ", ".join(
["{}: [{}]".format(s, sp) for s, sp in message_parts.items()])
messages.append(
"Services with ports not open that should be: {}"
.format(message))
state = 'blocked'
if ports is not None:
# and we can also check ports which we don't know the service for
ports_open, ports_open_bools = _check_listening_on_ports_list(ports)
if not all(ports_open_bools):
messages.append(
"Ports which should be open, but are not: {}"
.format(", ".join([str(p) for p, v in ports_open
if not v])))
state = 'blocked'
if state is not None:
message = "; ".join(messages)
return state, message
return None, None | python | def _ows_check_services_running(services, ports):
"""Check that the services that should be running are actually running
and that any ports specified are being listened to.
@param services: list of strings OR dictionary specifying services/ports
@param ports: list of ports
@returns state, message: strings or None, None
"""
messages = []
state = None
if services is not None:
services = _extract_services_list_helper(services)
services_running, running = _check_running_services(services)
if not all(running):
messages.append(
"Services not running that should be: {}"
.format(", ".join(_filter_tuples(services_running, False))))
state = 'blocked'
# also verify that the ports that should be open are open
# NB, that ServiceManager objects only OPTIONALLY have ports
map_not_open, ports_open = (
_check_listening_on_services_ports(services))
if not all(ports_open):
# find which service has missing ports. They are in service
# order which makes it a bit easier.
message_parts = {service: ", ".join([str(v) for v in open_ports])
for service, open_ports in map_not_open.items()}
message = ", ".join(
["{}: [{}]".format(s, sp) for s, sp in message_parts.items()])
messages.append(
"Services with ports not open that should be: {}"
.format(message))
state = 'blocked'
if ports is not None:
# and we can also check ports which we don't know the service for
ports_open, ports_open_bools = _check_listening_on_ports_list(ports)
if not all(ports_open_bools):
messages.append(
"Ports which should be open, but are not: {}"
.format(", ".join([str(p) for p, v in ports_open
if not v])))
state = 'blocked'
if state is not None:
message = "; ".join(messages)
return state, message
return None, None | [
"def",
"_ows_check_services_running",
"(",
"services",
",",
"ports",
")",
":",
"messages",
"=",
"[",
"]",
"state",
"=",
"None",
"if",
"services",
"is",
"not",
"None",
":",
"services",
"=",
"_extract_services_list_helper",
"(",
"services",
")",
"services_running",
",",
"running",
"=",
"_check_running_services",
"(",
"services",
")",
"if",
"not",
"all",
"(",
"running",
")",
":",
"messages",
".",
"append",
"(",
"\"Services not running that should be: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"_filter_tuples",
"(",
"services_running",
",",
"False",
")",
")",
")",
")",
"state",
"=",
"'blocked'",
"# also verify that the ports that should be open are open",
"# NB, that ServiceManager objects only OPTIONALLY have ports",
"map_not_open",
",",
"ports_open",
"=",
"(",
"_check_listening_on_services_ports",
"(",
"services",
")",
")",
"if",
"not",
"all",
"(",
"ports_open",
")",
":",
"# find which service has missing ports. They are in service",
"# order which makes it a bit easier.",
"message_parts",
"=",
"{",
"service",
":",
"\", \"",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"open_ports",
"]",
")",
"for",
"service",
",",
"open_ports",
"in",
"map_not_open",
".",
"items",
"(",
")",
"}",
"message",
"=",
"\", \"",
".",
"join",
"(",
"[",
"\"{}: [{}]\"",
".",
"format",
"(",
"s",
",",
"sp",
")",
"for",
"s",
",",
"sp",
"in",
"message_parts",
".",
"items",
"(",
")",
"]",
")",
"messages",
".",
"append",
"(",
"\"Services with ports not open that should be: {}\"",
".",
"format",
"(",
"message",
")",
")",
"state",
"=",
"'blocked'",
"if",
"ports",
"is",
"not",
"None",
":",
"# and we can also check ports which we don't know the service for",
"ports_open",
",",
"ports_open_bools",
"=",
"_check_listening_on_ports_list",
"(",
"ports",
")",
"if",
"not",
"all",
"(",
"ports_open_bools",
")",
":",
"messages",
".",
"append",
"(",
"\"Ports which should be open, but are not: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"[",
"str",
"(",
"p",
")",
"for",
"p",
",",
"v",
"in",
"ports_open",
"if",
"not",
"v",
"]",
")",
")",
")",
"state",
"=",
"'blocked'",
"if",
"state",
"is",
"not",
"None",
":",
"message",
"=",
"\"; \"",
".",
"join",
"(",
"messages",
")",
"return",
"state",
",",
"message",
"return",
"None",
",",
"None"
] | Check that the services that should be running are actually running
and that any ports specified are being listened to.
@param services: list of strings OR dictionary specifying services/ports
@param ports: list of ports
@returns state, message: strings or None, None | [
"Check",
"that",
"the",
"services",
"that",
"should",
"be",
"running",
"are",
"actually",
"running",
"and",
"that",
"any",
"ports",
"specified",
"are",
"being",
"listened",
"to",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L998-L1046 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | _check_listening_on_ports_list | def _check_listening_on_ports_list(ports):
"""Check that the ports list given are being listened to
Returns a list of ports being listened to and a list of the
booleans.
@param ports: LIST or port numbers.
@returns [(port_num, boolean), ...], [boolean]
"""
ports_open = [port_has_listener('0.0.0.0', p) for p in ports]
return zip(ports, ports_open), ports_open | python | def _check_listening_on_ports_list(ports):
"""Check that the ports list given are being listened to
Returns a list of ports being listened to and a list of the
booleans.
@param ports: LIST or port numbers.
@returns [(port_num, boolean), ...], [boolean]
"""
ports_open = [port_has_listener('0.0.0.0', p) for p in ports]
return zip(ports, ports_open), ports_open | [
"def",
"_check_listening_on_ports_list",
"(",
"ports",
")",
":",
"ports_open",
"=",
"[",
"port_has_listener",
"(",
"'0.0.0.0'",
",",
"p",
")",
"for",
"p",
"in",
"ports",
"]",
"return",
"zip",
"(",
"ports",
",",
"ports_open",
")",
",",
"ports_open"
] | Check that the ports list given are being listened to
Returns a list of ports being listened to and a list of the
booleans.
@param ports: LIST or port numbers.
@returns [(port_num, boolean), ...], [boolean] | [
"Check",
"that",
"the",
"ports",
"list",
"given",
"are",
"being",
"listened",
"to"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1118-L1128 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | workload_state_compare | def workload_state_compare(current_workload_state, workload_state):
""" Return highest priority of two states"""
hierarchy = {'unknown': -1,
'active': 0,
'maintenance': 1,
'waiting': 2,
'blocked': 3,
}
if hierarchy.get(workload_state) is None:
workload_state = 'unknown'
if hierarchy.get(current_workload_state) is None:
current_workload_state = 'unknown'
# Set workload_state based on hierarchy of statuses
if hierarchy.get(current_workload_state) > hierarchy.get(workload_state):
return current_workload_state
else:
return workload_state | python | def workload_state_compare(current_workload_state, workload_state):
""" Return highest priority of two states"""
hierarchy = {'unknown': -1,
'active': 0,
'maintenance': 1,
'waiting': 2,
'blocked': 3,
}
if hierarchy.get(workload_state) is None:
workload_state = 'unknown'
if hierarchy.get(current_workload_state) is None:
current_workload_state = 'unknown'
# Set workload_state based on hierarchy of statuses
if hierarchy.get(current_workload_state) > hierarchy.get(workload_state):
return current_workload_state
else:
return workload_state | [
"def",
"workload_state_compare",
"(",
"current_workload_state",
",",
"workload_state",
")",
":",
"hierarchy",
"=",
"{",
"'unknown'",
":",
"-",
"1",
",",
"'active'",
":",
"0",
",",
"'maintenance'",
":",
"1",
",",
"'waiting'",
":",
"2",
",",
"'blocked'",
":",
"3",
",",
"}",
"if",
"hierarchy",
".",
"get",
"(",
"workload_state",
")",
"is",
"None",
":",
"workload_state",
"=",
"'unknown'",
"if",
"hierarchy",
".",
"get",
"(",
"current_workload_state",
")",
"is",
"None",
":",
"current_workload_state",
"=",
"'unknown'",
"# Set workload_state based on hierarchy of statuses",
"if",
"hierarchy",
".",
"get",
"(",
"current_workload_state",
")",
">",
"hierarchy",
".",
"get",
"(",
"workload_state",
")",
":",
"return",
"current_workload_state",
"else",
":",
"return",
"workload_state"
] | Return highest priority of two states | [
"Return",
"highest",
"priority",
"of",
"two",
"states"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1142-L1160 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | incomplete_relation_data | def incomplete_relation_data(configs, required_interfaces):
"""Check complete contexts against required_interfaces
Return dictionary of incomplete relation data.
configs is an OSConfigRenderer object with configs registered
required_interfaces is a dictionary of required general interfaces
with dictionary values of possible specific interfaces.
Example:
required_interfaces = {'database': ['shared-db', 'pgsql-db']}
The interface is said to be satisfied if anyone of the interfaces in the
list has a complete context.
Return dictionary of incomplete or missing required contexts with relation
status of interfaces and any missing data points. Example:
{'message':
{'amqp': {'missing_data': ['rabbitmq_password'], 'related': True},
'zeromq-configuration': {'related': False}},
'identity':
{'identity-service': {'related': False}},
'database':
{'pgsql-db': {'related': False},
'shared-db': {'related': True}}}
"""
complete_ctxts = configs.complete_contexts()
incomplete_relations = [
svc_type
for svc_type, interfaces in required_interfaces.items()
if not set(interfaces).intersection(complete_ctxts)]
return {
i: configs.get_incomplete_context_data(required_interfaces[i])
for i in incomplete_relations} | python | def incomplete_relation_data(configs, required_interfaces):
"""Check complete contexts against required_interfaces
Return dictionary of incomplete relation data.
configs is an OSConfigRenderer object with configs registered
required_interfaces is a dictionary of required general interfaces
with dictionary values of possible specific interfaces.
Example:
required_interfaces = {'database': ['shared-db', 'pgsql-db']}
The interface is said to be satisfied if anyone of the interfaces in the
list has a complete context.
Return dictionary of incomplete or missing required contexts with relation
status of interfaces and any missing data points. Example:
{'message':
{'amqp': {'missing_data': ['rabbitmq_password'], 'related': True},
'zeromq-configuration': {'related': False}},
'identity':
{'identity-service': {'related': False}},
'database':
{'pgsql-db': {'related': False},
'shared-db': {'related': True}}}
"""
complete_ctxts = configs.complete_contexts()
incomplete_relations = [
svc_type
for svc_type, interfaces in required_interfaces.items()
if not set(interfaces).intersection(complete_ctxts)]
return {
i: configs.get_incomplete_context_data(required_interfaces[i])
for i in incomplete_relations} | [
"def",
"incomplete_relation_data",
"(",
"configs",
",",
"required_interfaces",
")",
":",
"complete_ctxts",
"=",
"configs",
".",
"complete_contexts",
"(",
")",
"incomplete_relations",
"=",
"[",
"svc_type",
"for",
"svc_type",
",",
"interfaces",
"in",
"required_interfaces",
".",
"items",
"(",
")",
"if",
"not",
"set",
"(",
"interfaces",
")",
".",
"intersection",
"(",
"complete_ctxts",
")",
"]",
"return",
"{",
"i",
":",
"configs",
".",
"get_incomplete_context_data",
"(",
"required_interfaces",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"incomplete_relations",
"}"
] | Check complete contexts against required_interfaces
Return dictionary of incomplete relation data.
configs is an OSConfigRenderer object with configs registered
required_interfaces is a dictionary of required general interfaces
with dictionary values of possible specific interfaces.
Example:
required_interfaces = {'database': ['shared-db', 'pgsql-db']}
The interface is said to be satisfied if anyone of the interfaces in the
list has a complete context.
Return dictionary of incomplete or missing required contexts with relation
status of interfaces and any missing data points. Example:
{'message':
{'amqp': {'missing_data': ['rabbitmq_password'], 'related': True},
'zeromq-configuration': {'related': False}},
'identity':
{'identity-service': {'related': False}},
'database':
{'pgsql-db': {'related': False},
'shared-db': {'related': True}}} | [
"Check",
"complete",
"contexts",
"against",
"required_interfaces",
"Return",
"dictionary",
"of",
"incomplete",
"relation",
"data",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1163-L1195 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | do_action_openstack_upgrade | def do_action_openstack_upgrade(package, upgrade_callback, configs):
"""Perform action-managed OpenStack upgrade.
Upgrades packages to the configured openstack-origin version and sets
the corresponding action status as a result.
If the charm was installed from source we cannot upgrade it.
For backwards compatibility a config flag (action-managed-upgrade) must
be set for this code to run, otherwise a full service level upgrade will
fire on config-changed.
@param package: package name for determining if upgrade available
@param upgrade_callback: function callback to charm's upgrade function
@param configs: templating object derived from OSConfigRenderer class
@return: True if upgrade successful; False if upgrade failed or skipped
"""
ret = False
if openstack_upgrade_available(package):
if config('action-managed-upgrade'):
juju_log('Upgrading OpenStack release')
try:
upgrade_callback(configs=configs)
action_set({'outcome': 'success, upgrade completed.'})
ret = True
except Exception:
action_set({'outcome': 'upgrade failed, see traceback.'})
action_set({'traceback': traceback.format_exc()})
action_fail('do_openstack_upgrade resulted in an '
'unexpected error')
else:
action_set({'outcome': 'action-managed-upgrade config is '
'False, skipped upgrade.'})
else:
action_set({'outcome': 'no upgrade available.'})
return ret | python | def do_action_openstack_upgrade(package, upgrade_callback, configs):
"""Perform action-managed OpenStack upgrade.
Upgrades packages to the configured openstack-origin version and sets
the corresponding action status as a result.
If the charm was installed from source we cannot upgrade it.
For backwards compatibility a config flag (action-managed-upgrade) must
be set for this code to run, otherwise a full service level upgrade will
fire on config-changed.
@param package: package name for determining if upgrade available
@param upgrade_callback: function callback to charm's upgrade function
@param configs: templating object derived from OSConfigRenderer class
@return: True if upgrade successful; False if upgrade failed or skipped
"""
ret = False
if openstack_upgrade_available(package):
if config('action-managed-upgrade'):
juju_log('Upgrading OpenStack release')
try:
upgrade_callback(configs=configs)
action_set({'outcome': 'success, upgrade completed.'})
ret = True
except Exception:
action_set({'outcome': 'upgrade failed, see traceback.'})
action_set({'traceback': traceback.format_exc()})
action_fail('do_openstack_upgrade resulted in an '
'unexpected error')
else:
action_set({'outcome': 'action-managed-upgrade config is '
'False, skipped upgrade.'})
else:
action_set({'outcome': 'no upgrade available.'})
return ret | [
"def",
"do_action_openstack_upgrade",
"(",
"package",
",",
"upgrade_callback",
",",
"configs",
")",
":",
"ret",
"=",
"False",
"if",
"openstack_upgrade_available",
"(",
"package",
")",
":",
"if",
"config",
"(",
"'action-managed-upgrade'",
")",
":",
"juju_log",
"(",
"'Upgrading OpenStack release'",
")",
"try",
":",
"upgrade_callback",
"(",
"configs",
"=",
"configs",
")",
"action_set",
"(",
"{",
"'outcome'",
":",
"'success, upgrade completed.'",
"}",
")",
"ret",
"=",
"True",
"except",
"Exception",
":",
"action_set",
"(",
"{",
"'outcome'",
":",
"'upgrade failed, see traceback.'",
"}",
")",
"action_set",
"(",
"{",
"'traceback'",
":",
"traceback",
".",
"format_exc",
"(",
")",
"}",
")",
"action_fail",
"(",
"'do_openstack_upgrade resulted in an '",
"'unexpected error'",
")",
"else",
":",
"action_set",
"(",
"{",
"'outcome'",
":",
"'action-managed-upgrade config is '",
"'False, skipped upgrade.'",
"}",
")",
"else",
":",
"action_set",
"(",
"{",
"'outcome'",
":",
"'no upgrade available.'",
"}",
")",
"return",
"ret"
] | Perform action-managed OpenStack upgrade.
Upgrades packages to the configured openstack-origin version and sets
the corresponding action status as a result.
If the charm was installed from source we cannot upgrade it.
For backwards compatibility a config flag (action-managed-upgrade) must
be set for this code to run, otherwise a full service level upgrade will
fire on config-changed.
@param package: package name for determining if upgrade available
@param upgrade_callback: function callback to charm's upgrade function
@param configs: templating object derived from OSConfigRenderer class
@return: True if upgrade successful; False if upgrade failed or skipped | [
"Perform",
"action",
"-",
"managed",
"OpenStack",
"upgrade",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1198-L1236 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | manage_payload_services | def manage_payload_services(action, services=None, charm_func=None):
"""Run an action against all services.
An optional charm_func() can be called. It should raise an Exception to
indicate that the function failed. If it was succesfull it should return
None or an optional message.
The signature for charm_func is:
charm_func() -> message: str
charm_func() is executed after any services are stopped, if supplied.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optionally OrderedDict) {service_name: {'service': ..}}
- An array of [{'service': service_name, ...}, ...]
:param action: Action to run: pause, resume, start or stop.
:type action: str
:param services: See above
:type services: See above
:param charm_func: function to run for custom charm pausing.
:type charm_func: f()
:returns: Status boolean and list of messages
:rtype: (bool, [])
:raises: RuntimeError
"""
actions = {
'pause': service_pause,
'resume': service_resume,
'start': service_start,
'stop': service_stop}
action = action.lower()
if action not in actions.keys():
raise RuntimeError(
"action: {} must be one of: {}".format(action,
', '.join(actions.keys())))
services = _extract_services_list_helper(services)
messages = []
success = True
if services:
for service in services.keys():
rc = actions[action](service)
if not rc:
success = False
messages.append("{} didn't {} cleanly.".format(service,
action))
if charm_func:
try:
message = charm_func()
if message:
messages.append(message)
except Exception as e:
success = False
messages.append(str(e))
return success, messages | python | def manage_payload_services(action, services=None, charm_func=None):
"""Run an action against all services.
An optional charm_func() can be called. It should raise an Exception to
indicate that the function failed. If it was succesfull it should return
None or an optional message.
The signature for charm_func is:
charm_func() -> message: str
charm_func() is executed after any services are stopped, if supplied.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optionally OrderedDict) {service_name: {'service': ..}}
- An array of [{'service': service_name, ...}, ...]
:param action: Action to run: pause, resume, start or stop.
:type action: str
:param services: See above
:type services: See above
:param charm_func: function to run for custom charm pausing.
:type charm_func: f()
:returns: Status boolean and list of messages
:rtype: (bool, [])
:raises: RuntimeError
"""
actions = {
'pause': service_pause,
'resume': service_resume,
'start': service_start,
'stop': service_stop}
action = action.lower()
if action not in actions.keys():
raise RuntimeError(
"action: {} must be one of: {}".format(action,
', '.join(actions.keys())))
services = _extract_services_list_helper(services)
messages = []
success = True
if services:
for service in services.keys():
rc = actions[action](service)
if not rc:
success = False
messages.append("{} didn't {} cleanly.".format(service,
action))
if charm_func:
try:
message = charm_func()
if message:
messages.append(message)
except Exception as e:
success = False
messages.append(str(e))
return success, messages | [
"def",
"manage_payload_services",
"(",
"action",
",",
"services",
"=",
"None",
",",
"charm_func",
"=",
"None",
")",
":",
"actions",
"=",
"{",
"'pause'",
":",
"service_pause",
",",
"'resume'",
":",
"service_resume",
",",
"'start'",
":",
"service_start",
",",
"'stop'",
":",
"service_stop",
"}",
"action",
"=",
"action",
".",
"lower",
"(",
")",
"if",
"action",
"not",
"in",
"actions",
".",
"keys",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"action: {} must be one of: {}\"",
".",
"format",
"(",
"action",
",",
"', '",
".",
"join",
"(",
"actions",
".",
"keys",
"(",
")",
")",
")",
")",
"services",
"=",
"_extract_services_list_helper",
"(",
"services",
")",
"messages",
"=",
"[",
"]",
"success",
"=",
"True",
"if",
"services",
":",
"for",
"service",
"in",
"services",
".",
"keys",
"(",
")",
":",
"rc",
"=",
"actions",
"[",
"action",
"]",
"(",
"service",
")",
"if",
"not",
"rc",
":",
"success",
"=",
"False",
"messages",
".",
"append",
"(",
"\"{} didn't {} cleanly.\"",
".",
"format",
"(",
"service",
",",
"action",
")",
")",
"if",
"charm_func",
":",
"try",
":",
"message",
"=",
"charm_func",
"(",
")",
"if",
"message",
":",
"messages",
".",
"append",
"(",
"message",
")",
"except",
"Exception",
"as",
"e",
":",
"success",
"=",
"False",
"messages",
".",
"append",
"(",
"str",
"(",
"e",
")",
")",
"return",
"success",
",",
"messages"
] | Run an action against all services.
An optional charm_func() can be called. It should raise an Exception to
indicate that the function failed. If it was succesfull it should return
None or an optional message.
The signature for charm_func is:
charm_func() -> message: str
charm_func() is executed after any services are stopped, if supplied.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optionally OrderedDict) {service_name: {'service': ..}}
- An array of [{'service': service_name, ...}, ...]
:param action: Action to run: pause, resume, start or stop.
:type action: str
:param services: See above
:type services: See above
:param charm_func: function to run for custom charm pausing.
:type charm_func: f()
:returns: Status boolean and list of messages
:rtype: (bool, [])
:raises: RuntimeError | [
"Run",
"an",
"action",
"against",
"all",
"services",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1334-L1390 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | pausable_restart_on_change | def pausable_restart_on_change(restart_map, stopstart=False,
restart_functions=None):
"""A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorator
is in core.host, yet the openstack specific helpers are in this file
(contrib.openstack.utils). Thus, this needs to be an optional feature
for openstack charms (or charms that wish to use the openstack
pause/resume type features).
It is used as follows:
from contrib.openstack.utils import (
pausable_restart_on_change as restart_on_change)
@restart_on_change(restart_map, stopstart=<boolean>)
def some_hook(...):
pass
see core.utils.restart_on_change() for more details.
Note restart_map can be a callable, in which case, restart_map is only
evaluated at runtime. This means that it is lazy and the underlying
function won't be called if the decorated function is never called. Note,
retains backwards compatibility for passing a non-callable dictionary.
@param f: the function to decorate
@param restart_map: (optionally callable, which then returns the
restart_map) the restart map {conf_file: [services]}
@param stopstart: DEFAULT false; whether to stop, start or just restart
@returns decorator to use a restart_on_change with pausability
"""
def wrap(f):
# py27 compatible nonlocal variable. When py3 only, replace with
# nonlocal keyword
__restart_map_cache = {'cache': None}
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
if is_unit_paused_set():
return f(*args, **kwargs)
if __restart_map_cache['cache'] is None:
__restart_map_cache['cache'] = restart_map() \
if callable(restart_map) else restart_map
# otherwise, normal restart_on_change functionality
return restart_on_change_helper(
(lambda: f(*args, **kwargs)), __restart_map_cache['cache'],
stopstart, restart_functions)
return wrapped_f
return wrap | python | def pausable_restart_on_change(restart_map, stopstart=False,
restart_functions=None):
"""A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorator
is in core.host, yet the openstack specific helpers are in this file
(contrib.openstack.utils). Thus, this needs to be an optional feature
for openstack charms (or charms that wish to use the openstack
pause/resume type features).
It is used as follows:
from contrib.openstack.utils import (
pausable_restart_on_change as restart_on_change)
@restart_on_change(restart_map, stopstart=<boolean>)
def some_hook(...):
pass
see core.utils.restart_on_change() for more details.
Note restart_map can be a callable, in which case, restart_map is only
evaluated at runtime. This means that it is lazy and the underlying
function won't be called if the decorated function is never called. Note,
retains backwards compatibility for passing a non-callable dictionary.
@param f: the function to decorate
@param restart_map: (optionally callable, which then returns the
restart_map) the restart map {conf_file: [services]}
@param stopstart: DEFAULT false; whether to stop, start or just restart
@returns decorator to use a restart_on_change with pausability
"""
def wrap(f):
# py27 compatible nonlocal variable. When py3 only, replace with
# nonlocal keyword
__restart_map_cache = {'cache': None}
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
if is_unit_paused_set():
return f(*args, **kwargs)
if __restart_map_cache['cache'] is None:
__restart_map_cache['cache'] = restart_map() \
if callable(restart_map) else restart_map
# otherwise, normal restart_on_change functionality
return restart_on_change_helper(
(lambda: f(*args, **kwargs)), __restart_map_cache['cache'],
stopstart, restart_functions)
return wrapped_f
return wrap | [
"def",
"pausable_restart_on_change",
"(",
"restart_map",
",",
"stopstart",
"=",
"False",
",",
"restart_functions",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"# py27 compatible nonlocal variable. When py3 only, replace with",
"# nonlocal keyword",
"__restart_map_cache",
"=",
"{",
"'cache'",
":",
"None",
"}",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"is_unit_paused_set",
"(",
")",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"__restart_map_cache",
"[",
"'cache'",
"]",
"is",
"None",
":",
"__restart_map_cache",
"[",
"'cache'",
"]",
"=",
"restart_map",
"(",
")",
"if",
"callable",
"(",
"restart_map",
")",
"else",
"restart_map",
"# otherwise, normal restart_on_change functionality",
"return",
"restart_on_change_helper",
"(",
"(",
"lambda",
":",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
",",
"__restart_map_cache",
"[",
"'cache'",
"]",
",",
"stopstart",
",",
"restart_functions",
")",
"return",
"wrapped_f",
"return",
"wrap"
] | A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorator
is in core.host, yet the openstack specific helpers are in this file
(contrib.openstack.utils). Thus, this needs to be an optional feature
for openstack charms (or charms that wish to use the openstack
pause/resume type features).
It is used as follows:
from contrib.openstack.utils import (
pausable_restart_on_change as restart_on_change)
@restart_on_change(restart_map, stopstart=<boolean>)
def some_hook(...):
pass
see core.utils.restart_on_change() for more details.
Note restart_map can be a callable, in which case, restart_map is only
evaluated at runtime. This means that it is lazy and the underlying
function won't be called if the decorated function is never called. Note,
retains backwards compatibility for passing a non-callable dictionary.
@param f: the function to decorate
@param restart_map: (optionally callable, which then returns the
restart_map) the restart map {conf_file: [services]}
@param stopstart: DEFAULT false; whether to stop, start or just restart
@returns decorator to use a restart_on_change with pausability | [
"A",
"restart_on_change",
"decorator",
"that",
"checks",
"to",
"see",
"if",
"the",
"unit",
"is",
"paused",
".",
"If",
"it",
"is",
"paused",
"then",
"the",
"decorated",
"function",
"doesn",
"t",
"fire",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1498-L1548 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | ordered | def ordered(orderme):
"""Converts the provided dictionary into a collections.OrderedDict.
The items in the returned OrderedDict will be inserted based on the
natural sort order of the keys. Nested dictionaries will also be sorted
in order to ensure fully predictable ordering.
:param orderme: the dict to order
:return: collections.OrderedDict
:raises: ValueError: if `orderme` isn't a dict instance.
"""
if not isinstance(orderme, dict):
raise ValueError('argument must be a dict type')
result = OrderedDict()
for k, v in sorted(six.iteritems(orderme), key=lambda x: x[0]):
if isinstance(v, dict):
result[k] = ordered(v)
else:
result[k] = v
return result | python | def ordered(orderme):
"""Converts the provided dictionary into a collections.OrderedDict.
The items in the returned OrderedDict will be inserted based on the
natural sort order of the keys. Nested dictionaries will also be sorted
in order to ensure fully predictable ordering.
:param orderme: the dict to order
:return: collections.OrderedDict
:raises: ValueError: if `orderme` isn't a dict instance.
"""
if not isinstance(orderme, dict):
raise ValueError('argument must be a dict type')
result = OrderedDict()
for k, v in sorted(six.iteritems(orderme), key=lambda x: x[0]):
if isinstance(v, dict):
result[k] = ordered(v)
else:
result[k] = v
return result | [
"def",
"ordered",
"(",
"orderme",
")",
":",
"if",
"not",
"isinstance",
"(",
"orderme",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'argument must be a dict type'",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"six",
".",
"iteritems",
"(",
"orderme",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"result",
"[",
"k",
"]",
"=",
"ordered",
"(",
"v",
")",
"else",
":",
"result",
"[",
"k",
"]",
"=",
"v",
"return",
"result"
] | Converts the provided dictionary into a collections.OrderedDict.
The items in the returned OrderedDict will be inserted based on the
natural sort order of the keys. Nested dictionaries will also be sorted
in order to ensure fully predictable ordering.
:param orderme: the dict to order
:return: collections.OrderedDict
:raises: ValueError: if `orderme` isn't a dict instance. | [
"Converts",
"the",
"provided",
"dictionary",
"into",
"a",
"collections",
".",
"OrderedDict",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1551-L1572 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | config_flags_parser | def config_flags_parser(config_flags):
"""Parses config flags string into dict.
This parsing method supports a few different formats for the config
flag values to be parsed:
1. A string in the simple format of key=value pairs, with the possibility
of specifying multiple key value pairs within the same string. For
example, a string in the format of 'key1=value1, key2=value2' will
return a dict of:
{'key1': 'value1', 'key2': 'value2'}.
2. A string in the above format, but supporting a comma-delimited list
of values for the same key. For example, a string in the format of
'key1=value1, key2=value3,value4,value5' will return a dict of:
{'key1': 'value1', 'key2': 'value2,value3,value4'}
3. A string containing a colon character (:) prior to an equal
character (=) will be treated as yaml and parsed as such. This can be
used to specify more complex key value pairs. For example,
a string in the format of 'key1: subkey1=value1, subkey2=value2' will
return a dict of:
{'key1', 'subkey1=value1, subkey2=value2'}
The provided config_flags string may be a list of comma-separated values
which themselves may be comma-separated list of values.
"""
# If we find a colon before an equals sign then treat it as yaml.
# Note: limit it to finding the colon first since this indicates assignment
# for inline yaml.
colon = config_flags.find(':')
equals = config_flags.find('=')
if colon > 0:
if colon < equals or equals < 0:
return ordered(yaml.safe_load(config_flags))
if config_flags.find('==') >= 0:
juju_log("config_flags is not in expected format (key=value)",
level=ERROR)
raise OSContextError
# strip the following from each value.
post_strippers = ' ,'
# we strip any leading/trailing '=' or ' ' from the string then
# split on '='.
split = config_flags.strip(' =').split('=')
limit = len(split)
flags = OrderedDict()
for i in range(0, limit - 1):
current = split[i]
next = split[i + 1]
vindex = next.rfind(',')
if (i == limit - 2) or (vindex < 0):
value = next
else:
value = next[:vindex]
if i == 0:
key = current
else:
# if this not the first entry, expect an embedded key.
index = current.rfind(',')
if index < 0:
juju_log("Invalid config value(s) at index %s" % (i),
level=ERROR)
raise OSContextError
key = current[index + 1:]
# Add to collection.
flags[key.strip(post_strippers)] = value.rstrip(post_strippers)
return flags | python | def config_flags_parser(config_flags):
"""Parses config flags string into dict.
This parsing method supports a few different formats for the config
flag values to be parsed:
1. A string in the simple format of key=value pairs, with the possibility
of specifying multiple key value pairs within the same string. For
example, a string in the format of 'key1=value1, key2=value2' will
return a dict of:
{'key1': 'value1', 'key2': 'value2'}.
2. A string in the above format, but supporting a comma-delimited list
of values for the same key. For example, a string in the format of
'key1=value1, key2=value3,value4,value5' will return a dict of:
{'key1': 'value1', 'key2': 'value2,value3,value4'}
3. A string containing a colon character (:) prior to an equal
character (=) will be treated as yaml and parsed as such. This can be
used to specify more complex key value pairs. For example,
a string in the format of 'key1: subkey1=value1, subkey2=value2' will
return a dict of:
{'key1', 'subkey1=value1, subkey2=value2'}
The provided config_flags string may be a list of comma-separated values
which themselves may be comma-separated list of values.
"""
# If we find a colon before an equals sign then treat it as yaml.
# Note: limit it to finding the colon first since this indicates assignment
# for inline yaml.
colon = config_flags.find(':')
equals = config_flags.find('=')
if colon > 0:
if colon < equals or equals < 0:
return ordered(yaml.safe_load(config_flags))
if config_flags.find('==') >= 0:
juju_log("config_flags is not in expected format (key=value)",
level=ERROR)
raise OSContextError
# strip the following from each value.
post_strippers = ' ,'
# we strip any leading/trailing '=' or ' ' from the string then
# split on '='.
split = config_flags.strip(' =').split('=')
limit = len(split)
flags = OrderedDict()
for i in range(0, limit - 1):
current = split[i]
next = split[i + 1]
vindex = next.rfind(',')
if (i == limit - 2) or (vindex < 0):
value = next
else:
value = next[:vindex]
if i == 0:
key = current
else:
# if this not the first entry, expect an embedded key.
index = current.rfind(',')
if index < 0:
juju_log("Invalid config value(s) at index %s" % (i),
level=ERROR)
raise OSContextError
key = current[index + 1:]
# Add to collection.
flags[key.strip(post_strippers)] = value.rstrip(post_strippers)
return flags | [
"def",
"config_flags_parser",
"(",
"config_flags",
")",
":",
"# If we find a colon before an equals sign then treat it as yaml.",
"# Note: limit it to finding the colon first since this indicates assignment",
"# for inline yaml.",
"colon",
"=",
"config_flags",
".",
"find",
"(",
"':'",
")",
"equals",
"=",
"config_flags",
".",
"find",
"(",
"'='",
")",
"if",
"colon",
">",
"0",
":",
"if",
"colon",
"<",
"equals",
"or",
"equals",
"<",
"0",
":",
"return",
"ordered",
"(",
"yaml",
".",
"safe_load",
"(",
"config_flags",
")",
")",
"if",
"config_flags",
".",
"find",
"(",
"'=='",
")",
">=",
"0",
":",
"juju_log",
"(",
"\"config_flags is not in expected format (key=value)\"",
",",
"level",
"=",
"ERROR",
")",
"raise",
"OSContextError",
"# strip the following from each value.",
"post_strippers",
"=",
"' ,'",
"# we strip any leading/trailing '=' or ' ' from the string then",
"# split on '='.",
"split",
"=",
"config_flags",
".",
"strip",
"(",
"' ='",
")",
".",
"split",
"(",
"'='",
")",
"limit",
"=",
"len",
"(",
"split",
")",
"flags",
"=",
"OrderedDict",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"limit",
"-",
"1",
")",
":",
"current",
"=",
"split",
"[",
"i",
"]",
"next",
"=",
"split",
"[",
"i",
"+",
"1",
"]",
"vindex",
"=",
"next",
".",
"rfind",
"(",
"','",
")",
"if",
"(",
"i",
"==",
"limit",
"-",
"2",
")",
"or",
"(",
"vindex",
"<",
"0",
")",
":",
"value",
"=",
"next",
"else",
":",
"value",
"=",
"next",
"[",
":",
"vindex",
"]",
"if",
"i",
"==",
"0",
":",
"key",
"=",
"current",
"else",
":",
"# if this not the first entry, expect an embedded key.",
"index",
"=",
"current",
".",
"rfind",
"(",
"','",
")",
"if",
"index",
"<",
"0",
":",
"juju_log",
"(",
"\"Invalid config value(s) at index %s\"",
"%",
"(",
"i",
")",
",",
"level",
"=",
"ERROR",
")",
"raise",
"OSContextError",
"key",
"=",
"current",
"[",
"index",
"+",
"1",
":",
"]",
"# Add to collection.",
"flags",
"[",
"key",
".",
"strip",
"(",
"post_strippers",
")",
"]",
"=",
"value",
".",
"rstrip",
"(",
"post_strippers",
")",
"return",
"flags"
] | Parses config flags string into dict.
This parsing method supports a few different formats for the config
flag values to be parsed:
1. A string in the simple format of key=value pairs, with the possibility
of specifying multiple key value pairs within the same string. For
example, a string in the format of 'key1=value1, key2=value2' will
return a dict of:
{'key1': 'value1', 'key2': 'value2'}.
2. A string in the above format, but supporting a comma-delimited list
of values for the same key. For example, a string in the format of
'key1=value1, key2=value3,value4,value5' will return a dict of:
{'key1': 'value1', 'key2': 'value2,value3,value4'}
3. A string containing a colon character (:) prior to an equal
character (=) will be treated as yaml and parsed as such. This can be
used to specify more complex key value pairs. For example,
a string in the format of 'key1: subkey1=value1, subkey2=value2' will
return a dict of:
{'key1', 'subkey1=value1, subkey2=value2'}
The provided config_flags string may be a list of comma-separated values
which themselves may be comma-separated list of values. | [
"Parses",
"config",
"flags",
"string",
"into",
"dict",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1575-L1649 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | os_application_version_set | def os_application_version_set(package):
'''Set version of application for Juju 2.0 and later'''
application_version = get_upstream_version(package)
# NOTE(jamespage) if not able to figure out package version, fallback to
# openstack codename version detection.
if not application_version:
application_version_set(os_release(package))
else:
application_version_set(application_version) | python | def os_application_version_set(package):
'''Set version of application for Juju 2.0 and later'''
application_version = get_upstream_version(package)
# NOTE(jamespage) if not able to figure out package version, fallback to
# openstack codename version detection.
if not application_version:
application_version_set(os_release(package))
else:
application_version_set(application_version) | [
"def",
"os_application_version_set",
"(",
"package",
")",
":",
"application_version",
"=",
"get_upstream_version",
"(",
"package",
")",
"# NOTE(jamespage) if not able to figure out package version, fallback to",
"# openstack codename version detection.",
"if",
"not",
"application_version",
":",
"application_version_set",
"(",
"os_release",
"(",
"package",
")",
")",
"else",
":",
"application_version_set",
"(",
"application_version",
")"
] | Set version of application for Juju 2.0 and later | [
"Set",
"version",
"of",
"application",
"for",
"Juju",
"2",
".",
"0",
"and",
"later"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1652-L1660 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | enable_memcache | def enable_memcache(source=None, release=None, package=None):
"""Determine if memcache should be enabled on the local unit
@param release: release of OpenStack currently deployed
@param package: package to derive OpenStack version deployed
@returns boolean Whether memcache should be enabled
"""
_release = None
if release:
_release = release
else:
_release = os_release(package, base='icehouse')
if not _release:
_release = get_os_codename_install_source(source)
return CompareOpenStackReleases(_release) >= 'mitaka' | python | def enable_memcache(source=None, release=None, package=None):
"""Determine if memcache should be enabled on the local unit
@param release: release of OpenStack currently deployed
@param package: package to derive OpenStack version deployed
@returns boolean Whether memcache should be enabled
"""
_release = None
if release:
_release = release
else:
_release = os_release(package, base='icehouse')
if not _release:
_release = get_os_codename_install_source(source)
return CompareOpenStackReleases(_release) >= 'mitaka' | [
"def",
"enable_memcache",
"(",
"source",
"=",
"None",
",",
"release",
"=",
"None",
",",
"package",
"=",
"None",
")",
":",
"_release",
"=",
"None",
"if",
"release",
":",
"_release",
"=",
"release",
"else",
":",
"_release",
"=",
"os_release",
"(",
"package",
",",
"base",
"=",
"'icehouse'",
")",
"if",
"not",
"_release",
":",
"_release",
"=",
"get_os_codename_install_source",
"(",
"source",
")",
"return",
"CompareOpenStackReleases",
"(",
"_release",
")",
">=",
"'mitaka'"
] | Determine if memcache should be enabled on the local unit
@param release: release of OpenStack currently deployed
@param package: package to derive OpenStack version deployed
@returns boolean Whether memcache should be enabled | [
"Determine",
"if",
"memcache",
"should",
"be",
"enabled",
"on",
"the",
"local",
"unit"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1663-L1678 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | token_cache_pkgs | def token_cache_pkgs(source=None, release=None):
"""Determine additional packages needed for token caching
@param source: source string for charm
@param release: release of OpenStack currently deployed
@returns List of package to enable token caching
"""
packages = []
if enable_memcache(source=source, release=release):
packages.extend(['memcached', 'python-memcache'])
return packages | python | def token_cache_pkgs(source=None, release=None):
"""Determine additional packages needed for token caching
@param source: source string for charm
@param release: release of OpenStack currently deployed
@returns List of package to enable token caching
"""
packages = []
if enable_memcache(source=source, release=release):
packages.extend(['memcached', 'python-memcache'])
return packages | [
"def",
"token_cache_pkgs",
"(",
"source",
"=",
"None",
",",
"release",
"=",
"None",
")",
":",
"packages",
"=",
"[",
"]",
"if",
"enable_memcache",
"(",
"source",
"=",
"source",
",",
"release",
"=",
"release",
")",
":",
"packages",
".",
"extend",
"(",
"[",
"'memcached'",
",",
"'python-memcache'",
"]",
")",
"return",
"packages"
] | Determine additional packages needed for token caching
@param source: source string for charm
@param release: release of OpenStack currently deployed
@returns List of package to enable token caching | [
"Determine",
"additional",
"packages",
"needed",
"for",
"token",
"caching"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1681-L1691 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | snap_install_requested | def snap_install_requested():
""" Determine if installing from snaps
If openstack-origin is of the form snap:track/channel[/branch]
and channel is in SNAPS_CHANNELS return True.
"""
origin = config('openstack-origin') or ""
if not origin.startswith('snap:'):
return False
_src = origin[5:]
if '/' in _src:
channel = _src.split('/')[1]
else:
# Handle snap:track with no channel
channel = 'stable'
return valid_snap_channel(channel) | python | def snap_install_requested():
""" Determine if installing from snaps
If openstack-origin is of the form snap:track/channel[/branch]
and channel is in SNAPS_CHANNELS return True.
"""
origin = config('openstack-origin') or ""
if not origin.startswith('snap:'):
return False
_src = origin[5:]
if '/' in _src:
channel = _src.split('/')[1]
else:
# Handle snap:track with no channel
channel = 'stable'
return valid_snap_channel(channel) | [
"def",
"snap_install_requested",
"(",
")",
":",
"origin",
"=",
"config",
"(",
"'openstack-origin'",
")",
"or",
"\"\"",
"if",
"not",
"origin",
".",
"startswith",
"(",
"'snap:'",
")",
":",
"return",
"False",
"_src",
"=",
"origin",
"[",
"5",
":",
"]",
"if",
"'/'",
"in",
"_src",
":",
"channel",
"=",
"_src",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"else",
":",
"# Handle snap:track with no channel",
"channel",
"=",
"'stable'",
"return",
"valid_snap_channel",
"(",
"channel",
")"
] | Determine if installing from snaps
If openstack-origin is of the form snap:track/channel[/branch]
and channel is in SNAPS_CHANNELS return True. | [
"Determine",
"if",
"installing",
"from",
"snaps"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1718-L1734 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | get_snaps_install_info_from_origin | def get_snaps_install_info_from_origin(snaps, src, mode='classic'):
"""Generate a dictionary of snap install information from origin
@param snaps: List of snaps
@param src: String of openstack-origin or source of the form
snap:track/channel
@param mode: String classic, devmode or jailmode
@returns: Dictionary of snaps with channels and modes
"""
if not src.startswith('snap:'):
juju_log("Snap source is not a snap origin", 'WARN')
return {}
_src = src[5:]
channel = '--channel={}'.format(_src)
return {snap: {'channel': channel, 'mode': mode}
for snap in snaps} | python | def get_snaps_install_info_from_origin(snaps, src, mode='classic'):
"""Generate a dictionary of snap install information from origin
@param snaps: List of snaps
@param src: String of openstack-origin or source of the form
snap:track/channel
@param mode: String classic, devmode or jailmode
@returns: Dictionary of snaps with channels and modes
"""
if not src.startswith('snap:'):
juju_log("Snap source is not a snap origin", 'WARN')
return {}
_src = src[5:]
channel = '--channel={}'.format(_src)
return {snap: {'channel': channel, 'mode': mode}
for snap in snaps} | [
"def",
"get_snaps_install_info_from_origin",
"(",
"snaps",
",",
"src",
",",
"mode",
"=",
"'classic'",
")",
":",
"if",
"not",
"src",
".",
"startswith",
"(",
"'snap:'",
")",
":",
"juju_log",
"(",
"\"Snap source is not a snap origin\"",
",",
"'WARN'",
")",
"return",
"{",
"}",
"_src",
"=",
"src",
"[",
"5",
":",
"]",
"channel",
"=",
"'--channel={}'",
".",
"format",
"(",
"_src",
")",
"return",
"{",
"snap",
":",
"{",
"'channel'",
":",
"channel",
",",
"'mode'",
":",
"mode",
"}",
"for",
"snap",
"in",
"snaps",
"}"
] | Generate a dictionary of snap install information from origin
@param snaps: List of snaps
@param src: String of openstack-origin or source of the form
snap:track/channel
@param mode: String classic, devmode or jailmode
@returns: Dictionary of snaps with channels and modes | [
"Generate",
"a",
"dictionary",
"of",
"snap",
"install",
"information",
"from",
"origin"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1737-L1755 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | install_os_snaps | def install_os_snaps(snaps, refresh=False):
"""Install OpenStack snaps from channel and with mode
@param snaps: Dictionary of snaps with channels and modes of the form:
{'snap_name': {'channel': 'snap_channel',
'mode': 'snap_mode'}}
Where channel is a snapstore channel and mode is --classic, --devmode
or --jailmode.
@param post_snap_install: Callback function to run after snaps have been
installed
"""
def _ensure_flag(flag):
if flag.startswith('--'):
return flag
return '--{}'.format(flag)
if refresh:
for snap in snaps.keys():
snap_refresh(snap,
_ensure_flag(snaps[snap]['channel']),
_ensure_flag(snaps[snap]['mode']))
else:
for snap in snaps.keys():
snap_install(snap,
_ensure_flag(snaps[snap]['channel']),
_ensure_flag(snaps[snap]['mode'])) | python | def install_os_snaps(snaps, refresh=False):
"""Install OpenStack snaps from channel and with mode
@param snaps: Dictionary of snaps with channels and modes of the form:
{'snap_name': {'channel': 'snap_channel',
'mode': 'snap_mode'}}
Where channel is a snapstore channel and mode is --classic, --devmode
or --jailmode.
@param post_snap_install: Callback function to run after snaps have been
installed
"""
def _ensure_flag(flag):
if flag.startswith('--'):
return flag
return '--{}'.format(flag)
if refresh:
for snap in snaps.keys():
snap_refresh(snap,
_ensure_flag(snaps[snap]['channel']),
_ensure_flag(snaps[snap]['mode']))
else:
for snap in snaps.keys():
snap_install(snap,
_ensure_flag(snaps[snap]['channel']),
_ensure_flag(snaps[snap]['mode'])) | [
"def",
"install_os_snaps",
"(",
"snaps",
",",
"refresh",
"=",
"False",
")",
":",
"def",
"_ensure_flag",
"(",
"flag",
")",
":",
"if",
"flag",
".",
"startswith",
"(",
"'--'",
")",
":",
"return",
"flag",
"return",
"'--{}'",
".",
"format",
"(",
"flag",
")",
"if",
"refresh",
":",
"for",
"snap",
"in",
"snaps",
".",
"keys",
"(",
")",
":",
"snap_refresh",
"(",
"snap",
",",
"_ensure_flag",
"(",
"snaps",
"[",
"snap",
"]",
"[",
"'channel'",
"]",
")",
",",
"_ensure_flag",
"(",
"snaps",
"[",
"snap",
"]",
"[",
"'mode'",
"]",
")",
")",
"else",
":",
"for",
"snap",
"in",
"snaps",
".",
"keys",
"(",
")",
":",
"snap_install",
"(",
"snap",
",",
"_ensure_flag",
"(",
"snaps",
"[",
"snap",
"]",
"[",
"'channel'",
"]",
")",
",",
"_ensure_flag",
"(",
"snaps",
"[",
"snap",
"]",
"[",
"'mode'",
"]",
")",
")"
] | Install OpenStack snaps from channel and with mode
@param snaps: Dictionary of snaps with channels and modes of the form:
{'snap_name': {'channel': 'snap_channel',
'mode': 'snap_mode'}}
Where channel is a snapstore channel and mode is --classic, --devmode
or --jailmode.
@param post_snap_install: Callback function to run after snaps have been
installed | [
"Install",
"OpenStack",
"snaps",
"from",
"channel",
"and",
"with",
"mode"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1758-L1784 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | series_upgrade_complete | def series_upgrade_complete(resume_unit_helper=None, configs=None):
""" Run common series upgrade complete tasks.
:param resume_unit_helper: function: Function to resume unit
:param configs: OSConfigRenderer object: Configurations
:returns None:
"""
clear_unit_paused()
clear_unit_upgrading()
if configs:
configs.write_all()
if resume_unit_helper:
resume_unit_helper(configs) | python | def series_upgrade_complete(resume_unit_helper=None, configs=None):
""" Run common series upgrade complete tasks.
:param resume_unit_helper: function: Function to resume unit
:param configs: OSConfigRenderer object: Configurations
:returns None:
"""
clear_unit_paused()
clear_unit_upgrading()
if configs:
configs.write_all()
if resume_unit_helper:
resume_unit_helper(configs) | [
"def",
"series_upgrade_complete",
"(",
"resume_unit_helper",
"=",
"None",
",",
"configs",
"=",
"None",
")",
":",
"clear_unit_paused",
"(",
")",
"clear_unit_upgrading",
"(",
")",
"if",
"configs",
":",
"configs",
".",
"write_all",
"(",
")",
"if",
"resume_unit_helper",
":",
"resume_unit_helper",
"(",
"configs",
")"
] | Run common series upgrade complete tasks.
:param resume_unit_helper: function: Function to resume unit
:param configs: OSConfigRenderer object: Configurations
:returns None: | [
"Run",
"common",
"series",
"upgrade",
"complete",
"tasks",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1831-L1843 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | get_certificate_request | def get_certificate_request(json_encode=True):
"""Generate a certificatee requests based on the network confioguration
"""
req = CertRequest(json_encode=json_encode)
req.add_hostname_cn()
# Add os-hostname entries
for net_type in [INTERNAL, ADMIN, PUBLIC]:
net_config = config(ADDRESS_MAP[net_type]['override'])
try:
net_addr = resolve_address(endpoint_type=net_type)
ip = network_get_primary_address(
ADDRESS_MAP[net_type]['binding'])
addresses = [net_addr, ip]
vip = get_vip_in_network(resolve_network_cidr(ip))
if vip:
addresses.append(vip)
if net_config:
req.add_entry(
net_type,
net_config,
addresses)
else:
# There is network address with no corresponding hostname.
# Add the ip to the hostname cert to allow for this.
req.add_hostname_cn_ip(addresses)
except NoNetworkBinding:
log("Skipping request for certificate for ip in {} space, no "
"local address found".format(net_type), WARNING)
return req.get_request() | python | def get_certificate_request(json_encode=True):
"""Generate a certificatee requests based on the network confioguration
"""
req = CertRequest(json_encode=json_encode)
req.add_hostname_cn()
# Add os-hostname entries
for net_type in [INTERNAL, ADMIN, PUBLIC]:
net_config = config(ADDRESS_MAP[net_type]['override'])
try:
net_addr = resolve_address(endpoint_type=net_type)
ip = network_get_primary_address(
ADDRESS_MAP[net_type]['binding'])
addresses = [net_addr, ip]
vip = get_vip_in_network(resolve_network_cidr(ip))
if vip:
addresses.append(vip)
if net_config:
req.add_entry(
net_type,
net_config,
addresses)
else:
# There is network address with no corresponding hostname.
# Add the ip to the hostname cert to allow for this.
req.add_hostname_cn_ip(addresses)
except NoNetworkBinding:
log("Skipping request for certificate for ip in {} space, no "
"local address found".format(net_type), WARNING)
return req.get_request() | [
"def",
"get_certificate_request",
"(",
"json_encode",
"=",
"True",
")",
":",
"req",
"=",
"CertRequest",
"(",
"json_encode",
"=",
"json_encode",
")",
"req",
".",
"add_hostname_cn",
"(",
")",
"# Add os-hostname entries",
"for",
"net_type",
"in",
"[",
"INTERNAL",
",",
"ADMIN",
",",
"PUBLIC",
"]",
":",
"net_config",
"=",
"config",
"(",
"ADDRESS_MAP",
"[",
"net_type",
"]",
"[",
"'override'",
"]",
")",
"try",
":",
"net_addr",
"=",
"resolve_address",
"(",
"endpoint_type",
"=",
"net_type",
")",
"ip",
"=",
"network_get_primary_address",
"(",
"ADDRESS_MAP",
"[",
"net_type",
"]",
"[",
"'binding'",
"]",
")",
"addresses",
"=",
"[",
"net_addr",
",",
"ip",
"]",
"vip",
"=",
"get_vip_in_network",
"(",
"resolve_network_cidr",
"(",
"ip",
")",
")",
"if",
"vip",
":",
"addresses",
".",
"append",
"(",
"vip",
")",
"if",
"net_config",
":",
"req",
".",
"add_entry",
"(",
"net_type",
",",
"net_config",
",",
"addresses",
")",
"else",
":",
"# There is network address with no corresponding hostname.",
"# Add the ip to the hostname cert to allow for this.",
"req",
".",
"add_hostname_cn_ip",
"(",
"addresses",
")",
"except",
"NoNetworkBinding",
":",
"log",
"(",
"\"Skipping request for certificate for ip in {} space, no \"",
"\"local address found\"",
".",
"format",
"(",
"net_type",
")",
",",
"WARNING",
")",
"return",
"req",
".",
"get_request",
"(",
")"
] | Generate a certificatee requests based on the network confioguration | [
"Generate",
"a",
"certificatee",
"requests",
"based",
"on",
"the",
"network",
"confioguration"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L114-L143 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | create_ip_cert_links | def create_ip_cert_links(ssl_dir, custom_hostname_link=None):
"""Create symlinks for SAN records
:param ssl_dir: str Directory to create symlinks in
:param custom_hostname_link: str Additional link to be created
"""
hostname = get_hostname(unit_get('private-address'))
hostname_cert = os.path.join(
ssl_dir,
'cert_{}'.format(hostname))
hostname_key = os.path.join(
ssl_dir,
'key_{}'.format(hostname))
# Add links to hostname cert, used if os-hostname vars not set
for net_type in [INTERNAL, ADMIN, PUBLIC]:
try:
addr = resolve_address(endpoint_type=net_type)
cert = os.path.join(ssl_dir, 'cert_{}'.format(addr))
key = os.path.join(ssl_dir, 'key_{}'.format(addr))
if os.path.isfile(hostname_cert) and not os.path.isfile(cert):
os.symlink(hostname_cert, cert)
os.symlink(hostname_key, key)
except NoNetworkBinding:
log("Skipping creating cert symlink for ip in {} space, no "
"local address found".format(net_type), WARNING)
if custom_hostname_link:
custom_cert = os.path.join(
ssl_dir,
'cert_{}'.format(custom_hostname_link))
custom_key = os.path.join(
ssl_dir,
'key_{}'.format(custom_hostname_link))
if os.path.isfile(hostname_cert) and not os.path.isfile(custom_cert):
os.symlink(hostname_cert, custom_cert)
os.symlink(hostname_key, custom_key) | python | def create_ip_cert_links(ssl_dir, custom_hostname_link=None):
"""Create symlinks for SAN records
:param ssl_dir: str Directory to create symlinks in
:param custom_hostname_link: str Additional link to be created
"""
hostname = get_hostname(unit_get('private-address'))
hostname_cert = os.path.join(
ssl_dir,
'cert_{}'.format(hostname))
hostname_key = os.path.join(
ssl_dir,
'key_{}'.format(hostname))
# Add links to hostname cert, used if os-hostname vars not set
for net_type in [INTERNAL, ADMIN, PUBLIC]:
try:
addr = resolve_address(endpoint_type=net_type)
cert = os.path.join(ssl_dir, 'cert_{}'.format(addr))
key = os.path.join(ssl_dir, 'key_{}'.format(addr))
if os.path.isfile(hostname_cert) and not os.path.isfile(cert):
os.symlink(hostname_cert, cert)
os.symlink(hostname_key, key)
except NoNetworkBinding:
log("Skipping creating cert symlink for ip in {} space, no "
"local address found".format(net_type), WARNING)
if custom_hostname_link:
custom_cert = os.path.join(
ssl_dir,
'cert_{}'.format(custom_hostname_link))
custom_key = os.path.join(
ssl_dir,
'key_{}'.format(custom_hostname_link))
if os.path.isfile(hostname_cert) and not os.path.isfile(custom_cert):
os.symlink(hostname_cert, custom_cert)
os.symlink(hostname_key, custom_key) | [
"def",
"create_ip_cert_links",
"(",
"ssl_dir",
",",
"custom_hostname_link",
"=",
"None",
")",
":",
"hostname",
"=",
"get_hostname",
"(",
"unit_get",
"(",
"'private-address'",
")",
")",
"hostname_cert",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"'cert_{}'",
".",
"format",
"(",
"hostname",
")",
")",
"hostname_key",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"'key_{}'",
".",
"format",
"(",
"hostname",
")",
")",
"# Add links to hostname cert, used if os-hostname vars not set",
"for",
"net_type",
"in",
"[",
"INTERNAL",
",",
"ADMIN",
",",
"PUBLIC",
"]",
":",
"try",
":",
"addr",
"=",
"resolve_address",
"(",
"endpoint_type",
"=",
"net_type",
")",
"cert",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"'cert_{}'",
".",
"format",
"(",
"addr",
")",
")",
"key",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"'key_{}'",
".",
"format",
"(",
"addr",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"hostname_cert",
")",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"cert",
")",
":",
"os",
".",
"symlink",
"(",
"hostname_cert",
",",
"cert",
")",
"os",
".",
"symlink",
"(",
"hostname_key",
",",
"key",
")",
"except",
"NoNetworkBinding",
":",
"log",
"(",
"\"Skipping creating cert symlink for ip in {} space, no \"",
"\"local address found\"",
".",
"format",
"(",
"net_type",
")",
",",
"WARNING",
")",
"if",
"custom_hostname_link",
":",
"custom_cert",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"'cert_{}'",
".",
"format",
"(",
"custom_hostname_link",
")",
")",
"custom_key",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"'key_{}'",
".",
"format",
"(",
"custom_hostname_link",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"hostname_cert",
")",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"custom_cert",
")",
":",
"os",
".",
"symlink",
"(",
"hostname_cert",
",",
"custom_cert",
")",
"os",
".",
"symlink",
"(",
"hostname_key",
",",
"custom_key",
")"
] | Create symlinks for SAN records
:param ssl_dir: str Directory to create symlinks in
:param custom_hostname_link: str Additional link to be created | [
"Create",
"symlinks",
"for",
"SAN",
"records"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L146-L180 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | install_certs | def install_certs(ssl_dir, certs, chain=None, user='root', group='root'):
"""Install the certs passed into the ssl dir and append the chain if
provided.
:param ssl_dir: str Directory to create symlinks in
:param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}}
:param chain: str Chain to be appended to certs
:param user: (Optional) Owner of certificate files. Defaults to 'root'
:type user: str
:param group: (Optional) Group of certificate files. Defaults to 'root'
:type group: str
"""
for cn, bundle in certs.items():
cert_filename = 'cert_{}'.format(cn)
key_filename = 'key_{}'.format(cn)
cert_data = bundle['cert']
if chain:
# Append chain file so that clients that trust the root CA will
# trust certs signed by an intermediate in the chain
cert_data = cert_data + os.linesep + chain
write_file(
path=os.path.join(ssl_dir, cert_filename), owner=user, group=group,
content=cert_data, perms=0o640)
write_file(
path=os.path.join(ssl_dir, key_filename), owner=user, group=group,
content=bundle['key'], perms=0o640) | python | def install_certs(ssl_dir, certs, chain=None, user='root', group='root'):
"""Install the certs passed into the ssl dir and append the chain if
provided.
:param ssl_dir: str Directory to create symlinks in
:param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}}
:param chain: str Chain to be appended to certs
:param user: (Optional) Owner of certificate files. Defaults to 'root'
:type user: str
:param group: (Optional) Group of certificate files. Defaults to 'root'
:type group: str
"""
for cn, bundle in certs.items():
cert_filename = 'cert_{}'.format(cn)
key_filename = 'key_{}'.format(cn)
cert_data = bundle['cert']
if chain:
# Append chain file so that clients that trust the root CA will
# trust certs signed by an intermediate in the chain
cert_data = cert_data + os.linesep + chain
write_file(
path=os.path.join(ssl_dir, cert_filename), owner=user, group=group,
content=cert_data, perms=0o640)
write_file(
path=os.path.join(ssl_dir, key_filename), owner=user, group=group,
content=bundle['key'], perms=0o640) | [
"def",
"install_certs",
"(",
"ssl_dir",
",",
"certs",
",",
"chain",
"=",
"None",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
")",
":",
"for",
"cn",
",",
"bundle",
"in",
"certs",
".",
"items",
"(",
")",
":",
"cert_filename",
"=",
"'cert_{}'",
".",
"format",
"(",
"cn",
")",
"key_filename",
"=",
"'key_{}'",
".",
"format",
"(",
"cn",
")",
"cert_data",
"=",
"bundle",
"[",
"'cert'",
"]",
"if",
"chain",
":",
"# Append chain file so that clients that trust the root CA will",
"# trust certs signed by an intermediate in the chain",
"cert_data",
"=",
"cert_data",
"+",
"os",
".",
"linesep",
"+",
"chain",
"write_file",
"(",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"cert_filename",
")",
",",
"owner",
"=",
"user",
",",
"group",
"=",
"group",
",",
"content",
"=",
"cert_data",
",",
"perms",
"=",
"0o640",
")",
"write_file",
"(",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssl_dir",
",",
"key_filename",
")",
",",
"owner",
"=",
"user",
",",
"group",
"=",
"group",
",",
"content",
"=",
"bundle",
"[",
"'key'",
"]",
",",
"perms",
"=",
"0o640",
")"
] | Install the certs passed into the ssl dir and append the chain if
provided.
:param ssl_dir: str Directory to create symlinks in
:param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}}
:param chain: str Chain to be appended to certs
:param user: (Optional) Owner of certificate files. Defaults to 'root'
:type user: str
:param group: (Optional) Group of certificate files. Defaults to 'root'
:type group: str | [
"Install",
"the",
"certs",
"passed",
"into",
"the",
"ssl",
"dir",
"and",
"append",
"the",
"chain",
"if",
"provided",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L183-L208 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | process_certificates | def process_certificates(service_name, relation_id, unit,
custom_hostname_link=None, user='root', group='root'):
"""Process the certificates supplied down the relation
:param service_name: str Name of service the certifcates are for.
:param relation_id: str Relation id providing the certs
:param unit: str Unit providing the certs
:param custom_hostname_link: str Name of custom link to create
:param user: (Optional) Owner of certificate files. Defaults to 'root'
:type user: str
:param group: (Optional) Group of certificate files. Defaults to 'root'
:type group: str
:returns: True if certificates processed for local unit or False
:rtype: bool
"""
data = relation_get(rid=relation_id, unit=unit)
ssl_dir = os.path.join('/etc/apache2/ssl/', service_name)
mkdir(path=ssl_dir)
name = local_unit().replace('/', '_')
certs = data.get('{}.processed_requests'.format(name))
chain = data.get('chain')
ca = data.get('ca')
if certs:
certs = json.loads(certs)
install_ca_cert(ca.encode())
install_certs(ssl_dir, certs, chain, user=user, group=group)
create_ip_cert_links(
ssl_dir,
custom_hostname_link=custom_hostname_link)
return True
return False | python | def process_certificates(service_name, relation_id, unit,
custom_hostname_link=None, user='root', group='root'):
"""Process the certificates supplied down the relation
:param service_name: str Name of service the certifcates are for.
:param relation_id: str Relation id providing the certs
:param unit: str Unit providing the certs
:param custom_hostname_link: str Name of custom link to create
:param user: (Optional) Owner of certificate files. Defaults to 'root'
:type user: str
:param group: (Optional) Group of certificate files. Defaults to 'root'
:type group: str
:returns: True if certificates processed for local unit or False
:rtype: bool
"""
data = relation_get(rid=relation_id, unit=unit)
ssl_dir = os.path.join('/etc/apache2/ssl/', service_name)
mkdir(path=ssl_dir)
name = local_unit().replace('/', '_')
certs = data.get('{}.processed_requests'.format(name))
chain = data.get('chain')
ca = data.get('ca')
if certs:
certs = json.loads(certs)
install_ca_cert(ca.encode())
install_certs(ssl_dir, certs, chain, user=user, group=group)
create_ip_cert_links(
ssl_dir,
custom_hostname_link=custom_hostname_link)
return True
return False | [
"def",
"process_certificates",
"(",
"service_name",
",",
"relation_id",
",",
"unit",
",",
"custom_hostname_link",
"=",
"None",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
")",
":",
"data",
"=",
"relation_get",
"(",
"rid",
"=",
"relation_id",
",",
"unit",
"=",
"unit",
")",
"ssl_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'/etc/apache2/ssl/'",
",",
"service_name",
")",
"mkdir",
"(",
"path",
"=",
"ssl_dir",
")",
"name",
"=",
"local_unit",
"(",
")",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"certs",
"=",
"data",
".",
"get",
"(",
"'{}.processed_requests'",
".",
"format",
"(",
"name",
")",
")",
"chain",
"=",
"data",
".",
"get",
"(",
"'chain'",
")",
"ca",
"=",
"data",
".",
"get",
"(",
"'ca'",
")",
"if",
"certs",
":",
"certs",
"=",
"json",
".",
"loads",
"(",
"certs",
")",
"install_ca_cert",
"(",
"ca",
".",
"encode",
"(",
")",
")",
"install_certs",
"(",
"ssl_dir",
",",
"certs",
",",
"chain",
",",
"user",
"=",
"user",
",",
"group",
"=",
"group",
")",
"create_ip_cert_links",
"(",
"ssl_dir",
",",
"custom_hostname_link",
"=",
"custom_hostname_link",
")",
"return",
"True",
"return",
"False"
] | Process the certificates supplied down the relation
:param service_name: str Name of service the certifcates are for.
:param relation_id: str Relation id providing the certs
:param unit: str Unit providing the certs
:param custom_hostname_link: str Name of custom link to create
:param user: (Optional) Owner of certificate files. Defaults to 'root'
:type user: str
:param group: (Optional) Group of certificate files. Defaults to 'root'
:type group: str
:returns: True if certificates processed for local unit or False
:rtype: bool | [
"Process",
"the",
"certificates",
"supplied",
"down",
"the",
"relation"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L211-L241 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | get_requests_for_local_unit | def get_requests_for_local_unit(relation_name=None):
"""Extract any certificates data targeted at this unit down relation_name.
:param relation_name: str Name of relation to check for data.
:returns: List of bundles of certificates.
:rtype: List of dicts
"""
local_name = local_unit().replace('/', '_')
raw_certs_key = '{}.processed_requests'.format(local_name)
relation_name = relation_name or 'certificates'
bundles = []
for rid in relation_ids(relation_name):
for unit in related_units(rid):
data = relation_get(rid=rid, unit=unit)
if data.get(raw_certs_key):
bundles.append({
'ca': data['ca'],
'chain': data.get('chain'),
'certs': json.loads(data[raw_certs_key])})
return bundles | python | def get_requests_for_local_unit(relation_name=None):
"""Extract any certificates data targeted at this unit down relation_name.
:param relation_name: str Name of relation to check for data.
:returns: List of bundles of certificates.
:rtype: List of dicts
"""
local_name = local_unit().replace('/', '_')
raw_certs_key = '{}.processed_requests'.format(local_name)
relation_name = relation_name or 'certificates'
bundles = []
for rid in relation_ids(relation_name):
for unit in related_units(rid):
data = relation_get(rid=rid, unit=unit)
if data.get(raw_certs_key):
bundles.append({
'ca': data['ca'],
'chain': data.get('chain'),
'certs': json.loads(data[raw_certs_key])})
return bundles | [
"def",
"get_requests_for_local_unit",
"(",
"relation_name",
"=",
"None",
")",
":",
"local_name",
"=",
"local_unit",
"(",
")",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"raw_certs_key",
"=",
"'{}.processed_requests'",
".",
"format",
"(",
"local_name",
")",
"relation_name",
"=",
"relation_name",
"or",
"'certificates'",
"bundles",
"=",
"[",
"]",
"for",
"rid",
"in",
"relation_ids",
"(",
"relation_name",
")",
":",
"for",
"unit",
"in",
"related_units",
"(",
"rid",
")",
":",
"data",
"=",
"relation_get",
"(",
"rid",
"=",
"rid",
",",
"unit",
"=",
"unit",
")",
"if",
"data",
".",
"get",
"(",
"raw_certs_key",
")",
":",
"bundles",
".",
"append",
"(",
"{",
"'ca'",
":",
"data",
"[",
"'ca'",
"]",
",",
"'chain'",
":",
"data",
".",
"get",
"(",
"'chain'",
")",
",",
"'certs'",
":",
"json",
".",
"loads",
"(",
"data",
"[",
"raw_certs_key",
"]",
")",
"}",
")",
"return",
"bundles"
] | Extract any certificates data targeted at this unit down relation_name.
:param relation_name: str Name of relation to check for data.
:returns: List of bundles of certificates.
:rtype: List of dicts | [
"Extract",
"any",
"certificates",
"data",
"targeted",
"at",
"this",
"unit",
"down",
"relation_name",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L244-L263 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | get_bundle_for_cn | def get_bundle_for_cn(cn, relation_name=None):
"""Extract certificates for the given cn.
:param cn: str Canonical Name on certificate.
:param relation_name: str Relation to check for certificates down.
:returns: Dictionary of certificate data,
:rtype: dict.
"""
entries = get_requests_for_local_unit(relation_name)
cert_bundle = {}
for entry in entries:
for _cn, bundle in entry['certs'].items():
if _cn == cn:
cert_bundle = {
'cert': bundle['cert'],
'key': bundle['key'],
'chain': entry['chain'],
'ca': entry['ca']}
break
if cert_bundle:
break
return cert_bundle | python | def get_bundle_for_cn(cn, relation_name=None):
"""Extract certificates for the given cn.
:param cn: str Canonical Name on certificate.
:param relation_name: str Relation to check for certificates down.
:returns: Dictionary of certificate data,
:rtype: dict.
"""
entries = get_requests_for_local_unit(relation_name)
cert_bundle = {}
for entry in entries:
for _cn, bundle in entry['certs'].items():
if _cn == cn:
cert_bundle = {
'cert': bundle['cert'],
'key': bundle['key'],
'chain': entry['chain'],
'ca': entry['ca']}
break
if cert_bundle:
break
return cert_bundle | [
"def",
"get_bundle_for_cn",
"(",
"cn",
",",
"relation_name",
"=",
"None",
")",
":",
"entries",
"=",
"get_requests_for_local_unit",
"(",
"relation_name",
")",
"cert_bundle",
"=",
"{",
"}",
"for",
"entry",
"in",
"entries",
":",
"for",
"_cn",
",",
"bundle",
"in",
"entry",
"[",
"'certs'",
"]",
".",
"items",
"(",
")",
":",
"if",
"_cn",
"==",
"cn",
":",
"cert_bundle",
"=",
"{",
"'cert'",
":",
"bundle",
"[",
"'cert'",
"]",
",",
"'key'",
":",
"bundle",
"[",
"'key'",
"]",
",",
"'chain'",
":",
"entry",
"[",
"'chain'",
"]",
",",
"'ca'",
":",
"entry",
"[",
"'ca'",
"]",
"}",
"break",
"if",
"cert_bundle",
":",
"break",
"return",
"cert_bundle"
] | Extract certificates for the given cn.
:param cn: str Canonical Name on certificate.
:param relation_name: str Relation to check for certificates down.
:returns: Dictionary of certificate data,
:rtype: dict. | [
"Extract",
"certificates",
"for",
"the",
"given",
"cn",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L266-L287 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | CertRequest.add_entry | def add_entry(self, net_type, cn, addresses):
"""Add a request to the batch
:param net_type: str netwrok space name request is for
:param cn: str Canonical Name for certificate
:param addresses: [] List of addresses to be used as SANs
"""
self.entries.append({
'cn': cn,
'addresses': addresses}) | python | def add_entry(self, net_type, cn, addresses):
"""Add a request to the batch
:param net_type: str netwrok space name request is for
:param cn: str Canonical Name for certificate
:param addresses: [] List of addresses to be used as SANs
"""
self.entries.append({
'cn': cn,
'addresses': addresses}) | [
"def",
"add_entry",
"(",
"self",
",",
"net_type",
",",
"cn",
",",
"addresses",
")",
":",
"self",
".",
"entries",
".",
"append",
"(",
"{",
"'cn'",
":",
"cn",
",",
"'addresses'",
":",
"addresses",
"}",
")"
] | Add a request to the batch
:param net_type: str netwrok space name request is for
:param cn: str Canonical Name for certificate
:param addresses: [] List of addresses to be used as SANs | [
"Add",
"a",
"request",
"to",
"the",
"batch"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L64-L73 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | CertRequest.add_hostname_cn | def add_hostname_cn(self):
"""Add a request for the hostname of the machine"""
ip = unit_get('private-address')
addresses = [ip]
# If a vip is being used without os-hostname config or
# network spaces then we need to ensure the local units
# cert has the approriate vip in the SAN list
vip = get_vip_in_network(resolve_network_cidr(ip))
if vip:
addresses.append(vip)
self.hostname_entry = {
'cn': get_hostname(ip),
'addresses': addresses} | python | def add_hostname_cn(self):
"""Add a request for the hostname of the machine"""
ip = unit_get('private-address')
addresses = [ip]
# If a vip is being used without os-hostname config or
# network spaces then we need to ensure the local units
# cert has the approriate vip in the SAN list
vip = get_vip_in_network(resolve_network_cidr(ip))
if vip:
addresses.append(vip)
self.hostname_entry = {
'cn': get_hostname(ip),
'addresses': addresses} | [
"def",
"add_hostname_cn",
"(",
"self",
")",
":",
"ip",
"=",
"unit_get",
"(",
"'private-address'",
")",
"addresses",
"=",
"[",
"ip",
"]",
"# If a vip is being used without os-hostname config or",
"# network spaces then we need to ensure the local units",
"# cert has the approriate vip in the SAN list",
"vip",
"=",
"get_vip_in_network",
"(",
"resolve_network_cidr",
"(",
"ip",
")",
")",
"if",
"vip",
":",
"addresses",
".",
"append",
"(",
"vip",
")",
"self",
".",
"hostname_entry",
"=",
"{",
"'cn'",
":",
"get_hostname",
"(",
"ip",
")",
",",
"'addresses'",
":",
"addresses",
"}"
] | Add a request for the hostname of the machine | [
"Add",
"a",
"request",
"for",
"the",
"hostname",
"of",
"the",
"machine"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L75-L87 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | CertRequest.add_hostname_cn_ip | def add_hostname_cn_ip(self, addresses):
"""Add an address to the SAN list for the hostname request
:param addr: [] List of address to be added
"""
for addr in addresses:
if addr not in self.hostname_entry['addresses']:
self.hostname_entry['addresses'].append(addr) | python | def add_hostname_cn_ip(self, addresses):
"""Add an address to the SAN list for the hostname request
:param addr: [] List of address to be added
"""
for addr in addresses:
if addr not in self.hostname_entry['addresses']:
self.hostname_entry['addresses'].append(addr) | [
"def",
"add_hostname_cn_ip",
"(",
"self",
",",
"addresses",
")",
":",
"for",
"addr",
"in",
"addresses",
":",
"if",
"addr",
"not",
"in",
"self",
".",
"hostname_entry",
"[",
"'addresses'",
"]",
":",
"self",
".",
"hostname_entry",
"[",
"'addresses'",
"]",
".",
"append",
"(",
"addr",
")"
] | Add an address to the SAN list for the hostname request
:param addr: [] List of address to be added | [
"Add",
"an",
"address",
"to",
"the",
"SAN",
"list",
"for",
"the",
"hostname",
"request"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L89-L96 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | CertRequest.get_request | def get_request(self):
"""Generate request from the batched up entries
"""
if self.hostname_entry:
self.entries.append(self.hostname_entry)
request = {}
for entry in self.entries:
sans = sorted(list(set(entry['addresses'])))
request[entry['cn']] = {'sans': sans}
if self.json_encode:
return {'cert_requests': json.dumps(request, sort_keys=True)}
else:
return {'cert_requests': request} | python | def get_request(self):
"""Generate request from the batched up entries
"""
if self.hostname_entry:
self.entries.append(self.hostname_entry)
request = {}
for entry in self.entries:
sans = sorted(list(set(entry['addresses'])))
request[entry['cn']] = {'sans': sans}
if self.json_encode:
return {'cert_requests': json.dumps(request, sort_keys=True)}
else:
return {'cert_requests': request} | [
"def",
"get_request",
"(",
"self",
")",
":",
"if",
"self",
".",
"hostname_entry",
":",
"self",
".",
"entries",
".",
"append",
"(",
"self",
".",
"hostname_entry",
")",
"request",
"=",
"{",
"}",
"for",
"entry",
"in",
"self",
".",
"entries",
":",
"sans",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"entry",
"[",
"'addresses'",
"]",
")",
")",
")",
"request",
"[",
"entry",
"[",
"'cn'",
"]",
"]",
"=",
"{",
"'sans'",
":",
"sans",
"}",
"if",
"self",
".",
"json_encode",
":",
"return",
"{",
"'cert_requests'",
":",
"json",
".",
"dumps",
"(",
"request",
",",
"sort_keys",
"=",
"True",
")",
"}",
"else",
":",
"return",
"{",
"'cert_requests'",
":",
"request",
"}"
] | Generate request from the batched up entries | [
"Generate",
"request",
"from",
"the",
"batched",
"up",
"entries"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L98-L111 | train |
juju/charm-helpers | charmhelpers/contrib/hardening/host/checks/sysctl.py | get_audits | def get_audits():
"""Get OS hardening sysctl audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Apply the sysctl settings which are configured to be applied.
audits.append(SysctlConf())
# Make sure that only root has access to the sysctl.conf file, and
# that it is read-only.
audits.append(FilePermissionAudit('/etc/sysctl.conf',
user='root',
group='root', mode=0o0440))
# If module loading is not enabled, then ensure that the modules
# file has the appropriate permissions and rebuild the initramfs
if not settings['security']['kernel_enable_module_loading']:
audits.append(ModulesTemplate())
return audits | python | def get_audits():
"""Get OS hardening sysctl audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Apply the sysctl settings which are configured to be applied.
audits.append(SysctlConf())
# Make sure that only root has access to the sysctl.conf file, and
# that it is read-only.
audits.append(FilePermissionAudit('/etc/sysctl.conf',
user='root',
group='root', mode=0o0440))
# If module loading is not enabled, then ensure that the modules
# file has the appropriate permissions and rebuild the initramfs
if not settings['security']['kernel_enable_module_loading']:
audits.append(ModulesTemplate())
return audits | [
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"]",
"settings",
"=",
"utils",
".",
"get_settings",
"(",
"'os'",
")",
"# Apply the sysctl settings which are configured to be applied.",
"audits",
".",
"append",
"(",
"SysctlConf",
"(",
")",
")",
"# Make sure that only root has access to the sysctl.conf file, and",
"# that it is read-only.",
"audits",
".",
"append",
"(",
"FilePermissionAudit",
"(",
"'/etc/sysctl.conf'",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"mode",
"=",
"0o0440",
")",
")",
"# If module loading is not enabled, then ensure that the modules",
"# file has the appropriate permissions and rebuild the initramfs",
"if",
"not",
"settings",
"[",
"'security'",
"]",
"[",
"'kernel_enable_module_loading'",
"]",
":",
"audits",
".",
"append",
"(",
"ModulesTemplate",
"(",
")",
")",
"return",
"audits"
] | Get OS hardening sysctl audits.
:returns: dictionary of audits | [
"Get",
"OS",
"hardening",
"sysctl",
"audits",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/sysctl.py#L77-L97 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/openstack_security_guide.py | _stat | def _stat(file):
"""
Get the Ownership information from a file.
:param file: The path to a file to stat
:type file: str
:returns: owner, group, and mode of the specified file
:rtype: Ownership
:raises subprocess.CalledProcessError: If the underlying stat fails
"""
out = subprocess.check_output(
['stat', '-c', '%U %G %a', file]).decode('utf-8')
return Ownership(*out.strip().split(' ')) | python | def _stat(file):
"""
Get the Ownership information from a file.
:param file: The path to a file to stat
:type file: str
:returns: owner, group, and mode of the specified file
:rtype: Ownership
:raises subprocess.CalledProcessError: If the underlying stat fails
"""
out = subprocess.check_output(
['stat', '-c', '%U %G %a', file]).decode('utf-8')
return Ownership(*out.strip().split(' ')) | [
"def",
"_stat",
"(",
"file",
")",
":",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'stat'",
",",
"'-c'",
",",
"'%U %G %a'",
",",
"file",
"]",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"Ownership",
"(",
"*",
"out",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
")"
] | Get the Ownership information from a file.
:param file: The path to a file to stat
:type file: str
:returns: owner, group, and mode of the specified file
:rtype: Ownership
:raises subprocess.CalledProcessError: If the underlying stat fails | [
"Get",
"the",
"Ownership",
"information",
"from",
"a",
"file",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L104-L116 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/openstack_security_guide.py | _config_ini | def _config_ini(path):
"""
Parse an ini file
:param path: The path to a file to parse
:type file: str
:returns: Configuration contained in path
:rtype: Dict
"""
conf = configparser.ConfigParser()
conf.read(path)
return dict(conf) | python | def _config_ini(path):
"""
Parse an ini file
:param path: The path to a file to parse
:type file: str
:returns: Configuration contained in path
:rtype: Dict
"""
conf = configparser.ConfigParser()
conf.read(path)
return dict(conf) | [
"def",
"_config_ini",
"(",
"path",
")",
":",
"conf",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"path",
")",
"return",
"dict",
"(",
"conf",
")"
] | Parse an ini file
:param path: The path to a file to parse
:type file: str
:returns: Configuration contained in path
:rtype: Dict | [
"Parse",
"an",
"ini",
"file"
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L120-L131 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/openstack_security_guide.py | _validate_file_mode | def _validate_file_mode(mode, file_name, optional=False):
"""
Validate that a specified file has the specified permissions.
:param mode: file mode that is desires
:type owner: str
:param file_name: Path to the file to verify
:type file_name: str
:param optional: Is this file optional,
ie: Should this test fail when it's missing
:type optional: bool
"""
try:
ownership = _stat(file_name)
except subprocess.CalledProcessError as e:
print("Error reading file: {}".format(e))
if not optional:
assert False, "Specified file does not exist: {}".format(file_name)
assert mode == ownership.mode, \
"{} has an incorrect mode: {} should be {}".format(
file_name, ownership.mode, mode)
print("Validate mode of {}: PASS".format(file_name)) | python | def _validate_file_mode(mode, file_name, optional=False):
"""
Validate that a specified file has the specified permissions.
:param mode: file mode that is desires
:type owner: str
:param file_name: Path to the file to verify
:type file_name: str
:param optional: Is this file optional,
ie: Should this test fail when it's missing
:type optional: bool
"""
try:
ownership = _stat(file_name)
except subprocess.CalledProcessError as e:
print("Error reading file: {}".format(e))
if not optional:
assert False, "Specified file does not exist: {}".format(file_name)
assert mode == ownership.mode, \
"{} has an incorrect mode: {} should be {}".format(
file_name, ownership.mode, mode)
print("Validate mode of {}: PASS".format(file_name)) | [
"def",
"_validate_file_mode",
"(",
"mode",
",",
"file_name",
",",
"optional",
"=",
"False",
")",
":",
"try",
":",
"ownership",
"=",
"_stat",
"(",
"file_name",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"print",
"(",
"\"Error reading file: {}\"",
".",
"format",
"(",
"e",
")",
")",
"if",
"not",
"optional",
":",
"assert",
"False",
",",
"\"Specified file does not exist: {}\"",
".",
"format",
"(",
"file_name",
")",
"assert",
"mode",
"==",
"ownership",
".",
"mode",
",",
"\"{} has an incorrect mode: {} should be {}\"",
".",
"format",
"(",
"file_name",
",",
"ownership",
".",
"mode",
",",
"mode",
")",
"print",
"(",
"\"Validate mode of {}: PASS\"",
".",
"format",
"(",
"file_name",
")",
")"
] | Validate that a specified file has the specified permissions.
:param mode: file mode that is desires
:type owner: str
:param file_name: Path to the file to verify
:type file_name: str
:param optional: Is this file optional,
ie: Should this test fail when it's missing
:type optional: bool | [
"Validate",
"that",
"a",
"specified",
"file",
"has",
"the",
"specified",
"permissions",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L163-L184 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/openstack_security_guide.py | _config_section | def _config_section(config, section):
"""Read the configuration file and return a section."""
path = os.path.join(config.get('config_path'), config.get('config_file'))
conf = _config_ini(path)
return conf.get(section) | python | def _config_section(config, section):
"""Read the configuration file and return a section."""
path = os.path.join(config.get('config_path'), config.get('config_file'))
conf = _config_ini(path)
return conf.get(section) | [
"def",
"_config_section",
"(",
"config",
",",
"section",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"get",
"(",
"'config_path'",
")",
",",
"config",
".",
"get",
"(",
"'config_file'",
")",
")",
"conf",
"=",
"_config_ini",
"(",
"path",
")",
"return",
"conf",
".",
"get",
"(",
"section",
")"
] | Read the configuration file and return a section. | [
"Read",
"the",
"configuration",
"file",
"and",
"return",
"a",
"section",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L188-L192 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/openstack_security_guide.py | validate_file_permissions | def validate_file_permissions(config):
"""Verify that permissions on configuration files are secure enough."""
files = config.get('files', {})
for file_name, options in files.items():
for key in options.keys():
if key not in ["owner", "group", "mode"]:
raise RuntimeError(
"Invalid ownership configuration: {}".format(key))
mode = options.get('mode', config.get('permissions', '600'))
optional = options.get('optional', config.get('optional', 'False'))
if '*' in file_name:
for file in glob.glob(file_name):
if file not in files.keys():
if os.path.isfile(file):
_validate_file_mode(mode, file, optional)
else:
if os.path.isfile(file_name):
_validate_file_mode(mode, file_name, optional) | python | def validate_file_permissions(config):
"""Verify that permissions on configuration files are secure enough."""
files = config.get('files', {})
for file_name, options in files.items():
for key in options.keys():
if key not in ["owner", "group", "mode"]:
raise RuntimeError(
"Invalid ownership configuration: {}".format(key))
mode = options.get('mode', config.get('permissions', '600'))
optional = options.get('optional', config.get('optional', 'False'))
if '*' in file_name:
for file in glob.glob(file_name):
if file not in files.keys():
if os.path.isfile(file):
_validate_file_mode(mode, file, optional)
else:
if os.path.isfile(file_name):
_validate_file_mode(mode, file_name, optional) | [
"def",
"validate_file_permissions",
"(",
"config",
")",
":",
"files",
"=",
"config",
".",
"get",
"(",
"'files'",
",",
"{",
"}",
")",
"for",
"file_name",
",",
"options",
"in",
"files",
".",
"items",
"(",
")",
":",
"for",
"key",
"in",
"options",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"[",
"\"owner\"",
",",
"\"group\"",
",",
"\"mode\"",
"]",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid ownership configuration: {}\"",
".",
"format",
"(",
"key",
")",
")",
"mode",
"=",
"options",
".",
"get",
"(",
"'mode'",
",",
"config",
".",
"get",
"(",
"'permissions'",
",",
"'600'",
")",
")",
"optional",
"=",
"options",
".",
"get",
"(",
"'optional'",
",",
"config",
".",
"get",
"(",
"'optional'",
",",
"'False'",
")",
")",
"if",
"'*'",
"in",
"file_name",
":",
"for",
"file",
"in",
"glob",
".",
"glob",
"(",
"file_name",
")",
":",
"if",
"file",
"not",
"in",
"files",
".",
"keys",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file",
")",
":",
"_validate_file_mode",
"(",
"mode",
",",
"file",
",",
"optional",
")",
"else",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_name",
")",
":",
"_validate_file_mode",
"(",
"mode",
",",
"file_name",
",",
"optional",
")"
] | Verify that permissions on configuration files are secure enough. | [
"Verify",
"that",
"permissions",
"on",
"configuration",
"files",
"are",
"secure",
"enough",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L220-L237 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/openstack_security_guide.py | validate_uses_tls_for_keystone | def validate_uses_tls_for_keystone(audit_options):
"""Verify that TLS is used to communicate with Keystone."""
section = _config_section(audit_options, 'keystone_authtoken')
assert section is not None, "Missing section 'keystone_authtoken'"
assert not section.get('insecure') and \
"https://" in section.get("auth_uri"), \
"TLS is not used for Keystone" | python | def validate_uses_tls_for_keystone(audit_options):
"""Verify that TLS is used to communicate with Keystone."""
section = _config_section(audit_options, 'keystone_authtoken')
assert section is not None, "Missing section 'keystone_authtoken'"
assert not section.get('insecure') and \
"https://" in section.get("auth_uri"), \
"TLS is not used for Keystone" | [
"def",
"validate_uses_tls_for_keystone",
"(",
"audit_options",
")",
":",
"section",
"=",
"_config_section",
"(",
"audit_options",
",",
"'keystone_authtoken'",
")",
"assert",
"section",
"is",
"not",
"None",
",",
"\"Missing section 'keystone_authtoken'\"",
"assert",
"not",
"section",
".",
"get",
"(",
"'insecure'",
")",
"and",
"\"https://\"",
"in",
"section",
".",
"get",
"(",
"\"auth_uri\"",
")",
",",
"\"TLS is not used for Keystone\""
] | Verify that TLS is used to communicate with Keystone. | [
"Verify",
"that",
"TLS",
"is",
"used",
"to",
"communicate",
"with",
"Keystone",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L250-L256 | train |
juju/charm-helpers | charmhelpers/contrib/openstack/audits/openstack_security_guide.py | validate_uses_tls_for_glance | def validate_uses_tls_for_glance(audit_options):
"""Verify that TLS is used to communicate with Glance."""
section = _config_section(audit_options, 'glance')
assert section is not None, "Missing section 'glance'"
assert not section.get('insecure') and \
"https://" in section.get("api_servers"), \
"TLS is not used for Glance" | python | def validate_uses_tls_for_glance(audit_options):
"""Verify that TLS is used to communicate with Glance."""
section = _config_section(audit_options, 'glance')
assert section is not None, "Missing section 'glance'"
assert not section.get('insecure') and \
"https://" in section.get("api_servers"), \
"TLS is not used for Glance" | [
"def",
"validate_uses_tls_for_glance",
"(",
"audit_options",
")",
":",
"section",
"=",
"_config_section",
"(",
"audit_options",
",",
"'glance'",
")",
"assert",
"section",
"is",
"not",
"None",
",",
"\"Missing section 'glance'\"",
"assert",
"not",
"section",
".",
"get",
"(",
"'insecure'",
")",
"and",
"\"https://\"",
"in",
"section",
".",
"get",
"(",
"\"api_servers\"",
")",
",",
"\"TLS is not used for Glance\""
] | Verify that TLS is used to communicate with Glance. | [
"Verify",
"that",
"TLS",
"is",
"used",
"to",
"communicate",
"with",
"Glance",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L260-L266 | train |
juju/charm-helpers | charmhelpers/core/services/helpers.py | RelationContext.is_ready | def is_ready(self):
"""
Returns True if all of the `required_keys` are available from any units.
"""
ready = len(self.get(self.name, [])) > 0
if not ready:
hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG)
return ready | python | def is_ready(self):
"""
Returns True if all of the `required_keys` are available from any units.
"""
ready = len(self.get(self.name, [])) > 0
if not ready:
hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG)
return ready | [
"def",
"is_ready",
"(",
"self",
")",
":",
"ready",
"=",
"len",
"(",
"self",
".",
"get",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
")",
">",
"0",
"if",
"not",
"ready",
":",
"hookenv",
".",
"log",
"(",
"'Incomplete relation: {}'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
",",
"hookenv",
".",
"DEBUG",
")",
"return",
"ready"
] | Returns True if all of the `required_keys` are available from any units. | [
"Returns",
"True",
"if",
"all",
"of",
"the",
"required_keys",
"are",
"available",
"from",
"any",
"units",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/helpers.py#L70-L77 | train |
juju/charm-helpers | charmhelpers/core/services/helpers.py | RelationContext._is_ready | def _is_ready(self, unit_data):
"""
Helper method that tests a set of relation data and returns True if
all of the `required_keys` are present.
"""
return set(unit_data.keys()).issuperset(set(self.required_keys)) | python | def _is_ready(self, unit_data):
"""
Helper method that tests a set of relation data and returns True if
all of the `required_keys` are present.
"""
return set(unit_data.keys()).issuperset(set(self.required_keys)) | [
"def",
"_is_ready",
"(",
"self",
",",
"unit_data",
")",
":",
"return",
"set",
"(",
"unit_data",
".",
"keys",
"(",
")",
")",
".",
"issuperset",
"(",
"set",
"(",
"self",
".",
"required_keys",
")",
")"
] | Helper method that tests a set of relation data and returns True if
all of the `required_keys` are present. | [
"Helper",
"method",
"that",
"tests",
"a",
"set",
"of",
"relation",
"data",
"and",
"returns",
"True",
"if",
"all",
"of",
"the",
"required_keys",
"are",
"present",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/helpers.py#L79-L84 | train |
juju/charm-helpers | charmhelpers/core/services/base.py | service_restart | def service_restart(service_name):
"""
Wrapper around host.service_restart to prevent spurious "unknown service"
messages in the logs.
"""
if host.service_available(service_name):
if host.service_running(service_name):
host.service_restart(service_name)
else:
host.service_start(service_name) | python | def service_restart(service_name):
"""
Wrapper around host.service_restart to prevent spurious "unknown service"
messages in the logs.
"""
if host.service_available(service_name):
if host.service_running(service_name):
host.service_restart(service_name)
else:
host.service_start(service_name) | [
"def",
"service_restart",
"(",
"service_name",
")",
":",
"if",
"host",
".",
"service_available",
"(",
"service_name",
")",
":",
"if",
"host",
".",
"service_running",
"(",
"service_name",
")",
":",
"host",
".",
"service_restart",
"(",
"service_name",
")",
"else",
":",
"host",
".",
"service_start",
"(",
"service_name",
")"
] | Wrapper around host.service_restart to prevent spurious "unknown service"
messages in the logs. | [
"Wrapper",
"around",
"host",
".",
"service_restart",
"to",
"prevent",
"spurious",
"unknown",
"service",
"messages",
"in",
"the",
"logs",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L349-L358 | train |
juju/charm-helpers | charmhelpers/core/services/base.py | ServiceManager.manage | def manage(self):
"""
Handle the current hook by doing The Right Thing with the registered services.
"""
hookenv._run_atstart()
try:
hook_name = hookenv.hook_name()
if hook_name == 'stop':
self.stop_services()
else:
self.reconfigure_services()
self.provide_data()
except SystemExit as x:
if x.code is None or x.code == 0:
hookenv._run_atexit()
hookenv._run_atexit() | python | def manage(self):
"""
Handle the current hook by doing The Right Thing with the registered services.
"""
hookenv._run_atstart()
try:
hook_name = hookenv.hook_name()
if hook_name == 'stop':
self.stop_services()
else:
self.reconfigure_services()
self.provide_data()
except SystemExit as x:
if x.code is None or x.code == 0:
hookenv._run_atexit()
hookenv._run_atexit() | [
"def",
"manage",
"(",
"self",
")",
":",
"hookenv",
".",
"_run_atstart",
"(",
")",
"try",
":",
"hook_name",
"=",
"hookenv",
".",
"hook_name",
"(",
")",
"if",
"hook_name",
"==",
"'stop'",
":",
"self",
".",
"stop_services",
"(",
")",
"else",
":",
"self",
".",
"reconfigure_services",
"(",
")",
"self",
".",
"provide_data",
"(",
")",
"except",
"SystemExit",
"as",
"x",
":",
"if",
"x",
".",
"code",
"is",
"None",
"or",
"x",
".",
"code",
"==",
"0",
":",
"hookenv",
".",
"_run_atexit",
"(",
")",
"hookenv",
".",
"_run_atexit",
"(",
")"
] | Handle the current hook by doing The Right Thing with the registered services. | [
"Handle",
"the",
"current",
"hook",
"by",
"doing",
"The",
"Right",
"Thing",
"with",
"the",
"registered",
"services",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L125-L140 | train |
juju/charm-helpers | charmhelpers/core/services/base.py | ServiceManager.provide_data | def provide_data(self):
"""
Set the relation data for each provider in the ``provided_data`` list.
A provider must have a `name` attribute, which indicates which relation
to set data on, and a `provide_data()` method, which returns a dict of
data to set.
The `provide_data()` method can optionally accept two parameters:
* ``remote_service`` The name of the remote service that the data will
be provided to. The `provide_data()` method will be called once
for each connected service (not unit). This allows the method to
tailor its data to the given service.
* ``service_ready`` Whether or not the service definition had all of
its requirements met, and thus the ``data_ready`` callbacks run.
Note that the ``provided_data`` methods are now called **after** the
``data_ready`` callbacks are run. This gives the ``data_ready`` callbacks
a chance to generate any data necessary for the providing to the remote
services.
"""
for service_name, service in self.services.items():
service_ready = self.is_ready(service_name)
for provider in service.get('provided_data', []):
for relid in hookenv.relation_ids(provider.name):
units = hookenv.related_units(relid)
if not units:
continue
remote_service = units[0].split('/')[0]
argspec = getargspec(provider.provide_data)
if len(argspec.args) > 1:
data = provider.provide_data(remote_service, service_ready)
else:
data = provider.provide_data()
if data:
hookenv.relation_set(relid, data) | python | def provide_data(self):
"""
Set the relation data for each provider in the ``provided_data`` list.
A provider must have a `name` attribute, which indicates which relation
to set data on, and a `provide_data()` method, which returns a dict of
data to set.
The `provide_data()` method can optionally accept two parameters:
* ``remote_service`` The name of the remote service that the data will
be provided to. The `provide_data()` method will be called once
for each connected service (not unit). This allows the method to
tailor its data to the given service.
* ``service_ready`` Whether or not the service definition had all of
its requirements met, and thus the ``data_ready`` callbacks run.
Note that the ``provided_data`` methods are now called **after** the
``data_ready`` callbacks are run. This gives the ``data_ready`` callbacks
a chance to generate any data necessary for the providing to the remote
services.
"""
for service_name, service in self.services.items():
service_ready = self.is_ready(service_name)
for provider in service.get('provided_data', []):
for relid in hookenv.relation_ids(provider.name):
units = hookenv.related_units(relid)
if not units:
continue
remote_service = units[0].split('/')[0]
argspec = getargspec(provider.provide_data)
if len(argspec.args) > 1:
data = provider.provide_data(remote_service, service_ready)
else:
data = provider.provide_data()
if data:
hookenv.relation_set(relid, data) | [
"def",
"provide_data",
"(",
"self",
")",
":",
"for",
"service_name",
",",
"service",
"in",
"self",
".",
"services",
".",
"items",
"(",
")",
":",
"service_ready",
"=",
"self",
".",
"is_ready",
"(",
"service_name",
")",
"for",
"provider",
"in",
"service",
".",
"get",
"(",
"'provided_data'",
",",
"[",
"]",
")",
":",
"for",
"relid",
"in",
"hookenv",
".",
"relation_ids",
"(",
"provider",
".",
"name",
")",
":",
"units",
"=",
"hookenv",
".",
"related_units",
"(",
"relid",
")",
"if",
"not",
"units",
":",
"continue",
"remote_service",
"=",
"units",
"[",
"0",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"argspec",
"=",
"getargspec",
"(",
"provider",
".",
"provide_data",
")",
"if",
"len",
"(",
"argspec",
".",
"args",
")",
">",
"1",
":",
"data",
"=",
"provider",
".",
"provide_data",
"(",
"remote_service",
",",
"service_ready",
")",
"else",
":",
"data",
"=",
"provider",
".",
"provide_data",
"(",
")",
"if",
"data",
":",
"hookenv",
".",
"relation_set",
"(",
"relid",
",",
"data",
")"
] | Set the relation data for each provider in the ``provided_data`` list.
A provider must have a `name` attribute, which indicates which relation
to set data on, and a `provide_data()` method, which returns a dict of
data to set.
The `provide_data()` method can optionally accept two parameters:
* ``remote_service`` The name of the remote service that the data will
be provided to. The `provide_data()` method will be called once
for each connected service (not unit). This allows the method to
tailor its data to the given service.
* ``service_ready`` Whether or not the service definition had all of
its requirements met, and thus the ``data_ready`` callbacks run.
Note that the ``provided_data`` methods are now called **after** the
``data_ready`` callbacks are run. This gives the ``data_ready`` callbacks
a chance to generate any data necessary for the providing to the remote
services. | [
"Set",
"the",
"relation",
"data",
"for",
"each",
"provider",
"in",
"the",
"provided_data",
"list",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L142-L178 | train |
juju/charm-helpers | charmhelpers/core/services/base.py | ServiceManager.reconfigure_services | def reconfigure_services(self, *service_names):
"""
Update all files for one or more registered services, and,
if ready, optionally restart them.
If no service names are given, reconfigures all registered services.
"""
for service_name in service_names or self.services.keys():
if self.is_ready(service_name):
self.fire_event('data_ready', service_name)
self.fire_event('start', service_name, default=[
service_restart,
manage_ports])
self.save_ready(service_name)
else:
if self.was_ready(service_name):
self.fire_event('data_lost', service_name)
self.fire_event('stop', service_name, default=[
manage_ports,
service_stop])
self.save_lost(service_name) | python | def reconfigure_services(self, *service_names):
"""
Update all files for one or more registered services, and,
if ready, optionally restart them.
If no service names are given, reconfigures all registered services.
"""
for service_name in service_names or self.services.keys():
if self.is_ready(service_name):
self.fire_event('data_ready', service_name)
self.fire_event('start', service_name, default=[
service_restart,
manage_ports])
self.save_ready(service_name)
else:
if self.was_ready(service_name):
self.fire_event('data_lost', service_name)
self.fire_event('stop', service_name, default=[
manage_ports,
service_stop])
self.save_lost(service_name) | [
"def",
"reconfigure_services",
"(",
"self",
",",
"*",
"service_names",
")",
":",
"for",
"service_name",
"in",
"service_names",
"or",
"self",
".",
"services",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"is_ready",
"(",
"service_name",
")",
":",
"self",
".",
"fire_event",
"(",
"'data_ready'",
",",
"service_name",
")",
"self",
".",
"fire_event",
"(",
"'start'",
",",
"service_name",
",",
"default",
"=",
"[",
"service_restart",
",",
"manage_ports",
"]",
")",
"self",
".",
"save_ready",
"(",
"service_name",
")",
"else",
":",
"if",
"self",
".",
"was_ready",
"(",
"service_name",
")",
":",
"self",
".",
"fire_event",
"(",
"'data_lost'",
",",
"service_name",
")",
"self",
".",
"fire_event",
"(",
"'stop'",
",",
"service_name",
",",
"default",
"=",
"[",
"manage_ports",
",",
"service_stop",
"]",
")",
"self",
".",
"save_lost",
"(",
"service_name",
")"
] | Update all files for one or more registered services, and,
if ready, optionally restart them.
If no service names are given, reconfigures all registered services. | [
"Update",
"all",
"files",
"for",
"one",
"or",
"more",
"registered",
"services",
"and",
"if",
"ready",
"optionally",
"restart",
"them",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L180-L200 | train |
juju/charm-helpers | charmhelpers/core/services/base.py | ServiceManager.stop_services | def stop_services(self, *service_names):
"""
Stop one or more registered services, by name.
If no service names are given, stops all registered services.
"""
for service_name in service_names or self.services.keys():
self.fire_event('stop', service_name, default=[
manage_ports,
service_stop]) | python | def stop_services(self, *service_names):
"""
Stop one or more registered services, by name.
If no service names are given, stops all registered services.
"""
for service_name in service_names or self.services.keys():
self.fire_event('stop', service_name, default=[
manage_ports,
service_stop]) | [
"def",
"stop_services",
"(",
"self",
",",
"*",
"service_names",
")",
":",
"for",
"service_name",
"in",
"service_names",
"or",
"self",
".",
"services",
".",
"keys",
"(",
")",
":",
"self",
".",
"fire_event",
"(",
"'stop'",
",",
"service_name",
",",
"default",
"=",
"[",
"manage_ports",
",",
"service_stop",
"]",
")"
] | Stop one or more registered services, by name.
If no service names are given, stops all registered services. | [
"Stop",
"one",
"or",
"more",
"registered",
"services",
"by",
"name",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L202-L211 | train |
juju/charm-helpers | charmhelpers/core/services/base.py | ServiceManager.get_service | def get_service(self, service_name):
"""
Given the name of a registered service, return its service definition.
"""
service = self.services.get(service_name)
if not service:
raise KeyError('Service not registered: %s' % service_name)
return service | python | def get_service(self, service_name):
"""
Given the name of a registered service, return its service definition.
"""
service = self.services.get(service_name)
if not service:
raise KeyError('Service not registered: %s' % service_name)
return service | [
"def",
"get_service",
"(",
"self",
",",
"service_name",
")",
":",
"service",
"=",
"self",
".",
"services",
".",
"get",
"(",
"service_name",
")",
"if",
"not",
"service",
":",
"raise",
"KeyError",
"(",
"'Service not registered: %s'",
"%",
"service_name",
")",
"return",
"service"
] | Given the name of a registered service, return its service definition. | [
"Given",
"the",
"name",
"of",
"a",
"registered",
"service",
"return",
"its",
"service",
"definition",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L213-L220 | train |
juju/charm-helpers | charmhelpers/core/services/base.py | ServiceManager.fire_event | def fire_event(self, event_name, service_name, default=None):
"""
Fire a data_ready, data_lost, start, or stop event on a given service.
"""
service = self.get_service(service_name)
callbacks = service.get(event_name, default)
if not callbacks:
return
if not isinstance(callbacks, Iterable):
callbacks = [callbacks]
for callback in callbacks:
if isinstance(callback, ManagerCallback):
callback(self, service_name, event_name)
else:
callback(service_name) | python | def fire_event(self, event_name, service_name, default=None):
"""
Fire a data_ready, data_lost, start, or stop event on a given service.
"""
service = self.get_service(service_name)
callbacks = service.get(event_name, default)
if not callbacks:
return
if not isinstance(callbacks, Iterable):
callbacks = [callbacks]
for callback in callbacks:
if isinstance(callback, ManagerCallback):
callback(self, service_name, event_name)
else:
callback(service_name) | [
"def",
"fire_event",
"(",
"self",
",",
"event_name",
",",
"service_name",
",",
"default",
"=",
"None",
")",
":",
"service",
"=",
"self",
".",
"get_service",
"(",
"service_name",
")",
"callbacks",
"=",
"service",
".",
"get",
"(",
"event_name",
",",
"default",
")",
"if",
"not",
"callbacks",
":",
"return",
"if",
"not",
"isinstance",
"(",
"callbacks",
",",
"Iterable",
")",
":",
"callbacks",
"=",
"[",
"callbacks",
"]",
"for",
"callback",
"in",
"callbacks",
":",
"if",
"isinstance",
"(",
"callback",
",",
"ManagerCallback",
")",
":",
"callback",
"(",
"self",
",",
"service_name",
",",
"event_name",
")",
"else",
":",
"callback",
"(",
"service_name",
")"
] | Fire a data_ready, data_lost, start, or stop event on a given service. | [
"Fire",
"a",
"data_ready",
"data_lost",
"start",
"or",
"stop",
"event",
"on",
"a",
"given",
"service",
"."
] | aa785c40c3b7a8c69dbfbc7921d6b9f30142e171 | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L222-L236 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.