charmhelpers.core.hookenv¶
Config |
A dictionary representation of the charm’s config.yaml, with some extra features: |
Hooks |
A convenient handler for hook functions. |
NoNetworkBinding |
|
Serializable |
Wrapper, an object that can be serialized to yaml or json |
UnregisteredHookError |
Raised when an undefined hook is called |
action_fail |
Deprecated since version 0.20.7. |
action_get |
Deprecated since version 0.20.7. |
action_name |
Get the name of the currently executing action. |
action_set |
Deprecated since version 0.20.7. |
action_tag |
Get the tag for the currently executing action. |
action_uuid |
Get the UUID of the currently executing action. |
add_metric |
Add metric values. |
application_name |
The name of the deployed application this unit belongs to. |
application_version_set |
Charm authors may trigger this command from any hook to output what version of the application is running. |
atexit |
Schedule a callback to run on successful hook completion. |
atstart |
Schedule a callback to run before the main hook. |
cached |
Cache return values for multiple executions of func + args |
charm_dir |
Return the root directory of the current charm |
charm_name |
Get the name of the current charm as is specified on metadata.yaml |
close_port |
Close a service network port |
close_ports |
Close a range of service network ports |
cmd_exists |
Return True if the specified cmd exists in the path |
config |
Get the juju charm configuration (scope==None) or individual key, (scope=str). |
egress_subnets |
Retrieve the egress-subnets from a relation. |
env_proxy_settings |
Get proxy settings from process environment variables. |
execution_environment |
A convenient bundling of the current execution context |
expected_peer_units |
Get a generator for units we expect to join peer relation based on goal-state. |
expected_related_units |
Get a generator for units we expect to join relation based on goal-state. |
flush |
Flushes any entries from function cache where the key is found in the function+args |
function_fail |
Sets the function status to failed and sets the error message. |
function_get |
Gets the value of an action parameter, or all key/value param pairs |
function_id |
Get the ID of the currently executing function. |
function_log |
Write a function progress message |
function_name |
Get the name of the currently executing function. |
function_set |
Sets the values to be returned after the function finishes |
function_tag |
Get the tag for the currently executing function. |
goal_state |
Juju goal state values |
has_juju_version |
Return True if the Juju version is at least the provided version |
hook_name |
The name of the currently executing hook |
in_relation_hook |
Determine whether we’re running in a relation hook |
ingress_address |
Retrieve the ingress-address from a relation when available. |
interface_to_relations |
Given an interface, return a list of relation names for the current charm that use that interface. |
is_leader |
Does the current unit hold the juju leadership |
is_relation_made |
Determine whether a relation is established by checking for presence of key(s). |
iter_units_for_relation_name |
Iterate through all units in a relation |
juju_version |
Full version string (eg. |
leader_get |
Juju leader get value(s) |
leader_set |
Juju leader set value(s) |
local_unit |
Local unit ID |
log |
Write a message to the juju log |
metadata |
Get the current charm metadata.yaml contents as a python object |
meter_info |
Get the meter status information, if running in the meter-status-changed hook. |
meter_status |
Get the meter status, if running in the meter-status-changed hook. |
model_name |
Name of the model that this unit is deployed in. |
model_uuid |
UUID of the model that this unit is deployed in. |
network_get |
Retrieve the network details for a relation endpoint |
network_get_primary_address |
Deprecated since Juju 2.3; use network_get() |
open_port |
Open a service network port |
open_ports |
Opens a range of service network ports |
opened_ports |
Get the opened ports |
payload_register |
is used while a hook is running to let Juju know that a payload has been started. |
payload_status_set |
is used to update the current status of a registered payload. |
payload_unregister |
is used while a hook is running to let Juju know that a payload has been manually stopped. |
peer_relation_id |
Get the peers relation id if a peers relation has been joined, else None. |
principal_unit |
Returns the principal unit of this unit, otherwise None |
related_units |
A list of related units |
relation_clear |
Clears any relation data already set on relation r_id |
relation_for_unit |
Get the json represenation of a unit’s relation |
relation_get |
Get relation information |
relation_id |
The relation ID for the current or a specified relation |
relation_ids |
A list of relation_ids |
relation_set |
Set relation information for the current unit |
relation_to_interface |
Given the name of a relation, return the interface that relation uses. |
relation_to_role_and_interface |
Given the name of a relation, return the role and the name of the interface that relation uses (where role is one of provides , requires , or peers ). |
relation_type |
The scope for the current relation hook |
relation_types |
Get a list of relation types supported by this charm |
relations |
Get a nested dictionary of relation data for all related units |
relations_for_id |
Get relations of a specific relation ID |
relations_of_type |
Get relations of a specific type |
remote_service_name |
The remote service name for a given relation-id (or the current relation) |
remote_unit |
The remote unit for the current relation hook |
resource_get |
used to fetch the resource path of the given name. |
role_and_interface_to_relations |
Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of provides , requires , or peers ). |
service_name |
Deprecated since version 0.19.1. |
status_get |
Retrieve the previously set juju workload state and message |
status_set |
Set the workload state with a message |
storage_get |
Get storage attributes |
storage_list |
List the storage IDs for the unit |
translate_exc |
|
unit_doomed |
Determines if the unit is being removed from the model |
unit_get |
Get the unit ID for the remote unit |
unit_private_ip |
Get this unit’s private IP address |
unit_public_ip |
Get this unit’s public IP address |
Interactions with the Juju environment
-
class
charmhelpers.core.hookenv.
Config
(*args, **kw)¶ Bases:
dict
A dictionary representation of the charm’s config.yaml, with some extra features:
- See which values in the dictionary have changed since the previous hook.
- For values that have changed, see what the previous value was.
- Store arbitrary data for use in a later hook.
NOTE: Do not instantiate this object directly - instead call
hookenv.config()
, which will return an instance ofConfig
.Example usage:
>>> # inside a hook >>> from charmhelpers.core import hookenv >>> config = hookenv.config() >>> config['foo'] 'bar' >>> # store a new key/value for later use >>> config['mykey'] = 'myval' >>> # user runs `juju set mycharm foo=baz` >>> # now we're inside subsequent config-changed hook >>> config = hookenv.config() >>> config['foo'] 'baz' >>> # test to see if this val has changed since last hook >>> config.changed('foo') True >>> # what was the previous value? >>> config.previous('foo') 'bar' >>> # keys/values that we add are preserved across hooks >>> config['mykey'] 'myval'
-
CONFIG_FILE_NAME
= '.juju-persistent-config'¶
-
changed
(key)¶ Return True if the current value for this key is different from the previous value.
-
load_previous
(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.
Parameters: 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.
-
previous
(key)¶ Return previous value for this key, or None if there is no previous value.
-
save
()¶ Save this config to disk.
If the charm is using the
Services Framework
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.
-
class
charmhelpers.core.hookenv.
Hooks
(config_save=None)¶ Bases:
object
A convenient handler for hook functions.
Example:
hooks = Hooks() # register a hook, taking its name from the function name @hooks.hook() def install(): pass # your code here # register a hook, providing a custom hook name @hooks.hook("config-changed") def config_changed(): pass # your code here if __name__ == "__main__": # execute a hook based on the name the program is called by hooks.execute(sys.argv)
-
execute
(args)¶ Execute a registered hook based on args[0]
-
hook
(*hook_names)¶ Decorator, registering them as hooks
-
register
(name, function)¶ Register a hook
-
-
exception
charmhelpers.core.hookenv.
NoNetworkBinding
¶ Bases:
Exception
-
class
charmhelpers.core.hookenv.
Serializable
(obj)¶ Bases:
collections.UserDict
Wrapper, an object that can be serialized to yaml or json
-
json
()¶ Serialize the object to json
-
yaml
()¶ Serialize the object to yaml
-
-
exception
charmhelpers.core.hookenv.
UnregisteredHookError
¶ Bases:
Exception
Raised when an undefined hook is called
-
charmhelpers.core.hookenv.
action_fail
(message)¶ Deprecated since version 0.20.7: Alias for
function_fail()
.Sets the action status to failed and sets the error message.
The results set by action_set are preserved.
-
charmhelpers.core.hookenv.
action_get
(key=None)¶ Deprecated since version 0.20.7: Alias for
function_get()
.Gets the value of an action parameter, or all key/value param pairs.
-
charmhelpers.core.hookenv.
action_name
()¶ Get the name of the currently executing action.
-
charmhelpers.core.hookenv.
action_set
(values)¶ Deprecated since version 0.20.7: Alias for
function_set()
.Sets the values to be returned after the action finishes.
-
charmhelpers.core.hookenv.
action_tag
()¶ Get the tag for the currently executing action.
-
charmhelpers.core.hookenv.
action_uuid
()¶ Get the UUID of the currently executing action.
-
charmhelpers.core.hookenv.
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.
-
charmhelpers.core.hookenv.
application_name
()¶ The name of the deployed application this unit belongs to.
-
charmhelpers.core.hookenv.
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.
-
charmhelpers.core.hookenv.
atexit
(callback, *args, **kwargs)¶ Schedule a callback to run on successful hook completion.
Callbacks are run in the reverse order that they were added.
-
charmhelpers.core.hookenv.
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.
-
charmhelpers.core.hookenv.
cached
(func)¶ Cache return values for multiple executions of func + args
For example:
@cached def unit_get(attribute): pass unit_get('test')
will cache the result of unit_get + ‘test’ for future calls.
-
charmhelpers.core.hookenv.
charm_dir
()¶ Return the root directory of the current charm
-
charmhelpers.core.hookenv.
charm_name
()¶ Get the name of the current charm as is specified on metadata.yaml
-
charmhelpers.core.hookenv.
close_port
(port, protocol='TCP')¶ Close a service network port
-
charmhelpers.core.hookenv.
close_ports
(start, end, protocol='TCP')¶ Close a range of service network ports
-
charmhelpers.core.hookenv.
cmd_exists
(cmd)¶ Return True if the specified cmd exists in the path
-
charmhelpers.core.hookenv.
config
(scope=None)¶ Get the juju charm configuration (scope==None) or individual key, (scope=str). The returned value is a Python data structure loaded as JSON from the Juju config command.
Parameters: scope (Optional[str]) – If set, return the value for the specified key. Returns: Either the whole config as a Config, or a key from it. Return type: Any
-
charmhelpers.core.hookenv.
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.
Parameters: - rid – string relation id
- unit – string unit name
Side effect: calls relation_get
Returns: list of subnets in CIDR format. eg. [‘192.168.1.0/24’, ‘2001::F00F/128’]
-
charmhelpers.core.hookenv.
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 juju-no-proxy (available as of 2.4.2, see lp:1782236) and juju-ftp-proxy 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.
Parameters: selected_settings (list) – format only a subset of possible settings Return type: Option(None, dict[str, str])
-
charmhelpers.core.hookenv.
execution_environment
()¶ A convenient bundling of the current execution context
-
charmhelpers.core.hookenv.
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 Return type: types.GeneratorType Raises: NotImplementedError
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()))
Parameters: reltype (str) – Relation type to list data for, default is to list data for the realtion type we are currently executing a hook for. Returns: iterator Return type: types.GeneratorType Raises: KeyError, NotImplementedError
-
charmhelpers.core.hookenv.
flush
(key)¶ Flushes any entries from function cache where the key is found in the function+args
-
charmhelpers.core.hookenv.
function_fail
(message)¶ Sets the function status to failed and sets the error message.
The results set by function_set are preserved.
-
charmhelpers.core.hookenv.
function_get
(key=None)¶ Gets the value of an action parameter, or all key/value param pairs
-
charmhelpers.core.hookenv.
function_id
()¶ Get the ID of the currently executing function.
-
charmhelpers.core.hookenv.
function_log
(message)¶ Write a function progress message
-
charmhelpers.core.hookenv.
function_name
()¶ Get the name of the currently executing function.
-
charmhelpers.core.hookenv.
function_set
(values)¶ Sets the values to be returned after the function finishes
-
charmhelpers.core.hookenv.
function_tag
()¶ Get the tag for the currently executing function.
-
charmhelpers.core.hookenv.
goal_state
()¶ Juju goal state values
-
charmhelpers.core.hookenv.
has_juju_version
(minimum_version)¶ Return True if the Juju version is at least the provided version
-
charmhelpers.core.hookenv.
hook_name
()¶ The name of the currently executing hook
-
charmhelpers.core.hookenv.
in_relation_hook
()¶ Determine whether we’re running in a relation hook
-
charmhelpers.core.hookenv.
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)]Parameters: - rid – string relation id
- unit – string unit name
Side effect: calls relation_get
Returns: string IP address
-
charmhelpers.core.hookenv.
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.
-
charmhelpers.core.hookenv.
is_leader
()¶ Does the current unit hold the juju leadership
Uses juju to determine whether the current unit is the leader of its peers
-
charmhelpers.core.hookenv.
is_relation_made
(relation, keys='private-address')¶ Determine whether a relation is established by checking for presence of key(s). If a list of keys is provided, they must all be present for the relation to be identified as made
-
charmhelpers.core.hookenv.
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)]Parameters: relation_name – string relation name Yield: Named Tuple with rid and unit field names
-
charmhelpers.core.hookenv.
juju_version
()¶ Full version string (eg. ‘1.23.3.1-trusty-amd64’)
-
charmhelpers.core.hookenv.
leader_get
(attribute=None)¶ Juju leader get value(s)
-
charmhelpers.core.hookenv.
leader_set
(settings=None, **kwargs)¶ Juju leader set value(s)
-
charmhelpers.core.hookenv.
local_unit
()¶ Local unit ID
-
charmhelpers.core.hookenv.
log
(message, level=None)¶ Write a message to the juju log
-
charmhelpers.core.hookenv.
metadata
()¶ Get the current charm metadata.yaml contents as a python object
-
charmhelpers.core.hookenv.
meter_info
()¶ Get the meter status information, if running in the meter-status-changed hook.
-
charmhelpers.core.hookenv.
meter_status
()¶ Get the meter status, if running in the meter-status-changed hook.
-
charmhelpers.core.hookenv.
model_name
()¶ Name of the model that this unit is deployed in.
-
charmhelpers.core.hookenv.
model_uuid
()¶ UUID of the model that this unit is deployed in.
-
charmhelpers.core.hookenv.
network_get
(endpoint, relation_id=None)¶ Retrieve the network details for a relation endpoint
Parameters: - endpoint – string. The name of a relation endpoint
- relation_id – int. The ID of the relation for the current context.
Returns: dict. The loaded YAML output of the network-get query.
Raise: NotImplementedError if request not supported by the Juju version.
-
charmhelpers.core.hookenv.
network_get_primary_address
(binding)¶ Deprecated since Juju 2.3; use network_get()
Retrieve the primary network address for a named binding
Parameters: binding – string. The name of a relation of extra-binding Returns: string. The primary IP address for the named binding Raise: NotImplementedError if run on Juju < 2.0
-
charmhelpers.core.hookenv.
open_port
(port, protocol='TCP')¶ Open a service network port
-
charmhelpers.core.hookenv.
open_ports
(start, end, protocol='TCP')¶ Opens a range of service network ports
-
charmhelpers.core.hookenv.
opened_ports
()¶ Get the opened ports
Note that this will only show ports opened in a previous hook
Returns: Opened ports as a list of strings: ['8080/tcp', '8081-8083/tcp']
-
charmhelpers.core.hookenv.
payload_register
(ptype, klass, pid)¶ is used while a hook is running to let Juju know that a payload has been started.
-
charmhelpers.core.hookenv.
payload_status_set
(klass, pid, status)¶ is used to update the current status of a registered payload. The <class> and <id> provided must match a payload that has been previously registered with juju using payload-register. The <status> must be one of the follow: starting, started, stopping, stopped
-
charmhelpers.core.hookenv.
payload_unregister
(klass, pid)¶ is used while a hook is running to let Juju know that a payload has been manually stopped. The <class> and <id> provided must match a payload that has been previously registered with juju using payload-register.
-
charmhelpers.core.hookenv.
peer_relation_id
()¶ Get the peers relation id if a peers relation has been joined, else None.
-
charmhelpers.core.hookenv.
principal_unit
()¶ Returns the principal unit of this unit, otherwise None
A list of related units
-
charmhelpers.core.hookenv.
relation_clear
(r_id=None)¶ Clears any relation data already set on relation r_id
-
charmhelpers.core.hookenv.
relation_for_unit
(unit=None, rid=None)¶ Get the json represenation of a unit’s relation
-
charmhelpers.core.hookenv.
relation_get
(attribute=None, unit=None, rid=None)¶ Get relation information
-
charmhelpers.core.hookenv.
relation_id
(relation_name=None, service_or_unit=None)¶ The relation ID for the current or a specified relation
-
charmhelpers.core.hookenv.
relation_ids
(reltype=None)¶ A list of relation_ids
-
charmhelpers.core.hookenv.
relation_set
(relation_id=None, relation_settings=None, **kwargs)¶ Set relation information for the current unit
-
charmhelpers.core.hookenv.
relation_to_interface
(relation_name)¶ Given the name of a relation, return the interface that relation uses.
Returns: The interface name, or None
.
-
charmhelpers.core.hookenv.
relation_to_role_and_interface
(relation_name)¶ Given the name of a relation, return the role and the name of the interface that relation uses (where role is one of
provides
,requires
, orpeers
).Returns: A tuple containing (role, interface)
, or(None, None)
.
-
charmhelpers.core.hookenv.
relation_type
()¶ The scope for the current relation hook
-
charmhelpers.core.hookenv.
relation_types
()¶ Get a list of relation types supported by this charm
-
charmhelpers.core.hookenv.
relations
()¶ Get a nested dictionary of relation data for all related units
-
charmhelpers.core.hookenv.
relations_for_id
(relid=None)¶ Get relations of a specific relation ID
-
charmhelpers.core.hookenv.
relations_of_type
(reltype=None)¶ Get relations of a specific type
-
charmhelpers.core.hookenv.
remote_service_name
(relid=None)¶ The remote service name for a given relation-id (or the current relation)
-
charmhelpers.core.hookenv.
remote_unit
()¶ The remote unit for the current relation hook
-
charmhelpers.core.hookenv.
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
-
charmhelpers.core.hookenv.
role_and_interface_to_relations
(role, interface_name)¶ Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of
provides
,requires
, orpeers
).Returns: A list of relation names.
-
charmhelpers.core.hookenv.
service_name
()¶ Deprecated since version 0.19.1: Alias for
application_name()
.
-
charmhelpers.core.hookenv.
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’, “”
-
charmhelpers.core.hookenv.
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 instead.
workload_state – valid juju workload state. message – status update message
-
charmhelpers.core.hookenv.
storage_get
(attribute=None, storage_id=None)¶ Get storage attributes
-
charmhelpers.core.hookenv.
storage_list
(storage_name=None)¶ List the storage IDs for the unit
-
charmhelpers.core.hookenv.
translate_exc
(from_exc, to_exc)¶
-
charmhelpers.core.hookenv.
unit_doomed
(unit=None)¶ Determines if the unit is being removed from the model
Requires Juju 2.4.1.
Parameters: unit – string unit name, defaults to local_unit Side effect: calls goal_state Side effect: calls local_unit Side effect: calls has_juju_version Returns: True if the unit is being removed, already gone, or never existed
-
charmhelpers.core.hookenv.
unit_get
(attribute)¶ Get the unit ID for the remote unit
-
charmhelpers.core.hookenv.
unit_private_ip
()¶ Get this unit’s private IP address
-
charmhelpers.core.hookenv.
unit_public_ip
()¶ Get this unit’s public IP address