Charm hooks

An application unit’s direct action is entirely defined by its charm’s hooks. Hooks are executable files in a charm’s hooks directory; hooks with particular names (see below) will be invoked by the juju unit agent at particular times, and thereby cause changes to the world.

Whenever a hook-worthy event takes place, the unit agent first checks whether that hook is being debugged, and if so hands over control to the user. Otherwise, it tries to find a hook with precisely the right name. If the hook doesn’t exist, the agent continues without complaint; if the hook does exist, it is invoked without arguments in a specific hook context, and its output is written to the unit agent’s log. If it returns a non-zero exit code, the agent enters an error state and awaits user intervention.

The agent will also enter an error state if the unit agent process is aborted during hook execution.

There are multiple types of hooks, each described in more detail in the following sections.

None of the hooks are required; if you don’t implement a hook, it just doesn’t get run. When a hook event occurs, Juju will look for the corresponding hook file to execute, but if it finds none, will continue running without generating an error.

All the hooks must be written to be idempotent, meaning that there should be no different from running the hook once from running it multiple times. This property is important because hooks can be run multiple times by the Juju system in ways that might be difficult to predict.

Core lifecycle hooks

These run during the normal charm lifecycle.

config-changed

config-changed runs in several different situations.

  • immediately after “install”
  • immediately after “upgrade-charm”
  • at least once when the unit agent is restarted (but, if the unit is in an error state, it won’t be run until after the error state is cleared).
  • after changing charm configuration using the GUI or command line interface

It cannot assume that the software has already been started; it should not start stopped software, but should (if appropriate) restart running software to make configuration changes into account.

install

install is run at the beginning of a charm lifecycle. The hook should be used to perform one-time setup operations, such as installing prerequisite software that will not change with configuration changes.

leader-elected

leader-elected is run at least once to signify that Juju decided this unit is the leader. Authors can use this hook to take action if their protocols for leadership, consensus, raft, or quorum require one unit to assert leadership. If the election process is done internally to the application, other code should be used to signal the leader to Juju. For more information read the Implementing leadership and leader-elected pages.

leader-settings-changed

