Grafana

  • By Jose C. Massón
Channel Version Revision Published Runs on
latest/stable 52 52 21 Oct 2022
Ubuntu 20.04
latest/candidate 52 52 21 Oct 2022
Ubuntu 20.04
latest/beta 52 52 21 Oct 2022
Ubuntu 20.04
latest/edge 54 54 24 Nov 2022
Ubuntu 20.04
1.0/stable 52 52 21 Oct 2022
Ubuntu 20.04
1.0/candidate 52 52 21 Oct 2022
Ubuntu 20.04
1.0/beta 52 52 21 Oct 2022
Ubuntu 20.04
1.0/edge 52 52 21 Oct 2022
Ubuntu 20.04
juju deploy grafana-k8s
Show information

Platform:

charms.grafana_k8s.v0.grafana_dashboard

Overview.

This document explains how to integrate with the Grafana charm for the purpose of providing a dashboard which can be used by end users. It also explains the structure of the data expected by the grafana-dashboard interface, and may provide a mechanism or reference point for providing a compatible interface or library by providing a definitive reference guide to the structure of relation data which is shared between the Grafana charm and any charm providing datasource information.

Provider Library Usage

The Grafana charm interacts with its dashboards using its charm library. The goal of this library is to be as simple to use as possible, and instantiation of the class with or without changing the default arguments provides a complete use case. For the simplest use case of a charm which bundles dashboards and provides a provides: grafana-dashboard interface,

requires:
  grafana-dashboard:
    interface: grafana_dashboard

creation of a GrafanaDashboardProvider object with the default arguments is sufficient.

:class:GrafanaDashboardProvider expects that bundled dashboards should be included in your charm with a default path of:

