gapi

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2018 License: Apache-2.0 Imports: 11 Imported by: 3

README

Golang Grafana API

Grafana HTTP API Client for Golang. Based of the 4.6 version of the API: http://docs.grafana.org/v4.6/http_api

Installation

$ go get github.com/AutogrowSystems/go-grafana-api

Usage

First create a client, you can use an API key or username:pass auth for the first argument, but be aware that the API key is not supported for some API endpoints. See the documentation for more info.

client, err := gapi.New("username:pass", "http://localhost:3000")

Once you have the client, you can perform various operations:

org, err := client.NewOrg("freds beaver tanks")
fmt.Println(org.Id)

datasources, err := org.DataSources(client)
ds = datasources[0]
ds.IsDefault = true

if err := client.UpdateDataSource(ds); err != nil {
    panic(err)
}

See the documentation for other methods.

CLI Usage

There is also a CLI tool that comes with the package called gapi. It's experimental and will probably change a lot in the future (aiming towards outputting more JSON).

List all orgs:

$ gapi -org -list
1       Main Org.
2       freds beaver tanks

Add a new org:

$ gapi -org -create -name "horse monkey"
2018/03/01 22:58:36 created new org with ID 3
3

Note that the log output goes to stderr and the org ID goes to stdout.

Add a new datasource:

$ cat newdatasource.json | gapi -datasource -create

Tests

To run the tests:

go test

Documentation

Index

Constants

View Source
const (
	// OrgUserRoleViewer is the readonly role
	OrgUserRoleViewer = "Viewer"
	// OrgUserRoleAdmin is the admin role
	OrgUserRoleAdmin = "Admin"
	// OrgUserRoleEditor is the editing role
	OrgUserRoleEditor = "Editor"
)

Variables

View Source
var (
	// ErrNotFound 404
	ErrNotFound = errors.New(http.StatusText(404))
	// ErrConflict 409
	ErrConflict = errors.New(http.StatusText(409))
	// ErrNotImplemented 501
	ErrNotImplemented = errors.New(http.StatusText(501))
	// ErrNotAuthorized 401
	ErrNotAuthorized = errors.New(http.StatusText(401))
	// ErrInternalServerError 500
	ErrInternalServerError = errors.New(http.StatusText(500))
)
View Source
var ErrInvalidUserRole = fmt.Errorf("invalid user role")

ErrInvalidUserRole will be returned when a org user role is unknown

View Source
var UserRoleIsValid = IsUserRoleValid

UserRoleIsValid is deprecated in preference to IsUserRoleValid

Functions

func AutoFixRole

func AutoFixRole(role string) string

AutoFixRole will attempt to automatically fix common issues when setting user roles using strings. It will titleize and correct the miss-spelling of viewer

func IsUserRoleValid

func IsUserRoleValid(role string) bool

IsUserRoleValid will return true if the given role is valid

Types

type AdminCreateUserForm added in v1.0.0

type AdminCreateUserForm struct {
	Email    string `json:"email"`
	Login    string `json:"login"`
	Name     string `json:"name"`
	Password string `json:"password" binding:"Required"`
}

AdminCreateUserForm is used to create a new user

type AlertNotification

type AlertNotification struct {
	ID        int64       `json:"id,omitempty"`
	Name      string      `json:"name"`
	Type      string      `json:"type"`
	IsDefault bool        `json:"isDefault"`
	Settings  interface{} `json:"settings"`
}

AlertNotification represents a Grafana alert notification

type Client

type Client struct {
	LastStatusCode int
	*http.Client
	// contains filtered or unexported fields
}

Client represents a Grafana API client

func New

func New(auth, baseURL string) (*Client, error)

New creates a new grafana client auth can be in user:pass format, or it can be an api key

func (*Client) ActualUser added in v1.1.0

func (c *Client) ActualUser() (*User, error)

ActualUser will return the actual user that is logged into the API

func (*Client) AlertNotification

func (c *Client) AlertNotification(id int64) (*AlertNotification, error)

AlertNotification gets the alert with the given ID from Grafana

func (*Client) AlertNotifications

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

AlertNotifications returns all notifications for the actual/current org

func (*Client) CreateUser

func (c *Client) CreateUser(u User) error

CreateUser creates a new user by wrapping the CreateUserForm method to avoiding requiring a dependency on Grafana code in your code

func (*Client) CreateUserForm

func (c *Client) CreateUserForm(settings AdminCreateUserForm) error

CreateUserForm will create a user from the given form

func (*Client) Dashboard

func (c *Client) Dashboard(slug string) (*Dashboard, error)

Dashboard gets the dashboard with the given URI from Grafana

func (*Client) DashboardMetas