leader-settings-changed runs when the leader has set values for the other units to respond to. Much like (config-changed)[#heading–config-changed] but for the leaders to send values to other units. Follower units can implement this hook and take action when the leader sets values. For more information read the Implementing leadership page.

start

start runs immediately after the first config-changed hook. It should be used to ensure the charm’s software is running. Note that the charm’s software should be configured to persist through reboots without further intervention on juju’s part.

stop

stop runs immediately before the end of the unit’s destruction sequence. It should be used to ensure that the charm’s software is not running, and will not start again on reboot.

This hook is called when an application removal is requested by the client. It should implement the following logic:

  • Stop the application
  • Remove any files/configuration created during the application lifecycle
  • Prepare any backup(s) of the application that are required for restore purposes.

upgrade-charm

upgrade-charm runs immediately after any upgrade operation that does not itself interrupt an existing error state. It should be used to reconcile local state written by some other version of the charm into whatever form it needs to take to be manipulated by the current version.

While the forced upgrade functionality is intended as a developer tool, and is not generally suitable for end users, it’s somewhat optimistic to depend on the functionality never being abused. In light of this, if you need to run an upgrade-charm hook before your other hooks will work correctly, it may be wise to preface all your other hooks with a quick call to your (idempotent) upgrade-charm.

update-status

update-status provides constant feedback to the user about the status of the application the charm is modeling. The charm is run by Juju at regular intervals, and allows authors to run code that gets the “health” of the application.

Relation hooks

Units will only participate in relations after they’re been started, and before they’ve been stopped. Within that time window, the unit may participate in several different relations at a time, including multiple relations with the same name.

To illustrate, consider a database application that will be used by multiple client applications. Units of a single client application will surely want to connect to, and use the same database; but if units of another client application were to use that same database, the consequences could be catastrophic for all concerned.

If juju respected the limit field in relation metadata, it would be possible to work around this, but it’s not a high- priority bug: most provider applications should be able to handle multiple requirers anyway, and most requirers will only be connected to one provider anyway.

When a unit running a given charm participates in a given relation, it runs at least three hooks for every remote unit it becomes aware of in that relation.

[name]-relation-joined

[name]-relation-joined is run only when that remote unit is first observed by the unit. It should be used to relation-set any local unit settings that can be determined using no more than the name of the joining unit and the remote private-address setting, which is always available when the relation is created and is by convention not deleted.

You should not depend upon any other relation settings in the -joined hook because they’re not guaranteed to be present; if you need more information you should wait for a -changed hook that presents the right information.

[name]-relation-changed

[name]-relation-changed is always run once, after -joined, and will subsequently be run whenever that remote unit changes its settings for the relation. It should be the only hook that relies upon remote relation settings from relation-get, and it should not error if the settings are incomplete: you can guarantee that when the remote unit changes its settings, the hook will be run again.

The settings that you can get, and that you should set, are determined by the relation’s interface.

[name]-relation-departed

[name]-relation-departed is run once only, when the remote unit is known to be leaving the relation; it will only run once at least one -changed has been run, and after -departed has run, no further -changed hooks will be run. This should be used to remove all references to the remote unit, because there’s no guarantee that it’s still part of the system; it’s perfectly probable (although not guaranteed) that the system running that unit has already shut down.

When a unit’s participation in a relation is known to be ending, the unit agent continues to uphold the ordering guarantees above; but within those constraints, it will run the fewest possible hooks to notify the charm of the departure of each remote unit.

Once all necessary -departed hooks have been run for such a relation, the unit agent will run the final relation hook:

[name]-relation-broken

[name]-relation-broken indicates that the current relation is no longer valid, and that the charm’s software must be configured as though the relation had never existed. It will only be called after every necessary -departed hook has been run; if it’s being executed, you can be sure that no remote units are currently known locally.

It is important to note that the -broken hook might run even if no other units have ever joined the relation. This is not a bug: even if no remote units have ever joined, the fact of the unit’s participation can be detected in other hooks via the relation-ids tool, and the -broken hook needs to execute to allow the charm to clean up any optimistically-generated configuration.

And, again, it’s important to internalise the fact that there may be multiple runtime relations in play with the same name, and that they’re independent: one -broken hook does not mean that every such relation is broken.

Storage Charm Hooks

Juju can provide a variety of storage to charms. The charms can define several different types of storage that are allocated from Juju. To read more information, see the storage document

[name]-storage-attached

[name]-storage-attached allows the charm to run code when storage has been added. The storage-attached hooks will be run before the install hook, so that the installation routine may use the storage. The name prefix of this hook will depend on the storage key defined in the metadata.yaml file.

[name]-storage-detaching

[name]-storage-detaching allows the charm to run code before storage is removed. The storage-detaching hooks will be run before storage is detached, and always before the stop hook is run, to allow the charm to gracefully release resources before they are removed and before the unit terminates. The name prefix of the hook will depend on the storage key defined in the metadata.yaml file.

Metric Hooks

collect-metrics

Juju executes the collect-metrics hook every five minutes for the lifetime of the unit. Use the add-metric hook tool in collect-metrics to add measurements to Juju.

Because it may run concurrently with lifecycle charm hooks, collect-metrics executes in a more restricted environment where many hook tools (such as config-get) are not available. If access to charm configuration or other items is required, charmhelpers.core.unitdata.kv may be used to pass information into the collect-metrics hook context.

Writing hooks

If you follow the Getting started guide, you’ll get a good sense of the basics. To fill out your knowledge, you’ll want to study the hook context and tools, and to experiment with debug-hooks.

Independent of the nuts and bolts, though, good hooks display several useful high-level properties:

  • They are idempotent: that is to say that there should be no observable difference between running a hook once, and running it N times in a row. If this property does not hold, you are likely to be making your own life unnecessarily difficult: apart from anything else, the average user’s most likely first response to a failed hook will be to try to run it again (if they don’t just skip it).

  • They are easy to read and understand. It’s tempting to write a single file that does everything, and which just calls different functions internally depending on the value of argv[0], and to symlink that one file for every hook; but such structures quickly become unwieldy. The time taken to write a library, separate from the hooks, is very likely to be well spent: it lets you write single hooks that are clear and focused, and insulates the maintainer from irrelevant details.

  • Where possible, they reuse common code already written to ease or solve common use cases.

  • They do not return errors unless there is a good reason to believe that they cannot be resolved without user intervention. Doing so is an admission of defeat: a user who sees your charm returning an error state is unlikely to have the specific expertise necessary to resolve it. If you have to return an error, please be sure to at least write any context you can to the log before you do so.

  • They write only very sparingly to the charm directory.

We recommend you also familiarise yourself with the best practices and, if you plan to distribute your charm, the charm store policy.

1 Like

Typo: the link has its format broken

Fixed :slight_smile: Thanks for pointing it out.

This is also missing ‘relation-created’ which was added in Juju 2.8

1 Like

2.8 hasn’t been released yet. The docs reflect the current stable release.

1 Like

Fair enough. Though given our intent to flag specific items with “introduced in X.Y” it would be nice to have it. We were hoping to link to it from our own release documents indicating support for it. It does feel like starting to have documentation for rc so that people can understand what they’re looking forward to on new releases is reasonable.

1 Like

This would be maybe difficult to maintain, but it would be nice if you could say something like, “Introduced in Juju 2.8 ( upcoming release candidate )” because I could imaging it being easy for a user to miss that 2.8 was not released yet, especially in a product’s public documentation which I would assume is only going to show me up-to-date ( and not ahead of release ) information.


On a related note, many projects solve this problem by using static site generators and building a new version of the site for every release, keeping the old versions for reference and providing a way to select which version you want to view the documentation for. Then you can always choose to view the latest master ( or RC ) version of the docs if you desire, but the default is always the latest stable release.

I know that we are currently serving the documentation site directly from discourse, but it would be possible to hook up a static site generator to build the static site by querying the discourse API. This would allow us to take snapshots of the Discourse documentation at every Juju release, create a static site from it, and deploy the static site as the public facing documentation.

Discourse would then be always kept up-to-date as the documentation for the latest RC and the documentation would be rendered and released as a static site on every Juju release.

That way we would have the documentation for each version of Juju and users could pick which one the want to view, while we are able to always put the latest documentation in Discourse as soon as we can write it down.

Just an idea… :slight_smile:

3 Likes

We used to have separate documentation per release for Juju. It actually was a net negative for SEO, because the old versions end up entrenched in search engines (it is the one that was linked first and most often), and that ends up pointing people at the oldest documentation, which is almost always out of date. So instead we’re trying to follow the Python standard of the newest version as the canonical URL and including versioning as part of the text rather than as separate documents.

1 Like

I’m pretty sure this is a non-issue if you just have the non-versioned URL’s route to the latest stable documentation.

For example if I go to: https://docs.traefik.io/operations/cli/

It brings me to the documentation for the latest stable Traefik. The URLs without the versions in them are the URLs that you should use for all public links and such and the search engines will then point to the latest stable documentation, even as it is updated in new releases, automatically.

But if I want to go to a specific version of the documentation, then it has a URL with the version in it: https://docs.traefik.io/master/operations/cli/.

These URLs would rarely be linked to directly, and only if a user wanted to reference a specific version of the documentation. Because the default URL has no such version in it, though, anybody who just wants to copy a link to a doc page would just naturally copy the URL without the version in it, leading to happy SEO that always points to the latest docs even as users and developers copy links to the documentation.

2 Likes

In kubernetes charms, the start hook is the equivalent of install, and it runs before config-changed. I think this post should be updated to reflect that.

3 Likes

This is great post. The best I know on relations.

I’m curious on when the following keys are available:

egress-subnets: 172.31.25.105/32
ingress-address: 172.31.25.105

… in the relational hooks?

@camille.rodriguez1 perhaps knows?

Also, adding in “relation-created” here would be awesome…

@erik-lonroth has an awesome diagram showing the hook events:

https://github.com/erik78se/masterworker/blob/master/juju-hook-state-machine.png

Could this (or something similar) be incorporated in these docs? It is a very good visualization of the hooks.

@heitor me and @jamesbeedy has been requesting that we develop a visualization that accurately reflect the exakt state machine and its transitions which also contains information about what data is available to the units and relations in various states.

The image above I fear is not 100%, but rather something I’ve recreated with help från @Dmitrii and some own discoveries.

This a really fundamental flaw in the general teaching/learning material which I would love to get an accurate version of in the official docs.

This visualization helped me (and still does) alot when I was trying to learn, not only, relations with Juju.

This has also been discussed in other threads: Ubuntu OnAir - Community Office Hours - 1st July 2021

@jameinel @bianka @jnsgruk @pedroleaoc

3 Likes

That makes a lot of sense to have visualization, as if helps to explain certain concepts.

2 Likes

@tmihoc is working on consolidating this I believe… Look also here: Core lifecycle events

1 Like