path/to/charm.py
path/to/src/grafana_dashboards/*.{json|json.tmpl|.tmpl}

Where the files are Grafana dashboard JSON data either from the Grafana marketplace, or directly exported from a Grafana instance. Refer to the official docs for more information.

When constructing a dashboard that is intended to be consumed by COS, make sure to use variables for your datasources, and name them "prometheusds" and "lokids". You can also use the following juju topology variables in your dashboards: $juju_model, $juju_model_uuid, $juju_application and $juju_unit. Note, however, that if metrics are coming via peripheral charms (scrape-config or cos-config) then topology labels would not exist.

The default constructor arguments are:

`charm`: `self` from the charm instantiating this library
`relation_name`: grafana-dashboard
`dashboards_path`: "/src/grafana_dashboards"

If your configuration requires any changes from these defaults, they may be set from the class constructor. It may be instantiated as follows:

from charms.grafana_k8s.v0.grafana_dashboard import GrafanaDashboardProvider

class FooCharm:
    def __init__(self, *args):
        super().__init__(*args, **kwargs)
        ...
        self.grafana_dashboard_provider = GrafanaDashboardProvider(self)
        ...

The first argument (self) should be a reference to the parent (providing dashboards), as this charm's lifecycle events will be used to re-submit dashboard information if a charm is upgraded, the pod is restarted, or other.

An instantiated GrafanaDashboardProvider validates that the path specified in the constructor (or the default) exists, reads the file contents, then compresses them with LZMA and adds them to the application relation data when a relation is established with Grafana.

Provided dashboards will be checked by Grafana, and a series of dropdown menus providing the ability to select query targets by Juju Model, application instance, and unit will be added if they do not exist.

To avoid requiring jinja in GrafanaDashboardProvider users, template validation and rendering occurs on the other side of the relation, and relation data in the form of:

{
    "event": {
        "valid": `true|false`,
        "errors": [],
    }
}

Will be returned if rendering or validation fails. In this case, the GrafanaDashboardProvider object will emit a dashboard_status_changed event of the type :class:GrafanaDashboardEvent, which will contain information about the validation error.

This information is added to the relation data for the charms as serialized JSON from a dict, with a structure of:

{
    "application": {
        "dashboards": {
            "uuid": a uuid generated to ensure a relation event triggers,
            "templates": {
                "file:{hash}": {
                    "content": `{compressed_template_data}`,
                    "charm": `charm.meta.name`,
                    "juju_topology": {
                        "model": `charm.model.name`,
                        "model_uuid": `charm.model.uuid`,
                        "application": `charm.app.name`,
                        "unit": `charm.unit.name`,
                    }
                },
                "file:{other_file_hash}": {
                    ...
                },
            },
        },
    },
}

This is ingested by :class:GrafanaDashboardConsumer, and is sufficient for configuration.

The COS Configuration Charm can be used to add dashboards which are not bundled with charms.

Consumer Library Usage

The GrafanaDashboardConsumer object may be used by Grafana charms to manage relations with available dashboards. For this purpose, a charm consuming Grafana dashboard information should do the following things:

  1. Instantiate the GrafanaDashboardConsumer object by providing it a

reference to the parent (Grafana) charm and, optionally, the name of the relation that the Grafana charm uses to interact with dashboards. This relation must confirm to the grafana-dashboard interface.

For example a Grafana charm may instantiate the GrafanaDashboardConsumer in its constructor as follows

from charms.grafana_k8s.v0.grafana_dashboard import GrafanaDashboardConsumer

def __init__(self, *args):
    super().__init__(*args)
    ...
    self.grafana_dashboard_consumer = GrafanaDashboardConsumer(self)
    ...

  1. A Grafana charm also needs to listen to the

GrafanaDashboardConsumer events emitted by the GrafanaDashboardConsumer by adding itself as an observer for these events:

self.framework.observe(
    self.grafana_source_consumer.on.sources_changed,
    self._on_dashboards_changed,
)

Dashboards can be retrieved the :meth:dashboards:

It will be returned in the format of:

[
    {
        "id": unique_id,
        "relation_id": relation_id,
        "charm": the name of the charm which provided the dashboard,
        "content": compressed_template_data
    },
]

The consuming charm should decompress the dashboard.


Index

class RelationNotFoundError

Description

Raised if there is no relation with the given name. None

Methods

RelationNotFoundError. __init__( self , relation_name: str )

class RelationInterfaceMismatchError

Description

Raised if the relation with the given name has a different interface. None

Methods

RelationInterfaceMismatchError. __init__( self , relation_name: str , expected_relation_interface: str , actual_relation_interface: str )

class RelationRoleMismatchError

Description

Raised if the relation with the given name has a different direction. None

Methods

RelationRoleMismatchError. __init__( self , relation_name: str , expected_relation_role: RelationRole , actual_relation_role: RelationRole )

class InvalidDirectoryPathError

Description

Raised if the grafana dashboards folder cannot be found or is otherwise invalid. None

Methods

InvalidDirectoryPathError. __init__( self , grafana_dashboards_absolute_path: str , message: str )

def _resolve_dir_against_charm_path(charm: CharmBase)

Resolve the provided path items against the directory of the main file.

Description

Look up the directory of the charmed operator file being executed. This is normally going to be the charm.py file of the charm including this library. Then, resolve the provided path elements and return its absolute path. Raises: InvalidDirectoryPathError if the resolved path does not exist or it is not a directory

def _validate_relation_by_interface_and_direction(
    charm: CharmBase,
    relation_name: str,
    expected_relation_interface: str,
    expected_relation_role: RelationRole
)

Verifies that a relation has the necessary characteristics.

Arguments

charm
a `CharmBase` object to scan for the matching relation.
relation_name
the name of the relation to be verified.
expected_relation_interface
the interface name to be matched by the relation named `relation_name`.
expected_relation_role
whether the `relation_name` must be either provided or required by `charm`.

Description

Verifies that the `relation_name` provided: (1) exists in metadata.yaml, (2) declares as interface the interface name passed as `relation_interface` and (3) has the right "direction", i.e., it is a relation that `charm` provides or requires.

def _encode_dashboard_content(content)

def _decode_dashboard_content(encoded_content: str)

def _convert_dashboard_fields(
    content: str,
    inject_dropdowns: bool
)

Make sure values are present for Juju topology.

Description

Inserts Juju topology variables and selectors into the template, as well as a variable for Prometheus.

def _replace_template_fields(
    dict_content: dict,
    datasources: dict,
    existing_templates: bool
)

Make templated fields get cleaned up afterwards.

Description

If existing datasource variables are present, try to substitute them.

def _inject_labels(
    content: str,
    topology: dict,
    transformer
)

Inject Juju topology into panel expressions via CosTool.

Arguments

content
dashboard content as a string
topology
a dict containing topology values
transformer
a 'CosTool' instance

Returns

dashboard content with replaced values.

Description

A dashboard will have a structure approximating: { "__inputs": [], "templating": { "list": [ { "name": "prometheusds", "type": "prometheus" } ] }, "panels": [ { "foo": "bar", "targets": [ { "some": "field", "expr": "up{job="foo"}" }, { "some_other": "field", "expr": "sum(http_requests_total{instance="$foo"}[5m])} } ], "datasource": "${someds}" } ] } `templating` is used elsewhere in this library, but the structure is not rigid. It is not guaranteed that a panel will actually have any targets (it could be a "spacer" with no datasource, hence no expression). It could have only one target. It could have multiple targets. It could have multiple targets of which only one has an `expr` to evaluate. We need to try to handle all of these concisely. `cos-tool` (`github.com/canonical/cos-tool` as a Go module in general) does not know "Grafana-isms", such as using `[$_variable]` to modify the query from the user interface, so we add placeholders (as `5y`, since it must parse, but a dashboard looking for five years for a panel query would be unusual).

def _modify_panel(
    panel: dict,
    topology: dict,
    transformer
)

Inject Juju topology into panel expressions via CosTool.

Arguments

panel
a dashboard panel as a dict
topology
a dict containing topology values
transformer
a 'CosTool' instance

Returns

the panel with injected values

def _type_convert_stored(obj)

Description

Convert Stored* to their appropriate types, recursively. None

class GrafanaDashboardsChanged

Description

Event emitted when Grafana dashboards change. None

Methods

GrafanaDashboardsChanged. __init__( self , handle , data )

GrafanaDashboardsChanged. snapshot( self )

Description

Save grafana source information. None

GrafanaDashboardsChanged. restore( self , snapshot )

Description

Restore grafana source information. None

class GrafanaDashboardEvents

Description

Events raised by :class:`GrafanaSourceEvents`. None

class GrafanaDashboardEvent

Event emitted when Grafana dashboards cannot be resolved.

Description

Enables us to set a clear status on the provider.

Methods

GrafanaDashboardEvent. __init__( self , handle , errors , valid: bool )

GrafanaDashboardEvent. snapshot( self )

Description

Save grafana source information. None

GrafanaDashboardEvent. restore( self , snapshot )

Description

Restore grafana source information. None

class GrafanaProviderEvents

Description

Events raised by :class:`GrafanaSourceEvents`. None

class GrafanaDashboardProvider

Description

An API to provide Grafana dashboards to a Grafana charm. None

Methods

GrafanaDashboardProvider. __init__( self , charm: CharmBase , relation_name: str , dashboards_path: str )

API to provide Grafana dashboard to a Grafana charmed operator.

Arguments

charm
a :class:`CharmBase` object which manages this :class:`GrafanaProvider` object. Generally this is `self` in the instantiating class.
relation_name
a :string: name of the relation managed by this :class:`GrafanaDashboardProvider`; it defaults to "grafana-dashboard".
dashboards_path
a filesystem path relative to the charm root where dashboard templates can be located. By default, the library expects dashboard files to be in the `<charm-py-directory>/grafana_dashboards` directory.

Description

The :class:`GrafanaDashboardProvider` object provides an API to upload dashboards to a Grafana charm. In its most streamlined usage, the :class:`GrafanaDashboardProvider` is integrated in a charmed operator as follows: self.grafana = GrafanaDashboardProvider(self) The :class:`GrafanaDashboardProvider` will look for dashboard templates in the `<charm-py-directory>/grafana_dashboards` folder. Additionally, dashboard templates can be uploaded programmatically via the :method:`GrafanaDashboardProvider.add_dashboard` method. To use the :class:`GrafanaDashboardProvider` API, you need a relation defined in your charm operator's metadata.yaml as follows: provides: grafana-dashboard: interface: grafana_dashboard If you would like to use relation name other than `grafana-dashboard`, you will need to specify the relation name via the `relation_name` argument when instantiating the :class:`GrafanaDashboardProvider` object. However, it is strongly advised to keep the default relation name, so that people deploying your charm will have a consistent experience with all other charms that provide Grafana dashboards. It is possible to provide a different file path for the Grafana dashboards to be automatically managed by the :class:`GrafanaDashboardProvider` object via the `dashboards_path` argument. This may be necessary when the directory structure of your charmed operator repository is not the "usual" one as generated by `charmcraft init`, for example when adding the charmed operator in a Java repository managed by Maven or Gradle. However, unless there are such constraints with other tooling, it is strongly advised to store the Grafana dashboards in the default `<charm-py-directory>/grafana_dashboards` folder, in order to provide a consistent experience for other charmed operator authors.

GrafanaDashboardProvider. add_dashboard( self , content: str , inject_dropdowns: bool )

Add a dashboard to the relation managed by this :class:`GrafanaDashboardProvider`.

Arguments

content
a string representing a Jinja template. Currently, no global variables are added to the Jinja template evaluation context.
inject_dropdowns
a :boolean: indicating whether topology dropdowns should be added to the dashboard

GrafanaDashboardProvider. remove_non_builtin_dashboards( self )

Description

Remove all dashboards to the relation added via :method:`add_dashboard`. None

GrafanaDashboardProvider. update_dashboards( self )

Description

Trigger the re-evaluation of the data on all relations. None

GrafanaDashboardProvider. _update_all_dashboards_from_dir( self , _ , inject_dropdowns: bool )

Description

Scans the built-in dashboards and updates relations with changes. None

GrafanaDashboardProvider. _generate_alt_uid( self , key: str )

Generate alternative uid for dashboards.

Arguments

key
A string used (along with charm.meta.name) to build the hash uid.

GrafanaDashboardProvider. _reinitialize_dashboard_data( self , inject_dropdowns: bool )

Triggers a reload of dashboard outside of an eventing workflow.

Arguments

inject_dropdowns
a :bool: used to indicate whether topology dropdowns should be added

GrafanaDashboardProvider. _on_grafana_dashboard_relation_created( self , event: RelationCreatedEvent )

Watch for a relation being created and automatically send dashboards.

Arguments

event
The :class:`RelationJoinedEvent` sent when a `grafana_dashboaard` relationship is joined

GrafanaDashboardProvider. _on_grafana_dashboard_relation_changed( self , event: RelationChangedEvent )

Watch for changes so we know if there's an error to signal back to the parent charm.

Arguments

event
The `RelationChangedEvent` that triggered this handler.

GrafanaDashboardProvider. _upset_dashboards_on_relation( self , relation: Relation )

Description

Update the dashboards in the relation data bucket. None

GrafanaDashboardProvider. _content_to_dashboard_object( self , content: str , inject_dropdowns: bool )

GrafanaDashboardProvider. _juju_topology( self )

GrafanaDashboardProvider. dashboard_templates( self )

Description

Return a list of the known dashboard templates. None

class GrafanaDashboardConsumer

Description

A consumer object for working with Grafana Dashboards. None

Methods

GrafanaDashboardConsumer. __init__( self , charm: CharmBase , relation_name: str )

API to receive Grafana dashboards from charmed operators.

Description

The :class:`GrafanaDashboardConsumer` object provides an API to consume dashboards provided by a charmed operator using the

GrafanaDashboardConsumer. get_dashboards_from_relation( self , relation_id: int )

Get a list of known dashboards for one instance of the monitored relation.

Arguments

relation_id
the identifier of the relation instance, as returned by :method:`ops.model.Relation.id`.

GrafanaDashboardConsumer. _on_grafana_dashboard_relation_changed( self , event: RelationChangedEvent )

Handle relation changes in related providers.

Description

If there are changes in relations between Grafana dashboard consumers and providers, this event handler (if the unit is the leader) will get data for an incoming grafana-dashboard relation through a

GrafanaDashboardConsumer. _on_grafana_peer_changed( self , _: RelationChangedEvent )

Description

Emit dashboard events on peer events so secondary charm data updates. None

GrafanaDashboardConsumer. update_dashboards( self , relation )

Re-establish dashboards on one or more relations.

Arguments

relation
a specific relation for which the dashboards have to be updated. If not specified, all relations managed by this :class:`GrafanaDashboardConsumer` will be updated.

Description

If something changes between this library and a datasource, try to re-establish invalid dashboards and invalidate active ones.

GrafanaDashboardConsumer. _on_grafana_dashboard_relation_broken( self , event: RelationBrokenEvent )

Update job config when providers depart.

Description

When a Grafana dashboard provider departs, the configuration for that provider is removed from the list of dashboards

GrafanaDashboardConsumer. _render_dashboards_and_signal_changed( self , relation: Relation )

Validate a given dashboard.

Arguments

relation
Relation; The relation the dashboard is associated with.

Returns

a boolean indicating whether an event should be emitted

Description

Verify that the passed dashboard data is able to be found in our list of datasources and will render. If they do, let the charm know by emitting an event.

GrafanaDashboardConsumer. _manage_dashboard_uid( self , dashboard: str , template: dict )

Description

Add an uid to the dashboard if it is not present. None

GrafanaDashboardConsumer. _remove_all_dashboards_for_relation( self , relation: Relation )

Description

If an errored dashboard is in stored data, remove it and trigger a deletion. None

GrafanaDashboardConsumer. _to_external_object( self , relation_id , dashboard )

GrafanaDashboardConsumer. dashboards( self )

Get a list of known dashboards across all instances of the monitored relation.

Description

Returns: a list of known dashboards. The JSON of each of the dashboards is available in the `content` field of the corresponding `dict`.

GrafanaDashboardConsumer. _get_stored_dashboards( self , relation_id: int )

Description

Pull stored dashboards out of the peer data bucket. None

GrafanaDashboardConsumer. _set_default_data( self )

Description

Set defaults if they are not in peer relation data. None

GrafanaDashboardConsumer. set_peer_data( self , key: str , data: Any )

Description

Put information into the peer data bucket instead of `StoredState`. None

GrafanaDashboardConsumer. get_peer_data( self , key: str )

Description

Retrieve information from the peer data bucket instead of `StoredState`. None

class GrafanaDashboardAggregator

API to retrieve Grafana dashboards from machine dashboards.

Arguments

charm
a :class:`CharmBase` object which manages this :class:`GrafanaProvider` object. Generally this is `self` in the instantiating class.
target_relation
a :string: name of a relation managed by this :class:`GrafanaDashboardAggregator`, which is used to communicate with reactive/machine charms it defaults to "dashboards".
grafana_relation
a :string: name of a relation used by this :class:`GrafanaDashboardAggregator`, which is used to communicate with charmed grafana. It defaults to "downstream-grafana-dashboard"

Description

The :class:`GrafanaDashboardAggregator` object provides a way to collate and aggregate Grafana dashboards from reactive/machine charms and transport them into Charmed Operators, using Juju topology. For detailed usage instructions, see the documentation for :module:`lma-proxy-operator`, as this class is intended for use as a single point of intersection rather than use in individual charms. Since :class:`GrafanaDashboardAggregator` serves as a bridge between Canonical Observability Stack Charmed Operators and Reactive Charms, deployed in a Reactive Juju model, both a target relation which is used to collect events from Reactive charms and a `grafana_relation` which is used to send the collected data back to the Canonical Observability Stack are required. In its most streamlined usage, :class:`GrafanaDashboardAggregator` is integrated in a charmed operator as follows: self.grafana = GrafanaDashboardAggregator(self)

Methods

GrafanaDashboardAggregator. __init__( self , charm: CharmBase , target_relation: str , grafana_relation: str )

GrafanaDashboardAggregator. update_dashboards( self , event: RelationEvent )

Description

If we get a dashboard from a reactive charm, parse it out and update. None

GrafanaDashboardAggregator. _upset_dashboards_on_event( self , event: RelationEvent )

Description

Update the dashboards in the relation data bucket. None

GrafanaDashboardAggregator. _update_remote_grafana( self , _ )

Description

Push dashboards to the downstream Grafana relation. None

GrafanaDashboardAggregator. remove_dashboards( self , event: RelationBrokenEvent )

Description

Remove a dashboard if the relation is broken. None

GrafanaDashboardAggregator. _strip_existing_datasources( self , template: dict )

Remove existing reactive charm datasource templating out.

Description

This method iterates through *known* places where reactive charms may set data in contributed dashboards and removes them. `dashboard["__inputs"]` is a property sometimes set when exporting dashboards from the Grafana UI. It is not present in earlier Grafana versions, and can be disabled in 5.3.4 and above (optionally). If set, any values present will be substituted on import. Some reactive charms use this for Prometheus. LMA2 uses dropdown selectors for datasources, and leaving this present results in "default" datasource values which are broken. Similarly, `dashboard["templating"]["list"][N]["name"] == "host"` can be used to set a `host` variable for use in dashboards which is not meaningful in the context of Juju topology and will yield broken dashboards. Further properties may be discovered.

GrafanaDashboardAggregator. _handle_reactive_dashboards( self , event: RelationEvent )

Description

Look for a dashboard in relation data (during a reactive hook) or builtin by name. None

GrafanaDashboardAggregator. _maybe_get_builtin_dashboards( self , event: RelationEvent )

Tries to match the event with an included dashboard.

Description

Scans dashboards packed with the charm instantiating this class, and tries to match one with the event. There is no guarantee that any given event will match a builtin, since each charm instantiating this class may include a different set of dashboards, or none.

GrafanaDashboardAggregator. _content_to_dashboard_object( self , content: str , event: RelationEvent )

GrafanaDashboardAggregator. _juju_topology( self , event: RelationEvent )

class CosTool

Description

Uses cos-tool to inject label matchers into alert rule expressions and validate rules. None

Methods

CosTool. __init__( self , charm )

CosTool. path( self )

Description

Lazy lookup of the path of cos-tool. None

CosTool. apply_label_matchers( self , rules: dict , type: str )

Description

Will apply label matchers to the expression of all alerts in all supplied groups. None

CosTool. validate_alert_rules( self , rules: dict )

Description

Will validate correctness of alert rules, returning a boolean and any errors. None

CosTool. inject_label_matchers( self , expression: str , topology: dict , type: str )

Description

Add label matchers to an expression. None

CosTool. _get_tool_path( self )

CosTool. _exec( self , cmd )