func (c *Client) DashboardMetas() ([]*DashboardMeta, error)

DashboardMetas returns the dashboard metadata for the current organisation context. These can then be used to get specific dashboards

func (*Client) Dashboards

func (c *Client) Dashboards() ([]*Dashboard, error)

Dashboards returns the dashboards for the current org

func (*Client) DataSource

func (c *Client) DataSource(id int64) (*DataSource, error)

DataSource will return the datasource with the given ID

func (*Client) DataSources

func (c *Client) DataSources() ([]*DataSource, error)

DataSources will return all the datasources from Grafana

func (*Client) DataSourcesByOrgID

func (c *Client) DataSourcesByOrgID(id int64) ([]*DataSource, error)

DataSourcesByOrgID will return the datasources for the given org ID

func (*Client) DeleteAlertNotification

func (c *Client) DeleteAlertNotification(id int64) error

DeleteAlertNotification will delete the alert notification from Grafana matching the given ID

func (*Client) DeleteDashboard

func (c *Client) DeleteDashboard(uri string) error

DeleteDashboard will delete the dashboard with the given slug from Grafana

func (*Client) DeleteDataSource

func (c *Client) DeleteDataSource(id int64) error

DeleteDataSource will delete the datasource with the given ID from Grafana

func (*Client) DeleteOrg

func (c *Client) DeleteOrg(id int64) error

DeleteOrg deletes the given org ID from Grafana

func (*Client) DeleteUser

func (c *Client) DeleteUser(id int64) error

DeleteUser deletes the user with the given ID from Grafana

func (*Client) Do

func (c *Client) Do(req *http.Request) (*http.Response, error)

Do overrides the Do method to hook in a response logger before returning the response

func (*Client) FrontEndSettings

func (c *Client) FrontEndSettings() (map[string]interface{}, error)

FrontEndSettings will get the front end settings from the API

func (*Client) GetCurrentOrgPrefs added in v1.1.0

func (c *Client) GetCurrentOrgPrefs() (*OrgPrefs, error)

GetCurrentOrgPrefs will get the preferences for the organisation in the current context, as selected by the SwitchContext method

func (*Client) NewAlertNotification

func (c *Client) NewAlertNotification(a *AlertNotification) (int64, error)

NewAlertNotification creates the given alert notification object in Grafana

func (*Client) NewDataSource

func (c *Client) NewDataSource(s *DataSource) (int64, error)

NewDataSource will create the given data source in Grafana

func (*Client) NewOrg

func (c *Client) NewOrg(name string) (Org, error)

NewOrg creates an Org with the given name in Grafana

func (*Client) NewUser

func (c *Client) NewUser(u User) error

NewUser is DEPRECATED

func (*Client) Org

func (c *Client) Org(id int64) (Org, error)

Org returns the organisation with the given ID

func (*Client) OrgByName

func (c *Client) OrgByName(name string) (Org, error)

OrgByName returns the organisation with the given name

func (*Client) Orgs

func (c *Client) Orgs() ([]Org, error)

Orgs returns all the orgs in Grafana

func (*Client) SaveDashboard

func (c *Client) SaveDashboard(model map[string]interface{}, overwrite bool) (*DashboardSaveResponse, error)

SaveDashboard saves the given dashboard model to the API

func (*Client) SaveUser

func (c *Client) SaveUser(u *User) error

SaveUser will save the given user to the API

func (*Client) SearchDashboards added in v1.1.0

func (c *Client) SearchDashboards(query string, tag string, starred bool) ([]*DashboardMeta, error)

SearchDashboards allows to search via query, tag or starred dashboards

func (*Client) SetUserAdmin

func (c *Client) SetUserAdmin(id int64, admin bool) error

SetUserAdmin will set the given user ID as an admin

func (*Client) Stats

func (c *Client) Stats() (map[string]int64, error)

Stats will get the stats from the API

func (*Client) SwitchCurrentUserOrg

func (c *Client) SwitchCurrentUserOrg(orgID int64) error

SwitchCurrentUserOrg will switch the current organisation of the signed in user

func (*Client) SwitchUserOrg

func (c *Client) SwitchUserOrg(userID, orgID int64) error

SwitchUserOrg will switch the current organisation of the given user ID (via basic auth) to the given organisation ID

func (*Client) UpdateAlertNotification

func (c *Client) UpdateAlertNotification(a *AlertNotification) error

UpdateAlertNotification wll update the alert notification in Grafana that matches the ID from the given alert notification object

func (*Client) UpdateCurrentOrgPrefs added in v1.1.0

func (c *Client) UpdateCurrentOrgPrefs(prefs *OrgPrefs) error

UpdateCurrentOrgPrefs will update the preferences of the organisation in the current context, as selected by the SwitchContext method

