grabana

package module
v0.22.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2023 License: MIT Imports: 14 Imported by: 12

README

Grabana

Go Report Card CI codecov GoDoc

Grabana provides a developer-friendly way of creating Grafana dashboards.

Whether you prefer writing code or YAML, if you are looking for a way to version your dashboards configuration or automate tedious and error-prone creation of dashboards, this library is meant for you.

Design goals

  • provide an understandable abstraction over dashboards configuration
  • expose a developer-friendly API
  • allow IDE assistance and auto-completion
  • generate Go code from existing dashboards

Note: Grafana 8+ is required, with unified alerting enabled.

Dashboard as code

Dashboard configuration:

builder := dashboard.New(
    "Awesome dashboard",
    dashboard.AutoRefresh("5s"),
    dashboard.Tags([]string{"generated"}),
    dashboard.VariableAsInterval(
        "interval",
        interval.Values([]string{"30s", "1m", "5m", "10m", "30m", "1h", "6h", "12h"}),
    ),
    dashboard.Row(
        "Prometheus",
        row.WithGraph(
            "HTTP Rate",
            graph.DataSource("prometheus-default"),
            graph.WithPrometheusTarget(
                "rate(prometheus_http_requests_total[30s])",
                prometheus.Legend("{{handler}} - {{ code }}"),
            ),
        ),
    ),
)

Note Existing dashboards can be converted to Go code using the grabana convert-go CLI command.

Dashboard creation:

ctx := context.Background()
client := grabana.NewClient(&http.Client{}, grafanaHost, grabana.WithAPIToken("such secret, much wow"))

// create the folder holding the dashboard for the service
folder, err := client.FindOrCreateFolder(ctx, "Test Folder")
if err != nil {
    fmt.Printf("Could not find or create folder: %s\n", err)
    os.Exit(1)
}

if _, err := client.UpsertDashboard(ctx, folder, builder); err != nil {
    fmt.Printf("Could not create dashboard: %s\n", err)
    os.Exit(1)
}

For a more complete example, see the example directory.

Dashboard as YAML

Dashboard configuration:

# dashboard.yaml
title: Awesome dashboard

editable: true
tags: [generated]
auto_refresh: 5s

variables:
  - interval:
      name: interval
      label: Interval
      values: ["30s", "1m", "5m", "10m", "30m", "1h", "6h", "12h"]

rows:
  - name: Prometheus
    panels:
      - graph:
          title: HTTP Rate
          height: 400px
          datasource: prometheus-default
          targets:
            - prometheus:
                query: "rate(promhttp_metric_handler_requests_total[$interval])"
                legend: "{{handler}} - {{ code }}"

Dashboard creation (or automatically as a Kubernetes Resource, using DARK):

content, err := os.ReadFile("dashboard.yaml")
if err != nil {
    fmt.Fprintf(os.Stderr, "Could not read file: %s\n", err)
    os.Exit(1)
}

dashboard, err := decoder.UnmarshalYAML(bytes.NewBuffer(content))
if err != nil {
    fmt.Fprintf(os.Stderr, "Could not parse file: %s\n", err)
    os.Exit(1)
}

ctx := context.Background()
client := grabana.NewClient(&http.Client{}, grafanaHost, grabana.WithAPIToken("such secret, much wow"))

// create the folder holding the dashboard for the service
folder, err := client.FindOrCreateFolder(ctx, "Test Folder")
if err != nil {
    fmt.Printf("Could not find or create folder: %s\n", err)
    os.Exit(1)
}

if _, err := client.UpsertDashboard(ctx, folder, dashboard); err != nil {
    fmt.Printf("Could not create dashboard: %s\n", err)
    os.Exit(1)
}

Going further

Check out the documentation to discover what Grabana can do for you.

License

This library is under the MIT license.

Documentation

Overview

Package grabana provides a developer-friendly way of creating Grafana dashboards.

