Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Alin Sinpalean 2017-09-07 20:26:28 +02:00
commit 567e877b9e
23 changed files with 244 additions and 138 deletions

View File

@ -9,6 +9,10 @@
# 4.5.0 (unreleased)
## Enhancements
* **Shortcuts**: Adds shortcut for creating new dashboard [#8876](https://github.com/grafana/grafana/pull/8876) thx [@mtanda](https://github.com/mtanda)
# 4.5.0-beta1 (2017-09-05)
## New Features

View File

@ -9,65 +9,8 @@ Graphite, Elasticsearch, OpenTSDB, Prometheus and InfluxDB.
![](http://docs.grafana.org/assets/img/features/dashboard_ex1.png)
- [Install instructions](http://docs.grafana.org/installation/)
- [What's New in Grafana 2.0](http://docs.grafana.org/guides/whats-new-in-v2/)
- [What's New in Grafana 2.1](http://docs.grafana.org/guides/whats-new-in-v2-1/)
- [What's New in Grafana 2.5](http://docs.grafana.org/guides/whats-new-in-v2-5/)
- [What's New in Grafana 3.0](http://docs.grafana.org/guides/whats-new-in-v3/)
- [What's New in Grafana 4.0](http://docs.grafana.org/guides/whats-new-in-v4/)
- [What's New in Grafana 4.1](http://docs.grafana.org/guides/whats-new-in-v4-1/)
- [What's New in Grafana 4.2](http://docs.grafana.org/guides/whats-new-in-v4-2/)
- [What's New in Grafana 4.3](http://docs.grafana.org/guides/whats-new-in-v4-3/)
- [What's New in Grafana 4.4](http://docs.grafana.org/guides/whats-new-in-v4-4/)
## Features
### Graphing
- Fast rendering, even over large timespans
- Click and drag to zoom
- Multiple Y-axis, logarithmic scales
- Bars, Lines, Points
- Smart Y-axis formatting
- Series toggles & color selector
- Legend values, and formatting options
- Grid thresholds, axis labels
- [Annotations](http://docs.grafana.org/reference/annotations/)
- Any panel can be rendered to PNG (server side using phantomjs)
### Dashboards
- Create, edit, save & search dashboards
- Change column spans and row heights
- Drag and drop panels to rearrange
- [Templating](http://docs.grafana.org/reference/templating/)
- [Scripted dashboards](http://docs.grafana.org/reference/scripting/)
- [Dashboard playlists](http://docs.grafana.org/reference/playlist/)
- [Time range controls](http://docs.grafana.org/reference/timerange/)
- [Share snapshots publicly](http://docs.grafana.org/v2.0/reference/sharing/)
### InfluxDB
- Use InfluxDB as a metric data source, annotation source
- Query editor with field and tag typeahead, easy group by and function selection
### Graphite
- Graphite target expression parser
- Feature rich query composer
- Quickly add and edit functions & parameters
- Templated queries
- [See it in action](http://docs.grafana.org/datasources/graphite/)
### Elasticsearch, Prometheus & OpenTSDB
- Feature rich query editor UI
### Alerting
- Define alert rules using graphs & query conditions
- Schedule & evalute alert rules, send notifications to Slack, Hipchat, Email, PagerDuty, etc.
## Requirements
There are no dependencies except an external time series data store. For dashboards and user accounts Grafana can use an embedded
database (sqlite3) or you can use an external SQL data base like MySQL or Postgres.
## Installation
Head to [grafana.org](http://docs.grafana.org/installation/) and [download](https://grafana.com/get)
Head to [docs.grafana.org](http://docs.grafana.org/installation/) and [download](https://grafana.com/get)
the latest release.
If you have any problems please read the [troubleshooting guide](http://docs.grafana.org/installation/troubleshooting/).
@ -84,27 +27,10 @@ the latest master builds [here](https://grafana.com/grafana/download)
- Go 1.8.1
- NodeJS LTS
### Get Code
```bash
go get github.com/grafana/grafana
```
Since imports of dependencies use the absolute path `github.com/grafana/grafana` within the `$GOPATH`,
you will need to put your version of the code in `$GOPATH/src/github.com/grafana/grafana` to be able
to develop and build grafana on a cloned repository. To do so, you can clone your forked repository
directly to `$GOPATH/src/github.com/grafana` or you can create a symbolic link from your version
of the code to `$GOPATH/src/github.com/grafana/grafana`. The last options makes it possible to change
easily the grafana repository you want to build.
```bash
go get github.com/*your_account*/grafana
mkdir $GOPATH/src/github.com/grafana
ln -s $GOPATH/src/github.com/*your_account*/grafana $GOPATH/src/github.com/grafana/grafana
```
### Building the backend
```bash
cd $GOPATH/src/github.com/grafana/grafana
go get github.com/grafana/grafana
cd ~/go/src/github.com/grafana/grafana
go run build.go setup
go run build.go build
```
@ -123,8 +49,7 @@ npm run build
To build the frontend assets only on changes:
```bash
sudo npm install -g grunt-cli # to do only once to install grunt command line interface
grunt && grunt watch
npm run dev
```
### Recompile backend on source change
@ -134,11 +59,6 @@ go get github.com/Unknwon/bra
bra run
```
### Running
```bash
./bin/grafana-server
```
Open grafana in your browser (default: `http://localhost:3000`) and login with admin user (default: `user/pass = admin/admin`).
### Dev config
@ -149,9 +69,6 @@ You only need to add the options you want to override. Config files are applied
1. grafana.ini
1. custom.ini
## Create a pull request
Before or after you create a pull request, sign the [contributor license agreement](http://docs.grafana.org/project/cla/).
## Contribute
If you have any idea for an improvement or found a bug do not hesitate to open an issue.
And if you have time clone this repo and submit a pull request and help me make Grafana

View File

@ -13,6 +13,7 @@ Here you can find links to older versions of the documentation that might be bet
of Grafana.
- [Latest](http://docs.grafana.org)
- [Version 4.4](http://docs.grafana.org/v4.4)
- [Version 4.3](http://docs.grafana.org/v4.3)
- [Version 4.2](http://docs.grafana.org/v4.2)
- [Version 4.1](http://docs.grafana.org/v4.1)

View File

@ -24,9 +24,9 @@ Read the [Basic Concepts](/guides/basic_concepts) document to get a crash course
### Top header
Let's start with creating a new Dashboard. You can find the new Dashboard link at the bottom of the Dashboard picker. You now have a blank Dashboard.
Let's start with creating a new Dashboard. You can find the new Dashboard link on the right side of the Dashboard picker. You now have a blank Dashboard.
<img class="no-shadow" src="/img/docs/v2/v2_top_nav_annotated.png">
<img class="no-shadow" src="/img/docs/v45/top_nav_annotated.png">
The image above shows you the top header for a Dashboard.
@ -41,19 +41,7 @@ The image above shows you the top header for a Dashboard.
Dashboards are at the core of what Grafana is all about. Dashboards are composed of individual Panels arranged on a number of Rows. Grafana ships with a variety of Panels. Grafana makes it easy to construct the right queries, and customize the display properties so that you can create the perfect Dashboard for your need. Each Panel can interact with data from any configured Grafana Data Source (currently InfluxDB, Graphite, OpenTSDB, Prometheus and Cloudwatch). The [Basic Concepts](/guides/basic_concepts) guide explores these key ideas in detail.
## Adding & Editing Graphs and Panels
![](/img/docs/v2/graph_metrics_tab_graphite.png)
1. You add panels via row menu. The row menu is the green icon to the left of each row.
2. To edit the graph you click on the graph title to open the panel menu, then `Edit`.
3. This should take you to the `Metrics` tab. In this tab you should see the editor for your default data source.
When you click the `Metrics` tab, you are presented with a Query Editor that is specific to the Panel Data Source. Use the Query Editor to build your queries and Grafana will visualize them in real time.
<img src="/img/docs/v2/dashboard_annotated.png" class="no-shadow">
<img src="/img/docs/v45/dashboard_annotated.png" class="no-shadow">
1. Zoom out time range
2. Time picker dropdown. Here you can access relative time range options, auto refresh options and set custom absolute time ranges.
@ -62,6 +50,17 @@ When you click the `Metrics` tab, you are presented with a Query Editor that is
5. Dashboard panel. You edit panels by clicking the panel title.
6. Graph legend. You can change series colors, y-axis and series visibility directly from the legend.
## Adding & Editing Graphs and Panels
![](/img/docs/v45/metrics_tab.png)
1. You add panels via row menu. The row menu is the icon to the left of each row.
2. To edit the graph you click on the graph title to open the panel menu, then `Edit`.
3. This should take you to the `Metrics` tab. In this tab you should see the editor for your default data source.
When you click the `Metrics` tab, you are presented with a Query Editor that is specific to the Panel Data Source. Use the Query Editor to build your queries and Grafana will visualize them in real time.
## Drag-and-Drop panels
You can Drag-and-Drop Panels within and between Rows. Click and hold the Panel title, and drag it to its new location. You can also easily resize panels by clicking the (-) and (+) icons.

View File

@ -0,0 +1,74 @@
+++
title = "What's New in Grafana v4.5"
description = "Feature & improvement highlights for Grafana v4.5"
keywords = ["grafana", "new", "documentation", "4.5"]
type = "docs"
[menu.docs]
name = "Version 4.5"
identifier = "v4.5"
parent = "whatsnew"
weight = -4
+++
# What's New in Grafana v4.5
## Hightlights
### New prometheus query editor
The new query editor has full syntax highlighting. As well as auto complete for metrics, functions, and range vectors.
![](/img/docs/v45/new_prom_editor_1.png)
There is also integrated function docs right from the query editor!
![](/img/docs/v45/new_prom_editor_2.png)
### Elasticsearch: Add ad-hoc filters from the table panel
![](/img/docs/v45/elastic_ad_hoc_filters.png)
### Table cell links!
Create column styles that turn cells into links that use the value in the cell (or other other row values) to generate a url to another dashboard or system:
![](/img/docs/v45/table_links.jpg)
### Query Inspector
Query Inspector is a new feature that shows query requests and responses. This can be helpful if a graph is not shown or shows something very different than what you expected.
More information [here](https://community.grafana.com/t/using-grafanas-query-inspector-to-troubleshoot-issues/2630).
![](/img/docs/v45/query_inspector.png)
## Changelog
### New Features
* **Table panel**: Render cell values as links that can have an url template that uses variables from current table row. [#3754](https://github.com/grafana/grafana/issues/3754)
* **Elasticsearch**: Add ad hoc filters directly by clicking values in table panel [#8052](https://github.com/grafana/grafana/issues/8052).
* **MySQL**: New rich query editor with syntax highlighting
* **Prometheus**: New rich query editor with syntax highlighting, metric & range auto complete and integrated function docs. [#5117](https://github.com/grafana/grafana/issues/5117)
### Enhancements
* **GitHub OAuth**: Support for GitHub organizations with 100+ teams. [#8846](https://github.com/grafana/grafana/issues/8846), thx [@skwashd](https://github.com/skwashd)
* **Graphite**: Calls to Graphite api /metrics/find now include panel or dashboad time range (from & until) in most cases, [#8055](https://github.com/grafana/grafana/issues/8055)
* **Graphite**: Added new graphite 1.0 functions, available if you set version to 1.0.x in data source settings. New Functions: mapSeries, reduceSeries, isNonNull, groupByNodes, offsetToZero, grep, weightedAverage, removeEmptySeries, aggregateLine, averageOutsidePercentile, delay, exponentialMovingAverage, fallbackSeries, integralByInterval, interpolate, invert, linearRegression, movingMin, movingMax, movingSum, multiplySeriesWithWildcards, pow, powSeries, removeBetweenPercentile, squareRoot, timeSlice, closes [#8261](https://github.com/grafana/grafana/issues/8261)
- **Elasticsearch**: Ad-hoc filters now use query phrase match filters instead of term filters, works on non keyword/raw fields [#9095](https://github.com/grafana/grafana/issues/9095).
### Breaking change
* **InfluxDB/Elasticsearch**: The panel & data source option named "Group by time interval" is now named "Min time interval" and does now always define a lower limit for the auto group by time. Without having to use `>` prefix (that prefix still works). This should in theory have close to zero actual impact on existing dashboards. It does mean that if you used this setting to define a hard group by time interval of, say "1d", if you zoomed to a time range wide enough the time range could increase above the "1d" range as the setting is now always considered a lower limit.
This option is now rennamed (and moved to Options sub section above your queries):
![image|519x120](upload://ySjHOVpavV6yk9LHQxL9nq2HIsT.png)
Datas source selection & options & help are now above your metric queries.
![image|690x179](upload://5kNDxKgMz1BycOKgG3iWYLsEVXv.png)
### Minor Changes
* **InfluxDB**: Change time range filter for absolute time ranges to be inclusive instead of exclusive [#8319](https://github.com/grafana/grafana/issues/8319), thx [@Oxydros](https://github.com/Oxydros)
* **InfluxDB**: Added paranthesis around tag filters in queries [#9131](https://github.com/grafana/grafana/pull/9131)
## Bug Fixes
* **Modals**: Maintain scroll position after opening/leaving modal [#8800](https://github.com/grafana/grafana/issues/8800)
* **Templating**: You cannot select data source variables as data source for other template variables [#7510](https://github.com/grafana/grafana/issues/7510)

View File

@ -137,7 +137,7 @@ parent = "http_api"
`POST /api/datasources`
**Example Request**:
**Example Graphite Request**:
POST /api/datasources HTTP/1.1
Accept: application/json
@ -152,6 +152,28 @@ parent = "http_api"
"basicAuth":false
}
**Example CloudWatch Request**:
```
POST /api/datasources HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk
{
"name": "test_datasource",
"type": "cloudwatch",
"url": "http://monitoring.us-west-1.amazonaws.com",
"access": "proxy",
"jsonData": {
"authType": "keys",
"defaultRegion": "us-west-1"
},
"secureJsonData": {
"accessKey": "Ol4pIDpeKSA6XikgOl4p",
"secretKey": "dGVzdCBrZXkgYmxlYXNlIGRvbid0IHN0ZWFs"
}
}
```
**Example Response**:

View File

@ -16,6 +16,7 @@ weight = 1
Description | Download
------------ | -------------
Stable for Debian-based Linux | [grafana_4.4.3_amd64.deb](https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_4.4.3_amd64.deb)
Beta for Debian-based Linux | [grafana_4.5.0-beta1_amd64.deb](https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_4.5.0-beta1_amd64.deb)
Read [Upgrading Grafana]({{< relref "installation/upgrading.md" >}}) for tips and guidance on updating an existing
installation.
@ -28,15 +29,13 @@ sudo apt-get install -y adduser libfontconfig
sudo dpkg -i grafana_4.4.3_amd64.deb
```
<!--
## Install Beta
## Install Latest Beta
```bash
wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_4.3.0-beta1_amd64.deb
wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_4.5.0-beta1_amd64.deb
sudo apt-get install -y adduser libfontconfig
sudo dpkg -i grafana_4.3.0-beta1_amd64.deb
sudo dpkg -i grafana_4.5.0-beta1_amd64.deb
```
-->
## APT Repository

View File

@ -16,6 +16,7 @@ weight = 2
Description | Download
------------ | -------------
Stable for CentOS / Fedora / OpenSuse / Redhat Linux | [4.4.3 (x86-64 rpm)](https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana-4.4.3-1.x86_64.rpm)
Latest Beta for CentOS / Fedora / OpenSuse / Redhat Linux | [4.5.0-beta1 (x86-64 rpm)](https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana-4.5.0-beta1.x86_64.rpm)
Read [Upgrading Grafana]({{< relref "installation/upgrading.md" >}}) for tips and guidance on updating an existing
installation.

View File

@ -11,13 +11,18 @@ weight = 8
# Troubleshooting
## visualization & query issues
## Visualization & Query issues
{{< imgbox max-width="40%" img="/img/docs/v45/query_inspector.png" caption="Query Inspector" >}}
The most common problems are related to the query & response from you data source. Even if it looks
like a bug or visualization issue in Grafana it is 99% of time a problem with the data source query or
the data source response.
So make sure to check the query sent and the raw response, learn how in this guide: [How to troubleshoot metric query issues](https://community.grafana.com/t/how-to-troubleshoot-metric-query-issues/50)
To check this you should use Query Inspector (new in Grafana v4.5). The query Inspector shows query requests and responses.
For more on the query insector read [this guide here](https://community.grafana.com/t/using-grafanas-query-inspector-to-troubleshoot-issues/2630). For
older versions of Grafana read the [how troubleshoot metric query issue](https://community.grafana.com/t/how-to-troubleshoot-metric-query-issues/50/2) article.
## Logging

View File

@ -59,7 +59,8 @@
},
"scripts": {
"build": "./node_modules/grunt-cli/bin/grunt",
"test": "./node_modules/grunt-cli/bin/grunt test"
"test": "./node_modules/grunt-cli/bin/grunt test",
"dev": "./node_modules/grunt-cli/bin/grunt && ./node_modules/grunt-cli/bin/grunt watch"
},
"license": "Apache-2.0",
"dependencies": {

View File

@ -1,10 +1,10 @@
#! /usr/bin/env bash
deb_ver=4.3.0-beta1
rpm_ver=4.3.0-beta1
deb_ver=4.5.0-beta1
rpm_ver=4.5.0-beta1
wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_${deb_ver}_amd64.deb
# wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_${deb_ver}_amd64.deb
package_cloud push grafana/testing/debian/jessie grafana_${deb_ver}_amd64.deb
# package_cloud push grafana/testing/debian/jessie grafana_${deb_ver}_amd64.deb
package_cloud push grafana/testing/debian/wheezy grafana_${deb_ver}_amd64.deb
package_cloud push grafana/testing/debian/stretch grafana_${deb_ver}_amd64.deb

View File

@ -166,9 +166,7 @@ func handleGetNamespaces(req *cwRequest, c *middleware.Context) {
customNamespaces := req.DataSource.JsonData.Get("customMetricsNamespaces").MustString()
if customNamespaces != "" {
for _, key := range strings.Split(customNamespaces, ",") {
keys = append(keys, key)
}
keys = append(keys, strings.Split(customNamespaces, ",")...)
}
sort.Sort(sort.StringSlice(keys))

View File

@ -231,7 +231,7 @@ func (b *BasicDiff) Basic(lines []*JSONLine) []*BasicBlock {
// in the JSON document to a top level key.
//
// In order to produce distinct "blocks" when rendering the basic diff,
// we need a way to distinguish between differnt sections of data.
// we need a way to distinguish between different sections of data.
// To do this, we consider the value(s) of each top-level JSON key to
// represent a distinct block for Grafana's JSON data structure, so
// we perform this check to see if we've entered a new "block". If we

View File

@ -302,16 +302,16 @@ func (f *JSONFormatter) processItem(value interface{}, deltas []diff.Delta, posi
return nil
}
func (f *JSONFormatter) searchDeltas(deltas []diff.Delta, postion diff.Position) (results []diff.Delta) {
func (f *JSONFormatter) searchDeltas(deltas []diff.Delta, position diff.Position) (results []diff.Delta) {
results = make([]diff.Delta, 0)
for _, delta := range deltas {
switch delta.(type) {
case diff.PostDelta:
if delta.(diff.PostDelta).PostPosition() == postion {
if delta.(diff.PostDelta).PostPosition() == position {
results = append(results, delta)
}
case diff.PreDelta:
if delta.(diff.PreDelta).PrePosition() == postion {
if delta.(diff.PreDelta).PrePosition() == position {
results = append(results, delta)
}
default:

View File

@ -33,8 +33,8 @@ func AuthenticateUser(query *LoginUserQuery) error {
if setting.LdapEnabled {
for _, server := range LdapCfg.Servers {
auther := NewLdapAuthenticator(server)
err = auther.Login(query)
author := NewLdapAuthenticator(server)
err = author.Login(query)
if err == nil || err != ErrInvalidCredentials {
return err
}

View File

@ -67,7 +67,7 @@ func initContextWithAuthProxy(ctx *Context, orgId int64) bool {
if getRequestUserId(ctx) > 0 && getRequestUserId(ctx) != query.Result.UserId {
// remove session
if err := ctx.Session.Destory(ctx); err != nil {
log.Error(3, "Failed to destory session, err")
log.Error(3, "Failed to destroy session, err")
}
// initialize a new session
@ -107,8 +107,8 @@ var syncGrafanaUserWithLdapUser = func(ctx *Context, query *m.GetSignedInUserQue
ldapCfg := login.LdapCfg
for _, server := range ldapCfg.Servers {
auther := login.NewLdapAuthenticator(server)
if err := auther.SyncSignedInUser(query.Result); err != nil {
author := login.NewLdapAuthenticator(server)
if err := author.SyncSignedInUser(query.Result); err != nil {
return err
}
}

View File

@ -71,7 +71,7 @@ func TestWildcardExpansion(t *testing.T) {
So(expandeQueries[0].RawQuery, ShouldEqual, fmt.Sprintf("`os.cpu.3.idle`|aggregate.min|aggregate.max where cluster in ('demoapp-1', 'demoapp-2') and host in ('staples-lab-1', 'staples-lab-2') from %v to %v", from, to))
})
Convey("Containg wildcard series", func() {
Convey("Containing wildcard series", func() {
query := &Query{
Metrics: []Metric{
{Metric: "os.cpu*", Alias: ""},

View File

@ -49,15 +49,42 @@ var PrometheusHighlightRules = function() {
regex : "\\+|\\-|\\*|\\/|%|\\^|=|==|!=|<=|>=|<|>|=\\~|!\\~"
}, {
token : "paren.lparen",
regex : "[[({]"
regex : "[[(]"
}, {
token : "paren.lparen",
regex : "{",
next : "start-label-matcher"
}, {
token : "paren.rparen",
regex : "[\\])}]"
regex : "[\\])]"
}, {
token : "paren.rparen",
regex : "}"
}, {
token : "text",
regex : "\\s+"
} ],
"start-label-matcher" : [ {
token : "label.name",
regex : '[a-zA-Z_][a-zA-Z0-9_]*'
}, {
token : "label.matching_operator",
regex : '=|!=|=~|!~'
}, {
token : "label.value",
regex : '"[^"]*"|\'[^\']*\''
}, {
token : "label.matching_delimiter",
regex : ",",
push : 'start-label-matcher'
}, {
token : "label.matching_end",
regex : "}",
next : "start"
} ]
};
this.normalizeRules();
};
oop.inherits(PrometheusHighlightRules, TextHighlightRules);
@ -373,6 +400,11 @@ var PrometheusCompletions = function() {};
(function() {
this.getCompletions = function(state, session, pos, prefix, callback) {
var token = session.getTokenAt(pos.row, pos.column);
if (token.type === 'label.name' || token.type === 'label.value') {
return callback(null, []);
}
var completions = keyWordsCompletions.concat(functionsCompletions);
callback(null, completions);
};

View File

@ -193,6 +193,10 @@ export class KeybindingSrv {
}
});
this.bind('d n', e => {
this.$location.url("/dashboard/new");
});
this.bind('d r', () => {
scope.broadcastRefresh();
});

View File

@ -191,10 +191,9 @@ export default class TimeSeries {
this.stats.logmin = currentValue;
}
}
if (currentValue !== 0) {
this.allIsZero = false;
if (currentValue !== 0) {
this.allIsZero = false;
}
}
result.push([currentTime, currentValue]);

View File

@ -9,6 +9,24 @@ export class PromCompleter {
}
getCompletions(editor, session, pos, prefix, callback) {
let token = session.getTokenAt(pos.row, pos.column);
switch (token.type) {
case 'label.name':
callback(null, ['instance', 'job'].map(function (key) {
return {
caption: key,
value: key,
meta: "label name",
score: Number.MAX_VALUE
};
}));
return;
case 'label.value':
callback(null, []);
return;
}
if (prefix === '[') {
var vectors = [];
for (let unit of ['s', 'm', 'h']) {
@ -23,7 +41,7 @@ export class PromCompleter {
var query = prefix;
var line = editor.session.getLine(pos.row);
return this.datasource.performSuggestQuery(query).then(metricNames => {
return this.datasource.performSuggestQuery(query, true).then(metricNames => {
callback(null, metricNames.map(name => {
let value = name;
if (prefix === '(') {

View File

@ -24,6 +24,7 @@ export class PrometheusDatasource {
directUrl: string;
basicAuth: any;
withCredentials: any;
metricsNameCache: any;
/** @ngInject */
constructor(instanceSettings,
@ -157,11 +158,21 @@ export class PrometheusDatasource {
return this._request('GET', url, query.requestId);
}
performSuggestQuery(query) {
performSuggestQuery(query, cache = false) {
var url = '/api/v1/label/__name__/values';
return this._request('GET', url).then(function(result) {
return _.filter(result.data.data, function (metricName) {
if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
return this.$q.when(_.filter(this.metricsNameCache.data, metricName => {
return metricName.indexOf(query) !== 1;
}));
}
return this._request('GET', url).then(result => {
this.metricsNameCache = {
data: result.data.data,
expire: Date.now() + (60 * 1000)
};
return _.filter(result.data.data, metricName => {
return metricName.indexOf(query) !== 1;
});
});

View File

@ -107,4 +107,25 @@ describe('PrometheusMetricFindQuery', function() {
expect(results[0].text).to.be('metric{job="testjob"} 3846 1443454528000');
});
});
describe('When performing performSuggestQuery', function() {
var results;
var response;
it('cache response', function() {
response = {
status: "success",
data: ["value1", "value2", "value3"]
};
ctx.$httpBackend.expect('GET', 'proxied/api/v1/label/__name__/values').respond(response);
ctx.ds.performSuggestQuery('value', true).then(function(data) { results = data; });
ctx.$httpBackend.flush();
ctx.$rootScope.$apply();
expect(results.length).to.be(3);
ctx.ds.performSuggestQuery('value', true).then(function (data) {
// get from cache, no need to flush
results = data;
expect(results.length).to.be(3);
});
});
});
});