sdk

package module
v0.0.0-...-2c80f41 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2020 License: Apache-2.0 Imports: 13 Imported by: 1

README

Grafana SDK Go Report Card

SDK for Go language offers a library for interacting with Grafana server from Go applications. It realizes many of HTTP REST API calls for administration, client, organizations. Beside of them it allows creating of Grafana objects (dashboards, panels, datasources) locally and manipulating them for constructing dashboards programmatically. It would be helpful for massive operations on a large set of Grafana objects.

It was made foremost for autograf project but later separated from it and moved to this new repository because the library is useful per se.

Library design principles

  1. SDK offers client functionality so it covers Grafana REST API with its requests and responses as close as possible.
  2. SDK maps Grafana objects (dashboard, row, panel, datasource) to similar Go structures but not follows exactly all Grafana abstractions.
  3. It doesn't use any logger, instead API functions could return errors where it need.
  4. Prefere no external deps except Go stdlib.
  5. Cover SDK calls with unit tests.

Examples GoDoc

	board := sdk.NewBoard("Sample dashboard title")
	board.ID = 1
	row1 := board.AddRow("Sample row title")
	row1.Add(sdk.NewGraph("Sample graph"))
	graph := sdk.NewGraph("Sample graph 2")
	target := sdk.Target{
		RefID:      "A",
		Datasource: "Sample Source 1",
		Expr:       "sample request 1"}
	graph.AddTarget(&target)
	row1.Add(graph)
	grafanaURL := "http://grafana.host"
	c := sdk.NewClient(grafanaURL, "grafana-api-key", sdk.DefaultHTTPClient)
	response, err := c.SetDashboard(board, false)
	err != nil {
		fmt.Printf("error on uploading dashboard %s", board.Title)
	} else {
		fmt.Printf("dashboard URL: %v", grafanaURL+*resp.URL)
	}

The library includes several demo apps for showing API usage:

You need Grafana API key with admin rights for using these utilities.

Installation Build Status

Of course Go development environment should be set up first. Then:

go get github.com/rikimaru0345/sdk

Dependency packages have included into distro. govendor utility used for vendoring. The single dependency now is:

go get github.com/gosimple/slug

The "slugify" for URLs is a simple task but this package used in Grafana server so it used in the SDK for the compatibility reasons.

Status of REST API realization Coverage Status

Work on full API implementation still in progress. Currently implemented only create/update/delete operations for dashboards and datasources. State of support for misc API parts noted below.

API Status
Authorization API tokens and Basic Auth
Dashboards partially
Datasources +
Alert notification channels +
Organization (current) partially
Organizations partially
Users partially
User (actual) partially
Snapshots -
Frontend settings -
Admin partially

There is no exact roadmap. The integration tests are being run against Grafana 6.6.0.

I still have interest to this library development but not always have time for it. So I gladly accept new contributions. Drop an issue or contact me.

Licence

Distributed under Apache v2.0. All rights belong to the SDK authors. There is no authors list yet, you can see the full list of the contributors in the git history. Official repository is https://github.com/rikimaru0345/sdk

Collection of Grafana tools in Golang

Documentation

Index

Examples

Constants

View Source
const (
	TemplatingHideNone = iota
	TemplatingHideLabel
	TemplatingHideVariable
)

Constants for templating

View Source
const (
	CustomType panelType = iota
	DashlistType
	GraphType
	TableType
	TextType
	PluginlistType
	AlertlistType
	SinglestatType
	RowType
)

Each panel may be one of these types.

View Source
const MixedSource = "-- Mixed --"

Variables

View Source
var DefaultHTTPClient = http.DefaultClient

DefaultHTTPClient initialized Grafana with appropriate conditions. It allows you globally redefine HTTP client.

Functions

This section is empty.

Types

type Alert

type Alert struct {
	Conditions          []AlertCondition    `json:"conditions,omitempty"`
	ExecutionErrorState string              `json:"executionErrorState,omitempty"`
	Frequency           string              `json:"frequency,omitempty"`
	Handler             int                 `json:"handler,omitempty"`
	Name                string              `json:"name,omitempty"`
	NoDataState         string              `json:"noDataState,omitempty"`
	Notifications       []AlertNotification `json:"notifications,omitempty"`
	Message             string              `json:"message,omitempty"`
	For                 string              `json:"for,omitempty"`
}

type AlertCondition

type AlertCondition struct {
	Evaluator struct {
		Params []float64 `json:"params,omitempty"`
		Type   string    `json:"type,omitempty"`
	} `json:"evaluator,omitempty"`
	Operator struct {
		Type string `json:"type,omitempty"`
	} `json:"operator,omitempty"`
	Query struct {
		Params []string `json:"params,omitempty"`
	} `json:"query,omitempty"`
	Reducer struct {
		Params []string `json:"params,omitempty"`
		Type   string   `json:"type,omitempty"`
	} `json:"reducer,omitempty"`
	Type string `json:"type,omitempty"`
}

type AlertNotification

type AlertNotification struct {
	ID                    int64       `json:"id,omitempty"`
	Name                  string      `json:"name"`
	Type                  string      `json:"type"`
	IsDefault             bool        `json:"isDefault"`
	DisableResolveMessage bool        `json:"disableResolveMessage"`
	SendReminder          bool        `json:"sendReminder"`
	Frequency             string      `json:"frequency"`
	Settings              interface{} `json:"settings"`
	UID                   string      `json:"uid,omitempty"`
}

AlertNotification as described in the doc https://grafana.com/docs/grafana/latest/http_api/alerting_notification_channels/

type AlertlistPanel

type AlertlistPanel struct {
	OnlyAlertsOnDashboard bool     `json:"onlyAlertsOnDashboard"`
	Show                  string   `json:"show"`
	SortOrder             int      `json:"sortOrder"`
	Limit                 int      `json:"limit"`
	StateFilter           []string `json:"stateFilter"`
	NameFilter            string   `json:"nameFilter,omitempty"`
	DashboardTags         []string `json:"dashboardTags,omitempty"`
}

type Annotation

type Annotation struct {
	Name       string   `json:"name"`
	Datasource *string  `json:"datasource"`
	ShowLine   bool     `json:"showLine"`
	IconColor  string   `json:"iconColor"`
	LineColor  string   `json:"lineColor"`
	IconSize   uint     `json:"iconSize"`
	Enable     bool     `json:"enable"`
	Query      string   `json:"query"`
	TextField  string   `json:"textField"`
	TagsField  string   `json:"tagsField"`
	Tags       []string `json:"tags"`
	Type       string   `json:"type"`
}

type Axis

type Axis struct {
	Format  string       `json:"format"`
	LogBase int          `json:"logBase"`
	Max     *FloatString `json:"max,omitempty"`
	Min     *FloatString `json:"min,omitempty"`
	Show    bool         `json:"show"`
	Label   string       `json:"label,omitempty"`
}

for a graph panel

type Board

type Board struct {
	ID              uint       `json:"id,omitempty"`
	UID             string     `json:"uid,omitempty"`
	Slug            string     `json:"slug"`
	Title           string     `json:"title"`
	OriginalTitle   string     `json:"originalTitle"`
	Tags            []string   `json:"tags"`
	Style           string     `json:"style"`
	Timezone        string     `json:"timezone"`
	Editable        bool       `json:"editable"`
	HideControls    bool       `json:"hideControls" graf:"hide-controls"`
	SharedCrosshair bool       `json:"sharedCrosshair" graf:"shared-crosshair"`
	Panels          []*Panel   `json:"panels"`
	Rows            []*Row     `json:"rows"`
	Templating      Templating `json:"templating"`
	Annotations     struct {
		List []Annotation `json:"list"`
	} `json:"annotations"`
	Refresh       *BoolString `json:"refresh,omitempty"`
	SchemaVersion uint        `json:"schemaVersion"`
	Version       uint        `json:"version"`
	Links         []link      `json:"links"`
	Time          Time        `json:"time"`
	Timepicker    Timepicker  `json:"timepicker"`

	GraphTooltip int `json:"graphTooltip,omitempty"`
	// contains filtered or unexported fields
}

Board represents Grafana dashboard.

func NewBoard

func NewBoard(title string) *Board
Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/rikimaru0345/sdk"
)

func main() {
	board := sdk.NewBoard("Sample dashboard title")
	board.ID = 1
	row1 := board.AddRow("Sample row title")
	row1.Add(sdk.NewGraph("Sample graph"))
	graphWithDs := sdk.NewGraph("Sample graph 2")
	target := sdk.Target{
		RefID:      "A",
		Datasource: "Sample Source 1",
		Expr:       "sample request 1"}
	graphWithDs.AddTarget(&target)
	row1.Add(graphWithDs)
	data, _ := json.MarshalIndent(board, "", "    ")
	fmt.Printf("%s", data)
}
Output:

{
    "id": 1,
    "slug": "",
    "title": "Sample dashboard title",
    "originalTitle": "",
    "tags": null,
    "style": "dark",
    "timezone": "browser",
    "editable": true,
    "hideControls": false,
    "sharedCrosshair": false,
    "panels": null,
    "rows": [
        {
            "title": "Sample row title",
            "showTitle": false,
            "collapse": false,
            "editable": true,
            "height": "250px",
            "panels": [
                {
                    "editable": false,
                    "error": false,
                    "gridPos": {},
                    "id": 1,
                    "isNew": true,
                    "renderer": "flot",
                    "span": 12,
                    "title": "Sample graph",
                    "transparent": false,
                    "type": "graph",
                    "aliasColors": null,
                    "bars": false,
                    "fill": 0,
                    "legend": {
                        "alignAsTable": false,
                        "avg": false,
                        "current": false,
                        "hideEmpty": false,
                        "hideZero": false,
                        "max": false,
                        "min": false,
                        "rightSide": false,
                        "show": false,
                        "total": false,
                        "values": false
                    },
                    "lines": false,
                    "linewidth": 0,
                    "nullPointMode": "connected",
                    "percentage": false,
                    "pointradius": 5,
                    "points": false,
                    "stack": false,
                    "steppedLine": false,
                    "tooltip": {
                        "shared": false,
                        "value_type": ""
                    },
                    "x-axis": true,
                    "y-axis": true,
                    "xaxis": {
                        "format": "",
                        "logBase": 0,
                        "show": false
                    },
                    "yaxes": null
                },
                {
                    "editable": false,
                    "error": false,
                    "gridPos": {},
                    "id": 2,
                    "isNew": true,
                    "renderer": "flot",
                    "span": 12,
                    "title": "Sample graph 2",
                    "transparent": false,
                    "type": "graph",
                    "aliasColors": null,
                    "bars": false,
                    "fill": 0,
                    "legend": {
                        "alignAsTable": false,
                        "avg": false,
                        "current": false,
                        "hideEmpty": false,
                        "hideZero": false,
                        "max": false,
                        "min": false,
                        "rightSide": false,
                        "show": false,
                        "total": false,
                        "values": false
                    },
                    "lines": false,
                    "linewidth": 0,
                    "nullPointMode": "connected",
                    "percentage": false,
                    "pointradius": 5,
                    "points": false,
                    "stack": false,
                    "steppedLine": false,
                    "targets": [
                        {
                            "refId": "A",
                            "datasource": "Sample Source 1",
                            "expr": "sample request 1"
                        }
                    ],
                    "tooltip": {
                        "shared": false,
                        "value_type": ""
                    },
                    "x-axis": true,
                    "y-axis": true,
                    "xaxis": {
                        "format": "",
                        "logBase": 0,
                        "show": false
                    },
                    "yaxes": null
                }
            ],
            "repeat": null
        }
    ],
    "templating": {
        "list": null
    },
    "annotations": {
        "list": null
    },
    "schemaVersion": 0,
    "version": 0,
    "links": null,
    "time": {
        "from": "",
        "to": ""
    },
    "timepicker": {
        "refresh_intervals": null,
        "time_options": null
    }
}

func (*Board) AddRow

func (b *Board) AddRow(title string) *Row

func (*Board) AddTags

func (b *Board) AddTags(tags ...string)

func (*Board) HasTag

func (b *Board) HasTag(tag string) bool

func (*Board) RemoveTags

func (b *Board) RemoveTags(tags ...string)

func (*Board) UpdateSlug

func (b *Board) UpdateSlug() string

type BoardProperties

type BoardProperties struct {
	IsStarred  bool      `json:"isStarred,omitempty"`
	IsHome     bool      `json:"isHome,omitempty"`
	IsSnapshot bool      `json:"isSnapshot,omitempty"`
	Type       string    `json:"type,omitempty"`
	CanSave    bool      `json:"canSave"`
	CanEdit    bool      `json:"canEdit"`
	CanStar    bool      `json:"canStar"`
	Slug       string    `json:"slug"`
	Expires    time.Time `json:"expires"`
	Created    time.Time `json:"created"`
	Updated    time.Time `json:"updated"`
	UpdatedBy  string    `json:"updatedBy"`
	CreatedBy  string    `json:"createdBy"`
	Version    int       `json:"version"`
}

BoardProperties keeps metadata of a dashboard.

type BoolInt

type BoolInt struct {
	Flag  bool
	Value *int64
}

func (BoolInt) MarshalJSON

func (s BoolInt) MarshalJSON() ([]byte, error)

func (*BoolInt) UnmarshalJSON

func (s *BoolInt) UnmarshalJSON(raw []byte) error

type BoolString

type BoolString struct {
	Flag  bool
	Value string
}

func (BoolString) MarshalJSON

func (s BoolString) MarshalJSON() ([]byte, error)

func (*BoolString) UnmarshalJSON

func (s *BoolString) UnmarshalJSON(raw []byte) error

type Client

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

Client uses Grafana REST API for interacting with Grafana server.

func NewClient

func NewClient(apiURL, apiKeyOrBasicAuth string, client *http.Client) *Client

NewClient initializes client for interacting with an instance of Grafana server; apiKeyOrBasicAuth accepts either 'username:password' basic authentication credentials, or a Grafana API key

func (*Client) AddActualOrgUser

func (r *Client) AddActualOrgUser(userRole UserRole) (StatusMessage, error)

AddActualOrgUser adds a global user to the current organization. Reflects POST /api/org/users API call.

func (*Client) AddOrgUser

func (r *Client) AddOrgUser(user UserRole, oid uint) (StatusMessage, error)

AddUserToOrg add user to organization with oid. Reflects POST /api/orgs/:orgId/users API call.

func (*Client) CreateAlertNotification

func (c *Client) CreateAlertNotification(an AlertNotification) (int64, error)

CreateAlertNotification creates a new alert notification channel. Reflects POST /api/alert-notifications API call.

func (*Client) CreateDatasource

func (r *Client) CreateDatasource(ds Datasource) (StatusMessage, error)

CreateDatasource creates a new datasource. Reflects POST /api/datasources API call.

func (*Client) CreateOrg

func (r *Client) CreateOrg(org Org) (StatusMessage, error)

CreateOrg creates a new organization. It reflects POST /api/orgs API call.

func (*Client) CreateUser

func (r *Client) CreateUser(user User) (StatusMessage, error)

CreateUser creates a new global user. Requires basic authentication and that the authenticated user is a Grafana Admin. Reflects POST /api/admin/users API call.

func (*Client) DeleteActualOrgUser

func (r *Client) DeleteActualOrgUser(uid uint) (StatusMessage, error)

DeleteActualOrgUser delete user in actual organization. Reflects DELETE /api/org/users/:userId API call.

func (*Client) DeleteAlertNotificationID

func (c *Client) DeleteAlertNotificationID(id uint) error

DeleteAlertNotificationID deletes the specified alert notification channel. Reflects DELETE /api/alert-notifications/:id API call.

func (*Client) DeleteAlertNotificationUID

func (c *Client) DeleteAlertNotificationUID(uid string) error

DeleteAlertNotificationUID deletes the specified alert notification channel. Reflects DELETE /api/alert-notifications/uid/:uid API call.

func (*Client) DeleteDashboard

func (r *Client) DeleteDashboard(slug string) (StatusMessage, error)

DeleteDashboard deletes dashboard that selected by slug string. Grafana only can delete a dashboard in a database. File dashboards may be only loaded with HTTP API but not deteled.

Reflects DELETE /api/dashboards/db/:slug API call.

func (*Client) DeleteDatasource

func (r *Client) DeleteDatasource(id uint) (StatusMessage, error)

DeleteDatasource deletes an existing datasource by ID. Reflects DELETE /api/datasources/:datasourceId API call.

func (*Client) DeleteDatasourceByName

func (r *Client) DeleteDatasourceByName(name string) (StatusMessage, error)

DeleteDatasourceByName deletes an existing datasource by Name. Reflects DELETE /api/datasources/name/:datasourceName API call.

func (*Client) DeleteOrg

func (r *Client) DeleteOrg(oid uint) (StatusMessage, error)

DeleteOrg deletes the organization identified by the oid. Reflects DELETE /api/orgs/:orgId API call.

func (*Client) DeleteOrgUser

func (r *Client) DeleteOrgUser(oid, uid uint) (StatusMessage, error)

DeleteOrgUser deletes the user specified by uid within the organization specified by oid. Reflects DELETE /api/orgs/:orgId/users/:userId API call.

func (*Client) GetActualOrg

func (r *Client) GetActualOrg() (Org, error)

GetActualOrg gets current organization. It reflects GET /api/org API call.

func (*Client) GetActualOrgPreferences

func (r *Client) GetActualOrgPreferences() (Preferences, error)

GetActualOrgPreferences gets preferences of the actual organization. It reflects GET /api/org/preferences API call.

func (*Client) GetActualOrgUsers

func (r *Client) GetActualOrgUsers() ([]OrgUser, error)

GetActualOrgUsers get all users within the actual organisation. Reflects GET /api/org/users API call.

func (*Client) GetActualUser

func (r *Client) GetActualUser() (User, error)

GetActualUser gets an actual user. Reflects GET /api/user API call.

func (*Client) GetAlertNotificationID

func (c *Client) GetAlertNotificationID(id uint) (AlertNotification, error)

GetAlertNotificationID gets the alert notification channel which has the specified id. Reflects GET /api/alert-notifications/:id API call.

func (*Client) GetAlertNotificationUID

func (c *Client) GetAlertNotificationUID(uid string) (AlertNotification, error)