func (*Client) UpdateDataSource

func (c *Client) UpdateDataSource(s *DataSource) error

UpdateDataSource will update the data source in Grafana from the given datasource object that matches the given datasource objects ID

func (*Client) UpdateOrgUserRole

func (c *Client) UpdateOrgUserRole(orgID, userID int64, role string) error

UpdateOrgUserRole will update the role for the given user on the given org

func (*Client) User

func (c *Client) User(id int64) (*User, error)

User returns the user with the given id

func (*Client) UserByEmail

func (c *Client) UserByEmail(email string) (*User, error)

UserByEmail will find a user by their email address

func (*Client) UserByLogin

func (c *Client) UserByLogin(login string) (*User, error)

UserByLogin will find a user by their login

func (*Client) Users

func (c *Client) Users() ([]*User, error)

Users returns all the users from Grafana

type Dashboard

type Dashboard struct {
	Meta  DashboardMeta          `json:"meta"`
	Model map[string]interface{} `json:"dashboard"`
}

Dashboard represents a Grafana dashboard

func NewDashboard

func NewDashboard() *Dashboard

NewDashboard creates a new blank dashboard

func (*Dashboard) AddTags

func (d *Dashboard) AddTags(newtags ...string)

AddTags will add the given tags to the dashboard

func (*Dashboard) RemoveTags

func (d *Dashboard) RemoveTags(deltags ...string)

RemoveTags will remove the given tags to the dashboard

func (*Dashboard) SetTags

func (d *Dashboard) SetTags(newtags ...string)

SetTags will set the given tags on the dashboard (deleting all others)

func (*Dashboard) Tags

func (d *Dashboard) Tags() []string

Tags returns the tags for the dashboard

func (Dashboard) Title

func (d Dashboard) Title() (string, bool)

Title returns the title of the dashboard

type DashboardMeta

type DashboardMeta struct {
	IsStarred bool     `json:"isStarred"`
	ID        int64    `json:"id"`
	Slug      string   `json:"slug"`
	Title     string   `json:"title"`
	URI       string   `json:"uri"`
	Type      string   `json:"type"`
	Tags      []string `json:"tags"`
}

DashboardMeta holds dashboard metadata

func (*DashboardMeta) SetSlug added in v1.1.0

func (meta *DashboardMeta) SetSlug()

type DashboardSaveResponse

type DashboardSaveResponse struct {
	ID      int64  `json:"id"`
	UID     int64  `json:"uid"`
	URL     string `json:"url"`
	Status  string `json:"status"`
	Version int64  `json:"version"`
	Slug    string `json:"slug"`
}

DashboardSaveResponse represents the response from the API when a dashboard is saved

type DataSource

type DataSource struct {
	ID          int64  `json:"id,omitempty"`
	Name        string `json:"name"`
	Type        string `json:"type"`
	TypeLogoURL string `json:"typeLogoUrl"`
	URL         string `json:"url"`
	Access      string `json:"access"`

	Database string `json:"database,omitempty"`
	User     string `json:"user,omitempty"`
	Password string `json:"password,omitempty"`

	OrgID     int64 `json:"orgId,omitempty"`
	IsDefault bool  `json:"isDefault"`

	BasicAuth         bool   `json:"basicAuth"`
	BasicAuthUser     string `json:"basicAuthUser,omitempty"`
	BasicAuthPassword string `json:"basicAuthPassword,omitempty"`

	JSONData       JSONData       `json:"jsonData,omitempty"`
	SecureJSONData SecureJSONData `json:"secureJsonData,omitempty"`
}

DataSource represents a Grafana data source

type JSONData

type JSONData struct {
	AssumeRoleArn string `json:"assumeRoleArn,omitempty"`
	AuthType      string `json:"authType,omitempty"`
	DefaultRegion string `json:"defaultRegion,omitempty"`
}

JSONData is a representation of the datasource `jsonData` property

type Org

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

Org represents an Organisation object in Grafana

func (Org) AddUser

func (o Org) AddUser(c *Client, username, role string) error

AddUser will add a user to the organisation

func (Org) DataSources

func (o Org) DataSources(c OrgDataSourceGetter) ([]*DataSource, error)

DataSources use the given client to return the datasources for the organisation

func (Org) RemoveUser

func (o Org) RemoveUser(c *Client, userID int64) error

RemoveUser removes the user from the organisation

func (Org) SetHomeDashboard added in v1.1.0

func (o Org) SetHomeDashboard(c *Client, dashID int64) error

SetHomeDashboard will set the home dashboard of the organisation

func (Org) String

func (o Org) String() string

func (Org) Users

func (o Org) Users(c *Client) ([]*OrgUser, error)

