Skip to content

Commit

Permalink
Merge pull request #44 from K-Phoen/yaml-unmarshall
Browse files Browse the repository at this point in the history
Yaml unmarshall
  • Loading branch information
K-Phoen authored Mar 22, 2020
2 parents 9102e1f + 5572be2 commit 5f86535
Show file tree
Hide file tree
Showing 31 changed files with 1,681 additions and 361 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ for you.
Dashboard configuration:

```go
dashboard := grabana.NewDashboardBuilder(
builder := dashboard.New(
"Awesome dashboard",
grabana.AutoRefresh("5s"),
grabana.Tags([]string{"generated"}),
Expand All @@ -45,7 +45,7 @@ Dashboard creation:

```go
ctx := context.Background()
client := grabana.NewClient(&http.Client{}, os.Args[1], os.Args[2])
client := grabana.NewClient(&http.Client{}, grafanaHost, grafanaAPIToken)

// create the folder holding the dashboard for the service
folder, err := client.GetFolderByTitle(ctx, "Test Folder")
Expand All @@ -63,7 +63,7 @@ if folder == nil {
fmt.Printf("Folder created (id: %d, uid: %s)\n", folder.ID, folder.UID)
}

if _, err := client.UpsertDashboard(ctx, folder, dashboard); err != nil {
if _, err := client.UpsertDashboard(ctx, folder, builder); err != nil {
fmt.Printf("Could not create dashboard: %s\n", err)
os.Exit(1)
}
Expand Down
12 changes: 6 additions & 6 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"strings"

"github.com/K-Phoen/grabana/alert"

"github.com/K-Phoen/grabana/dashboard"
"github.com/grafana-tools/sdk"
)

Expand Down Expand Up @@ -155,13 +155,13 @@ func (client *Client) GetAlertChannelByName(ctx context.Context, name string) (*
}

