diff --git a/CHANGELOG.md b/CHANGELOG.md
index ba944182794..f4b1928cef3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,18 +1,35 @@
# 5.0.0 (unreleased)
+### WIP (in develop branch currently as its unstable or unfinished)
+- Dashboard folders
+- User groups
+- Dashboard permissions (on folder & dashboard level), permissions can be assigned to groups or individual users
+- UX changes to nav & side menu
+- New dashboard grid layout system
+
+# 4.5.0 (unreleased)
+
## New Features
-* **Table panel**: Render cell values as links that can use url that uses variables from current table row. [#3754](https://github.com/grafana/grafana/issues/3754)
+* **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).
## 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).
+
## 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)
# 4.4.4 (unreleased)
diff --git a/README.md b/README.md
index 41f777d5dec..ab68eec24fd 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-[Grafana](https://grafana.com) [](https://circleci.com/gh/grafana/grafana)
+[Grafana](https://grafana.com) [](https://circleci.com/gh/grafana/grafana) [](https://goreportcard.com/report/github.com/grafana/grafana)
================
[Website](https://grafana.com) |
[Twitter](https://twitter.com/grafana) |
diff --git a/ROADMAP.md b/ROADMAP.md
index 260c4151442..62e6719c4f0 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,31 +1,29 @@
-# Roadmap (2017-04-23)
+# Roadmap (2017-08-29)
This roadmap is a tentative plan for the core development team. Things change constantly as PRs come in and priorities change.
But it will give you an idea of our current vision and plan.
### Short term (1-4 months)
- - New Heatmap Panel (Implemented and available in master)
- - Support for MySQL & Postgres as data sources (Work started and a alpha version for MySQL is available in master)
- - User Groups & Dashboard folders with ACLs (work started, not yet completed, https://github.com/grafana/grafana/issues/1611#issuecomment-287742633)
- - Improve new user UX
- - Improve docs
- - Support for alerting for Elasticsearch (can be tested in [branch](https://github.com/grafana/grafana/tree/alerting-elasticsearch) but needs more work)
- - Graph annotations (create from grafana, region annotations, better annotation viz)
- - Improve alerting (clustering, silence rules)
+ - Release Grafana v4.5 with fixes and minor enhancements
+ - Release Grafana v5
+ - User groups
+ - Dashboard folders
+ - Dashboard permissions (on folders as well), permissions on groups or users
+ - New Dashboard layout engine
+ - New sidemenu & nav UX
+ - Elasticsearch alerting
### Long term
-- Improved dashboard panel layout engine (to make it easier and enable more flexible layouts)
- Backend plugins to support more Auth options, Alerting data sources & notifications
- Universial time series transformations for any data source (meta queries)
- Reporting
- Web socket & live data streams
-- Migrate to Angular2
+- Migrate to Angular2 or react
### Outside contributions
We know this is being worked on right now by contributors (and we hope to merge it when it's ready).
-- Dashboard revisions (be able to revert dashboard changes)
- Clustering for alert engine (load distribution)
diff --git a/package.json b/package.json
index e70633ac9a8..2f4b7ad6707 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"company": "Coding Instinct AB"
},
"name": "grafana",
- "version": "5.0.0-pre1",
+ "version": "4.5.0-pre1",
"repository": {
"type": "git",
"url": "http://github.com/grafana/grafana.git"
@@ -63,6 +63,7 @@
},
"license": "Apache-2.0",
"dependencies": {
+ "ace-builds": "^1.2.8",
"eventemitter3": "^2.0.2",
"gaze": "^1.1.2",
"grunt-jscs": "3.0.1",
diff --git a/pkg/api/avatar/avatar.go b/pkg/api/avatar/avatar.go
index 41ce857db4f..7abb5da1cec 100644
--- a/pkg/api/avatar/avatar.go
+++ b/pkg/api/avatar/avatar.go
@@ -217,7 +217,10 @@ func (this *thunderTask) Fetch() {
this.Done()
}
-var client = &http.Client{}
+var client *http.Client = &http.Client{
+ Timeout: time.Second * 2,
+ Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
+}
func (this *thunderTask) fetch() error {
this.Avatar.timestamp = time.Now()
diff --git a/pkg/api/cloudwatch/metrics.go b/pkg/api/cloudwatch/metrics.go
index 2daa93bfb03..a7d5e528a4a 100644
--- a/pkg/api/cloudwatch/metrics.go
+++ b/pkg/api/cloudwatch/metrics.go
@@ -91,7 +91,7 @@ func init() {
"AWS/SWF": {"DecisionTaskScheduleToStartTime", "DecisionTaskStartToCloseTime", "DecisionTasksCompleted", "StartedDecisionTasksTimedOutOnClose", "WorkflowStartToCloseTime", "WorkflowsCanceled", "WorkflowsCompleted", "WorkflowsContinuedAsNew", "WorkflowsFailed", "WorkflowsTerminated", "WorkflowsTimedOut",
"ActivityTaskScheduleToCloseTime", "ActivityTaskScheduleToStartTime", "ActivityTaskStartToCloseTime", "ActivityTasksCanceled", "ActivityTasksCompleted", "ActivityTasksFailed", "ScheduledActivityTasksTimedOutOnClose", "ScheduledActivityTasksTimedOutOnStart", "StartedActivityTasksTimedOutOnClose", "StartedActivityTasksTimedOutOnHeartbeat"},
"AWS/VPN": {"TunnelState", "TunnelDataIn", "TunnelDataOut"},
- "AWS/WAF": {"AllowedRequests", "BlockedRequests", "CountedRequests"},
+ "WAF": {"AllowedRequests", "BlockedRequests", "CountedRequests"},
"AWS/WorkSpaces": {"Available", "Unhealthy", "ConnectionAttempt", "ConnectionSuccess", "ConnectionFailure", "SessionLaunchTime", "InSessionLatency", "SessionDisconnect"},
"KMS": {"SecondsUntilKeyMaterialExpiration"},
}
@@ -133,7 +133,7 @@ func init() {
"AWS/StorageGateway": {"GatewayId", "GatewayName", "VolumeId"},
"AWS/SWF": {"Domain", "WorkflowTypeName", "WorkflowTypeVersion", "ActivityTypeName", "ActivityTypeVersion"},
"AWS/VPN": {"VpnId", "TunnelIpAddress"},
- "AWS/WAF": {"Rule", "WebACL"},
+ "WAF": {"Rule", "WebACL"},
"AWS/WorkSpaces": {"DirectoryId", "WorkspaceId"},
"KMS": {"KeyId"},
}
@@ -292,11 +292,6 @@ func getAllMetrics(cwData *datasourceInfo) (cloudwatch.ListMetricsOutput, error)
var metricsCacheLock sync.Mutex
func getMetricsForCustomMetrics(dsInfo *datasourceInfo, getAllMetrics func(*datasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
- result, err := getAllMetrics(dsInfo)
- if err != nil {
- return []string{}, err
- }
-
metricsCacheLock.Lock()
defer metricsCacheLock.Unlock()
@@ -314,6 +309,10 @@ func getMetricsForCustomMetrics(dsInfo *datasourceInfo, getAllMetrics func(*data
if customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
}
+ result, err := getAllMetrics(dsInfo)
+ if err != nil {
+ return []string{}, err
+ }
customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
@@ -330,11 +329,6 @@ func getMetricsForCustomMetrics(dsInfo *datasourceInfo, getAllMetrics func(*data
var dimensionsCacheLock sync.Mutex
func getDimensionsForCustomMetrics(dsInfo *datasourceInfo, getAllMetrics func(*datasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
- result, err := getAllMetrics(dsInfo)
- if err != nil {
- return []string{}, err
- }
-
dimensionsCacheLock.Lock()
defer dimensionsCacheLock.Unlock()
@@ -352,6 +346,10 @@ func getDimensionsForCustomMetrics(dsInfo *datasourceInfo, getAllMetrics func(*d
if customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
}
+ result, err := getAllMetrics(dsInfo)
+ if err != nil {
+ return []string{}, err
+ }
customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
diff --git a/pkg/api/pluginproxy/ds_proxy.go b/pkg/api/pluginproxy/ds_proxy.go
index 11215a6eaa3..fff8d099d4b 100644
--- a/pkg/api/pluginproxy/ds_proxy.go
+++ b/pkg/api/pluginproxy/ds_proxy.go
@@ -2,15 +2,17 @@ package pluginproxy
import (
"bytes"
+ "encoding/json"
"errors"
"fmt"
- "html/template"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"net/url"
+ "strconv"
"strings"
+ "text/template"
"time"
"github.com/grafana/grafana/pkg/api/cloudwatch"
@@ -23,9 +25,20 @@ import (
)
var (
- logger log.Logger = log.New("data-proxy-log")
+ logger log.Logger = log.New("data-proxy-log")
+ client *http.Client = &http.Client{
+ Timeout: time.Second * 30,
+ Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
+ }
+ tokenCache = map[int64]*jwtToken{}
)
+type jwtToken struct {
+ ExpiresOn time.Time `json:"-"`
+ ExpiresOnString string `json:"expires_on"`
+ AccessToken string `json:"access_token"`
+}
+
type DataSourceProxy struct {
ds *m.DataSource
ctx *middleware.Context
@@ -229,8 +242,6 @@ func checkWhiteList(c *middleware.Context, host string) bool {
}
func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
- logger.Info("ApplyDataSourceRouteRules", "route", proxy.route.Path, "proxyPath", proxy.proxyPath)
-
proxy.proxyPath = strings.TrimPrefix(proxy.proxyPath, proxy.route.Path)
data := templateData{
@@ -238,8 +249,6 @@ func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
SecureJsonData: proxy.ds.SecureJsonData.Decrypt(),
}
- logger.Info("Apply Route Rule", "rule", proxy.route.Path)
-
routeUrl, err := url.Parse(proxy.route.Url)
if err != nil {
logger.Error("Error parsing plugin route url")
@@ -254,25 +263,86 @@ func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
if err := addHeaders(&req.Header, proxy.route, data); err != nil {
logger.Error("Failed to render plugin headers", "error", err)
}
+
+ if proxy.route.TokenAuth != nil {
+ if token, err := proxy.getAccessToken(data); err != nil {
+ logger.Error("Failed to get access token", "error", err)
+ } else {
+ req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
+ }
+ }
+
+ logger.Info("Requesting", "url", req.URL.String())
+}
+
+func (proxy *DataSourceProxy) getAccessToken(data templateData) (string, error) {
+ if cachedToken, found := tokenCache[proxy.ds.Id]; found {
+ if cachedToken.ExpiresOn.After(time.Now().Add(time.Second * 10)) {
+ logger.Info("Using token from cache")
+ return cachedToken.AccessToken, nil
+ }
+ }
+
+ urlInterpolated, err := interpolateString(proxy.route.TokenAuth.Url, data)
+ if err != nil {
+ return "", err
+ }
+
+ params := make(url.Values)
+ for key, value := range proxy.route.TokenAuth.Params {
+ if interpolatedParam, err := interpolateString(value, data); err != nil {
+ return "", err
+ } else {
+ params.Add(key, interpolatedParam)
+ }
+ }
+
+ getTokenReq, _ := http.NewRequest("POST", urlInterpolated, bytes.NewBufferString(params.Encode()))
+ getTokenReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
+ getTokenReq.Header.Add("Content-Length", strconv.Itoa(len(params.Encode())))
+
+ resp, err := client.Do(getTokenReq)
+ if err != nil {
+ return "", err
+ }
+
+ defer resp.Body.Close()
+
+ var token jwtToken
+ if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
+ return "", err
+ }
+
+ expiresOnEpoch, _ := strconv.ParseInt(token.ExpiresOnString, 10, 64)
+ token.ExpiresOn = time.Unix(expiresOnEpoch, 0)
+ tokenCache[proxy.ds.Id] = &token
+
+ logger.Info("Got new access token", "ExpiresOn", token.ExpiresOn)
+ return token.AccessToken, nil
+}
+
+func interpolateString(text string, data templateData) (string, error) {
+ t, err := template.New("content").Parse(text)
+ if err != nil {
+ return "", errors.New(fmt.Sprintf("Could not parse template %s.", text))
+ }
+
+ var contentBuf bytes.Buffer
+ err = t.Execute(&contentBuf, data)
+ if err != nil {
+ return "", errors.New(fmt.Sprintf("Failed to execute template %s.", text))
+ }
+
+ return contentBuf.String(), nil
}
func addHeaders(reqHeaders *http.Header, route *plugins.AppPluginRoute, data templateData) error {
for _, header := range route.Headers {
- var contentBuf bytes.Buffer
- t, err := template.New("content").Parse(header.Content)
+ interpolated, err := interpolateString(header.Content, data)
if err != nil {
- return errors.New(fmt.Sprintf("could not parse header content template for header %s.", header.Name))
+ return err
}
-
- err = t.Execute(&contentBuf, data)
- if err != nil {
- return errors.New(fmt.Sprintf("failed to execute header content template for header %s.", header.Name))
- }
-
- value := contentBuf.String()
-
- logger.Info("Adding headers", "name", header.Name, "value", value)
- reqHeaders.Add(header.Name, value)
+ reqHeaders.Add(header.Name, interpolated)
}
return nil
diff --git a/pkg/api/pluginproxy/ds_proxy_test.go b/pkg/api/pluginproxy/ds_proxy_test.go
index 831c4e2a3e4..0a900ad3a6d 100644
--- a/pkg/api/pluginproxy/ds_proxy_test.go
+++ b/pkg/api/pluginproxy/ds_proxy_test.go
@@ -148,5 +148,18 @@ func TestDSRouteRule(t *testing.T) {
So(queryVals["p"][0], ShouldEqual, "password")
})
})
+
+ Convey("When interpolating string", func() {
+ data := templateData{
+ SecureJsonData: map[string]string{
+ "Test": "0asd+asd",
+ },
+ }
+
+ interpolated, err := interpolateString("{{.SecureJsonData.Test}}", data)
+ So(err, ShouldBeNil)
+ So(interpolated, ShouldEqual, "0asd+asd")
+ })
+
})
}
diff --git a/pkg/plugins/app_plugin.go b/pkg/plugins/app_plugin.go
index 878d91f11f4..b070ba592f0 100644
--- a/pkg/plugins/app_plugin.go
+++ b/pkg/plugins/app_plugin.go
@@ -23,11 +23,12 @@ type AppPlugin struct {
}
type AppPluginRoute struct {
- Path string `json:"path"`
- Method string `json:"method"`
- ReqRole models.RoleType `json:"reqRole"`
- Url string `json:"url"`
- Headers []AppPluginRouteHeader `json:"headers"`
+ Path string `json:"path"`
+ Method string `json:"method"`
+ ReqRole models.RoleType `json:"reqRole"`
+ Url string `json:"url"`
+ Headers []AppPluginRouteHeader `json:"headers"`
+ TokenAuth *JwtTokenAuth `json:"tokenAuth"`
}
type AppPluginRouteHeader struct {
@@ -35,6 +36,11 @@ type AppPluginRouteHeader struct {
Content string `json:"content"`
}
+type JwtTokenAuth struct {
+ Url string `json:"url"`
+ Params map[string]string `json:"params"`
+}
+
func (app *AppPlugin) Load(decoder *json.Decoder, pluginDir string) error {
if err := decoder.Decode(&app); err != nil {
return err
diff --git a/pkg/tsdb/influxdb/query.go b/pkg/tsdb/influxdb/query.go
index f271c5d245f..0bcdf1d5291 100644
--- a/pkg/tsdb/influxdb/query.go
+++ b/pkg/tsdb/influxdb/query.go
@@ -151,8 +151,12 @@ func (query *Query) renderMeasurement() string {
func (query *Query) renderWhereClause() string {
res := " WHERE "
conditions := query.renderTags()
- res += strings.Join(conditions, " ")
if len(conditions) > 0 {
+ if len(conditions) > 1 {
+ res += "(" + strings.Join(conditions, " ") + ")"
+ } else {
+ res += conditions[0]
+ }
res += " AND "
}
diff --git a/pkg/tsdb/influxdb/query_test.go b/pkg/tsdb/influxdb/query_test.go
index 533df27f91f..0977ef8c1ce 100644
--- a/pkg/tsdb/influxdb/query_test.go
+++ b/pkg/tsdb/influxdb/query_test.go
@@ -57,7 +57,7 @@ func TestInfluxdbQueryBuilder(t *testing.T) {
rawQuery, err := query.Build(queryContext)
So(err, ShouldBeNil)
- So(rawQuery, ShouldEqual, `SELECT mean("value") FROM "cpu" WHERE "hostname" = 'server1' OR "hostname" = 'server2' AND time > now() - 5m GROUP BY time(5s), "datacenter" fill(null)`)
+ So(rawQuery, ShouldEqual, `SELECT mean("value") FROM "cpu" WHERE ("hostname" = 'server1' OR "hostname" = 'server2') AND time > now() - 5m GROUP BY time(5s), "datacenter" fill(null)`)
})
Convey("can build query with math part", func() {
diff --git a/pkg/tsdb/mysql/mysql.go b/pkg/tsdb/mysql/mysql.go
index 09ded090089..e568ca730c1 100644
--- a/pkg/tsdb/mysql/mysql.go
+++ b/pkg/tsdb/mysql/mysql.go
@@ -1,6 +1,7 @@
package mysql
import (
+ "container/list"
"context"
"database/sql"
"fmt"
@@ -245,6 +246,7 @@ func (e MysqlExecutor) getTypedRowData(types []*sql.ColumnType, rows *core.Rows)
func (e MysqlExecutor) TransformToTimeSeries(query *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult) error {
pointsBySeries := make(map[string]*tsdb.TimeSeries)
+ seriesByQueryOrder := list.New()
columnNames, err := rows.Columns()
if err != nil {
@@ -282,11 +284,13 @@ func (e MysqlExecutor) TransformToTimeSeries(query *tsdb.Query, rows *core.Rows,
series := &tsdb.TimeSeries{Name: rowData.metric}
series.Points = append(series.Points, tsdb.TimePoint{rowData.value, rowData.time})
pointsBySeries[rowData.metric] = series
+ seriesByQueryOrder.PushBack(rowData.metric)
}
}
- for _, value := range pointsBySeries {
- result.Series = append(result.Series, value)
+ for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
+ key := elem.Value.(string)
+ result.Series = append(result.Series, pointsBySeries[key])
}
result.Meta.Set("rowCount", rowCount)
diff --git a/public/app/core/components/code_editor/code_editor.ts b/public/app/core/components/code_editor/code_editor.ts
new file mode 100644
index 00000000000..d2d32d1f46e
--- /dev/null
+++ b/public/app/core/components/code_editor/code_editor.ts
@@ -0,0 +1,210 @@
+/**
+ * codeEditor directive based on Ace code editor
+ * https://github.com/ajaxorg/ace
+ *
+ * Basic usage:
+ *
+ *
+ *
+ * Params:
+ * content: Editor content.
+ * onChange: Function called on content change (invoked on editor blur, ctrl+enter, not on every change).
+ * getCompleter: Function returned external completer. Completer is an object implemented getCompletions() method,
+ * see Prometheus Data Source implementation for details.
+ *
+ * Some Ace editor options available via data-* attributes:
+ * data-mode - Language mode (text, sql, javascript, etc.). Default is 'text'.
+ * data-theme - Editor theme (eg 'solarized_dark').
+ * data-max-lines - Max editor height in lines. Editor grows automatically from 1 to maxLines.
+ * data-show-gutter - Show gutter (contains line numbers and additional info).
+ * data-tab-size - Tab size, default is 2.
+ * data-behaviours-enabled - Specifies whether to use behaviors or not. "Behaviors" in this case is the auto-pairing of
+ * special characters, like quotation marks, parenthesis, or brackets.
+ *
+ * Keybindings:
+ * Ctrl-Enter (Command-Enter): run onChange() function
+ */
+
+///
+import _ from 'lodash';
+import coreModule from 'app/core/core_module';
+import config from 'app/core/config';
+import ace from 'ace';
+
+const ACE_SRC_BASE = "public/vendor/npm/ace-builds/src-noconflict/";
+const DEFAULT_THEME_DARK = "grafana-dark";
+const DEFAULT_THEME_LIGHT = "textmate";
+const DEFAULT_MODE = "text";
+const DEFAULT_MAX_LINES = 10;
+const DEFAULT_TAB_SIZE = 2;
+const DEFAULT_BEHAVIOURS = true;
+
+const GRAFANA_MODULES = ['mode-prometheus', 'snippets-prometheus', 'theme-grafana-dark'];
+const GRAFANA_MODULE_BASE = "public/app/core/components/code_editor/";
+
+// Trick for loading additional modules
+function setModuleUrl(moduleType, name) {
+ let baseUrl = ACE_SRC_BASE;
+ let aceModeName = `ace/${moduleType}/${name}`;
+ let moduleName = `${moduleType}-${name}`;
+ let componentName = `${moduleName}.js`;
+
+ if (_.includes(GRAFANA_MODULES, moduleName)) {
+ baseUrl = GRAFANA_MODULE_BASE;
+ }
+
+ if (moduleType === 'snippets') {
+ componentName = `${moduleType}/${name}.js`;
+ }
+
+ ace.config.setModuleUrl(aceModeName, baseUrl + componentName);
+}
+
+setModuleUrl("ext", "language_tools");
+setModuleUrl("mode", "text");
+setModuleUrl("snippets", "text");
+
+let editorTemplate = `
`;
+
+function link(scope, elem, attrs) {
+ let lightTheme = config.bootData.user.lightTheme;
+ let default_theme = lightTheme ? DEFAULT_THEME_LIGHT : DEFAULT_THEME_DARK;
+
+ // Options
+ let langMode = attrs.mode || DEFAULT_MODE;
+ let maxLines = attrs.maxLines || DEFAULT_MAX_LINES;
+ let showGutter = attrs.showGutter !== undefined;
+ let theme = attrs.theme || default_theme;
+ let tabSize = attrs.tabSize || DEFAULT_TAB_SIZE;
+ let behavioursEnabled = attrs.behavioursEnabled ? attrs.behavioursEnabled === 'true' : DEFAULT_BEHAVIOURS;
+
+ // Initialize editor
+ let aceElem = elem.get(0);
+ let codeEditor = ace.edit(aceElem);
+ let editorSession = codeEditor.getSession();
+
+ let editorOptions = {
+ maxLines: maxLines,
+ showGutter: showGutter,
+ tabSize: tabSize,
+ behavioursEnabled: behavioursEnabled,
+ highlightActiveLine: false,
+ showPrintMargin: false,
+ autoScrollEditorIntoView: true // this is needed if editor is inside scrollable page
+ };
+
+ // Set options
+ codeEditor.setOptions(editorOptions);
+ // disable depreacation warning
+ codeEditor.$blockScrolling = Infinity;
+ // Padding hacks
+ codeEditor.renderer.setScrollMargin(15, 15);
+ codeEditor.renderer.setPadding(10);
+
+ setThemeMode(theme);
+ setLangMode(langMode);
+ setEditorContent(scope.content);
+
+ // Add classes
+ elem.addClass("gf-code-editor");
+ let textarea = elem.find("textarea");
+ textarea.addClass('gf-form-input');
+
+ // Event handlers
+ editorSession.on('change', (e) => {
+ scope.$apply(() => {
+ let newValue = codeEditor.getValue();
+ scope.content = newValue;
+ });
+ });
+
+ // Sync with outer scope - update editor content if model has been changed from outside of directive.
+ scope.$watch('content', (newValue, oldValue) => {
+ let editorValue = codeEditor.getValue();
+ if (newValue !== editorValue && newValue !== oldValue) {
+ scope.$$postDigest(function() {
+ setEditorContent(newValue);
+ });
+ }
+ });
+
+ codeEditor.on('blur', () => {
+ scope.onChange();
+ });
+
+ scope.$on("$destroy", () => {
+ codeEditor.destroy();
+ });
+
+ // Keybindings
+ codeEditor.commands.addCommand({
+ name: 'executeQuery',
+ bindKey: {win: 'Ctrl-Enter', mac: 'Command-Enter'},
+ exec: () => {
+ scope.onChange();
+ }
+ });
+
+ function setLangMode(lang) {
+ let aceModeName = `ace/mode/${lang}`;
+ setModuleUrl("mode", lang);
+ setModuleUrl("snippets", lang);
+ editorSession.setMode(aceModeName);
+
+ ace.config.loadModule("ace/ext/language_tools", (language_tools) => {
+ codeEditor.setOptions({
+ enableBasicAutocompletion: true,
+ enableLiveAutocompletion: true,
+ enableSnippets: true
+ });
+
+ console.log('getting completer', lang);
+ if (scope.getCompleter()) {
+ // make copy of array as ace seems to share completers array between instances
+ codeEditor.completers = codeEditor.completers.slice();
+ codeEditor.completers.push(scope.getCompleter());
+ }
+ });
+ }
+
+ function setThemeMode(theme) {
+ setModuleUrl("theme", theme);
+ let themeModule = `ace/theme/${theme}`;
+ ace.config.loadModule(themeModule, (theme_module) => {
+ // Check is theme light or dark and fix if needed
+ let lightTheme = config.bootData.user.lightTheme;
+ let fixedTheme = theme;
+ if (lightTheme && theme_module.isDark) {
+ fixedTheme = DEFAULT_THEME_LIGHT;
+ } else if (!lightTheme && !theme_module.isDark) {
+ fixedTheme = DEFAULT_THEME_DARK;
+ }
+ setModuleUrl("theme", fixedTheme);
+ themeModule = `ace/theme/${fixedTheme}`;
+ codeEditor.setTheme(themeModule);
+
+ elem.addClass("gf-code-editor--theme-loaded");
+ });
+ }
+
+ function setEditorContent(value) {
+ codeEditor.setValue(value);
+ codeEditor.clearSelection();
+ }
+}
+
+export function codeEditorDirective() {
+ return {
+ restrict: 'E',
+ template: editorTemplate,
+ scope: {
+ content: "=",
+ onChange: "&",
+ getCompleter: "&"
+ },
+ link: link
+ };
+}
+
+coreModule.directive('codeEditor', codeEditorDirective);
diff --git a/public/app/core/components/code_editor/mode-prometheus.js b/public/app/core/components/code_editor/mode-prometheus.js
new file mode 100644
index 00000000000..0bed46e755b
--- /dev/null
+++ b/public/app/core/components/code_editor/mode-prometheus.js
@@ -0,0 +1,481 @@
+// jshint ignore: start
+// jscs: disable
+ace.define("ace/mode/prometheus_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
+"use strict";
+
+var oop = require("../lib/oop");
+var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
+
+var PrometheusHighlightRules = function() {
+ var keywords = (
+ "by|without|keep_common|offset|bool|and|or|unless|ignoring|on|group_left|group_right|" +
+ "count|count_values|min|max|avg|sum|stddev|stdvar|bottomk|topk|quantile"
+ );
+
+ var builtinConstants = (
+ "true|false|null|__name__|job"
+ );
+
+ var builtinFunctions = (
+ "abs|absent|ceil|changes|clamp_max|clamp_min|count_scalar|day_of_month|day_of_week|days_in_month|delta|deriv|" + "drop_common_labels|exp|floor|histogram_quantile|holt_winters|hour|idelta|increase|irate|label_replace|ln|log2|" +
+ "log10|minute|month|predict_linear|rate|resets|round|scalar|sort|sort_desc|sqrt|time|vector|year|avg_over_time|" +
+ "min_over_time|max_over_time|sum_over_time|count_over_time|quantile_over_time|stddev_over_time|stdvar_over_time"
+ );
+
+ var keywordMapper = this.createKeywordMapper({
+ "support.function": builtinFunctions,
+ "keyword": keywords,
+ "constant.language": builtinConstants
+ }, "identifier", true);
+
+ this.$rules = {
+ "start" : [ {
+ token : "string", // single line
+ regex : /"(?:[^"\\]|\\.)*?"/
+ }, {
+ token : "string", // string
+ regex : "'.*?'"
+ }, {
+ token : "constant.numeric", // float
+ regex : "[-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
+ }, {
+ token : "constant.language", // time
+ regex : "\\d+[smhdwy]"
+ }, {
+ token : keywordMapper,
+ regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
+ }, {
+ token : "keyword.operator",
+ regex : "\\+|\\-|\\*|\\/|%|\\^|=|==|!=|<=|>=|<|>|=\\~|!\\~"
+ }, {
+ token : "paren.lparen",
+ regex : "[[({]"
+ }, {
+ token : "paren.rparen",
+ regex : "[\\])}]"
+ }, {
+ token : "text",
+ regex : "\\s+"
+ } ]
+ };
+};
+
+oop.inherits(PrometheusHighlightRules, TextHighlightRules);
+
+exports.PrometheusHighlightRules = PrometheusHighlightRules;
+});
+
+ace.define("ace/mode/prometheus_completions",["require","exports","module","ace/token_iterator", "ace/lib/lang"], function(require, exports, module) {
+"use strict";
+
+var lang = require("../lib/lang");
+
+var prometheusKeyWords = [
+ "by", "without", "keep_common", "offset", "bool", "and", "or", "unless", "ignoring", "on", "group_left",
+ "group_right", "count", "count_values", "min", "max", "avg", "sum", "stddev", "stdvar", "bottomk", "topk", "quantile"
+];
+
+var keyWordsCompletions = prometheusKeyWords.map(function(word) {
+ return {
+ caption: word,
+ value: word,
+ meta: "keyword",
+ score: Number.MAX_VALUE
+ }
+});
+
+var prometheusFunctions = [
+ {
+ name: 'abs()', value: 'abs',
+ def: 'abs(v instant-vector)',
+ docText: 'Returns the input vector with all sample values converted to their absolute value.'
+ },
+ {
+ name: 'abs()', value: 'abs',
+ def: 'abs(v instant-vector)',
+ docText: 'Returns the input vector with all sample values converted to their absolute value.'
+ },
+ {
+ name: 'absent()', value: 'absent',
+ def: 'absent(v instant-vector)',
+ docText: 'Returns an empty vector if the vector passed to it has any elements and a 1-element vector with the value 1 if the vector passed to it has no elements. This is useful for alerting on when no time series exist for a given metric name and label combination.'
+ },
+ {
+ name: 'ceil()', value: 'ceil',
+ def: 'ceil(v instant-vector)',
+ docText: 'Rounds the sample values of all elements in `v` up to the nearest integer.'
+ },
+ {
+ name: 'changes()', value: 'changes',
+ def: 'changes(v range-vector)',
+ docText: 'For each input time series, `changes(v range-vector)` returns the number of times its value has changed within the provided time range as an instant vector.'
+ },
+ {
+ name: 'clamp_max()', value: 'clamp_max',
+ def: 'clamp_max(v instant-vector, max scalar)',
+ docText: 'Clamps the sample values of all elements in `v` to have an upper limit of `max`.'
+ },
+ {
+ name: 'clamp_min()', value: 'clamp_min',
+ def: 'clamp_min(v instant-vector, min scalar)',
+ docText: 'Clamps the sample values of all elements in `v` to have a lower limit of `min`.'
+ },
+ {
+ name: 'count_scalar()', value: 'count_scalar',
+ def: 'count_scalar(v instant-vector)',
+ docText: 'Returns the number of elements in a time series vector as a scalar. This is in contrast to the `count()` aggregation operator, which always returns a vector (an empty one if the input vector is empty) and allows grouping by labels via a `by` clause.'
+ },
+ {
+ name: 'day_of_month()', value: 'day_of_month',
+ def: 'day_of_month(v=vector(time()) instant-vector)',
+ docText: 'Returns the day of the month for each of the given times in UTC. Returned values are from 1 to 31.'
+ },
+ {
+ name: 'day_of_week()', value: 'day_of_week',
+ def: 'day_of_week(v=vector(time()) instant-vector)',
+ docText: 'Returns the day of the week for each of the given times in UTC. Returned values are from 0 to 6, where 0 means Sunday etc.'
+ },
+ {
+ name: 'days_in_month()', value: 'days_in_month',
+ def: 'days_in_month(v=vector(time()) instant-vector)',
+ docText: 'Returns number of days in the month for each of the given times in UTC. Returned values are from 28 to 31.'
+ },
+ {
+ name: 'delta()', value: 'delta',
+ def: 'delta(v range-vector)',
+ docText: 'Calculates the difference between the first and last value of each time series element in a range vector `v`, returning an instant vector with the given deltas and equivalent labels. The delta is extrapolated to cover the full time range as specified in the range vector selector, so that it is possible to get a non-integer result even if the sample values are all integers.'
+ },
+ {
+ name: 'deriv()', value: 'deriv',
+ def: 'deriv(v range-vector)',
+ docText: 'Calculates the per-second derivative of the time series in a range vector `v`, using simple linear regression.'
+ },
+ {
+ name: 'drop_common_labels()', value: 'drop_common_labels',
+ def: 'drop_common_labels(instant-vector)',
+ docText: 'Drops all labels that have the same name and value across all series in the input vector.'
+ },
+ {
+ name: 'exp()', value: 'exp',
+ def: 'exp(v instant-vector)',
+ docText: 'Calculates the exponential function for all elements in `v`.\nSpecial cases are:\n* `Exp(+Inf) = +Inf` \n* `Exp(NaN) = NaN`'
+ },
+ {
+ name: 'floor()', value: 'floor',
+ def: 'floor(v instant-vector)',
+ docText: 'Rounds the sample values of all elements in `v` down to the nearest integer.'
+ },
+ {
+ name: 'histogram_quantile()', value: 'histogram_quantile',
+ def: 'histogram_quantile(φ float, b instant-vector)',
+ docText: 'Calculates the φ-quantile (0 ≤ φ ≤ 1) from the buckets `b` of a histogram. The samples in `b` are the counts of observations in each bucket. Each sample must have a label `le` where the label value denotes the inclusive upper bound of the bucket. (Samples without such a label are silently ignored.) The histogram metric type automatically provides time series with the `_bucket` suffix and the appropriate labels.'
+ },
+ {
+ name: 'holt_winters()', value: 'holt_winters',
+ def: 'holt_winters(v range-vector, sf scalar, tf scalar)',
+ docText: 'Produces a smoothed value for time series based on the range in `v`. The lower the smoothing factor `sf`, the more importance is given to old data. The higher the trend factor `tf`, the more trends in the data is considered. Both `sf` and `tf` must be between 0 and 1.'
+ },
+ {
+ name: 'hour()', value: 'hour',
+ def: 'hour(v=vector(time()) instant-vector)',
+ docText: 'Returns the hour of the day for each of the given times in UTC. Returned values are from 0 to 23.'
+ },
+ {
+ name: 'idelta()', value: 'idelta',
+ def: 'idelta(v range-vector)',
+ docText: 'Calculates the difference between the last two samples in the range vector `v`, returning an instant vector with the given deltas and equivalent labels.'
+ },
+ {
+ name: 'increase()', value: 'increase',
+ def: 'increase(v range-vector)',
+ docText: 'Calculates the increase in the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. The increase is extrapolated to cover the full time range as specified in the range vector selector, so that it is possible to get a non-integer result even if a counter increases only by integer increments.'
+ },
+ {
+ name: 'irate()', value: 'irate',
+ def: 'irate(v range-vector)',
+ docText: 'Calculates the per-second instant rate of increase of the time series in the range vector. This is based on the last two data points. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for.'
+ },
+ {
+ name: 'label_replace()', value: 'label_replace',
+ def: 'label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)',
+ docText: 'For each timeseries in `v`, `label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)` matches the regular expression `regex` against the label `src_label`. If it matches, then the timeseries is returned with the label `dst_label` replaced by the expansion of `replacement`. `$1` is replaced with the first matching subgroup, `$2` with the second etc. If the regular expression doesn\'t match then the timeseries is returned unchanged.'
+ },
+ {
+ name: 'ln()', value: 'ln',
+ def: 'ln(v instant-vector)',
+ docText: 'calculates the natural logarithm for all elements in `v`.\nSpecial cases are:\n * `ln(+Inf) = +Inf`\n * `ln(0) = -Inf`\n * `ln(x < 0) = NaN`\n * `ln(NaN) = NaN`'
+ },
+ {
+ name: 'log2()', value: 'log2',
+ def: 'log2(v instant-vector)',
+ docText: 'Calculates the binary logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.'
+ },
+ {
+ name: 'log10()', value: 'log10',
+ def: 'log10(v instant-vector)',
+ docText: 'Calculates the decimal logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.'
+ },
+ {
+ name: 'minute()', value: 'minute',
+ def: 'minute(v=vector(time()) instant-vector)',
+ docText: 'Returns the minute of the hour for each of the given times in UTC. Returned values are from 0 to 59.'
+ },
+ {
+ name: 'month()', value: 'month',
+ def: 'month(v=vector(time()) instant-vector)',
+ docText: 'Returns the month of the year for each of the given times in UTC. Returned values are from 1 to 12, where 1 means January etc.'
+ },
+ {
+ name: 'predict_linear()', value: 'predict_linear',
+ def: 'predict_linear(v range-vector, t scalar)',
+ docText: 'Predicts the value of time series `t` seconds from now, based on the range vector `v`, using simple linear regression.'
+ },
+ {
+ name: 'rate()', value: 'rate',
+ def: 'rate(v range-vector)',
+ docText: "Calculates the per-second average rate of increase of the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. Also, the calculation extrapolates to the ends of the time range, allowing for missed scrapes or imperfect alignment of scrape cycles with the range's time period."
+ },
+ {
+ name: 'resets()', value: 'resets',
+ def: 'resets(v range-vector)',
+ docText: 'For each input time series, `resets(v range-vector)` returns the number of counter resets within the provided time range as an instant vector. Any decrease in the value between two consecutive samples is interpreted as a counter reset.'
+ },
+ {
+ name: 'round()', value: 'round',
+ def: 'round(v instant-vector, to_nearest=1 scalar)',
+ docText: 'Rounds the sample values of all elements in `v` to the nearest integer. Ties are resolved by rounding up. The optional `to_nearest` argument allows specifying the nearest multiple to which the sample values should be rounded. This multiple may also be a fraction.'
+ },
+ {
+ name: 'scalar()', value: 'scalar',
+ def: 'scalar(v instant-vector)',
+ docText: 'Given a single-element input vector, `scalar(v instant-vector)` returns the sample value of that single element as a scalar. If the input vector does not have exactly one element, `scalar` will return `NaN`.'
+ },
+ {
+ name: 'sort()', value: 'sort',
+ def: 'sort(v instant-vector)',
+ docText: 'Returns vector elements sorted by their sample values, in ascending order.'
+ },
+ {
+ name: 'sort_desc()', value: 'sort_desc',
+ def: 'sort_desc(v instant-vector)',
+ docText: 'Returns vector elements sorted by their sample values, in descending order.'
+ },
+ {
+ name: 'sqrt()', value: 'sqrt',
+ def: 'sqrt(v instant-vector)',
+ docText: 'Calculates the square root of all elements in `v`.'
+ },
+ {
+ name: 'time()', value: 'time',
+ def: 'time()',
+ docText: 'Returns the number of seconds since January 1, 1970 UTC. Note that this does not actually return the current time, but the time at which the expression is to be evaluated.'
+ },
+ {
+ name: 'vector()', value: 'vector',
+ def: 'vector(s scalar)',
+ docText: 'Returns the scalar `s` as a vector with no labels.'
+ },
+ {
+ name: 'year()', value: 'year',
+ def: 'year(v=vector(time()) instant-vector)',
+ docText: 'Returns the year for each of the given times in UTC.'
+ },
+ {
+ name: 'avg_over_time()', value: 'avg_over_time',
+ def: 'avg_over_time(range-vector)',
+ docText: 'The average value of all points in the specified interval.'
+ },
+ {
+ name: 'min_over_time()', value: 'min_over_time',
+ def: 'min_over_time(range-vector)',
+ docText: 'The minimum value of all points in the specified interval.'
+ },
+ {
+ name: 'max_over_time()', value: 'max_over_time',
+ def: 'max_over_time(range-vector)',
+ docText: 'The maximum value of all points in the specified interval.'
+ },
+ {
+ name: 'sum_over_time()', value: 'sum_over_time',
+ def: 'sum_over_time(range-vector)',
+ docText: 'The sum of all values in the specified interval.'
+ },
+ {
+ name: 'count_over_time()', value: 'count_over_time',
+ def: 'count_over_time(range-vector)',
+ docText: 'The count of all values in the specified interval.'
+ },
+ {
+ name: 'quantile_over_time()', value: 'quantile_over_time',
+ def: 'quantile_over_time(scalar, range-vector)',
+ docText: 'The φ-quantile (0 ≤ φ ≤ 1) of the values in the specified interval.'
+ },
+ {
+ name: 'stddev_over_time()', value: 'stddev_over_time',
+ def: 'stddev_over_time(range-vector)',
+ docText: 'The population standard deviation of the values in the specified interval.'
+ },
+ {
+ name: 'stdvar_over_time()', value: 'stdvar_over_time',
+ def: 'stdvar_over_time(range-vector)',
+ docText: 'The population standard variance of the values in the specified interval.'
+ },
+];
+
+function wrapText(str, len) {
+ len = len || 60;
+ var lines = [];
+ var space_index = 0;
+ var line_start = 0;
+ var next_line_end = len;
+ var line = "";
+ for (var i = 0; i < str.length; i++) {
+ if (str[i] === ' ') {
+ space_index = i;
+ } else if (i >= next_line_end && space_index != 0) {
+ line = str.slice(line_start, space_index);
+ lines.push(line);
+ line_start = space_index + 1;
+ next_line_end = i + len;
+ space_index = 0;
+ }
+ }
+ line = str.slice(line_start);
+ lines.push(line);
+ return lines.join(" 
");
+}
+
+function convertMarkDownTags(text) {
+ text = text.replace(/```(.+)```/, "$1
");
+ text = text.replace(/`([^`]+)`/, "$1");
+ return text;
+}
+
+function convertToHTML(item) {
+ var docText = lang.escapeHTML(item.docText);
+ docText = convertMarkDownTags(wrapText(docText, 40));
+ return [
+ "", lang.escapeHTML(item.def), "", "
", docText, "
 "
+ ].join("");
+}
+
+var functionsCompletions = prometheusFunctions.map(function(item) {
+ return {
+ caption: item.name,
+ value: item.value,
+ docHTML: convertToHTML(item),
+ meta: "function",
+ score: Number.MAX_VALUE
+ };
+});
+
+var PrometheusCompletions = function() {};
+
+(function() {
+ this.getCompletions = function(state, session, pos, prefix, callback) {
+ var completions = keyWordsCompletions.concat(functionsCompletions);
+ callback(null, completions);
+ };
+
+}).call(PrometheusCompletions.prototype);
+
+exports.PrometheusCompletions = PrometheusCompletions;
+});
+
+ace.define("ace/mode/behaviour/prometheus",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) {
+"use strict";
+
+var oop = require("../../lib/oop");
+var Behaviour = require("../behaviour").Behaviour;
+var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
+var TokenIterator = require("../../token_iterator").TokenIterator;
+
+function getWrapped(selection, selected, opening, closing) {
+ var rowDiff = selection.end.row - selection.start.row;
+ return {
+ text: opening + selected + closing,
+ selection: [
+ 0,
+ selection.start.column + 1,
+ rowDiff,
+ selection.end.column + (rowDiff ? 0 : 1)
+ ]
+ };
+};
+
+var PrometheusBehaviour = function () {
+ this.inherit(CstyleBehaviour);
+
+ // Rewrite default CstyleBehaviour for {} braces
+ this.add("braces", "insertion", function(state, action, editor, session, text) {
+ if (text == '{') {
+ var selection = editor.getSelectionRange();
+ var selected = session.doc.getTextRange(selection);
+ if (selected !== "" && editor.getWrapBehavioursEnabled()) {
+ return getWrapped(selection, selected, '{', '}');
+ } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
+ return {
+ text: '{}',
+ selection: [1, 1]
+ };
+ }
+ } else if (text == '}') {
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar == '}') {
+ var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
+ if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
+ return {
+ text: '',
+ selection: [1, 1]
+ };
+ }
+ }
+ }
+ });
+
+ this.add("braces", "deletion", function(state, action, editor, session, range) {
+ var selected = session.doc.getTextRange(range);
+ if (!range.isMultiLine() && selected == '{') {
+ var line = session.doc.getLine(range.start.row);
+ var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
+ if (rightChar == '}') {
+ range.end.column++;
+ return range;
+ }
+ }
+ });
+
+}
+oop.inherits(PrometheusBehaviour, CstyleBehaviour);
+
+exports.PrometheusBehaviour = PrometheusBehaviour;
+});
+
+ace.define("ace/mode/prometheus",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/prometheus_highlight_rules"], function(require, exports, module) {
+"use strict";
+
+var oop = require("../lib/oop");
+var TextMode = require("./text").Mode;
+var PrometheusHighlightRules = require("./prometheus_highlight_rules").PrometheusHighlightRules;
+var PrometheusCompletions = require("./prometheus_completions").PrometheusCompletions;
+var PrometheusBehaviour = require("./behaviour/prometheus").PrometheusBehaviour;
+
+var Mode = function() {
+ this.HighlightRules = PrometheusHighlightRules;
+ this.$behaviour = new PrometheusBehaviour();
+ this.$completer = new PrometheusCompletions();
+ // replace keyWordCompleter
+ this.completer = this.$completer;
+};
+oop.inherits(Mode, TextMode);
+
+(function() {
+
+ this.$id = "ace/mode/prometheus";
+}).call(Mode.prototype);
+
+exports.Mode = Mode;
+
+});
diff --git a/public/app/core/components/code_editor/snippets/prometheus.js b/public/app/core/components/code_editor/snippets/prometheus.js
new file mode 100644
index 00000000000..eaaef482932
--- /dev/null
+++ b/public/app/core/components/code_editor/snippets/prometheus.js
@@ -0,0 +1,21 @@
+// jshint ignore: start
+// jscs: disable
+ace.define("ace/snippets/prometheus",["require","exports","module"], function(require, exports, module) {
+"use strict";
+
+// exports.snippetText = "# rate\n\
+// snippet r\n\
+// rate(${1:metric}[${2:range}])\n\
+// ";
+
+exports.snippets = [
+ {
+ "content": "rate(${1:metric}[${2:range}])",
+ "name": "rate()",
+ "scope": "prometheus",
+ "tabTrigger": "r"
+ }
+];
+
+exports.scope = "prometheus";
+});
diff --git a/public/app/core/components/code_editor/theme-grafana-dark.js b/public/app/core/components/code_editor/theme-grafana-dark.js
new file mode 100644
index 00000000000..621ec2c5efb
--- /dev/null
+++ b/public/app/core/components/code_editor/theme-grafana-dark.js
@@ -0,0 +1,116 @@
+/* jshint ignore:start */
+
+ace.define("ace/theme/grafana-dark",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
+ "use strict";
+
+ exports.isDark = true;
+ exports.cssClass = "gf-code-dark";
+ exports.cssText = ".gf-code-dark .ace_gutter {\
+ background: #2f3129;\
+ color: #8f908a\
+ }\
+ .gf-code-dark .ace_print-margin {\
+ width: 1px;\
+ background: #555651\
+ }\
+ .gf-code-dark {\
+ background-color: #111;\
+ color: #e0e0e0\
+ }\
+ .gf-code-dark .ace_cursor {\
+ color: #f8f8f0\
+ }\
+ .gf-code-dark .ace_marker-layer .ace_selection {\
+ background: #49483e\
+ }\
+ .gf-code-dark.ace_multiselect .ace_selection.ace_start {\
+ box-shadow: 0 0 3px 0px #272822;\
+ }\
+ .gf-code-dark .ace_marker-layer .ace_step {\
+ background: rgb(102, 82, 0)\
+ }\
+ .gf-code-dark .ace_marker-layer .ace_bracket {\
+ margin: -1px 0 0 -1px;\
+ border: 1px solid #49483e\
+ }\
+ .gf-code-dark .ace_marker-layer .ace_active-line {\
+ background: #202020\
+ }\
+ .gf-code-dark .ace_gutter-active-line {\
+ background-color: #272727\
+ }\
+ .gf-code-dark .ace_marker-layer .ace_selected-word {\
+ border: 1px solid #49483e\
+ }\
+ .gf-code-dark .ace_invisible {\
+ color: #52524d\
+ }\
+ .gf-code-dark .ace_entity.ace_name.ace_tag,\
+ .gf-code-dark .ace_keyword,\
+ .gf-code-dark .ace_meta.ace_tag,\
+ .gf-code-dark .ace_storage {\
+ color: #66d9ef\
+ }\
+ .gf-code-dark .ace_punctuation,\
+ .gf-code-dark .ace_punctuation.ace_tag {\
+ color: #fff\
+ }\
+ .gf-code-dark .ace_constant.ace_character,\
+ .gf-code-dark .ace_constant.ace_language,\
+ .gf-code-dark .ace_constant.ace_numeric,\
+ .gf-code-dark .ace_constant.ace_other {\
+ color: #fe85fc\
+ }\
+ .gf-code-dark .ace_invalid {\
+ color: #f8f8f0;\
+ background-color: #f92672\
+ }\
+ .gf-code-dark .ace_invalid.ace_deprecated {\
+ color: #f8f8f0;\
+ background-color: #ae81ff\
+ }\
+ .gf-code-dark .ace_support.ace_constant,\
+ .gf-code-dark .ace_support.ace_function {\
+ color: #59e6e3\
+ }\
+ .gf-code-dark .ace_fold {\
+ background-color: #a6e22e;\
+ border-color: #f8f8f2\
+ }\
+ .gf-code-dark .ace_storage.ace_type,\
+ .gf-code-dark .ace_support.ace_class,\
+ .gf-code-dark .ace_support.ace_type {\
+ font-style: italic;\
+ color: #66d9ef\
+ }\
+ .gf-code-dark .ace_entity.ace_name.ace_function,\
+ .gf-code-dark .ace_entity.ace_other,\
+ .gf-code-dark .ace_entity.ace_other.ace_attribute-name,\
+ .gf-code-dark .ace_variable {\
+ color: #a6e22e\
+ }\
+ .gf-code-dark .ace_variable.ace_parameter {\
+ font-style: italic;\
+ color: #fd971f\
+ }\
+ .gf-code-dark .ace_string {\
+ color: #74e680\
+ }\
+ .gf-code-dark .ace_paren {\
+ color: #f0a842\
+ }\
+ .gf-code-dark .ace_operator {\
+ color: #FFF\
+ }\
+ .gf-code-dark .ace_comment {\
+ color: #75715e\
+ }\
+ .gf-code-dark .ace_indent-guide {\
+ background: url(data:image/png;base64,ivborw0kggoaaaansuheugaaaaeaaaaccayaaaczgbynaaaaekleqvqimwpq0fd0zxbzd/wpaajvaoxesgneaaaaaelftksuqmcc) right repeat-y\
+ }";
+
+ var dom = require("../lib/dom");
+ dom.importCssString(exports.cssText, exports.cssClass);
+});
+
+/* jshint ignore:end */
diff --git a/public/app/core/components/form_dropdown/form_dropdown.ts b/public/app/core/components/form_dropdown/form_dropdown.ts
index 1c611e94397..6e3156df1fc 100644
--- a/public/app/core/components/form_dropdown/form_dropdown.ts
+++ b/public/app/core/components/form_dropdown/form_dropdown.ts
@@ -115,7 +115,9 @@ export class FormDropdownCtrl {
this.optionCache = options;
// extract texts
- let optionTexts = _.map(options, 'text');
+ let optionTexts = _.map(options, op => {
+ return _.escape(op.text);
+ });
// add custom values
if (this.allowCustom) {
diff --git a/public/app/core/core.ts b/public/app/core/core.ts
index 3f7867f41fa..f7ebb614d2a 100644
--- a/public/app/core/core.ts
+++ b/public/app/core/core.ts
@@ -19,6 +19,7 @@ import "./directives/diff-view";
import './jquery_extended';
import './partials';
import './components/jsontree/jsontree';
+import './components/code_editor/code_editor';
import {grafanaAppDirective} from './components/grafana_app';
import {sideMenuDirective} from './components/sidemenu/sidemenu';
diff --git a/public/app/features/dashboard/export/export_modal.ts b/public/app/features/dashboard/export/export_modal.ts
index c334818b3e7..6c76b7e824f 100644
--- a/public/app/features/dashboard/export/export_modal.ts
+++ b/public/app/features/dashboard/export/export_modal.ts
@@ -12,13 +12,14 @@ import {DashboardExporter} from './exporter';
export class DashExportCtrl {
dash: any;
exporter: DashboardExporter;
+ dismiss: () => void;
/** @ngInject */
- constructor(private backendSrv, dashboardSrv, datasourceSrv, $scope) {
+ constructor(private backendSrv, private dashboardSrv, datasourceSrv, private $scope) {
this.exporter = new DashboardExporter(datasourceSrv);
- this.exporter.makeExportable(dashboardSrv.getCurrent()).then(dash => {
- $scope.$apply(() => {
+ this.exporter.makeExportable(this.dashboardSrv.getCurrent()).then(dash => {
+ this.$scope.$apply(() => {
this.dash = dash;
});
});
@@ -31,11 +32,13 @@ export class DashExportCtrl {
}
saveJson() {
- var html = angular.toJson(this.dash, true);
- var uri = "data:application/json," + encodeURIComponent(html);
- var newWindow = window.open(uri);
- }
+ var clone = this.dashboardSrv.getCurrent().getSaveModelClone();
+ this.$scope.$root.appEvent('show-json-editor', {
+ object: clone,
+ });
+ this.dismiss();
+ }
}
export function dashExportDirective() {
@@ -45,6 +48,7 @@ export function dashExportDirective() {
controller: DashExportCtrl,
bindToController: true,
controllerAs: 'ctrl',
+ scope: {dismiss: "&"}
};
}
diff --git a/public/app/features/dashboard/partials/shareModal.html b/public/app/features/dashboard/partials/shareModal.html
index 382baec1aba..36dacfad9d8 100644
--- a/public/app/features/dashboard/partials/shareModal.html
+++ b/public/app/features/dashboard/partials/shareModal.html
@@ -47,7 +47,7 @@