Users use the given client to return the users for the organisation

type OrgDataSourceGetter

type OrgDataSourceGetter interface {
	DataSourcesByOrgID(int64) ([]*DataSource, error)
}

OrgDataSourceGetter allows getting datasources using an org ID

type OrgPrefs added in v1.1.0

type OrgPrefs struct {
	Theme           string `json:"theme"`
	HomeDashboardID int64  `json:"homeDashboardId"`
	Timezone        string `json:"timezone"`
}

OrgPrefs represents the organisation preferences

type OrgUser

type OrgUser struct {
	User
	ID    int64  `json:"userId"`
	Role  string `json:"role"`
	OrgID int64  `json:"orgId"`
}

OrgUser is a user of the org

func (OrgUser) UpdateRole

func (ouser OrgUser) UpdateRole(c *Client, role string) error

UpdateRole will update the role of the org user to the one given

type OrgUsers

type OrgUsers []*OrgUser

OrgUsers is a collection of Org user models

func (OrgUsers) FindByLogin

func (ousers OrgUsers) FindByLogin(login string) (*OrgUser, bool)

FindByLogin returns the org user with the given email from a collection of org users, and a false if it was not found

func (OrgUsers) Users

func (ousers OrgUsers) Users() []*User

Users returns the user objects from a collection of org users

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

Response is an API response

func NewResponse

func NewResponse(res *http.Response, rerr error) *Response

NewResponse returns a new grafana API response

func (*Response) BindJSON

func (res *Response) BindJSON(v interface{}) error

BindJSON unmarshals the body into the given interface

func (*Response) Error

func (res *Response) Error() error

func (*Response) Message

func (res *Response) Message() string

Message returns the message from the

func (*Response) OK

func (res *Response) OK() bool

OK is true if there is no error

type SecureJSONData

type SecureJSONData struct {
	AccessKey string `json:"accessKey,omitempty"`
	SecretKey string `json:"secretKey,omitempty"`
}

SecureJSONData is a representation of the datasource `secureJsonData` property

type Tags

type Tags map[string]bool

Tags represents a set of tags

func NewTags

func NewTags(tagslice []string) Tags

NewTags creates a new Tags object from the given string slice

func (Tags) Add

func (t Tags) Add(tags ...string)

Add will add the given tags to the Tag list

func (Tags) Remove

func (t Tags) Remove(tags ...string)

Remove will remote the given tags to the Tag list

func (Tags) Set

func (t Tags) Set(tags ...string)

Set will delete all existing tags, and add the given tags

func (Tags) Strings

func (t Tags) Strings() []string

Strings will give back the tags as a string slice

type User

type User struct {
	ID       int64  `json:"id"`
	Email    string `json:"email"`
	Name     string `json:"name"`
	Login    string `json:"login"`
	OrgID    int64  `json:"orgId"`
	IsAdmin  bool   `json:"isGrafanaAdmin"` // TODO: handle isAdmin returned from /api/users
	Password string `json:"password,omitempty"`
}

User represents a Grafana user

func (User) AddToAllOrgs

func (u User) AddToAllOrgs(c *Client, role string) error

AddToAllOrgs will add the user to all orgs with the given role

func (User) MakeGlobalAdmin

func (u User) MakeGlobalAdmin(c *Client) error

MakeGlobalAdmin assigns the user to all orgs with an Admin role

func (User) MakeGlobalEditor

func (u User) MakeGlobalEditor(c *Client) error

MakeGlobalEditor assigns the user to all orgs with a Editor role

func (User) MakeGlobalViewer

func (u User) MakeGlobalViewer(c *Client) error

MakeGlobalViewer assigns the user to all orgs with a Viewer role

func (User) RemoveFromAllOrgs

func (u User) RemoveFromAllOrgs(c *Client) error

RemoveFromAllOrgs will remove the user from all the orgs that they have a current role in

func (User) SwitchOrg

func (u User) SwitchOrg(c *Client, orgID int64) error

SwitchOrg will change the current org context for the user

type Users

type Users []*User

Users is a collection of user models

func (Users) FindByEmail

func (users Users) FindByEmail(email string) (*User, bool)

FindByEmail returns the user with the given email from a collection of users, and a false if it was not found

func (Users) FindByLogin

func (users Users) FindByLogin(login string) (*User, bool)

FindByLogin returns the user with the given email from a collection of users, and a false if it was not found

func (Users) FindIndexByEmail

func (users Users) FindIndexByEmail(email string) (int, bool)

FindIndexByEmail is like FindByEmail but it returns the index

func (Users) FindIndexByLogin

func (users Users) FindIndexByLogin(login string) (int, bool)

FindIndexByLogin is like FindByEmail but it returns the index

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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