// UpsertDashboard creates or replaces a dashboard, in the given folder.
func (client *Client) UpsertDashboard(ctx context.Context, folder *Folder, builder DashboardBuilder) (*Dashboard, error) {
func (client *Client) UpsertDashboard(ctx context.Context, folder *Folder, builder dashboard.Builder) (*Dashboard, error) {
buf, err := json.Marshal(struct {
Dashboard *sdk.Board `json:"dashboard"`
FolderID uint `json:"folderId"`
Overwrite bool `json:"overwrite"`
}{
Dashboard: builder.board,
Dashboard: builder.Internal(),
FolderID: folder.ID,
Overwrite: true,
})
Expand All @@ -185,12 +185,12 @@ func (client *Client) UpsertDashboard(ctx context.Context, folder *Folder, build
return nil, fmt.Errorf("could not create dashboard: %s", body)
}

var dashboard Dashboard
if err := decodeJSON(resp.Body, &dashboard); err != nil {
var model Dashboard
if err := decodeJSON(resp.Body, &model); err != nil {
return nil, err
}

return &dashboard, nil
return &model, nil
}

func (client Client) postJSON(ctx context.Context, path string, body []byte) (*http.Response, error) {
Expand Down
5 changes: 3 additions & 2 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"
"testing"

builder "github.com/K-Phoen/grabana/dashboard"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -208,7 +209,7 @@ func TestGetAlertChannelByNameCanFail(t *testing.T) {

func TestDashboardsCanBeCreated(t *testing.T) {
req := require.New(t)
dashboard := NewDashboardBuilder("Dashboard name")
dashboard := builder.New("Dashboard name")
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `{
"id": 1,
Expand All @@ -231,7 +232,7 @@ func TestDashboardsCanBeCreated(t *testing.T) {

func TestDashboardsCreationCanFail(t *testing.T) {
req := require.New(t)
dashboard := NewDashboardBuilder("Dashboard name")
dashboard := builder.New("Dashboard name")
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, `{
Expand Down
25 changes: 13 additions & 12 deletions cmd/example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/K-Phoen/grabana"
"github.com/K-Phoen/grabana/alert"
"github.com/K-Phoen/grabana/axis"
"github.com/K-Phoen/grabana/dashboard"
"github.com/K-Phoen/grabana/graph"
"github.com/K-Phoen/grabana/row"
"github.com/K-Phoen/grabana/singlestat"
Expand Down Expand Up @@ -52,27 +53,27 @@ func main() {
os.Exit(1)
}

dashboard := grabana.NewDashboardBuilder(
builder := dashboard.New(
"Awesome dashboard",
grabana.AutoRefresh("5s"),
grabana.Tags([]string{"generated"}),
grabana.TagsAnnotation(grabana.TagAnnotation{
dashboard.AutoRefresh("5s"),
dashboard.Tags([]string{"generated"}),
dashboard.TagsAnnotation(dashboard.TagAnnotation{
Name: "Deployments",
Datasource: "-- Grafana --",
IconColor: "#5794F2",
Tags: []string{"deploy", "production"},
}),
grabana.VariableAsInterval(
dashboard.VariableAsInterval(
"interval",
interval.Values([]string{"30s", "1m", "5m", "10m", "30m", "1h", "6h", "12h"}),
),
grabana.VariableAsQuery(
dashboard.VariableAsQuery(
"status",
query.DataSource("prometheus-default"),
query.Request("label_values(prometheus_http_requests_total, code)"),
query.Sort(query.NumericalAsc),
),
grabana.VariableAsConst(
dashboard.VariableAsConst(
"percentile",
constant.Label("Percentile"),
constant.Values(map[string]string{
Expand All @@ -86,7 +87,7 @@ func main() {
}),
constant.Default("80"),
),
grabana.VariableAsCustom(
dashboard.VariableAsCustom(
"vX",
custom.Multi(),
custom.IncludeAll(),
Expand All @@ -96,7 +97,7 @@ func main() {
}),
custom.Default("v2"),
),
grabana.Row(
dashboard.Row(
"Prometheus",
row.WithGraph(
"HTTP Rate",
Expand Down Expand Up @@ -145,19 +146,19 @@ func main() {
singlestat.Thresholds([2]string{"26000000", "28000000"}),
),
),
grabana.Row(
dashboard.Row(
"Some text, because it might be useful",
row.WithText(
"Some awesome text?",
text.Markdown("Markdown syntax help: [commonmark.org/help](https://commonmark.org/help/)\n${percentile}"),
),
row.WithText(
"Some awesome html?",
text.HTML("<b>lalalala</b>"),
text.HTML("Some awesome html?"),
),
),
)
if _, err := client.UpsertDashboard(ctx, folder, dashboard); err != nil {
if _, err := client.UpsertDashboard(ctx, folder, builder); err != nil {
fmt.Printf("Could not create dashboard: %s\n", err)
os.Exit(1)
}
Expand Down
92 changes: 92 additions & 0 deletions cmd/yaml/example.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
title: Awesome dashboard

editable: true
shared_crosshair: true
tags: [generated, yaml]
auto_refresh: 10s

tags_annotations:
- name: Deployments
datasource: "-- Grafana --"
color: "#5794F2"
tags: ["deploy", "production"]

variables:
- interval:
name: interval
label: Interval
values: ["30s", "1m", "5m", "10m", "30m", "1h", "6h", "12h"]
- query:
name: status
label: HTTP status
datasource: prometheus-default
request: "label_values(prometheus_http_requests_total, code)"
- const:
name: percentile
label: Percentile
default: 80
values_map:
50th: "50"
75th: "75"
80th: "80"
85th: "85"
90th: "90"
95th: "95"
99th: "99"
- custom:
name: vX
default: v2
values_map:
v1: v1
v2: v2

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 }}"
- graph:
title: Heap allocations
height: 400px
datasource: prometheus-default
targets:
- prometheus:
query: "go_memstats_heap_alloc_bytes"
legend: "{{job}}"
ref: A
- table:
title: Threads
datasource: prometheus-default
targets:
- prometheus:
query: "go_threads"
hidden_columns: ["Time"]
time_series_aggregations:
- label: AVG
type: avg
- label: Current
type: current
- single_stat:
title: Heap Allocations
datasource: prometheus-default
targets:
- prometheus:
query: 'go_memstats_heap_alloc_bytes{job="prometheus"}'
unit: bytes
thresholds: ["26000000", "28000000"]
color: ["value"]

- name: "Some text, because it might be useful"
panels:
- text:
title: Some awesome text?
markdown: "Markdown syntax help: [commonmark.org/help](https://commonmark.org/help/)\n${percentile}"
- text:
title: Some awesome html?
html: "Some <b>awesome</b> html?"
58 changes: 58 additions & 0 deletions cmd/yaml/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package main

import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"os"

"github.com/K-Phoen/grabana"
"github.com/K-Phoen/grabana/decoder"
)

func main() {
if len(os.Args) != 4 {
fmt.Fprint(os.Stderr, "Usage: go run -mod=vendor main.go file http://grafana-host:3000 api-key\n")
os.Exit(1)
}

content, err := ioutil.ReadFile(os.Args[1])
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{}, os.Args[2], os.Args[3])

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

fmt.Printf("Folder created (id: %d, uid: %s)\n", folder.ID, folder.UID)
}

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

fmt.Println("The deed is done.")
}
Loading

0 comments on commit 5f86535

Please sign in to comment.