Whether you prefer writing **code or YAML**, if you are looking for a way to version your dashboards configuration or automate tedious and error-prone creation of dashboards, this library is meant for you.

builder := dashboard.New(
	"Awesome dashboard",
	dashboard.VariableAsInterval(
		"interval",
		interval.Values([]string{"30s", "1m", "5m", "10m", "30m", "1h", "6h", "12h"}),
	),
	dashboard.VariableAsQuery(
		"status",
		query.DataSource("prometheus-default"),
		query.Request("label_values(prometheus_http_requests_total, code)"),
		query.Sort(query.NumericalAsc),
	),
	dashboard.Row(
		"Prometheus",
		row.WithTimeSeries(
			"HTTP Rate",
			timeseries.WithPrometheusTarget(
				"rate(promhttp_metric_handler_requests_total[$interval])",
				prometheus.Legend("{{handler}} - {{ code }}"),
			),
		),
		row.WithTable(
			"Threads",
			table.WithPrometheusTarget("go_threads"),
			table.HideColumn("Time"),
			table.AsTimeSeriesAggregations([]table.Aggregation{
				{Label: "AVG", Type: table.AVG},
				{Label: "Current", Type: table.Current},
			}),
		),
		row.WithStat(
			"Heap Allocations",
			stat.Unit("bytes"),
			stat.WithPrometheusTarget("go_memstats_heap_alloc_bytes"),
		),
	),
	dashboard.Row(
		"Some text, because it might be useful",
		row.WithText(
			"Some awesome html?",
			text.HTML("<b>lalalala</b>"),
		),
	),
)

For a more information visit https://github.com/K-Phoen/grabana

Index

Constants

This section is empty.

Variables

View Source
var ErrAPIKeyNotFound = errors.New("API key not found")

ErrAPIKeyNotFound is returned when the given API key can not be found.

View Source
var ErrAlertNotFound = errors.New("alert not found")

ErrAlertNotFound is returned when the requested alert can not be found.

View Source
var ErrDashboardNotFound = errors.New("dashboard not found")

ErrDashboardNotFound is returned when the given dashboard can not be found.

View Source
var ErrDatasourceNotFound = errors.New("datasource not found")

ErrDatasourceNotFound is returned when the given datasource can not be found.

View Source
var ErrFolderNotFound = errors.New("folder not found")

ErrFolderNotFound is returned when the given folder can not be found.

Functions

This section is empty.

Types

type APIKey added in v0.20.10

type APIKey struct {
	ID   uint   `json:"id"`
	Name string `json:"name"`
}

APIKey represents an API key.

type APIKeyRole added in v0.20.10

type APIKeyRole uint8

APIKeyRole represents a role given to an API key.

const (
	AdminRole APIKeyRole = iota
	EditorRole
	ViewerRole
)

func (APIKeyRole) MarshalJSON added in v0.20.10

func (role APIKeyRole) MarshalJSON() ([]byte, error)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a Grafana HTTP client.

func NewClient

func NewClient(http *http.Client, host string, options ...Option) *Client

NewClient creates a new Grafana HTTP client, using an API token.

func (*Client) APIKeys added in v0.20.10

func (client *Client) APIKeys(ctx context.Context) (map[string]APIKey, error)

APIKeys lists active API keys.

func (*Client) AddAlert added in v0.21.0

func (client *Client) AddAlert(ctx context.Context, namespace string, alertDefinition alert.Alert, datasourcesMap map[string]string) error

AddAlert creates an alert group within a given namespace.

func (*Client) ConfigureAlertManager added in v0.20.11

func (client *Client) ConfigureAlertManager(ctx context.Context, manager *alertmanager.Manager) error

ConfigureAlertManager updates the alert manager configuration.

func (*Client) CreateAPIKey added in v0.20.10

func (client *Client) CreateAPIKey(ctx context.Context, request CreateAPIKeyRequest) (string, error)