GetAlertNotificationUID gets the alert notification channel which has the specified uid. Reflects GET /api/alert-notifications/uid/:uid API call.

func (*Client) GetAllAlertNotifications

func (c *Client) GetAllAlertNotifications() ([]AlertNotification, error)

GetAllAlertNotifications gets all alert notification channels. Reflects GET /api/alert-notifications API call.

func (*Client) GetAllDatasources

func (r *Client) GetAllDatasources() ([]Datasource, error)

GetAllDatasources gets all datasources. Reflects GET /api/datasources API call.

func (*Client) GetAllOrgs

func (r *Client) GetAllOrgs() ([]Org, error)

GetAllOrgs returns all organizations. It reflects GET /api/orgs API call.

func (*Client) GetAllUsers

func (r *Client) GetAllUsers() ([]User, error)

GetAllUsers gets all users. Reflects GET /api/users API call.

func (*Client) GetDashboard

func (r *Client) GetDashboard(slug string) (Board, BoardProperties, error)

GetDashboard loads a dashboard from Grafana instance along with metadata for a dashboard. For dashboards from a filesystem set "file/" prefix for slug. By default dashboards from a database assumed. Database dashboards may have "db/" prefix or may have not, it will be appended automatically.

Reflects GET /api/dashboards/db/:slug API call.

func (*Client) GetDatasource

func (r *Client) GetDatasource(id uint) (Datasource, error)

GetDatasource gets an datasource by ID. Reflects GET /api/datasources/:datasourceId API call.

func (*Client) GetDatasourceByName

func (r *Client) GetDatasourceByName(name string) (Datasource, error)

GetDatasourceByName gets an datasource by Name. Reflects GET /api/datasources/name/:datasourceName API call.

func (*Client) GetDatasourceTypes

func (r *Client) GetDatasourceTypes() (map[string]DatasourceType, error)

GetDatasourceTypes gets all available plugins for the datasources. Reflects GET /api/datasources/plugins API call.

func (*Client) GetOrgById

func (r *Client) GetOrgById(oid uint) (Org, error)

GetOrgById gets organization by organization Id. It reflects GET /api/orgs/:orgId API call.

func (*Client) GetOrgByOrgName

func (r *Client) GetOrgByOrgName(name string) (Org, error)

GetOrgByOrgName gets organization by organization name. It reflects GET /api/orgs/name/:orgName API call.

func (*Client) GetOrgUsers

func (r *Client) GetOrgUsers(oid uint) ([]OrgUser, error)

GetOrgUsers gets the users for the organization specified by oid. Reflects GET /api/orgs/:orgId/users API call.

func (*Client) GetRawDashboard

func (r *Client) GetRawDashboard(slug string) ([]byte, BoardProperties, error)

GetRawDashboard loads a dashboard JSON from Grafana instance along with metadata for a dashboard. Contrary to GetDashboard() it not unpack loaded JSON to Board structure. Instead it returns it as byte slice. It guarantee that data of dashboard returned untouched by conversion with Board so no matter how properly fields from a current version of Grafana mapped to our Board fields. It useful for backuping purposes when you want a dashboard exactly with same data as it exported by Grafana.

For dashboards from a filesystem set "file/" prefix for slug. By default dashboards from a database assumed. Database dashboards may have "db/" prefix or may have not, it will be appended automatically.

Reflects GET /api/dashboards/db/:slug API call.

func (*Client) GetUser

func (r *Client) GetUser(id uint) (User, error)

GetUser gets an user by ID. Reflects GET /api/users/:id API call.

func (*Client) SearchDashboards

func (r *Client) SearchDashboards(query string, starred bool, tags ...string) ([]FoundBoard, error)

SearchDashboards search dashboards by substring of their title. It allows restrict the result set with only starred dashboards and only for tags (logical OR applied to multiple tags).

Reflects GET /api/search API call.

func (*Client) SearchUsersWithPaging

func (r *Client) SearchUsersWithPaging(query *string, perpage, page *int) (PageUsers, error)

SearchUsersWithPaging search users with paging. query optional. query value is contained in one of the name, login or email fields. Query values with spaces need to be url encoded e.g. query=Jane%20Doe perpage optional. default 1000 page optional. default 1 http://docs.grafana.org/http_api/user/#search-users http://docs.grafana.org/http_api/user/#search-users-with-paging

Reflects GET /api/users/search API call.

func (*Client) SetDashboard

func (r *Client) SetDashboard(board Board, overwrite bool) (StatusMessage, error)

SetDashboard updates existing dashboard or creates a new one. Set dasboard ID to nil to create a new dashboard. Set overwrite to true if you want to overwrite existing dashboard with newer version or with same dashboard title. Grafana only can create or update a dashboard in a database. File dashboards may be only loaded with HTTP API but not created or updated.

Reflects POST /api/dashboards/db API call.

func (*Client) SetRawDashboard

func (r *Client) SetRawDashboard(raw []byte) (StatusMessage, error)

SetRawDashboard updates existing dashboard or creates a new one. Contrary to SetDashboard() it accepts raw JSON instead of Board structure. Grafana only can create or update a dashboard in a database. File dashboards may be only loaded with HTTP API but not created or updated.

Reflects POST /api/dashboards/db API call.

func (*Client) SwitchUserContext

func (r *Client) SwitchUserContext(uid uint, oid uint) (StatusMessage, error)

SwitchUserContext switches user context to the given organization. Requires basic authentication and that the authenticated user is a Grafana Admin. Reflects POST /api/users/:userId/using/:organizationId API call.

func (*Client) UpdateActualOrg

func (r *Client) UpdateActualOrg(org Org) (StatusMessage, error)

UpdateActualOrg updates current organization. It reflects PUT /api/org API call.

func (*Client) UpdateActualOrgPreferences

func (r *Client) UpdateActualOrgPreferences(prefs Preferences) (StatusMessage, error)

UpdateActualOrgPreferences updates preferences of the actual organization. Reflects PUT /api/org/preferences API call.

func (*Client) UpdateActualOrgUser

func (r *Client) UpdateActualOrgUser(user UserRole, uid uint) (StatusMessage, error)

UpdateUser updates the existing user. Reflects POST /api/org/users/:userId API call.

func (*Client) UpdateAlertNotificationID

