Compare commits

...

60 Commits

Author SHA1 Message Date
Leonard Gram
1ad5b02166 Updated version to 4.6.4. 2018-08-22 16:20:02 +02:00
Leonard Gram
7baecf0d0d sql: added code migration type 2018-08-22 16:16:25 +02:00
bergquist
7a06a47e63 release 4.6.3 2017-12-14 09:36:59 +01:00
Mitsuhiro Tanda
239f8a88bf fix default alias
(cherry picked from commit 4a63d696ff)
2017-12-13 14:29:54 +01:00
bergquist
75fa151026 fixes broken alert eval when first condition is using OR
closes #9318
2017-12-13 13:48:59 +01:00
Torkel Ödegaard
783355f1d6 fix: alert list panel now works correctly after adding manual annotation on dashboard, fixes #9951
(cherry picked from commit 0d12b37dfd)
2017-11-21 11:32:49 +01:00
Torkel Ödegaard
69a0a8e89c fix: fix for avatar images when gzip is turned on, fixes #5952
(cherry picked from commit 303e3de488)
2017-11-17 13:24:38 +01:00
bergquist
8db5f087eb sets version to 4.6.2 2017-11-16 10:19:25 +01:00
Carl Bergquist
8a1616305c prom: add support for default step param (#9866)
Alerting for prometheus have been depending on the step parameter from each query.
In https://github.com/grafana/grafana/pull/9226 we changed the behavior for step in the
frontend which caused problems for alerting. This commit fixes that by introducing a default
min interval value so alerting always have something to depend on.

closes #9777
(cherry picked from commit 5d6ed6c45f)
2017-11-15 11:23:25 +01:00
Torkel Ödegaard
7ca3d32a10 build: fixed jshint error
(cherry picked from commit a534ac4948)
2017-11-14 12:44:02 +01:00
Torkel Ödegaard
dba7383bb9 fix: Html escaping caused issue in InfluxDB query editor, could not pick greater than or less then operators, fixes #9871
(cherry picked from commit 012b72cdbf)
2017-11-14 11:28:55 +01:00
Alexander Zobnin
1ebea3775d heatmap: fix tooltip in "Time series bucket" mode, #9332 (#9867)
(cherry picked from commit e7f3480803)
2017-11-13 16:36:38 +01:00
Mitsuhiro Tanda
5a80b0aede fix cloudwatch ec2_instance_attribute (#9718)
* fix cloudwatch ec2_instance_attribute

* add test

* minor fix

(cherry picked from commit 52e1c4113b)
2017-11-13 13:09:24 +01:00
Alexander Zobnin
981f4f230c colorpicker: fix color string change #9769 (#9780)
(cherry picked from commit a3bf38cc21)
2017-11-03 13:31:39 +01:00
bergquist
cac8b976d9 changes version to 4.6.1 2017-11-01 11:27:12 +01:00
Torkel Ödegaard
4366d2f281 fix: panel view now wraps, no scrolling required, fixes #9746
(cherry picked from commit 894951c7d4)
2017-11-01 11:25:50 +01:00
Torkel Ödegaard
c80995b067 plugins: fix for loading external plugins behind auth proxy, fixes #9509
(cherry picked from commit e19b4a9291)
2017-11-01 10:49:01 +01:00
Alexander Zobnin
ebaf8620ea fix: color picker bug at series overrides page, #9715 (#9738)
(cherry picked from commit 948a5259a2)
2017-10-31 13:54:47 +01:00
bergquist
64d8ae9dcb tech: switch to golang 1.9.2
(cherry picked from commit 1be476b5f5)
2017-10-31 12:39:31 +01:00
bergquist
989bf2067c tech: add missing include 2017-10-29 21:16:34 +01:00
bergquist
baeea98473 save as should only delete threshold for panels with alerts
closes #9681
2017-10-29 19:34:41 +01:00
Torkel Ödegaard
dce8522575 fix: graphite annotation tooltip included undefined, fixes #9707
(cherry picked from commit 43d45f9fae)
2017-10-28 13:00:26 +02:00
Torkel Ödegaard
c47f670a58 build: updated version to v4.6.0 2017-10-26 12:15:29 +02:00
Torkel Ödegaard
fb50cec096 plugins: added backward compatible path for rxjs
(cherry picked from commit 01f16ece3e)
2017-10-26 12:08:25 +02:00
Torkel Ödegaard
eb9bdb09b3 ux: updated singlestat default colors
(cherry picked from commit bf680acae5)
2017-10-26 12:00:08 +02:00
Torkel Ödegaard
002ac79124 prometheus: fixed unsaved changes warning when changing time range due to step option on query model was changed in datasource.query code, fixes #9675
(cherry picked from commit 74fcb2494a)
2017-10-26 11:48:00 +02:00
Torkel Ödegaard
bd11b01aaa fix: firefox can now create region annotations, fixes #9638
(cherry picked from commit 0c2aa91e61)
2017-10-26 10:58:31 +02:00
bergquist
d7dd7e3c81 alerting: only editors can pause rules
closes #9640
2017-10-24 11:01:55 +02:00
Torkel Ödegaard
ea78d13b54 fix: another fix for playlist view state, #9639
(cherry picked from commit 7861c27557)
2017-10-24 10:59:23 +02:00
Patrick O'Carroll
83c5853900 fix: fixed playlist controls and view state, fixes #9639
(cherry picked from commit 8afb84a5e5)
2017-10-24 10:48:48 +02:00
bergquist
0f0be4e6e3 prom: adds pre built grafana dashboard
(cherry picked from commit 28af20ff813fd1e3d734ac38163fac0d8ea1b522)
2017-10-24 10:35:45 +02:00
Daniel Lee
f308a25589 bump version for publish_testing.sh 2017-10-23 16:30:15 +02:00
Daniel Lee
9a91a882b4 update version to 4.6.0-beta3 2017-10-23 15:22:06 +02:00
Daniel Lee
6ad6131aaf plugins: expose dashboard impression store
(cherry picked from commit 90ef877e6e)
2017-10-23 15:20:29 +02:00
Sven Klemm
1f10928450 modify $__timeGroup macro so it can be used in select clause (#9527)
* modify $__timeGroup macro so it can be used in select clause

* fix $__interval_ms for postgres datasource

* use $__timeGroup macro in documentation

* fix annotation template query
remove title since its no longer used and add tags instead

* change __timeFilter macro to work on postgresql < 8.1 and redshift

(cherry picked from commit b2d880c6de)
2017-10-23 14:13:38 +02:00
Daniel Lee
0cd0aa19d6 plugins: fixes path issue on Windows
When loading a plugin and setting the path, an extra backslash sneaks
when running on Windows. Fixes #9597

(cherry picked from commit 7863a0417c)
2017-10-23 13:06:09 +02:00
bergquist
c2f2a43197 prometheus: enable gzip for /metrics endpoint
closes #9464

(cherry picked from commit 139f077453)
2017-10-23 09:37:41 +02:00
Torkel Ödegaard
7fe1ac5fe7 fix: fixed save to file button in export modal, fixes #9586
(cherry picked from commit 1e61eae9f4)
2017-10-19 12:54:24 +02:00
bergquist
aec448f7c6 mysql: add usage stats for mysql 2017-10-19 10:31:30 +02:00
Daniel Lee
2ce36c8670 pluginloader: esModule true for systemjs config
Supports importing a module's contents with the
'* as module' syntax. The latest version of SystemJS turns
it off per default which broke several plugins.

(cherry picked from commit 7cbb4020e9)
2017-10-19 09:04:22 +02:00
Alexander Zobnin
fb35d839c1 Fix heatmap Y axis rendering (#9580)
* heatmap: fix Y axis rendering, #9576

* heatmap: fix color legend rendering

(cherry picked from commit 92c67e8c83)
2017-10-18 15:23:12 +02:00
Mitsuhiro Tanda
c8f5d39d97 fix vector range
(cherry picked from commit 8a43d4e25c)
2017-10-18 14:07:44 +02:00
bergquist
34bc19359d prometheus: add builtin template variable as range vectors
add $__interval and $__interval_ms as range vectors to
prometheus editor

(cherry picked from commit c2c5f529f3)
2017-10-18 14:05:43 +02:00
Torkel Ödegaard
3dcae78126 fix: fixed prometheus step issue that caused browser crash, fixes #9575
(cherry picked from commit 8d68bd6bb9)
2017-10-18 13:29:02 +02:00
Torkel Ödegaard
054c7a154a fix: getting started panel and mark adding data source as done, fixes #9568
(cherry picked from commit 039fc2964a)
2017-10-18 12:04:52 +02:00
Alexander Zobnin
6f3d61f4d2 Fixes for annotations API (#9577)
* annotations: throw error if no text specified and set default time to Now() if empty, #9571

* annotations: fix saving graphite event with empty string tags

* docs: add /api/annotations/graphite endpoint docs, #9571

(cherry picked from commit 74e90d01ec)
2017-10-18 10:13:51 +02:00
bergquist
305f8c10e9 bump packagecloud script 2017-10-17 14:16:40 +02:00
Torkel Ödegaard
fff4cfd11e build: added imports of rxjs utility functions
(cherry picked from commit eda3cffe22)
2017-10-17 12:17:32 +02:00
Torkel Ödegaard
d20434f828 Merge branch 'v4.6.x' of github.com:grafana/grafana into v4.6.x 2017-10-17 12:15:26 +02:00
bergquist
1ef850fae0 prepare for v4.6.0-beta2 release 2017-10-17 11:17:34 +02:00
Mitsuhiro Tanda
2f7a59fb18 fix template variable expanding
(cherry picked from commit 0f87279ab8)
2017-10-17 11:16:36 +02:00
krise3k
07be20eeb3 annotations: quote reserved fields (#9550)
(cherry picked from commit 45a572ebd8)
2017-10-17 11:04:17 +02:00
Torkel Ödegaard
689b8d79df ux: align alert and btn colors
(cherry picked from commit b86ae3f0e8)
2017-10-17 10:57:34 +02:00
Torkel Ödegaard
b70c538633 fix: fixed color pickers that were broken in minified builds, fixes #9549
(cherry picked from commit 574afe8568)
2017-10-17 10:54:49 +02:00
Daniel Lee
769bc5df21 textpanel: fixes #9491
(cherry picked from commit 14241404ff)
2017-10-17 09:15:44 +02:00
Daniel Lee
4eb6d82254 csv: fix import for saveAs shim
After switch from systemjs to webpack, needed to import the
file-saver saveAs shim for it work. Fixes #9525

(cherry picked from commit f3ec139eab)
2017-10-17 09:14:45 +02:00
Daniel Lee
7935739eb3 plugins: expose more util and flot dependencies
Also, fix for coremodules export. Have to add the __esModule
attribute to fool SystemJS.

(cherry picked from commit eb4e71e2c6)
2017-10-17 09:13:58 +02:00
bergquist
7403fa0fa7 alert_tab: clear test result when testing rules
closes #9539

(cherry picked from commit 9de4d0fa6b)
2017-10-16 10:34:59 +02:00
Mitsuhiro Tanda
5ebfd1e5ab (cloudwatch) fix cloudwatch query error over 24h (#9536)
fix cloudwatch query error over 24h

(cherry picked from commit 7edc95cc35)

closes #9523
2017-10-16 08:32:13 +02:00
Mitsuhiro Tanda
a1a8c0fc07 show error message when cloudwatch datasource can't add
(cherry picked from commit 40b11654fd)
2017-10-16 08:10:24 +02:00
98 changed files with 2048 additions and 310 deletions

View File

@@ -7,7 +7,12 @@
- UX changes to nav & side menu
- New dashboard grid layout system
# 4.6.0 (unreleased)
# 4.6.0-beta2 (2017-10-17)
## Fixes
* **ColorPicker**: Fix for color picker not showing [#9549](https://github.com/grafana/grafana/issues/9549)
# 4.6.0-beta1 (2017-10-13)
## New Features
* **GCS**: Adds support for Google Cloud Storage [#8370](https://github.com/grafana/grafana/issues/8370) thx [@chuhlomin](https://github.com/chuhlomin)
@@ -40,7 +45,7 @@
## Tech
* **Go**: Grafana is now built using golang 1.9
* **Webpack**: Changed from systemjs to webpack (see readme or building from source guide for new build instructions). Systemjs is still used to load plugins but now plugins can only import a limited set of dependencies. See [PLUGIN_DEV.md](https://github.com/grafana/grafana/blob/master/PLUGIN_DEV.md) for more details on how this can effect some plugins.
* **Webpack**: Changed from systemjs to webpack (see readme or building from source guide for new build instructions). Systemjs is still used to load plugins but now plugins can only import a limited set of dependencies. See [PLUGIN_DEV.md](https://github.com/grafana/grafana/blob/master/PLUGIN_DEV.md) for more details on how this can effect some plugins.
# 4.5.2 (2017-09-22)

View File

@@ -7,7 +7,7 @@ clone_folder: c:\gopath\src\github.com\grafana\grafana
environment:
nodejs_version: "6"
GOPATH: c:\gopath
GOVERSION: 1.9.1
GOVERSION: 1.9.2
install:
- rmdir c:\go /s /q

View File

@@ -9,7 +9,7 @@ machine:
GOPATH: "/home/ubuntu/.go_workspace"
ORG_PATH: "github.com/grafana"
REPO_PATH: "${ORG_PATH}/grafana"
GODIST: "go1.9.1.linux-amd64.tar.gz"
GODIST: "go1.9.2.linux-amd64.tar.gz"
post:
- mkdir -p ~/download
- mkdir -p ~/docker

View File

@@ -0,0 +1,77 @@
version: "2"
services:
graphite:
build:
context: blocks/graphite1
args:
version: master
ports:
- "8080:80"
- "2003:2003"
- "8125:8125/udp"
- "8126:8126"
volumes:
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:ro
fake-graphite-data:
image: grafana/fake-data-gen
network_mode: bridge
environment:
FD_DATASOURCE: graphite
FD_PORT: 2003
prometheus:
build: blocks/prometheus
network_mode: host
ports:
- "9090:9090"
node_exporter:
image: prom/node-exporter
network_mode: host
ports:
- "9100:9100"
fake-prometheus-data:
image: grafana/fake-data-gen
network_mode: host
ports:
- "9091:9091"
environment:
FD_DATASOURCE: prom
alertmanager:
image: quay.io/prometheus/alertmanager
network_mode: host
ports:
- "9093:9093"
influxdb:
image: influxdb:latest
container_name: influxdb
ports:
- "2004:2004"
- "8083:8083"
- "8086:8086"
volumes:
- ./blocks/influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
fake-influxdb-data:
image: grafana/fake-data-gen
network_mode: bridge
environment:
FD_DATASOURCE: influxdb
FD_PORT: 8086
# You need to run 'sysctl -w vm.max_map_count=262144' on the host machine
elasticsearch5:
image: elasticsearch:5
command: elasticsearch
ports:
- "10200:9200"
- "10300:9300"

View File

@@ -48,7 +48,7 @@ Macro example | Description
*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)*
*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*
*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*
*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from "dateColumn")/extract(epoch from '5m'::interval))::int*
*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from "dateColumn")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)*
*$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183*
*$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783*
*$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183*
@@ -94,26 +94,26 @@ Example with `metric` column
```sql
SELECT
min(time_date_time) as time,
$__timeGroup(time_date_time,'5m') as time,
min(value_double),
'min' as metric
FROM test_data
WHERE $__timeFilter(time_date_time)
GROUP BY metric1, (extract(epoch from time_date_time)/extract(epoch from $__interval::interval))::int
ORDER BY time asc
GROUP BY time
ORDER BY time
```
Example with multiple columns:
```sql
SELECT
min(time_date_time) as time,
$__timeGroup(time_date_time,'5m') as time,
min(value_double) as min_value,
max(value_double) as max_value
FROM test_data
WHERE $__timeFilter(time_date_time)
GROUP BY metric1, (extract(epoch from time_date_time)/extract(epoch from $__interval::interval))::int
ORDER BY time asc
GROUP BY time
ORDER BY time
```
## Templating

View File

@@ -34,6 +34,7 @@ Name | Description
*Basic Auth* | Enable basic authentication to the Prometheus data source.
*User* | Name of your Prometheus user
*Password* | Database user's password
*Scrape interval* | This will be used as a lower limit for the Prometheus step query parameter. Default value is 15s.
## Query editor

View File

@@ -120,6 +120,37 @@ Content-Type: application/json
PUT /api/annotations/1141 HTTP/1.1
Accept: application/json
Content-Type: application/json
{
"time":1507037197339,
"isRegion":true,
"timeEnd":1507180805056,
"text":"Annotation Description",
"tags":["tag3","tag4","tag5"]
}
```
## Delete Annotation By Id
`DELETE /api/annotation/:id`
Deletes the annotation that matches the specified id.
**Example Request**:
```http
DELETE /api/annotation/1 HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk
```
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
```
## Delete Annotation By RegionId

View File

@@ -13,7 +13,7 @@ dev environment. Grafana ships with its own required backend server; also comple
## Dependencies
- [Go 1.9.1](https://golang.org/dl/)
- [Go 1.9.2](https://golang.org/dl/)
- [NodeJS LTS](https://nodejs.org/download/)
- [Git](https://git-scm.com/downloads)

View File

@@ -4,7 +4,7 @@
"company": "Grafana Labs"
},
"name": "grafana",
"version": "4.6.0-beta1",
"version": "4.6.4",
"repository": {
"type": "git",
"url": "http://github.com/grafana/grafana.git"

View File

@@ -1,6 +1,6 @@
#! /usr/bin/env bash
deb_ver=4.6.0-beta1
rpm_ver=4.6.0-beta1
deb_ver=4.6.0-beta3
rpm_ver=4.6.0-beta3
wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_${deb_ver}_amd64.deb

View File

@@ -1,7 +1,6 @@
package api
import (
"fmt"
"strings"
"time"
@@ -22,6 +21,7 @@ func GetAnnotations(c *middleware.Context) Response {
PanelId: c.QueryInt64("panelId"),
Limit: c.QueryInt64("limit"),
Tags: c.QueryStrings("tags"),
Type: c.Query("type"),
}
repo := annotations.GetRepository()
@@ -41,9 +41,22 @@ func GetAnnotations(c *middleware.Context) Response {
return Json(200, items)
}
type CreateAnnotationError struct {
message string
}
func (e *CreateAnnotationError) Error() string {
return e.message
}
func PostAnnotation(c *middleware.Context, cmd dtos.PostAnnotationsCmd) Response {
repo := annotations.GetRepository()
if cmd.Text == "" {
err := &CreateAnnotationError{"text field should not be empty"}
return ApiError(500, "Failed to save annotation", err)
}
item := annotations.Item{
OrgId: c.OrgId,
UserId: c.UserId,
@@ -55,6 +68,10 @@ func PostAnnotation(c *middleware.Context, cmd dtos.PostAnnotationsCmd) Response
Tags: cmd.Tags,
}
if item.Epoch == 0 {
item.Epoch = time.Now().Unix()
}
if err := repo.Save(&item); err != nil {
return ApiError(500, "Failed to save annotation", err)
}
@@ -82,21 +99,22 @@ func PostAnnotation(c *middleware.Context, cmd dtos.PostAnnotationsCmd) Response
return ApiSuccess("Annotation added")
}
type GraphiteAnnotationError struct {
message string
}
func (e *GraphiteAnnotationError) Error() string {
return e.message
}
func formatGraphiteAnnotation(what string, data string) string {
return fmt.Sprintf("%s\n%s", what, data)
text := what
if data != "" {
text = text + "\n" + data
}
return text
}
func PostGraphiteAnnotation(c *middleware.Context, cmd dtos.PostGraphiteAnnotationsCmd) Response {
repo := annotations.GetRepository()
if cmd.What == "" {
err := &CreateAnnotationError{"what field should not be empty"}
return ApiError(500, "Failed to save Graphite annotation", err)
}
if cmd.When == 0 {
cmd.When = time.Now().Unix()
}
@@ -106,18 +124,22 @@ func PostGraphiteAnnotation(c *middleware.Context, cmd dtos.PostGraphiteAnnotati
var tagsArray []string
switch tags := cmd.Tags.(type) {
case string:
tagsArray = strings.Split(tags, " ")
if tags != "" {
tagsArray = strings.Split(tags, " ")
} else {
tagsArray = []string{}
}
case []interface{}:
for _, t := range tags {
if tagStr, ok := t.(string); ok {
tagsArray = append(tagsArray, tagStr)
} else {
err := &GraphiteAnnotationError{"tag should be a string"}
err := &CreateAnnotationError{"tag should be a string"}
return ApiError(500, "Failed to save Graphite annotation", err)
}
}
default:
err := &GraphiteAnnotationError{"unsupported tags format"}
err := &CreateAnnotationError{"unsupported tags format"}
return ApiError(500, "Failed to save Graphite annotation", err)
}
@@ -133,7 +155,7 @@ func PostGraphiteAnnotation(c *middleware.Context, cmd dtos.PostGraphiteAnnotati
return ApiError(500, "Failed to save Graphite annotation", err)
}
return ApiSuccess("Graphite Annotation added")
return ApiSuccess("Graphite annotation added")
}
func UpdateAnnotation(c *middleware.Context, cmd dtos.UpdateAnnotationsCmd) Response {

View File

@@ -267,7 +267,7 @@ func (hs *HttpServer) registerRoutes() {
apiRoute.Group("/alerts", func(alertsRoute RouteRegister) {
alertsRoute.Post("/test", bind(dtos.AlertTestCommand{}), wrap(AlertTest))
alertsRoute.Post("/:alertId/pause", bind(dtos.PauseAlertCommand{}), wrap(PauseAlert), reqEditorRole)
alertsRoute.Post("/:alertId/pause", reqEditorRole, bind(dtos.PauseAlertCommand{}), wrap(PauseAlert))
alertsRoute.Get("/:alertId", ValidateOrgAlert, wrap(GetAlert))
alertsRoute.Get("/", wrap(GetAlerts))
alertsRoute.Get("/states-for-dashboard", wrap(GetAlertStatesForDashboard))
@@ -320,8 +320,8 @@ func (hs *HttpServer) registerRoutes() {
r.Any("/api/gnet/*", reqSignedIn, ProxyGnetRequest)
// Gravatar service.
avt := avatar.CacheServer()
r.Get("/avatar/:hash", avt.ServeHTTP)
avatarCacheServer := avatar.NewCacheServer()
r.Get("/avatar/:hash", avatarCacheServer.Handler)
// Websocket
r.Any("/ws", hs.streamManager.Serve)

View File

@@ -24,6 +24,7 @@ import (
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/setting"
"gopkg.in/macaron.v1"
)
var gravatarSource string
@@ -89,12 +90,12 @@ func (this *Avatar) Update() (err error) {
return err
}
type service struct {
type CacheServer struct {
notFound *Avatar
cache map[string]*Avatar
}
func (this *service) mustInt(r *http.Request, defaultValue int, keys ...string) (v int) {
func (this *CacheServer) mustInt(r *http.Request, defaultValue int, keys ...string) (v int) {
for _, k := range keys {
if _, err := fmt.Sscanf(r.FormValue(k), "%d", &v); err == nil {
defaultValue = v
@@ -103,8 +104,8 @@ func (this *service) mustInt(r *http.Request, defaultValue int, keys ...string)
return defaultValue
}
func (this *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
urlPath := r.URL.Path
func (this *CacheServer) Handler(ctx *macaron.Context) {
urlPath := ctx.Req.URL.Path
hash := urlPath[strings.LastIndex(urlPath, "/")+1:]
var avatar *Avatar
@@ -126,20 +127,24 @@ func (this *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
this.cache[hash] = avatar
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(avatar.data.Bytes())))
w.Header().Set("Cache-Control", "private, max-age=3600")
ctx.Resp.Header().Add("Content-Type", "image/jpeg")
if err := avatar.Encode(w); err != nil {
if !setting.EnableGzip {
ctx.Resp.Header().Add("Content-Length", strconv.Itoa(len(avatar.data.Bytes())))
}
ctx.Resp.Header().Add("Cache-Control", "private, max-age=3600")
if err := avatar.Encode(ctx.Resp); err != nil {
log.Warn("avatar encode error: %v", err)
w.WriteHeader(500)
ctx.WriteHeader(500)
}
}
func CacheServer() http.Handler {
func NewCacheServer() *CacheServer {
UpdateGravatarSource()
return &service{
return &CacheServer{
notFound: newNotFound(),
cache: make(map[string]*Avatar),
}

View File

@@ -188,9 +188,8 @@ func (hs *HttpServer) metricsEndpoint(ctx *macaron.Context) {
return
}
promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{
DisableCompression: true,
}).ServeHTTP(ctx.Resp, ctx.Req.Request)
promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}).
ServeHTTP(ctx.Resp, ctx.Req.Request)
}
func (hs *HttpServer) healthHandler(ctx *macaron.Context) {

View File

@@ -78,7 +78,14 @@ func tryLoginUsingRememberCookie(c *middleware.Context) bool {
user := userQuery.Result
// validate remember me cookie
if val, _ := c.GetSuperSecureCookie(user.Rands+user.Password, setting.CookieRememberName); val != user.Login {
signingKey := user.Rands + user.Password
if len(signingKey) < 10 {
c.Logger.Error("Invalid user signingKey")
return false
}
if val, _ := c.GetSuperSecureCookie(signingKey, setting.CookieRememberName); val != user.Login {
return false
}

View File

@@ -21,6 +21,10 @@ func Gziper() macaron.Handler {
return
}
if strings.HasPrefix(requestPath, "/metrics") {
return
}
ctx.Invoke(macaronGziper)
}
}

View File

@@ -18,6 +18,7 @@ const (
DS_KAIROSDB = "kairosdb"
DS_PROMETHEUS = "prometheus"
DS_POSTGRES = "postgres"
DS_MYSQL = "mysql"
DS_ACCESS_DIRECT = "direct"
DS_ACCESS_PROXY = "proxy"
)
@@ -64,6 +65,7 @@ var knownDatasourcePlugins map[string]bool = map[string]bool{
DS_PROMETHEUS: true,
DS_OPENTSDB: true,
DS_POSTGRES: true,
DS_MYSQL: true,
"opennms": true,
"druid": true,
"dalmatinerdb": true,

View File

@@ -40,7 +40,7 @@ func getPluginLogoUrl(pluginType, path, baseUrl string) string {
}
func (fp *FrontendPluginBase) setPathsBasedOnApp(app *AppPlugin) {
appSubPath := strings.Replace(fp.PluginDir, app.PluginDir, "", 1)
appSubPath := strings.Replace(strings.Replace(fp.PluginDir, app.PluginDir, "", 1), "\\", "/", 1)
fp.IncludedInAppId = app.Id
fp.BaseUrl = app.BaseUrl

View File

@@ -0,0 +1,34 @@
package plugins
import (
"testing"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
func TestFrontendPlugin(t *testing.T) {
Convey("When setting paths based on App on Windows", t, func() {
setting.StaticRootPath = "c:\\grafana\\public"
fp := &FrontendPluginBase{
PluginBase: PluginBase{
PluginDir: "c:\\grafana\\public\\app\\plugins\\app\\testdata\\datasource",
BaseUrl: "fpbase",
},
}
app := &AppPlugin{
FrontendPluginBase: FrontendPluginBase{
PluginBase: PluginBase{
PluginDir: "c:\\grafana\\public\\app\\plugins\\app\\testdata",
Id: "testdata",
BaseUrl: "public/app/plugins/app/testdata",
},
},
}
fp.setPathsBasedOnApp(app)
So(fp.Module, ShouldEqual, "app/plugins/app/testdata/datasource/module")
})
}

View File

@@ -39,6 +39,11 @@ func (e *DefaultEvalHandler) Eval(context *EvalContext) {
break
}
if i == 0 {
firing = cr.Firing
noDataFound = cr.NoDataFound
}
// calculating Firing based on operator
if cr.Operator == "or" {
firing = firing || cr.Firing

View File

@@ -36,6 +36,16 @@ func TestAlertingEvaluationHandler(t *testing.T) {
So(context.ConditionEvals, ShouldEqual, "true = true")
})
Convey("Show return triggered with single passing condition2", func() {
context := NewEvalContext(context.TODO(), &Rule{
Conditions: []Condition{&conditionStub{firing: true, operator: "and"}},
})
handler.Eval(context)
So(context.Firing, ShouldEqual, true)
So(context.ConditionEvals, ShouldEqual, "true = true")
})
Convey("Show return false with not passing asdf", func() {
context := NewEvalContext(context.TODO(), &Rule{
Conditions: []Condition{
@@ -131,6 +141,33 @@ func TestAlertingEvaluationHandler(t *testing.T) {
So(context.ConditionEvals, ShouldEqual, "[[true OR false] OR true] = true")
})
Convey("Should return false if no condition is firing using OR operator", func() {
context := NewEvalContext(context.TODO(), &Rule{
Conditions: []Condition{
&conditionStub{firing: false, operator: "or"},
&conditionStub{firing: false, operator: "or"},
&conditionStub{firing: false, operator: "or"},
},
})
handler.Eval(context)
So(context.Firing, ShouldEqual, false)
So(context.ConditionEvals, ShouldEqual, "[[false OR false] OR false] = false")
})
Convey("Should retuasdfrn no data if one condition has nodata", func() {
context := NewEvalContext(context.TODO(), &Rule{
Conditions: []Condition{
&conditionStub{operator: "or", noData: false},
&conditionStub{operator: "or", noData: false},
&conditionStub{operator: "or", noData: false},
},
})
handler.Eval(context)
So(context.NoDataFound, ShouldBeFalse)
})
Convey("Should return no data if one condition has nodata", func() {
context := NewEvalContext(context.TODO(), &Rule{
Conditions: []Condition{

View File

@@ -17,6 +17,7 @@ type ItemQuery struct {
DashboardId int64 `json:"dashboardId"`
PanelId int64 `json:"panelId"`
Tags []string `json:"tags"`
Type string `json:"type"`
Limit int64 `json:"limit"`
}

View File

@@ -43,7 +43,7 @@ func (r *SqlAnnotationRepo) ensureTagsExist(sess *DBSession, tags []*models.Tag)
var existingTag models.Tag
// check if it exists
if exists, err := sess.Table("tag").Where("key=? AND value=?", tag.Key, tag.Value).Get(&existingTag); err != nil {
if exists, err := sess.Table("tag").Where("`key`=? AND `value`=?", tag.Key, tag.Value).Get(&existingTag); err != nil {
return nil, err
} else if exists {
tag.Id = existingTag.Id
@@ -158,6 +158,10 @@ func (r *SqlAnnotationRepo) Find(query *annotations.ItemQuery) ([]*annotations.I
params = append(params, query.From, query.To)
}
if query.Type == "alert" {
sql.WriteString(` AND annotation.alert_id > 0`)
}
if len(query.Tags) > 0 {
keyValueFilters := []string{}

View File

@@ -42,6 +42,7 @@ func TestAnnotations(t *testing.T) {
UserId: 1,
DashboardId: 1,
Text: "hello",
Type: "alert",
Epoch: 10,
Tags: []string{"outage", "error", "type:outage", "server:server-1"},
})
@@ -89,6 +90,19 @@ func TestAnnotations(t *testing.T) {
So(items, ShouldHaveLength, 0)
})
Convey("Should not find one when type filter does not match", func() {
items, err := repo.Find(&annotations.ItemQuery{
OrgId: 1,
DashboardId: 1,
From: 1,
To: 15,
Type: "alert",
})
So(err, ShouldBeNil)
So(items, ShouldHaveLength, 0)
})
Convey("Should find one when all tag filters does match", func() {
items, err := repo.Find(&annotations.ItemQuery{
OrgId: 1,

View File

@@ -1,6 +1,11 @@
package migrations
import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
import (
"fmt"
"github.com/go-xorm/xorm"
. "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/util"
)
func addUserMigrations(mg *Migrator) {
userV1 := Table{
@@ -107,4 +112,37 @@ func addUserMigrations(mg *Migrator) {
mg.AddMigration("Add last_seen_at column to user", NewAddColumnMigration(userV2, &Column{
Name: "last_seen_at", Type: DB_DateTime, Nullable: true,
}))
// Adds salt & rands for old users who used ldap or oauth
mg.AddMigration("Add missing user data", &AddMissingUserSaltAndRandsMigration{})
}
type AddMissingUserSaltAndRandsMigration struct {
MigrationBase
}
func (m *AddMissingUserSaltAndRandsMigration) Sql(dialect Dialect) string {
return "code migration"
}
type TempUserDTO struct {
Id int64
Login string
}
func (m *AddMissingUserSaltAndRandsMigration) Exec(sess *xorm.Session, mg *Migrator) error {
users := make([]*TempUserDTO, 0)
err := sess.Sql(fmt.Sprintf("SELECT id, login from %s WHERE rands = ''", mg.Dialect.Quote("user"))).Find(&users)
if err != nil {
return err
}
for _, user := range users {
_, err := sess.Exec("UPDATE "+mg.Dialect.Quote("user")+" SET salt = ?, rands = ? WHERE id = ?", util.GetRandomString(10), util.GetRandomString(10), user.Id)
if err != nil {
return err
}
}
return nil
}

View File

@@ -12,7 +12,7 @@ import (
type Migrator struct {
x *xorm.Engine
dialect Dialect
Dialect Dialect
migrations []Migration
Logger log.Logger
}
@@ -31,7 +31,7 @@ func NewMigrator(engine *xorm.Engine) *Migrator {
mg.x = engine
mg.Logger = log.New("migrator")
mg.migrations = make([]Migration, 0)
mg.dialect = NewDialect(mg.x.DriverName())
mg.Dialect = NewDialect(mg.x.DriverName())
return mg
}
@@ -82,7 +82,7 @@ func (mg *Migrator) Start() error {
continue
}
sql := m.Sql(mg.dialect)
sql := m.Sql(mg.Dialect)
record := MigrationLog{
MigrationId: m.Id(),
@@ -120,7 +120,7 @@ func (mg *Migrator) exec(m Migration, sess *xorm.Session) error {
condition := m.GetCondition()
if condition != nil {
sql, args := condition.Sql(mg.dialect)
sql, args := condition.Sql(mg.Dialect)
results, err := sess.Query(sql, args...)
if err != nil || len(results) == 0 {
mg.Logger.Info("Skipping migration condition not fulfilled", "id", m.Id())
@@ -128,7 +128,13 @@ func (mg *Migrator) exec(m Migration, sess *xorm.Session) error {
}
}
_, err := sess.Exec(m.Sql(mg.dialect))
var err error
if codeMigration, ok := m.(CodeMigration); ok {
err = codeMigration.Exec(sess, mg)
} else {
_, err = sess.Exec(m.Sql(mg.Dialect))
}
if err != nil {
mg.Logger.Error("Executing migration failed", "id", m.Id(), "error", err)
return err

View File

@@ -2,6 +2,7 @@ package migrator
import (
"fmt"
"github.com/go-xorm/xorm"
"strings"
)
@@ -18,6 +19,11 @@ type Migration interface {
GetCondition() MigrationCondition
}
type CodeMigration interface {
Migration
Exec(sess *xorm.Session, migrator * Migrator) error
}
type SQLType string
type ColumnType string

View File

@@ -99,9 +99,10 @@ func CreateUser(cmd *m.CreateUserCommand) error {
LastSeenAt: time.Now().AddDate(-10, 0, 0),
}
user.Salt = util.GetRandomString(10)
user.Rands = util.GetRandomString(10)
if len(cmd.Password) > 0 {
user.Salt = util.GetRandomString(10)
user.Rands = util.GetRandomString(10)
user.Password = util.EncodePassword(cmd.Password, user.Salt)
}

View File

@@ -14,6 +14,28 @@ func TestUserDataAccess(t *testing.T) {
Convey("Testing DB", t, func() {
InitTestDB(t)
Convey("Creating a user", func() {
cmd := &models.CreateUserCommand{
Email: "usertest@test.com",
Name: "user name",
Login: "user_test_login",
}
err := CreateUser(cmd)
So(err, ShouldBeNil)
Convey("Loading a user", func() {
query := models.GetUserByIdQuery{Id: cmd.Result.Id}
err := GetUserById(&query)
So(err, ShouldBeNil)
So(query.Result.Email, ShouldEqual, "usertest@test.com")
So(query.Result.Password, ShouldEqual, "")
So(query.Result.Rands, ShouldHaveLength, 10)
So(query.Result.Salt, ShouldHaveLength, 10)
})
})
var err error
for i := 0; i < 5; i++ {
err = CreateUser(&models.CreateUserCommand{

View File

@@ -17,6 +17,7 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/grafana/grafana/pkg/components/null"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/metrics"
@@ -24,6 +25,7 @@ import (
type CloudWatchExecutor struct {
*models.DataSource
ec2Svc ec2iface.EC2API
}
type DatasourceInfo struct {
@@ -267,7 +269,10 @@ func parseQuery(model *simplejson.Json) (*CloudWatchQuery, error) {
period = int(d.Seconds())
}
alias := model.Get("alias").MustString("{{metric}}_{{stat}}")
alias := model.Get("alias").MustString()
if alias == "" {
alias = "{{metric}}_{{stat}}"
}
return &CloudWatchQuery{
Region: region,

View File

@@ -183,6 +183,18 @@ func (e *CloudWatchExecutor) executeMetricFindQuery(ctx context.Context, queryCo
data, err = e.handleGetEbsVolumeIds(ctx, parameters, queryContext)
break
case "ec2_instance_attribute":
region := parameters.Get("region").MustString()
dsInfo := e.getDsInfo(region)
cfg, err := e.getAwsConfig(dsInfo)
if err != nil {
return nil, errors.New("Failed to call ec2:DescribeInstances")
}
sess, err := session.NewSession(cfg)
if err != nil {
return nil, errors.New("Failed to call ec2:DescribeInstances")
}
e.ec2Svc = ec2.New(sess, cfg)
data, err = e.handleGetEc2InstanceAttribute(ctx, parameters, queryContext)
break
}
@@ -373,14 +385,16 @@ func (e *CloudWatchExecutor) handleGetEc2InstanceAttribute(ctx context.Context,
var filters []*ec2.Filter
for k, v := range filterJson {
if vv, ok := v.([]string); ok {
var vvvv []*string
if vv, ok := v.([]interface{}); ok {
var vvvvv []*string
for _, vvv := range vv {
vvvv = append(vvvv, &vvv)
if vvvv, ok := vvv.(string); ok {
vvvvv = append(vvvvv, &vvvv)
}
}
filters = append(filters, &ec2.Filter{
Name: aws.String(k),
Values: vvvv,
Values: vvvvv,
})
}
}
@@ -467,24 +481,13 @@ func (e *CloudWatchExecutor) cloudwatchListMetrics(region string, namespace stri
}
func (e *CloudWatchExecutor) ec2DescribeInstances(region string, filters []*ec2.Filter, instanceIds []*string) (*ec2.DescribeInstancesOutput, error) {
dsInfo := e.getDsInfo(region)
cfg, err := e.getAwsConfig(dsInfo)
if err != nil {
return nil, errors.New("Failed to call ec2:DescribeInstances")
}
sess, err := session.NewSession(cfg)
if err != nil {
return nil, errors.New("Failed to call ec2:DescribeInstances")
}
svc := ec2.New(sess, cfg)
params := &ec2.DescribeInstancesInput{
Filters: filters,
InstanceIds: instanceIds,
}
var resp ec2.DescribeInstancesOutput
err = svc.DescribeInstancesPages(params,
err := e.ec2Svc.DescribeInstancesPages(params,
func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
reservations, _ := awsutil.ValuesAtPath(page, "Reservations")
for _, reservation := range reservations {

View File

@@ -1,13 +1,28 @@
package cloudwatch
import (
"context"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/tsdb"
. "github.com/smartystreets/goconvey/convey"
)
type mockedEc2 struct {
ec2iface.EC2API
Resp ec2.DescribeInstancesOutput
}
func (m mockedEc2) DescribeInstancesPages(in *ec2.DescribeInstancesInput, fn func(*ec2.DescribeInstancesOutput, bool) bool) error {
fn(&m.Resp, true)
return nil
}
func TestCloudWatchMetrics(t *testing.T) {
Convey("When calling getMetricsForCustomMetrics", t, func() {
@@ -66,4 +81,37 @@ func TestCloudWatchMetrics(t *testing.T) {
})
})
Convey("When calling handleGetEc2InstanceAttribute", t, func() {
executor := &CloudWatchExecutor{
ec2Svc: mockedEc2{Resp: ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{
{
Instances: []*ec2.Instance{
{
InstanceId: aws.String("i-12345678"),
Tags: []*ec2.Tag{
{
Key: aws.String("Environment"),
Value: aws.String("production"),
},
},
},
},
},
},
}},
}
json := simplejson.New()
json.Set("region", "us-east-1")
json.Set("attributeName", "InstanceId")
filters := make(map[string]interface{})
filters["tag:Environment"] = []string{"production"}
json.Set("filters", filters)
result, _ := executor.handleGetEc2InstanceAttribute(context.Background(), json, &tsdb.TsdbQuery{})
Convey("Should equal production InstanceId", func() {
So(result[0].Text, ShouldEqual, "i-12345678")
})
})
}

View File

@@ -2,9 +2,11 @@ package influxdb
import (
"strconv"
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/tsdb"
)
type InfluxdbQueryParser struct{}
@@ -37,13 +39,7 @@ func (qp *InfluxdbQueryParser) Parse(model *simplejson.Json, dsInfo *models.Data
return nil, err
}
interval := model.Get("interval").MustString("")
if interval == "" && dsInfo.JsonData != nil {
dsInterval := dsInfo.JsonData.Get("timeInterval").MustString("")
if dsInterval != "" {
interval = dsInterval
}
}
parsedInterval, err := tsdb.GetIntervalFrom(dsInfo, model, time.Millisecond*1)
return &Query{
Measurement: measurement,
@@ -53,7 +49,7 @@ func (qp *InfluxdbQueryParser) Parse(model *simplejson.Json, dsInfo *models.Data
Tags: tags,
Selects: selects,
RawQuery: rawQuery,
Interval: interval,
Interval: parsedInterval,
Alias: alias,
UseRawQuery: useRawQuery,
}, nil

View File

@@ -2,6 +2,7 @@ package influxdb
import (
"testing"
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
@@ -115,7 +116,7 @@ func TestInfluxdbQueryParser(t *testing.T) {
So(len(res.GroupBy), ShouldEqual, 3)
So(len(res.Selects), ShouldEqual, 3)
So(len(res.Tags), ShouldEqual, 2)
So(res.Interval, ShouldEqual, ">20s")
So(res.Interval, ShouldEqual, time.Second*20)
So(res.Alias, ShouldEqual, "serie alias")
})
@@ -174,7 +175,7 @@ func TestInfluxdbQueryParser(t *testing.T) {
So(len(res.GroupBy), ShouldEqual, 2)
So(len(res.Selects), ShouldEqual, 1)
So(len(res.Tags), ShouldEqual, 0)
So(res.Interval, ShouldEqual, ">10s")
So(res.Interval, ShouldEqual, time.Second*10)
})
})
}

View File

@@ -1,5 +1,7 @@
package influxdb
import "time"
type Query struct {
Measurement string
Policy string
@@ -10,8 +12,7 @@ type Query struct {
RawQuery string
UseRawQuery bool
Alias string
Interval string
Interval time.Duration
}
type Tag struct {

View File

@@ -29,10 +29,8 @@ func (query *Query) Build(queryContext *tsdb.TsdbQuery) (string, error) {
res += query.renderGroupBy(queryContext)
}
interval, err := getDefinedInterval(query, queryContext)
if err != nil {
return "", err
}
calculator := tsdb.NewIntervalCalculator(&tsdb.IntervalOptions{})
interval := calculator.Calculate(queryContext.TimeRange, query.Interval)
res = strings.Replace(res, "$timeFilter", query.renderTimeFilter(queryContext), -1)
res = strings.Replace(res, "$interval", interval.Text, -1)
@@ -41,29 +39,6 @@ func (query *Query) Build(queryContext *tsdb.TsdbQuery) (string, error) {
return res, nil
}
func getDefinedInterval(query *Query, queryContext *tsdb.TsdbQuery) (*tsdb.Interval, error) {
defaultInterval := tsdb.CalculateInterval(queryContext.TimeRange)
if query.Interval == "" {
return &defaultInterval, nil
}
setInterval := strings.Replace(strings.Replace(query.Interval, "<", "", 1), ">", "", 1)
parsedSetInterval, err := time.ParseDuration(setInterval)
if err != nil {
return nil, err
}
if strings.Contains(query.Interval, ">") {
if defaultInterval.Value > parsedSetInterval {
return &defaultInterval, nil
}
}
return &tsdb.Interval{Value: parsedSetInterval, Text: setInterval}, nil
}
func (query *Query) renderTags() []string {
var res []string
for i, tag := range query.Tags {

View File

@@ -2,6 +2,7 @@ package influxdb
import (
"testing"
"time"
"strings"
@@ -38,7 +39,7 @@ func TestInfluxdbQueryBuilder(t *testing.T) {
Measurement: "cpu",
Policy: "policy",
GroupBy: []*QueryPart{groupBy1, groupBy3},
Interval: "10s",
Interval: time.Second * 10,
}
rawQuery, err := query.Build(queryContext)
@@ -52,7 +53,7 @@ func TestInfluxdbQueryBuilder(t *testing.T) {
Measurement: "cpu",
GroupBy: []*QueryPart{groupBy1, groupBy2, groupBy3},
Tags: []*Tag{tag1, tag2},
Interval: "5s",
Interval: time.Second * 5,
}
rawQuery, err := query.Build(queryContext)
@@ -64,7 +65,7 @@ func TestInfluxdbQueryBuilder(t *testing.T) {
query := &Query{
Selects: []*Select{{*qp1, *qp2, *mathPartDivideBy100}},
Measurement: "cpu",
Interval: "5s",
Interval: time.Second * 5,
}
rawQuery, err := query.Build(queryContext)
@@ -76,7 +77,7 @@ func TestInfluxdbQueryBuilder(t *testing.T) {
query := &Query{
Selects: []*Select{{*qp1, *qp2, *mathPartDivideByIntervalMs}},
Measurement: "cpu",
Interval: "5s",
Interval: time.Second * 5,
}
rawQuery, err := query.Build(queryContext)
@@ -117,7 +118,7 @@ func TestInfluxdbQueryBuilder(t *testing.T) {
Measurement: "cpu",
Policy: "policy",
GroupBy: []*QueryPart{groupBy1, groupBy3},
Interval: "10s",
Interval: time.Second * 10,
RawQuery: "Raw query",
UseRawQuery: true,
}

View File

@@ -2,14 +2,18 @@ package tsdb
import (
"fmt"
"strings"
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
)
var (
defaultRes int64 = 1500
minInterval time.Duration = 1 * time.Millisecond
year time.Duration = time.Hour * 24 * 365
day time.Duration = time.Hour * 24 * 365
defaultRes int64 = 1500
defaultMinInterval time.Duration = 1 * time.Millisecond
year time.Duration = time.Hour * 24 * 365
day time.Duration = time.Hour * 24
)
type Interval struct {
@@ -17,14 +21,68 @@ type Interval struct {
Value time.Duration
}
func CalculateInterval(timerange *TimeRange) Interval {
interval := time.Duration((timerange.MustGetTo().UnixNano() - timerange.MustGetFrom().UnixNano()) / defaultRes)
type intervalCalculator struct {
minInterval time.Duration
}
if interval < minInterval {
return Interval{Text: formatDuration(minInterval), Value: interval}
type IntervalCalculator interface {
Calculate(timeRange *TimeRange, minInterval time.Duration) Interval
}
type IntervalOptions struct {
MinInterval time.Duration
}
func NewIntervalCalculator(opt *IntervalOptions) *intervalCalculator {
if opt == nil {
opt = &IntervalOptions{}
}
return Interval{Text: formatDuration(roundInterval(interval)), Value: interval}
calc := &intervalCalculator{}
if opt.MinInterval == 0 {
calc.minInterval = defaultMinInterval
} else {
calc.minInterval = opt.MinInterval
}
return calc
}
func (ic *intervalCalculator) Calculate(timerange *TimeRange, minInterval time.Duration) Interval {
to := timerange.MustGetTo().UnixNano()
from := timerange.MustGetFrom().UnixNano()
interval := time.Duration((to - from) / defaultRes)
if interval < minInterval {
return Interval{Text: formatDuration(minInterval), Value: minInterval}
}
rounded := roundInterval(interval)
return Interval{Text: formatDuration(rounded), Value: rounded}
}
func GetIntervalFrom(dsInfo *models.DataSource, queryModel *simplejson.Json, defaultInterval time.Duration) (time.Duration, error) {
interval := queryModel.Get("interval").MustString("")
if interval == "" && dsInfo.JsonData != nil {
dsInterval := dsInfo.JsonData.Get("timeInterval").MustString("")
if dsInterval != "" {
interval = dsInterval
}
}
if interval == "" {
return defaultInterval, nil
}
interval = strings.Replace(strings.Replace(interval, "<", "", 1), ">", "", 1)
parsedInterval, err := time.ParseDuration(interval)
if err != nil {
return time.Duration(0), err
}
return parsedInterval, nil
}
func formatDuration(inter time.Duration) string {

View File

@@ -14,31 +14,33 @@ func TestInterval(t *testing.T) {
HomePath: "../../",
})
calculator := NewIntervalCalculator(&IntervalOptions{})
Convey("for 5min", func() {
tr := NewTimeRange("5m", "now")
interval := CalculateInterval(tr)
interval := calculator.Calculate(tr, time.Millisecond*1)
So(interval.Text, ShouldEqual, "200ms")
})
Convey("for 15min", func() {
tr := NewTimeRange("15m", "now")
interval := CalculateInterval(tr)
interval := calculator.Calculate(tr, time.Millisecond*1)
So(interval.Text, ShouldEqual, "500ms")
})
Convey("for 30min", func() {
tr := NewTimeRange("30m", "now")
interval := CalculateInterval(tr)
interval := calculator.Calculate(tr, time.Millisecond*1)
So(interval.Text, ShouldEqual, "1s")
})
Convey("for 1h", func() {
tr := NewTimeRange("1h", "now")
interval := CalculateInterval(tr)
interval := calculator.Calculate(tr, time.Millisecond*1)
So(interval.Text, ShouldEqual, "2s")
})
@@ -51,6 +53,7 @@ func TestInterval(t *testing.T) {
So(formatDuration(time.Second*61), ShouldEqual, "1m")
So(formatDuration(time.Millisecond*30), ShouldEqual, "30ms")
So(formatDuration(time.Hour*23), ShouldEqual, "23h")
So(formatDuration(time.Hour*24), ShouldEqual, "1d")
So(formatDuration(time.Hour*24*367), ShouldEqual, "1y")
})
})

View File

@@ -74,7 +74,7 @@ func (m *PostgresMacroEngine) evaluateMacro(name string, args []string) (string,
if len(args) == 0 {
return "", fmt.Errorf("missing time column argument for macro %v", name)
}
return fmt.Sprintf("%s >= to_timestamp(%d) AND %s <= to_timestamp(%d)", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
case "__timeFrom":
return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
case "__timeTo":
@@ -83,7 +83,7 @@ func (m *PostgresMacroEngine) evaluateMacro(name string, args []string) (string,
if len(args) < 2 {
return "", fmt.Errorf("macro %v needs time column and interval", name)
}
return fmt.Sprintf("(extract(epoch from \"%s\")/extract(epoch from %s::interval))::int", args[0], args[1]), nil
return fmt.Sprintf("(extract(epoch from \"%s\")/extract(epoch from %s::interval))::int*extract(epoch from %s::interval)", args[0], args[1], args[1]), nil
case "__unixEpochFilter":
if len(args) == 0 {
return "", fmt.Errorf("missing time column argument for macro %v", name)

View File

@@ -30,7 +30,7 @@ func TestMacroEngine(t *testing.T) {
sql, err := engine.Interpolate(timeRange, "WHERE $__timeFilter(time_column)")
So(err, ShouldBeNil)
So(sql, ShouldEqual, "WHERE time_column >= to_timestamp(18446744066914186738) AND time_column <= to_timestamp(18446744066914187038)")
So(sql, ShouldEqual, "WHERE extract(epoch from time_column) BETWEEN 18446744066914186738 AND 18446744066914187038")
})
Convey("interpolate __timeFrom function", func() {
@@ -45,7 +45,7 @@ func TestMacroEngine(t *testing.T) {
sql, err := engine.Interpolate(timeRange, "GROUP BY $__timeGroup(time_column,'5m')")
So(err, ShouldBeNil)
So(sql, ShouldEqual, "GROUP BY (extract(epoch from \"time_column\")/extract(epoch from '5m'::interval))::int")
So(sql, ShouldEqual, "GROUP BY (extract(epoch from \"time_column\")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)")
})
Convey("interpolate __timeTo function", func() {

View File

@@ -48,14 +48,16 @@ func NewPrometheusExecutor(dsInfo *models.DataSource) (tsdb.TsdbQueryEndpoint, e
}
var (
plog log.Logger
legendFormat *regexp.Regexp
plog log.Logger
legendFormat *regexp.Regexp
intervalCalculator tsdb.IntervalCalculator
)
func init() {
plog = log.New("tsdb.prometheus")
tsdb.RegisterTsdbQueryEndpoint("prometheus", NewPrometheusExecutor)
legendFormat = regexp.MustCompile(`\{\{\s*(.+?)\s*\}\}`)
intervalCalculator = tsdb.NewIntervalCalculator(&tsdb.IntervalOptions{MinInterval: time.Second * 1})
}
func (e *PrometheusExecutor) getClient(dsInfo *models.DataSource) (apiv1.API, error) {
@@ -88,7 +90,7 @@ func (e *PrometheusExecutor) Query(ctx context.Context, dsInfo *models.DataSourc
return nil, err
}
query, err := parseQuery(tsdbQuery.Queries, tsdbQuery)
query, err := parseQuery(dsInfo, tsdbQuery.Queries, tsdbQuery)
if err != nil {
return nil, err
}
@@ -138,7 +140,7 @@ func formatLegend(metric model.Metric, query *PrometheusQuery) string {
return string(result)
}
func parseQuery(queries []*tsdb.Query, queryContext *tsdb.TsdbQuery) (*PrometheusQuery, error) {
func parseQuery(dsInfo *models.DataSource, queries []*tsdb.Query, queryContext *tsdb.TsdbQuery) (*PrometheusQuery, error) {
queryModel := queries[0]
expr, err := queryModel.Model.Get("expr").String()
@@ -146,11 +148,6 @@ func parseQuery(queries []*tsdb.Query, queryContext *tsdb.TsdbQuery) (*Prometheu
return nil, err
}
step, err := queryModel.Model.Get("step").Int64()
if err != nil {
return nil, err
}
format := queryModel.Model.Get("legendFormat").MustString("")
start, err := queryContext.TimeRange.ParseFrom()
@@ -163,9 +160,18 @@ func parseQuery(queries []*tsdb.Query, queryContext *tsdb.TsdbQuery) (*Prometheu
return nil, err
}
dsInterval, err := tsdb.GetIntervalFrom(dsInfo, queryModel.Model, time.Second*15)
if err != nil {
return nil, err
}
intervalFactor := queryModel.Model.Get("intervalFactor").MustInt64(1)
interval := intervalCalculator.Calculate(queryContext.TimeRange, dsInterval)
step := time.Duration(int64(interval.Value) * intervalFactor)
return &PrometheusQuery{
Expr: expr,
Step: time.Second * time.Duration(step),
Step: step,
LegendFormat: format,
Start: start,
End: end,

View File

@@ -2,13 +2,21 @@ package prometheus
import (
"testing"
"time"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/components/simplejson"
p "github.com/prometheus/common/model"
. "github.com/smartystreets/goconvey/convey"
)
func TestPrometheus(t *testing.T) {
Convey("Prometheus", t, func() {
dsInfo := &models.DataSource{
JsonData: simplejson.New(),
}
Convey("converting metric name", func() {
metric := map[p.LabelName]p.LabelValue{
@@ -36,5 +44,108 @@ func TestPrometheus(t *testing.T) {
So(formatLegend(metric, query), ShouldEqual, `http_request_total{app="backend", device="mobile"}`)
})
Convey("parsing query model with step", func() {
json := `{
"expr": "go_goroutines",
"format": "time_series",
"refId": "A"
}`
jsonModel, _ := simplejson.NewJson([]byte(json))
queryContext := &tsdb.TsdbQuery{}
queryModels := []*tsdb.Query{
{Model: jsonModel},
}
Convey("with 48h time range", func() {
queryContext.TimeRange = tsdb.NewTimeRange("12h", "now")
model, err := parseQuery(dsInfo, queryModels, queryContext)
So(err, ShouldBeNil)
So(model.Step, ShouldEqual, time.Second*30)
})
})
Convey("parsing query model without step parameter", func() {
json := `{
"expr": "go_goroutines",
"format": "time_series",
"intervalFactor": 1,
"refId": "A"
}`
jsonModel, _ := simplejson.NewJson([]byte(json))
queryContext := &tsdb.TsdbQuery{}
queryModels := []*tsdb.Query{
{Model: jsonModel},
}
Convey("with 48h time range", func() {
queryContext.TimeRange = tsdb.NewTimeRange("48h", "now")
model, err := parseQuery(dsInfo, queryModels, queryContext)
So(err, ShouldBeNil)
So(model.Step, ShouldEqual, time.Minute*2)
})
Convey("with 1h time range", func() {
queryContext.TimeRange = tsdb.NewTimeRange("1h", "now")
model, err := parseQuery(dsInfo, queryModels, queryContext)
So(err, ShouldBeNil)
So(model.Step, ShouldEqual, time.Second*15)
})
})
Convey("parsing query model with intervalFactor", func() {
Convey("high intervalFactor", func() {
json := `{
"expr": "go_goroutines",
"format": "time_series",
"intervalFactor": 10,
"refId": "A"
}`
jsonModel, _ := simplejson.NewJson([]byte(json))
queryContext := &tsdb.TsdbQuery{}
queryModels := []*tsdb.Query{
{Model: jsonModel},
}
Convey("with 48h time range", func() {
queryContext.TimeRange = tsdb.NewTimeRange("48h", "now")
model, err := parseQuery(dsInfo, queryModels, queryContext)
So(err, ShouldBeNil)
So(model.Step, ShouldEqual, time.Minute*20)
})
})
Convey("low intervalFactor", func() {
json := `{
"expr": "go_goroutines",
"format": "time_series",
"intervalFactor": 1,
"refId": "A"
}`
jsonModel, _ := simplejson.NewJson([]byte(json))
queryContext := &tsdb.TsdbQuery{}
queryModels := []*tsdb.Query{
{Model: jsonModel},
}
Convey("with 48h time range", func() {
queryContext.TimeRange = tsdb.NewTimeRange("48h", "now")
model, err := parseQuery(dsInfo, queryModels, queryContext)
So(err, ShouldBeNil)
So(model.Step, ShouldEqual, time.Minute*2)
})
})
})
})
}

View File

@@ -1,5 +1,5 @@
import React from 'react';
import coreModule from '../core_module';
import { react2AngularDirective } from 'app/core/utils/react2angular';
export interface IProps {
password: string;
@@ -33,7 +33,5 @@ export class PasswordStrength extends React.Component<IProps, any> {
}
}
coreModule.directive('passwordStrength', function(reactDirective) {
return reactDirective(PasswordStrength, ['password']);
});
react2AngularDirective('passwordStrength', PasswordStrength, ['password']);

View File

@@ -1,5 +1,4 @@
import React from 'react';
import coreModule from 'app/core/core_module';
import { sortedColors } from 'app/core/utils/colors';
export interface IProps {
@@ -23,12 +22,15 @@ export class GfColorPalette extends React.Component<IProps, any> {
}
render() {
const colorPaletteItems = this.paletteColors.map((paletteColor) => {
const colorPaletteItems = this.paletteColors.map(paletteColor => {
const cssClass = paletteColor.toLowerCase() === this.props.color.toLowerCase() ? 'fa-circle-o' : 'fa-circle';
return (
<i key={paletteColor} className={"pointer fa " + cssClass}
style={{'color': paletteColor}}
onClick={this.onColorSelect(paletteColor)}>&nbsp;
<i
key={paletteColor}
className={'pointer fa ' + cssClass}
style={{ color: paletteColor }}
onClick={this.onColorSelect(paletteColor)}>
&nbsp;
</i>
);
});
@@ -40,6 +42,3 @@ export class GfColorPalette extends React.Component<IProps, any> {
}
}
coreModule.directive('gfColorPalette', function (reactDirective) {
return reactDirective(GfColorPalette, ['color', 'onColorSelect']);
});

View File

@@ -2,8 +2,8 @@ import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import Drop from 'tether-drop';
import coreModule from 'app/core/core_module';
import { ColorPickerPopover } from './ColorPickerPopover';
import { react2AngularDirective } from 'app/core/utils/react2angular';
export interface IProps {
color: string;
@@ -27,9 +27,7 @@ export class ColorPicker extends React.Component<IProps, any> {
}
openColorPicker() {
const dropContent = (
<ColorPickerPopover color={this.props.color} onColorSelect={this.onColorSelect} />
);
const dropContent = <ColorPickerPopover color={this.props.color} onColorSelect={this.onColorSelect} />;
let dropContentElem = document.createElement('div');
ReactDOM.render(dropContent, dropContentElem);
@@ -38,12 +36,12 @@ export class ColorPicker extends React.Component<IProps, any> {
target: this.pickerElem[0],
content: dropContentElem,
position: 'top center',
classes: 'drop-popover drop-popover--form',
openOn: 'hover',
classes: 'drop-popover',
openOn: 'click',
hoverCloseDelay: 200,
tetherOptions: {
constraints: [{ to: 'scrollParent', attachment: "none both" }]
}
constraints: [{ to: 'scrollParent', attachment: 'none both' }],
},
});
drop.on('close', this.closeColorPicker);
@@ -68,17 +66,14 @@ export class ColorPicker extends React.Component<IProps, any> {
return (
<div className="sp-replacer sp-light" onClick={this.openColorPicker} ref={this.setPickerElem}>
<div className="sp-preview">
<div className="sp-preview-inner" style={{backgroundColor: this.props.color}}>
</div>
<div className="sp-preview-inner" style={{ backgroundColor: this.props.color }} />
</div>
</div>
);
}
}
coreModule.directive('colorPicker', function (reactDirective) {
return reactDirective(ColorPicker, [
'color',
['onChange', { watchDepth: 'reference', wrapApply: true }]
]);
});
react2AngularDirective('colorPicker', ColorPicker, [
'color',
['onChange', { watchDepth: 'reference', wrapApply: true }],
]);

View File

@@ -1,7 +1,6 @@
import React from 'react';
import $ from 'jquery';
import tinycolor from 'tinycolor2';
import coreModule from 'app/core/core_module';
import { GfColorPalette } from './ColorPalette';
import { GfSpectrumPicker } from './SpectrumPicker';
@@ -57,10 +56,11 @@ export class ColorPickerPopover extends React.Component<IProps, any> {
let newColor = tinycolor(colorString);
if (newColor.isValid()) {
// Update only color state
let newColorString = newColor.toString();
this.setState({
color: newColor.toString(),
color: newColorString,
});
this.props.onColorSelect(newColor);
this.props.onColorSelect(newColorString);
}
}
@@ -115,7 +115,3 @@ export class ColorPickerPopover extends React.Component<IProps, any> {
);
}
}
coreModule.directive('gfColorPickerPopover', function (reactDirective) {
return reactDirective(ColorPickerPopover, ['color', 'onColorSelect']);
});

View File

@@ -1,6 +1,6 @@
import React from 'react';
import coreModule from 'app/core/core_module';
import {ColorPickerPopover} from './ColorPickerPopover';
import { ColorPickerPopover } from './ColorPickerPopover';
import { react2AngularDirective } from 'app/core/utils/react2angular';
export interface IProps {
series: any;
@@ -43,13 +43,11 @@ export class SeriesColorPicker extends React.Component<IProps, any> {
render() {
return (
<div className="graph-legend-popover">
{this.props.series && this.renderAxisSelection()}
{this.props.series.yaxis && this.renderAxisSelection()}
<ColorPickerPopover color={this.props.series.color} onColorSelect={this.onColorChange} />
</div>
);
}
}
coreModule.directive('seriesColorPicker', function(reactDirective) {
return reactDirective(SeriesColorPicker, ['series', 'onColorChange', 'onToggleAxis']);
});
react2AngularDirective('seriesColorPicker', SeriesColorPicker, ['series', 'onColorChange', 'onToggleAxis']);

View File

@@ -1,5 +1,4 @@
import React from 'react';
import coreModule from 'app/core/core_module';
import _ from 'lodash';
import $ from 'jquery';
import 'vendor/spectrum';
@@ -71,6 +70,3 @@ export class GfSpectrumPicker extends React.Component<IProps, any> {
}
}
coreModule.directive('gfSpectrumPicker', function (reactDirective) {
return reactDirective(GfSpectrumPicker, ['color', 'options', 'onColorSelect']);
});

View File

@@ -5,6 +5,7 @@
*/
import coreModule from '../../core_module';
/** @ngInject */
export function spectrumPicker() {
return {
restrict: 'E',

View File

@@ -159,6 +159,8 @@ export class FormDropdownCtrl {
}
updateValue(text) {
text = _.unescape(text);
if (text === '' || this.text === text) {
return;
}

View File

@@ -31,8 +31,8 @@ function (_, $, coreModule) {
}
});
$scope.$watch('playlistSrv', function(newValue) {
elem.toggleClass('playlist-active', _.isObject(newValue));
$scope.$watch('playlistSrv.isPlaying', function(newValue) {
elem.toggleClass('playlist-active', newValue === true);
});
}
};

View File

@@ -7,14 +7,15 @@ export class DeltaCtrl {
observer: any;
/** @ngInject */
constructor($rootScope) {
const waitForCompile = function(mutations) {
constructor(private $rootScope) {
const waitForCompile = (mutations) => {
if (mutations.length === 1) {
this.$rootScope.appEvent('json-diff-ready');
}
};
this.observer = new MutationObserver(waitForCompile.bind(this));
this.observer = new MutationObserver(waitForCompile);
const observerConfig = {
attributes: true,

View File

@@ -39,6 +39,8 @@ function (_, $, coreModule) {
return;
}
value = _.unescape(value);
$scope.$apply(function() {
var selected = _.find($scope.altSegments, {value: value});
if (selected) {

View File

@@ -1,7 +1,6 @@
import _ from 'lodash';
import moment from 'moment';
declare var window: any;
import {saveAs} from 'file-saver';
const DEFAULT_DATETIME_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ';
@@ -69,5 +68,5 @@ export function exportTableDataToCsv(table, excel = false) {
export function saveSaveBlob(payload, fname) {
var blob = new Blob([payload], { type: "text/csv;charset=utf-8" });
window.saveAs(blob, fname);
saveAs(blob, fname);
}

View File

@@ -0,0 +1,10 @@
import coreModule from 'app/core/core_module';
export function react2AngularDirective(name: string, component: any, options: any) {
coreModule.directive(name, ['reactDirective', reactDirective => {
return reactDirective(component, options);
}]);
}

View File

@@ -383,6 +383,7 @@ export class AlertTabCtrl {
test() {
this.testing = true;
this.testResult = false;
var payload = {
dashboard: this.dashboardSrv.getCurrent().getSaveModelClone(),

View File

@@ -39,7 +39,7 @@ export function annotationTooltipDirective($sanitize, dashboardSrv, contextSrv,
text = text + '<br />' + event.text;
}
} else if (title) {
text = title + '<br />' + text;
text = title + '<br />' + (_.isString(text) ? text : '');
title = '';
}

View File

@@ -20,10 +20,12 @@ export class DashboardCtrl {
dynamicDashboardSrv,
dashboardViewStateSrv,
contextSrv,
playlistSrv,
alertSrv,
$timeout) {
$scope.editor = { index: 0 };
$scope.playlistSrv = playlistSrv;
var resizeEventTimeout;

View File

@@ -19,6 +19,7 @@ export class DashNavCtrl {
private $location,
private backendSrv,
private contextSrv,
public playlistSrv,
navModelSrv) {
this.navModel = navModelSrv.getDashboardNav(this.dashboard, this);

View File

@@ -1,8 +1,7 @@
///<reference path="../../../headers/common.d.ts" />
import angular from 'angular';
import coreModule from 'app/core/core_module';
import {saveAs} from 'file-saver';
import coreModule from 'app/core/core_module';
import {DashboardExporter} from './exporter';
export class DashExportCtrl {
@@ -22,9 +21,8 @@ export class DashExportCtrl {
}
save() {
var blob = new Blob([angular.toJson(this.dash, true)], { type: "application/json;charset=utf-8" });
var wnd: any = window;
wnd.saveAs(blob, this.dash.title + '-' + new Date().getTime() + '.json');
var blob = new Blob([angular.toJson(this.dash, true)], {type: 'application/json;charset=utf-8'});
saveAs(blob, this.dash.title + '-' + new Date().getTime() + '.json');
}
saveJson() {
@@ -44,7 +42,7 @@ export function dashExportDirective() {
controller: DashExportCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {dismiss: "&"}
scope: {dismiss: '&'},
};
}

View File

@@ -35,7 +35,6 @@ export class DashboardModel {
gnetId: any;
meta: any;
events: any;
editMode: boolean;
constructor(data, meta?) {
if (!data) {

View File

@@ -3,25 +3,21 @@
<i class="fa fa-remove"></i>
</a>
<div class="gf-form-inline dash-row-add-panel-form">
<div class="gf-form">
<input type="text" class="gf-form-input max-width-14" ng-model='ctrl.panelSearch' give-focus='true' ng-keydown="ctrl.keyDown($event)" ng-change="ctrl.panelSearchChanged()" placeholder="panel search filter"></input>
</div>
</div>
<div class="gf-form width-10">
<input type="text" class="gf-form-input width-10" ng-model='ctrl.panelSearch' give-focus='true' ng-keydown="ctrl.keyDown($event)" ng-change="ctrl.panelSearchChanged()" placeholder="panel search filter"></input>
</div>
<div class="add-panel-panels-scroll">
<div class="add-panel-panels">
<div class="add-panel-item"
ng-repeat="panel in ctrl.panelHits"
ng-class="{active: $index === ctrl.activeIndex}"
ng-click="ctrl.addPanel(panel)"
ui-draggable="true"
drag="panel.id"
title="{{panel.name}}">
<img class="add-panel-item-img" ng-src="{{panel.info.logos.small}}"></img>
<div class="add-panel-item-name">{{panel.name}}</div>
</div>
</div>
</div>
<div class="add-panel-panels">
<div class="add-panel-item"
ng-repeat="panel in ctrl.panelHits"
ng-class="{active: $index === ctrl.activeIndex}"
ng-click="ctrl.addPanel(panel)"
ui-draggable="true"
drag="panel.id"
title="{{panel.name}}">
<img class="add-panel-item-img" ng-src="{{panel.info.logos.small}}"></img>
<div class="add-panel-item-name">{{panel.name}}</div>
</div>
</div>
</div>

View File

@@ -49,7 +49,10 @@ export class SaveDashboardAsModalCtrl {
if (dashboard.id > 0) {
this.clone.rows.forEach(row => {
row.panels.forEach(panel => {
delete panel.thresholds;
if (panel.type === "graph" && panel.alert) {
delete panel.thresholds;
}
delete panel.alert;
});
});

View File

@@ -0,0 +1,67 @@
import {SaveDashboardAsModalCtrl} from '../save_as_modal';
import {describe, it, expect} from 'test/lib/common';
describe('saving dashboard as', () => {
function scenario(name, panel, verify) {
describe(name, () => {
var json = {
title: "name",
rows: [ { panels: [
panel
]}]
};
var mockDashboardSrv = {
getCurrent: function() {
return {
id: 5,
getSaveModelClone: function() {
return json;
}
};
}
};
var ctrl = new SaveDashboardAsModalCtrl(mockDashboardSrv);
var ctx: any = {
clone: ctrl.clone,
ctrl: ctrl,
panel: {}
};
for (let row of ctrl.clone.rows) {
for (let panel of row.panels) {
ctx.panel = panel;
}
}
it("verify", () => {
verify(ctx);
});
});
}
scenario("default values", {}, (ctx) => {
var clone = ctx.clone;
expect(clone.id).toBe(null);
expect(clone.title).toBe("name Copy");
expect(clone.editable).toBe(true);
expect(clone.hideControls).toBe(false);
});
var graphPanel = { id: 1, type: "graph", alert: { rule: 1}, thresholds: { value: 3000} };
scenario("should remove alert from graph panel", graphPanel , (ctx) => {
expect(ctx.panel.alert).toBe(undefined);
});
scenario("should remove threshold from graph panel", graphPanel, (ctx) => {
expect(ctx.panel.thresholds).toBe(undefined);
});
scenario("singlestat should keep threshold", { id: 1, type: "singlestat", thresholds: { value: 3000} }, (ctx) => {
expect(ctx.panel.thresholds).not.toBe(undefined);
});
scenario("table should keep threshold", { id: 1, type: "table", thresholds: { value: 3000} }, (ctx) => {
expect(ctx.panel.thresholds).not.toBe(undefined);
});
});

View File

@@ -73,7 +73,6 @@ function(angular, _) {
dash.time = 0;
dash.refresh = 0;
dash.schemaVersion = 0;
dash.editMode = false;
// filter row and panels properties that should be ignored
dash.rows = _.filter(dash.rows, function(row) {

View File

@@ -154,7 +154,6 @@ function (angular, _, $, config) {
ctrl.editMode = false;
ctrl.fullscreen = false;
ctrl.dashboard.editMode = this.oldDashboardEditMode;
this.$scope.appEvent('panel-fullscreen-exit', {panelId: ctrl.panel.id});
@@ -176,10 +175,8 @@ function (angular, _, $, config) {
ctrl.editMode = this.state.edit && this.dashboard.meta.canEdit;
ctrl.fullscreen = true;
this.oldDashboardEditMode = this.dashboard.editMode;
this.oldTimeRange = ctrl.range;
this.fullscreenPanel = panelScope;
this.dashboard.editMode = false;
$(window).scrollTop(0);

View File

@@ -9,11 +9,23 @@ import config from 'app/core/config';
import TimeSeries from 'app/core/time_series2';
import TableModel from 'app/core/table_model';
import {coreModule, appEvents, contextSrv} from 'app/core/core';
import * as datemath from 'app/core/utils/datemath';
import * as fileExport from 'app/core/utils/file_export';
import * as flatten from 'app/core/utils/flatten';
import * as ticks from 'app/core/utils/ticks';
import {impressions} from 'app/features/dashboard/impression_store';
import builtInPlugins from './built_in_plugins';
import d3 from 'vendor/d3/d3';
// rxjs
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import * as datemath from 'app/core/utils/datemath';
import builtInPlugins from './buit_in_plugins';
import d3 from 'vendor/d3/d3';
// these imports add functions to Observable
import 'rxjs/add/observable/empty';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/combineAll';
System.config({
baseURL: 'public',
@@ -27,6 +39,12 @@ System.config({
text: 'vendor/plugin-text/text.js',
css: 'vendor/plugin-css/css.js'
},
meta: {
'*': {
esModule: true,
authorization: true,
}
}
});
// add cache busting
@@ -49,24 +67,39 @@ exposeToPlugin('lodash', _);
exposeToPlugin('moment', moment);
exposeToPlugin('jquery', jquery);
exposeToPlugin('angular', angular);
exposeToPlugin('d3', d3);
exposeToPlugin('rxjs/Subject', Subject);
exposeToPlugin('rxjs/Observable', Observable);
exposeToPlugin('d3', d3);
// backward compatible path
exposeToPlugin('vendor/npm/rxjs/Rx', {
Subject: Subject,
Observable: Observable
});
exposeToPlugin('app/features/dashboard/impression_store', {
impressions: impressions,
__esModule: true
});
exposeToPlugin('app/plugins/sdk', sdk);
exposeToPlugin('app/core/utils/datemath', datemath);
exposeToPlugin('app/core/utils/file_export', fileExport);
exposeToPlugin('app/core/utils/flatten', flatten);
exposeToPlugin('app/core/utils/kbn', kbn);
exposeToPlugin('app/core/utils/ticks', ticks);
exposeToPlugin('app/core/config', config);
exposeToPlugin('app/core/time_series', TimeSeries);
exposeToPlugin('app/core/time_series2', TimeSeries);
exposeToPlugin('app/core/table_model', TableModel);
exposeToPlugin('app/core/app_events', appEvents);
exposeToPlugin('app/core/core_module', coreModule);
exposeToPlugin('app/core/core_module', coreModule);
exposeToPlugin('app/core/core', {
coreModule: coreModule,
appEvents: appEvents,
contextSrv: contextSrv,
__esModule: true
});
import 'vendor/flot/jquery.flot';
@@ -79,7 +112,11 @@ import 'vendor/flot/jquery.flot.fillbelow';
import 'vendor/flot/jquery.flot.crosshair';
import 'vendor/flot/jquery.flot.dashes';
for (let flotDep of ['jquery.flot', 'jquery.flot.pie', 'jquery.flot.time']) {
const flotDeps = [
'jquery.flot', 'jquery.flot.pie', 'jquery.flot.time', 'jquery.flot.fillbelow', 'jquery.flot.crosshair',
'jquery.flot.stack', 'jquery.flot.selection', 'jquery.flot.stackpercent', 'jquery.flot.events'
];
for (let flotDep of flotDeps) {
exposeToPlugin(flotDep, {fakeDep: 1});
}

View File

@@ -41,7 +41,7 @@ function (angular, _, moment, dateMath, kbn, templatingVariable) {
item.namespace = templateSrv.replace(item.namespace, options.scopedVars);
item.metricName = templateSrv.replace(item.metricName, options.scopedVars);
item.dimensions = self.convertDimensionFormat(item.dimensions, options.scopeVars);
item.period = self.getPeriod(item, options);
item.period = String(self.getPeriod(item, options)); // use string format for period in graph query, and alerting
return _.extend({
refId: item.refId,
@@ -318,6 +318,8 @@ function (angular, _, moment, dateMath, kbn, templatingVariable) {
return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(function () {
return { status: 'success', message: 'Data source is working' };
}, function (err) {
return { status: 'error', message: err.message };
});
};
@@ -352,6 +354,7 @@ function (angular, _, moment, dateMath, kbn, templatingVariable) {
var t = angular.copy(target);
var scopedVar = {};
scopedVar[variable.name] = v;
t.refId = target.refId + '_' + v.value;
t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar);
return t;
}).value();

View File

@@ -37,7 +37,7 @@ describe('CloudWatchDatasource', function() {
InstanceId: 'i-12345678'
},
statistics: ['Average'],
period: 300
period: '300'
}
]
};
@@ -109,7 +109,7 @@ describe('CloudWatchDatasource', function() {
ctx.ds.query(query).then(function() {
var params = requestParams.queries[0];
expect(params.period).to.be(600);
expect(params.period).to.be('600');
done();
});
ctx.$rootScope.$apply();

View File

@@ -75,6 +75,12 @@ export class ElasticDatasource {
return this.request('POST', url, data).then(function(results) {
results.data.$$config = results.config;
return results.data;
}).catch(err => {
if (err.data && err.data.error) {
throw {message: 'Elasticsearch error: ' + err.data.error.reason, error: err.data.error};
}
throw err;
});
}

View File

@@ -20,6 +20,10 @@ export class PostgresDatasource {
return '\'' + value + '\'';
}
if (typeof value === 'number') {
return value.toString();
}
var quotedValues = _.map(value, function(val) {
return '\'' + val + '\'';
});

View File

@@ -16,8 +16,8 @@ class PostgresConfigCtrl {
const defaultQuery = `SELECT
extract(epoch from time_column) AS time,
title_column as title,
description_column as text
text_column as text,
tags_column as tags
FROM
metric_table
WHERE

View File

@@ -8,7 +8,7 @@ export class PromCompleter {
labelNameCache: any;
labelValueCache: any;
identifierRegexps = [/[\[\]a-zA-Z_0-9=]/];
identifierRegexps = [/\[/, /[a-zA-Z0-9_:]/];
constructor(private datasource: PrometheusDatasource) {
this.labelQueryCache = {};
@@ -73,13 +73,15 @@ export class PromCompleter {
});
}
if (prefix === '[') {
if (token.type === 'paren.lparen' && token.value === '[') {
var vectors = [];
for (let unit of ['s', 'm', 'h']) {
for (let value of [1,5,10,30]) {
vectors.push({caption: value+unit, value: '['+value+unit, meta: 'range vector'});
}
}
vectors.push({caption: '$__interval', value: '[$__interval', meta: 'range vector'});
vectors.push({caption: '$__interval_ms', value: '[$__interval_ms', meta: 'range vector'});
callback(null, vectors);
return;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,3 @@
///<reference path="../../../headers/common.d.ts" />
import _ from 'lodash';
import kbn from 'app/core/utils/kbn';
@@ -21,6 +19,7 @@ export class PrometheusDatasource {
basicAuth: any;
withCredentials: any;
metricsNameCache: any;
interval: string;
/** @ngInject */
constructor(instanceSettings,
@@ -36,6 +35,7 @@ export class PrometheusDatasource {
this.directUrl = instanceSettings.directUrl;
this.basicAuth = instanceSettings.basicAuth;
this.withCredentials = instanceSettings.withCredentials;
this.interval = instanceSettings.jsonData.timeInterval || '15s';
}
_request(method, url, requestId?) {
@@ -122,7 +122,7 @@ export class PrometheusDatasource {
} else {
for (let metricData of response.data.data.result) {
if (response.data.data.resultType === 'matrix') {
result.push(self.transformMetricData(metricData, activeTargets[index], start, end));
result.push(self.transformMetricData(metricData, activeTargets[index], start, end, queries[index].step));
} else if (response.data.data.resultType === 'vector') {
result.push(self.transformInstantMetricData(metricData, activeTargets[index]));
}
@@ -144,7 +144,6 @@ export class PrometheusDatasource {
var intervalFactor = target.intervalFactor || 1;
// Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
var adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
var scopedVars = options.scopedVars;
// If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
if (interval !== adjustedInterval) {
@@ -154,7 +153,7 @@ export class PrometheusDatasource {
"__interval_ms": {text: interval * 1000, value: interval * 1000},
});
}
target.step = query.step = interval;
query.step = interval;
// Only replace vars in expression after having (possibly) updated interval vars
query.expr = this.templateSrv.replace(target.expr, scopedVars, this.interpolateQueryExpr);
@@ -168,7 +167,7 @@ export class PrometheusDatasource {
if (interval !== 0 && range / intervalFactor / interval > 11000) {
interval = Math.ceil(range / intervalFactor / 11000);
}
return Math.max(interval * intervalFactor, minInterval);
return Math.max(interval * intervalFactor, minInterval, 1);
}
performTimeSeriesQuery(query, start, end) {
@@ -272,13 +271,13 @@ export class PrometheusDatasource {
});
}
transformMetricData(md, options, start, end) {
transformMetricData(md, options, start, end, step) {
var dps = [],
metricLabel = null;
metricLabel = this.createMetricLabel(md.metric, options);
var stepMs = parseInt(options.step) * 1000;
var stepMs = step * 1000;
var baseTimestamp = start * 1000;
for (let value of md.values) {
var dp_value = parseFloat(value[1]);

View File

@@ -1,3 +1,16 @@
<datasource-http-settings current="ctrl.current" suggest-url="http://localhost:9090">
</datasource-http-settings>
<div class="gf-form-group">
<div class="gf-form-inline">
<div class="gf-form">
<span class="gf-form-label">Scrape interval</span>
<input type="text" class="gf-form-input width-6" ng-model="ctrl.current.jsonData.timeInterval" spellcheck='false' placeholder="15s"></input>
<info-popover mode="right-absolute">
Set this to your global scrape interval defined in your Prometheus config file. This will be used as a lower limit for
the Prometheus step query parameter.
</info-popover>
</div>
</div>
</div>

View File

@@ -4,7 +4,8 @@
"id": "prometheus",
"includes": [
{"type": "dashboard", "name": "Prometheus Stats", "path": "dashboards/prometheus_stats.json"}
{"type": "dashboard", "name": "Prometheus Stats", "path": "dashboards/prometheus_stats.json"},
{"type": "dashboard", "name": "Grafana Stats", "path": "dashboards/grafana_stats.json"}
],
"metrics": true,

View File

@@ -44,12 +44,18 @@ describe('Prometheus editor completer', function() {
describe('When inside brackets', () => {
it('Should return range vectors', () => {
const session = getSessionStub({
currentToken: {},
tokens: [],
line: '',
currentToken: {type: 'paren.lparen', value: '[', index: 2, start: 9},
tokens: [
{type: 'identifier', value: 'node_cpu'},
{type: 'paren.lparen', value: '['}
],
line: 'node_cpu[',
});
completer.getCompletions(editor, session, {row: 0, column: 10}, '[', (s, res) => {
expect(res[0]).to.eql({caption: '1s', value: '[1s', meta: 'range vector'});
return completer.getCompletions(editor, session, {row: 0, column: 10}, '[', (s, res) => {
expect(res[0].caption).to.eql('1s');
expect(res[0].value).to.eql('[1s');
expect(res[0].meta).to.eql('range vector');
});
});
});

View File

@@ -5,7 +5,7 @@ import {PrometheusDatasource} from '../datasource';
describe('PrometheusDatasource', function() {
var ctx = new helpers.ServiceTestContext();
var instanceSettings = {url: 'proxied', directUrl: 'direct', user: 'test', password: 'mupp' };
var instanceSettings = {url: 'proxied', directUrl: 'direct', user: 'test', password: 'mupp', jsonData: {}};
beforeEach(angularMocks.module('grafana.core'));
beforeEach(angularMocks.module('grafana.services'));
@@ -294,6 +294,20 @@ describe('PrometheusDatasource', function() {
ctx.ds.query(query);
ctx.$httpBackend.verifyNoOutstandingExpectation();
});
it('step should never go below 1', function() {
var query = {
// 6 hour range
range: { from: moment(1508318768202), to: moment(1508318770118) },
targets: [{expr: 'test'}],
interval: '100ms'
};
var urlExpected = 'proxied/api/v1/query_range?query=test&start=1508318769&end=1508318771&step=1';
ctx.$httpBackend.expect('GET', urlExpected).respond(response);
ctx.ds.query(query);
ctx.$httpBackend.verifyNoOutstandingExpectation();
});
it('should be auto interval when greater than min interval', function() {
var query = {
// 6 hour range

View File

@@ -8,7 +8,7 @@ import PrometheusMetricFindQuery from '../metric_find_query';
describe('PrometheusMetricFindQuery', function() {
var ctx = new helpers.ServiceTestContext();
var instanceSettings = {url: 'proxied', directUrl: 'direct', user: 'test', password: 'mupp' };
var instanceSettings = {url: 'proxied', directUrl: 'direct', user: 'test', password: 'mupp', jsonData: {}};
beforeEach(angularMocks.module('grafana.core'));
beforeEach(angularMocks.module('grafana.services'));

View File

@@ -34,7 +34,7 @@ class GettingStartedPanelCtrl extends PanelCtrl {
check: () => {
return $q.when(
datasourceSrv.getMetricSources().filter(item => {
return item.meta.builtIn === false;
return item.meta.builtIn !== true;
}).length > 0
);
}

View File

@@ -29,7 +29,7 @@ define([
$scope.setOverride = function(item, subItem) {
// handle color overrides
if (item.propertyName === 'color') {
$scope.openColorSelector();
$scope.openColorSelector($scope.override['color']);
return;
}
@@ -52,15 +52,17 @@ define([
$scope.ctrl.render();
};
$scope.openColorSelector = function() {
$scope.openColorSelector = function(color) {
var fakeSeries = {color: color};
popoverSrv.show({
element: $element.find(".dropdown")[0],
position: 'top center',
openOn: 'click',
template: '<series-color-picker onColorChange="colorSelected" />',
template: '<series-color-picker series="series" onColorChange="colorSelected" />',
model: {
autoClose: true,
colorSelected: $scope.colorSelected,
series: fakeSeries
},
onClose: function() {
$scope.ctrl.render();

View File

@@ -152,7 +152,7 @@ function drawLegendValues(elem, colorScale, rangeFrom, rangeTo, maxValue, minVal
.tickSize(2);
let colorRect = legendElem.find(":first-child");
let posY = colorRect.height() + 2;
let posY = getSvgElemHeight(legendElem) + 2;
let posX = getSvgElemX(colorRect);
d3.select(legendElem.get(0)).append("g")
@@ -256,7 +256,16 @@ function getOpacityScale(options, maxValue, minValue = 0) {
function getSvgElemX(elem) {
let svgElem = elem.get(0);
if (svgElem && svgElem.x && svgElem.x.baseVal) {
return elem.get(0).x.baseVal.value;
return svgElem.x.baseVal.value;
} else {
return 0;
}
}
function getSvgElemHeight(elem) {
let svgElem = elem.get(0);
if (svgElem && svgElem.height && svgElem.height.baseVal) {
return svgElem.height.baseVal.value;
} else {
return 0;
}

View File

@@ -37,7 +37,16 @@ function elasticHistogramToHeatmap(seriesList) {
bucket = heatmap[time] = {x: time, buckets: {}};
}
bucket.buckets[bound] = {y: bound, count: count, values: [], points: []};
bucket.buckets[bound] = {
y: bound,
count: count,
bounds: {
top: null,
bottom: bound
},
values: [],
points: []
};
}
}

View File

@@ -83,7 +83,7 @@ export class HeatmapTooltip {
let xData = data.buckets[xBucketIndex];
// Search in special 'zero' bucket also
let yData = _.find(xData.buckets, (bucket, bucketIndex) => {
return bucket.bounds.bottom === yBucketIndex || bucketIndex === yBucketIndex;
return bucket.bounds.bottom === yBucketIndex || bucketIndex === yBucketIndex.toString();
});
let tooltipTimeFormat = 'YYYY-MM-DD HH:mm:ss';
@@ -168,7 +168,8 @@ export class HeatmapTooltip {
let yBucketSize = this.scope.ctrl.data.yBucketSize;
let {min, max, ticks} = this.scope.ctrl.data.yAxis;
let histogramData = _.map(xBucket.buckets, bucket => {
return [bucket.bounds.bottom, bucket.values.length];
let count = bucket.count !== undefined ? bucket.count : bucket.values.length;
return [bucket.bounds.bottom, count];
});
histogramData = _.filter(histogramData, d => {
return d[0] >= min && d[0] <= max;

View File

@@ -71,9 +71,8 @@ export default function link(scope, elem, attrs, ctrl) {
function getYAxisWidth(elem) {
let axis_text = elem.selectAll(".axis-y text").nodes();
let max_text_width = _.max(_.map(axis_text, text => {
let el = $(text);
// Use JQuery outerWidth() to compute full element width
return el.outerWidth();
// Use SVG getBBox method
return text.getBBox().width;
}));
return max_text_width;

View File

@@ -224,17 +224,17 @@ describe('ES Histogram converter', () => {
'1422774000000': {
x: 1422774000000,
buckets: {
'1': { y: 1, count: 1, values: [], points: [] },
'2': { y: 2, count: 5, values: [], points: [] },
'3': { y: 3, count: 0, values: [], points: [] }
'1': { y: 1, count: 1, values: [], points: [], bounds: {bottom: 1, top: null}},
'2': { y: 2, count: 5, values: [], points: [], bounds: {bottom: 2, top: null}},
'3': { y: 3, count: 0, values: [], points: [], bounds: {bottom: 3, top: null}}
}
},
'1422774060000': {
x: 1422774060000,
buckets: {
'1': { y: 1, count: 0, values: [], points: [] },
'2': { y: 2, count: 3, values: [], points: [] },
'3': { y: 3, count: 1, values: [], points: [] }
'1': { y: 1, count: 0, values: [], points: [], bounds: {bottom: 1, top: null}},
'2': { y: 2, count: 3, values: [], points: [], bounds: {bottom: 2, top: null}},
'3': { y: 3, count: 1, values: [], points: [], bounds: {bottom: 3, top: null}}
}
},
};

View File

@@ -66,7 +66,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
thresholds: '',
colorBackground: false,
colorValue: false,
colors: ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
colors: ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
sparkline: {
show: false,
full: false,

View File

@@ -27,8 +27,8 @@ $white: #fff;
// -------------------------
$blue: #33B5E5;
$blue-dark: #005f81;
$green: #609000;
$red: #CC3900;
$green: #299c46;
$red: #d44a3a;
$yellow: #ECBB13;
$pink: #FF4444;
$purple: #9933CC;
@@ -130,20 +130,20 @@ $table-border: $dark-3; // table and cell border
// Buttons
// -------------------------
$btn-primary-bg: $brand-primary;
$btn-primary-bg-hl: lighten($brand-primary, 8%);
$btn-primary-bg: #ff6600;
$btn-primary-bg-hl: #bc3e06;
$btn-secondary-bg: $blue-dark;
$btn-secondary-bg-hl: lighten($blue-dark, 5%);
$btn-success-bg: lighten($green, 3%);
$btn-success-bg-hl: darken($green, 3%);
$btn-success-bg: $green;
$btn-success-bg-hl: darken($green, 6%);
$btn-warning-bg: $brand-warning;
$btn-warning-bg-hl: lighten($brand-warning, 8%);
$btn-danger-bg: $red;
$btn-danger-bg-hl: lighten($red, 5%);
$btn-danger-bg-hl: darken($red, 8%);
$btn-inverse-bg: $dark-3;
$btn-inverse-bg-hl: lighten($dark-3, 4%);

View File

@@ -32,8 +32,8 @@ $white: #fff;
// -------------------------
$blue: #2AB2E4;
$blue-dark: #3CAAD6;
$green: #28B62C;
$red: #FF4136;
$green: #3aa655;
$red: #d44939;
$yellow: #FF851B;
$orange: #Ff7941;
$pink: #E671B8;

View File

@@ -121,6 +121,7 @@ $gf-form-margin: 0.25rem;
// text areas should be scrollable
@at-root textarea#{&} {
overflow: auto;
white-space: pre-wrap;
}
// Unstyle the caret on `<select>`s in IE10+.

View File

@@ -211,15 +211,6 @@
margin-right: 0px;
line-height: initial;
}
.close {
margin-right: 5px;
color: $link-color;
opacity: 0.7;
text-shadow: none;
}
.editor-row {
padding: 5px;
}
}
.annotation-tags {

View File

@@ -61,6 +61,7 @@
margin: 0 $panel-margin $panel-margin*2 $panel-margin;
padding: $panel-margin*2;
display: flex;
flex-direction: row;
}
.dash-row-dropview-close {
@@ -71,19 +72,10 @@
height: 20px;
}
.add-panel-panels-scroll {
width: 100%;
overflow: auto;
-ms-overflow-style: none;
&::-webkit-scrollbar {
display: none
}
}
.add-panel-panels {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.add-panel-item {

View File

@@ -2962,8 +2962,11 @@ Licensed under the MIT license.
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
if (plot.isSelecting) {
return;
}
triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters

View File

@@ -152,6 +152,10 @@ The plugin allso adds the following methods to the plot object:
plot.getPlaceholder().trigger("plotselecting", [ null ]);
}
setTimeout(function() {
plot.isSelecting = false;
}, 10);
return false;
}
@@ -218,6 +222,7 @@ The plugin allso adds the following methods to the plot object:
setSelectionPos(selection.second, pos);
if (selectionIsSane()) {
plot.isSelecting = true;
selection.show = true;
plot.triggerRedrawOverlay();
}

View File

@@ -21,7 +21,7 @@ RUN gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A170311380
RUN curl --silent --location https://rpm.nodesource.com/setup_6.x | bash - && \
yum install -y nodejs --nogpgcheck
ENV GOLANG_VERSION 1.9.1
ENV GOLANG_VERSION 1.9.2
RUN wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo && \
yum install -y yarn --nogpgcheck && \