Grafana

  • By Canonical Observability
Channel Revision Published Runs on
latest/stable 114 28 Jun 2024
Ubuntu 20.04
latest/candidate 117 28 Jun 2024
Ubuntu 20.04
latest/beta 117 21 Jun 2024
Ubuntu 20.04
latest/edge 117 18 Jun 2024
Ubuntu 20.04
1.0/stable 93 12 Dec 2023
Ubuntu 20.04
1.0/candidate 93 22 Nov 2023
Ubuntu 20.04
1.0/beta 93 22 Nov 2023
Ubuntu 20.04
1.0/edge 93 22 Nov 2023
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 )

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. 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. 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. 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. 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:cos-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. remove_dashboards( self , event: RelationBrokenEvent )

Description

Remove a dashboard if the relation is broken. None

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