func (c *Client) UpdateAlertNotificationID(an AlertNotification, id uint) error

UpdateAlertNotificationID updates the specified alert notification channel. Reflects PUT /api/alert-notifications/:id API call.

func (*Client) UpdateAlertNotificationUID

func (c *Client) UpdateAlertNotificationUID(an AlertNotification, uid string) error

UpdateAlertNotificationUID updates the specified alert notification channel. Reflects PUT /api/alert-notifications/uid/:uid API call.

func (*Client) UpdateDatasource

func (r *Client) UpdateDatasource(ds Datasource) (StatusMessage, error)

UpdateDatasource updates a datasource from data passed in argument. Reflects PUT /api/datasources/:datasourceId API call.

func (*Client) UpdateOrg

func (r *Client) UpdateOrg(org Org, oid uint) (StatusMessage, error)

UpdateOrg updates the organization identified by oid. It reflects PUT /api/orgs/:orgId API call.

func (*Client) UpdateOrgUser

func (r *Client) UpdateOrgUser(user UserRole, oid, uid uint) (StatusMessage, error)

UpdateOrgUser updates the user specified by uid within the organization specified by oid. Reflects PATCH /api/orgs/:orgId/users/:userId API call.

func (*Client) UpdateUserPermissions

func (r *Client) UpdateUserPermissions(permissions UserPermissions, uid uint) (StatusMessage, error)

UpdateUserPermissions updates the permissions of a global user. Requires basic authentication and that the authenticated user is a Grafana Admin. Reflects PUT /api/admin/users/:userId/password API call.

type Column

type Column struct {
	TextType string `json:"text"`
	Value    string `json:"value"`
}

for a table

type ColumnStyle

type ColumnStyle struct {
	Alias      *string   `json:"alias"`
	DateFormat *string   `json:"dateFormat,omitempty"`
	Pattern    string    `json:"pattern"`
	Type       string    `json:"type"`
	ColorMode  *string   `json:"colorMode,omitempty"`
	Colors     *[]string `json:"colors,omitempty"`
	Decimals   *uint     `json:"decimals,omitempty"`
	Thresholds *[]string `json:"thresholds,omitempty"`
	Unit       *string   `json:"unit,omitempty"`
}

for a table

type CommonPanel

type CommonPanel struct {
	Datasource *string `json:"datasource,omitempty"` // metrics
	Editable   bool    `json:"editable"`
	Error      bool    `json:"error"`
	GridPos    struct {
		H *int `json:"h,omitempty"`
		W *int `json:"w,omitempty"`
		X *int `json:"x,omitempty"`
		Y *int `json:"y,omitempty"`
	} `json:"gridPos,omitempty"`
	Height           *string   `json:"height,omitempty"` // general
	HideTimeOverride *bool     `json:"hideTimeOverride,omitempty"`
	ID               uint      `json:"id"`
	IsNew            bool      `json:"isNew"`
	Links            []link    `json:"links,omitempty"`    // general
	MinSpan          *float32  `json:"minSpan,omitempty"`  // templating options
	OfType           panelType `json:"-"`                  // it required for defining type of the panel
	Renderer         *string   `json:"renderer,omitempty"` // display styles
	Repeat           *string   `json:"repeat,omitempty"`   // templating options
	// RepeatIteration *int64   `json:"repeatIteration,omitempty"`
	RepeatPanelID *uint `json:"repeatPanelId,omitempty"`
	ScopedVars    map[string]struct {
		Selected bool   `json:"selected"`
		Text     string `json:"text"`
		Value    string `json:"value"`
	} `json:"scopedVars,omitempty"`
	Span        float32 `json:"span"`  // general
	Title       string  `json:"title"` // general
	Transparent bool    `json:"transparent"`
	Type        string  `json:"type"`
	Alert       *Alert  `json:"alert,omitempty"`
}

type Current

type Current struct {
	Tags  []*string   `json:"tags,omitempty"`
	Text  string      `json:"text"`
	Value interface{} `json:"value"` // TODO select more precise type
}

for templateVar

type CustomPanel

type CustomPanel map[string]interface{}

type DashlistPanel

type DashlistPanel struct {
	Mode  string   `json:"mode"`
	Limit uint     `json:"limit"`
	Query string   `json:"query"`
	Tags  []string `json:"tags"`
}

type Datasource

type Datasource struct {
	ID                uint        `json:"id"`
	OrgID             uint        `json:"orgId"`
	Name              string      `json:"name"`
	Type              string      `json:"type"`
	Access            string      `json:"access"` // direct or proxy
	URL               string      `json:"url"`
	Password          *string     `json:"password,omitempty"`
	User              *string     `json:"user,omitempty"`
	Database          *string     `json:"database,omitempty"`
	BasicAuth         *bool       `json:"basicAuth,omitempty"`
	BasicAuthUser     *string     `json:"basicAuthUser,omitempty"`
	BasicAuthPassword *string     `json:"basicAuthPassword,omitempty"`
	IsDefault         bool        `json:"isDefault"`
	JSONData          interface{} `json:"jsonData"`
	SecureJSONData    interface{} `json:"secureJsonData"`
}

Datasource as described in the doc http://docs.grafana.org/reference/http_api/#get-all-datasources

type DatasourceType

type DatasourceType struct {
	Metrics  bool   `json:"metrics"`
	Module   string `json:"module"`
	Name     string `json:"name"`
	Partials struct {
		Query string `json:"query"`
	} `json:"datasource"`
	PluginType  string `json:"pluginType"`
	ServiceName string `json:"serviceName"`
	Type        string `json:"type"`
}

Datasource type as described in http://docs.grafana.org/reference/http_api/#available-data-source-types

type FloatString

type FloatString struct {
	Value float64
	Valid bool
}

FloatString represents special type for json values that could be strings or ints: 100 or "100"

func NewFloatString

func NewFloatString(i float64) *FloatString

func (*FloatString) MarshalJSON

func (v *FloatString) MarshalJSON() ([]byte, error)

MarshalJSON implements custom marshalling for FloatString type

func (*FloatString) UnmarshalJSON

func (v *FloatString) UnmarshalJSON(raw []byte) error

UnmarshalJSON implements custom unmarshalling for FloatString type

type FoundBoard

type FoundBoard struct {
	ID        uint     `json:"id"`
	Title     string   `json:"title"`
	URI       string   `json:"uri"`
	Type      string   `json:"type"`
	Tags      []string `json:"tags"`
	IsStarred bool     `json:"isStarred"`
}

FoundBoard keeps result of search with metadata of a dashboard.

type GraphPanel

type GraphPanel struct {
	AliasColors interface{} `json:"aliasColors"` // XXX
	Bars        bool        `json:"bars"`
	DashLength  *uint       `json:"dashLength,omitempty"`
	Dashes      *bool       `json:"dashes,omitempty"`
	Decimals    *uint       `json:"decimals,omitempty"`
	Description *string     `json:"description,omitempty"`
	Fill        int         `json:"fill"`

	Legend struct {
		AlignAsTable bool  `json:"alignAsTable"`
		Avg          bool  `json:"avg"`
		Current      bool  `json:"current"`
		HideEmpty    bool  `json:"hideEmpty"`
		HideZero     bool  `json:"hideZero"`
		Max          bool  `json:"max"`
		Min          bool  `json:"min"`
		RightSide    bool  `json:"rightSide"`
		Show         bool  `json:"show"`
		SideWidth    *uint `json:"sideWidth,omitempty"`
		Total        bool  `json:"total"`
		Values       bool  `json:"values"`
	} `json:"legend,omitempty"`
	LeftYAxisLabel  *string          `json:"leftYAxisLabel,omitempty"`
	Lines           bool             `json:"lines"`
	Linewidth       uint             `json:"linewidth"`
	NullPointMode   string           `json:"nullPointMode"`
	Percentage      bool             `json:"percentage"`
	Pointradius     int              `json:"pointradius"`
	Points          bool             `json:"points"`
	RightYAxisLabel *string          `json:"rightYAxisLabel,omitempty"`
	SeriesOverrides []SeriesOverride `json:"seriesOverrides,omitempty"`
	SpaceLength     *uint            `json:"spaceLength,omitempty"`
	Stack           bool             `json:"stack"`
	SteppedLine     bool             `json:"steppedLine"`
	Targets         []Target         `json:"targets,omitempty"`
	Thresholds      []Threshold      `json:"thresholds,omitempty"`
	TimeFrom        *string          `json:"timeFrom,omitempty"`
	TimeShift       *string          `json:"timeShift,omitempty"`
	Tooltip         Tooltip          `json:"tooltip"`
	XAxis           bool             `json:"x-axis,omitempty"`
	YAxis           bool             `json:"y-axis,omitempty"`
	YFormats        []string         `json:"y_formats,omitempty"`
	Xaxis           Axis             `json:"xaxis"` // was added in Grafana 4.x?
	Yaxes           []Axis           `json:"yaxes"` // was added in Grafana 4.x?
}

type Height

type Height string

Height of rows maybe passed as number (ex 200) or as string (ex "200px") or empty string

func (*Height) UnmarshalJSON

func (h *Height) UnmarshalJSON(raw []byte) error

type IntString

type IntString struct {
	Value int64
	Valid bool
}

IntString represents special type for json values that could be strings or ints: 100 or "100"

func NewIntString

func NewIntString(i int64) *IntString

func (*IntString) MarshalJSON

func (v *IntString) MarshalJSON() ([]byte, error)

MarshalJSON implements custom marshalling for IntString type

func (*IntString) UnmarshalJSON

func (v *IntString) UnmarshalJSON(raw []byte) error

UnmarshalJSON implements custom unmarshalling for IntString type

type MapType

type MapType struct {
	Name  *string `json:"name,omitempty"`
	Value *int    `json:"value,omitempty"`
}

type Option

type Option struct {
	Text     string `json:"text"`
	Value    string `json:"value"`
	Selected bool   `json:"selected"`
}

for templateVar

type Org

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

Org -

type OrgUser

type OrgUser struct {
	OrgID         uint   `json:"orgId"`
	ID            uint   `json:"userId"`
	Email         string `json:"email"`
	AvatarURL     string `json:"avatarUrl"`
	Login         string `json:"login"`
	Role          string `json:"role"`
	LastSeenAt    string `json:"lastSeenAt"`
	LastSeenAtAge string `json:"lastSeenAtAge"`
}

OrgUser - updated according to: https://grafana.com/docs/grafana/latest/http_api/org/#get-users-in-organization

type PageUsers

type PageUsers struct {
	TotalCount int    `json:"totalCount"`
	Users      []User `json:"users"`
	Page       int    `json:"page"`
	PerPage    int    `json:"perPage"`
}

type Panel

type Panel struct {
	CommonPanel
	// Should be initialized only one type of panels.
	// OfType field defines which of types below will be used.
	*GraphPanel
	*TablePanel
	*TextPanel
	*SinglestatPanel
	*DashlistPanel
	*PluginlistPanel
	*RowPanel
	*AlertlistPanel
	*CustomPanel
}

Panel represents panels of different types defined in Grafana.

func NewAlertlist

func NewAlertlist(title string) *Panel

func NewCustom

func NewCustom(title string) *Panel

NewCustom initializes panel with a singlestat panel.

func NewDashlist

func NewDashlist(title string) *Panel

NewDashlist initializes panel with a dashlist panel.

func NewGraph

func NewGraph(title string) *Panel

NewGraph initializes panel with a graph panel.

func NewPluginlist

func NewPluginlist(title string) *Panel

NewPluginlist initializes panel with a singlestat panel.

func NewSinglestat

func NewSinglestat(title string) *Panel

NewSinglestat initializes panel with a singlestat panel.

func NewTable

func NewTable(title string) *Panel

NewTable initializes panel with a table panel.

func NewText

func NewText(title string) *Panel

NewText initializes panel with a text panel.

func (*Panel) AddTarget

func (p *Panel) AddTarget(t *Target)

AddTarget adds a new target as defined in the argument but with refId letter incremented. Value of refID from the argument will be used only if no target with such value already exists.

func (*Panel) GetTargets

func (p *Panel) GetTargets() *[]Target

GetTargets is iterate over all panel targets. It just returns nil if no targets defined for panel of concrete type.

func (*Panel) MarshalJSON

func (p *Panel) MarshalJSON() ([]byte, error)

func (*Panel) RepeatDatasourcesForEachTarget

func (p *Panel) RepeatDatasourcesForEachTarget(dsNames ...string)

MapDatasources on all existing targets for the panel.

func (*Panel) RepeatTargetsForDatasources

func (p *Panel) RepeatTargetsForDatasources(dsNames ...string)

RepeatTargetsForDatasources repeats all existing targets for a panel for all provided in the argument datasources. Existing datasources of targets are ignored.

func (*Panel) ResetTargets

func (p *Panel) ResetTargets()

ResetTargets delete all targets defined for a panel.

func (*Panel) SetTarget

func (p *Panel) SetTarget(t *Target)

SetTarget updates a target if target with such refId exists or creates a new one.

func (*Panel) UnmarshalJSON

func (p *Panel) UnmarshalJSON(b []byte) (err error)

type PluginlistPanel

type PluginlistPanel struct {
	Limit int `json:"limit,omitempty"`
}

type Preferences

type Preferences struct {
	Theme           string `json:"theme,omitempty"`
	HomeDashboardId uint   `json:"homeDashboardId,omitempty"`
	Timezone        string `json:"timezone,omitempty"`
}

type RangeMap

type RangeMap struct {
	From *string `json:"from,omitempty"`
	Text *string `json:"text,omitempty"`
	To   *string `json:"to,omitempty"`
}

type Row

type Row struct {
	Title     string  `json:"title"`
	ShowTitle bool    `json:"showTitle"`
	Collapse  bool    `json:"collapse"`
	Editable  bool    `json:"editable"`
	Height    Height  `json:"height"`
	Panels    []Panel `json:"panels"`
	Repeat    *string `json:"repeat"`
}

Row represents single row of Grafana dashboard.

func (*Row) Add

func (r *Row) Add(panel *Panel)

func (*Row) AddCustom

func (r *Row) AddCustom(data *CustomPanel)

func (*Row) AddDashlist

func (r *Row) AddDashlist(data *DashlistPanel)

func (*Row) AddGraph

func (r *Row) AddGraph(data *GraphPanel)

func (*Row) AddSinglestat

func (r *Row) AddSinglestat(data *SinglestatPanel)

func (*Row) AddTable

func (r *Row) AddTable(data *TablePanel)

func (*Row) AddText

func (r *Row) AddText(data *TextPanel)

type RowPanel

type RowPanel struct {
	Panels []Panel
}

type SeriesOverride

type SeriesOverride struct {
	Alias         string      `json:"alias"`
	Bars          *bool       `json:"bars,omitempty"`
	Color         *string     `json:"color,omitempty"`
	Fill          *int        `json:"fill,omitempty"`
	FillBelowTo   *string     `json:"fillBelowTo,omitempty"`
	Legend        *bool       `json:"legend,omitempty"`
	Lines         *bool       `json:"lines,omitempty"`
	Stack         *BoolString `json:"stack,omitempty"`
	Transform     *string     `json:"transform,omitempty"`
	YAxis         *int        `json:"yaxis,omitempty"`
	ZIndex        *int        `json:"zindex,omitempty"`
	NullPointMode *string     `json:"nullPointMode,omitempty"`
}

for a graph panel

type SinglestatPanel

type SinglestatPanel struct {
	Colors          []string `json:"colors"`
	ColorValue      bool     `json:"colorValue"`
	ColorBackground bool     `json:"colorBackground"`
	Decimals        int      `json:"decimals"`
	Format          string   `json:"format"`
	Gauge           struct {
		MaxValue         float32 `json:"maxValue"`
		MinValue         float32 `json:"minValue"`
		Show             bool    `json:"show"`
		ThresholdLabels  bool    `json:"thresholdLabels"`
		ThresholdMarkers bool    `json:"thresholdMarkers"`
	} `json:"gauge,omitempty"`
	MappingType     *uint       `json:"mappingType,omitempty"`
	MappingTypes    []*MapType  `json:"mappingTypes,omitempty"`
	MaxDataPoints   *IntString  `json:"maxDataPoints,omitempty"`
	NullPointMode   string      `json:"nullPointMode"`
	Postfix         *string     `json:"postfix,omitempty"`
	PostfixFontSize *string     `json:"postfixFontSize,omitempty"`
	Prefix          *string     `json:"prefix,omitempty"`
	PrefixFontSize  *string     `json:"prefixFontSize,omitempty"`
	RangeMaps       []*RangeMap `json:"rangeMaps,omitempty"`
	SparkLine       struct {
		FillColor *string  `json:"fillColor,omitempty"`
		Full      bool     `json:"full,omitempty"`
		LineColor *string  `json:"lineColor,omitempty"`
		Show      bool     `json:"show,omitempty"`
		YMin      *float64 `json:"ymin,omitempty"`
		YMax      *float64 `json:"ymax,omitempty"`
	} `json:"sparkline,omitempty"`
	Targets       []Target   `json:"targets,omitempty"`
	Thresholds    string     `json:"thresholds"`
	ValueFontSize string     `json:"valueFontSize"`
	ValueMaps     []ValueMap `json:"valueMaps"`
	ValueName     string     `json:"valueName"`
}

type StatusMessage

type StatusMessage struct {
	ID      *uint   `json:"id"`
	OrgID   *uint   `json:"orgId"`
	Message *string `json:"message"`
	Slug    *string `json:"slug"`
	Version *int    `json:"version"`
	Status  *string `json:"status"`
	UID     *string `json:"uid"`
	URL     *string `json:"url"`
}

StatusMessage reflects status message as it returned by Grafana REST API.

type TablePanel

type TablePanel struct {
	Columns []Column `json:"columns"`
	Sort    *struct {
		Col  uint `json:"col"`
		Desc bool `json:"desc"`
	} `json:"sort,omitempty"`
	Styles    []ColumnStyle `json:"styles"`
	Transform string        `json:"transform"`
	Targets   []Target      `json:"targets,omitempty"`
	Scroll    bool          `json:"scroll"` // from grafana 3.x
}

type Target

type Target struct {
	RefID      string `json:"refId"`
	Datasource string `json:"datasource,omitempty"`

	// For Prometheus
	Expr           string `json:"expr,omitempty"`
	IntervalFactor int    `json:"intervalFactor,omitempty"`
	Interval       string `json:"interval,omitempty"`
	Step           int    `json:"step,omitempty"`
	LegendFormat   string `json:"legendFormat,omitempty"`
	Instant        bool   `json:"instant,omitempty"`
	Format         string `json:"format,omitempty"`

	// For Elasticsearch
	DsType  *string `json:"dsType,omitempty"`
	Metrics []struct {
		ID    string `json:"id"`
		Field string `json:"field"`
		Type  string `json:"type"`
	} `json:"metrics,omitempty"`
	Query      string `json:"query,omitempty"`
	Alias      string `json:"alias,omitempty"`
	RawQuery   bool   `json:"rawQuery,omitempty"`
	TimeField  string `json:"timeField,omitempty"`
	BucketAggs []struct {
		ID       string `json:"id"`
		Field    string `json:"field"`
		Type     string `json:"type"`
		Settings struct {
			Interval    string `json:"interval,omitempty"`
			MinDocCount int    `json:"min_doc_count"`
			Order       string `json:"order,omitempty"`
			OrderBy     string `json:"orderBy,omitempty"`
			Size        string `json:"size,omitempty"`
		} `json:"settings"`
	} `json:"bucketAggs,omitempty"`

	// For Graphite
	Target string `json:"target,omitempty"`

	// For CloudWatch
	Namespace  string            `json:"namespace,omitempty"`
	MetricName string            `json:"metricName,omitempty"`
	Statistics []string          `json:"statistics,omitempty"`
	Dimensions map[string]string `json:"dimensions,omitempty"`
	Period     string            `json:"period,omitempty"`
	Region     string            `json:"region,omitempty"`
}

for an any panel

type TemplateVar

type TemplateVar struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"`
	Auto        bool     `json:"auto,omitempty"`
	AutoCount   *int     `json:"auto_count,omitempty"`
	Datasource  *string  `json:"datasource"`
	Refresh     BoolInt  `json:"refresh"`
	Options     []Option `json:"options"`
	IncludeAll  bool     `json:"includeAll"`
	AllFormat   string   `json:"allFormat"`
	AllValue    string   `json:"allValue"`
	Multi       bool     `json:"multi"`
	MultiFormat string   `json:"multiFormat"`
	Query       string   `json:"query"`
	Regex       string   `json:"regex"`
	Current     Current  `json:"current"`
	Label       string   `json:"label"`
	Hide        uint8    `json:"hide"`
	Sort        int      `json:"sort"`
}

type Templating

type Templating struct {
	List []TemplateVar `json:"list"`
}

type TextPanel

type TextPanel struct {
	Content    string `json:"content"`
	Mode       string `json:"mode"`
	PageSize   uint   `json:"pageSize"`
	Scroll     bool   `json:"scroll"`
	ShowHeader bool   `json:"showHeader"`
	Sort       struct {
		Col  int  `json:"col"`
		Desc bool `json:"desc"`
	} `json:"sort"`
	Styles []ColumnStyle `json:"styles"`
}

type Threshold

type Threshold struct {
	// the alert threshold value, we do not omitempty, since 0 is a valid
	// threshold
	Value float32 `json:"value"`
	// critical, warning, ok, custom
	ColorMode string `json:"colorMode,omitempty"`
	// gt or lt
	Op   string `json:"op,omitempty"`
	Fill bool   `json:"fill"`
	Line bool   `json:"line"`
	// hexadecimal color (e.g. #629e51, only when ColorMode is "custom")
	FillColor string `json:"fillColor,omitempty"`
	// hexadecimal color (e.g. #629e51, only when ColorMode is "custom")
	LineColor string `json:"lineColor,omitempty"`
	// left or right
	Yaxis string `json:"yaxis,omitempty"`
}

type Time

type Time struct {
	From string `json:"from"`
	To   string `json:"to"`
}

type Timepicker

type Timepicker struct {
	Now              *bool    `json:"now,omitempty"`
	RefreshIntervals []string `json:"refresh_intervals"`
	TimeOptions      []string `json:"time_options"`
}

type Tooltip

type Tooltip struct {
	Shared       bool   `json:"shared"`
	ValueType    string `json:"value_type"`
	MsResolution bool   `json:"msResolution,omitempty"` // was added in Grafana 3.x
	Sort         int    `json:"sort,omitempty"`
}

type User

type User struct {
	ID             uint   `json:"id"`
	Login          string `json:"login"`
	Name           string `json:"name"`
	Email          string `json:"email"`
	Theme          string `json:"theme"`
	OrgID          uint   `json:"orgId"`
	Password       string `json:"password"`
	IsGrafanaAdmin bool   `json:"isGrafanaAdmin"`
}

type UserPermissions

type UserPermissions struct {
	IsGrafanaAdmin bool `json:"isGrafanaAdmin"`
}

type UserRole

type UserRole struct {
	LoginOrEmail string `json:"loginOrEmail"`
	Role         string `json:"role"`
}

type ValueMap

type ValueMap struct {
	Op       string `json:"op"`
	TextType string `json:"text"`
	Value    string `json:"value"`
}

for a singlestat

Directories

Path Synopsis
cmd
backup-dashboards
This is a simple example of usage of Grafana client for copying dashboards and saving them to a disk.
This is a simple example of usage of Grafana client for copying dashboards and saving them to a disk.
backup-datasources
This is a simple example of usage of Grafana client for copying dashboards and saving them to a disk.
This is a simple example of usage of Grafana client for copying dashboards and saving them to a disk.
import-dashboards
This is a simple example of usage of Grafana client for importing dashboards from a bunch of JSON files (current dir used).
This is a simple example of usage of Grafana client for importing dashboards from a bunch of JSON files (current dir used).
import-dashboards-raw
This is a simple example of usage of Grafana sdk for importing dashboards from a bunch of JSON files (current dir used).
This is a simple example of usage of Grafana sdk for importing dashboards from a bunch of JSON files (current dir used).
import-datasources
This is a simple example of usage of Grafana client for importing datasources from a bunch of JSON files (current dir used).
This is a simple example of usage of Grafana client for importing datasources from a bunch of JSON files (current dir used).

Jump to

Keyboard shortcuts

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