CreateAPIKey creates a new API key.

func (*Client) CreateFolder

func (client *Client) CreateFolder(ctx context.Context, name string) (*Folder, error)

CreateFolder creates a dashboard folder. See https://grafana.com/docs/grafana/latest/reference/dashboard_folders/

func (*Client) DeleteAPIKeyByName added in v0.20.10

func (client *Client) DeleteAPIKeyByName(ctx context.Context, name string) error

DeleteAPIKeyByName deletes an API key given its name.

func (*Client) DeleteAlertGroup added in v0.21.0

func (client *Client) DeleteAlertGroup(ctx context.Context, namespace string, groupName string) error

DeleteAlertGroup deletes an alert group.

func (*Client) DeleteDashboard added in v0.5.2

func (client *Client) DeleteDashboard(ctx context.Context, uid string) error

DeleteDashboard deletes a dashboard given its UID.

func (*Client) DeleteDatasource added in v0.20.0

func (client *Client) DeleteDatasource(ctx context.Context, name string) error

DeleteDatasource deletes a datasource given its name.

func (*Client) FindOrCreateFolder added in v0.5.3

func (client *Client) FindOrCreateFolder(ctx context.Context, name string) (*Folder, error)

FindOrCreateFolder returns the folder by its name or creates it if it doesn't exist.

func (*Client) GetDashboardByTitle added in v0.20.12

func (client *Client) GetDashboardByTitle(ctx context.Context, title string) (*Dashboard, error)

GetDashboardByTitle finds a dashboard, given its title.

func (*Client) GetDatasourceUIDByName added in v0.20.5

func (client *Client) GetDatasourceUIDByName(ctx context.Context, name string) (string, error)

GetDatasourceUIDByName finds a datasource UID given its name.

func (*Client) GetFolderByTitle

func (client *Client) GetFolderByTitle(ctx context.Context, title string) (*Folder, error)

GetFolderByTitle finds a folder, given its title.

func (*Client) UpsertDashboard

func (client *Client) UpsertDashboard(ctx context.Context, folder *Folder, builder dashboard.Builder) (*Dashboard, error)

UpsertDashboard creates or replaces a dashboard, in the given folder.

func (*Client) UpsertDatasource added in v0.20.0

func (client *Client) UpsertDatasource(ctx context.Context, datasource datasource.Datasource) error

UpsertDatasource creates or replaces a datasource.

type CreateAPIKeyRequest added in v0.20.10

type CreateAPIKeyRequest struct {
	Name          string     `json:"name"`
	Role          APIKeyRole `json:"role"`
	SecondsToLive int        `json:"secondsToLive"`
}

CreateAPIKeyRequest represents a request made to the API key creation endpoint.

type Dashboard

type Dashboard struct {
	ID          int      `json:"id"`
	UID         string   `json:"uid"`
	Title       string   `json:"title"`
	URL         string   `json:"url"`
	Tags        []string `json:"tags"`
	IsStarred   bool     `json:"isStarred"`
	FolderID    int      `json:"folderId"`
	FolderUID   string   `json:"folderUid"`
	FolderTitle string   `json:"folderTitle"`
	FolderURL   string   `json:"folderUrl"`
}

Dashboard represents a Grafana dashboard.

type Folder

type Folder struct {
	ID    uint   `json:"id"`
	UID   string `json:"uid"`
	Title string `json:"title"`
}

Folder represents a dashboard folder. See https://grafana.com/docs/grafana/latest/reference/dashboard_folders/

type Option added in v0.8.0

type Option func(client *Client)

Option represents an option that can be used to configure a client.

func WithAPIToken added in v0.8.0

func WithAPIToken(token string) Option

WithAPIToken sets up the client to use the given token to authenticate.

func WithBasicAuth added in v0.8.0

func WithBasicAuth(username string, password string) Option

WithBasicAuth sets up the client to use the given credentials to authenticate.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL