grabana

package module
Version: v0.17.2 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2021 License: MIT Imports: 12 Imported by: 4

README

Grabana

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

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 }}"),
            ),
        ),
    ),
)

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 := ioutil.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.WithGraph(
			"HTTP Rate",
			graph.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.WithSingleStat(
			"Heap Allocations",
			singlestat.Unit("bytes"),
			singlestat.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 ErrAlertChannelNotFound = errors.New("alert channel not found")

ErrAlertChannelNotFound is returned when the given alert notification channel 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 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) 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) 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) 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) GetAlertChannelByName

func (client *Client) GetAlertChannelByName(ctx context.Context, name string) (*alert.Channel, error)

GetAlertChannelByName finds an alert notification channel, 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.

type Dashboard

type Dashboard struct {
	ID  uint   `json:"id"`
	UID string `json:"uid"`
	URL string `json:"url"`
}

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.

Source Files

Jump to

Keyboard shortcuts

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