gapi

package module
v0.0.0-...-d48887f Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2018 License: Apache-2.0 Imports: 12 Imported by: 0

README

Golang Grafana API

Grafana HTTP API Client for Go

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))
)

Functions

func AutoFixRole

func AutoFixRole(role string) string

func UserRoleIsValid

func UserRoleIsValid(role string) bool

UserRoleIsValid will return true if the given role is valid

Types

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) AlertNotification

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

AlertNotification gets the alert with the given ID from Grafana

func (*Client) CreateUserForm

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

CreateUserForm will create a user from the given form

func (*Client) Dashboard

func (c *Client) Dashboard(uri 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) 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 creates a new user by wrapping the CreateUserForm method to avoiding requiring a dependency on Grafana code in your code

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) 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 (uses basic auth)

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) 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) 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"`
	Slug      string   `json:"slug"`
	Title     string   `json:"title"`
	URI       string   `json:"uri"`
	Type      string   `json:"type"`
	Tags      []string `json:"tags"`
}

DashboardMeta holds dashboard metadata

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

type OrgUser

type OrgUser struct {
	User
	Role  string `json:"role"`
	OrgID int64  `json:"org_id"`
}

OrgUser is a user of the org

type OrgUsers

type OrgUsers []*OrgUser

OrgUsers is a collection of Org user models

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    string `json:"org_id"`
	IsAdmin  bool   `json:"isGrafanaAdmin"` // TODO: handle isAdmin returned from /api/users
	Password string `json:"password,omitempty"`
}

User represents a Grafana user

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