[Backend] Merge 'master' changes into the backend (#875)

* CI: fix shellcheck issues (#789)

Signed-off-by: Mario Trangoni <mjtrangoni@gmail.com>

* annotations: fix options in grafana 6.x, fix #813

* fix function editor in Grafana 6.4, closes #810

* add typings for grafana packages

* Add $__range_series variable for calculating function over the whole series, #531

* fix tests

* Don't set alert styles for react panels, fix #823

* docs: add range variables

* docs: percentile reference

* fix codespell

* update packages (build with node 12)

* update circleci node image to 12

* fix test configuration (babel)

* Fix 817 (#851)

* problems: update panel schema

* update packages (build with node 12)

* problems: use datasource from target

* problems: fix query editor after schema update

* problems: fix list layout

* update circleci node image to 12

* fix tests

* build(deps-dev): bump lodash from 4.17.10 to 4.17.13 (#852)

Bumps [lodash](https://github.com/lodash/lodash) from 4.17.10 to 4.17.13.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.10...4.17.13)

Signed-off-by: dependabot[bot] <support@github.com>

* fix packages security alerts

* problems: fix tags adding and removal

* fix adding func from typeahead, closes #468

* update change log

* bump plugin version to 3.10.5

* problems: fix tag removal (list layout)

* Fix percentile() function, closes #862 (#863)

Like the other aggregation functions, the datapoints need to be sorted in
time before calling groupBy_perf().

* Update copyright, happy New Year!

* fix not acknowledged problem color with a message (#858)

* fix not acknowledged problem color with a message

* fix not acknowledged problem color with a message, closes #857

* Variable query editor (#856)

* refactor: convert module to typescript

* refactor: covert utils to typescript

* variable query editor WIP

* variable editor: fix type error after grafana/ui update

* variable editor: use FormLabel from grafana/ui

* variable editor: refactor

* variable editor: input validation and highlights

* variable editor: fix tests

* variable query: fix backward compatibility with empty queries

* fix linter errors

* variable editor: fix variable replacement in queries

* Fixes for backend

Co-authored-by: Mario Trangoni <mario@mariotrangoni.de>
Co-authored-by: Alexander Zobnin <alexanderzobnin@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Mark Reibert <mreibert@netskope.com>
Co-authored-by: memfiz <arnis.civciss@gmail.com>
This commit is contained in:
Alec Sears
2020-01-15 05:48:43 -06:00
committed by Alexander Zobnin
parent fcfb237004
commit 92e77617cf
30 changed files with 2973 additions and 3320 deletions

View File

@@ -47,7 +47,7 @@ angular
}
$scope.$apply(function() {
$scope.addFunction(funcDef);
$scope.ctrl.addFunction(funcDef);
});
$input.trigger('blur');

View File

@@ -0,0 +1,157 @@
import React, { PureComponent } from 'react';
import { parseLegacyVariableQuery } from '../utils';
import { Select, Input, AsyncSelect, FormLabel } from '@grafana/ui';
import { SelectableValue } from '@grafana/data';
import { VariableQuery, VariableQueryTypes, VariableQueryProps, VariableQueryData } from '../types';
import { ZabbixInput } from './ZabbixInput';
export class ZabbixVariableQueryEditor extends PureComponent<VariableQueryProps, VariableQueryData> {
queryTypes: Array<SelectableValue<VariableQueryTypes>> = [
{ value: VariableQueryTypes.Group, label: 'Group'},
{ value: VariableQueryTypes.Host, label: 'Host' },
{ value: VariableQueryTypes.Application, label: 'Application' },
{ value: VariableQueryTypes.Item, label: 'Item' },
];
defaults: VariableQueryData = {
selectedQueryType: { value: VariableQueryTypes.Group, label: 'Group' },
queryType: VariableQueryTypes.Group,
group: '/.*/',
host: '',
application: '',
item: '',
};
constructor(props: VariableQueryProps) {
super(props);
if (this.props.query && typeof this.props.query === 'string') {
// Backward compatibility
const query = parseLegacyVariableQuery(this.props.query);
const selectedQueryType = this.getSelectedQueryType(query.queryType);
this.state = {
selectedQueryType,
legacyQuery: this.props.query,
...query
};
} else if (this.props.query) {
const query = (this.props.query as VariableQuery);
const selectedQueryType = this.getSelectedQueryType(query.queryType);
this.state = {
...this.defaults,
...query,
selectedQueryType,
};
} else {
this.state = this.defaults;
}
}
getSelectedQueryType(queryType: VariableQueryTypes) {
return this.queryTypes.find(q => q.value === queryType);
}
handleQueryUpdate = (evt: React.ChangeEvent<HTMLInputElement>, prop: string) => {
const value = evt.currentTarget.value;
this.setState((prevState: VariableQueryData) => {
const newQuery = {
...prevState,
};
newQuery[prop] = value;
return {
...newQuery,
};
});
}
handleQueryChange = () => {
const { queryType, group, host, application, item } = this.state;
const queryModel = { queryType, group, host, application, item };
this.props.onChange(queryModel, `Zabbix - ${queryType}`);
}
handleQueryTypeChange = (selectedItem: SelectableValue<VariableQueryTypes>) => {
this.setState({
...this.state,
selectedQueryType: selectedItem,
queryType: selectedItem.value,
});
const { group, host, application, item } = this.state;
const queryType = selectedItem.value;
const queryModel = { queryType, group, host, application, item };
this.props.onChange(queryModel, `Zabbix - ${queryType}`);
}
render() {
const { selectedQueryType, legacyQuery, group, host, application, item } = this.state;
return (
<>
<div className="gf-form max-width-21">
<FormLabel width={10}>Query Type</FormLabel>
<Select
width={11}
value={selectedQueryType}
options={this.queryTypes}
onChange={this.handleQueryTypeChange}
/>
</div>
<div className="gf-form-inline">
<div className="gf-form max-width-30">
<FormLabel width={10}>Group</FormLabel>
<ZabbixInput
value={group}
onChange={evt => this.handleQueryUpdate(evt, 'group')}
onBlur={this.handleQueryChange}
/>
</div>
{selectedQueryType.value !== VariableQueryTypes.Group &&
<div className="gf-form max-width-30">
<FormLabel width={10}>Host</FormLabel>
<ZabbixInput
value={host}
onChange={evt => this.handleQueryUpdate(evt, 'host')}
onBlur={this.handleQueryChange}
/>
</div>
}
</div>
{(selectedQueryType.value === VariableQueryTypes.Application ||
selectedQueryType.value === VariableQueryTypes.Item) &&
<div className="gf-form-inline">
<div className="gf-form max-width-30">
<FormLabel width={10}>Application</FormLabel>
<ZabbixInput
value={application}
onChange={evt => this.handleQueryUpdate(evt, 'application')}
onBlur={this.handleQueryChange}
/>
</div>
{selectedQueryType.value === VariableQueryTypes.Item &&
<div className="gf-form max-width-30">
<FormLabel width={10}>Item</FormLabel>
<ZabbixInput
value={item}
onChange={evt => this.handleQueryUpdate(evt, 'item')}
onBlur={this.handleQueryChange}
/>
</div>
}
</div>
}
{legacyQuery &&
<div className="gf-form">
<FormLabel width={10} tooltip="Original query string, read-only">Legacy Query</FormLabel>
<Input
value={legacyQuery}
readOnly={true}
/>
</div>
}
</>
);
}
}

View File

@@ -0,0 +1,70 @@
import React, { FC } from 'react';
import { css, cx } from 'emotion';
import { Themeable, withTheme, Input, EventsWithValidation, ValidationEvents } from '@grafana/ui';
import { GrafanaTheme } from '@grafana/data';
import { isRegex, variableRegex } from '../utils';
const variablePattern = RegExp(`^${variableRegex.source}`);
const getStyles = (theme: GrafanaTheme) => ({
inputRegex: css`
color: ${theme.colors.orange}
`,
inputVariable: css`
color: ${theme.colors.variable}
`,
});
const zabbixInputValidationEvents: ValidationEvents = {
[EventsWithValidation.onBlur]: [
{
rule: value => {
if (!value) {
return true;
}
if (value.length > 1 && value[0] === '/') {
if (value[value.length - 1] !== '/') {
return false;
}
}
return true;
},
errorMessage: 'Not a valid regex',
},
{
rule: value => {
if (value === '*') {
return false;
}
return true;
},
errorMessage: 'Wildcards not supported. Use /.*/ instead',
},
],
};
interface Props extends React.ComponentProps<typeof Input>, Themeable {
}
const UnthemedZabbixInput: FC<Props> = ({ theme, value, ref, validationEvents, ...restProps }) => {
const styles = getStyles(theme);
let inputClass;
if (variablePattern.test(value as string)) {
inputClass = styles.inputVariable;
}
if (isRegex(value)) {
inputClass = styles.inputRegex;
}
return (
<Input
className={inputClass}
value={value}
validationEvents={zabbixInputValidationEvents}
{...restProps}
/>
);
};
export const ZabbixInput = withTheme(UnthemedZabbixInput);

View File

@@ -121,9 +121,11 @@ function aggregateWrapper(groupByCallback, interval, datapoints) {
}
function percentile(interval, n, datapoints) {
var flattenedPoints = ts.flattenDatapoints(datapoints);
var groupByCallback = _.partial(PERCENTILE, n);
return groupBy(flattenedPoints, interval, groupByCallback);
const flattenedPoints = ts.flattenDatapoints(datapoints);
// groupBy_perf works with sorted series only
const sortedPoints = ts.sortByTime(flattenedPoints);
let groupByCallback = _.partial(PERCENTILE, n);
return groupBy(sortedPoints, interval, groupByCallback);
}
function timeShift(interval, range) {

View File

@@ -12,10 +12,11 @@ import { ZabbixAPIError } from './zabbix/connectors/zabbix_api/zabbixAPICore';
import {
DataSourceApi,
// DataSourceInstanceSettings,
} from '@grafana/ui';
} from '@grafana/data';
// import { BackendSrv, DataSourceSrv } from '@grafana/runtime';
// import { ZabbixAlertingService } from './zabbixAlerting.service';
// import { ZabbixConnectionTestQuery, ZabbixConnectionInfo, TemplateSrv, TSDBResponse } from './types';
import { VariableQueryTypes } from './types';
const DEFAULT_ZABBIX_VERSION = 3;
@@ -495,42 +496,41 @@ export class ZabbixDatasource extends DataSourceApi {
* of metrics in "{metric1,metcic2,...,metricN}" format.
*/
metricFindQuery(query) {
let result;
let parts = [];
let resultPromise;
let queryModel = _.cloneDeep(query);
// Split query. Query structure: group.host.app.item
_.each(utils.splitTemplateQuery(query), part => {
part = this.replaceTemplateVars(part, {});
// Replace wildcard to regex
if (part === '*') {
part = '/.*/';
}
parts.push(part);
});
let template = _.zipObject(['group', 'host', 'app', 'item'], parts);
// Get items
if (parts.length === 4) {
// Search for all items, even it's not belong to any application
if (template.app === '/.*/') {
template.app = '';
}
result = this.zabbix.getItems(template.group, template.host, template.app, template.item);
} else if (parts.length === 3) {
// Get applications
result = this.zabbix.getApps(template.group, template.host, template.app);
} else if (parts.length === 2) {
// Get hosts
result = this.zabbix.getHosts(template.group, template.host);
} else if (parts.length === 1) {
// Get groups
result = this.zabbix.getGroups(template.group);
} else {
result = Promise.resolve([]);
if (!query) {
return Promise.resolve([]);
}
return result.then(metrics => {
if (typeof query === 'string') {
// Backward compatibility
queryModel = utils.parseLegacyVariableQuery(query);
}
for (const prop of ['group', 'host', 'application', 'item']) {
queryModel[prop] = this.replaceTemplateVars(queryModel[prop], {});
}
switch (queryModel.queryType) {
case VariableQueryTypes.Group:
resultPromise = this.zabbix.getGroups(queryModel.group);
break;
case VariableQueryTypes.Host:
resultPromise = this.zabbix.getHosts(queryModel.group, queryModel.host);
break;
case VariableQueryTypes.Application:
resultPromise = this.zabbix.getApps(queryModel.group, queryModel.host, queryModel.application);
break;
case VariableQueryTypes.Item:
resultPromise = this.zabbix.getItems(queryModel.group, queryModel.host, queryModel.application, queryModel.item);
break;
default:
resultPromise = Promise.resolve([]);
break;
}
return resultPromise.then(metrics => {
return _.map(metrics, formatMetric);
});
}

View File

@@ -2,15 +2,18 @@ import { loadPluginCss } from '@grafana/runtime';
import { ZabbixDatasource } from './datasource';
import { ZabbixQueryController } from './query.controller';
import { ZabbixDSConfigController } from './config.controller';
import { ZabbixVariableQueryEditor } from './components/VariableQueryEditor';
import './zabbixAlerting.service.js';
import './add-metric-function.directive';
import './metric-function-editor.directive';
class ZabbixQueryOptionsController {}
ZabbixQueryOptionsController.templateUrl = 'datasource-zabbix/partials/query.options.html';
class ZabbixQueryOptionsController {
static templateUrl = 'datasource-zabbix/partials/query.options.html';
}
class ZabbixAnnotationsQueryController {}
ZabbixAnnotationsQueryController.templateUrl = 'datasource-zabbix/partials/annotations.editor.html';
class ZabbixAnnotationsQueryController {
static templateUrl = 'datasource-zabbix/partials/annotations.editor.html';
}
ZabbixQueryController.templateUrl = 'datasource-zabbix/partials/query.editor.html';
ZabbixDSConfigController.templateUrl = 'datasource-zabbix/partials/config.html';
@@ -25,5 +28,6 @@ export {
ZabbixDSConfigController as ConfigCtrl,
ZabbixQueryController as QueryCtrl,
ZabbixQueryOptionsController as QueryOptionsCtrl,
ZabbixAnnotationsQueryController as AnnotationsQueryCtrl
ZabbixAnnotationsQueryController as AnnotationsQueryCtrl,
ZabbixVariableQueryEditor as VariableQueryEditor,
};

View File

@@ -231,7 +231,7 @@ describe('ZabbixDatasource', () => {
});
});
describe('When invoking metricFindQuery()', () => {
describe('When invoking metricFindQuery() with legacy query', () => {
beforeEach(() => {
ctx.ds.replaceTemplateVars = (str) => str;
ctx.ds.zabbix = {
@@ -245,7 +245,6 @@ describe('ZabbixDatasource', () => {
it('should return groups', (done) => {
const tests = [
{query: '*', expect: '/.*/'},
{query: '', expect: ''},
{query: 'Backend', expect: 'Backend'},
{query: 'Back*', expect: 'Back*'},
];
@@ -258,6 +257,16 @@ describe('ZabbixDatasource', () => {
done();
});
it('should return empty list for empty query', (done) => {
ctx.ds.metricFindQuery('').then(result => {
expect(ctx.ds.zabbix.getGroups).toBeCalledTimes(0);
ctx.ds.zabbix.getGroups.mockClear();
expect(result).toEqual([]);
done();
});
});
it('should return hosts', (done) => {
const tests = [
{query: '*.*', expect: ['/.*/', '/.*/']},

View File

@@ -1,4 +1,4 @@
import { DataQuery } from '@grafana/ui';
import { SelectableValue, DataQuery } from "@grafana/data";
export interface ZabbixConnectionInfo {
zabbixVersion: string;
@@ -81,5 +81,34 @@ interface QueryResult {
export interface TSDBResponse {
results: { [key: string]: QueryResult };
message: string;
message: string;
}
export interface VariableQueryProps {
query: LegacyVariableQuery;
onChange: (query: VariableQuery, definition: string) => void;
datasource: any;
templateSrv: any;
}
export interface VariableQueryData extends VariableQuery {
selectedQueryType: SelectableValue<VariableQueryTypes>;
legacyQuery?: string;
}
export interface VariableQuery {
queryType: VariableQueryTypes;
group?: string;
host?: string;
application?: string;
item?: string;
}
export type LegacyVariableQuery = VariableQuery | string;
export enum VariableQueryTypes {
Group = 'group',
Host = 'host',
Application = 'application',
Item = 'item',
}

View File

@@ -2,6 +2,15 @@ import _ from 'lodash';
import moment from 'moment';
import kbn from 'grafana/app/core/utils/kbn';
import * as c from './constants';
import { VariableQuery, VariableQueryTypes } from './types';
/*
* This regex matches 3 types of variable reference with an optional format specifier
* \$(\w+) $var1
* \[\[([\s\S]+?)(?::(\w+))?\]\] [[var2]] or [[var2:fmt2]]
* \${(\w+)(?::(\w+))?} ${var3} or ${var3:fmt3}
*/
export const variableRegex = /\$(\w+)|\[\[([\s\S]+?)(?::(\w+))?\]\]|\${(\w+)(?:\.([^:^\}]+))?(?::(\w+))?}/g;
/**
* Expand Zabbix item name
@@ -14,8 +23,8 @@ export function expandItemName(name, key) {
// extract params from key:
// "system.cpu.util[,system,avg1]" --> ["", "system", "avg1"]
let key_params_str = key.substring(key.indexOf('[') + 1, key.lastIndexOf(']'));
let key_params = splitKeyParams(key_params_str);
const key_params_str = key.substring(key.indexOf('[') + 1, key.lastIndexOf(']'));
const key_params = splitKeyParams(key_params_str);
// replace item parameters
for (let i = key_params.length; i >= 1; i--) {
@@ -34,10 +43,10 @@ export function expandItems(items) {
}
function splitKeyParams(paramStr) {
let params = [];
const params = [];
let quoted = false;
let in_array = false;
let split_symbol = ',';
const split_symbol = ',';
let param = '';
_.forEach(paramStr, symbol => {
@@ -71,9 +80,9 @@ export function containsMacro(itemName) {
export function replaceMacro(item, macros) {
let itemName = item.name;
let item_macros = itemName.match(MACRO_PATTERN);
const item_macros = itemName.match(MACRO_PATTERN);
_.forEach(item_macros, macro => {
let host_macros = _.filter(macros, m => {
const host_macros = _.filter(macros, m => {
if (m.hostid) {
return m.hostid === item.hostid;
} else {
@@ -82,10 +91,10 @@ export function replaceMacro(item, macros) {
}
});
let macro_def = _.find(host_macros, { macro: macro });
const macro_def = _.find(host_macros, { macro: macro });
if (macro_def && macro_def.value) {
let macro_value = macro_def.value;
let macro_regex = new RegExp(escapeMacro(macro));
const macro_value = macro_def.value;
const macro_regex = new RegExp(escapeMacro(macro));
itemName = itemName.replace(macro_regex, macro_value);
}
});
@@ -98,17 +107,62 @@ function escapeMacro(macro) {
return macro;
}
export function parseLegacyVariableQuery(query: string): VariableQuery {
let queryType: VariableQueryTypes;
const parts = [];
// Split query. Query structure: group.host.app.item
_.each(splitTemplateQuery(query), part => {
// Replace wildcard to regex
if (part === '*') {
part = '/.*/';
}
parts.push(part);
});
const template = _.zipObject(['group', 'host', 'app', 'item'], parts);
if (parts.length === 4 && template.app === '/.*/') {
// Search for all items, even it's not belong to any application
template.app = '';
}
switch (parts.length) {
case 1:
queryType = VariableQueryTypes.Group;
break;
case 2:
queryType = VariableQueryTypes.Host;
break;
case 3:
queryType = VariableQueryTypes.Application;
break;
case 4:
queryType = VariableQueryTypes.Item;
break;
}
const variableQuery: VariableQuery = {
queryType,
group: template.group || '',
host: template.host || '',
application: template.app || '',
item: template.item || '',
};
return variableQuery;
}
/**
* Split template query to parts of zabbix entities
* group.host.app.item -> [group, host, app, item]
* {group}{host.com} -> [group, host.com]
*/
export function splitTemplateQuery(query) {
let splitPattern = /\{[^\{\}]*\}|\{\/.*\/\}/g;
const splitPattern = /\{[^\{\}]*\}|\{\/.*\/\}/g;
let split;
if (isContainsBraces(query)) {
let result = query.match(splitPattern);
const result = query.match(splitPattern);
split = _.map(result, part => {
return _.trim(part, '{}');
});
@@ -120,7 +174,7 @@ export function splitTemplateQuery(query) {
}
function isContainsBraces(query) {
let bracesPattern = /^\{.+\}$/;
const bracesPattern = /^\{.+\}$/;
return bracesPattern.test(query);
}
@@ -132,9 +186,9 @@ export function isRegex(str) {
}
export function isTemplateVariable(str, templateVariables) {
var variablePattern = /^\$\w+/;
const variablePattern = /^\$\w+/;
if (variablePattern.test(str)) {
var variables = _.map(templateVariables, variable => {
const variables = _.map(templateVariables, variable => {
return '$' + variable.name;
});
return _.includes(variables, str);
@@ -156,9 +210,9 @@ export function getRangeScopedVars(range) {
}
export function buildRegex(str) {
var matches = str.match(regexPattern);
var pattern = matches[1];
var flags = matches[2] !== "" ? matches[2] : undefined;
const matches = str.match(regexPattern);
const pattern = matches[1];
const flags = matches[2] !== "" ? matches[2] : undefined;
return new RegExp(pattern, flags);
}
@@ -169,18 +223,18 @@ export function escapeRegex(value) {
}
export function parseInterval(interval) {
var intervalPattern = /(^[\d]+)(y|M|w|d|h|m|s)/g;
var momentInterval = intervalPattern.exec(interval);
const intervalPattern = /(^[\d]+)(y|M|w|d|h|m|s)/g;
const momentInterval: any[] = intervalPattern.exec(interval);
return moment.duration(Number(momentInterval[1]), momentInterval[2]).valueOf();
}
export function parseTimeShiftInterval(interval) {
let intervalPattern = /^([\+\-]*)([\d]+)(y|M|w|d|h|m|s)/g;
let momentInterval = intervalPattern.exec(interval);
let duration = 0;
const intervalPattern = /^([\+\-]*)([\d]+)(y|M|w|d|h|m|s)/g;
const momentInterval: any[] = intervalPattern.exec(interval);
let duration: any = 0;
if (momentInterval[1] === '+') {
duration = 0 - moment.duration(Number(momentInterval[2]), momentInterval[3]).valueOf();
duration = 0 - (moment.duration(Number(momentInterval[2]), momentInterval[3]).valueOf() as any);
} else {
duration = moment.duration(Number(momentInterval[2]), momentInterval[3]).valueOf();
}
@@ -196,13 +250,13 @@ export function parseTimeShiftInterval(interval) {
*/
export function formatAcknowledges(acknowledges) {
if (acknowledges.length) {
var formatted_acknowledges = '<br><br>Acknowledges:<br><table><tr><td><b>Time</b></td>'
let formatted_acknowledges = '<br><br>Acknowledges:<br><table><tr><td><b>Time</b></td>'
+ '<td><b>User</b></td><td><b>Comments</b></td></tr>';
_.each(_.map(acknowledges, function (ack) {
var timestamp = moment.unix(ack.clock);
_.each(_.map(acknowledges, ack => {
const timestamp = moment.unix(ack.clock);
return '<tr><td><i>' + timestamp.format("DD MMM YYYY HH:mm:ss") + '</i></td><td>' + ack.alias
+ ' (' + ack.name + ' ' + ack.surname + ')' + '</td><td>' + ack.message + '</td></tr>';
}), function (ack) {
}), ack => {
formatted_acknowledges = formatted_acknowledges.concat(ack);
});
formatted_acknowledges = formatted_acknowledges.concat('</table>');
@@ -213,8 +267,8 @@ export function formatAcknowledges(acknowledges) {
}
export function convertToZabbixAPIUrl(url) {
var zabbixAPIUrlPattern = /.*api_jsonrpc.php$/;
var trimSlashPattern = /(.*?)[\/]*$/;
const zabbixAPIUrlPattern = /.*api_jsonrpc.php$/;
const trimSlashPattern = /(.*?)[\/]*$/;
if (url.match(zabbixAPIUrlPattern)) {
return url;
} else {
@@ -247,7 +301,7 @@ export function callOnce(func, promiseKeeper) {
*/
export function sequence(funcsArray) {
return function(result) {
for (var i = 0; i < funcsArray.length; i++) {
for (let i = 0; i < funcsArray.length; i++) {
result = funcsArray[i].call(this, result);
}
return result;
@@ -292,5 +346,5 @@ export function getArrayDepth(a, level = 0) {
// Fix for backward compatibility with lodash 2.4
if (!_.includes) {
_.includes = _.contains;
_.includes = (_ as any).contains;
}

View File

@@ -13,7 +13,7 @@ import AlertIcon from './AlertIcon';
interface AlertCardProps {
problem: ZBXTrigger;
panelOptions: ProblemsPanelOptions;
onTagClick?: (tag: ZBXTag, datasource: string) => void;
onTagClick?: (tag: ZBXTag, datasource: string, ctrlKey?: boolean, shiftKey?: boolean) => void;
onProblemAck?: (problem: ZBXTrigger, data: AckProblemData) => Promise<any> | any;
}
@@ -27,9 +27,9 @@ export default class AlertCard extends PureComponent<AlertCardProps, AlertCardSt
this.state = { showAckDialog: false };
}
handleTagClick = (tag: ZBXTag) => {
handleTagClick = (tag: ZBXTag, ctrlKey?: boolean, shiftKey?: boolean) => {
if (this.props.onTagClick) {
this.props.onTagClick(tag, this.props.problem.datasource);
this.props.onTagClick(tag, this.props.problem.datasource, ctrlKey, shiftKey);
}
}
@@ -56,6 +56,7 @@ export default class AlertCard extends PureComponent<AlertCardProps, AlertCardSt
render() {
const { problem, panelOptions } = this.props;
const showDatasourceName = panelOptions.targets && panelOptions.targets.length > 1;
const cardClass = classNames('alert-rule-item', 'zbx-trigger-card', { 'zbx-trigger-highlighted': panelOptions.highlightBackground });
const descriptionClass = classNames('alert-rule-item__text', { 'zbx-description--newline': panelOptions.descriptionAtNewLine });
const severityDesc = _.find(panelOptions.triggerSeverity, s => s.priority === Number(problem.priority));
@@ -71,7 +72,7 @@ export default class AlertCard extends PureComponent<AlertCardProps, AlertCardSt
let problemColor: string;
if (problem.value === '0') {
problemColor = panelOptions.okEventColor;
} else if (panelOptions.markAckEvents && problem.acknowledges && problem.acknowledges.length) {
} else if (panelOptions.markAckEvents && problem.lastEvent.acknowledged === "1") {
problemColor = panelOptions.ackEventColor;
} else {
problemColor = severityDesc.color;
@@ -134,7 +135,7 @@ export default class AlertCard extends PureComponent<AlertCardProps, AlertCardSt
</div>
</div>
{panelOptions.datasources.length > 1 && (
{showDatasourceName && (
<div className="alert-rule-item__time zabbix-trigger-source">
<span>
<i className="fa fa-database"></i>

View File

@@ -12,7 +12,7 @@ export interface AlertListProps {
pageSize?: number;
fontSize?: number;
onProblemAck?: (problem: ZBXTrigger, data: AckProblemData) => void;
onTagClick?: (tag: ZBXTag, datasource: string) => void;
onTagClick?: (tag: ZBXTag, datasource: string, ctrlKey?: boolean, shiftKey?: boolean) => void;
}
interface AlertListState {
@@ -45,9 +45,9 @@ export default class AlertList extends PureComponent<AlertListProps, AlertListSt
}
handleTagClick = (tag: ZBXTag, datasource: string) => {
handleTagClick = (tag: ZBXTag, datasource: string, ctrlKey?: boolean, shiftKey?: boolean) => {
if (this.props.onTagClick) {
this.props.onTagClick(tag, datasource);
this.props.onTagClick(tag, datasource, ctrlKey, shiftKey);
}
}
@@ -68,7 +68,7 @@ export default class AlertList extends PureComponent<AlertListProps, AlertListSt
<ol className={alertListClass}>
{currentProblems.map(problem =>
<AlertCard
key={problem.triggerid}
key={`${problem.triggerid}-${problem.datasource}`}
problem={problem}
panelOptions={panelOptions}
onTagClick={this.handleTagClick}

View File

@@ -18,8 +18,8 @@ export interface ProblemListProps {
timeRange?: GFTimeRange;
pageSize?: number;
fontSize?: number;
getProblemEvents: (problem: ZBXTrigger) => ZBXEvent[];
getProblemAlerts: (problem: ZBXTrigger) => ZBXAlert[];
getProblemEvents: (problem: ZBXTrigger) => Promise<ZBXEvent[]>;
getProblemAlerts: (problem: ZBXTrigger) => Promise<ZBXAlert[]>;
onProblemAck?: (problem: ZBXTrigger, data: AckProblemData) => void;
onTagClick?: (tag: ZBXTag, datasource: string, ctrlKey?: boolean, shiftKey?: boolean) => void;
onPageSizeChange?: (pageSize: number, pageIndex: number) => void;
@@ -183,7 +183,7 @@ function SeverityCell(props: RTCell<ZBXTrigger>, problemSeverityDesc: TriggerSev
color = severityDesc.color;
// Mark acknowledged triggers with different color
if (markAckEvents && problem.acknowledges && problem.acknowledges.length) {
if (markAckEvents && problem.lastEvent.acknowledged === "1") {
color = ackEventColor;
}
@@ -260,13 +260,13 @@ function LastChangeCell(props: RTCell<ZBXTrigger>, customFormat?: string) {
}
interface TagCellProps extends RTCell<ZBXTrigger> {
onTagClick: (tag: ZBXTag, datasource: string) => void;
onTagClick: (tag: ZBXTag, datasource: string, ctrlKey?: boolean, shiftKey?: boolean) => void;
}
class TagCell extends PureComponent<TagCellProps> {
handleTagClick = (tag: ZBXTag) => {
handleTagClick = (tag: ZBXTag, ctrlKey?: boolean, shiftKey?: boolean) => {
if (this.props.onTagClick) {
this.props.onTagClick(tag, this.props.original.datasource);
this.props.onTagClick(tag, this.props.original.datasource, ctrlKey, shiftKey);
}
}

View File

@@ -1,8 +1,9 @@
import _ from 'lodash';
import { getNextRefIdChar } from './utils';
import { getDefaultTarget } from './triggers_panel_ctrl';
// Actual schema version
export const CURRENT_SCHEMA_VERSION = 6;
export const CURRENT_SCHEMA_VERSION = 7;
export function migratePanelSchema(panel) {
if (isEmptyPanel(panel)) {
@@ -45,6 +46,26 @@ export function migratePanelSchema(panel) {
}
}
if (schemaVersion < 7) {
const updatedTargets = [];
for (const targetKey in panel.targets) {
const target = panel.targets[targetKey];
if (!isEmptyTarget(target) && !isInvalidTarget(target, targetKey)) {
updatedTargets.push({
...target,
datasource: targetKey,
});
}
}
for (const target of updatedTargets) {
if (!target.refId) {
target.refId = getNextRefIdChar(updatedTargets);
}
}
panel.targets = updatedTargets;
delete panel.datasources;
}
return panel;
}
@@ -59,3 +80,11 @@ function isEmptyPanel(panel) {
function isEmptyTargets(targets) {
return !targets || (_.isArray(targets) && (targets.length === 0 || targets.length === 1 && _.isEmpty(targets[0])));
}
function isEmptyTarget(target) {
return !target || !(target.group && target.host && target.application && target.trigger);
}
function isInvalidTarget(target, targetKey) {
return target && target.refId === 'A' && targetKey === '0';
}

View File

@@ -6,7 +6,7 @@
</div>
<div class="gf-form">
<datasource-selector
datasources="ctrl.panel.datasources"
datasources="editor.selectedDatasources"
options="editor.panelCtrl.available_datasources"
on-change="editor.datasourcesChanged()">
</datasource-selector>
@@ -15,50 +15,50 @@
</div>
</div>
<div class="editor-row" ng-repeat="ds in ctrl.panel.datasources">
<div class="editor-row" ng-repeat="target in ctrl.panel.targets">
<div class="section gf-form-group">
<h5 class="section-heading">{{ ds }}</h5>
<h5 class="section-heading">{{ target.datasource }}</h5>
<div class="gf-form-inline">
<div class="gf-form">
<label class="gf-form-label query-keyword width-7">Group</label>
<input type="text"
ng-model="ctrl.panel.targets[ds].group.filter"
bs-typeahead="editor.getGroupNames[ds]"
ng-model="target.group.filter"
bs-typeahead="editor.getGroupNames[target.datasource]"
ng-blur="editor.parseTarget()"
data-min-length=0
data-items=100
class="gf-form-input width-14"
ng-class="{
'zbx-variable': editor.isVariable(ctrl.panel.targets[ds].group.filter),
'zbx-regex': editor.isRegex(ctrl.panel.targets[ds].group.filter)
'zbx-variable': editor.isVariable(target.group.filter),
'zbx-regex': editor.isRegex(target.group.filter)
}">
</div>
<div class="gf-form">
<label class="gf-form-label query-keyword width-7">Host</label>
<input type="text"
ng-model="ctrl.panel.targets[ds].host.filter"
bs-typeahead="editor.getHostNames[ds]"
ng-model="target.host.filter"
bs-typeahead="editor.getHostNames[target.datasource]"
ng-blur="editor.parseTarget()"
data-min-length=0
data-items=100
class="gf-form-input width-14"
ng-class="{
'zbx-variable': editor.isVariable(ctrl.panel.targets[ds].host.filter),
'zbx-regex': editor.isRegex(ctrl.panel.targets[ds].host.filter)
'zbx-variable': editor.isVariable(target.host.filter),
'zbx-regex': editor.isRegex(target.host.filter)
}">
</div>
<div class="gf-form">
<label class="gf-form-label query-keyword width-7">Proxy</label>
<input type="text"
ng-model="ctrl.panel.targets[ds].proxy.filter"
bs-typeahead="editor.getProxyNames[ds]"
ng-model="target.proxy.filter"
bs-typeahead="editor.getProxyNames[target.datasource]"
ng-blur="editor.parseTarget()"
data-min-length=0
data-items=100
class="gf-form-input width-14"
ng-class="{
'zbx-variable': editor.isVariable(ctrl.panel.targets[ds].proxy.filter),
'zbx-regex': editor.isRegex(ctrl.panel.targets[ds].proxy.filter)
'zbx-variable': editor.isVariable(target.proxy.filter),
'zbx-regex': editor.isRegex(target.proxy.filter)
}">
</div>
</div>
@@ -67,35 +67,35 @@
<div class="gf-form">
<label class="gf-form-label query-keyword width-7">Application</label>
<input type="text"
ng-model="ctrl.panel.targets[ds].application.filter"
bs-typeahead="editor.getApplicationNames[ds]"
ng-model="target.application.filter"
bs-typeahead="editor.getApplicationNames[target.datasource]"
ng-blur="editor.parseTarget()"
data-min-length=0
data-items=100
class="gf-form-input width-14"
ng-class="{
'zbx-variable': editor.isVariable(ctrl.panel.targets[ds].application.filter),
'zbx-regex': editor.isRegex(ctrl.panel.targets[ds].application.filter)
'zbx-variable': editor.isVariable(target.application.filter),
'zbx-regex': editor.isRegex(target.application.filter)
}">
</div>
<div class="gf-form">
<label class="gf-form-label query-keyword width-7">Trigger</label>
<input type="text"
ng-model="ctrl.panel.targets[ds].trigger.filter"
ng-model="target.trigger.filter"
ng-blur="editor.parseTarget()"
placeholder="trigger name"
class="gf-form-input width-14"
ng-style="ctrl.panel.targets[ds].trigger.style"
ng-style="target.trigger.style"
ng-class="{
'zbx-variable': editor.isVariable(ctrl.panel.targets[ds].trigger.filter),
'zbx-regex': editor.isRegex(ctrl.panel.targets[ds].trigger.filter)
'zbx-variable': editor.isVariable(target.trigger.filter),
'zbx-regex': editor.isRegex(target.trigger.filter)
}"
empty-to-null>
</div>
<div class="gf-form">
<label class="gf-form-label query-keyword width-7">Tags</label>
<input type="text" class="gf-form-input width-14"
ng-model="ctrl.panel.targets[ds].tags.filter"
ng-model="target.tags.filter"
ng-blur="editor.parseTarget()"
placeholder="tag1:value1, tag2:value2">
</div>

View File

@@ -5,16 +5,16 @@ import {DEFAULT_TARGET, DEFAULT_SEVERITY, PANEL_DEFAULTS} from '../triggers_pane
import {CURRENT_SCHEMA_VERSION} from '../migrations';
describe('Triggers Panel schema migration', () => {
let ctx = {};
let ctx: any = {};
let updatePanelCtrl;
let datasourceSrvMock = {
const datasourceSrvMock = {
getMetricSources: () => {
return [{ meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix_default' }];
},
get: () => Promise.resolve({})
};
let timeoutMock = () => {};
const timeoutMock = () => {};
beforeEach(() => {
ctx = {
@@ -47,14 +47,16 @@ describe('Triggers Panel schema migration', () => {
});
it('should update old panel schema', () => {
let updatedPanelCtrl = updatePanelCtrl(ctx.scope);
const updatedPanelCtrl = updatePanelCtrl(ctx.scope);
let expected = _.defaultsDeep({
const expected = _.defaultsDeep({
schemaVersion: CURRENT_SCHEMA_VERSION,
datasources: ['zabbix'],
targets: {
'zabbix': DEFAULT_TARGET
},
targets: [
{
...DEFAULT_TARGET,
datasource: 'zabbix',
}
],
ageField: true,
statusField: false,
severityField: false,
@@ -68,29 +70,29 @@ describe('Triggers Panel schema migration', () => {
it('should create new panel with default schema', () => {
ctx.scope.panel = {};
let updatedPanelCtrl = updatePanelCtrl(ctx.scope);
const updatedPanelCtrl = updatePanelCtrl(ctx.scope);
let expected = _.defaultsDeep({
const expected = _.defaultsDeep({
schemaVersion: CURRENT_SCHEMA_VERSION,
datasources: ['zabbix_default'],
targets: {
'zabbix_default': DEFAULT_TARGET
}
targets: [{
...DEFAULT_TARGET,
datasource: 'zabbix_default'
}]
}, PANEL_DEFAULTS);
expect(updatedPanelCtrl.panel).toEqual(expected);
});
it('should set default targets for new panel with empty targets', () => {
ctx.scope.panel = {
targets: [{}]
targets: []
};
let updatedPanelCtrl = updatePanelCtrl(ctx.scope);
const updatedPanelCtrl = updatePanelCtrl(ctx.scope);
let expected = _.defaultsDeep({
datasources: ['zabbix_default'],
targets: {
'zabbix_default': DEFAULT_TARGET
},
const expected = _.defaultsDeep({
targets: [{
...DEFAULT_TARGET,
datasource: 'zabbix_default'
}]
}, PANEL_DEFAULTS);
expect(updatedPanelCtrl.panel).toEqual(expected);

View File

@@ -5,9 +5,9 @@ import {PANEL_DEFAULTS, DEFAULT_TARGET} from '../triggers_panel_ctrl';
// import { create } from 'domain';
describe('TriggerPanelCtrl', () => {
let ctx = {};
let ctx: any = {};
let datasourceSrvMock, zabbixDSMock;
let timeoutMock = () => {};
const timeoutMock = () => {};
let createPanelCtrl;
beforeEach(() => {
@@ -61,7 +61,7 @@ describe('TriggerPanelCtrl', () => {
describe('When adding new panel', () => {
it('should suggest all zabbix data sources', () => {
ctx.scope.panel = {};
let panelCtrl = createPanelCtrl();
const panelCtrl = createPanelCtrl();
expect(panelCtrl.available_datasources).toEqual([
'zabbix_default', 'zabbix'
]);
@@ -69,10 +69,8 @@ describe('TriggerPanelCtrl', () => {
it('should load first zabbix data source as default', () => {
ctx.scope.panel = {};
let panelCtrl = createPanelCtrl();
expect(panelCtrl.panel.datasources).toEqual([
'zabbix_default'
]);
const panelCtrl = createPanelCtrl();
expect(panelCtrl.panel.targets[0].datasource).toEqual('zabbix_default');
});
it('should rewrite default empty target', () => {
@@ -82,7 +80,7 @@ describe('TriggerPanelCtrl', () => {
"refId": "A"
}],
};
let panelCtrl = createPanelCtrl();
const panelCtrl = createPanelCtrl();
expect(panelCtrl.available_datasources).toEqual([
'zabbix_default', 'zabbix'
]);
@@ -92,16 +90,22 @@ describe('TriggerPanelCtrl', () => {
describe('When refreshing panel', () => {
beforeEach(() => {
ctx.scope.panel.datasources = ['zabbix_default', 'zabbix'];
ctx.scope.panel.targets = {
'zabbix_default': DEFAULT_TARGET,
'zabbix': DEFAULT_TARGET
};
ctx.scope.panel.targets = [
{
...DEFAULT_TARGET,
datasource: 'zabbix_default'
},
{
...DEFAULT_TARGET,
datasource: 'zabbix'
},
];
ctx.panelCtrl = createPanelCtrl();
});
it('should format triggers', (done) => {
ctx.panelCtrl.onRefresh().then(() => {
let formattedTrigger = _.find(ctx.panelCtrl.triggerList, {triggerid: "1"});
const formattedTrigger: any = _.find(ctx.panelCtrl.triggerList, {triggerid: "1"});
expect(formattedTrigger.host).toBe('backend01');
expect(formattedTrigger.hostTechName).toBe('backend01_tech');
expect(formattedTrigger.datasource).toBe('zabbix_default');
@@ -113,7 +117,7 @@ describe('TriggerPanelCtrl', () => {
it('should sort triggers by time by default', (done) => {
ctx.panelCtrl.onRefresh().then(() => {
let trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid');
const trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid');
expect(trigger_ids).toEqual([
'2', '4', '3', '1'
]);
@@ -124,7 +128,7 @@ describe('TriggerPanelCtrl', () => {
it('should sort triggers by severity', (done) => {
ctx.panelCtrl.panel.sortTriggersBy = { text: 'severity', value: 'priority' };
ctx.panelCtrl.onRefresh().then(() => {
let trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid');
const trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid');
expect(trigger_ids).toEqual([
'1', '3', '2', '4'
]);
@@ -134,7 +138,7 @@ describe('TriggerPanelCtrl', () => {
it('should add acknowledges to trigger', (done) => {
ctx.panelCtrl.onRefresh().then(() => {
let trigger = getTriggerById(1, ctx);
const trigger = getTriggerById(1, ctx);
expect(trigger.acknowledges).toHaveLength(1);
expect(trigger.acknowledges[0].message).toBe("event ack");
@@ -153,15 +157,15 @@ describe('TriggerPanelCtrl', () => {
it('should handle new lines in trigger description', () => {
ctx.panelCtrl.setTriggerSeverity = jest.fn((trigger) => trigger);
let trigger = {comments: "this is\ndescription"};
const trigger = {comments: "this is\ndescription"};
const formattedTrigger = ctx.panelCtrl.formatTrigger(trigger);
expect(formattedTrigger.comments).toBe("this is<br>description");
});
it('should format host name to display (default)', (done) => {
ctx.panelCtrl.onRefresh().then(() => {
let trigger = getTriggerById(1, ctx);
let hostname = ctx.panelCtrl.formatHostName(trigger);
const trigger = getTriggerById(1, ctx);
const hostname = ctx.panelCtrl.formatHostName(trigger);
expect(hostname).toBe('backend01');
done();
});
@@ -171,8 +175,8 @@ describe('TriggerPanelCtrl', () => {
ctx.panelCtrl.panel.hostField = false;
ctx.panelCtrl.panel.hostTechNameField = true;
ctx.panelCtrl.onRefresh().then(() => {
let trigger = getTriggerById(1, ctx);
let hostname = ctx.panelCtrl.formatHostName(trigger);
const trigger = getTriggerById(1, ctx);
const hostname = ctx.panelCtrl.formatHostName(trigger);
expect(hostname).toBe('backend01_tech');
done();
});
@@ -182,8 +186,8 @@ describe('TriggerPanelCtrl', () => {
ctx.panelCtrl.panel.hostField = true;
ctx.panelCtrl.panel.hostTechNameField = true;
ctx.panelCtrl.onRefresh().then(() => {
let trigger = getTriggerById(1, ctx);
let hostname = ctx.panelCtrl.formatHostName(trigger);
const trigger = getTriggerById(1, ctx);
const hostname = ctx.panelCtrl.formatHostName(trigger);
expect(hostname).toBe('backend01 (backend01_tech)');
done();
});
@@ -193,8 +197,8 @@ describe('TriggerPanelCtrl', () => {
ctx.panelCtrl.panel.hostField = false;
ctx.panelCtrl.panel.hostTechNameField = false;
ctx.panelCtrl.onRefresh().then(() => {
let trigger = getTriggerById(1, ctx);
let hostname = ctx.panelCtrl.formatHostName(trigger);
const trigger = getTriggerById(1, ctx);
const hostname = ctx.panelCtrl.formatHostName(trigger);
expect(hostname).toBe("");
done();
});
@@ -222,7 +226,7 @@ describe('TriggerPanelCtrl', () => {
});
});
const defaultTrigger = {
const defaultTrigger: any = {
"triggerid": "13565",
"value": "1",
"groups": [{"groupid": "1", "name": "Backend"}] ,
@@ -248,7 +252,7 @@ const defaultTrigger = {
"flags": "0", "type": "0", "items": [] , "error": ""
};
const defaultEvent = {
const defaultEvent: any = {
"eventid": "11",
"acknowledges": [
{
@@ -272,8 +276,8 @@ const defaultEvent = {
"objectid": "1",
};
function generateTrigger(id, timestamp, severity) {
let trigger = _.cloneDeep(defaultTrigger);
function generateTrigger(id, timestamp?, severity?): any {
const trigger = _.cloneDeep(defaultTrigger);
trigger.triggerid = id.toString();
if (severity) {
trigger.priority = severity.toString();
@@ -284,13 +288,13 @@ function generateTrigger(id, timestamp, severity) {
return trigger;
}
function createTrigger(props) {
function createTrigger(props): any {
let trigger = _.cloneDeep(defaultTrigger);
trigger = _.merge(trigger, props);
trigger.lastEvent.objectid = trigger.triggerid;
return trigger;
}
function getTriggerById(id, ctx) {
function getTriggerById(id, ctx): any {
return _.find(ctx.panelCtrl.triggerList, {triggerid: id.toString()});
}

View File

@@ -10,6 +10,7 @@ import { triggerPanelTriggersTab } from './triggers_tab';
import { migratePanelSchema, CURRENT_SCHEMA_VERSION } from './migrations';
import ProblemList from './components/Problems/Problems';
import AlertList from './components/AlertList/AlertList';
import { getNextRefIdChar } from './utils';
const ZABBIX_DS_ID = 'alexanderzobnin-zabbix-datasource';
const PROBLEM_EVENTS_LIMIT = 100;
@@ -23,7 +24,17 @@ export const DEFAULT_TARGET = {
proxy: {filter: ""},
};
export const getDefaultTarget = () => DEFAULT_TARGET;
export const getDefaultTarget = (targets) => {
return {
group: {filter: ""},
host: {filter: ""},
application: {filter: ""},
trigger: {filter: ""},
tags: {filter: ""},
proxy: {filter: ""},
refId: getNextRefIdChar(targets),
};
};
export const DEFAULT_SEVERITY = [
{ priority: 0, severity: 'Not classified', color: 'rgb(108, 108, 108)', show: true},
@@ -40,8 +51,7 @@ const DEFAULT_TIME_FORMAT = "DD MMM YYYY HH:mm:ss";
export const PANEL_DEFAULTS = {
schemaVersion: CURRENT_SCHEMA_VERSION,
datasources: [],
targets: {},
targets: [getDefaultTarget([])],
// Fields
hostField: true,
hostTechNameField: false,
@@ -108,11 +118,8 @@ export class TriggerPanelCtrl extends PanelCtrl {
_.defaultsDeep(this.panel, _.cloneDeep(PANEL_DEFAULTS));
this.available_datasources = _.map(this.getZabbixDataSources(), 'name');
if (this.panel.datasources.length === 0) {
this.panel.datasources.push(this.available_datasources[0]);
}
if (this.isEmptyTargets()) {
this.panel.targets[this.panel.datasources[0]] = getDefaultTarget();
if (this.panel.targets && !this.panel.targets[0].datasource) {
this.panel.targets[0].datasource = this.available_datasources[0];
}
this.initDatasources();
@@ -138,7 +145,11 @@ export class TriggerPanelCtrl extends PanelCtrl {
}
initDatasources() {
let promises = _.map(this.panel.datasources, (ds) => {
if (!this.panel.targets) {
return;
}
const targetDatasources = _.compact(this.panel.targets.map(target => target.datasource));
let promises = targetDatasources.map(ds => {
// Load datasource
return this.datasourceSrv.get(ds)
.then(datasource => {
@@ -236,14 +247,15 @@ export class TriggerPanelCtrl extends PanelCtrl {
const timeTo = Math.ceil(dateMath.parse(this.range.to) / 1000);
const userIsEditor = this.contextSrv.isEditor || this.contextSrv.isGrafanaAdmin;
let promises = _.map(this.panel.datasources, (ds) => {
let promises = _.map(this.panel.targets, (target) => {
const ds = target.datasource;
let proxies;
let showAckButton = true;
return this.datasourceSrv.get(ds)
.then(datasource => {
const zabbix = datasource.zabbix;
const showEvents = this.panel.showEvents.value;
const triggerFilter = this.panel.targets[ds];
const triggerFilter = target;
const showProxy = this.panel.hostProxy;
const getProxiesPromise = showProxy ? zabbix.getProxies() : () => [];
showAckButton = !datasource.disableReadOnlyUsersAck || userIsEditor;
@@ -284,8 +296,8 @@ export class TriggerPanelCtrl extends PanelCtrl {
})
.then(triggers => this.setMaintenanceStatus(triggers))
.then(triggers => this.setAckButtonStatus(triggers, showAckButton))
.then(triggers => this.filterTriggersPre(triggers, ds))
.then(triggers => this.addTriggerDataSource(triggers, ds))
.then(triggers => this.filterTriggersPre(triggers, target))
.then(triggers => this.addTriggerDataSource(triggers, target))
.then(triggers => this.addTriggerHostProxy(triggers, proxies));
});
@@ -339,16 +351,17 @@ export class TriggerPanelCtrl extends PanelCtrl {
return triggers;
}
filterTriggersPre(triggerList, ds) {
filterTriggersPre(triggerList, target) {
// Filter triggers by description
let triggerFilter = this.panel.targets[ds].trigger.filter;
const ds = target.datasource;
let triggerFilter = target.trigger.filter;
triggerFilter = this.datasources[ds].replaceTemplateVars(triggerFilter);
if (triggerFilter) {
triggerList = filterTriggers(triggerList, triggerFilter);
}
// Filter by tags
const target = this.panel.targets[ds];
// const target = this.panel.targets[ds];
if (target.tags.filter) {
let tagsFilter = this.datasources[ds].replaceTemplateVars(target.tags.filter);
// replaceTemplateVars() builds regex-like string, so we should trim it.
@@ -406,9 +419,9 @@ export class TriggerPanelCtrl extends PanelCtrl {
return triggers;
}
addTriggerDataSource(triggers, ds) {
addTriggerDataSource(triggers, target) {
_.each(triggers, (trigger) => {
trigger.datasource = ds;
trigger.datasource = target.datasource;
});
return triggers;
}
@@ -479,24 +492,27 @@ export class TriggerPanelCtrl extends PanelCtrl {
return _.map(tags, (tag) => `${tag.tag}:${tag.value}`).join(', ');
}
addTagFilter(tag, ds) {
let tagFilter = this.panel.targets[ds].tags.filter;
addTagFilter(tag, datasource) {
const target = this.panel.targets.find(t => t.datasource === datasource);
console.log(target);
let tagFilter = target.tags.filter;
let targetTags = this.parseTags(tagFilter);
let newTag = {tag: tag.tag, value: tag.value};
targetTags.push(newTag);
targetTags = _.uniqWith(targetTags, _.isEqual);
let newFilter = this.tagsToString(targetTags);
this.panel.targets[ds].tags.filter = newFilter;
target.tags.filter = newFilter;
this.refresh();
}
removeTagFilter(tag, ds) {
let tagFilter = this.panel.targets[ds].tags.filter;
removeTagFilter(tag, datasource) {
const target = this.panel.targets.find(t => t.datasource === datasource);
let tagFilter = target.tags.filter;
let targetTags = this.parseTags(tagFilter);
_.remove(targetTags, t => t.tag === tag.tag && t.value === tag.value);
targetTags = _.uniqWith(targetTags, _.isEqual);
let newFilter = this.tagsToString(targetTags);
this.panel.targets[ds].tags.filter = newFilter;
target.tags.filter = newFilter;
this.refresh();
}

View File

@@ -10,7 +10,7 @@ class TriggersTabCtrl {
this.panelCtrl = $scope.ctrl;
this.panel = this.panelCtrl.panel;
this.templateSrv = templateSrv;
this.datasources = this.panelCtrl.datasources;
this.datasources = {};
// Load scope defaults
var scopeDefaults = {
@@ -21,6 +21,7 @@ class TriggersTabCtrl {
oldTarget: _.cloneDeep(this.panel.targets)
};
_.defaultsDeep(this, scopeDefaults);
this.selectedDatasources = this.getSelectedDatasources();
this.initDatasources();
this.panelCtrl.refresh();
@@ -30,6 +31,7 @@ class TriggersTabCtrl {
return this.panelCtrl.initDatasources()
.then((datasources) => {
_.each(datasources, (datasource) => {
this.datasources[datasource.name] = datasource;
this.bindSuggestionFunctions(datasource);
});
});
@@ -44,6 +46,10 @@ class TriggersTabCtrl {
this.getProxyNames[ds] = _.bind(this.suggestProxies, this, datasource);
}
getSelectedDatasources() {
return _.compact(this.panel.targets.map(target => target.datasource));
}
suggestGroups(datasource, query, callback) {
return datasource.zabbix.getAllGroups()
.then(groups => {
@@ -53,7 +59,8 @@ class TriggersTabCtrl {
}
suggestHosts(datasource, query, callback) {
let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);
const target = this.panel.targets.find(t => t.datasource === datasource.name);
let groupFilter = datasource.replaceTemplateVars(target.group.filter);
return datasource.zabbix.getAllHosts(groupFilter)
.then(hosts => {
return _.map(hosts, 'name');
@@ -62,8 +69,9 @@ class TriggersTabCtrl {
}
suggestApps(datasource, query, callback) {
let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);
let hostFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].host.filter);
const target = this.panel.targets.find(t => t.datasource === datasource.name);
let groupFilter = datasource.replaceTemplateVars(target.group.filter);
let hostFilter = datasource.replaceTemplateVars(target.host.filter);
return datasource.zabbix.getAllApps(groupFilter, hostFilter)
.then(apps => {
return _.map(apps, 'name');
@@ -78,16 +86,17 @@ class TriggersTabCtrl {
}
datasourcesChanged() {
_.each(this.panel.datasources, (ds) => {
if (!this.panel.targets[ds]) {
this.panel.targets[ds] = getDefaultTarget();
}
});
// Remove unchecked targets
_.each(this.panel.targets, (target, ds) => {
if (!_.includes(this.panel.datasources, ds)) {
delete this.panel.targets[ds];
const newTargets = [];
_.each(this.selectedDatasources, (ds) => {
const dsTarget = this.panel.targets.find((target => target.datasource === ds));
if (dsTarget) {
newTargets.push(dsTarget);
} else {
const newTarget = getDefaultTarget(this.panel.targets);
newTarget.datasource = ds;
newTargets.push(newTarget);
}
this.panel.targets = newTargets;
});
this.parseTarget();
}

View File

@@ -1,7 +1,7 @@
export interface ProblemsPanelOptions {
schemaVersion: number;
datasources: any[];
targets: Map<string, ProblemsPanelTarget>;
targets: ProblemsPanelTarget[];
// Fields
hostField?: boolean;
hostTechNameField?: boolean;
@@ -62,6 +62,7 @@ export interface ProblemsPanelTarget {
proxy: {
filter: string
};
datasource: string;
}
export interface TriggerSeverity {
@@ -192,7 +193,7 @@ export interface RTRow<T> {
/** true if this row was produced by a pivot */
groupedByPivot?: boolean;
/** any sub rows defined by the `subRowKey` prop */
subRows?: boolean;
subRows?: any[];
}
export interface RTCell<T> extends RTRow<T> {

View File

@@ -1,4 +1,6 @@
import _ from 'lodash';
import moment from 'moment';
import { DataQuery } from '@grafana/data';
import * as utils from '../datasource-zabbix/utils';
import { ZBXTrigger } from './types';
@@ -20,3 +22,13 @@ export function formatLastChange(lastchangeUnix: number, customFormat?: string)
const lastchange = timestamp.format(format);
return lastchange;
}
export const getNextRefIdChar = (queries: DataQuery[]): string => {
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
return _.find(letters, refId => {
return _.every(queries, other => {
return other.refId !== refId;
});
});
};

View File

@@ -27,7 +27,7 @@
{"name": "Triggers", "path": "img/screenshot-triggers.png"}
],
"version": "4.0.0-alpha",
"updated": "2019-10-08"
"updated": "2020-01-14"
},
"includes": [

View File

@@ -82,10 +82,6 @@ jest.mock('grafana/app/core/config', () => {
jest.mock('jquery', () => 'module not found', {virtual: true});
jest.mock('@grafana/ui');
jest.mock('@grafana/runtime');
// Required for loading angularjs
let dom = new JSDOM('<html><head><script></script></head><body></body></html>');
// Setup jsdom