Commit 93d21bec by Torkel Ödegaard

Merge branch 'master' into develop

parents 02e2d5da 4ce1ee41
FROM phusion/baseimage:0.9.22
MAINTAINER Denys Zhdanov <denis.zhdanov@gmail.com>
RUN apt-get -y update \
&& apt-get -y upgrade \
&& apt-get -y install vim \
nginx \
python-dev \
python-flup \
python-pip \
python-ldap \
expect \
git \
memcached \
sqlite3 \
libffi-dev \
libcairo2 \
libcairo2-dev \
python-cairo \
python-rrdtool \
pkg-config \
nodejs \
&& rm -rf /var/lib/apt/lists/*
# choose a timezone at build-time
# use `--build-arg CONTAINER_TIMEZONE=Europe/Brussels` in `docker build`
ARG CONTAINER_TIMEZONE
ENV DEBIAN_FRONTEND noninteractive
RUN if [ ! -z "${CONTAINER_TIMEZONE}" ]; \
then ln -sf /usr/share/zoneinfo/$CONTAINER_TIMEZONE /etc/localtime && \
dpkg-reconfigure -f noninteractive tzdata; \
fi
# fix python dependencies (LTS Django and newer memcached/txAMQP)
RUN pip install --upgrade pip && \
pip install django==1.8.18 \
python-memcached==1.53 \
txAMQP==0.6.2
ARG version=1.0.2
ARG whisper_version=${version}
ARG carbon_version=${version}
ARG graphite_version=${version}
ARG statsd_version=v0.7.2
# install whisper
RUN git clone -b ${whisper_version} --depth 1 https://github.com/graphite-project/whisper.git /usr/local/src/whisper
WORKDIR /usr/local/src/whisper
RUN python ./setup.py install
# install carbon
RUN git clone -b ${carbon_version} --depth 1 https://github.com/graphite-project/carbon.git /usr/local/src/carbon
WORKDIR /usr/local/src/carbon
RUN pip install -r requirements.txt \
&& python ./setup.py install
# install graphite
RUN git clone -b ${graphite_version} --depth 1 https://github.com/graphite-project/graphite-web.git /usr/local/src/graphite-web
WORKDIR /usr/local/src/graphite-web
RUN pip install -r requirements.txt \
&& python ./setup.py install
ADD conf/opt/graphite/conf/*.conf /opt/graphite/conf/
ADD conf/opt/graphite/webapp/graphite/local_settings.py /opt/graphite/webapp/graphite/local_settings.py
# ADD conf/opt/graphite/webapp/graphite/app_settings.py /opt/graphite/webapp/graphite/app_settings.py
WORKDIR /opt/graphite/webapp
RUN mkdir -p /var/log/graphite/ \
&& PYTHONPATH=/opt/graphite/webapp django-admin.py collectstatic --noinput --settings=graphite.settings
# install statsd
RUN git clone -b ${statsd_version} https://github.com/etsy/statsd.git /opt/statsd
ADD conf/opt/statsd/config.js /opt/statsd/config.js
# config nginx
RUN rm /etc/nginx/sites-enabled/default
ADD conf/etc/nginx/nginx.conf /etc/nginx/nginx.conf
ADD conf/etc/nginx/sites-enabled/graphite-statsd.conf /etc/nginx/sites-enabled/graphite-statsd.conf
# init django admin
ADD conf/usr/local/bin/django_admin_init.exp /usr/local/bin/django_admin_init.exp
ADD conf/usr/local/bin/manage.sh /usr/local/bin/manage.sh
RUN chmod +x /usr/local/bin/manage.sh && /usr/local/bin/django_admin_init.exp
# logging support
RUN mkdir -p /var/log/carbon /var/log/graphite /var/log/nginx
ADD conf/etc/logrotate.d/graphite-statsd /etc/logrotate.d/graphite-statsd
# daemons
ADD conf/etc/service/carbon/run /etc/service/carbon/run
ADD conf/etc/service/carbon-aggregator/run /etc/service/carbon-aggregator/run
ADD conf/etc/service/graphite/run /etc/service/graphite/run
ADD conf/etc/service/statsd/run /etc/service/statsd/run
ADD conf/etc/service/nginx/run /etc/service/nginx/run
# default conf setup
ADD conf /etc/graphite-statsd/conf
ADD conf/etc/my_init.d/01_conf_init.sh /etc/my_init.d/01_conf_init.sh
# cleanup
RUN apt-get clean\
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# defaults
EXPOSE 80 2003-2004 2023-2024 8125/udp 8126
VOLUME ["/opt/graphite/conf", "/opt/graphite/storage", "/etc/nginx", "/opt/statsd", "/etc/logrotate.d", "/var/log"]
WORKDIR /
ENV HOME /root
CMD ["/sbin/my_init"]
Copyright (c) 2013-2016 Nathan Hopkins
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
...@@ -495,3 +495,4 @@ public_url = ...@@ -495,3 +495,4 @@ public_url =
[external_image_storage.gcs] [external_image_storage.gcs]
key_file = key_file =
bucket = bucket =
path =
\ No newline at end of file
...@@ -438,3 +438,4 @@ log_queries = ...@@ -438,3 +438,4 @@ log_queries =
[external_image_storage.gcs] [external_image_storage.gcs]
;key_file = ;key_file =
;bucket = ;bucket =
;path =
\ No newline at end of file
...@@ -133,6 +133,37 @@ Content-Type: application/json ...@@ -133,6 +133,37 @@ Content-Type: application/json
} }
``` ```
## Pause all alerts
`POST /api/admin/pause-all-alerts`
```http
POST /api/admin/pause-all-alerts HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk
{
"paused": true
}
```
JSON Body Schema:
- **paused** – Can be `true` or `false`. True to pause an alert. False to unpause an alert.
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
{
"state": "Paused",
"message": "alert paused",
"alertsAffected": 1
}
```
## Get alert notifications ## Get alert notifications
`GET /api/alert-notifications` `GET /api/alert-notifications`
......
...@@ -140,9 +140,9 @@ Content-Type: application/json ...@@ -140,9 +140,9 @@ Content-Type: application/json
} }
``` ```
## Delete Snapshot by Id ## Delete Snapshot by deleteKey
`GET /api/snapshots-delete/:key` `GET /api/snapshots-delete/:deleteKey`
**Example Request**: **Example Request**:
......
...@@ -778,6 +778,9 @@ Service Account should have "Storage Object Writer" role. ...@@ -778,6 +778,9 @@ Service Account should have "Storage Object Writer" role.
### bucket name ### bucket name
Bucket Name on Google Cloud Storage. Bucket Name on Google Cloud Storage.
### path
Optional extra path inside bucket
## [alerting] ## [alerting]
### enabled ### enabled
......
{ {
"stable": "4.5.2", "stable": "4.6.2",
"testing": "4.5.2" "testing": "4.6.2"
} }
...@@ -6,6 +6,7 @@ import ( ...@@ -6,6 +6,7 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os" "os"
"path"
"github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
...@@ -20,19 +21,22 @@ const ( ...@@ -20,19 +21,22 @@ const (
type GCSUploader struct { type GCSUploader struct {
keyFile string keyFile string
bucket string bucket string
path string
log log.Logger log log.Logger
} }
func NewGCSUploader(keyFile, bucket string) *GCSUploader { func NewGCSUploader(keyFile, bucket, path string) *GCSUploader {
return &GCSUploader{ return &GCSUploader{
keyFile: keyFile, keyFile: keyFile,
bucket: bucket, bucket: bucket,
path: path,
log: log.New("gcsuploader"), log: log.New("gcsuploader"),
} }
} }
func (u *GCSUploader) Upload(ctx context.Context, imageDiskPath string) (string, error) { func (u *GCSUploader) Upload(ctx context.Context, imageDiskPath string) (string, error) {
key := util.GetRandomString(20) + ".png" fileName := util.GetRandomString(20) + ".png"
key := path.Join(u.path, fileName)
u.log.Debug("Opening key file ", u.keyFile) u.log.Debug("Opening key file ", u.keyFile)
data, err := ioutil.ReadFile(u.keyFile) data, err := ioutil.ReadFile(u.keyFile)
......
...@@ -73,8 +73,9 @@ func NewImageUploader() (ImageUploader, error) { ...@@ -73,8 +73,9 @@ func NewImageUploader() (ImageUploader, error) {
keyFile := gcssec.Key("key_file").MustString("") keyFile := gcssec.Key("key_file").MustString("")
bucketName := gcssec.Key("bucket").MustString("") bucketName := gcssec.Key("bucket").MustString("")
path := gcssec.Key("path").MustString("")
return NewGCSUploader(keyFile, bucketName), nil return NewGCSUploader(keyFile, bucketName, path), nil
} }
return NopImageUploader{}, nil return NopImageUploader{}, nil
......
...@@ -5,9 +5,10 @@ ...@@ -5,9 +5,10 @@
package log package log
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
...@@ -124,6 +125,30 @@ func (w *FileLogWriter) createLogFile() (*os.File, error) { ...@@ -124,6 +125,30 @@ func (w *FileLogWriter) createLogFile() (*os.File, error) {
return os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) return os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
} }
func (w *FileLogWriter) lineCounter() (int, error) {
r, err := os.OpenFile(w.Filename, os.O_RDONLY, 0644)
if err != nil {
return 0, fmt.Errorf("lineCounter Open File : %s", err)
}
buf := make([]byte, 32*1024)
count := 0
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], []byte{'\n'})
switch {
case err == io.EOF:
if err := r.Close(); err != nil {
return count, err
}
return count, nil
case err != nil:
return count, err
}
}
}
func (w *FileLogWriter) initFd() error { func (w *FileLogWriter) initFd() error {
fd := w.mw.fd fd := w.mw.fd
finfo, err := fd.Stat() finfo, err := fd.Stat()
...@@ -133,11 +158,11 @@ func (w *FileLogWriter) initFd() error { ...@@ -133,11 +158,11 @@ func (w *FileLogWriter) initFd() error {
w.maxsize_cursize = int(finfo.Size()) w.maxsize_cursize = int(finfo.Size())
w.daily_opendate = time.Now().Day() w.daily_opendate = time.Now().Day()
if finfo.Size() > 0 { if finfo.Size() > 0 {
content, err := ioutil.ReadFile(w.Filename) count, err := w.lineCounter()
if err != nil { if err != nil {
return err return err
} }
w.maxlines_curlines = len(strings.Split(string(content), "\n")) w.maxlines_curlines = count
} else { } else {
w.maxlines_curlines = 0 w.maxlines_curlines = 0
} }
......
package log
import (
"os"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func (w *FileLogWriter) WriteLine(line string) error {
n, err := w.mw.Write([]byte(line))
if err != nil {
return err
}
w.docheck(n)
return nil
}
func TestLogFile(t *testing.T) {
Convey("When logging to file", t, func() {
fileLogWrite := NewFileWriter()
So(fileLogWrite, ShouldNotBeNil)
fileLogWrite.Filename = "grafana_test.log"
err := fileLogWrite.Init()
So(err, ShouldBeNil)
Convey("Log file is empty", func() {
So(fileLogWrite.maxlines_curlines, ShouldEqual, 0)
})
Convey("Logging should add lines", func() {
err := fileLogWrite.WriteLine("test1\n")
err = fileLogWrite.WriteLine("test2\n")
err = fileLogWrite.WriteLine("test3\n")
So(err, ShouldBeNil)
So(fileLogWrite.maxlines_curlines, ShouldEqual, 3)
})
err = os.Remove(fileLogWrite.Filename)
So(err, ShouldBeNil)
})
}
...@@ -15,6 +15,8 @@ class Settings { ...@@ -15,6 +15,8 @@ class Settings {
disableLoginForm: boolean; disableLoginForm: boolean;
defaultDatasource: string; defaultDatasource: string;
alertingEnabled: boolean; alertingEnabled: boolean;
authProxyEnabled: boolean;
ldapEnabled: boolean;
constructor(options) { constructor(options) {
var defaults = { var defaults = {
......
define([
'angular',
'require',
'../core_module',
'app/core/utils/kbn',
],
function (angular, require, coreModule, kbn) {
'use strict';
kbn = kbn.default;
coreModule.default.directive('tip', function($compile) {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
var _t = '<i class="grafana-tip fa fa-'+(attrs.icon||'question-circle')+'" bs-tooltip="\''+
kbn.addslashes(elem.text())+'\'"></i>';
_t = _t.replace(/{/g, '\\{').replace(/}/g, '\\}');
elem.replaceWith($compile(angular.element(_t))(scope));
}
};
});
coreModule.default.directive('clipboardButton', function() {
return {
scope: {
getText: '&clipboardButton'
},
link: function(scope, elem) {
require(['clipboard'], function(Clipboard) {
scope.clipboard = new Clipboard(elem[0], {
text: function() {
return scope.getText();
}
});
});
scope.$on('$destroy', function() {
if (scope.clipboard) {
scope.clipboard.destroy();
}
});
}
};
});
coreModule.default.directive('compile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(function(scope) {
return scope.$eval(attrs.compile);
}, function(value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
});
coreModule.default.directive('watchChange', function() {
return {
scope: { onchange: '&watchChange' },
link: function(scope, element) {
element.on('input', function() {
scope.$apply(function () {
scope.onchange({ inputValue: element.val() });
});
});
}
};
});
coreModule.default.directive('editorOptBool', function($compile) {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
var ngchange = attrs.change ? (' ng-change="' + attrs.change + '"') : '';
var tip = attrs.tip ? (' <tip>' + attrs.tip + '</tip>') : '';
var showIf = attrs.showIf ? (' ng-show="' + attrs.showIf + '" ') : '';
var template = '<div class="editor-option gf-form-checkbox text-center"' + showIf + '>' +
' <label for="' + attrs.model + '" class="small">' +
attrs.text + tip + '</label>' +
'<input class="cr1" id="' + attrs.model + '" type="checkbox" ' +
' ng-model="' + attrs.model + '"' + ngchange +
' ng-checked="' + attrs.model + '"></input>' +
' <label for="' + attrs.model + '" class="cr1"></label>';
elem.replaceWith($compile(angular.element(template))(scope));
}
};
});
coreModule.default.directive('editorCheckbox', function($compile, $interpolate) {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
var text = $interpolate(attrs.text)(scope);
var model = $interpolate(attrs.model)(scope);
var ngchange = attrs.change ? (' ng-change="' + attrs.change + '"') : '';
var tip = attrs.tip ? (' <tip>' + attrs.tip + '</tip>') : '';
var label = '<label for="' + scope.$id + model + '" class="checkbox-label">' +
text + tip + '</label>';
var template =
'<input class="cr1" id="' + scope.$id + model + '" type="checkbox" ' +
' ng-model="' + model + '"' + ngchange +
' ng-checked="' + model + '"></input>' +
' <label for="' + scope.$id + model + '" class="cr1"></label>';
template = template + label;
elem.addClass('gf-form-checkbox');
elem.html($compile(angular.element(template))(scope));
}
};
});
coreModule.default.directive('gfDropdown', function ($parse, $compile, $timeout) {
function buildTemplate(items, placement) {
var upclass = placement === 'top' ? 'dropup' : '';
var ul = [
'<ul class="dropdown-menu ' + upclass + '" role="menu" aria-labelledby="drop1">',
'</ul>'
];
angular.forEach(items, function (item, index) {
if (item.divider) {
return ul.splice(index + 1, 0, '<li class="divider"></li>');
}
var li = '<li' + (item.submenu && item.submenu.length ? ' class="dropdown-submenu"' : '') + '>' +
'<a tabindex="-1" ng-href="' + (item.href || '') + '"' + (item.click ? ' ng-click="' + item.click + '"' : '') +
(item.target ? ' target="' + item.target + '"' : '') + (item.method ? ' data-method="' + item.method + '"' : '') +
'>' + (item.text || '') + '</a>';
if (item.submenu && item.submenu.length) {
li += buildTemplate(item.submenu).join('\n');
}
li += '</li>';
ul.splice(index + 1, 0, li);
});
return ul;
}
return {
restrict: 'EA',
scope: true,
link: function postLink(scope, iElement, iAttrs) {
var getter = $parse(iAttrs.gfDropdown), items = getter(scope);
$timeout(function () {
var placement = iElement.data('placement');
var dropdown = angular.element(buildTemplate(items, placement).join(''));
dropdown.insertAfter(iElement);
$compile(iElement.next('ul.dropdown-menu'))(scope);
});
iElement.addClass('dropdown-toggle').attr('data-toggle', 'dropdown');
}
};
});
});
import angular from "angular";
import Clipboard from "clipboard";
import coreModule from "../core_module";
import kbn from "app/core/utils/kbn";
/** @ngInject */
function tip($compile) {
return {
restrict: "E",
link: function(scope, elem, attrs) {
var _t =
'<i class="grafana-tip fa fa-' +
(attrs.icon || "question-circle") +
'" bs-tooltip="\'' +
kbn.addslashes(elem.text()) +
"'\"></i>";
_t = _t.replace(/{/g, "\\{").replace(/}/g, "\\}");
elem.replaceWith($compile(angular.element(_t))(scope));
}
};
}
function clipboardButton() {
return {
scope: {
getText: "&clipboardButton"
},
link: function(scope, elem) {
scope.clipboard = new Clipboard(elem[0], {
text: function() {
return scope.getText();
}
});
scope.$on("$destroy", function() {
if (scope.clipboard) {
scope.clipboard.destroy();
}
});
}
};
}
/** @ngInject */
function compile($compile) {
return {
restrict: "A",
link: function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.compile);
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
);
}
};
}
function watchChange() {
return {
scope: { onchange: "&watchChange" },
link: function(scope, element) {
element.on("input", function() {
scope.$apply(function() {
scope.onchange({ inputValue: element.val() });
});
});
}
};
}
/** @ngInject */
function editorOptBool($compile) {
return {
restrict: "E",
link: function(scope, elem, attrs) {
var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : "";
var tip = attrs.tip ? " <tip>" + attrs.tip + "</tip>" : "";
var showIf = attrs.showIf ? ' ng-show="' + attrs.showIf + '" ' : "";
var template =
'<div class="editor-option gf-form-checkbox text-center"' +
showIf +
">" +
' <label for="' +
attrs.model +
'" class="small">' +
attrs.text +
tip +
"</label>" +
'<input class="cr1" id="' +
attrs.model +
'" type="checkbox" ' +
' ng-model="' +
attrs.model +
'"' +
ngchange +
' ng-checked="' +
attrs.model +
'"></input>' +
' <label for="' +
attrs.model +
'" class="cr1"></label>';
elem.replaceWith($compile(angular.element(template))(scope));
}
};
}
/** @ngInject */
function editorCheckbox($compile, $interpolate) {
return {
restrict: "E",
link: function(scope, elem, attrs) {
var text = $interpolate(attrs.text)(scope);
var model = $interpolate(attrs.model)(scope);
var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : "";
var tip = attrs.tip ? " <tip>" + attrs.tip + "</tip>" : "";
var label =
'<label for="' +
scope.$id +
model +
'" class="checkbox-label">' +
text +
tip +
"</label>";
var template =
'<input class="cr1" id="' +
scope.$id +
model +
'" type="checkbox" ' +
' ng-model="' +
model +
'"' +
ngchange +
' ng-checked="' +
model +
'"></input>' +
' <label for="' +
scope.$id +
model +
'" class="cr1"></label>';
template = template + label;
elem.addClass("gf-form-checkbox");
elem.html($compile(angular.element(template))(scope));
}
};
}
/** @ngInject */
function gfDropdown($parse, $compile, $timeout) {
function buildTemplate(items, placement?) {
var upclass = placement === "top" ? "dropup" : "";
var ul = [
'<ul class="dropdown-menu ' +
upclass +
'" role="menu" aria-labelledby="drop1">',
"</ul>"
];
for (let index = 0; index < items.length; index++) {
let item = items[index];
if (item.divider) {
ul.splice(index + 1, 0, '<li class="divider"></li>');
continue;
}
var li =
"<li" +
(item.submenu && item.submenu.length
? ' class="dropdown-submenu"'
: "") +
">" +
'<a tabindex="-1" ng-href="' +
(item.href || "") +
'"' +
(item.click ? ' ng-click="' + item.click + '"' : "") +
(item.target ? ' target="' + item.target + '"' : "") +
(item.method ? ' data-method="' + item.method + '"' : "") +
">" +
(item.text || "") +
"</a>";
if (item.submenu && item.submenu.length) {
li += buildTemplate(item.submenu).join("\n");
}
li += "</li>";
ul.splice(index + 1, 0, li);
}
return ul;
}
return {
restrict: "EA",
scope: true,
link: function postLink(scope, iElement, iAttrs) {
var getter = $parse(iAttrs.gfDropdown),
items = getter(scope);
$timeout(function() {
var placement = iElement.data("placement");
var dropdown = angular.element(
buildTemplate(items, placement).join("")
);
dropdown.insertAfter(iElement);
$compile(iElement.next("ul.dropdown-menu"))(scope);
});
iElement.addClass("dropdown-toggle").attr("data-toggle", "dropdown");
}
};
}
coreModule.directive("tip", tip);
coreModule.directive("clipboardButton", clipboardButton);
coreModule.directive("compile", compile);
coreModule.directive("watchChange", watchChange);
coreModule.directive("editorOptBool", editorOptBool);
coreModule.directive("editorCheckbox", editorCheckbox);
coreModule.directive("gfDropdown", gfDropdown);
import coreModule from '../core_module'; import coreModule from '../core_module';
import * as rangeUtil from 'app/core/utils/rangeutil'; import * as rangeUtil from 'app/core/utils/rangeutil';
export class NgModelOnBlur { function ngModelOnBlur() {
constructor() {
return { return {
restrict: 'A', restrict: 'A',
priority: 1, priority: 1,
...@@ -20,12 +19,9 @@ export class NgModelOnBlur { ...@@ -20,12 +19,9 @@ export class NgModelOnBlur {
}); });
} }
}; };
}
} }
function emptyToNull() {
export class EmptyToNull {
constructor() {
return { return {
restrict: 'A', restrict: 'A',
require: 'ngModel', require: 'ngModel',
...@@ -36,11 +32,9 @@ export class EmptyToNull { ...@@ -36,11 +32,9 @@ export class EmptyToNull {
}); });
} }
}; };
}
} }
export class ValidTimeSpan { function validTimeSpan() {
constructor() {
return { return {
require: 'ngModel', require: 'ngModel',
link: function(scope, elm, attrs, ctrl) { link: function(scope, elm, attrs, ctrl) {
...@@ -56,9 +50,8 @@ export class ValidTimeSpan { ...@@ -56,9 +50,8 @@ export class ValidTimeSpan {
}; };
} }
}; };
}
} }
coreModule.directive('ngModelOnblur', NgModelOnBlur); coreModule.directive('ngModelOnblur', ngModelOnBlur);
coreModule.directive('emptyToNull', EmptyToNull); coreModule.directive('emptyToNull', emptyToNull);
coreModule.directive('validTimeSpan', ValidTimeSpan); coreModule.directive('validTimeSpan', validTimeSpan);
define([ import angular from 'angular';
'angular', import $ from 'jquery';
'jquery', import coreModule from '../core_module';
'../core_module', import 'vendor/tagsinput/bootstrap-tagsinput.js';
'vendor/tagsinput/bootstrap-tagsinput.js',
], function djb2(str) {
function (angular, $, coreModule) {
'use strict';
function djb2(str) {
var hash = 5381; var hash = 5381;
for (var i = 0; i < str.length; i++) { for (var i = 0; i < str.length; i++) {
hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */ hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */
} }
return hash; return hash;
} }
function setColor(name, element) { function setColor(name, element) {
var hash = djb2(name.toLowerCase()); var hash = djb2(name.toLowerCase());
var colors = [ var colors = [
"#E24D42","#1F78C1","#BA43A9","#705DA0","#466803", "#E24D42","#1F78C1","#BA43A9","#705DA0","#466803",
...@@ -37,19 +33,18 @@ function (angular, $, coreModule) { ...@@ -37,19 +33,18 @@ function (angular, $, coreModule) {
var borderColor = borderColors[Math.abs(hash % borderColors.length)]; var borderColor = borderColors[Math.abs(hash % borderColors.length)];
element.css("background-color", color); element.css("background-color", color);
element.css("border-color", borderColor); element.css("border-color", borderColor);
} }
coreModule.default.directive('tagColorFromName', function() { function tagColorFromName() {
return { return {
scope: { tagColorFromName: "=" }, scope: { tagColorFromName: "=" },
link: function (scope, element) { link: function (scope, element) {
setColor(scope.tagColorFromName, element); setColor(scope.tagColorFromName, element);
} }
}; };
}); }
coreModule.default.directive('bootstrapTagsinput', function() {
function bootstrapTagsinput() {
function getItemProperty(scope, property) { function getItemProperty(scope, property) {
if (!property) { if (!property) {
return undefined; return undefined;
...@@ -130,6 +125,7 @@ function (angular, $, coreModule) { ...@@ -130,6 +125,7 @@ function (angular, $, coreModule) {
}, true); }, true);
} }
}; };
}); }
}); coreModule.directive('tagColorFromName', tagColorFromName);
coreModule.directive('bootstrapTagsinput', bootstrapTagsinput);
import AdminListUsersCtrl from './admin_list_users_ctrl'; import AdminListUsersCtrl from './admin_list_users_ctrl';
import './adminListOrgsCtrl'; import './admin_list_orgs_ctrl';
import './adminEditOrgCtrl'; import './admin_edit_org_ctrl';
import './adminEditUserCtrl'; import './admin_edit_user_ctrl';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
......
define([ import angular from 'angular';
'angular',
],
function (angular) {
'use strict';
var module = angular.module('grafana.controllers'); export class AdminEditOrgCtrl {
module.controller('AdminEditOrgCtrl', function($scope, $routeParams, backendSrv, $location, navModelSrv) {
/** @ngInject */
constructor($scope, $routeParams, backendSrv, $location, navModelSrv) {
$scope.init = function() { $scope.init = function() {
$scope.navModel = navModelSrv.getNav('cfg', 'admin', 'global-orgs'); $scope.navModel = navModelSrv.getNav('cfg', 'admin', 'global-orgs');
...@@ -48,7 +44,7 @@ function (angular) { ...@@ -48,7 +44,7 @@ function (angular) {
}; };
$scope.init(); $scope.init();
}
}
}); angular.module('grafana.controllers').controller('AdminEditOrgCtrl', AdminEditOrgCtrl);
});
define([ import angular from 'angular';
'angular', import _ from 'lodash';
'lodash',
],
function (angular, _) {
'use strict';
var module = angular.module('grafana.controllers'); export class AdminEditUserCtrl {
module.controller('AdminEditUserCtrl', function($scope, $routeParams, backendSrv, $location, navModelSrv) { /** @ngInject */
constructor($scope, $routeParams, backendSrv, $location, navModelSrv) {
$scope.user = {}; $scope.user = {};
$scope.newOrg = { name: '', role: 'Editor' }; $scope.newOrg = { name: '', role: 'Editor' };
$scope.permissions = {}; $scope.permissions = {};
...@@ -106,6 +103,7 @@ function (angular, _) { ...@@ -106,6 +103,7 @@ function (angular, _) {
}; };
$scope.init(); $scope.init();
}
}
}); angular.module('grafana.controllers').controller('AdminEditUserCtrl', AdminEditUserCtrl);
});
define([ import angular from 'angular';
'angular',
],
function (angular) {
'use strict';
var module = angular.module('grafana.controllers'); export class AdminListOrgsCtrl {
module.controller('AdminListOrgsCtrl', function($scope, backendSrv, navModelSrv) {
/** @ngInject */
constructor($scope, backendSrv, navModelSrv) {
$scope.init = function() { $scope.init = function() {
$scope.navModel = navModelSrv.getNav('cfg', 'admin', 'global-orgs'); $scope.navModel = navModelSrv.getNav('cfg', 'admin', 'global-orgs');
$scope.getOrgs(); $scope.getOrgs();
...@@ -35,7 +31,7 @@ function (angular) { ...@@ -35,7 +31,7 @@ function (angular) {
}; };
$scope.init(); $scope.init();
}
}
}); angular.module('grafana.controllers').controller('AdminListOrgsCtrl', AdminListOrgsCtrl);
});
define([ import angular from 'angular';
'angular', import _ from 'lodash';
'lodash',
],
function (angular, _) {
'use strict';
var module = angular.module('grafana.directives'); var iconMap = {
var iconMap = {
"external link": "fa-external-link", "external link": "fa-external-link",
"dashboard": "fa-th-large", "dashboard": "fa-th-large",
"question": "fa-question", "question": "fa-question",
...@@ -15,9 +9,9 @@ function (angular, _) { ...@@ -15,9 +9,9 @@ function (angular, _) {
"bolt": "fa-bolt", "bolt": "fa-bolt",
"doc": "fa-file-text-o", "doc": "fa-file-text-o",
"cloud": "fa-cloud", "cloud": "fa-cloud",
}; };
module.directive('dashLinksEditor', function() { function dashLinksEditor() {
return { return {
restrict: 'E', restrict: 'E',
controller: 'DashLinkEditorCtrl', controller: 'DashLinkEditorCtrl',
...@@ -25,9 +19,9 @@ function (angular, _) { ...@@ -25,9 +19,9 @@ function (angular, _) {
link: function() { link: function() {
} }
}; };
}); }
module.directive('dashLinksContainer', function() { function dashLinksContainer() {
return { return {
scope: { scope: {
links: "=" links: "="
...@@ -37,9 +31,10 @@ function (angular, _) { ...@@ -37,9 +31,10 @@ function (angular, _) {
template: '<dash-link ng-repeat="link in generatedLinks" link="link"></dash-link>', template: '<dash-link ng-repeat="link in generatedLinks" link="link"></dash-link>',
link: function() { } link: function() { }
}; };
}); }
module.directive('dashLink', function($compile, linkSrv) { /** @ngInject */
function dashLink($compile, linkSrv) {
return { return {
restrict: 'E', restrict: 'E',
link: function(scope, elem) { link: function(scope, elem) {
...@@ -84,9 +79,11 @@ function (angular, _) { ...@@ -84,9 +79,11 @@ function (angular, _) {
scope.$on('refresh', update); scope.$on('refresh', update);
} }
}; };
}); }
module.controller("DashLinksContainerCtrl", function($scope, $rootScope, $q, backendSrv, dashboardSrv, linkSrv) { export class DashLinksContainerCtrl {
/** @ngInject */
constructor($scope, $rootScope, $q, backendSrv, dashboardSrv, linkSrv) {
var currentDashId = dashboardSrv.getCurrent().id; var currentDashId = dashboardSrv.getCurrent().id;
function buildLinks(linkDef) { function buildLinks(linkDef) {
...@@ -162,10 +159,12 @@ function (angular, _) { ...@@ -162,10 +159,12 @@ function (angular, _) {
updateDashLinks(); updateDashLinks();
$rootScope.onAppEvent('dash-links-updated', updateDashLinks, $scope); $rootScope.onAppEvent('dash-links-updated', updateDashLinks, $scope);
}); }
}
module.controller('DashLinkEditorCtrl', function($scope, $rootScope) {
export class DashLinkEditorCtrl {
/** @ngInject */
constructor($scope, $rootScope) {
$scope.iconMap = iconMap; $scope.iconMap = iconMap;
$scope.dashboard.links = $scope.dashboard.links || []; $scope.dashboard.links = $scope.dashboard.links || [];
...@@ -189,6 +188,11 @@ function (angular, _) { ...@@ -189,6 +188,11 @@ function (angular, _) {
$scope.dashboard.updateSubmenuVisibility(); $scope.dashboard.updateSubmenuVisibility();
$scope.updated(); $scope.updated();
}; };
}
}
}); angular.module('grafana.directives').directive('dashLinksEditor', dashLinksEditor);
}); angular.module('grafana.directives').directive('dashLinksContainer', dashLinksContainer);
angular.module('grafana.directives').directive('dashLink', dashLink);
angular.module('grafana.directives').controller("DashLinksContainerCtrl", DashLinksContainerCtrl);
angular.module('grafana.directives').controller('DashLinkEditorCtrl', DashLinkEditorCtrl);
define([
'./org_users_ctrl',
'./profile_ctrl',
'./select_org_ctrl',
'./change_password_ctrl',
'./newOrgCtrl',
'./userInviteCtrl',
'./orgApiKeysCtrl',
'./orgDetailsCtrl',
'./prefs_control',
'./user_groups_ctrl',
'./user_group_details_ctrl',
'./create_user_group_modal',
], function () {});
import './org_users_ctrl';
import './profile_ctrl';
import './org_users_ctrl';
import './select_org_ctrl';
import './change_password_ctrl';
import './new_org_ctrl';
import './user_invite_ctrl';
import './org_api_keys_ctrl';
import './org_details_ctrl';
import './prefs_control';
define([ import angular from 'angular';
'angular', import config from 'app/core/config';
'app/core/config',
],
function (angular, config) {
'use strict';
config = config.default; export class ChangePasswordCtrl {
var module = angular.module('grafana.controllers');
module.controller('ChangePasswordCtrl', function($scope, backendSrv, $location, navModelSrv) {
/** @ngInject **/
constructor($scope, backendSrv, $location, navModelSrv) {
$scope.command = {}; $scope.command = {};
$scope.authProxyEnabled = config.authProxyEnabled; $scope.authProxyEnabled = config.authProxyEnabled;
$scope.ldapEnabled = config.ldapEnabled; $scope.ldapEnabled = config.ldapEnabled;
...@@ -28,6 +22,7 @@ function (angular, config) { ...@@ -28,6 +22,7 @@ function (angular, config) {
$location.path("profile"); $location.path("profile");
}); });
}; };
}
}
}); angular.module('grafana.controllers').controller('ChangePasswordCtrl', ChangePasswordCtrl);
});
define([
'angular',
'app/core/config',
],
function (angular, config) {
'use strict';
config = config.default;
var module = angular.module('grafana.controllers');
module.controller('NewOrgCtrl', function($scope, $http, backendSrv, navModelSrv) {
$scope.navModel = navModelSrv.getOrgNav(0);
$scope.newOrg = {name: ''};
$scope.createOrg = function() {
backendSrv.post('/api/orgs/', $scope.newOrg).then(function(result) {
backendSrv.post('/api/user/using/' + result.orgId).then(function() {
window.location.href = config.appSubUrl + '/org';
});
});
};
});
});
import angular from 'angular';
import config from 'app/core/config';
export class NewOrgCtrl {
/** @ngInject **/
constructor($scope, $http, backendSrv, navModelSrv) {
$scope.navModel = navModelSrv.getOrgNav(0);
$scope.newOrg = {name: ''};
$scope.createOrg = function() {
backendSrv.post('/api/orgs/', $scope.newOrg).then(function(result) {
backendSrv.post('/api/user/using/' + result.orgId).then(function() {
window.location.href = config.appSubUrl + '/org';
});
});
};
}
}
angular.module('grafana.controllers').controller('NewOrgCtrl', NewOrgCtrl);
define([ import angular from 'angular';
'angular',
],
function (angular) {
'use strict';
var module = angular.module('grafana.controllers'); export class OrgApiKeysCtrl {
module.controller('OrgApiKeysCtrl', function($scope, $http, backendSrv, navModelSrv) {
/** @ngInject **/
constructor ($scope, $http, backendSrv, navModelSrv) {
$scope.navModel = navModelSrv.getNav('cfg', 'apikeys'); $scope.navModel = navModelSrv.getNav('cfg', 'apikeys');
$scope.roleTypes = ['Viewer', 'Editor', 'Admin']; $scope.roleTypes = ['Viewer', 'Editor', 'Admin'];
$scope.token = { role: 'Viewer' }; $scope.token = { role: 'Viewer' };
...@@ -43,6 +40,7 @@ function (angular) { ...@@ -43,6 +40,7 @@ function (angular) {
}; };
$scope.init(); $scope.init();
}
}
}); angular.module('grafana.controllers').controller('OrgApiKeysCtrl', OrgApiKeysCtrl);
});
define([ import angular from 'angular';
'angular',
],
function (angular) {
'use strict';
var module = angular.module('grafana.controllers'); export class OrgDetailsCtrl {
module.controller('OrgDetailsCtrl', function($scope, $http, backendSrv, contextSrv, navModelSrv) {
/** @ngInject **/
constructor($scope, $http, backendSrv, contextSrv, navModelSrv) {
$scope.init = function() { $scope.init = function() {
$scope.getOrgInfo(); $scope.getOrgInfo();
$scope.navModel = navModelSrv.getNav('cfg', 'org'); $scope.navModel = navModelSrv.getNav('cfg', 'org');
...@@ -33,6 +29,7 @@ function (angular) { ...@@ -33,6 +29,7 @@ function (angular) {
}; };
$scope.init(); $scope.init();
}
}
}); angular.module('grafana.controllers').controller('OrgDetailsCtrl', OrgDetailsCtrl);
});
define([ import angular from 'angular';
'angular', import config from 'app/core/config';
'app/core/config',
],
function (angular, config) {
'use strict';
config = config.default; export class SelectOrgCtrl {
var module = angular.module('grafana.controllers');
module.controller('SelectOrgCtrl', function($scope, backendSrv, contextSrv) {
/** @ngInject **/
constructor($scope, backendSrv, contextSrv) {
contextSrv.sidemenu = false; contextSrv.sidemenu = false;
$scope.init = function() { $scope.init = function() {
...@@ -30,6 +24,7 @@ function (angular, config) { ...@@ -30,6 +24,7 @@ function (angular, config) {
}; };
$scope.init(); $scope.init();
}
}
}); angular.module('grafana.controllers').controller('SelectOrgCtrl', SelectOrgCtrl);
});
define([ import angular from 'angular';
'angular', import _ from 'lodash';
'lodash',
],
function (angular, _) {
'use strict';
var module = angular.module('grafana.controllers'); export class UserInviteCtrl {
module.controller('UserInviteCtrl', function($scope, backendSrv) {
/** @ngInject **/
constructor($scope, backendSrv) {
$scope.invites = [ $scope.invites = [
{name: '', email: '', role: 'Editor'}, {name: '', email: '', role: 'Editor'},
]; ];
...@@ -44,5 +40,7 @@ function (angular, _) { ...@@ -44,5 +40,7 @@ function (angular, _) {
} }
}); });
}; };
}); }
}); }
angular.module('grafana.controllers').controller('UserInviteCtrl', UserInviteCtrl);
define([ import angular from 'angular';
'angular', import _ from 'lodash';
'lodash', import './link_srv';
'./link_srv',
], function panelLinksEditor() {
function (angular, _) {
'use strict';
angular
.module('grafana.directives')
.directive('panelLinksEditor', function() {
return { return {
scope: { scope: {
panel: "=" panel: "="
...@@ -19,8 +13,11 @@ function (angular, _) { ...@@ -19,8 +13,11 @@ function (angular, _) {
link: function() { link: function() {
} }
}; };
}).controller('PanelLinksEditorCtrl', function($scope, backendSrv) { }
export class PanelLinksEditorCtrl {
/** @ngInject */
constructor($scope, backendSrv) {
$scope.panel.links = $scope.panel.links || []; $scope.panel.links = $scope.panel.links || [];
$scope.addLink = function() { $scope.addLink = function() {
...@@ -52,5 +49,9 @@ function (angular, _) { ...@@ -52,5 +49,9 @@ function (angular, _) {
$scope.deleteLink = function(link) { $scope.deleteLink = function(link) {
$scope.panel.links = _.without($scope.panel.links, link); $scope.panel.links = _.without($scope.panel.links, link);
}; };
}); }
}); }
angular.module('grafana.directives').directive('panelLinksEditor', panelLinksEditor)
.controller('PanelLinksEditorCtrl', PanelLinksEditorCtrl);
define([ import angular from 'angular';
'angular', import _ from 'lodash';
'lodash',
],
function (angular, _) {
'use strict';
var module = angular.module('grafana.controllers'); export class CloudWatchQueryParameter {
module.directive('cloudwatchQueryParameter', function() { constructor() {
return { return {
templateUrl: 'public/app/plugins/datasource/cloudwatch/partials/query.parameter.html', templateUrl: 'public/app/plugins/datasource/cloudwatch/partials/query.parameter.html',
controller: 'CloudWatchQueryParameterCtrl', controller: 'CloudWatchQueryParameterCtrl',
...@@ -18,9 +14,12 @@ function (angular, _) { ...@@ -18,9 +14,12 @@ function (angular, _) {
onChange: "&", onChange: "&",
} }
}; };
}); }
}
module.controller('CloudWatchQueryParameterCtrl', function($scope, templateSrv, uiSegmentSrv, datasourceSrv, $q) { export class CloudWatchQueryParameterCtrl {
constructor($scope, templateSrv, uiSegmentSrv, datasourceSrv, $q) {
$scope.init = function() { $scope.init = function() {
var target = $scope.target; var target = $scope.target;
...@@ -120,8 +119,7 @@ function (angular, _) { ...@@ -120,8 +119,7 @@ function (angular, _) {
if (segment.value === $scope.removeDimSegment.value) { if (segment.value === $scope.removeDimSegment.value) {
$scope.dimSegments.splice(index, 3); $scope.dimSegments.splice(index, 3);
} } else if (segment.type === 'plus-button') {
else if (segment.type === 'plus-button') {
$scope.dimSegments.push(uiSegmentSrv.newOperator('=')); $scope.dimSegments.push(uiSegmentSrv.newOperator('='));
$scope.dimSegments.push(uiSegmentSrv.newFake('select dimension value', 'value', 'query-segment-value')); $scope.dimSegments.push(uiSegmentSrv.newFake('select dimension value', 'value', 'query-segment-value'));
segment.type = 'key'; segment.type = 'key';
...@@ -195,7 +193,8 @@ function (angular, _) { ...@@ -195,7 +193,8 @@ function (angular, _) {
}; };
$scope.init(); $scope.init();
}
}
}); angular.module('grafana.controllers').directive('cloudwatchQueryParameter', CloudWatchQueryParameter);
angular.module('grafana.controllers').controller('CloudWatchQueryParameterCtrl', CloudWatchQueryParameterCtrl);
});
...@@ -8,6 +8,7 @@ export class ElasticConfigCtrl { ...@@ -8,6 +8,7 @@ export class ElasticConfigCtrl {
constructor($scope) { constructor($scope) {
this.current.jsonData.timeField = this.current.jsonData.timeField || '@timestamp'; this.current.jsonData.timeField = this.current.jsonData.timeField || '@timestamp';
this.current.jsonData.esVersion = this.current.jsonData.esVersion || 5; this.current.jsonData.esVersion = this.current.jsonData.esVersion || 5;
this.current.jsonData.maxConcurrentShardRequests = this.current.jsonData.maxConcurrentShardRequests || 256;
} }
indexPatternTypes = [ indexPatternTypes = [
...@@ -22,6 +23,7 @@ export class ElasticConfigCtrl { ...@@ -22,6 +23,7 @@ export class ElasticConfigCtrl {
esVersions = [ esVersions = [
{name: '2.x', value: 2}, {name: '2.x', value: 2},
{name: '5.x', value: 5}, {name: '5.x', value: 5},
{name: '5.6+', value: 56},
]; ];
indexPatternTypeChanged() { indexPatternTypeChanged() {
......
...@@ -16,6 +16,7 @@ export class ElasticDatasource { ...@@ -16,6 +16,7 @@ export class ElasticDatasource {
timeField: string; timeField: string;
esVersion: number; esVersion: number;
interval: string; interval: string;
maxConcurrentShardRequests: number;
queryBuilder: ElasticQueryBuilder; queryBuilder: ElasticQueryBuilder;
indexPattern: IndexPattern; indexPattern: IndexPattern;
...@@ -30,6 +31,7 @@ export class ElasticDatasource { ...@@ -30,6 +31,7 @@ export class ElasticDatasource {
this.esVersion = instanceSettings.jsonData.esVersion; this.esVersion = instanceSettings.jsonData.esVersion;
this.indexPattern = new IndexPattern(instanceSettings.index, instanceSettings.jsonData.interval); this.indexPattern = new IndexPattern(instanceSettings.index, instanceSettings.jsonData.interval);
this.interval = instanceSettings.jsonData.timeInterval; this.interval = instanceSettings.jsonData.timeInterval;
this.maxConcurrentShardRequests = instanceSettings.jsonData.maxConcurrentShardRequests;
this.queryBuilder = new ElasticQueryBuilder({ this.queryBuilder = new ElasticQueryBuilder({
timeField: this.timeField, timeField: this.timeField,
esVersion: this.esVersion, esVersion: this.esVersion,
...@@ -213,11 +215,15 @@ export class ElasticDatasource { ...@@ -213,11 +215,15 @@ export class ElasticDatasource {
} }
getQueryHeader(searchType, timeFrom, timeTo) { getQueryHeader(searchType, timeFrom, timeTo) {
return angular.toJson({ var query_header: any = {
search_type: searchType, search_type: searchType,
"ignore_unavailable": true, "ignore_unavailable": true,
index: this.indexPattern.getIndexList(timeFrom, timeTo), index: this.indexPattern.getIndexList(timeFrom, timeTo),
}); };
if (this.esVersion >= 56) {
query_header["max_concurrent_shard_requests"] = this.maxConcurrentShardRequests;
}
return angular.toJson(query_header);
} }
query(options) { query(options) {
......
...@@ -25,6 +25,10 @@ ...@@ -25,6 +25,10 @@
<span class="gf-form-label width-9">Version</span> <span class="gf-form-label width-9">Version</span>
<select class="gf-form-input gf-size-auto" ng-model="ctrl.current.jsonData.esVersion" ng-options="f.value as f.name for f in ctrl.esVersions"></select> <select class="gf-form-input gf-size-auto" ng-model="ctrl.current.jsonData.esVersion" ng-options="f.value as f.name for f in ctrl.esVersions"></select>
</div> </div>
<div class="gf-form max-width-30" ng-if="ctrl.current.jsonData.esVersion>=56">
<span class="gf-form-label width-15">Max concurrent Shard Requests</span>
<input class="gf-form-input" type="text" ng-model='ctrl.current.jsonData.maxConcurrentShardRequests' placeholder="" required></input>
</div>
<div class="gf-form-inline"> <div class="gf-form-inline">
<div class="gf-form"> <div class="gf-form">
<span class="gf-form-label width-9">Min interval</span> <span class="gf-form-label width-9">Min interval</span>
......
define([ import _ from "lodash";
'lodash'
],
function (_) {
'use strict';
function PrometheusMetricFindQuery(datasource, query, timeSrv) { export default class PrometheusMetricFindQuery {
datasource: any;
query: any;
range: any;
constructor(datasource, query, timeSrv) {
this.datasource = datasource; this.datasource = datasource;
this.query = query; this.query = query;
this.range = timeSrv.timeRange(); this.range = timeSrv.timeRange();
} }
PrometheusMetricFindQuery.prototype.process = function() { process() {
var label_values_regex = /^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]+)\)$/; var label_values_regex = /^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]+)\)$/;
var metric_names_regex = /^metrics\((.+)\)$/; var metric_names_regex = /^metrics\((.+)\)$/;
var query_result_regex = /^query_result\((.+)\)$/; var query_result_regex = /^query_result\((.+)\)$/;
...@@ -18,7 +19,10 @@ function (_) { ...@@ -18,7 +19,10 @@ function (_) {
var label_values_query = this.query.match(label_values_regex); var label_values_query = this.query.match(label_values_regex);
if (label_values_query) { if (label_values_query) {
if (label_values_query[1]) { if (label_values_query[1]) {
return this.labelValuesQuery(label_values_query[2], label_values_query[1]); return this.labelValuesQuery(
label_values_query[2],
label_values_query[1]
);
} else { } else {
return this.labelValuesQuery(label_values_query[2], null); return this.labelValuesQuery(label_values_query[2], null);
} }
...@@ -36,29 +40,32 @@ function (_) { ...@@ -36,29 +40,32 @@ function (_) {
// if query contains full metric name, return metric name and label list // if query contains full metric name, return metric name and label list
return this.metricNameAndLabelsQuery(this.query); return this.metricNameAndLabelsQuery(this.query);
}; }
PrometheusMetricFindQuery.prototype.labelValuesQuery = function(label, metric) { labelValuesQuery(label, metric) {
var url; var url;
if (!metric) { if (!metric) {
// return label values globally // return label values globally
url = '/api/v1/label/' + label + '/values'; url = "/api/v1/label/" + label + "/values";
return this.datasource._request('GET', url).then(function(result) { return this.datasource._request("GET", url).then(function(result) {
return _.map(result.data.data, function(value) { return _.map(result.data.data, function(value) {
return {text: value}; return { text: value };
}); });
}); });
} else { } else {
var start = this.datasource.getPrometheusTime(this.range.from, false); var start = this.datasource.getPrometheusTime(this.range.from, false);
var end = this.datasource.getPrometheusTime(this.range.to, true); var end = this.datasource.getPrometheusTime(this.range.to, true);
url = '/api/v1/series?match[]=' + encodeURIComponent(metric) url =
+ '&start=' + start "/api/v1/series?match[]=" +
+ '&end=' + end; encodeURIComponent(metric) +
"&start=" +
return this.datasource._request('GET', url) start +
.then(function(result) { "&end=" +
end;
return this.datasource._request("GET", url).then(function(result) {
var _labels = _.map(result.data.data, function(metric) { var _labels = _.map(result.data.data, function(metric) {
return metric[label]; return metric[label];
}); });
...@@ -71,13 +78,12 @@ function (_) { ...@@ -71,13 +78,12 @@ function (_) {
}); });
}); });
} }
}; }
PrometheusMetricFindQuery.prototype.metricNameQuery = function(metricFilterPattern) { metricNameQuery(metricFilterPattern) {
var url = '/api/v1/label/__name__/values'; var url = "/api/v1/label/__name__/values";
return this.datasource._request('GET', url) return this.datasource._request("GET", url).then(function(result) {
.then(function(result) {
return _.chain(result.data.data) return _.chain(result.data.data)
.filter(function(metricName) { .filter(function(metricName) {
var r = new RegExp(metricFilterPattern); var r = new RegExp(metricFilterPattern);
...@@ -91,19 +97,23 @@ function (_) { ...@@ -91,19 +97,23 @@ function (_) {
}) })
.value(); .value();
}); });
}; }
PrometheusMetricFindQuery.prototype.queryResultQuery = function(query) { queryResultQuery(query) {
var end = this.datasource.getPrometheusTime(this.range.to, true); var end = this.datasource.getPrometheusTime(this.range.to, true);
return this.datasource.performInstantQuery({ expr: query }, end) return this.datasource
.performInstantQuery({ expr: query }, end)
.then(function(result) { .then(function(result) {
return _.map(result.data.data.result, function(metricData) { return _.map(result.data.data.result, function(metricData) {
var text = metricData.metric.__name__ || ''; var text = metricData.metric.__name__ || "";
delete metricData.metric.__name__; delete metricData.metric.__name__;
text += '{' + text +=
_.map(metricData.metric, function(v, k) { return k + '="' + v + '"'; }).join(',') + "{" +
'}'; _.map(metricData.metric, function(v, k) {
text += ' ' + metricData.value[1] + ' ' + metricData.value[0] * 1000; return k + '="' + v + '"';
}).join(",") +
"}";
text += " " + metricData.value[1] + " " + metricData.value[0] * 1000;
return { return {
text: text, text: text,
...@@ -111,18 +121,21 @@ function (_) { ...@@ -111,18 +121,21 @@ function (_) {
}; };
}); });
}); });
}; }
PrometheusMetricFindQuery.prototype.metricNameAndLabelsQuery = function(query) { metricNameAndLabelsQuery(query) {
var start = this.datasource.getPrometheusTime(this.range.from, false); var start = this.datasource.getPrometheusTime(this.range.from, false);
var end = this.datasource.getPrometheusTime(this.range.to, true); var end = this.datasource.getPrometheusTime(this.range.to, true);
var url = '/api/v1/series?match[]=' + encodeURIComponent(query) var url =
+ '&start=' + start "/api/v1/series?match[]=" +
+ '&end=' + end; encodeURIComponent(query) +
"&start=" +
start +
"&end=" +
end;
var self = this; var self = this;
return this.datasource._request('GET', url) return this.datasource._request("GET", url).then(function(result) {
.then(function(result) {
return _.map(result.data.data, function(metric) { return _.map(result.data.data, function(metric) {
return { return {
text: self.datasource.getOriginalMetricName(metric), text: self.datasource.getOriginalMetricName(metric),
...@@ -130,7 +143,5 @@ function (_) { ...@@ -130,7 +143,5 @@ function (_) {
}; };
}); });
}); });
}; }
}
return PrometheusMetricFindQuery;
});
define([ import _ from 'lodash';
'angular', import angular from 'angular';
'jquery',
'lodash',
], function(angular, jquery, _) {
'use strict';
var module = angular.module('grafana.controllers'); export class SeriesOverridesCtrl {
module.controller('SeriesOverridesCtrl', function($scope, $element, popoverSrv) { /** @ngInject */
constructor($scope, $element, popoverSrv) {
$scope.overrideMenu = []; $scope.overrideMenu = [];
$scope.currentOverrides = []; $scope.currentOverrides = [];
$scope.override = $scope.override || {}; $scope.override = $scope.override || {};
$scope.addOverrideOption = function(name, propertyName, values) { $scope.addOverrideOption = function(name, propertyName, values) {
var option = {}; var option = {
option.text = name; text: name,
option.propertyName = propertyName; propertyName: propertyName,
option.index = $scope.overrideMenu.length; index: $scope.overrideMenu.lenght,
option.values = values; values: values,
submenu: _.map(values, function(value) {
option.submenu = _.map(values, function(value) {
return { text: String(value), value: value }; return { text: String(value), value: value };
}); })
};
$scope.overrideMenu.push(option); $scope.overrideMenu.push(option);
}; };
...@@ -97,22 +94,24 @@ define([ ...@@ -97,22 +94,24 @@ define([
$scope.addOverrideOption('Bars', 'bars', [true, false]); $scope.addOverrideOption('Bars', 'bars', [true, false]);
$scope.addOverrideOption('Lines', 'lines', [true, false]); $scope.addOverrideOption('Lines', 'lines', [true, false]);
$scope.addOverrideOption('Line fill', 'fill', [0,1,2,3,4,5,6,7,8,9,10]); $scope.addOverrideOption('Line fill', 'fill', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$scope.addOverrideOption('Line width', 'linewidth', [0,1,2,3,4,5,6,7,8,9,10]); $scope.addOverrideOption('Line width', 'linewidth', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$scope.addOverrideOption('Null point mode', 'nullPointMode', ['connected', 'null', 'null as zero']); $scope.addOverrideOption('Null point mode', 'nullPointMode', ['connected', 'null', 'null as zero']);
$scope.addOverrideOption('Fill below to', 'fillBelowTo', $scope.getSeriesNames()); $scope.addOverrideOption('Fill below to', 'fillBelowTo', $scope.getSeriesNames());
$scope.addOverrideOption('Staircase line', 'steppedLine', [true, false]); $scope.addOverrideOption('Staircase line', 'steppedLine', [true, false]);
$scope.addOverrideOption('Dashes', 'dashes', [true, false]); $scope.addOverrideOption('Dashes', 'dashes', [true, false]);
$scope.addOverrideOption('Dash Length', 'dashLength', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]); $scope.addOverrideOption('Dash Length', 'dashLength', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
$scope.addOverrideOption('Dash Space', 'spaceLength', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]); $scope.addOverrideOption('Dash Space', 'spaceLength', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
$scope.addOverrideOption('Points', 'points', [true, false]); $scope.addOverrideOption('Points', 'points', [true, false]);
$scope.addOverrideOption('Points Radius', 'pointradius', [1,2,3,4,5]); $scope.addOverrideOption('Points Radius', 'pointradius', [1, 2, 3, 4, 5]);
$scope.addOverrideOption('Stack', 'stack', [true, false, 'A', 'B', 'C', 'D']); $scope.addOverrideOption('Stack', 'stack', [true, false, 'A', 'B', 'C', 'D']);
$scope.addOverrideOption('Color', 'color', ['change']); $scope.addOverrideOption('Color', 'color', ['change']);
$scope.addOverrideOption('Y-axis', 'yaxis', [1, 2]); $scope.addOverrideOption('Y-axis', 'yaxis', [1, 2]);
$scope.addOverrideOption('Z-index', 'zindex', [-3,-2,-1,0,1,2,3]); $scope.addOverrideOption('Z-index', 'zindex', [-3, -2, -1, 0, 1, 2, 3]);
$scope.addOverrideOption('Transform', 'transform', ['negative-Y']); $scope.addOverrideOption('Transform', 'transform', ['negative-Y']);
$scope.addOverrideOption('Legend', 'legend', [true, false]); $scope.addOverrideOption('Legend', 'legend', [true, false]);
$scope.updateCurrentOverrides(); $scope.updateCurrentOverrides();
}); }
}); }
angular.module('grafana.controllers').controller('SeriesOverridesCtrl', SeriesOverridesCtrl);
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
"max-line-length": [true, 150], "max-line-length": [true, 150],
"member-access": false, "member-access": false,
"no-arg": true, "no-arg": true,
"no-bitwise": true, "no-bitwise": false,
"no-console": [true, "no-console": [true,
"debug", "debug",
"info", "info",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment